diff --git a/.changelog/12103.txt b/.changelog/12103.txt new file mode 100644 index 00000000000..765b74e5a15 --- /dev/null +++ b/.changelog/12103.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_snapshot_create_volume_permission: Error if `account_id` is the snapshot's owner +``` \ No newline at end of file diff --git a/.changelog/17695.txt b/.changelog/17695.txt new file mode 100644 index 00000000000..58589ec566b --- /dev/null +++ b/.changelog/17695.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_launch_configuration: Honor associate_public_ip_address = false +``` diff --git a/.changelog/19277.txt b/.changelog/19277.txt new file mode 100644 index 00000000000..fd68b469ede --- /dev/null +++ b/.changelog/19277.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_instance: Correctly delete instance on destroy when `disable_api_termination` is `true` +``` \ No newline at end of file diff --git a/.changelog/19523.txt b/.changelog/19523.txt new file mode 100644 index 00000000000..92e459a2de2 --- /dev/null +++ b/.changelog/19523.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_lakeformation_lf_tag +``` \ No newline at end of file diff --git a/.changelog/19648.txt b/.changelog/19648.txt new file mode 100644 index 00000000000..5061ae7f2bd --- /dev/null +++ b/.changelog/19648.txt @@ -0,0 +1,7 @@ +```release-note:note:enhancement +resource/aws_lakeformation_permissions: Add LF-tag support +``` + +```release-note:note:enhancement +datasource/aws_lakeformation_permissions: Add LF-tag support +``` diff --git a/.changelog/20625.txt b/.changelog/20625.txt new file mode 100644 index 00000000000..7505a3f7f0e --- /dev/null +++ b/.changelog/20625.txt @@ -0,0 +1,7 @@ +```release-note:new-resource +aws_lightsail_container_service +``` + +```release-note:new-resource +aws_lightsail_container_service_deployment_version +``` diff --git a/.changelog/20912.txt b/.changelog/20912.txt new file mode 100644 index 00000000000..d35acd82876 --- /dev/null +++ b/.changelog/20912.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_ebs_snapshot_copy: Add support for `timeouts` configuration block. +``` diff --git a/.changelog/21846.txt b/.changelog/21846.txt new file mode 100644 index 00000000000..a64ef4474cf --- /dev/null +++ b/.changelog/21846.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_dms_endpoint: Add `redshift_settings` configuration block +``` diff --git a/.changelog/21916.txt b/.changelog/21916.txt new file mode 100644 index 00000000000..09e0d9a6eeb --- /dev/null +++ b/.changelog/21916.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_ebs_volume: Add `final_snapshot` argument +``` \ No newline at end of file diff --git a/.changelog/22646.txt b/.changelog/22646.txt new file mode 100644 index 00000000000..39e82e33f58 --- /dev/null +++ b/.changelog/22646.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_dms_endpoint: Add ability to use AWS Secrets Manager with the `sqlserver` engine +``` \ No newline at end of file diff --git a/.changelog/22844.txt b/.changelog/22844.txt new file mode 100644 index 00000000000..bd2123c0f5e --- /dev/null +++ b/.changelog/22844.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_efs_replication_configuration +``` diff --git a/.changelog/22859.txt b/.changelog/22859.txt new file mode 100644 index 00000000000..2af56bc2ef4 --- /dev/null +++ b/.changelog/22859.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_guardduty_detector: Add `kubernetes` attribute to the `datasources` configuration block +``` diff --git a/.changelog/23280.txt b/.changelog/23280.txt new file mode 100644 index 00000000000..6f82b341c39 --- /dev/null +++ b/.changelog/23280.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_ebs_volume: Fix to preserve `iops` when changing EBS volume type (`io1`, `io2`, `gp3`) +``` diff --git a/.changelog/23691.txt b/.changelog/23691.txt new file mode 100644 index 00000000000..b274bcc580f --- /dev/null +++ b/.changelog/23691.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_dms_endpoint: Add ability to use AWS Secrets Manager with the `aurora-postgresql` and `mongodb` engines +``` \ No newline at end of file diff --git a/.changelog/24695.txt b/.changelog/24695.txt new file mode 100644 index 00000000000..7d97765724b --- /dev/null +++ b/.changelog/24695.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_instance: Prevent error `InvalidParameterCombination: The parameter GroupName within placement information cannot be specified when instanceInterruptionBehavior is set to 'STOP'` when using a launch template that sets `instance_interruption_behavior` to `stop` +``` diff --git a/.changelog/24764.txt b/.changelog/24764.txt new file mode 100644 index 00000000000..46054bc6a12 --- /dev/null +++ b/.changelog/24764.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_s3_bucket: Add error handling for `ErrCodeNotImplemented` and `ErrCodeXNotImplemented` errors when ready bucket information. +``` diff --git a/.changelog/24795.txt b/.changelog/24795.txt new file mode 100644 index 00000000000..3482fda8eb7 --- /dev/null +++ b/.changelog/24795.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_autoscaling_group: Add `mixed_instances_policy.launch_template.override.instance_requirements` argument +``` \ No newline at end of file diff --git a/.changelog/24804.txt b/.changelog/24804.txt new file mode 100644 index 00000000000..aa458f8eebd --- /dev/null +++ b/.changelog/24804.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_servicecatalog_provisioned_product: Add possible `TAINTED` target state for resource update and remove one of the internal waiters during read +``` \ No newline at end of file diff --git a/.changelog/24821.txt b/.changelog/24821.txt new file mode 100644 index 00000000000..eca08358af3 --- /dev/null +++ b/.changelog/24821.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_location_place_index +``` diff --git a/.changelog/24846.txt b/.changelog/24846.txt new file mode 100644 index 00000000000..8e399c6db49 --- /dev/null +++ b/.changelog/24846.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_dms_endpoint: Add ability to use AWS Secrets Manager with the `aurora`, `mariadb` and `mysql` engines +``` diff --git a/.changelog/24856.txt b/.changelog/24856.txt new file mode 100644 index 00000000000..0e4291d5978 --- /dev/null +++ b/.changelog/24856.txt @@ -0,0 +1,11 @@ +```release-note:enhancement +resource/aws_redshift_cluster: Add plan-time validation for `iam_roles`, `owner_account`, and `port`. +``` + +```release-note:enhancement +resource/aws_redshift_cluster: Add `aqua_configuration_status` and `apply_immediately` arguments. +``` + +```release-note:enhancement +data-source/aws_redshift_cluster: Add `aqua_configuration_status` attribute. +``` \ No newline at end of file diff --git a/.changelog/24875.txt b/.changelog/24875.txt new file mode 100644 index 00000000000..af8f79d4f09 --- /dev/null +++ b/.changelog/24875.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_db_proxy_target: Fix `InvalidDBInstanceState: DB Instance is in an unsupported state - CREATING, needs to be in [AVAILABLE, MODIFYING, BACKING_UP]` error on resource Create +``` diff --git a/.changelog/24882.txt b/.changelog/24882.txt new file mode 100644 index 00000000000..73c42e41145 --- /dev/null +++ b/.changelog/24882.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_cloudwatch_metric_stream: Add `statistics_configuration` argument +``` diff --git a/.changelog/24886.txt b/.changelog/24886.txt new file mode 100644 index 00000000000..c30edf10633 --- /dev/null +++ b/.changelog/24886.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_redshift_cluster: Add `logging.log_destination_type` and `logging.log_exports` arguments. +``` \ No newline at end of file diff --git a/.changelog/24889.txt b/.changelog/24889.txt new file mode 100644 index 00000000000..05690584938 --- /dev/null +++ b/.changelog/24889.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_appflow_flow: Amend `task_properties` validation to avoid conflicting type assumption +``` diff --git a/.changelog/24899.txt b/.changelog/24899.txt new file mode 100644 index 00000000000..c185e24b971 --- /dev/null +++ b/.changelog/24899.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_organizations_account: Fix reading account state for existing accounts +``` diff --git a/.changelog/24906.txt b/.changelog/24906.txt new file mode 100644 index 00000000000..a3ec8fa7dd0 --- /dev/null +++ b/.changelog/24906.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_redshift_hsm_client_certificate +``` diff --git a/.changelog/24907.txt b/.changelog/24907.txt new file mode 100644 index 00000000000..69221d10ebe --- /dev/null +++ b/.changelog/24907.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_redshift_authentication_profile +``` diff --git a/.changelog/24909.txt b/.changelog/24909.txt new file mode 100644 index 00000000000..73dd24788bd --- /dev/null +++ b/.changelog/24909.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_redshift_event_subscription: Add plan time validations for `event_categories`, `source_type`, and `severity`. +``` \ No newline at end of file diff --git a/.changelog/24913.txt b/.changelog/24913.txt new file mode 100644 index 00000000000..309a31d1c63 --- /dev/null +++ b/.changelog/24913.txt @@ -0,0 +1,7 @@ +```release-note:enhancement +resource/aws_cloudfront_response_headers_policy: Add `server_timing_headers_config` argument +``` + +```release-note:enhancement +datasource/aws_cloudfront_response_headers_policy: Add `server_timing_headers_config` attribute +``` \ No newline at end of file diff --git a/.changelog/24915.txt b/.changelog/24915.txt new file mode 100644 index 00000000000..e25a2d8f299 --- /dev/null +++ b/.changelog/24915.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_cloudsearch_domain: Add `index_field.source_fields` argument +``` \ No newline at end of file diff --git a/.changelog/24916.txt b/.changelog/24916.txt new file mode 100644 index 00000000000..e06cb85cee7 --- /dev/null +++ b/.changelog/24916.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_redshift_usage_limit +``` \ No newline at end of file diff --git a/.changelog/24920.txt b/.changelog/24920.txt new file mode 100644 index 00000000000..74b9b9e7aed --- /dev/null +++ b/.changelog/24920.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_kendra_index +``` \ No newline at end of file diff --git a/.changelog/24951.txt b/.changelog/24951.txt new file mode 100644 index 00000000000..0a3a25ffd74 --- /dev/null +++ b/.changelog/24951.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_autoscaling_group: Add `context` argument +``` \ No newline at end of file diff --git a/.changelog/24980.txt b/.changelog/24980.txt new file mode 100644 index 00000000000..ea9d317d3e3 --- /dev/null +++ b/.changelog/24980.txt @@ -0,0 +1,3 @@ +```release-note:new-data-source +aws_location_place_index +``` diff --git a/.changelog/24982.txt b/.changelog/24982.txt new file mode 100644 index 00000000000..f4f23362caa --- /dev/null +++ b/.changelog/24982.txt @@ -0,0 +1,7 @@ +```release-note:enhancement +resource/aws_redshift_cluster: Add `default_iam_role_arn`, `maintenance_track_name`, and `manual_snapshot_retention_period` arguments. +``` + +```release-note:enhancement +data-source/aws_redshift_cluster: Add `arn`, `cluster_nodes`, `cluster_nodes`, `maintenance_track_name`, `manual_snapshot_retention_period`, `log_destination_type`, and `log_exports` attributes. +``` \ No newline at end of file diff --git a/.changelog/25045.txt b/.changelog/25045.txt new file mode 100644 index 00000000000..555f1f8d227 --- /dev/null +++ b/.changelog/25045.txt @@ -0,0 +1,15 @@ +```release-note:enhancement +data-source/aws_ami: Add `tpm_support` attribute +``` + +```release-note:enhancement +resource/aws_ami: Add `tpm_support` argument +``` + +```release-note:enhancement +resource/aws_ami_copy: Add `tpm_support` argument +``` + +```release-note:enhancement +resource/aws_ami_from_instance: Add `tpm_support` argument +``` \ No newline at end of file diff --git a/.changelog/25046.txt b/.changelog/25046.txt new file mode 100644 index 00000000000..4e478e7c60e --- /dev/null +++ b/.changelog/25046.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_ec2_managed_prefix_list_entry: Fix error when attempting to create or delete multiple list entries +``` diff --git a/.changelog/25053.txt b/.changelog/25053.txt new file mode 100644 index 00000000000..bfb2f2e9872 --- /dev/null +++ b/.changelog/25053.txt @@ -0,0 +1,3 @@ +```release-note:new-data-source +aws_redshift_subnet_group +``` \ No newline at end of file diff --git a/.changelog/25060.txt b/.changelog/25060.txt new file mode 100644 index 00000000000..e5d5841ea11 --- /dev/null +++ b/.changelog/25060.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_transfer_server: Add support for `TransferSecurityPolicy-2022-03` `security_policy_name` value +``` \ No newline at end of file diff --git a/.changelog/25062.txt b/.changelog/25062.txt new file mode 100644 index 00000000000..928ccb3b428 --- /dev/null +++ b/.changelog/25062.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_msk_cluster: Support multiple attribute updates by refreshing `current_version` after each update +``` \ No newline at end of file diff --git a/.changelog/25072.txt b/.changelog/25072.txt new file mode 100644 index 00000000000..d13027644ad --- /dev/null +++ b/.changelog/25072.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_msk_cluster: Prevent crash on apply when `client_authentication.tls` is empty +``` \ No newline at end of file diff --git a/.changelog/25073.txt b/.changelog/25073.txt new file mode 100644 index 00000000000..e84268d581c --- /dev/null +++ b/.changelog/25073.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_redshift_endpoint_access +``` diff --git a/.changelog/25077.txt b/.changelog/25077.txt new file mode 100644 index 00000000000..12cbef42524 --- /dev/null +++ b/.changelog/25077.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_elasticache_global_replication_group: Add support for upgrading `engine_version`. +``` diff --git a/.changelog/25080.txt b/.changelog/25080.txt new file mode 100644 index 00000000000..cf5150a377e --- /dev/null +++ b/.changelog/25080.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_dms_endpoint: Add ability to use AWS Secrets Manager with the `redshift` engine +``` \ No newline at end of file diff --git a/.changelog/25092.txt b/.changelog/25092.txt new file mode 100644 index 00000000000..8560fc53dea --- /dev/null +++ b/.changelog/25092.txt @@ -0,0 +1,3 @@ +```release-note:new-data-source +aws_redshift_cluster_credentials +``` \ No newline at end of file diff --git a/.changelog/25093.txt b/.changelog/25093.txt new file mode 100644 index 00000000000..b092b4b90fc --- /dev/null +++ b/.changelog/25093.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_redshift_hsm_configuration +``` \ No newline at end of file diff --git a/.changelog/25096.txt b/.changelog/25096.txt new file mode 100644 index 00000000000..73b535357bd --- /dev/null +++ b/.changelog/25096.txt @@ -0,0 +1,7 @@ +```release-note:new-resource +aws_redshift_cluster_iam_roles +``` + +```release-note:enhancement +resource/aws_redshift_cluster: The `default_iam_role_arn` argument is now Computed +``` \ No newline at end of file diff --git a/.changelog/25097.txt b/.changelog/25097.txt new file mode 100644 index 00000000000..d2e5d809052 --- /dev/null +++ b/.changelog/25097.txt @@ -0,0 +1,3 @@ +```release-note:bug +data-source/aws_launch_configuration: Correct data type for `ebs_block_device.throughput` and `root_block_device.throughput` attributes +``` \ No newline at end of file diff --git a/.changelog/25104.txt b/.changelog/25104.txt new file mode 100644 index 00000000000..73ff040fb97 --- /dev/null +++ b/.changelog/25104.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_redshiftdata_statement +``` \ No newline at end of file diff --git a/.changelog/25109.txt b/.changelog/25109.txt new file mode 100644 index 00000000000..0506725a3fe --- /dev/null +++ b/.changelog/25109.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_acmpca_policy +``` \ No newline at end of file diff --git a/.changelog/25113.txt b/.changelog/25113.txt new file mode 100644 index 00000000000..ce2a31f3501 --- /dev/null +++ b/.changelog/25113.txt @@ -0,0 +1,2 @@ +```release-note:enhancement +resource/aws_ram_resource_share: Add `permission_arns` argument. diff --git a/.changelog/25130.txt b/.changelog/25130.txt new file mode 100644 index 00000000000..5ca2489f924 --- /dev/null +++ b/.changelog/25130.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_servicecatalog_provisioned_product: Correctly handle resources in a `TAINTED` state +``` \ No newline at end of file diff --git a/.changelog/25140.txt b/.changelog/25140.txt new file mode 100644 index 00000000000..a663d76aca7 --- /dev/null +++ b/.changelog/25140.txt @@ -0,0 +1,2 @@ +```release-note:enhancement +resource/aws_neptune_cluster: Add `allow_major_version_upgrade` argument. \ No newline at end of file diff --git a/.changelog/25144.txt b/.changelog/25144.txt new file mode 100644 index 00000000000..e56a8c417ba --- /dev/null +++ b/.changelog/25144.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_emrserverless_application +``` diff --git a/.changelog/25145.txt b/.changelog/25145.txt new file mode 100644 index 00000000000..d594bb8d4b3 --- /dev/null +++ b/.changelog/25145.txt @@ -0,0 +1,7 @@ +```release-note:bug +resource/aws_rds_cluster_role_association: Extend timeout to 10 minutes +``` + +```release-note:bug +resource/aws_db_instance_role_association: Extend timeout to 10 minutes +``` diff --git a/.changelog/25158.txt b/.changelog/25158.txt new file mode 100644 index 00000000000..5c944aea752 --- /dev/null +++ b/.changelog/25158.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_ram_resource_share: Fix regression in v4.17.0 where `permission_arns` would get clobbered if already set +``` diff --git a/.changelog/25159.txt b/.changelog/25159.txt new file mode 100644 index 00000000000..e9b0f66d6ad --- /dev/null +++ b/.changelog/25159.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +data-source/aws_ram_resource_share: Add `resource_share_status` argument. +``` diff --git a/.changelog/25161.txt b/.changelog/25161.txt new file mode 100644 index 00000000000..35a37cb4813 --- /dev/null +++ b/.changelog/25161.txt @@ -0,0 +1,23 @@ +```release-note:enhancement +resource/aws_instance: Add `private_dns_name_options` argument +``` + +```release-note:enhancement +data-source/aws_instance: Add `private_dns_name_options` attribute +``` + +```release-note:enhancement +resource/aws_instance: Correctly handle `credit_specification` for T4g instances +``` + +```release-note:enhancement +data-source/aws_instance: Correctly set `credit_specification` for T4g instances +``` + +```release-note:enhancement +resource/aws_launch_template: Correctly handle `credit_specification` for T4g instances +``` + +```release-note:enhancement +data-source/aws_launch_template: Correctly set `credit_specification` for T4g instances +``` \ No newline at end of file diff --git a/.changelog/25174.txt b/.changelog/25174.txt new file mode 100644 index 00000000000..d3094cf24fd --- /dev/null +++ b/.changelog/25174.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_ssm_parameter: Allow `Intelligent-Tiering` to upgrade to `Advanced` tier as needed. +``` diff --git a/.changelog/25177.txt b/.changelog/25177.txt new file mode 100644 index 00000000000..3448d181df3 --- /dev/null +++ b/.changelog/25177.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_ce_anomaly_monitor +``` diff --git a/.changelog/25180.txt b/.changelog/25180.txt new file mode 100644 index 00000000000..548a6c9336b --- /dev/null +++ b/.changelog/25180.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_cloudwatchrum_app_monitor +``` \ No newline at end of file diff --git a/.changelog/25181.txt b/.changelog/25181.txt new file mode 100644 index 00000000000..c6dcdbfcebd --- /dev/null +++ b/.changelog/25181.txt @@ -0,0 +1,7 @@ +```release-note:enhancement +resource/aws_cognito_user_pool_client: Add `enable_propagate_additional_user_context_data` argument +``` + +```release-note:enhancement +data-source/aws_cognito_user_pool_client: Add `enable_propagate_additional_user_context_data` argument +``` \ No newline at end of file diff --git a/.changelog/25182.txt b/.changelog/25182.txt new file mode 100644 index 00000000000..dd35bbe7670 --- /dev/null +++ b/.changelog/25182.txt @@ -0,0 +1,7 @@ +```release-note:enhancement +resource/aws_datasync_location_efs: Add `access_point_arn`, `file_system_access_role_arn`, and `in_transit_encryption` arguments +``` + +```release-note:enhancement +resource/aws_datasync_location_efs: Add plan time validations for `ec2_config.security_group_arns` +``` diff --git a/.changelog/25184.txt b/.changelog/25184.txt new file mode 100644 index 00000000000..79c1580f6e7 --- /dev/null +++ b/.changelog/25184.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_cognito_user_pool: Correctly handle missing or empty `account_recovery_setting` attribute +``` \ No newline at end of file diff --git a/.changelog/25185.txt b/.changelog/25185.txt new file mode 100644 index 00000000000..fce806a3a12 --- /dev/null +++ b/.changelog/25185.txt @@ -0,0 +1,15 @@ +```release-note:enhancement +resource/aws_instance: Add `disable_api_stop` argument +``` + +```release-note:enhancement +data-source/aws_instance: Add `disable_api_stop` attribute +``` + +```release-note:enhancement +resource/aws_launch_template: Add `disable_api_stop` argument +``` + +```release-note:enhancement +data-source/aws_launch_template: Add `disable_api_stop` attribute +``` diff --git a/.changelog/25187.txt b/.changelog/25187.txt new file mode 100644 index 00000000000..b1c2e8397b9 --- /dev/null +++ b/.changelog/25187.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +data-source/aws_cloudwatch_logs_groups: Make `log_group_name_prefix` optional +``` diff --git a/.changelog/25189.txt b/.changelog/25189.txt new file mode 100644 index 00000000000..21dc12068b0 --- /dev/null +++ b/.changelog/25189.txt @@ -0,0 +1,7 @@ +```release-note:enhancement +resource/aws_vpc_endpoint_service: Add `supported_ip_address_types` argument +``` + +```release-note:enhancement +data-source/aws_vpc_endpoint_service: Add `supported_ip_address_types` attribute +``` \ No newline at end of file diff --git a/.changelog/25190.txt b/.changelog/25190.txt new file mode 100644 index 00000000000..f24fb3554b8 --- /dev/null +++ b/.changelog/25190.txt @@ -0,0 +1,7 @@ +```release-note:enhancement +resource/aws_vpc_endpoint: Add `dns_options` and `ip_address_type` arguments +``` + +```release-note:enhancement +data-source/aws_vpc_endpoint: Add `dns_options` and `ip_address_type` attributes +``` \ No newline at end of file diff --git a/.changelog/25195.txt b/.changelog/25195.txt new file mode 100644 index 00000000000..c338575d364 --- /dev/null +++ b/.changelog/25195.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_applicationinsights_application +``` \ No newline at end of file diff --git a/.changelog/25198.txt b/.changelog/25198.txt new file mode 100644 index 00000000000..6eca29623a0 --- /dev/null +++ b/.changelog/25198.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_kendra_query_suggestions_block_list +``` \ No newline at end of file diff --git a/.changelog/25199.txt b/.changelog/25199.txt new file mode 100644 index 00000000000..edc5494ad56 --- /dev/null +++ b/.changelog/25199.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_kendra_thesaurus +``` \ No newline at end of file diff --git a/.changelog/25218.txt b/.changelog/25218.txt new file mode 100644 index 00000000000..91a9cd5a215 --- /dev/null +++ b/.changelog/25218.txt @@ -0,0 +1,7 @@ +```release-note:enhancement +resource/aws_sagemaker_endpoint_configuration: Add `serverless_config` argument +``` + +```release-note:enhancement +resource/aws_sagemaker_endpoint_configuration: Make `production_variants.initial_instance_count` and `production_variants.instance_type` arguments optional +``` \ No newline at end of file diff --git a/.changelog/25224.txt b/.changelog/25224.txt new file mode 100644 index 00000000000..2bdc77d87da --- /dev/null +++ b/.changelog/25224.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_ce_anomaly_subscription +``` \ No newline at end of file diff --git a/.changelog/25230.txt b/.changelog/25230.txt new file mode 100644 index 00000000000..081bdd4b32e --- /dev/null +++ b/.changelog/25230.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_keyspaces_table: Relax validation of the `schema_definition.column.type` argument to allow collection types +``` \ No newline at end of file diff --git a/.changelog/25236.txt b/.changelog/25236.txt new file mode 100644 index 00000000000..5f1d8ae1dd1 --- /dev/null +++ b/.changelog/25236.txt @@ -0,0 +1,7 @@ +```release-note:enhancement +resource/aws_sagemaker_notebook_instance: Add `instance_metadata_service_configuration` argument +``` + +```release-note:enhancement +resource/aws_sagemaker_notebook_instance: Support `notebook-al2-v2` value for `platform_identifier` +``` \ No newline at end of file diff --git a/.changelog/25245.txt b/.changelog/25245.txt new file mode 100644 index 00000000000..26872e926c7 --- /dev/null +++ b/.changelog/25245.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_api_gateway_model: Suppress whitespace differences between model schemas +``` diff --git a/.changelog/25257.txt b/.changelog/25257.txt new file mode 100644 index 00000000000..e97c8061011 --- /dev/null +++ b/.changelog/25257.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_vpc_ipam_pool_cidr_allocation: improve internal search mechanism +``` diff --git a/.changelog/25260.txt b/.changelog/25260.txt new file mode 100644 index 00000000000..9a95512ae4b --- /dev/null +++ b/.changelog/25260.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_s3_bucket_metric: Add validation to ensure name is <= 64 characters. +``` diff --git a/.changelog/25272.txt b/.changelog/25272.txt new file mode 100644 index 00000000000..51e13e6941f --- /dev/null +++ b/.changelog/25272.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_ce_cost_allocation_tag +``` diff --git a/.changelog/25277.txt b/.changelog/25277.txt new file mode 100644 index 00000000000..72a9b92582d --- /dev/null +++ b/.changelog/25277.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_cloudwatch_event_api_destination: Remove validation of a maximum value for the `invocation_rate_limit_per_second` argument +``` \ No newline at end of file diff --git a/.changelog/25282.txt b/.changelog/25282.txt new file mode 100644 index 00000000000..eca1d4ba480 --- /dev/null +++ b/.changelog/25282.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_cognito_risk_configuration +``` \ No newline at end of file diff --git a/.changelog/25284.txt b/.changelog/25284.txt new file mode 100644 index 00000000000..3a91d2d89fb --- /dev/null +++ b/.changelog/25284.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_synthetics_canary: Add `delete_lambda` argument +``` \ No newline at end of file diff --git a/.changelog/25315.txt b/.changelog/25315.txt new file mode 100644 index 00000000000..3fc3978c350 --- /dev/null +++ b/.changelog/25315.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_kendra_experience +``` \ No newline at end of file diff --git a/.changelog/25326.txt b/.changelog/25326.txt new file mode 100644 index 00000000000..a20b264d19e --- /dev/null +++ b/.changelog/25326.txt @@ -0,0 +1,3 @@ +```release-note:bug + resource/aws_dynamodb_table_item: Fix to remove attribute from table item on update + ``` \ No newline at end of file diff --git a/.changelog/25450.txt b/.changelog/25450.txt new file mode 100644 index 00000000000..bedad122977 --- /dev/null +++ b/.changelog/25450.txt @@ -0,0 +1,3 @@ +```release-note:bug + resource/aws_launch_configuration: Remove default value for `associate_public_ip_address` argument and mark as Computed. This fixes a regression introduced in [v4.17.0](https://github.com/hashicorp/terraform-provider-aws/blob/main/CHANGELOG.md#4170-june--3-2022) via [#17695](https://github.com/hashicorp/terraform-provider-aws/issues/17695) when no value is configured, whilst honoring any configured value + ``` \ No newline at end of file diff --git a/.changelog/25464.txt b/.changelog/25464.txt new file mode 100644 index 00000000000..7f0a183a1a4 --- /dev/null +++ b/.changelog/25464.txt @@ -0,0 +1,7 @@ +```release-note:enhancement + resource/aws_ec2_host: Add `outpost_arn` argument + ``` + + ```release-note:enhancement + data-source/aws_ec2_host: Add `outpost_arn` attribute + ``` \ No newline at end of file diff --git a/.changelog/25466.txt b/.changelog/25466.txt new file mode 100644 index 00000000000..35550ba6bed --- /dev/null +++ b/.changelog/25466.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_location_tracker +``` diff --git a/.changelog/25473.txt b/.changelog/25473.txt new file mode 100644 index 00000000000..152bc6e22f5 --- /dev/null +++ b/.changelog/25473.txt @@ -0,0 +1,3 @@ +```release-note:new-data-source +aws_kendra_index +``` \ No newline at end of file diff --git a/.changelog/25476.txt b/.changelog/25476.txt new file mode 100644 index 00000000000..7505e49ac05 --- /dev/null +++ b/.changelog/25476.txt @@ -0,0 +1,7 @@ +```release-note:new-data-source +aws_outposts_assets +``` + +```release-note:new-data-source +aws_outposts_asset +``` diff --git a/.changelog/25488.txt b/.changelog/25488.txt new file mode 100644 index 00000000000..3c7e61aba4a --- /dev/null +++ b/.changelog/25488.txt @@ -0,0 +1,7 @@ +```release-note:bug + resource/aws_ce_cost_category: Allow duplicate values in `split_charge_rule.parameter.values` argument + ``` + +```release-note:bug + resource/aws_ce_cost_category: Fix error passing `split_charge_rule.parameter` to the AWS API + ``` \ No newline at end of file diff --git a/.changelog/25515.txt b/.changelog/25515.txt new file mode 100644 index 00000000000..2e54043b9fa --- /dev/null +++ b/.changelog/25515.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_kendra_faq +``` \ No newline at end of file diff --git a/.changelog/25523.txt b/.changelog/25523.txt new file mode 100644 index 00000000000..2aca90db292 --- /dev/null +++ b/.changelog/25523.txt @@ -0,0 +1,3 @@ +```release-note:new-data-source +aws_kendra_faq +``` \ No newline at end of file diff --git a/.changelog/25529.txt b/.changelog/25529.txt new file mode 100644 index 00000000000..ab85f18c0ec --- /dev/null +++ b/.changelog/25529.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_vpn_connection: Add `outside_ip_address_type` and `transport_transit_gateway_attachment_id` arguments in support of [Private IP VPNs](https://docs.aws.amazon.com/vpn/latest/s2svpn/private-ip-dx.html) +``` \ No newline at end of file diff --git a/.changelog/25538.txt b/.changelog/25538.txt new file mode 100644 index 00000000000..904c684033a --- /dev/null +++ b/.changelog/25538.txt @@ -0,0 +1,7 @@ +```release-note:bug +data-source/aws_iam_policy: Add validation to prevent setting incompatible parameters. +``` + +```release-note:bug +data-source/aws_iam_policy: Now loads tags. +``` diff --git a/.changelog/25549.txt b/.changelog/25549.txt new file mode 100644 index 00000000000..8e4c9073519 --- /dev/null +++ b/.changelog/25549.txt @@ -0,0 +1,151 @@ +```release-note:bug +resource/aws_cloudwatch_composite_alarm: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_cloudwatch_metric_alarm: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_cloudwatch_metric_stream: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_ecr_repository: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +data-source/aws_ecr_repository: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_ecs_capacity_provider: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_ecs_cluster: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_ecs_service: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_ecs_task_definition: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_ecs_task_set: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_elasticache_cluster: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +data-source/aws_elasticache_cluster: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_elasticache_parameter_group: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_elasticache_replication_group: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_elasticache_subnet_group: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_elasticache_user: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_elasticache_user_group: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_lb_listener: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +data-source/aws_lb_listener: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_lb_listener_rule: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_lb: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +data-source/aws_lb: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_lb_target_group: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +data-source/aws_lb_target_group: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_cloudwatch_event_bus: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_cloudwatch_event_rule: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_iam_instance_profile: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_iam_openid_connect_provider: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_iam_policy: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_iam_role: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_iam_saml_provider: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_iam_server_certificate: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_iam_service_linked_role: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_iam_user: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_iam_virtual_mfa_device: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_sns_topic: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +resource/aws_sqs_queue: Prevent ISO-partition tagging precautions from eating legit errors +``` + +```release-note:bug +data-source/aws_sqs_queue: Prevent ISO-partition tagging precautions from eating legit errors +``` diff --git a/.changelog/25562.txt b/.changelog/25562.txt new file mode 100644 index 00000000000..a1e0349c453 --- /dev/null +++ b/.changelog/25562.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_default_vpc_dhcp_options: Fix `missing expected [` error introduced in [v4.20.0](https://github.com/hashicorp/terraform-provider-aws/blob/main/CHANGELOG.md#4200-june-23-2022) +``` \ No newline at end of file diff --git a/.github/goreleaser-cross-compiler-test.yml b/.github/goreleaser-cross-compiler-test.yml new file mode 100644 index 00000000000..d44f785f103 --- /dev/null +++ b/.github/goreleaser-cross-compiler-test.yml @@ -0,0 +1,27 @@ +archives: + - files: + # Ensure only built binary is archived + - 'none*' + format: zip + name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}' +before: + hooks: + - 'go mod download' +builds: + # Check and build binary for 32-bit architecture (FreeBSD/ARM) + - id: 32-bit-arch + # Binary naming only required for Terraform CLI 0.12 + binary: '{{ .ProjectName }}_v{{ .Version }}_x5' + env: + - CGO_ENABLED=0 + flags: + - -trimpath + goos: + - freebsd + goarch: + - arm + ldflags: + - -s -w -X version.ProviderVersion={{.Version}} + mod_timestamp: '{{ .CommitTimestamp }}' +snapshot: + name_template: "{{ .Tag }}-next" diff --git a/.github/labeler-issue-triage.yml b/.github/labeler-issue-triage.yml index c41bc49b69f..18f38c7c4d4 100644 --- a/.github/labeler-issue-triage.yml +++ b/.github/labeler-issue-triage.yml @@ -142,7 +142,7 @@ service/codestarnotifications: service/cognitoidentity: - '((\*|-)\s*`?|(data|resource)\s+"?)aws_cognito_identity_(?!provider)' service/cognitoidp: - - '((\*|-)\s*`?|(data|resource)\s+"?)aws_cognito_(identity_provider|resource|user)' + - '((\*|-)\s*`?|(data|resource)\s+"?)aws_cognito_(identity_provider|resource|user|risk)' service/cognitosync: - '((\*|-)\s*`?|(data|resource)\s+"?)aws_cognitosync_' service/comprehend: @@ -237,6 +237,8 @@ service/emr: - '((\*|-)\s*`?|(data|resource)\s+"?)aws_emr_' service/emrcontainers: - '((\*|-)\s*`?|(data|resource)\s+"?)aws_emrcontainers_' +service/emrserverless: + - '((\*|-)\s*`?|(data|resource)\s+"?)aws_emrserverless_' service/events: - '((\*|-)\s*`?|(data|resource)\s+"?)aws_cloudwatch_event_' service/evidently: diff --git a/.github/labeler-pr-triage.yml b/.github/labeler-pr-triage.yml index abbab95f84f..643a873c82e 100644 --- a/.github/labeler-pr-triage.yml +++ b/.github/labeler-pr-triage.yml @@ -249,6 +249,7 @@ service/cognitoidp: - 'website/**/cognito_identity_provider*' - 'website/**/cognito_resource_*' - 'website/**/cognito_user*' + - 'website/**/cognito_risk*' service/cognitosync: - 'internal/service/cognitosync/**/*' - 'website/**/cognitosync_*' @@ -416,6 +417,9 @@ service/emr: service/emrcontainers: - 'internal/service/emrcontainers/**/*' - 'website/**/emrcontainers_*' +service/emrserverless: + - 'internal/service/emrserverless/**/*' + - 'website/**/emrserverless_*' service/events: - 'internal/service/events/**/*' - 'website/**/cloudwatch_event_*' diff --git a/.github/scripts/providerlint.sh b/.github/scripts/providerlint.sh new file mode 100755 index 00000000000..7d272bdb050 --- /dev/null +++ b/.github/scripts/providerlint.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +results=$( make providerlint 2>&1 ) +while [[ "${results}" == *Killed* ]]; do + echo "${results}" + results=$( make providerlint 2>&1 ) +done +echo "${results}" diff --git a/.github/scripts/semgrep.sh b/.github/scripts/semgrep.sh new file mode 100755 index 00000000000..de4ecfd2369 --- /dev/null +++ b/.github/scripts/semgrep.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +cfile=$1 + +results=$( semgrep -c "${cfile}" 2>&1 ) +while [[ "${results}" == *Invalid_argument* ]] && [[ "${results}" == *" 0 findings"* ]]; do + echo "${results}" + results=$( semgrep -c "${cfile}" 2>&1 ) +done +if [[ ! "${results}" == *" 0 findings"* ]]; then + echo "${results}" >&2 + exit 1 +fi +echo "${results}" diff --git a/.github/workflows/acctest-terraform-lint.yml b/.github/workflows/acctest-terraform-lint.yml index 7580ad9f602..bf11fc07b93 100644 --- a/.github/workflows/acctest-terraform-lint.yml +++ b/.github/workflows/acctest-terraform-lint.yml @@ -18,11 +18,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true timeout-minutes: 2 @@ -41,11 +39,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true timeout-minutes: 2 diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index 63235dee16e..965e3026b9e 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -59,11 +59,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true timeout-minutes: 2 diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml index 3bbdc25894a..4357954a35d 100644 --- a/.github/workflows/dependencies.yml +++ b/.github/workflows/dependencies.yml @@ -64,11 +64,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - name: go mod run: | echo "==> Checking source code with go mod tidy..." diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index 672c8ef27b0..d2cf8f29fda 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -39,11 +39,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true timeout-minutes: 2 diff --git a/.github/workflows/examples.yml b/.github/workflows/examples.yml index 700f4b2d8a9..05729d6c0fe 100644 --- a/.github/workflows/examples.yml +++ b/.github/workflows/examples.yml @@ -29,11 +29,9 @@ jobs: with: path: ~/go/pkg/mod key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - name: go build run: go build -o terraform-plugin-dir/terraform-provider-aws_v99.99.99_x5 . - name: override plugin diff --git a/.github/workflows/goreleaser-ci.yml b/.github/workflows/goreleaser-ci.yml new file mode 100644 index 00000000000..48b35d76c58 --- /dev/null +++ b/.github/workflows/goreleaser-ci.yml @@ -0,0 +1,73 @@ +# Continuous integration handling for GoReleaser +name: GoReleaser CI + +on: + push: + branches: + - main + - 'release/**' + pull_request: + paths: + - .github/workflows/goreleaser-ci.yml + - .goreleaser.yml + - .go-version + - go.sum + - main.go + - internal/** + - names/** + - providerlint/** + - skaff/** + - tools/** + +jobs: + changes: + runs-on: ubuntu-latest + outputs: + goreleaser: ${{ steps.filter.outputs.goreleaser }} + steps: + - uses: actions/checkout@v3 + - uses: dorny/paths-filter@v2 + id: filter + with: + filters: | + goreleaser: + - '.github/workflows/goreleaser-ci.yml' + - '.goreleaser.yml' + check: + needs: changes + if: ${{ needs.changes.outputs.goreleaser == 'true' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v3 + with: + go-version-file: go.mod + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - name: goreleaser check + uses: goreleaser/goreleaser-action@v2 + with: + args: check + build-32-bit: + # Run a single compiler check for 32-bit architecture (FreeBSD/ARM) + # Ref: https://github.com/hashicorp/terraform-provider-aws/issues/8988 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v3 + with: + go-version-file: go.mod + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - name: goreleaser build + uses: goreleaser/goreleaser-action@v2 + with: + args: build --config .github/goreleaser-cross-compiler-test.yml --id 32-bit-arch --snapshot \ No newline at end of file diff --git a/.github/workflows/maintainer-edit.yml b/.github/workflows/maintainer-edit.yml index 3b29d99bc87..71b3df3b38a 100644 --- a/.github/workflows/maintainer-edit.yml +++ b/.github/workflows/maintainer-edit.yml @@ -19,4 +19,3 @@ jobs: Hey @${{ github.actor }} :wave: Thank you very much for your contribution! At times, our maintainers need to make direct edits to pull requests in order to help get it ready to be merged. Your current settings do not allow maintainers to make such edits. To help facilitate this, update your pull request to allow such edits as described in GitHub's [Allowing changes to a pull request branch created from a fork][1] documentation. (If you're using a fork owned by an organization, your organization may not allow you to change this setting. If that is the case, let us know.) [1]: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork - diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ce3edc85789..5b716154ad8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -45,7 +45,7 @@ jobs: hc-releases-host-staging: '${{ secrets.HC_RELEASES_HOST_STAGING }}' hc-releases-host-prod: '${{ secrets.HC_RELEASES_HOST_PROD }}' with: - goreleaser-release-args: --timeout 2h + goreleaser-release-args: --timeout 3h release-notes: true setup-go-version: '${{ needs.go-version.outputs.version }}' # Product Version (e.g. v1.2.3 or github.ref_name) diff --git a/.github/workflows/semgrep-ci.yml b/.github/workflows/semgrep-ci.yml new file mode 100644 index 00000000000..ccd5504ac6a --- /dev/null +++ b/.github/workflows/semgrep-ci.yml @@ -0,0 +1,79 @@ +name: Semgrep Checks + +on: + push: + branches: + - main + - 'release/**' + pull_request: + paths: + - internal/** + - .semgrep*yml + - .github/workflows/semgrep-ci.yml + - .github/scripts/semgrep.sh + +jobs: + semgrep: + name: Semgrep Code Quality Scan + runs-on: ubuntu-latest + container: + image: returntocorp/semgrep + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - run: .github/scripts/semgrep.sh .semgrep.yml + naming_cac: + name: Semgrep Naming Scan Caps/AWS/EC2 + runs-on: ubuntu-latest + container: + image: returntocorp/semgrep + if: (github.action != 'dependabot[bot]') + steps: + - uses: actions/checkout@v3 + - run: .github/scripts/semgrep.sh .semgrep-caps-aws-ec2.yml + naming_tests: + name: Semgrep Test Configs Scan + runs-on: ubuntu-latest + container: + image: returntocorp/semgrep + if: (github.action != 'dependabot[bot]') + steps: + - uses: actions/checkout@v3 + - run: .github/scripts/semgrep.sh .semgrep-configs.yml + naming_semgrep0: + name: Semgrep Service Name Scan A-C + runs-on: ubuntu-latest + container: + image: returntocorp/semgrep + if: (github.action != 'dependabot[bot]') + steps: + - uses: actions/checkout@v3 + - run: .github/scripts/semgrep.sh .semgrep-service-name0.yml + naming_semgrep1: + name: Semgrep Service Name Scan C-I + runs-on: ubuntu-latest + container: + image: returntocorp/semgrep + if: (github.action != 'dependabot[bot]') + steps: + - uses: actions/checkout@v3 + - run: .github/scripts/semgrep.sh .semgrep-service-name1.yml + naming_semgrep2: + name: Semgrep Service Name Scan I-Q + runs-on: ubuntu-latest + container: + image: returntocorp/semgrep + if: (github.action != 'dependabot[bot]') + steps: + - uses: actions/checkout@v3 + - run: .github/scripts/semgrep.sh .semgrep-service-name2.yml + naming_semgrep3: + name: Semgrep Service Name Scan Q-Z + runs-on: ubuntu-latest + container: + image: returntocorp/semgrep + if: (github.action != 'dependabot[bot]') + steps: + - uses: actions/checkout@v3 + - run: .github/scripts/semgrep.sh .semgrep-service-name3.yml diff --git a/.github/workflows/skaff.yml b/.github/workflows/skaff.yml new file mode 100644 index 00000000000..c7bf34541c1 --- /dev/null +++ b/.github/workflows/skaff.yml @@ -0,0 +1,43 @@ +name: Skaff Checks + +on: + push: + branches: + - main + - 'release/**' + pull_request: + paths: + - names/** + - skaff/** + +jobs: + compile_skaff: + name: Compile skaff + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - uses: actions/setup-go@v3 + with: + go-version-file: .go-version + # See also: https://github.com/actions/setup-go/issues/54 + - name: go env + run: | + echo "GOCACHE=$(go env GOCACHE)" >> $GITHUB_ENV + - uses: actions/cache@v3 + continue-on-error: true + timeout-minutes: 2 + with: + path: ${{ env.GOCACHE }} + key: ${{ runner.os }}-GOCACHE-${{ hashFiles('go.sum') }}-${{ hashFiles('internal/**') }} + - uses: actions/cache@v3 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - name: Try building + run: | + cd skaff + go build diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml index 3cf9ba8b097..7a3d7a96d9f 100644 --- a/.github/workflows/snapshot.yml +++ b/.github/workflows/snapshot.yml @@ -10,11 +10,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true timeout-minutes: 2 diff --git a/.github/workflows/terraform_provider.yml b/.github/workflows/terraform_provider.yml index 472d68bbbe2..552be8576fc 100644 --- a/.github/workflows/terraform_provider.yml +++ b/.github/workflows/terraform_provider.yml @@ -8,9 +8,9 @@ on: pull_request: paths: - .github/workflows/terraform_provider.yml + - .github/scripts/providerlint.sh - .go-version - .golangci.yml - - .semgrep.yml - internal/** - providerlint/** - docs/index.md @@ -35,11 +35,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true id: cache-go-pkg-mod @@ -63,12 +61,10 @@ jobs: with: path: terraform-plugin-dir key: ${{ runner.os }}-terraform-plugin-dir-${{ hashFiles('go.sum') }}-${{ hashFiles('internal/**') }} - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - if: steps.cache-terraform-plugin-dir.outputs.cache-hit != 'true' || steps.cache-terraform-plugin-dir.outcome == 'failure' uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version # See also: https://github.com/actions/setup-go/issues/54 - if: steps.cache-terraform-plugin-dir.outputs.cache-hit != 'true' || steps.cache-terraform-plugin-dir.outcome == 'failure' name: go env @@ -129,11 +125,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version # See also: https://github.com/actions/setup-go/issues/54 - name: go env run: | @@ -152,7 +146,7 @@ jobs: key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} - run: cd providerlint && go install . - name: providerlint - run: make providerlint + run: .github/scripts/providerlint.sh go_generate: name: go generate @@ -160,11 +154,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version # See also: https://github.com/actions/setup-go/issues/54 - name: go env run: | @@ -196,11 +188,9 @@ jobs: - uses: actions/checkout@v3 with: fetch-depth: 0 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version # See also: https://github.com/actions/setup-go/issues/54 - name: go env run: | @@ -219,7 +209,7 @@ jobs: key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} - name: Get all changed files id: changed-files - uses: tj-actions/changed-files@v19 + uses: tj-actions/changed-files@v23 - name: Get changed packages run: | touch /tmp/dirs_changed_all @@ -282,11 +272,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version # See also: https://github.com/actions/setup-go/issues/54 - name: go env run: | @@ -304,19 +292,20 @@ jobs: path: ~/go/pkg/mod key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} - run: cd tools && go install github.com/golangci/golangci-lint/cmd/golangci-lint + shell: bash - run: golangci-lint run ./internal/... + shell: bash - run: cd providerlint && golangci-lint run ./... + shell: bash importlint: needs: [go_build] runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version # See also: https://github.com/actions/setup-go/issues/54 - name: go env run: | @@ -336,35 +325,14 @@ jobs: - run: cd tools && go install github.com/pavius/impi/cmd/impi - run: impi --local . --scheme stdThirdPartyLocal ./... - semgrep: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - name: semgrep - uses: returntocorp/semgrep-action@v1 - - naming_semgrep: - name: Semgrep Naming Scan - runs-on: ubuntu-latest - container: - image: returntocorp/semgrep - if: (github.action != 'dependabot[bot]') - steps: - - uses: actions/checkout@v3 - - run: semgrep -c .semgrep-service-name.yml - tfproviderdocs: needs: [terraform_providers_schema] runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true timeout-minutes: 2 @@ -396,11 +364,9 @@ jobs: - uses: actions/checkout@v3 with: fetch-depth: 0 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version # See also: https://github.com/actions/setup-go/issues/54 - name: go env run: | @@ -419,36 +385,3 @@ jobs: key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} - name: Try building run: go build -tags=sweep - - compile_skaff: - name: Compile compile_skaff - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - - uses: actions/setup-go@v3 - with: - go-version: ${{ env.GO_VERSION }} - # See also: https://github.com/actions/setup-go/issues/54 - - name: go env - run: | - echo "GOCACHE=$(go env GOCACHE)" >> $GITHUB_ENV - - uses: actions/cache@v3 - continue-on-error: true - timeout-minutes: 2 - with: - path: ${{ env.GOCACHE }} - key: ${{ runner.os }}-GOCACHE-${{ hashFiles('go.sum') }}-${{ hashFiles('internal/**') }} - - uses: actions/cache@v3 - continue-on-error: true - timeout-minutes: 2 - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} - - name: Try building - run: | - cd skaff - go build diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml index 36a039638b9..64edb8f3f7c 100644 --- a/.github/workflows/website.yml +++ b/.github/workflows/website.yml @@ -74,11 +74,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true timeout-minutes: 2 @@ -91,11 +89,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true timeout-minutes: 2 @@ -108,11 +104,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - uses: actions/cache@v3 continue-on-error: true timeout-minutes: 2 diff --git a/.github/workflows/workflow-lint.yml b/.github/workflows/workflow-lint.yml index f844eaa1a41..ac1cd700c85 100644 --- a/.github/workflows/workflow-lint.yml +++ b/.github/workflows/workflow-lint.yml @@ -12,11 +12,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - # See also: https://github.com/actions/setup-go/pull/62 - - run: echo "GO_VERSION=$(cat .go-version)" >> $GITHUB_ENV - uses: actions/setup-go@v3 with: - go-version: ${{ env.GO_VERSION }} + go-version-file: .go-version - name: Install actionlint run: cd tools && go install github.com/rhysd/actionlint/cmd/actionlint - name: Run actionlint on workflow files diff --git a/.semgrep-caps-aws-ec2.yml b/.semgrep-caps-aws-ec2.yml new file mode 100644 index 00000000000..7bfeddb08cf --- /dev/null +++ b/.semgrep-caps-aws-ec2.yml @@ -0,0 +1,339 @@ +# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. +rules: + - id: aws-in-func-name + languages: + - go + message: Do not use "AWS" in func name inside AWS Provider + paths: + include: + - internal + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AWS" + severity: WARNING + - id: aws-in-const-name + languages: + - go + message: Do not use "AWS" in const name inside AWS Provider + paths: + include: + - internal + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AWS" + severity: WARNING + - id: aws-in-var-name + languages: + - go + message: Do not use "AWS" in var name inside AWS Provider + paths: + include: + - internal + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AWS" + severity: WARNING + - id: caps0-in-func-name + languages: + - go + message: Use correct caps in func name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Cloudformation|ElasticSearch|Autoscaling|Elasticache|ApiGateway|Cloudfront|Cloudwatch|Workspaces|Appconfig|Guardduty|Sagemaker|Workgroup|DynamoDb|Dynamodb|Gamelift|Opsworks|Precheck|Rabbitmq|Worklink|Appmesh|Appsync)" + severity: WARNING + - id: caps0-in-const-name + languages: + - go + message: Use correct caps in const name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Cloudformation|ElasticSearch|Autoscaling|Elasticache|ApiGateway|Cloudfront|Cloudwatch|Workspaces|Appconfig|Guardduty|Sagemaker|Workgroup|DynamoDb|Dynamodb|Gamelift|Opsworks|Precheck|Rabbitmq|Worklink|Appmesh|Appsync)" + severity: WARNING + - id: caps0-in-var-name + languages: + - go + message: Use correct caps in var name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Cloudformation|ElasticSearch|Autoscaling|Elasticache|ApiGateway|Cloudfront|Cloudwatch|Workspaces|Appconfig|Guardduty|Sagemaker|Workgroup|DynamoDb|Dynamodb|Gamelift|Opsworks|Precheck|Rabbitmq|Worklink|Appmesh|Appsync)" + severity: WARNING + - id: caps1-in-func-name + languages: + - go + message: Use correct caps in func name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Graphql|Haproxy|AcmPca|Acmpca|Dnssec|Byoip|Cname|DocDb|Docdb|Fqdns|Https|Ipset|Iscsi|Mysql|Oauth|Posix|Wafv2|Cidr|Coip|Dhcp|Dkim)" + severity: WARNING + - id: caps1-in-const-name + languages: + - go + message: Use correct caps in const name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Graphql|Haproxy|AcmPca|Acmpca|Dnssec|Byoip|Cname|DocDb|Docdb|Fqdns|Https|Ipset|Iscsi|Mysql|Oauth|Posix|Wafv2|Cidr|Coip|Dhcp|Dkim)" + severity: WARNING + - id: caps1-in-var-name + languages: + - go + message: Use correct caps in var name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Graphql|Haproxy|AcmPca|Acmpca|Dnssec|Byoip|Cname|DocDb|Docdb|Fqdns|Https|Ipset|Iscsi|Mysql|Oauth|Posix|Wafv2|Cidr|Coip|Dhcp|Dkim)" + severity: WARNING + - id: caps2-in-func-name + languages: + - go + message: Use correct caps in func name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Ecmp|Fifo|Grpc|Http|Ipam|Jdbc|Json|Mwaa|Oidc|Pitr|Qldb|Sasl|Smtp|Voip|Xray|Yaml|Acl|Acm|Ami|Api|Arn)" + severity: WARNING + - id: caps2-in-const-name + languages: + - go + message: Use correct caps in const name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Ecmp|Fifo|Grpc|Http|Ipam|Jdbc|Json|Mwaa|Oidc|Pitr|Qldb|Sasl|Smtp|Voip|Xray|Yaml|Acl|Acm|Ami|Api|Arn)" + severity: WARNING + - id: caps2-in-var-name + languages: + - go + message: Use correct caps in var name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Ecmp|Fifo|Grpc|Http|Ipam|Jdbc|Json|Mwaa|Oidc|Pitr|Qldb|Sasl|Smtp|Voip|Xray|Yaml|Acl|Acm|Ami|Api|Arn)" + severity: WARNING + - id: caps3-in-func-name + languages: + - go + message: Use correct caps in func name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Asg|Asn|Bgp|Cmk|Cpu|Css|Csv|Dax|Dlm|Dms|Dns|Ebs|Ec2|Ecr|Ecs|Efs|Eip|Eks|Elb|Emr|FSX)" + severity: WARNING + - id: caps3-in-const-name + languages: + - go + message: Use correct caps in const name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Asg|Asn|Bgp|Cmk|Cpu|Css|Csv|Dax|Dlm|Dms|Dns|Ebs|Ec2|Ecr|Ecs|Efs|Eip|Eks|Elb|Emr|FSX)" + severity: WARNING + - id: caps3-in-var-name + languages: + - go + message: Use correct caps in var name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Asg|Asn|Bgp|Cmk|Cpu|Css|Csv|Dax|Dlm|Dms|Dns|Ebs|Ec2|Ecr|Ecs|Efs|Eip|Eks|Elb|Emr|FSX)" + severity: WARNING + - id: caps4-in-func-name + languages: + - go + message: Use correct caps in func name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Fms|Fsx|Gcm|Gp2|Gp3|Hsm|Hvm|Iam|Iot|Kms|Mfa|Msk|Nfs|Php|Rds|Rfc|Sfn|Smb|Sms|Sns|Sql)" + severity: WARNING + - id: caps4-in-const-name + languages: + - go + message: Use correct caps in const name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Fms|Fsx|Gcm|Gp2|Gp3|Hsm|Hvm|Iam|Iot|Kms|Mfa|Msk|Nfs|Php|Rds|Rfc|Sfn|Smb|Sms|Sns|Sql)" + severity: WARNING + - id: caps4-in-var-name + languages: + - go + message: Use correct caps in var name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Fms|Fsx|Gcm|Gp2|Gp3|Hsm|Hvm|Iam|Iot|Kms|Mfa|Msk|Nfs|Php|Rds|Rfc|Sfn|Smb|Sms|Sns|Sql)" + severity: WARNING + - id: caps5-in-func-name + languages: + - go + message: Use correct caps in func name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Sqs|Ssh|Ssl|Ssm|Sso|Sts|Swf|Tcp|Tls|Ttl|Uri|Url|Vgw|Vpc|Vpn|Waf|Xss|Db|Ip)" + severity: WARNING + - id: caps5-in-const-name + languages: + - go + message: Use correct caps in const name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Sqs|Ssh|Ssl|Ssm|Sso|Sts|Swf|Tcp|Tls|Ttl|Uri|Url|Vgw|Vpc|Vpn|Waf|Xss|Db|Ip)" + severity: WARNING + - id: caps5-in-var-name + languages: + - go + message: Use correct caps in var name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(Sqs|Ssh|Ssl|Ssm|Sso|Sts|Swf|Tcp|Tls|Ttl|Uri|Url|Vgw|Vpc|Vpn|Waf|Xss|Db|Ip)" + severity: WARNING + - id: ec2-in-func-name + languages: + - go + message: Do not use "EC2" in func name inside ec2 package + paths: + include: + - internal/service/ec2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EC2" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ec2-in-const-name + languages: + - go + message: Do not use "EC2" in const name inside ec2 package + paths: + include: + - internal/service/ec2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EC2" + severity: WARNING + - id: ec2-in-var-name + languages: + - go + message: Do not use "EC2" in var name inside ec2 package + paths: + include: + - internal/service/ec2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EC2" + severity: WARNING diff --git a/.semgrep-configs.yml b/.semgrep-configs.yml new file mode 100644 index 00000000000..c98fce788eb --- /dev/null +++ b/.semgrep-configs.yml @@ -0,0 +1,80 @@ +# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. +rules: + - id: test-config-funcs-correct-form + languages: + - go + message: "Config funcs should follow form testAccConfig_" + paths: + include: + - internal/service/**/*_test.go + patterns: + - pattern-inside: "[]resource.TestStep{ ... }" + - pattern: "{..., $KEY:$VALUE, ...}" + - metavariable-pattern: + metavariable: "$KEY" + patterns: + - pattern: "Config" + - metavariable-pattern: + metavariable: "$VALUE" + patterns: + - pattern-not-regex: "testAcc[a-zA-Z0-9]+Config(_[a-zA-Z0-9_]+_|_)[a-z0-9].*" + - pattern-not: acctest.ConfigCompose(...) + severity: WARNING + - id: test-configcompose-funcs-correct-form + languages: + - go + message: "Config funcs should follow form testAccConfig_" + paths: + include: + - internal/service/**/*_test.go + patterns: + - pattern-inside: "[]resource.TestStep{ ... }" + - pattern: "{..., $KEY: acctest.ConfigCompose(..., $VALUE, ...), ...}" + - metavariable-pattern: + metavariable: "$KEY" + patterns: + - pattern: "Config" + - metavariable-pattern: + metavariable: "$VALUE" + patterns: + - pattern-not-regex: "testAcc[a-zA-Z0-9]+Config(_[a-zA-Z0-9_]+_|_)[a-z0-9].*" + - pattern-not-regex: "acctest\\..*" + severity: WARNING + - id: test-config-funcs-check + languages: + - go + message: "Config funcs should not begin with 'testAccCheck'" + paths: + include: + - internal/service/**/*_test.go + patterns: + - pattern-inside: "[]resource.TestStep{ ... }" + - pattern: "{..., $KEY:$VALUE, ...}" + - metavariable-pattern: + metavariable: "$KEY" + patterns: + - pattern: "Config" + - metavariable-pattern: + metavariable: "$VALUE" + patterns: + - pattern-regex: "testAccCheck.*" + severity: WARNING + - id: test-configcompose-funcs-check + languages: + - go + message: "Config funcs should not begin with 'testAccCheck'" + paths: + include: + - internal/service/**/*_test.go + patterns: + - pattern-inside: "[]resource.TestStep{ ... }" + - pattern: "{..., $KEY: acctest.ConfigCompose(..., $VALUE, ...), ...}" + - metavariable-pattern: + metavariable: "$KEY" + patterns: + - pattern: "Config" + - metavariable-pattern: + metavariable: "$VALUE" + patterns: + - pattern-regex: "testAccCheck.*" + severity: WARNING diff --git a/.semgrep-service-name.yml b/.semgrep-service-name.yml deleted file mode 100644 index 0641c350a04..00000000000 --- a/.semgrep-service-name.yml +++ /dev/null @@ -1,7491 +0,0 @@ -# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. -rules: - - id: aws-in-func-name - languages: - - go - message: Do not use "AWS" in func name inside AWS Provider - paths: - include: - - internal/service/ec2 - - internal/service/timestreamwrite - - internal/service/transfer - - internal/service/waf - - internal/service/wafregional - - internal/service/wafv2 - - internal/service/worklink - - internal/service/workspaces - - internal/service/xray - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)AWS" - severity: WARNING - - id: aws-in-const-name - languages: - - go - message: Do not use "AWS" in const name inside AWS Provider - paths: - include: - - internal/service/ec2 - - internal/service/timestreamwrite - - internal/service/transfer - - internal/service/waf - - internal/service/wafregional - - internal/service/wafv2 - - internal/service/worklink - - internal/service/workspaces - - internal/service/xray - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)AWS" - severity: WARNING - - id: aws-in-var-name - languages: - - go - message: Do not use "AWS" in var name inside AWS Provider - paths: - include: - - internal/service/ec2 - - internal/service/timestreamwrite - - internal/service/transfer - - internal/service/waf - - internal/service/wafregional - - internal/service/wafv2 - - internal/service/worklink - - internal/service/workspaces - - internal/service/xray - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)AWS" - severity: WARNING - - id: caps-in-func-name - languages: - - go - message: Use correct caps in func name (i.e., HTTPS or https, not Https) - paths: - include: - - internal/service/ec2 - - internal/service/timestreamwrite - - internal/service/transfer - - internal/service/waf - - internal/service/wafregional - - internal/service/wafv2 - - internal/service/worklink - - internal/service/workspaces - - internal/service/xray - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(Cloudformation|ElasticSearch|Autoscaling|Elasticache|ApiGateway|Cloudfront|Cloudwatch|Workspaces|Appconfig|Guardduty|Sagemaker|Workgroup|DynamoDb|Dynamodb|Gamelift|Opsworks|Precheck|Rabbitmq|Worklink|Appmesh|Appsync|Graphql|Haproxy|AcmPca|Acmpca|Dnssec|Byoip|Cname|DocDb|Docdb|Fqdns|Https|Ipset|Iscsi|Mysql|Oauth|Posix|Wafv2|Cidr|Coip|Dhcp|Dkim|Ecmp|Fifo|Grpc|Http|Ipam|Jdbc|Json|Mwaa|Oidc|Pitr|Qldb|Sasl|Smtp|Voip|Xray|Yaml|Acl|Acm|Ami|Api|Arn|Asg|Asn|Bgp|Cmk|Cpu|Css|Csv|Dax|Dlm|Dms|Dns|Ebs|Ec2|Ecr|Ecs|Efs|Eip|Eks|Elb|Emr|FSX|Fms|Fsx|Gcm|Gp2|Gp3|Hsm|Hvm|Iam|Iot|Kms|Mfa|Msk|Nfs|Php|Rds|Rfc|Sfn|Smb|Sms|Sns|Sql|Sqs|Ssh|Ssl|Ssm|Sso|Sts|Swf|Tcp|Tls|Ttl|Uri|Url|Vgw|Vpc|Vpn|Waf|Xss|Db|Ip)" - severity: WARNING - - id: caps-in-const-name - languages: - - go - message: Use correct caps in const name (i.e., HTTPS or https, not Https) - paths: - include: - - internal/service/ec2 - - internal/service/timestreamwrite - - internal/service/transfer - - internal/service/waf - - internal/service/wafregional - - internal/service/wafv2 - - internal/service/worklink - - internal/service/workspaces - - internal/service/xray - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(Cloudformation|ElasticSearch|Autoscaling|Elasticache|ApiGateway|Cloudfront|Cloudwatch|Workspaces|Appconfig|Guardduty|Sagemaker|Workgroup|DynamoDb|Dynamodb|Gamelift|Opsworks|Precheck|Rabbitmq|Worklink|Appmesh|Appsync|Graphql|Haproxy|AcmPca|Acmpca|Dnssec|Byoip|Cname|DocDb|Docdb|Fqdns|Https|Ipset|Iscsi|Mysql|Oauth|Posix|Wafv2|Cidr|Coip|Dhcp|Dkim|Ecmp|Fifo|Grpc|Http|Ipam|Jdbc|Json|Mwaa|Oidc|Pitr|Qldb|Sasl|Smtp|Voip|Xray|Yaml|Acl|Acm|Ami|Api|Arn|Asg|Asn|Bgp|Cmk|Cpu|Css|Csv|Dax|Dlm|Dms|Dns|Ebs|Ec2|Ecr|Ecs|Efs|Eip|Eks|Elb|Emr|FSX|Fms|Fsx|Gcm|Gp2|Gp3|Hsm|Hvm|Iam|Iot|Kms|Mfa|Msk|Nfs|Php|Rds|Rfc|Sfn|Smb|Sms|Sns|Sql|Sqs|Ssh|Ssl|Ssm|Sso|Sts|Swf|Tcp|Tls|Ttl|Uri|Url|Vgw|Vpc|Vpn|Waf|Xss|Db|Ip)" - severity: WARNING - - id: caps-in-var-name - languages: - - go - message: Use correct caps in var name (i.e., HTTPS or https, not Https) - paths: - include: - - internal/service/ec2 - - internal/service/timestreamwrite - - internal/service/transfer - - internal/service/waf - - internal/service/wafregional - - internal/service/wafv2 - - internal/service/worklink - - internal/service/workspaces - - internal/service/xray - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(Cloudformation|ElasticSearch|Autoscaling|Elasticache|ApiGateway|Cloudfront|Cloudwatch|Workspaces|Appconfig|Guardduty|Sagemaker|Workgroup|DynamoDb|Dynamodb|Gamelift|Opsworks|Precheck|Rabbitmq|Worklink|Appmesh|Appsync|Graphql|Haproxy|AcmPca|Acmpca|Dnssec|Byoip|Cname|DocDb|Docdb|Fqdns|Https|Ipset|Iscsi|Mysql|Oauth|Posix|Wafv2|Cidr|Coip|Dhcp|Dkim|Ecmp|Fifo|Grpc|Http|Ipam|Jdbc|Json|Mwaa|Oidc|Pitr|Qldb|Sasl|Smtp|Voip|Xray|Yaml|Acl|Acm|Ami|Api|Arn|Asg|Asn|Bgp|Cmk|Cpu|Css|Csv|Dax|Dlm|Dms|Dns|Ebs|Ec2|Ecr|Ecs|Efs|Eip|Eks|Elb|Emr|FSX|Fms|Fsx|Gcm|Gp2|Gp3|Hsm|Hvm|Iam|Iot|Kms|Mfa|Msk|Nfs|Php|Rds|Rfc|Sfn|Smb|Sms|Sns|Sql|Sqs|Ssh|Ssl|Ssm|Sso|Sts|Swf|Tcp|Tls|Ttl|Uri|Url|Vgw|Vpc|Vpn|Waf|Xss|Db|Ip)" - severity: WARNING - - id: config-funcs-correct-form - message: "Config funcs should follow form testAccConfig_" - languages: [go] - paths: - include: - - internal/service/timestreamwrite - - internal/service/transfer - - internal/service/waf - - internal/service/wafregional - - internal/service/wafv2 - - internal/service/worklink - - internal/service/workspaces - - internal/service/xray - patterns: - - pattern-inside: "[]resource.TestStep{ ... }" - - pattern: "{..., $KEY:$VALUE, ...}" - - metavariable-pattern: - metavariable: "$KEY" - patterns: - - pattern: "Config" - - metavariable-pattern: - metavariable: "$VALUE" - patterns: - - pattern-not-regex: "testAcc[a-zA-Z0-9]+Config_.*" - severity: WARNING - - id: ec2-in-func-name - languages: - - go - message: Do not use "EC2" in func name inside ec2 package - paths: - include: - - internal/service/ec2 - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EC2" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: ec2-in-const-name - languages: - - go - message: Do not use "EC2" in const name inside ec2 package - paths: - include: - - internal/service/ec2 - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EC2" - severity: WARNING - - id: ec2-in-var-name - languages: - - go - message: Do not use "EC2" in var name inside ec2 package - paths: - include: - - internal/service/ec2 - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EC2" - severity: WARNING - - id: ec2-in-test-name - languages: - - go - message: Include "EC2" in test name - paths: - include: - - internal/service/ec2/ec2_*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccEC2" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ec2ebs-in-test-name - languages: - - go - message: Include "EC2EBS" in test name - paths: - include: - - internal/service/ec2/ebs_*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccEC2EBS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ec2outposts-in-test-name - languages: - - go - message: Include "EC2Outposts" in test name - paths: - include: - - internal/service/ec2/outposts_*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccEC2Outposts" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ecr-in-func-name - languages: - - go - message: Do not use "ECR" in func name inside ecr package - paths: - include: - - internal/service/ecr - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ECR" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: ecr-in-test-name - languages: - - go - message: Include "ECR" in test name - paths: - include: - - internal/service/ecr/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccECR" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ecr-in-const-name - languages: - - go - message: Do not use "ECR" in const name inside ecr package - paths: - include: - - internal/service/ecr - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ECR" - severity: WARNING - - id: ecr-in-var-name - languages: - - go - message: Do not use "ECR" in var name inside ecr package - paths: - include: - - internal/service/ecr - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ECR" - severity: WARNING - - id: ecrpublic-in-func-name - languages: - - go - message: Do not use "ECRPublic" in func name inside ecrpublic package - paths: - include: - - internal/service/ecrpublic - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ECRPublic" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: ecrpublic-in-test-name - languages: - - go - message: Include "ECRPublic" in test name - paths: - include: - - internal/service/ecrpublic/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccECRPublic" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ecrpublic-in-const-name - languages: - - go - message: Do not use "ECRPublic" in const name inside ecrpublic package - paths: - include: - - internal/service/ecrpublic - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ECRPublic" - severity: WARNING - - id: ecrpublic-in-var-name - languages: - - go - message: Do not use "ECRPublic" in var name inside ecrpublic package - paths: - include: - - internal/service/ecrpublic - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ECRPublic" - severity: WARNING - - id: ecs-in-func-name - languages: - - go - message: Do not use "ECS" in func name inside ecs package - paths: - include: - - internal/service/ecs - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ECS" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: ecs-in-test-name - languages: - - go - message: Include "ECS" in test name - paths: - include: - - internal/service/ecs/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccECS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ecs-in-const-name - languages: - - go - message: Do not use "ECS" in const name inside ecs package - paths: - include: - - internal/service/ecs - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ECS" - severity: WARNING - - id: ecs-in-var-name - languages: - - go - message: Do not use "ECS" in var name inside ecs package - paths: - include: - - internal/service/ecs - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ECS" - severity: WARNING - - id: efs-in-func-name - languages: - - go - message: Do not use "EFS" in func name inside efs package - paths: - include: - - internal/service/efs - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EFS" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: efs-in-test-name - languages: - - go - message: Include "EFS" in test name - paths: - include: - - internal/service/efs/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccEFS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: efs-in-const-name - languages: - - go - message: Do not use "EFS" in const name inside efs package - paths: - include: - - internal/service/efs - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EFS" - severity: WARNING - - id: efs-in-var-name - languages: - - go - message: Do not use "EFS" in var name inside efs package - paths: - include: - - internal/service/efs - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EFS" - severity: WARNING - - id: eks-in-func-name - languages: - - go - message: Do not use "EKS" in func name inside eks package - paths: - include: - - internal/service/eks - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EKS" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: eks-in-test-name - languages: - - go - message: Include "EKS" in test name - paths: - include: - - internal/service/eks/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccEKS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: eks-in-const-name - languages: - - go - message: Do not use "EKS" in const name inside eks package - paths: - include: - - internal/service/eks - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EKS" - severity: WARNING - - id: eks-in-var-name - languages: - - go - message: Do not use "EKS" in var name inside eks package - paths: - include: - - internal/service/eks - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EKS" - severity: WARNING - - id: elasticache-in-func-name - languages: - - go - message: Do not use "ElastiCache" in func name inside elasticache package - paths: - include: - - internal/service/elasticache - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ElastiCache" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: elasticache-in-test-name - languages: - - go - message: Include "ElastiCache" in test name - paths: - include: - - internal/service/elasticache/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccElastiCache" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: elasticache-in-const-name - languages: - - go - message: Do not use "ElastiCache" in const name inside elasticache package - paths: - include: - - internal/service/elasticache - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ElastiCache" - severity: WARNING - - id: elasticache-in-var-name - languages: - - go - message: Do not use "ElastiCache" in var name inside elasticache package - paths: - include: - - internal/service/elasticache - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ElastiCache" - severity: WARNING - - id: elasticbeanstalk-in-func-name - languages: - - go - message: Do not use "ElasticBeanstalk" in func name inside elasticbeanstalk package - paths: - include: - - internal/service/elasticbeanstalk - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ElasticBeanstalk" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: elasticbeanstalk-in-test-name - languages: - - go - message: Include "ElasticBeanstalk" in test name - paths: - include: - - internal/service/elasticbeanstalk/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccElasticBeanstalk" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: elasticbeanstalk-in-const-name - languages: - - go - message: Do not use "ElasticBeanstalk" in const name inside elasticbeanstalk package - paths: - include: - - internal/service/elasticbeanstalk - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ElasticBeanstalk" - severity: WARNING - - id: elasticbeanstalk-in-var-name - languages: - - go - message: Do not use "ElasticBeanstalk" in var name inside elasticbeanstalk package - paths: - include: - - internal/service/elasticbeanstalk - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ElasticBeanstalk" - severity: WARNING - - id: elasticloadbalancing-in-func-name - languages: - - go - message: Do not use "elasticloadbalancing" in func name inside elb package - paths: - include: - - internal/service/elb - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)elasticloadbalancing" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: elasticloadbalancing-in-const-name - languages: - - go - message: Do not use "elasticloadbalancing" in const name inside elb package - paths: - include: - - internal/service/elb - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)elasticloadbalancing" - severity: WARNING - - id: elasticloadbalancing-in-var-name - languages: - - go - message: Do not use "elasticloadbalancing" in var name inside elb package - paths: - include: - - internal/service/elb - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)elasticloadbalancing" - severity: WARNING - - id: elasticloadbalancingv2-in-func-name - languages: - - go - message: Do not use "elasticloadbalancingv2" in func name inside elbv2 package - paths: - include: - - internal/service/elbv2 - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)elasticloadbalancingv2" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: elasticloadbalancingv2-in-const-name - languages: - - go - message: Do not use "elasticloadbalancingv2" in const name inside elbv2 package - paths: - include: - - internal/service/elbv2 - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)elasticloadbalancingv2" - severity: WARNING - - id: elasticloadbalancingv2-in-var-name - languages: - - go - message: Do not use "elasticloadbalancingv2" in var name inside elbv2 package - paths: - include: - - internal/service/elbv2 - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)elasticloadbalancingv2" - severity: WARNING - - id: elasticsearch-in-func-name - languages: - - go - message: Do not use "Elasticsearch" in func name inside elasticsearch package - paths: - include: - - internal/service/elasticsearch - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Elasticsearch" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: elasticsearch-in-test-name - languages: - - go - message: Include "Elasticsearch" in test name - paths: - include: - - internal/service/elasticsearch/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccElasticsearch" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: elasticsearch-in-const-name - languages: - - go - message: Do not use "Elasticsearch" in const name inside elasticsearch package - paths: - include: - - internal/service/elasticsearch - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Elasticsearch" - severity: WARNING - - id: elasticsearch-in-var-name - languages: - - go - message: Do not use "Elasticsearch" in var name inside elasticsearch package - paths: - include: - - internal/service/elasticsearch - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Elasticsearch" - severity: WARNING - - id: elasticsearchservice-in-func-name - languages: - - go - message: Do not use "elasticsearchservice" in func name inside elasticsearch package - paths: - include: - - internal/service/elasticsearch - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)elasticsearchservice" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: elasticsearchservice-in-const-name - languages: - - go - message: Do not use "elasticsearchservice" in const name inside elasticsearch package - paths: - include: - - internal/service/elasticsearch - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)elasticsearchservice" - severity: WARNING - - id: elasticsearchservice-in-var-name - languages: - - go - message: Do not use "elasticsearchservice" in var name inside elasticsearch package - paths: - include: - - internal/service/elasticsearch - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)elasticsearchservice" - severity: WARNING - - id: elastictranscoder-in-func-name - languages: - - go - message: Do not use "ElasticTranscoder" in func name inside elastictranscoder package - paths: - include: - - internal/service/elastictranscoder - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ElasticTranscoder" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: elastictranscoder-in-test-name - languages: - - go - message: Include "ElasticTranscoder" in test name - paths: - include: - - internal/service/elastictranscoder/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccElasticTranscoder" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: elastictranscoder-in-const-name - languages: - - go - message: Do not use "ElasticTranscoder" in const name inside elastictranscoder package - paths: - include: - - internal/service/elastictranscoder - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ElasticTranscoder" - severity: WARNING - - id: elastictranscoder-in-var-name - languages: - - go - message: Do not use "ElasticTranscoder" in var name inside elastictranscoder package - paths: - include: - - internal/service/elastictranscoder - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ElasticTranscoder" - severity: WARNING - - id: elb-in-func-name - languages: - - go - message: Do not use "ELB" in func name inside elb package - paths: - include: - - internal/service/elb - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ELB" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: elb-in-test-name - languages: - - go - message: Include "ELB" in test name - paths: - include: - - internal/service/elb/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccELB" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: elb-in-const-name - languages: - - go - message: Do not use "ELB" in const name inside elb package - paths: - include: - - internal/service/elb - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ELB" - severity: WARNING - - id: elb-in-var-name - languages: - - go - message: Do not use "ELB" in var name inside elb package - paths: - include: - - internal/service/elb - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ELB" - severity: WARNING - - id: elbv2-in-func-name - languages: - - go - message: Do not use "ELBV2" in func name inside elbv2 package - paths: - include: - - internal/service/elbv2 - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ELBV2" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: elbv2-in-test-name - languages: - - go - message: Include "ELBV2" in test name - paths: - include: - - internal/service/elbv2/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccELBV2" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: elbv2-in-const-name - languages: - - go - message: Do not use "ELBV2" in const name inside elbv2 package - paths: - include: - - internal/service/elbv2 - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ELBV2" - severity: WARNING - - id: elbv2-in-var-name - languages: - - go - message: Do not use "ELBV2" in var name inside elbv2 package - paths: - include: - - internal/service/elbv2 - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ELBV2" - severity: WARNING - - id: emr-in-func-name - languages: - - go - message: Do not use "EMR" in func name inside emr package - paths: - include: - - internal/service/emr - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EMR" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: emr-in-test-name - languages: - - go - message: Include "EMR" in test name - paths: - include: - - internal/service/emr/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccEMR" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: emr-in-const-name - languages: - - go - message: Do not use "EMR" in const name inside emr package - paths: - include: - - internal/service/emr - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EMR" - severity: WARNING - - id: emr-in-var-name - languages: - - go - message: Do not use "EMR" in var name inside emr package - paths: - include: - - internal/service/emr - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EMR" - severity: WARNING - - id: emrcontainers-in-func-name - languages: - - go - message: Do not use "EMRContainers" in func name inside emrcontainers package - paths: - include: - - internal/service/emrcontainers - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EMRContainers" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: emrcontainers-in-test-name - languages: - - go - message: Include "EMRContainers" in test name - paths: - include: - - internal/service/emrcontainers/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccEMRContainers" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: emrcontainers-in-const-name - languages: - - go - message: Do not use "EMRContainers" in const name inside emrcontainers package - paths: - include: - - internal/service/emrcontainers - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EMRContainers" - severity: WARNING - - id: emrcontainers-in-var-name - languages: - - go - message: Do not use "EMRContainers" in var name inside emrcontainers package - paths: - include: - - internal/service/emrcontainers - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)EMRContainers" - severity: WARNING - - id: eventbridge-in-func-name - languages: - - go - message: Do not use "eventbridge" in func name inside events package - paths: - include: - - internal/service/events - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)eventbridge" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: eventbridge-in-const-name - languages: - - go - message: Do not use "eventbridge" in const name inside events package - paths: - include: - - internal/service/events - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)eventbridge" - severity: WARNING - - id: eventbridge-in-var-name - languages: - - go - message: Do not use "eventbridge" in var name inside events package - paths: - include: - - internal/service/events - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)eventbridge" - severity: WARNING - - id: events-in-func-name - languages: - - go - message: Do not use "Events" in func name inside events package - paths: - include: - - internal/service/events - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Events" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: events-in-test-name - languages: - - go - message: Include "Events" in test name - paths: - include: - - internal/service/events/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccEvents" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: events-in-const-name - languages: - - go - message: Do not use "Events" in const name inside events package - paths: - include: - - internal/service/events - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Events" - severity: WARNING - - id: events-in-var-name - languages: - - go - message: Do not use "Events" in var name inside events package - paths: - include: - - internal/service/events - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Events" - severity: WARNING - - id: firehose-in-func-name - languages: - - go - message: Do not use "Firehose" in func name inside firehose package - paths: - include: - - internal/service/firehose - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Firehose" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: firehose-in-test-name - languages: - - go - message: Include "Firehose" in test name - paths: - include: - - internal/service/firehose/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccFirehose" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: firehose-in-const-name - languages: - - go - message: Do not use "Firehose" in const name inside firehose package - paths: - include: - - internal/service/firehose - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Firehose" - severity: WARNING - - id: firehose-in-var-name - languages: - - go - message: Do not use "Firehose" in var name inside firehose package - paths: - include: - - internal/service/firehose - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Firehose" - severity: WARNING - - id: fms-in-func-name - languages: - - go - message: Do not use "FMS" in func name inside fms package - paths: - include: - - internal/service/fms - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)FMS" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: fms-in-test-name - languages: - - go - message: Include "FMS" in test name - paths: - include: - - internal/service/fms/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccFMS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: fms-in-const-name - languages: - - go - message: Do not use "FMS" in const name inside fms package - paths: - include: - - internal/service/fms - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)FMS" - severity: WARNING - - id: fms-in-var-name - languages: - - go - message: Do not use "FMS" in var name inside fms package - paths: - include: - - internal/service/fms - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)FMS" - severity: WARNING - - id: fsx-in-func-name - languages: - - go - message: Do not use "FSx" in func name inside fsx package - paths: - include: - - internal/service/fsx - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)FSx" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: fsx-in-test-name - languages: - - go - message: Include "FSx" in test name - paths: - include: - - internal/service/fsx/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccFSx" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: fsx-in-const-name - languages: - - go - message: Do not use "FSx" in const name inside fsx package - paths: - include: - - internal/service/fsx - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)FSx" - severity: WARNING - - id: fsx-in-var-name - languages: - - go - message: Do not use "FSx" in var name inside fsx package - paths: - include: - - internal/service/fsx - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)FSx" - severity: WARNING - - id: gamelift-in-func-name - languages: - - go - message: Do not use "GameLift" in func name inside gamelift package - paths: - include: - - internal/service/gamelift - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)GameLift" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: gamelift-in-test-name - languages: - - go - message: Include "GameLift" in test name - paths: - include: - - internal/service/gamelift/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccGameLift" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: gamelift-in-const-name - languages: - - go - message: Do not use "GameLift" in const name inside gamelift package - paths: - include: - - internal/service/gamelift - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)GameLift" - severity: WARNING - - id: gamelift-in-var-name - languages: - - go - message: Do not use "GameLift" in var name inside gamelift package - paths: - include: - - internal/service/gamelift - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)GameLift" - severity: WARNING - - id: glacier-in-func-name - languages: - - go - message: Do not use "Glacier" in func name inside glacier package - paths: - include: - - internal/service/glacier - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Glacier" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: glacier-in-test-name - languages: - - go - message: Include "Glacier" in test name - paths: - include: - - internal/service/glacier/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccGlacier" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: glacier-in-const-name - languages: - - go - message: Do not use "Glacier" in const name inside glacier package - paths: - include: - - internal/service/glacier - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Glacier" - severity: WARNING - - id: glacier-in-var-name - languages: - - go - message: Do not use "Glacier" in var name inside glacier package - paths: - include: - - internal/service/glacier - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Glacier" - severity: WARNING - - id: globalaccelerator-in-func-name - languages: - - go - message: Do not use "GlobalAccelerator" in func name inside globalaccelerator package - paths: - include: - - internal/service/globalaccelerator - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)GlobalAccelerator" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: globalaccelerator-in-test-name - languages: - - go - message: Include "GlobalAccelerator" in test name - paths: - include: - - internal/service/globalaccelerator/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccGlobalAccelerator" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: globalaccelerator-in-const-name - languages: - - go - message: Do not use "GlobalAccelerator" in const name inside globalaccelerator package - paths: - include: - - internal/service/globalaccelerator - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)GlobalAccelerator" - severity: WARNING - - id: globalaccelerator-in-var-name - languages: - - go - message: Do not use "GlobalAccelerator" in var name inside globalaccelerator package - paths: - include: - - internal/service/globalaccelerator - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)GlobalAccelerator" - severity: WARNING - - id: glue-in-func-name - languages: - - go - message: Do not use "Glue" in func name inside glue package - paths: - include: - - internal/service/glue - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Glue" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: glue-in-test-name - languages: - - go - message: Include "Glue" in test name - paths: - include: - - internal/service/glue/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccGlue" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: glue-in-const-name - languages: - - go - message: Do not use "Glue" in const name inside glue package - paths: - include: - - internal/service/glue - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Glue" - severity: WARNING - - id: glue-in-var-name - languages: - - go - message: Do not use "Glue" in var name inside glue package - paths: - include: - - internal/service/glue - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Glue" - severity: WARNING - - id: grafana-in-func-name - languages: - - go - message: Do not use "Grafana" in func name inside grafana package - paths: - include: - - internal/service/grafana - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Grafana" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: grafana-in-test-name - languages: - - go - message: Include "Grafana" in test name - paths: - include: - - internal/service/grafana/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccGrafana" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: grafana-in-const-name - languages: - - go - message: Do not use "Grafana" in const name inside grafana package - paths: - include: - - internal/service/grafana - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Grafana" - severity: WARNING - - id: grafana-in-var-name - languages: - - go - message: Do not use "Grafana" in var name inside grafana package - paths: - include: - - internal/service/grafana - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Grafana" - severity: WARNING - - id: greengrass-in-func-name - languages: - - go - message: Do not use "Greengrass" in func name inside greengrass package - paths: - include: - - internal/service/greengrass - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Greengrass" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: greengrass-in-test-name - languages: - - go - message: Include "Greengrass" in test name - paths: - include: - - internal/service/greengrass/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccGreengrass" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: greengrass-in-const-name - languages: - - go - message: Do not use "Greengrass" in const name inside greengrass package - paths: - include: - - internal/service/greengrass - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Greengrass" - severity: WARNING - - id: greengrass-in-var-name - languages: - - go - message: Do not use "Greengrass" in var name inside greengrass package - paths: - include: - - internal/service/greengrass - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Greengrass" - severity: WARNING - - id: guardduty-in-func-name - languages: - - go - message: Do not use "GuardDuty" in func name inside guardduty package - paths: - include: - - internal/service/guardduty - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)GuardDuty" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: guardduty-in-test-name - languages: - - go - message: Include "GuardDuty" in test name - paths: - include: - - internal/service/guardduty/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccGuardDuty" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: guardduty-in-const-name - languages: - - go - message: Do not use "GuardDuty" in const name inside guardduty package - paths: - include: - - internal/service/guardduty - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)GuardDuty" - severity: WARNING - - id: guardduty-in-var-name - languages: - - go - message: Do not use "GuardDuty" in var name inside guardduty package - paths: - include: - - internal/service/guardduty - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)GuardDuty" - severity: WARNING - - id: iam-in-func-name - languages: - - go - message: Do not use "IAM" in func name inside iam package - paths: - include: - - internal/service/iam - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IAM" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: iam-in-test-name - languages: - - go - message: Include "IAM" in test name - paths: - include: - - internal/service/iam/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccIAM" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: iam-in-const-name - languages: - - go - message: Do not use "IAM" in const name inside iam package - paths: - include: - - internal/service/iam - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IAM" - severity: WARNING - - id: iam-in-var-name - languages: - - go - message: Do not use "IAM" in var name inside iam package - paths: - include: - - internal/service/iam - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IAM" - severity: WARNING - - id: identitystore-in-func-name - languages: - - go - message: Do not use "IdentityStore" in func name inside identitystore package - paths: - include: - - internal/service/identitystore - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IdentityStore" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: identitystore-in-test-name - languages: - - go - message: Include "IdentityStore" in test name - paths: - include: - - internal/service/identitystore/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccIdentityStore" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: identitystore-in-const-name - languages: - - go - message: Do not use "IdentityStore" in const name inside identitystore package - paths: - include: - - internal/service/identitystore - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IdentityStore" - severity: WARNING - - id: identitystore-in-var-name - languages: - - go - message: Do not use "IdentityStore" in var name inside identitystore package - paths: - include: - - internal/service/identitystore - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IdentityStore" - severity: WARNING - - id: imagebuilder-in-func-name - languages: - - go - message: Do not use "ImageBuilder" in func name inside imagebuilder package - paths: - include: - - internal/service/imagebuilder - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ImageBuilder" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: imagebuilder-in-test-name - languages: - - go - message: Include "ImageBuilder" in test name - paths: - include: - - internal/service/imagebuilder/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccImageBuilder" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: imagebuilder-in-const-name - languages: - - go - message: Do not use "ImageBuilder" in const name inside imagebuilder package - paths: - include: - - internal/service/imagebuilder - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ImageBuilder" - severity: WARNING - - id: imagebuilder-in-var-name - languages: - - go - message: Do not use "ImageBuilder" in var name inside imagebuilder package - paths: - include: - - internal/service/imagebuilder - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ImageBuilder" - severity: WARNING - - id: inspector-in-func-name - languages: - - go - message: Do not use "Inspector" in func name inside inspector package - paths: - include: - - internal/service/inspector - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Inspector" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: inspector-in-test-name - languages: - - go - message: Include "Inspector" in test name - paths: - include: - - internal/service/inspector/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccInspector" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: inspector-in-const-name - languages: - - go - message: Do not use "Inspector" in const name inside inspector package - paths: - include: - - internal/service/inspector - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Inspector" - severity: WARNING - - id: inspector-in-var-name - languages: - - go - message: Do not use "Inspector" in var name inside inspector package - paths: - include: - - internal/service/inspector - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Inspector" - severity: WARNING - - id: iot-in-func-name - languages: - - go - message: Do not use "IoT" in func name inside iot package - paths: - include: - - internal/service/iot - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IoT" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: iot-in-test-name - languages: - - go - message: Include "IoT" in test name - paths: - include: - - internal/service/iot/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccIoT" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: iot-in-const-name - languages: - - go - message: Do not use "IoT" in const name inside iot package - paths: - include: - - internal/service/iot - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IoT" - severity: WARNING - - id: iot-in-var-name - languages: - - go - message: Do not use "IoT" in var name inside iot package - paths: - include: - - internal/service/iot - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IoT" - severity: WARNING - - id: iotanalytics-in-func-name - languages: - - go - message: Do not use "IoTAnalytics" in func name inside iotanalytics package - paths: - include: - - internal/service/iotanalytics - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IoTAnalytics" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: iotanalytics-in-test-name - languages: - - go - message: Include "IoTAnalytics" in test name - paths: - include: - - internal/service/iotanalytics/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccIoTAnalytics" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: iotanalytics-in-const-name - languages: - - go - message: Do not use "IoTAnalytics" in const name inside iotanalytics package - paths: - include: - - internal/service/iotanalytics - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IoTAnalytics" - severity: WARNING - - id: iotanalytics-in-var-name - languages: - - go - message: Do not use "IoTAnalytics" in var name inside iotanalytics package - paths: - include: - - internal/service/iotanalytics - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IoTAnalytics" - severity: WARNING - - id: iotevents-in-func-name - languages: - - go - message: Do not use "IoTEvents" in func name inside iotevents package - paths: - include: - - internal/service/iotevents - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IoTEvents" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: iotevents-in-test-name - languages: - - go - message: Include "IoTEvents" in test name - paths: - include: - - internal/service/iotevents/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccIoTEvents" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: iotevents-in-const-name - languages: - - go - message: Do not use "IoTEvents" in const name inside iotevents package - paths: - include: - - internal/service/iotevents - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IoTEvents" - severity: WARNING - - id: iotevents-in-var-name - languages: - - go - message: Do not use "IoTEvents" in var name inside iotevents package - paths: - include: - - internal/service/iotevents - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)IoTEvents" - severity: WARNING - - id: ipam-in-test-name - languages: - - go - message: Include "IPAM" in test name - paths: - include: - - internal/service/ec2/ipam_*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccIPAM" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: kafka-in-func-name - languages: - - go - message: Do not use "Kafka" in func name inside kafka package - paths: - include: - - internal/service/kafka - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Kafka" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: kafka-in-test-name - languages: - - go - message: Include "Kafka" in test name - paths: - include: - - internal/service/kafka/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccKafka" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: kafka-in-const-name - languages: - - go - message: Do not use "Kafka" in const name inside kafka package - paths: - include: - - internal/service/kafka - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Kafka" - severity: WARNING - - id: kafka-in-var-name - languages: - - go - message: Do not use "Kafka" in var name inside kafka package - paths: - include: - - internal/service/kafka - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Kafka" - severity: WARNING - - id: kafkaconnect-in-func-name - languages: - - go - message: Do not use "KafkaConnect" in func name inside kafkaconnect package - paths: - include: - - internal/service/kafkaconnect - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KafkaConnect" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: kafkaconnect-in-test-name - languages: - - go - message: Include "KafkaConnect" in test name - paths: - include: - - internal/service/kafkaconnect/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccKafkaConnect" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: kafkaconnect-in-const-name - languages: - - go - message: Do not use "KafkaConnect" in const name inside kafkaconnect package - paths: - include: - - internal/service/kafkaconnect - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KafkaConnect" - severity: WARNING - - id: kafkaconnect-in-var-name - languages: - - go - message: Do not use "KafkaConnect" in var name inside kafkaconnect package - paths: - include: - - internal/service/kafkaconnect - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KafkaConnect" - severity: WARNING - - id: keyspaces-in-func-name - languages: - - go - message: Do not use "Keyspaces" in func name inside keyspaces package - paths: - include: - - internal/service/keyspaces - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Keyspaces" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: keyspaces-in-test-name - languages: - - go - message: Include "Keyspaces" in test name - paths: - include: - - internal/service/keyspaces/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccKeyspaces" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: keyspaces-in-const-name - languages: - - go - message: Do not use "Keyspaces" in const name inside keyspaces package - paths: - include: - - internal/service/keyspaces - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Keyspaces" - severity: WARNING - - id: keyspaces-in-var-name - languages: - - go - message: Do not use "Keyspaces" in var name inside keyspaces package - paths: - include: - - internal/service/keyspaces - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Keyspaces" - severity: WARNING - - id: kinesis-in-func-name - languages: - - go - message: Do not use "Kinesis" in func name inside kinesis package - paths: - include: - - internal/service/kinesis - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Kinesis" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: kinesis-in-test-name - languages: - - go - message: Include "Kinesis" in test name - paths: - include: - - internal/service/kinesis/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccKinesis" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: kinesis-in-const-name - languages: - - go - message: Do not use "Kinesis" in const name inside kinesis package - paths: - include: - - internal/service/kinesis - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Kinesis" - severity: WARNING - - id: kinesis-in-var-name - languages: - - go - message: Do not use "Kinesis" in var name inside kinesis package - paths: - include: - - internal/service/kinesis - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Kinesis" - severity: WARNING - - id: kinesisanalytics-in-func-name - languages: - - go - message: Do not use "KinesisAnalytics" in func name inside kinesisanalytics package - paths: - include: - - internal/service/kinesisanalytics - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KinesisAnalytics" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: kinesisanalytics-in-test-name - languages: - - go - message: Include "KinesisAnalytics" in test name - paths: - include: - - internal/service/kinesisanalytics/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccKinesisAnalytics" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: kinesisanalytics-in-const-name - languages: - - go - message: Do not use "KinesisAnalytics" in const name inside kinesisanalytics package - paths: - include: - - internal/service/kinesisanalytics - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KinesisAnalytics" - severity: WARNING - - id: kinesisanalytics-in-var-name - languages: - - go - message: Do not use "KinesisAnalytics" in var name inside kinesisanalytics package - paths: - include: - - internal/service/kinesisanalytics - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KinesisAnalytics" - severity: WARNING - - id: kinesisanalyticsv2-in-func-name - languages: - - go - message: Do not use "KinesisAnalyticsV2" in func name inside kinesisanalyticsv2 package - paths: - include: - - internal/service/kinesisanalyticsv2 - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KinesisAnalyticsV2" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: kinesisanalyticsv2-in-test-name - languages: - - go - message: Include "KinesisAnalyticsV2" in test name - paths: - include: - - internal/service/kinesisanalyticsv2/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccKinesisAnalyticsV2" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: kinesisanalyticsv2-in-const-name - languages: - - go - message: Do not use "KinesisAnalyticsV2" in const name inside kinesisanalyticsv2 package - paths: - include: - - internal/service/kinesisanalyticsv2 - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KinesisAnalyticsV2" - severity: WARNING - - id: kinesisanalyticsv2-in-var-name - languages: - - go - message: Do not use "KinesisAnalyticsV2" in var name inside kinesisanalyticsv2 package - paths: - include: - - internal/service/kinesisanalyticsv2 - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KinesisAnalyticsV2" - severity: WARNING - - id: kinesisvideo-in-func-name - languages: - - go - message: Do not use "KinesisVideo" in func name inside kinesisvideo package - paths: - include: - - internal/service/kinesisvideo - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KinesisVideo" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: kinesisvideo-in-test-name - languages: - - go - message: Include "KinesisVideo" in test name - paths: - include: - - internal/service/kinesisvideo/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccKinesisVideo" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: kinesisvideo-in-const-name - languages: - - go - message: Do not use "KinesisVideo" in const name inside kinesisvideo package - paths: - include: - - internal/service/kinesisvideo - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KinesisVideo" - severity: WARNING - - id: kinesisvideo-in-var-name - languages: - - go - message: Do not use "KinesisVideo" in var name inside kinesisvideo package - paths: - include: - - internal/service/kinesisvideo - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KinesisVideo" - severity: WARNING - - id: kms-in-func-name - languages: - - go - message: Do not use "KMS" in func name inside kms package - paths: - include: - - internal/service/kms - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KMS" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: kms-in-test-name - languages: - - go - message: Include "KMS" in test name - paths: - include: - - internal/service/kms/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccKMS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: kms-in-const-name - languages: - - go - message: Do not use "KMS" in const name inside kms package - paths: - include: - - internal/service/kms - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KMS" - severity: WARNING - - id: kms-in-var-name - languages: - - go - message: Do not use "KMS" in var name inside kms package - paths: - include: - - internal/service/kms - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)KMS" - severity: WARNING - - id: lakeformation-in-func-name - languages: - - go - message: Do not use "LakeFormation" in func name inside lakeformation package - paths: - include: - - internal/service/lakeformation - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)LakeFormation" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: lakeformation-in-test-name - languages: - - go - message: Include "LakeFormation" in test name - paths: - include: - - internal/service/lakeformation/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccLakeFormation" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: lakeformation-in-const-name - languages: - - go - message: Do not use "LakeFormation" in const name inside lakeformation package - paths: - include: - - internal/service/lakeformation - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)LakeFormation" - severity: WARNING - - id: lakeformation-in-var-name - languages: - - go - message: Do not use "LakeFormation" in var name inside lakeformation package - paths: - include: - - internal/service/lakeformation - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)LakeFormation" - severity: WARNING - - id: lambda-in-func-name - languages: - - go - message: Do not use "Lambda" in func name inside lambda package - paths: - include: - - internal/service/lambda - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Lambda" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: lambda-in-test-name - languages: - - go - message: Include "Lambda" in test name - paths: - include: - - internal/service/lambda/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccLambda" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: lambda-in-const-name - languages: - - go - message: Do not use "Lambda" in const name inside lambda package - paths: - include: - - internal/service/lambda - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Lambda" - severity: WARNING - - id: lambda-in-var-name - languages: - - go - message: Do not use "Lambda" in var name inside lambda package - paths: - include: - - internal/service/lambda - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Lambda" - severity: WARNING - - id: lex-in-func-name - languages: - - go - message: Do not use "lex" in func name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)lex" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: lex-in-const-name - languages: - - go - message: Do not use "lex" in const name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)lex" - severity: WARNING - - id: lex-in-var-name - languages: - - go - message: Do not use "lex" in var name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)lex" - severity: WARNING - - id: lexmodelbuilding-in-func-name - languages: - - go - message: Do not use "lexmodelbuilding" in func name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)lexmodelbuilding" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: lexmodelbuilding-in-const-name - languages: - - go - message: Do not use "lexmodelbuilding" in const name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)lexmodelbuilding" - severity: WARNING - - id: lexmodelbuilding-in-var-name - languages: - - go - message: Do not use "lexmodelbuilding" in var name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)lexmodelbuilding" - severity: WARNING - - id: lexmodelbuildingservice-in-func-name - languages: - - go - message: Do not use "lexmodelbuildingservice" in func name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)lexmodelbuildingservice" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: lexmodelbuildingservice-in-const-name - languages: - - go - message: Do not use "lexmodelbuildingservice" in const name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)lexmodelbuildingservice" - severity: WARNING - - id: lexmodelbuildingservice-in-var-name - languages: - - go - message: Do not use "lexmodelbuildingservice" in var name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)lexmodelbuildingservice" - severity: WARNING - - id: lexmodels-in-func-name - languages: - - go - message: Do not use "LexModels" in func name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)LexModels" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: lexmodels-in-test-name - languages: - - go - message: Include "LexModels" in test name - paths: - include: - - internal/service/lexmodels/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccLexModels" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: lexmodels-in-const-name - languages: - - go - message: Do not use "LexModels" in const name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)LexModels" - severity: WARNING - - id: lexmodels-in-var-name - languages: - - go - message: Do not use "LexModels" in var name inside lexmodels package - paths: - include: - - internal/service/lexmodels - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)LexModels" - severity: WARNING - - id: licensemanager-in-func-name - languages: - - go - message: Do not use "LicenseManager" in func name inside licensemanager package - paths: - include: - - internal/service/licensemanager - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)LicenseManager" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: licensemanager-in-test-name - languages: - - go - message: Include "LicenseManager" in test name - paths: - include: - - internal/service/licensemanager/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccLicenseManager" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: licensemanager-in-const-name - languages: - - go - message: Do not use "LicenseManager" in const name inside licensemanager package - paths: - include: - - internal/service/licensemanager - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)LicenseManager" - severity: WARNING - - id: licensemanager-in-var-name - languages: - - go - message: Do not use "LicenseManager" in var name inside licensemanager package - paths: - include: - - internal/service/licensemanager - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)LicenseManager" - severity: WARNING - - id: lightsail-in-func-name - languages: - - go - message: Do not use "Lightsail" in func name inside lightsail package - paths: - include: - - internal/service/lightsail - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Lightsail" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: lightsail-in-test-name - languages: - - go - message: Include "Lightsail" in test name - paths: - include: - - internal/service/lightsail/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccLightsail" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: lightsail-in-const-name - languages: - - go - message: Do not use "Lightsail" in const name inside lightsail package - paths: - include: - - internal/service/lightsail - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Lightsail" - severity: WARNING - - id: lightsail-in-var-name - languages: - - go - message: Do not use "Lightsail" in var name inside lightsail package - paths: - include: - - internal/service/lightsail - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Lightsail" - severity: WARNING - - id: location-in-func-name - languages: - - go - message: Do not use "Location" in func name inside location package - paths: - include: - - internal/service/location - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Location" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: location-in-test-name - languages: - - go - message: Include "Location" in test name - paths: - include: - - internal/service/location/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccLocation" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: location-in-const-name - languages: - - go - message: Do not use "Location" in const name inside location package - paths: - include: - - internal/service/location - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Location" - severity: WARNING - - id: location-in-var-name - languages: - - go - message: Do not use "Location" in var name inside location package - paths: - include: - - internal/service/location - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Location" - severity: WARNING - - id: locationservice-in-func-name - languages: - - go - message: Do not use "locationservice" in func name inside location package - paths: - include: - - internal/service/location - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)locationservice" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: locationservice-in-const-name - languages: - - go - message: Do not use "locationservice" in const name inside location package - paths: - include: - - internal/service/location - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)locationservice" - severity: WARNING - - id: locationservice-in-var-name - languages: - - go - message: Do not use "locationservice" in var name inside location package - paths: - include: - - internal/service/location - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)locationservice" - severity: WARNING - - id: logs-in-func-name - languages: - - go - message: Do not use "Logs" in func name inside logs package - paths: - include: - - internal/service/logs - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Logs" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: logs-in-test-name - languages: - - go - message: Include "Logs" in test name - paths: - include: - - internal/service/logs/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccLogs" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: logs-in-const-name - languages: - - go - message: Do not use "Logs" in const name inside logs package - paths: - include: - - internal/service/logs - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Logs" - severity: WARNING - - id: logs-in-var-name - languages: - - go - message: Do not use "Logs" in var name inside logs package - paths: - include: - - internal/service/logs - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Logs" - severity: WARNING - - id: macie-in-func-name - languages: - - go - message: Do not use "Macie" in func name inside macie package - paths: - include: - - internal/service/macie - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Macie" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: macie-in-test-name - languages: - - go - message: Include "Macie" in test name - paths: - include: - - internal/service/macie/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMacie" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: macie-in-const-name - languages: - - go - message: Do not use "Macie" in const name inside macie package - paths: - include: - - internal/service/macie - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Macie" - severity: WARNING - - id: macie-in-var-name - languages: - - go - message: Do not use "Macie" in var name inside macie package - paths: - include: - - internal/service/macie - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Macie" - severity: WARNING - - id: macie2-in-func-name - languages: - - go - message: Do not use "Macie2" in func name inside macie2 package - paths: - include: - - internal/service/macie2 - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Macie2" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: macie2-in-test-name - languages: - - go - message: Include "Macie2" in test name - paths: - include: - - internal/service/macie2/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMacie2" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: macie2-in-const-name - languages: - - go - message: Do not use "Macie2" in const name inside macie2 package - paths: - include: - - internal/service/macie2 - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Macie2" - severity: WARNING - - id: macie2-in-var-name - languages: - - go - message: Do not use "Macie2" in var name inside macie2 package - paths: - include: - - internal/service/macie2 - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Macie2" - severity: WARNING - - id: managedgrafana-in-func-name - languages: - - go - message: Do not use "managedgrafana" in func name inside grafana package - paths: - include: - - internal/service/grafana - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)managedgrafana" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: managedgrafana-in-const-name - languages: - - go - message: Do not use "managedgrafana" in const name inside grafana package - paths: - include: - - internal/service/grafana - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)managedgrafana" - severity: WARNING - - id: managedgrafana-in-var-name - languages: - - go - message: Do not use "managedgrafana" in var name inside grafana package - paths: - include: - - internal/service/grafana - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)managedgrafana" - severity: WARNING - - id: mediaconnect-in-func-name - languages: - - go - message: Do not use "MediaConnect" in func name inside mediaconnect package - paths: - include: - - internal/service/mediaconnect - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaConnect" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: mediaconnect-in-test-name - languages: - - go - message: Include "MediaConnect" in test name - paths: - include: - - internal/service/mediaconnect/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMediaConnect" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: mediaconnect-in-const-name - languages: - - go - message: Do not use "MediaConnect" in const name inside mediaconnect package - paths: - include: - - internal/service/mediaconnect - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaConnect" - severity: WARNING - - id: mediaconnect-in-var-name - languages: - - go - message: Do not use "MediaConnect" in var name inside mediaconnect package - paths: - include: - - internal/service/mediaconnect - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaConnect" - severity: WARNING - - id: mediaconvert-in-func-name - languages: - - go - message: Do not use "MediaConvert" in func name inside mediaconvert package - paths: - include: - - internal/service/mediaconvert - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaConvert" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: mediaconvert-in-test-name - languages: - - go - message: Include "MediaConvert" in test name - paths: - include: - - internal/service/mediaconvert/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMediaConvert" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: mediaconvert-in-const-name - languages: - - go - message: Do not use "MediaConvert" in const name inside mediaconvert package - paths: - include: - - internal/service/mediaconvert - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaConvert" - severity: WARNING - - id: mediaconvert-in-var-name - languages: - - go - message: Do not use "MediaConvert" in var name inside mediaconvert package - paths: - include: - - internal/service/mediaconvert - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaConvert" - severity: WARNING - - id: medialive-in-func-name - languages: - - go - message: Do not use "MediaLive" in func name inside medialive package - paths: - include: - - internal/service/medialive - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaLive" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: medialive-in-test-name - languages: - - go - message: Include "MediaLive" in test name - paths: - include: - - internal/service/medialive/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMediaLive" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: medialive-in-const-name - languages: - - go - message: Do not use "MediaLive" in const name inside medialive package - paths: - include: - - internal/service/medialive - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaLive" - severity: WARNING - - id: medialive-in-var-name - languages: - - go - message: Do not use "MediaLive" in var name inside medialive package - paths: - include: - - internal/service/medialive - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaLive" - severity: WARNING - - id: mediapackage-in-func-name - languages: - - go - message: Do not use "MediaPackage" in func name inside mediapackage package - paths: - include: - - internal/service/mediapackage - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaPackage" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: mediapackage-in-test-name - languages: - - go - message: Include "MediaPackage" in test name - paths: - include: - - internal/service/mediapackage/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMediaPackage" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: mediapackage-in-const-name - languages: - - go - message: Do not use "MediaPackage" in const name inside mediapackage package - paths: - include: - - internal/service/mediapackage - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaPackage" - severity: WARNING - - id: mediapackage-in-var-name - languages: - - go - message: Do not use "MediaPackage" in var name inside mediapackage package - paths: - include: - - internal/service/mediapackage - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaPackage" - severity: WARNING - - id: mediastore-in-func-name - languages: - - go - message: Do not use "MediaStore" in func name inside mediastore package - paths: - include: - - internal/service/mediastore - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaStore" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: mediastore-in-test-name - languages: - - go - message: Include "MediaStore" in test name - paths: - include: - - internal/service/mediastore/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMediaStore" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: mediastore-in-const-name - languages: - - go - message: Do not use "MediaStore" in const name inside mediastore package - paths: - include: - - internal/service/mediastore - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaStore" - severity: WARNING - - id: mediastore-in-var-name - languages: - - go - message: Do not use "MediaStore" in var name inside mediastore package - paths: - include: - - internal/service/mediastore - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MediaStore" - severity: WARNING - - id: memorydb-in-func-name - languages: - - go - message: Do not use "MemoryDB" in func name inside memorydb package - paths: - include: - - internal/service/memorydb - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MemoryDB" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: memorydb-in-test-name - languages: - - go - message: Include "MemoryDB" in test name - paths: - include: - - internal/service/memorydb/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMemoryDB" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: memorydb-in-const-name - languages: - - go - message: Do not use "MemoryDB" in const name inside memorydb package - paths: - include: - - internal/service/memorydb - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MemoryDB" - severity: WARNING - - id: memorydb-in-var-name - languages: - - go - message: Do not use "MemoryDB" in var name inside memorydb package - paths: - include: - - internal/service/memorydb - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MemoryDB" - severity: WARNING - - id: meta-in-func-name - languages: - - go - message: Do not use "Meta" in func name inside meta package - paths: - include: - - internal/service/meta - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Meta" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: meta-in-test-name - languages: - - go - message: Include "Meta" in test name - paths: - include: - - internal/service/meta/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMeta" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: meta-in-const-name - languages: - - go - message: Do not use "Meta" in const name inside meta package - paths: - include: - - internal/service/meta - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Meta" - severity: WARNING - - id: meta-in-var-name - languages: - - go - message: Do not use "Meta" in var name inside meta package - paths: - include: - - internal/service/meta - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Meta" - severity: WARNING - - id: mq-in-func-name - languages: - - go - message: Do not use "MQ" in func name inside mq package - paths: - include: - - internal/service/mq - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MQ" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: mq-in-test-name - languages: - - go - message: Include "MQ" in test name - paths: - include: - - internal/service/mq/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMQ" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: mq-in-const-name - languages: - - go - message: Do not use "MQ" in const name inside mq package - paths: - include: - - internal/service/mq - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MQ" - severity: WARNING - - id: mq-in-var-name - languages: - - go - message: Do not use "MQ" in var name inside mq package - paths: - include: - - internal/service/mq - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MQ" - severity: WARNING - - id: mwaa-in-func-name - languages: - - go - message: Do not use "MWAA" in func name inside mwaa package - paths: - include: - - internal/service/mwaa - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MWAA" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: mwaa-in-test-name - languages: - - go - message: Include "MWAA" in test name - paths: - include: - - internal/service/mwaa/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccMWAA" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: mwaa-in-const-name - languages: - - go - message: Do not use "MWAA" in const name inside mwaa package - paths: - include: - - internal/service/mwaa - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MWAA" - severity: WARNING - - id: mwaa-in-var-name - languages: - - go - message: Do not use "MWAA" in var name inside mwaa package - paths: - include: - - internal/service/mwaa - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)MWAA" - severity: WARNING - - id: neptune-in-func-name - languages: - - go - message: Do not use "Neptune" in func name inside neptune package - paths: - include: - - internal/service/neptune - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Neptune" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: neptune-in-test-name - languages: - - go - message: Include "Neptune" in test name - paths: - include: - - internal/service/neptune/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccNeptune" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: neptune-in-const-name - languages: - - go - message: Do not use "Neptune" in const name inside neptune package - paths: - include: - - internal/service/neptune - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Neptune" - severity: WARNING - - id: neptune-in-var-name - languages: - - go - message: Do not use "Neptune" in var name inside neptune package - paths: - include: - - internal/service/neptune - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Neptune" - severity: WARNING - - id: networkfirewall-in-func-name - languages: - - go - message: Do not use "NetworkFirewall" in func name inside networkfirewall package - paths: - include: - - internal/service/networkfirewall - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)NetworkFirewall" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: networkfirewall-in-test-name - languages: - - go - message: Include "NetworkFirewall" in test name - paths: - include: - - internal/service/networkfirewall/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccNetworkFirewall" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: networkfirewall-in-const-name - languages: - - go - message: Do not use "NetworkFirewall" in const name inside networkfirewall package - paths: - include: - - internal/service/networkfirewall - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)NetworkFirewall" - severity: WARNING - - id: networkfirewall-in-var-name - languages: - - go - message: Do not use "NetworkFirewall" in var name inside networkfirewall package - paths: - include: - - internal/service/networkfirewall - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)NetworkFirewall" - severity: WARNING - - id: networkmanager-in-func-name - languages: - - go - message: Do not use "NetworkManager" in func name inside networkmanager package - paths: - include: - - internal/service/networkmanager - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)NetworkManager" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: networkmanager-in-test-name - languages: - - go - message: Include "NetworkManager" in test name - paths: - include: - - internal/service/networkmanager/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccNetworkManager" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: networkmanager-in-const-name - languages: - - go - message: Do not use "NetworkManager" in const name inside networkmanager package - paths: - include: - - internal/service/networkmanager - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)NetworkManager" - severity: WARNING - - id: networkmanager-in-var-name - languages: - - go - message: Do not use "NetworkManager" in var name inside networkmanager package - paths: - include: - - internal/service/networkmanager - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)NetworkManager" - severity: WARNING - - id: opensearch-in-func-name - languages: - - go - message: Do not use "OpenSearch" in func name inside opensearch package - paths: - include: - - internal/service/opensearch - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)OpenSearch" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: opensearch-in-test-name - languages: - - go - message: Include "OpenSearch" in test name - paths: - include: - - internal/service/opensearch/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccOpenSearch" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: opensearch-in-const-name - languages: - - go - message: Do not use "OpenSearch" in const name inside opensearch package - paths: - include: - - internal/service/opensearch - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)OpenSearch" - severity: WARNING - - id: opensearch-in-var-name - languages: - - go - message: Do not use "OpenSearch" in var name inside opensearch package - paths: - include: - - internal/service/opensearch - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)OpenSearch" - severity: WARNING - - id: opensearchservice-in-func-name - languages: - - go - message: Do not use "opensearchservice" in func name inside opensearch package - paths: - include: - - internal/service/opensearch - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)opensearchservice" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: opensearchservice-in-const-name - languages: - - go - message: Do not use "opensearchservice" in const name inside opensearch package - paths: - include: - - internal/service/opensearch - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)opensearchservice" - severity: WARNING - - id: opensearchservice-in-var-name - languages: - - go - message: Do not use "opensearchservice" in var name inside opensearch package - paths: - include: - - internal/service/opensearch - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)opensearchservice" - severity: WARNING - - id: opsworks-in-func-name - languages: - - go - message: Do not use "OpsWorks" in func name inside opsworks package - paths: - include: - - internal/service/opsworks - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)OpsWorks" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: opsworks-in-test-name - languages: - - go - message: Include "OpsWorks" in test name - paths: - include: - - internal/service/opsworks/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccOpsWorks" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: opsworks-in-const-name - languages: - - go - message: Do not use "OpsWorks" in const name inside opsworks package - paths: - include: - - internal/service/opsworks - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)OpsWorks" - severity: WARNING - - id: opsworks-in-var-name - languages: - - go - message: Do not use "OpsWorks" in var name inside opsworks package - paths: - include: - - internal/service/opsworks - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)OpsWorks" - severity: WARNING - - id: organizations-in-func-name - languages: - - go - message: Do not use "Organizations" in func name inside organizations package - paths: - include: - - internal/service/organizations - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Organizations" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: organizations-in-test-name - languages: - - go - message: Include "Organizations" in test name - paths: - include: - - internal/service/organizations/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccOrganizations" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: organizations-in-const-name - languages: - - go - message: Do not use "Organizations" in const name inside organizations package - paths: - include: - - internal/service/organizations - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Organizations" - severity: WARNING - - id: organizations-in-var-name - languages: - - go - message: Do not use "Organizations" in var name inside organizations package - paths: - include: - - internal/service/organizations - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Organizations" - severity: WARNING - - id: outposts-in-func-name - languages: - - go - message: Do not use "Outposts" in func name inside outposts package - paths: - include: - - internal/service/outposts - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Outposts" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: outposts-in-test-name - languages: - - go - message: Include "Outposts" in test name - paths: - include: - - internal/service/outposts/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccOutposts" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: outposts-in-const-name - languages: - - go - message: Do not use "Outposts" in const name inside outposts package - paths: - include: - - internal/service/outposts - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Outposts" - severity: WARNING - - id: outposts-in-var-name - languages: - - go - message: Do not use "Outposts" in var name inside outposts package - paths: - include: - - internal/service/outposts - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Outposts" - severity: WARNING - - id: pinpoint-in-func-name - languages: - - go - message: Do not use "Pinpoint" in func name inside pinpoint package - paths: - include: - - internal/service/pinpoint - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Pinpoint" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: pinpoint-in-test-name - languages: - - go - message: Include "Pinpoint" in test name - paths: - include: - - internal/service/pinpoint/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccPinpoint" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: pinpoint-in-const-name - languages: - - go - message: Do not use "Pinpoint" in const name inside pinpoint package - paths: - include: - - internal/service/pinpoint - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Pinpoint" - severity: WARNING - - id: pinpoint-in-var-name - languages: - - go - message: Do not use "Pinpoint" in var name inside pinpoint package - paths: - include: - - internal/service/pinpoint - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Pinpoint" - severity: WARNING - - id: pricing-in-func-name - languages: - - go - message: Do not use "Pricing" in func name inside pricing package - paths: - include: - - internal/service/pricing - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Pricing" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: pricing-in-test-name - languages: - - go - message: Include "Pricing" in test name - paths: - include: - - internal/service/pricing/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccPricing" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: pricing-in-const-name - languages: - - go - message: Do not use "Pricing" in const name inside pricing package - paths: - include: - - internal/service/pricing - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Pricing" - severity: WARNING - - id: pricing-in-var-name - languages: - - go - message: Do not use "Pricing" in var name inside pricing package - paths: - include: - - internal/service/pricing - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Pricing" - severity: WARNING - - id: prometheus-in-func-name - languages: - - go - message: Do not use "prometheus" in func name inside amp package - paths: - include: - - internal/service/amp - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)prometheus" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: prometheus-in-const-name - languages: - - go - message: Do not use "prometheus" in const name inside amp package - paths: - include: - - internal/service/amp - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)prometheus" - severity: WARNING - - id: prometheus-in-var-name - languages: - - go - message: Do not use "prometheus" in var name inside amp package - paths: - include: - - internal/service/amp - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)prometheus" - severity: WARNING - - id: prometheusservice-in-func-name - languages: - - go - message: Do not use "prometheusservice" in func name inside amp package - paths: - include: - - internal/service/amp - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)prometheusservice" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: prometheusservice-in-const-name - languages: - - go - message: Do not use "prometheusservice" in const name inside amp package - paths: - include: - - internal/service/amp - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)prometheusservice" - severity: WARNING - - id: prometheusservice-in-var-name - languages: - - go - message: Do not use "prometheusservice" in var name inside amp package - paths: - include: - - internal/service/amp - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)prometheusservice" - severity: WARNING - - id: qldb-in-func-name - languages: - - go - message: Do not use "QLDB" in func name inside qldb package - paths: - include: - - internal/service/qldb - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)QLDB" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: qldb-in-test-name - languages: - - go - message: Include "QLDB" in test name - paths: - include: - - internal/service/qldb/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccQLDB" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: qldb-in-const-name - languages: - - go - message: Do not use "QLDB" in const name inside qldb package - paths: - include: - - internal/service/qldb - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)QLDB" - severity: WARNING - - id: qldb-in-var-name - languages: - - go - message: Do not use "QLDB" in var name inside qldb package - paths: - include: - - internal/service/qldb - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)QLDB" - severity: WARNING - - id: quicksight-in-func-name - languages: - - go - message: Do not use "QuickSight" in func name inside quicksight package - paths: - include: - - internal/service/quicksight - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)QuickSight" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: quicksight-in-test-name - languages: - - go - message: Include "QuickSight" in test name - paths: - include: - - internal/service/quicksight/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccQuickSight" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: quicksight-in-const-name - languages: - - go - message: Do not use "QuickSight" in const name inside quicksight package - paths: - include: - - internal/service/quicksight - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)QuickSight" - severity: WARNING - - id: quicksight-in-var-name - languages: - - go - message: Do not use "QuickSight" in var name inside quicksight package - paths: - include: - - internal/service/quicksight - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)QuickSight" - severity: WARNING - - id: ram-in-func-name - languages: - - go - message: Do not use "RAM" in func name inside ram package - paths: - include: - - internal/service/ram - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)RAM" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: ram-in-test-name - languages: - - go - message: Include "RAM" in test name - paths: - include: - - internal/service/ram/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccRAM" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ram-in-const-name - languages: - - go - message: Do not use "RAM" in const name inside ram package - paths: - include: - - internal/service/ram - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)RAM" - severity: WARNING - - id: ram-in-var-name - languages: - - go - message: Do not use "RAM" in var name inside ram package - paths: - include: - - internal/service/ram - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)RAM" - severity: WARNING - - id: rds-in-func-name - languages: - - go - message: Do not use "RDS" in func name inside rds package - paths: - include: - - internal/service/rds - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)RDS" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: rds-in-test-name - languages: - - go - message: Include "RDS" in test name - paths: - include: - - internal/service/rds/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccRDS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: rds-in-const-name - languages: - - go - message: Do not use "RDS" in const name inside rds package - paths: - include: - - internal/service/rds - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)RDS" - severity: WARNING - - id: rds-in-var-name - languages: - - go - message: Do not use "RDS" in var name inside rds package - paths: - include: - - internal/service/rds - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)RDS" - severity: WARNING - - id: redshift-in-func-name - languages: - - go - message: Do not use "Redshift" in func name inside redshift package - paths: - include: - - internal/service/redshift - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Redshift" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: redshift-in-test-name - languages: - - go - message: Include "Redshift" in test name - paths: - include: - - internal/service/redshift/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccRedshift" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: redshift-in-const-name - languages: - - go - message: Do not use "Redshift" in const name inside redshift package - paths: - include: - - internal/service/redshift - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Redshift" - severity: WARNING - - id: redshift-in-var-name - languages: - - go - message: Do not use "Redshift" in var name inside redshift package - paths: - include: - - internal/service/redshift - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Redshift" - severity: WARNING - - id: resourcegroups-in-func-name - languages: - - go - message: Do not use "ResourceGroups" in func name inside resourcegroups package - paths: - include: - - internal/service/resourcegroups - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ResourceGroups" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: resourcegroups-in-test-name - languages: - - go - message: Include "ResourceGroups" in test name - paths: - include: - - internal/service/resourcegroups/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccResourceGroups" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: resourcegroups-in-const-name - languages: - - go - message: Do not use "ResourceGroups" in const name inside resourcegroups package - paths: - include: - - internal/service/resourcegroups - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ResourceGroups" - severity: WARNING - - id: resourcegroups-in-var-name - languages: - - go - message: Do not use "ResourceGroups" in var name inside resourcegroups package - paths: - include: - - internal/service/resourcegroups - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ResourceGroups" - severity: WARNING - - id: resourcegroupstagging-in-func-name - languages: - - go - message: Do not use "resourcegroupstagging" in func name inside resourcegroupstaggingapi package - paths: - include: - - internal/service/resourcegroupstaggingapi - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)resourcegroupstagging" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: resourcegroupstagging-in-const-name - languages: - - go - message: Do not use "resourcegroupstagging" in const name inside resourcegroupstaggingapi package - paths: - include: - - internal/service/resourcegroupstaggingapi - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)resourcegroupstagging" - severity: WARNING - - id: resourcegroupstagging-in-var-name - languages: - - go - message: Do not use "resourcegroupstagging" in var name inside resourcegroupstaggingapi package - paths: - include: - - internal/service/resourcegroupstaggingapi - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)resourcegroupstagging" - severity: WARNING - - id: resourcegroupstaggingapi-in-func-name - languages: - - go - message: Do not use "ResourceGroupsTaggingAPI" in func name inside resourcegroupstaggingapi package - paths: - include: - - internal/service/resourcegroupstaggingapi - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ResourceGroupsTaggingAPI" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: resourcegroupstaggingapi-in-test-name - languages: - - go - message: Include "ResourceGroupsTaggingAPI" in test name - paths: - include: - - internal/service/resourcegroupstaggingapi/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccResourceGroupsTaggingAPI" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: resourcegroupstaggingapi-in-const-name - languages: - - go - message: Do not use "ResourceGroupsTaggingAPI" in const name inside resourcegroupstaggingapi package - paths: - include: - - internal/service/resourcegroupstaggingapi - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ResourceGroupsTaggingAPI" - severity: WARNING - - id: resourcegroupstaggingapi-in-var-name - languages: - - go - message: Do not use "ResourceGroupsTaggingAPI" in var name inside resourcegroupstaggingapi package - paths: - include: - - internal/service/resourcegroupstaggingapi - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ResourceGroupsTaggingAPI" - severity: WARNING - - id: route53-in-func-name - languages: - - go - message: Do not use "Route53" in func name inside route53 package - paths: - include: - - internal/service/route53 - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: route53-in-test-name - languages: - - go - message: Include "Route53" in test name - paths: - include: - - internal/service/route53/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccRoute53" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: route53-in-const-name - languages: - - go - message: Do not use "Route53" in const name inside route53 package - paths: - include: - - internal/service/route53 - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53" - severity: WARNING - - id: route53-in-var-name - languages: - - go - message: Do not use "Route53" in var name inside route53 package - paths: - include: - - internal/service/route53 - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53" - severity: WARNING - - id: route53domains-in-func-name - languages: - - go - message: Do not use "Route53Domains" in func name inside route53domains package - paths: - include: - - internal/service/route53domains - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53Domains" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: route53domains-in-test-name - languages: - - go - message: Include "Route53Domains" in test name - paths: - include: - - internal/service/route53domains/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccRoute53Domains" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: route53domains-in-const-name - languages: - - go - message: Do not use "Route53Domains" in const name inside route53domains package - paths: - include: - - internal/service/route53domains - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53Domains" - severity: WARNING - - id: route53domains-in-var-name - languages: - - go - message: Do not use "Route53Domains" in var name inside route53domains package - paths: - include: - - internal/service/route53domains - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53Domains" - severity: WARNING - - id: route53recoverycontrolconfig-in-func-name - languages: - - go - message: Do not use "Route53RecoveryControlConfig" in func name inside route53recoverycontrolconfig package - paths: - include: - - internal/service/route53recoverycontrolconfig - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53RecoveryControlConfig" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: route53recoverycontrolconfig-in-test-name - languages: - - go - message: Include "Route53RecoveryControlConfig" in test name - paths: - include: - - internal/service/route53recoverycontrolconfig/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccRoute53RecoveryControlConfig" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: route53recoverycontrolconfig-in-const-name - languages: - - go - message: Do not use "Route53RecoveryControlConfig" in const name inside route53recoverycontrolconfig package - paths: - include: - - internal/service/route53recoverycontrolconfig - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53RecoveryControlConfig" - severity: WARNING - - id: route53recoverycontrolconfig-in-var-name - languages: - - go - message: Do not use "Route53RecoveryControlConfig" in var name inside route53recoverycontrolconfig package - paths: - include: - - internal/service/route53recoverycontrolconfig - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53RecoveryControlConfig" - severity: WARNING - - id: route53recoveryreadiness-in-func-name - languages: - - go - message: Do not use "Route53RecoveryReadiness" in func name inside route53recoveryreadiness package - paths: - include: - - internal/service/route53recoveryreadiness - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53RecoveryReadiness" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: route53recoveryreadiness-in-test-name - languages: - - go - message: Include "Route53RecoveryReadiness" in test name - paths: - include: - - internal/service/route53recoveryreadiness/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccRoute53RecoveryReadiness" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: route53recoveryreadiness-in-const-name - languages: - - go - message: Do not use "Route53RecoveryReadiness" in const name inside route53recoveryreadiness package - paths: - include: - - internal/service/route53recoveryreadiness - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53RecoveryReadiness" - severity: WARNING - - id: route53recoveryreadiness-in-var-name - languages: - - go - message: Do not use "Route53RecoveryReadiness" in var name inside route53recoveryreadiness package - paths: - include: - - internal/service/route53recoveryreadiness - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53RecoveryReadiness" - severity: WARNING - - id: route53resolver-in-func-name - languages: - - go - message: Do not use "Route53Resolver" in func name inside route53resolver package - paths: - include: - - internal/service/route53resolver - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53Resolver" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: route53resolver-in-test-name - languages: - - go - message: Include "Route53Resolver" in test name - paths: - include: - - internal/service/route53resolver/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccRoute53Resolver" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: route53resolver-in-const-name - languages: - - go - message: Do not use "Route53Resolver" in const name inside route53resolver package - paths: - include: - - internal/service/route53resolver - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53Resolver" - severity: WARNING - - id: route53resolver-in-var-name - languages: - - go - message: Do not use "Route53Resolver" in var name inside route53resolver package - paths: - include: - - internal/service/route53resolver - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Route53Resolver" - severity: WARNING - - id: s3-in-func-name - languages: - - go - message: Do not use "S3" in func name inside s3 package - paths: - include: - - internal/service/s3 - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)S3" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: s3-in-test-name - languages: - - go - message: Include "S3" in test name - paths: - include: - - internal/service/s3/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccS3" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: s3-in-const-name - languages: - - go - message: Do not use "S3" in const name inside s3 package - paths: - include: - - internal/service/s3 - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)S3" - severity: WARNING - - id: s3-in-var-name - languages: - - go - message: Do not use "S3" in var name inside s3 package - paths: - include: - - internal/service/s3 - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)S3" - severity: WARNING - - id: s3api-in-func-name - languages: - - go - message: Do not use "s3api" in func name inside s3 package - paths: - include: - - internal/service/s3 - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)s3api" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: s3api-in-const-name - languages: - - go - message: Do not use "s3api" in const name inside s3 package - paths: - include: - - internal/service/s3 - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)s3api" - severity: WARNING - - id: s3api-in-var-name - languages: - - go - message: Do not use "s3api" in var name inside s3 package - paths: - include: - - internal/service/s3 - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)s3api" - severity: WARNING - - id: s3control-in-func-name - languages: - - go - message: Do not use "S3Control" in func name inside s3control package - paths: - include: - - internal/service/s3control - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)S3Control" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: s3control-in-test-name - languages: - - go - message: Include "S3Control" in test name - paths: - include: - - internal/service/s3control/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccS3Control" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: s3control-in-const-name - languages: - - go - message: Do not use "S3Control" in const name inside s3control package - paths: - include: - - internal/service/s3control - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)S3Control" - severity: WARNING - - id: s3control-in-var-name - languages: - - go - message: Do not use "S3Control" in var name inside s3control package - paths: - include: - - internal/service/s3control - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)S3Control" - severity: WARNING - - id: s3outposts-in-func-name - languages: - - go - message: Do not use "S3Outposts" in func name inside s3outposts package - paths: - include: - - internal/service/s3outposts - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)S3Outposts" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: s3outposts-in-test-name - languages: - - go - message: Include "S3Outposts" in test name - paths: - include: - - internal/service/s3outposts/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccS3Outposts" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: s3outposts-in-const-name - languages: - - go - message: Do not use "S3Outposts" in const name inside s3outposts package - paths: - include: - - internal/service/s3outposts - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)S3Outposts" - severity: WARNING - - id: s3outposts-in-var-name - languages: - - go - message: Do not use "S3Outposts" in var name inside s3outposts package - paths: - include: - - internal/service/s3outposts - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)S3Outposts" - severity: WARNING - - id: sagemaker-in-func-name - languages: - - go - message: Do not use "SageMaker" in func name inside sagemaker package - paths: - include: - - internal/service/sagemaker - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SageMaker" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: sagemaker-in-test-name - languages: - - go - message: Include "SageMaker" in test name - paths: - include: - - internal/service/sagemaker/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSageMaker" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: sagemaker-in-const-name - languages: - - go - message: Do not use "SageMaker" in const name inside sagemaker package - paths: - include: - - internal/service/sagemaker - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SageMaker" - severity: WARNING - - id: sagemaker-in-var-name - languages: - - go - message: Do not use "SageMaker" in var name inside sagemaker package - paths: - include: - - internal/service/sagemaker - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SageMaker" - severity: WARNING - - id: schemas-in-func-name - languages: - - go - message: Do not use "Schemas" in func name inside schemas package - paths: - include: - - internal/service/schemas - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Schemas" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: schemas-in-test-name - languages: - - go - message: Include "Schemas" in test name - paths: - include: - - internal/service/schemas/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSchemas" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: schemas-in-const-name - languages: - - go - message: Do not use "Schemas" in const name inside schemas package - paths: - include: - - internal/service/schemas - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Schemas" - severity: WARNING - - id: schemas-in-var-name - languages: - - go - message: Do not use "Schemas" in var name inside schemas package - paths: - include: - - internal/service/schemas - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Schemas" - severity: WARNING - - id: sdb-in-func-name - languages: - - go - message: Do not use "sdb" in func name inside simpledb package - paths: - include: - - internal/service/simpledb - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)sdb" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: sdb-in-const-name - languages: - - go - message: Do not use "sdb" in const name inside simpledb package - paths: - include: - - internal/service/simpledb - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)sdb" - severity: WARNING - - id: sdb-in-var-name - languages: - - go - message: Do not use "sdb" in var name inside simpledb package - paths: - include: - - internal/service/simpledb - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)sdb" - severity: WARNING - - id: secretsmanager-in-func-name - languages: - - go - message: Do not use "SecretsManager" in func name inside secretsmanager package - paths: - include: - - internal/service/secretsmanager - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SecretsManager" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: secretsmanager-in-test-name - languages: - - go - message: Include "SecretsManager" in test name - paths: - include: - - internal/service/secretsmanager/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSecretsManager" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: secretsmanager-in-const-name - languages: - - go - message: Do not use "SecretsManager" in const name inside secretsmanager package - paths: - include: - - internal/service/secretsmanager - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SecretsManager" - severity: WARNING - - id: secretsmanager-in-var-name - languages: - - go - message: Do not use "SecretsManager" in var name inside secretsmanager package - paths: - include: - - internal/service/secretsmanager - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SecretsManager" - severity: WARNING - - id: securityhub-in-func-name - languages: - - go - message: Do not use "SecurityHub" in func name inside securityhub package - paths: - include: - - internal/service/securityhub - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SecurityHub" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: securityhub-in-test-name - languages: - - go - message: Include "SecurityHub" in test name - paths: - include: - - internal/service/securityhub/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSecurityHub" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: securityhub-in-const-name - languages: - - go - message: Do not use "SecurityHub" in const name inside securityhub package - paths: - include: - - internal/service/securityhub - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SecurityHub" - severity: WARNING - - id: securityhub-in-var-name - languages: - - go - message: Do not use "SecurityHub" in var name inside securityhub package - paths: - include: - - internal/service/securityhub - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SecurityHub" - severity: WARNING - - id: serverlessapplicationrepository-in-func-name - languages: - - go - message: Do not use "serverlessapplicationrepository" in func name inside serverlessrepo package - paths: - include: - - internal/service/serverlessrepo - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)serverlessapplicationrepository" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: serverlessapplicationrepository-in-const-name - languages: - - go - message: Do not use "serverlessapplicationrepository" in const name inside serverlessrepo package - paths: - include: - - internal/service/serverlessrepo - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)serverlessapplicationrepository" - severity: WARNING - - id: serverlessapplicationrepository-in-var-name - languages: - - go - message: Do not use "serverlessapplicationrepository" in var name inside serverlessrepo package - paths: - include: - - internal/service/serverlessrepo - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)serverlessapplicationrepository" - severity: WARNING - - id: serverlessapprepo-in-func-name - languages: - - go - message: Do not use "serverlessapprepo" in func name inside serverlessrepo package - paths: - include: - - internal/service/serverlessrepo - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)serverlessapprepo" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: serverlessapprepo-in-const-name - languages: - - go - message: Do not use "serverlessapprepo" in const name inside serverlessrepo package - paths: - include: - - internal/service/serverlessrepo - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)serverlessapprepo" - severity: WARNING - - id: serverlessapprepo-in-var-name - languages: - - go - message: Do not use "serverlessapprepo" in var name inside serverlessrepo package - paths: - include: - - internal/service/serverlessrepo - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)serverlessapprepo" - severity: WARNING - - id: serverlessrepo-in-func-name - languages: - - go - message: Do not use "ServerlessRepo" in func name inside serverlessrepo package - paths: - include: - - internal/service/serverlessrepo - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServerlessRepo" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: serverlessrepo-in-test-name - languages: - - go - message: Include "ServerlessRepo" in test name - paths: - include: - - internal/service/serverlessrepo/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccServerlessRepo" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: serverlessrepo-in-const-name - languages: - - go - message: Do not use "ServerlessRepo" in const name inside serverlessrepo package - paths: - include: - - internal/service/serverlessrepo - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServerlessRepo" - severity: WARNING - - id: serverlessrepo-in-var-name - languages: - - go - message: Do not use "ServerlessRepo" in var name inside serverlessrepo package - paths: - include: - - internal/service/serverlessrepo - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServerlessRepo" - severity: WARNING - - id: servicecatalog-in-func-name - languages: - - go - message: Do not use "ServiceCatalog" in func name inside servicecatalog package - paths: - include: - - internal/service/servicecatalog - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServiceCatalog" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: servicecatalog-in-test-name - languages: - - go - message: Include "ServiceCatalog" in test name - paths: - include: - - internal/service/servicecatalog/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccServiceCatalog" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: servicecatalog-in-const-name - languages: - - go - message: Do not use "ServiceCatalog" in const name inside servicecatalog package - paths: - include: - - internal/service/servicecatalog - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServiceCatalog" - severity: WARNING - - id: servicecatalog-in-var-name - languages: - - go - message: Do not use "ServiceCatalog" in var name inside servicecatalog package - paths: - include: - - internal/service/servicecatalog - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServiceCatalog" - severity: WARNING - - id: servicediscovery-in-func-name - languages: - - go - message: Do not use "ServiceDiscovery" in func name inside servicediscovery package - paths: - include: - - internal/service/servicediscovery - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServiceDiscovery" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: servicediscovery-in-test-name - languages: - - go - message: Include "ServiceDiscovery" in test name - paths: - include: - - internal/service/servicediscovery/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccServiceDiscovery" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: servicediscovery-in-const-name - languages: - - go - message: Do not use "ServiceDiscovery" in const name inside servicediscovery package - paths: - include: - - internal/service/servicediscovery - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServiceDiscovery" - severity: WARNING - - id: servicediscovery-in-var-name - languages: - - go - message: Do not use "ServiceDiscovery" in var name inside servicediscovery package - paths: - include: - - internal/service/servicediscovery - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServiceDiscovery" - severity: WARNING - - id: servicequotas-in-func-name - languages: - - go - message: Do not use "ServiceQuotas" in func name inside servicequotas package - paths: - include: - - internal/service/servicequotas - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServiceQuotas" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: servicequotas-in-test-name - languages: - - go - message: Include "ServiceQuotas" in test name - paths: - include: - - internal/service/servicequotas/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccServiceQuotas" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: servicequotas-in-const-name - languages: - - go - message: Do not use "ServiceQuotas" in const name inside servicequotas package - paths: - include: - - internal/service/servicequotas - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServiceQuotas" - severity: WARNING - - id: servicequotas-in-var-name - languages: - - go - message: Do not use "ServiceQuotas" in var name inside servicequotas package - paths: - include: - - internal/service/servicequotas - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)ServiceQuotas" - severity: WARNING - - id: ses-in-func-name - languages: - - go - message: Do not use "SES" in func name inside ses package - paths: - include: - - internal/service/ses - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SES" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: ses-in-test-name - languages: - - go - message: Include "SES" in test name - paths: - include: - - internal/service/ses/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSES" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ses-in-const-name - languages: - - go - message: Do not use "SES" in const name inside ses package - paths: - include: - - internal/service/ses - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SES" - severity: WARNING - - id: ses-in-var-name - languages: - - go - message: Do not use "SES" in var name inside ses package - paths: - include: - - internal/service/ses - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SES" - severity: WARNING - - id: sfn-in-func-name - languages: - - go - message: Do not use "SFN" in func name inside sfn package - paths: - include: - - internal/service/sfn - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SFN" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: sfn-in-test-name - languages: - - go - message: Include "SFN" in test name - paths: - include: - - internal/service/sfn/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSFN" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: sfn-in-const-name - languages: - - go - message: Do not use "SFN" in const name inside sfn package - paths: - include: - - internal/service/sfn - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SFN" - severity: WARNING - - id: sfn-in-var-name - languages: - - go - message: Do not use "SFN" in var name inside sfn package - paths: - include: - - internal/service/sfn - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SFN" - severity: WARNING - - id: shield-in-func-name - languages: - - go - message: Do not use "Shield" in func name inside shield package - paths: - include: - - internal/service/shield - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Shield" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: shield-in-test-name - languages: - - go - message: Include "Shield" in test name - paths: - include: - - internal/service/shield/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccShield" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: shield-in-const-name - languages: - - go - message: Do not use "Shield" in const name inside shield package - paths: - include: - - internal/service/shield - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Shield" - severity: WARNING - - id: shield-in-var-name - languages: - - go - message: Do not use "Shield" in var name inside shield package - paths: - include: - - internal/service/shield - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Shield" - severity: WARNING - - id: signer-in-func-name - languages: - - go - message: Do not use "Signer" in func name inside signer package - paths: - include: - - internal/service/signer - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Signer" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: signer-in-test-name - languages: - - go - message: Include "Signer" in test name - paths: - include: - - internal/service/signer/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSigner" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: signer-in-const-name - languages: - - go - message: Do not use "Signer" in const name inside signer package - paths: - include: - - internal/service/signer - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Signer" - severity: WARNING - - id: signer-in-var-name - languages: - - go - message: Do not use "Signer" in var name inside signer package - paths: - include: - - internal/service/signer - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Signer" - severity: WARNING - - id: simpledb-in-func-name - languages: - - go - message: Do not use "SimpleDB" in func name inside simpledb package - paths: - include: - - internal/service/simpledb - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SimpleDB" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: simpledb-in-test-name - languages: - - go - message: Include "SimpleDB" in test name - paths: - include: - - internal/service/simpledb/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSimpleDB" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: simpledb-in-const-name - languages: - - go - message: Do not use "SimpleDB" in const name inside simpledb package - paths: - include: - - internal/service/simpledb - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SimpleDB" - severity: WARNING - - id: simpledb-in-var-name - languages: - - go - message: Do not use "SimpleDB" in var name inside simpledb package - paths: - include: - - internal/service/simpledb - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SimpleDB" - severity: WARNING - - id: sns-in-func-name - languages: - - go - message: Do not use "SNS" in func name inside sns package - paths: - include: - - internal/service/sns - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SNS" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: sns-in-test-name - languages: - - go - message: Include "SNS" in test name - paths: - include: - - internal/service/sns/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSNS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: sns-in-const-name - languages: - - go - message: Do not use "SNS" in const name inside sns package - paths: - include: - - internal/service/sns - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SNS" - severity: WARNING - - id: sns-in-var-name - languages: - - go - message: Do not use "SNS" in var name inside sns package - paths: - include: - - internal/service/sns - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SNS" - severity: WARNING - - id: sqs-in-func-name - languages: - - go - message: Do not use "SQS" in func name inside sqs package - paths: - include: - - internal/service/sqs - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SQS" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: sqs-in-test-name - languages: - - go - message: Include "SQS" in test name - paths: - include: - - internal/service/sqs/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSQS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: sqs-in-const-name - languages: - - go - message: Do not use "SQS" in const name inside sqs package - paths: - include: - - internal/service/sqs - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SQS" - severity: WARNING - - id: sqs-in-var-name - languages: - - go - message: Do not use "SQS" in var name inside sqs package - paths: - include: - - internal/service/sqs - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SQS" - severity: WARNING - - id: ssm-in-func-name - languages: - - go - message: Do not use "SSM" in func name inside ssm package - paths: - include: - - internal/service/ssm - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SSM" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: ssm-in-test-name - languages: - - go - message: Include "SSM" in test name - paths: - include: - - internal/service/ssm/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSSM" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ssm-in-const-name - languages: - - go - message: Do not use "SSM" in const name inside ssm package - paths: - include: - - internal/service/ssm - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SSM" - severity: WARNING - - id: ssm-in-var-name - languages: - - go - message: Do not use "SSM" in var name inside ssm package - paths: - include: - - internal/service/ssm - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SSM" - severity: WARNING - - id: ssoadmin-in-func-name - languages: - - go - message: Do not use "SSOAdmin" in func name inside ssoadmin package - paths: - include: - - internal/service/ssoadmin - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SSOAdmin" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: ssoadmin-in-test-name - languages: - - go - message: Include "SSOAdmin" in test name - paths: - include: - - internal/service/ssoadmin/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSSOAdmin" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: ssoadmin-in-const-name - languages: - - go - message: Do not use "SSOAdmin" in const name inside ssoadmin package - paths: - include: - - internal/service/ssoadmin - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SSOAdmin" - severity: WARNING - - id: ssoadmin-in-var-name - languages: - - go - message: Do not use "SSOAdmin" in var name inside ssoadmin package - paths: - include: - - internal/service/ssoadmin - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SSOAdmin" - severity: WARNING - - id: stepfunctions-in-func-name - languages: - - go - message: Do not use "stepfunctions" in func name inside sfn package - paths: - include: - - internal/service/sfn - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)stepfunctions" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: stepfunctions-in-const-name - languages: - - go - message: Do not use "stepfunctions" in const name inside sfn package - paths: - include: - - internal/service/sfn - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)stepfunctions" - severity: WARNING - - id: stepfunctions-in-var-name - languages: - - go - message: Do not use "stepfunctions" in var name inside sfn package - paths: - include: - - internal/service/sfn - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)stepfunctions" - severity: WARNING - - id: storagegateway-in-func-name - languages: - - go - message: Do not use "StorageGateway" in func name inside storagegateway package - paths: - include: - - internal/service/storagegateway - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)StorageGateway" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: storagegateway-in-test-name - languages: - - go - message: Include "StorageGateway" in test name - paths: - include: - - internal/service/storagegateway/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccStorageGateway" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: storagegateway-in-const-name - languages: - - go - message: Do not use "StorageGateway" in const name inside storagegateway package - paths: - include: - - internal/service/storagegateway - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)StorageGateway" - severity: WARNING - - id: storagegateway-in-var-name - languages: - - go - message: Do not use "StorageGateway" in var name inside storagegateway package - paths: - include: - - internal/service/storagegateway - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)StorageGateway" - severity: WARNING - - id: sts-in-func-name - languages: - - go - message: Do not use "STS" in func name inside sts package - paths: - include: - - internal/service/sts - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)STS" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: sts-in-test-name - languages: - - go - message: Include "STS" in test name - paths: - include: - - internal/service/sts/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSTS" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: sts-in-const-name - languages: - - go - message: Do not use "STS" in const name inside sts package - paths: - include: - - internal/service/sts - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)STS" - severity: WARNING - - id: sts-in-var-name - languages: - - go - message: Do not use "STS" in var name inside sts package - paths: - include: - - internal/service/sts - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)STS" - severity: WARNING - - id: swf-in-func-name - languages: - - go - message: Do not use "SWF" in func name inside swf package - paths: - include: - - internal/service/swf - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SWF" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: swf-in-test-name - languages: - - go - message: Include "SWF" in test name - paths: - include: - - internal/service/swf/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSWF" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: swf-in-const-name - languages: - - go - message: Do not use "SWF" in const name inside swf package - paths: - include: - - internal/service/swf - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SWF" - severity: WARNING - - id: swf-in-var-name - languages: - - go - message: Do not use "SWF" in var name inside swf package - paths: - include: - - internal/service/swf - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)SWF" - severity: WARNING - - id: synthetics-in-func-name - languages: - - go - message: Do not use "Synthetics" in func name inside synthetics package - paths: - include: - - internal/service/synthetics - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Synthetics" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: synthetics-in-test-name - languages: - - go - message: Include "Synthetics" in test name - paths: - include: - - internal/service/synthetics/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSynthetics" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: synthetics-in-const-name - languages: - - go - message: Do not use "Synthetics" in const name inside synthetics package - paths: - include: - - internal/service/synthetics - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Synthetics" - severity: WARNING - - id: synthetics-in-var-name - languages: - - go - message: Do not use "Synthetics" in var name inside synthetics package - paths: - include: - - internal/service/synthetics - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Synthetics" - severity: WARNING - - id: timestreamwrite-in-func-name - languages: - - go - message: Do not use "TimestreamWrite" in func name inside timestreamwrite package - paths: - include: - - internal/service/timestreamwrite - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)TimestreamWrite" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: timestreamwrite-in-test-name - languages: - - go - message: Include "TimestreamWrite" in test name - paths: - include: - - internal/service/timestreamwrite/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccTimestreamWrite" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: timestreamwrite-in-const-name - languages: - - go - message: Do not use "TimestreamWrite" in const name inside timestreamwrite package - paths: - include: - - internal/service/timestreamwrite - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)TimestreamWrite" - severity: WARNING - - id: timestreamwrite-in-var-name - languages: - - go - message: Do not use "TimestreamWrite" in var name inside timestreamwrite package - paths: - include: - - internal/service/timestreamwrite - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)TimestreamWrite" - severity: WARNING - - id: transfer-in-func-name - languages: - - go - message: Do not use "Transfer" in func name inside transfer package - paths: - include: - - internal/service/transfer - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Transfer" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: transfer-in-test-name - languages: - - go - message: Include "Transfer" in test name - paths: - include: - - internal/service/transfer/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccTransfer" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: transfer-in-const-name - languages: - - go - message: Do not use "Transfer" in const name inside transfer package - paths: - include: - - internal/service/transfer - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Transfer" - severity: WARNING - - id: transfer-in-var-name - languages: - - go - message: Do not use "Transfer" in var name inside transfer package - paths: - include: - - internal/service/transfer - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)Transfer" - severity: WARNING - - id: transitgateway-in-test-name - languages: - - go - message: Include "TransitGateway" in test name - paths: - include: - - internal/service/ec2/transitgateway_*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccTransitGateway" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: vpc-in-test-name - languages: - - go - message: Include "VPC" in test name - paths: - include: - - internal/service/ec2/vpc_*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccVPC" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: vpnclient-in-test-name - languages: - - go - message: Include "ClientVPN" in test name - paths: - include: - - internal/service/ec2/vpnclient_*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccClientVPN" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: vpnsite-in-test-name - languages: - - go - message: Include "SiteVPN" in test name - paths: - include: - - internal/service/ec2/vpnsite_*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccSiteVPN" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: waf-in-func-name - languages: - - go - message: Do not use "WAF" in func name inside waf package - paths: - include: - - internal/service/waf - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WAF" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: waf-in-test-name - languages: - - go - message: Include "WAF" in test name - paths: - include: - - internal/service/waf/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccWAF" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: waf-in-const-name - languages: - - go - message: Do not use "WAF" in const name inside waf package - paths: - include: - - internal/service/waf - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WAF" - severity: WARNING - - id: waf-in-var-name - languages: - - go - message: Do not use "WAF" in var name inside waf package - paths: - include: - - internal/service/waf - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WAF" - severity: WARNING - - id: wafregional-in-func-name - languages: - - go - message: Do not use "WAFRegional" in func name inside wafregional package - paths: - include: - - internal/service/wafregional - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WAFRegional" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: wafregional-in-test-name - languages: - - go - message: Include "WAFRegional" in test name - paths: - include: - - internal/service/wafregional/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccWAFRegional" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: wafregional-in-const-name - languages: - - go - message: Do not use "WAFRegional" in const name inside wafregional package - paths: - include: - - internal/service/wafregional - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WAFRegional" - severity: WARNING - - id: wafregional-in-var-name - languages: - - go - message: Do not use "WAFRegional" in var name inside wafregional package - paths: - include: - - internal/service/wafregional - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WAFRegional" - severity: WARNING - - id: wafv2-in-func-name - languages: - - go - message: Do not use "WAFV2" in func name inside wafv2 package - paths: - include: - - internal/service/wafv2 - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WAFV2" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: wafv2-in-test-name - languages: - - go - message: Include "WAFV2" in test name - paths: - include: - - internal/service/wafv2/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccWAFV2" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: wafv2-in-const-name - languages: - - go - message: Do not use "WAFV2" in const name inside wafv2 package - paths: - include: - - internal/service/wafv2 - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WAFV2" - severity: WARNING - - id: wafv2-in-var-name - languages: - - go - message: Do not use "WAFV2" in var name inside wafv2 package - paths: - include: - - internal/service/wafv2 - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WAFV2" - severity: WARNING - - id: wavelength-in-test-name - languages: - - go - message: Include "Wavelength" in test name - paths: - include: - - internal/service/ec2/wavelength_*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccWavelength" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: worklink-in-func-name - languages: - - go - message: Do not use "WorkLink" in func name inside worklink package - paths: - include: - - internal/service/worklink - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WorkLink" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: worklink-in-test-name - languages: - - go - message: Include "WorkLink" in test name - paths: - include: - - internal/service/worklink/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccWorkLink" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: worklink-in-const-name - languages: - - go - message: Do not use "WorkLink" in const name inside worklink package - paths: - include: - - internal/service/worklink - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WorkLink" - severity: WARNING - - id: worklink-in-var-name - languages: - - go - message: Do not use "WorkLink" in var name inside worklink package - paths: - include: - - internal/service/worklink - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WorkLink" - severity: WARNING - - id: workspaces-in-func-name - languages: - - go - message: Do not use "WorkSpaces" in func name inside workspaces package - paths: - include: - - internal/service/workspaces - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WorkSpaces" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: workspaces-in-test-name - languages: - - go - message: Include "WorkSpaces" in test name - paths: - include: - - internal/service/workspaces/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccWorkSpaces" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: workspaces-in-const-name - languages: - - go - message: Do not use "WorkSpaces" in const name inside workspaces package - paths: - include: - - internal/service/workspaces - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WorkSpaces" - severity: WARNING - - id: workspaces-in-var-name - languages: - - go - message: Do not use "WorkSpaces" in var name inside workspaces package - paths: - include: - - internal/service/workspaces - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)WorkSpaces" - severity: WARNING - - id: xray-in-func-name - languages: - - go - message: Do not use "XRay" in func name inside xray package - paths: - include: - - internal/service/xray - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)XRay" - - pattern-not-regex: ^TestAcc.* - severity: WARNING - - id: xray-in-test-name - languages: - - go - message: Include "XRay" in test name - paths: - include: - - internal/service/xray/*_test.go - patterns: - - pattern: func $NAME( ... ) { ... } - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-not-regex: "^TestAccXRay" - - pattern-regex: ^TestAcc.* - severity: WARNING - - id: xray-in-const-name - languages: - - go - message: Do not use "XRay" in const name inside xray package - paths: - include: - - internal/service/xray - patterns: - - pattern: const $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)XRay" - severity: WARNING - - id: xray-in-var-name - languages: - - go - message: Do not use "XRay" in var name inside xray package - paths: - include: - - internal/service/xray - patterns: - - pattern: var $NAME = ... - - metavariable-pattern: - metavariable: $NAME - patterns: - - pattern-regex: "(?i)XRay" - severity: WARNING diff --git a/.semgrep-service-name0.yml b/.semgrep-service-name0.yml new file mode 100644 index 00000000000..71fe5037752 --- /dev/null +++ b/.semgrep-service-name0.yml @@ -0,0 +1,2913 @@ +# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. +rules: + - id: accessanalyzer-in-func-name + languages: + - go + message: Do not use "AccessAnalyzer" in func name inside accessanalyzer package + paths: + include: + - internal/service/accessanalyzer + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AccessAnalyzer" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: accessanalyzer-in-test-name + languages: + - go + message: Include "AccessAnalyzer" in test name + paths: + include: + - internal/service/accessanalyzer/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAccessAnalyzer" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: accessanalyzer-in-const-name + languages: + - go + message: Do not use "AccessAnalyzer" in const name inside accessanalyzer package + paths: + include: + - internal/service/accessanalyzer + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AccessAnalyzer" + severity: WARNING + - id: accessanalyzer-in-var-name + languages: + - go + message: Do not use "AccessAnalyzer" in var name inside accessanalyzer package + paths: + include: + - internal/service/accessanalyzer + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AccessAnalyzer" + severity: WARNING + - id: account-in-func-name + languages: + - go + message: Do not use "Account" in func name inside account package + paths: + include: + - internal/service/account + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Account" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: account-in-test-name + languages: + - go + message: Include "Account" in test name + paths: + include: + - internal/service/account/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAccount" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: account-in-const-name + languages: + - go + message: Do not use "Account" in const name inside account package + paths: + include: + - internal/service/account + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Account" + severity: WARNING + - id: account-in-var-name + languages: + - go + message: Do not use "Account" in var name inside account package + paths: + include: + - internal/service/account + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Account" + severity: WARNING + - id: acm-in-func-name + languages: + - go + message: Do not use "ACM" in func name inside acm package + paths: + include: + - internal/service/acm + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ACM" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: acm-in-test-name + languages: + - go + message: Include "ACM" in test name + paths: + include: + - internal/service/acm/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccACM" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: acm-in-const-name + languages: + - go + message: Do not use "ACM" in const name inside acm package + paths: + include: + - internal/service/acm + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ACM" + severity: WARNING + - id: acm-in-var-name + languages: + - go + message: Do not use "ACM" in var name inside acm package + paths: + include: + - internal/service/acm + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ACM" + severity: WARNING + - id: acmpca-in-func-name + languages: + - go + message: Do not use "ACMPCA" in func name inside acmpca package + paths: + include: + - internal/service/acmpca + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ACMPCA" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: acmpca-in-test-name + languages: + - go + message: Include "ACMPCA" in test name + paths: + include: + - internal/service/acmpca/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccACMPCA" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: acmpca-in-const-name + languages: + - go + message: Do not use "ACMPCA" in const name inside acmpca package + paths: + include: + - internal/service/acmpca + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ACMPCA" + severity: WARNING + - id: acmpca-in-var-name + languages: + - go + message: Do not use "ACMPCA" in var name inside acmpca package + paths: + include: + - internal/service/acmpca + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ACMPCA" + severity: WARNING + - id: amg-in-func-name + languages: + - go + message: Do not use "amg" in func name inside grafana package + paths: + include: + - internal/service/grafana + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)amg" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: amg-in-const-name + languages: + - go + message: Do not use "amg" in const name inside grafana package + paths: + include: + - internal/service/grafana + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)amg" + severity: WARNING + - id: amg-in-var-name + languages: + - go + message: Do not use "amg" in var name inside grafana package + paths: + include: + - internal/service/grafana + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)amg" + severity: WARNING + - id: amp-in-func-name + languages: + - go + message: Do not use "AMP" in func name inside amp package + paths: + include: + - internal/service/amp + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AMP" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: amp-in-test-name + languages: + - go + message: Include "AMP" in test name + paths: + include: + - internal/service/amp/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAMP" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: amp-in-const-name + languages: + - go + message: Do not use "AMP" in const name inside amp package + paths: + include: + - internal/service/amp + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AMP" + severity: WARNING + - id: amp-in-var-name + languages: + - go + message: Do not use "AMP" in var name inside amp package + paths: + include: + - internal/service/amp + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AMP" + severity: WARNING + - id: amplify-in-func-name + languages: + - go + message: Do not use "Amplify" in func name inside amplify package + paths: + include: + - internal/service/amplify + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Amplify" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: amplify-in-test-name + languages: + - go + message: Include "Amplify" in test name + paths: + include: + - internal/service/amplify/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAmplify" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: amplify-in-const-name + languages: + - go + message: Do not use "Amplify" in const name inside amplify package + paths: + include: + - internal/service/amplify + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Amplify" + severity: WARNING + - id: amplify-in-var-name + languages: + - go + message: Do not use "Amplify" in var name inside amplify package + paths: + include: + - internal/service/amplify + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Amplify" + severity: WARNING + - id: apigateway-in-func-name + languages: + - go + message: Do not use "APIGateway" in func name inside apigateway package + paths: + include: + - internal/service/apigateway + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)APIGateway" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: apigateway-in-test-name + languages: + - go + message: Include "APIGateway" in test name + paths: + include: + - internal/service/apigateway/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAPIGateway" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: apigateway-in-const-name + languages: + - go + message: Do not use "APIGateway" in const name inside apigateway package + paths: + include: + - internal/service/apigateway + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)APIGateway" + severity: WARNING + - id: apigateway-in-var-name + languages: + - go + message: Do not use "APIGateway" in var name inside apigateway package + paths: + include: + - internal/service/apigateway + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)APIGateway" + severity: WARNING + - id: apigatewayv2-in-func-name + languages: + - go + message: Do not use "APIGatewayV2" in func name inside apigatewayv2 package + paths: + include: + - internal/service/apigatewayv2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)APIGatewayV2" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: apigatewayv2-in-test-name + languages: + - go + message: Include "APIGatewayV2" in test name + paths: + include: + - internal/service/apigatewayv2/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAPIGatewayV2" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: apigatewayv2-in-const-name + languages: + - go + message: Do not use "APIGatewayV2" in const name inside apigatewayv2 package + paths: + include: + - internal/service/apigatewayv2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)APIGatewayV2" + severity: WARNING + - id: apigatewayv2-in-var-name + languages: + - go + message: Do not use "APIGatewayV2" in var name inside apigatewayv2 package + paths: + include: + - internal/service/apigatewayv2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)APIGatewayV2" + severity: WARNING + - id: appautoscaling-in-func-name + languages: + - go + message: Do not use "AppAutoScaling" in func name inside appautoscaling package + paths: + include: + - internal/service/appautoscaling + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppAutoScaling" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: appautoscaling-in-test-name + languages: + - go + message: Include "AppAutoScaling" in test name + paths: + include: + - internal/service/appautoscaling/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAppAutoScaling" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: appautoscaling-in-const-name + languages: + - go + message: Do not use "AppAutoScaling" in const name inside appautoscaling package + paths: + include: + - internal/service/appautoscaling + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppAutoScaling" + severity: WARNING + - id: appautoscaling-in-var-name + languages: + - go + message: Do not use "AppAutoScaling" in var name inside appautoscaling package + paths: + include: + - internal/service/appautoscaling + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppAutoScaling" + severity: WARNING + - id: appconfig-in-func-name + languages: + - go + message: Do not use "AppConfig" in func name inside appconfig package + paths: + include: + - internal/service/appconfig + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppConfig" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: appconfig-in-test-name + languages: + - go + message: Include "AppConfig" in test name + paths: + include: + - internal/service/appconfig/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAppConfig" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: appconfig-in-const-name + languages: + - go + message: Do not use "AppConfig" in const name inside appconfig package + paths: + include: + - internal/service/appconfig + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppConfig" + severity: WARNING + - id: appconfig-in-var-name + languages: + - go + message: Do not use "AppConfig" in var name inside appconfig package + paths: + include: + - internal/service/appconfig + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppConfig" + severity: WARNING + - id: appflow-in-func-name + languages: + - go + message: Do not use "AppFlow" in func name inside appflow package + paths: + include: + - internal/service/appflow + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppFlow" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: appflow-in-test-name + languages: + - go + message: Include "AppFlow" in test name + paths: + include: + - internal/service/appflow/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAppFlow" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: appflow-in-const-name + languages: + - go + message: Do not use "AppFlow" in const name inside appflow package + paths: + include: + - internal/service/appflow + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppFlow" + severity: WARNING + - id: appflow-in-var-name + languages: + - go + message: Do not use "AppFlow" in var name inside appflow package + paths: + include: + - internal/service/appflow + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppFlow" + severity: WARNING + - id: appintegrations-in-func-name + languages: + - go + message: Do not use "AppIntegrations" in func name inside appintegrations package + paths: + include: + - internal/service/appintegrations + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppIntegrations" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: appintegrations-in-test-name + languages: + - go + message: Include "AppIntegrations" in test name + paths: + include: + - internal/service/appintegrations/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAppIntegrations" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: appintegrations-in-const-name + languages: + - go + message: Do not use "AppIntegrations" in const name inside appintegrations package + paths: + include: + - internal/service/appintegrations + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppIntegrations" + severity: WARNING + - id: appintegrations-in-var-name + languages: + - go + message: Do not use "AppIntegrations" in var name inside appintegrations package + paths: + include: + - internal/service/appintegrations + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppIntegrations" + severity: WARNING + - id: appintegrationsservice-in-func-name + languages: + - go + message: Do not use "appintegrationsservice" in func name inside appintegrations package + paths: + include: + - internal/service/appintegrations + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)appintegrationsservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: appintegrationsservice-in-const-name + languages: + - go + message: Do not use "appintegrationsservice" in const name inside appintegrations package + paths: + include: + - internal/service/appintegrations + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)appintegrationsservice" + severity: WARNING + - id: appintegrationsservice-in-var-name + languages: + - go + message: Do not use "appintegrationsservice" in var name inside appintegrations package + paths: + include: + - internal/service/appintegrations + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)appintegrationsservice" + severity: WARNING + - id: applicationautoscaling-in-func-name + languages: + - go + message: Do not use "applicationautoscaling" in func name inside appautoscaling package + paths: + include: + - internal/service/appautoscaling + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)applicationautoscaling" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: applicationautoscaling-in-const-name + languages: + - go + message: Do not use "applicationautoscaling" in const name inside appautoscaling package + paths: + include: + - internal/service/appautoscaling + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)applicationautoscaling" + severity: WARNING + - id: applicationautoscaling-in-var-name + languages: + - go + message: Do not use "applicationautoscaling" in var name inside appautoscaling package + paths: + include: + - internal/service/appautoscaling + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)applicationautoscaling" + severity: WARNING + - id: applicationinsights-in-func-name + languages: + - go + message: Do not use "ApplicationInsights" in func name inside applicationinsights package + paths: + include: + - internal/service/applicationinsights + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ApplicationInsights" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: applicationinsights-in-test-name + languages: + - go + message: Include "ApplicationInsights" in test name + paths: + include: + - internal/service/applicationinsights/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccApplicationInsights" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: applicationinsights-in-const-name + languages: + - go + message: Do not use "ApplicationInsights" in const name inside applicationinsights package + paths: + include: + - internal/service/applicationinsights + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ApplicationInsights" + severity: WARNING + - id: applicationinsights-in-var-name + languages: + - go + message: Do not use "ApplicationInsights" in var name inside applicationinsights package + paths: + include: + - internal/service/applicationinsights + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ApplicationInsights" + severity: WARNING + - id: appmesh-in-func-name + languages: + - go + message: Do not use "AppMesh" in func name inside appmesh package + paths: + include: + - internal/service/appmesh + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppMesh" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: appmesh-in-test-name + languages: + - go + message: Include "AppMesh" in test name + paths: + include: + - internal/service/appmesh/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAppMesh" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: appmesh-in-const-name + languages: + - go + message: Do not use "AppMesh" in const name inside appmesh package + paths: + include: + - internal/service/appmesh + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppMesh" + severity: WARNING + - id: appmesh-in-var-name + languages: + - go + message: Do not use "AppMesh" in var name inside appmesh package + paths: + include: + - internal/service/appmesh + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppMesh" + severity: WARNING + - id: apprunner-in-func-name + languages: + - go + message: Do not use "AppRunner" in func name inside apprunner package + paths: + include: + - internal/service/apprunner + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppRunner" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: apprunner-in-test-name + languages: + - go + message: Include "AppRunner" in test name + paths: + include: + - internal/service/apprunner/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAppRunner" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: apprunner-in-const-name + languages: + - go + message: Do not use "AppRunner" in const name inside apprunner package + paths: + include: + - internal/service/apprunner + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppRunner" + severity: WARNING + - id: apprunner-in-var-name + languages: + - go + message: Do not use "AppRunner" in var name inside apprunner package + paths: + include: + - internal/service/apprunner + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppRunner" + severity: WARNING + - id: appstream-in-func-name + languages: + - go + message: Do not use "AppStream" in func name inside appstream package + paths: + include: + - internal/service/appstream + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppStream" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: appstream-in-test-name + languages: + - go + message: Include "AppStream" in test name + paths: + include: + - internal/service/appstream/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAppStream" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: appstream-in-const-name + languages: + - go + message: Do not use "AppStream" in const name inside appstream package + paths: + include: + - internal/service/appstream + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppStream" + severity: WARNING + - id: appstream-in-var-name + languages: + - go + message: Do not use "AppStream" in var name inside appstream package + paths: + include: + - internal/service/appstream + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppStream" + severity: WARNING + - id: appsync-in-func-name + languages: + - go + message: Do not use "AppSync" in func name inside appsync package + paths: + include: + - internal/service/appsync + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppSync" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: appsync-in-test-name + languages: + - go + message: Include "AppSync" in test name + paths: + include: + - internal/service/appsync/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAppSync" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: appsync-in-const-name + languages: + - go + message: Do not use "AppSync" in const name inside appsync package + paths: + include: + - internal/service/appsync + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppSync" + severity: WARNING + - id: appsync-in-var-name + languages: + - go + message: Do not use "AppSync" in var name inside appsync package + paths: + include: + - internal/service/appsync + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AppSync" + severity: WARNING + - id: athena-in-func-name + languages: + - go + message: Do not use "Athena" in func name inside athena package + paths: + include: + - internal/service/athena + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Athena" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: athena-in-test-name + languages: + - go + message: Include "Athena" in test name + paths: + include: + - internal/service/athena/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAthena" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: athena-in-const-name + languages: + - go + message: Do not use "Athena" in const name inside athena package + paths: + include: + - internal/service/athena + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Athena" + severity: WARNING + - id: athena-in-var-name + languages: + - go + message: Do not use "Athena" in var name inside athena package + paths: + include: + - internal/service/athena + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Athena" + severity: WARNING + - id: autoscaling-in-func-name + languages: + - go + message: Do not use "AutoScaling" in func name inside autoscaling package + paths: + include: + - internal/service/autoscaling + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AutoScaling" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: autoscaling-in-test-name + languages: + - go + message: Include "AutoScaling" in test name + paths: + include: + - internal/service/autoscaling/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAutoScaling" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: autoscaling-in-const-name + languages: + - go + message: Do not use "AutoScaling" in const name inside autoscaling package + paths: + include: + - internal/service/autoscaling + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AutoScaling" + severity: WARNING + - id: autoscaling-in-var-name + languages: + - go + message: Do not use "AutoScaling" in var name inside autoscaling package + paths: + include: + - internal/service/autoscaling + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AutoScaling" + severity: WARNING + - id: autoscalingplans-in-func-name + languages: + - go + message: Do not use "AutoScalingPlans" in func name inside autoscalingplans package + paths: + include: + - internal/service/autoscalingplans + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AutoScalingPlans" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: autoscalingplans-in-test-name + languages: + - go + message: Include "AutoScalingPlans" in test name + paths: + include: + - internal/service/autoscalingplans/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccAutoScalingPlans" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: autoscalingplans-in-const-name + languages: + - go + message: Do not use "AutoScalingPlans" in const name inside autoscalingplans package + paths: + include: + - internal/service/autoscalingplans + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AutoScalingPlans" + severity: WARNING + - id: autoscalingplans-in-var-name + languages: + - go + message: Do not use "AutoScalingPlans" in var name inside autoscalingplans package + paths: + include: + - internal/service/autoscalingplans + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AutoScalingPlans" + severity: WARNING + - id: backup-in-func-name + languages: + - go + message: Do not use "Backup" in func name inside backup package + paths: + include: + - internal/service/backup + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Backup" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: backup-in-test-name + languages: + - go + message: Include "Backup" in test name + paths: + include: + - internal/service/backup/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccBackup" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: backup-in-const-name + languages: + - go + message: Do not use "Backup" in const name inside backup package + paths: + include: + - internal/service/backup + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Backup" + severity: WARNING + - id: backup-in-var-name + languages: + - go + message: Do not use "Backup" in var name inside backup package + paths: + include: + - internal/service/backup + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Backup" + severity: WARNING + - id: batch-in-func-name + languages: + - go + message: Do not use "Batch" in func name inside batch package + paths: + include: + - internal/service/batch + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Batch" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: batch-in-test-name + languages: + - go + message: Include "Batch" in test name + paths: + include: + - internal/service/batch/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccBatch" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: batch-in-const-name + languages: + - go + message: Do not use "Batch" in const name inside batch package + paths: + include: + - internal/service/batch + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Batch" + severity: WARNING + - id: batch-in-var-name + languages: + - go + message: Do not use "Batch" in var name inside batch package + paths: + include: + - internal/service/batch + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Batch" + severity: WARNING + - id: beanstalk-in-func-name + languages: + - go + message: Do not use "beanstalk" in func name inside elasticbeanstalk package + paths: + include: + - internal/service/elasticbeanstalk + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)beanstalk" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: beanstalk-in-const-name + languages: + - go + message: Do not use "beanstalk" in const name inside elasticbeanstalk package + paths: + include: + - internal/service/elasticbeanstalk + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)beanstalk" + severity: WARNING + - id: beanstalk-in-var-name + languages: + - go + message: Do not use "beanstalk" in var name inside elasticbeanstalk package + paths: + include: + - internal/service/elasticbeanstalk + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)beanstalk" + severity: WARNING + - id: budgets-in-func-name + languages: + - go + message: Do not use "Budgets" in func name inside budgets package + paths: + include: + - internal/service/budgets + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Budgets" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: budgets-in-test-name + languages: + - go + message: Include "Budgets" in test name + paths: + include: + - internal/service/budgets/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccBudgets" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: budgets-in-const-name + languages: + - go + message: Do not use "Budgets" in const name inside budgets package + paths: + include: + - internal/service/budgets + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Budgets" + severity: WARNING + - id: budgets-in-var-name + languages: + - go + message: Do not use "Budgets" in var name inside budgets package + paths: + include: + - internal/service/budgets + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Budgets" + severity: WARNING + - id: ce-in-func-name + languages: + - go + message: Do not use "CE" in func name inside ce package + paths: + include: + - internal/service/ce + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CE" + - pattern-not-regex: ource + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ce-in-test-name + languages: + - go + message: Include "CE" in test name + paths: + include: + - internal/service/ce/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCE" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ce-in-const-name + languages: + - go + message: Do not use "CE" in const name inside ce package + paths: + include: + - internal/service/ce + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CE" + severity: WARNING + - id: ce-in-var-name + languages: + - go + message: Do not use "CE" in var name inside ce package + paths: + include: + - internal/service/ce + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CE" + severity: WARNING + - id: chime-in-func-name + languages: + - go + message: Do not use "Chime" in func name inside chime package + paths: + include: + - internal/service/chime + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Chime" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: chime-in-test-name + languages: + - go + message: Include "Chime" in test name + paths: + include: + - internal/service/chime/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccChime" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: chime-in-const-name + languages: + - go + message: Do not use "Chime" in const name inside chime package + paths: + include: + - internal/service/chime + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Chime" + severity: WARNING + - id: chime-in-var-name + languages: + - go + message: Do not use "Chime" in var name inside chime package + paths: + include: + - internal/service/chime + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Chime" + severity: WARNING + - id: cloud9-in-func-name + languages: + - go + message: Do not use "Cloud9" in func name inside cloud9 package + paths: + include: + - internal/service/cloud9 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Cloud9" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloud9-in-test-name + languages: + - go + message: Include "Cloud9" in test name + paths: + include: + - internal/service/cloud9/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCloud9" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cloud9-in-const-name + languages: + - go + message: Do not use "Cloud9" in const name inside cloud9 package + paths: + include: + - internal/service/cloud9 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Cloud9" + severity: WARNING + - id: cloud9-in-var-name + languages: + - go + message: Do not use "Cloud9" in var name inside cloud9 package + paths: + include: + - internal/service/cloud9 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Cloud9" + severity: WARNING + - id: cloudcontrol-in-func-name + languages: + - go + message: Do not use "CloudControl" in func name inside cloudcontrol package + paths: + include: + - internal/service/cloudcontrol + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudControl" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudcontrol-in-test-name + languages: + - go + message: Include "CloudControl" in test name + paths: + include: + - internal/service/cloudcontrol/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCloudControl" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cloudcontrol-in-const-name + languages: + - go + message: Do not use "CloudControl" in const name inside cloudcontrol package + paths: + include: + - internal/service/cloudcontrol + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudControl" + severity: WARNING + - id: cloudcontrol-in-var-name + languages: + - go + message: Do not use "CloudControl" in var name inside cloudcontrol package + paths: + include: + - internal/service/cloudcontrol + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudControl" + severity: WARNING + - id: cloudcontrolapi-in-func-name + languages: + - go + message: Do not use "cloudcontrolapi" in func name inside cloudcontrol package + paths: + include: + - internal/service/cloudcontrol + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudcontrolapi" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudcontrolapi-in-const-name + languages: + - go + message: Do not use "cloudcontrolapi" in const name inside cloudcontrol package + paths: + include: + - internal/service/cloudcontrol + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudcontrolapi" + severity: WARNING + - id: cloudcontrolapi-in-var-name + languages: + - go + message: Do not use "cloudcontrolapi" in var name inside cloudcontrol package + paths: + include: + - internal/service/cloudcontrol + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudcontrolapi" + severity: WARNING + - id: cloudformation-in-func-name + languages: + - go + message: Do not use "CloudFormation" in func name inside cloudformation package + paths: + include: + - internal/service/cloudformation + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudFormation" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudformation-in-test-name + languages: + - go + message: Include "CloudFormation" in test name + paths: + include: + - internal/service/cloudformation/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCloudFormation" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cloudformation-in-const-name + languages: + - go + message: Do not use "CloudFormation" in const name inside cloudformation package + paths: + include: + - internal/service/cloudformation + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudFormation" + severity: WARNING + - id: cloudformation-in-var-name + languages: + - go + message: Do not use "CloudFormation" in var name inside cloudformation package + paths: + include: + - internal/service/cloudformation + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudFormation" + severity: WARNING + - id: cloudfront-in-func-name + languages: + - go + message: Do not use "CloudFront" in func name inside cloudfront package + paths: + include: + - internal/service/cloudfront + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudFront" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudfront-in-test-name + languages: + - go + message: Include "CloudFront" in test name + paths: + include: + - internal/service/cloudfront/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCloudFront" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cloudfront-in-const-name + languages: + - go + message: Do not use "CloudFront" in const name inside cloudfront package + paths: + include: + - internal/service/cloudfront + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudFront" + severity: WARNING + - id: cloudfront-in-var-name + languages: + - go + message: Do not use "CloudFront" in var name inside cloudfront package + paths: + include: + - internal/service/cloudfront + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudFront" + severity: WARNING + - id: cloudhsm-in-func-name + languages: + - go + message: Do not use "cloudhsm" in func name inside cloudhsmv2 package + paths: + include: + - internal/service/cloudhsmv2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudhsm" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudhsm-in-const-name + languages: + - go + message: Do not use "cloudhsm" in const name inside cloudhsmv2 package + paths: + include: + - internal/service/cloudhsmv2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudhsm" + severity: WARNING + - id: cloudhsm-in-var-name + languages: + - go + message: Do not use "cloudhsm" in var name inside cloudhsmv2 package + paths: + include: + - internal/service/cloudhsmv2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudhsm" + severity: WARNING + - id: cloudhsmv2-in-func-name + languages: + - go + message: Do not use "CloudHSMV2" in func name inside cloudhsmv2 package + paths: + include: + - internal/service/cloudhsmv2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudHSMV2" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudhsmv2-in-test-name + languages: + - go + message: Include "CloudHSMV2" in test name + paths: + include: + - internal/service/cloudhsmv2/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCloudHSMV2" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cloudhsmv2-in-const-name + languages: + - go + message: Do not use "CloudHSMV2" in const name inside cloudhsmv2 package + paths: + include: + - internal/service/cloudhsmv2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudHSMV2" + severity: WARNING + - id: cloudhsmv2-in-var-name + languages: + - go + message: Do not use "CloudHSMV2" in var name inside cloudhsmv2 package + paths: + include: + - internal/service/cloudhsmv2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudHSMV2" + severity: WARNING + - id: cloudsearch-in-func-name + languages: + - go + message: Do not use "CloudSearch" in func name inside cloudsearch package + paths: + include: + - internal/service/cloudsearch + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudSearch" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudsearch-in-test-name + languages: + - go + message: Include "CloudSearch" in test name + paths: + include: + - internal/service/cloudsearch/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCloudSearch" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cloudsearch-in-const-name + languages: + - go + message: Do not use "CloudSearch" in const name inside cloudsearch package + paths: + include: + - internal/service/cloudsearch + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudSearch" + severity: WARNING + - id: cloudsearch-in-var-name + languages: + - go + message: Do not use "CloudSearch" in var name inside cloudsearch package + paths: + include: + - internal/service/cloudsearch + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudSearch" + severity: WARNING + - id: cloudtrail-in-func-name + languages: + - go + message: Do not use "CloudTrail" in func name inside cloudtrail package + paths: + include: + - internal/service/cloudtrail + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudTrail" + - pattern-not-regex: ^testAccCloudTrailConfig_.* + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudtrail-in-test-name + languages: + - go + message: Include "CloudTrail" in test name + paths: + include: + - internal/service/cloudtrail/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCloudTrail" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cloudtrail-in-const-name + languages: + - go + message: Do not use "CloudTrail" in const name inside cloudtrail package + paths: + include: + - internal/service/cloudtrail + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudTrail" + severity: WARNING + - id: cloudtrail-in-var-name + languages: + - go + message: Do not use "CloudTrail" in var name inside cloudtrail package + paths: + include: + - internal/service/cloudtrail + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudTrail" + severity: WARNING + - id: cloudwatch-in-func-name + languages: + - go + message: Do not use "CloudWatch" in func name inside cloudwatch package + paths: + include: + - internal/service/cloudwatch + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudWatch" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudwatch-in-test-name + languages: + - go + message: Include "CloudWatch" in test name + paths: + include: + - internal/service/cloudwatch/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCloudWatch" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cloudwatch-in-const-name + languages: + - go + message: Do not use "CloudWatch" in const name inside cloudwatch package + paths: + include: + - internal/service/cloudwatch + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudWatch" + severity: WARNING + - id: cloudwatch-in-var-name + languages: + - go + message: Do not use "CloudWatch" in var name inside cloudwatch package + paths: + include: + - internal/service/cloudwatch + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CloudWatch" + severity: WARNING + - id: cloudwatchevents-in-func-name + languages: + - go + message: Do not use "cloudwatchevents" in func name inside events package + paths: + include: + - internal/service/events + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchevents" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudwatchevents-in-const-name + languages: + - go + message: Do not use "cloudwatchevents" in const name inside events package + paths: + include: + - internal/service/events + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchevents" + severity: WARNING + - id: cloudwatchevents-in-var-name + languages: + - go + message: Do not use "cloudwatchevents" in var name inside events package + paths: + include: + - internal/service/events + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchevents" + severity: WARNING + - id: cloudwatchlog-in-func-name + languages: + - go + message: Do not use "cloudwatchlog" in func name inside logs package + paths: + include: + - internal/service/logs + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchlog" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudwatchlog-in-const-name + languages: + - go + message: Do not use "cloudwatchlog" in const name inside logs package + paths: + include: + - internal/service/logs + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchlog" + severity: WARNING + - id: cloudwatchlog-in-var-name + languages: + - go + message: Do not use "cloudwatchlog" in var name inside logs package + paths: + include: + - internal/service/logs + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchlog" + severity: WARNING + - id: cloudwatchlogs-in-func-name + languages: + - go + message: Do not use "cloudwatchlogs" in func name inside logs package + paths: + include: + - internal/service/logs + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchlogs" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudwatchlogs-in-const-name + languages: + - go + message: Do not use "cloudwatchlogs" in const name inside logs package + paths: + include: + - internal/service/logs + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchlogs" + severity: WARNING + - id: cloudwatchlogs-in-var-name + languages: + - go + message: Do not use "cloudwatchlogs" in var name inside logs package + paths: + include: + - internal/service/logs + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchlogs" + severity: WARNING + - id: cloudwatchrum-in-func-name + languages: + - go + message: Do not use "cloudwatchrum" in func name inside rum package + paths: + include: + - internal/service/rum + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchrum" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cloudwatchrum-in-const-name + languages: + - go + message: Do not use "cloudwatchrum" in const name inside rum package + paths: + include: + - internal/service/rum + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchrum" + severity: WARNING + - id: cloudwatchrum-in-var-name + languages: + - go + message: Do not use "cloudwatchrum" in var name inside rum package + paths: + include: + - internal/service/rum + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cloudwatchrum" + severity: WARNING + - id: codeartifact-in-func-name + languages: + - go + message: Do not use "CodeArtifact" in func name inside codeartifact package + paths: + include: + - internal/service/codeartifact + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeArtifact" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: codeartifact-in-test-name + languages: + - go + message: Include "CodeArtifact" in test name + paths: + include: + - internal/service/codeartifact/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCodeArtifact" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: codeartifact-in-const-name + languages: + - go + message: Do not use "CodeArtifact" in const name inside codeartifact package + paths: + include: + - internal/service/codeartifact + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeArtifact" + severity: WARNING + - id: codeartifact-in-var-name + languages: + - go + message: Do not use "CodeArtifact" in var name inside codeartifact package + paths: + include: + - internal/service/codeartifact + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeArtifact" + severity: WARNING + - id: codebuild-in-func-name + languages: + - go + message: Do not use "CodeBuild" in func name inside codebuild package + paths: + include: + - internal/service/codebuild + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeBuild" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: codebuild-in-test-name + languages: + - go + message: Include "CodeBuild" in test name + paths: + include: + - internal/service/codebuild/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCodeBuild" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: codebuild-in-const-name + languages: + - go + message: Do not use "CodeBuild" in const name inside codebuild package + paths: + include: + - internal/service/codebuild + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeBuild" + severity: WARNING + - id: codebuild-in-var-name + languages: + - go + message: Do not use "CodeBuild" in var name inside codebuild package + paths: + include: + - internal/service/codebuild + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeBuild" + severity: WARNING + - id: codecommit-in-func-name + languages: + - go + message: Do not use "CodeCommit" in func name inside codecommit package + paths: + include: + - internal/service/codecommit + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeCommit" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: codecommit-in-test-name + languages: + - go + message: Include "CodeCommit" in test name + paths: + include: + - internal/service/codecommit/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCodeCommit" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: codecommit-in-const-name + languages: + - go + message: Do not use "CodeCommit" in const name inside codecommit package + paths: + include: + - internal/service/codecommit + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeCommit" + severity: WARNING + - id: codecommit-in-var-name + languages: + - go + message: Do not use "CodeCommit" in var name inside codecommit package + paths: + include: + - internal/service/codecommit + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeCommit" + severity: WARNING + - id: codedeploy-in-func-name + languages: + - go + message: Do not use "codedeploy" in func name inside deploy package + paths: + include: + - internal/service/deploy + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)codedeploy" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: codedeploy-in-const-name + languages: + - go + message: Do not use "codedeploy" in const name inside deploy package + paths: + include: + - internal/service/deploy + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)codedeploy" + severity: WARNING + - id: codedeploy-in-var-name + languages: + - go + message: Do not use "codedeploy" in var name inside deploy package + paths: + include: + - internal/service/deploy + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)codedeploy" + severity: WARNING + - id: codepipeline-in-func-name + languages: + - go + message: Do not use "CodePipeline" in func name inside codepipeline package + paths: + include: + - internal/service/codepipeline + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodePipeline" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: codepipeline-in-test-name + languages: + - go + message: Include "CodePipeline" in test name + paths: + include: + - internal/service/codepipeline/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCodePipeline" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: codepipeline-in-const-name + languages: + - go + message: Do not use "CodePipeline" in const name inside codepipeline package + paths: + include: + - internal/service/codepipeline + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodePipeline" + severity: WARNING + - id: codepipeline-in-var-name + languages: + - go + message: Do not use "CodePipeline" in var name inside codepipeline package + paths: + include: + - internal/service/codepipeline + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodePipeline" + severity: WARNING + - id: codestarconnections-in-func-name + languages: + - go + message: Do not use "CodeStarConnections" in func name inside codestarconnections package + paths: + include: + - internal/service/codestarconnections + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeStarConnections" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: codestarconnections-in-test-name + languages: + - go + message: Include "CodeStarConnections" in test name + paths: + include: + - internal/service/codestarconnections/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCodeStarConnections" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: codestarconnections-in-const-name + languages: + - go + message: Do not use "CodeStarConnections" in const name inside codestarconnections package + paths: + include: + - internal/service/codestarconnections + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeStarConnections" + severity: WARNING + - id: codestarconnections-in-var-name + languages: + - go + message: Do not use "CodeStarConnections" in var name inside codestarconnections package + paths: + include: + - internal/service/codestarconnections + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeStarConnections" + severity: WARNING + - id: codestarnotifications-in-func-name + languages: + - go + message: Do not use "CodeStarNotifications" in func name inside codestarnotifications package + paths: + include: + - internal/service/codestarnotifications + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeStarNotifications" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: codestarnotifications-in-test-name + languages: + - go + message: Include "CodeStarNotifications" in test name + paths: + include: + - internal/service/codestarnotifications/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCodeStarNotifications" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: codestarnotifications-in-const-name + languages: + - go + message: Do not use "CodeStarNotifications" in const name inside codestarnotifications package + paths: + include: + - internal/service/codestarnotifications + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeStarNotifications" + severity: WARNING + - id: codestarnotifications-in-var-name + languages: + - go + message: Do not use "CodeStarNotifications" in var name inside codestarnotifications package + paths: + include: + - internal/service/codestarnotifications + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CodeStarNotifications" + severity: WARNING + - id: cognitoidentity-in-func-name + languages: + - go + message: Do not use "CognitoIdentity" in func name inside cognitoidentity package + paths: + include: + - internal/service/cognitoidentity + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CognitoIdentity" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cognitoidentity-in-test-name + languages: + - go + message: Include "CognitoIdentity" in test name + paths: + include: + - internal/service/cognitoidentity/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCognitoIdentity" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cognitoidentity-in-const-name + languages: + - go + message: Do not use "CognitoIdentity" in const name inside cognitoidentity package + paths: + include: + - internal/service/cognitoidentity + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CognitoIdentity" + severity: WARNING + - id: cognitoidentity-in-var-name + languages: + - go + message: Do not use "CognitoIdentity" in var name inside cognitoidentity package + paths: + include: + - internal/service/cognitoidentity + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CognitoIdentity" + severity: WARNING + - id: cognitoidentityprovider-in-func-name + languages: + - go + message: Do not use "cognitoidentityprovider" in func name inside cognitoidp package + paths: + include: + - internal/service/cognitoidp + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cognitoidentityprovider" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cognitoidentityprovider-in-const-name + languages: + - go + message: Do not use "cognitoidentityprovider" in const name inside cognitoidp package + paths: + include: + - internal/service/cognitoidp + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cognitoidentityprovider" + severity: WARNING + - id: cognitoidentityprovider-in-var-name + languages: + - go + message: Do not use "cognitoidentityprovider" in var name inside cognitoidp package + paths: + include: + - internal/service/cognitoidp + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)cognitoidentityprovider" + severity: WARNING + - id: cognitoidp-in-func-name + languages: + - go + message: Do not use "CognitoIDP" in func name inside cognitoidp package + paths: + include: + - internal/service/cognitoidp + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CognitoIDP" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cognitoidp-in-test-name + languages: + - go + message: Include "CognitoIDP" in test name + paths: + include: + - internal/service/cognitoidp/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCognitoIDP" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cognitoidp-in-const-name + languages: + - go + message: Do not use "CognitoIDP" in const name inside cognitoidp package + paths: + include: + - internal/service/cognitoidp + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CognitoIDP" + severity: WARNING + - id: cognitoidp-in-var-name + languages: + - go + message: Do not use "CognitoIDP" in var name inside cognitoidp package + paths: + include: + - internal/service/cognitoidp + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CognitoIDP" + severity: WARNING + - id: configservice-in-func-name + languages: + - go + message: Do not use "ConfigService" in func name inside configservice package + paths: + include: + - internal/service/configservice + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ConfigService" + - pattern-not-regex: ^TestAcc.* + severity: WARNING diff --git a/.semgrep-service-name1.yml b/.semgrep-service-name1.yml new file mode 100644 index 00000000000..137e3faf641 --- /dev/null +++ b/.semgrep-service-name1.yml @@ -0,0 +1,2917 @@ +# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. +rules: + - id: configservice-in-test-name + languages: + - go + message: Include "ConfigService" in test name + paths: + include: + - internal/service/configservice/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccConfigService" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: configservice-in-const-name + languages: + - go + message: Do not use "ConfigService" in const name inside configservice package + paths: + include: + - internal/service/configservice + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ConfigService" + severity: WARNING + - id: configservice-in-var-name + languages: + - go + message: Do not use "ConfigService" in var name inside configservice package + paths: + include: + - internal/service/configservice + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ConfigService" + severity: WARNING + - id: connect-in-func-name + languages: + - go + message: Do not use "Connect" in func name inside connect package + paths: + include: + - internal/service/connect + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Connect" + - pattern-not-regex: .*uickConnect.* + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: connect-in-test-name + languages: + - go + message: Include "Connect" in test name + paths: + include: + - internal/service/connect/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccConnect" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: connect-in-const-name + languages: + - go + message: Do not use "Connect" in const name inside connect package + paths: + include: + - internal/service/connect + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Connect" + - pattern-not-regex: .*uickConnect.* + severity: WARNING + - id: connect-in-var-name + languages: + - go + message: Do not use "Connect" in var name inside connect package + paths: + include: + - internal/service/connect + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Connect" + - pattern-not-regex: .*uickConnect.* + severity: WARNING + - id: costandusagereportservice-in-func-name + languages: + - go + message: Do not use "costandusagereportservice" in func name inside cur package + paths: + include: + - internal/service/cur + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)costandusagereportservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: costandusagereportservice-in-const-name + languages: + - go + message: Do not use "costandusagereportservice" in const name inside cur package + paths: + include: + - internal/service/cur + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)costandusagereportservice" + severity: WARNING + - id: costandusagereportservice-in-var-name + languages: + - go + message: Do not use "costandusagereportservice" in var name inside cur package + paths: + include: + - internal/service/cur + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)costandusagereportservice" + severity: WARNING + - id: costexplorer-in-func-name + languages: + - go + message: Do not use "costexplorer" in func name inside ce package + paths: + include: + - internal/service/ce + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)costexplorer" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: costexplorer-in-const-name + languages: + - go + message: Do not use "costexplorer" in const name inside ce package + paths: + include: + - internal/service/ce + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)costexplorer" + severity: WARNING + - id: costexplorer-in-var-name + languages: + - go + message: Do not use "costexplorer" in var name inside ce package + paths: + include: + - internal/service/ce + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)costexplorer" + severity: WARNING + - id: cur-in-func-name + languages: + - go + message: Do not use "CUR" in func name inside cur package + paths: + include: + - internal/service/cur + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CUR" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: cur-in-test-name + languages: + - go + message: Include "CUR" in test name + paths: + include: + - internal/service/cur/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccCUR" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: cur-in-const-name + languages: + - go + message: Do not use "CUR" in const name inside cur package + paths: + include: + - internal/service/cur + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CUR" + severity: WARNING + - id: cur-in-var-name + languages: + - go + message: Do not use "CUR" in var name inside cur package + paths: + include: + - internal/service/cur + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)CUR" + severity: WARNING + - id: databasemigration-in-func-name + languages: + - go + message: Do not use "databasemigration" in func name inside dms package + paths: + include: + - internal/service/dms + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)databasemigration" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: databasemigration-in-const-name + languages: + - go + message: Do not use "databasemigration" in const name inside dms package + paths: + include: + - internal/service/dms + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)databasemigration" + severity: WARNING + - id: databasemigration-in-var-name + languages: + - go + message: Do not use "databasemigration" in var name inside dms package + paths: + include: + - internal/service/dms + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)databasemigration" + severity: WARNING + - id: databasemigrationservice-in-func-name + languages: + - go + message: Do not use "databasemigrationservice" in func name inside dms package + paths: + include: + - internal/service/dms + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)databasemigrationservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: databasemigrationservice-in-const-name + languages: + - go + message: Do not use "databasemigrationservice" in const name inside dms package + paths: + include: + - internal/service/dms + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)databasemigrationservice" + severity: WARNING + - id: databasemigrationservice-in-var-name + languages: + - go + message: Do not use "databasemigrationservice" in var name inside dms package + paths: + include: + - internal/service/dms + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)databasemigrationservice" + severity: WARNING + - id: dataexchange-in-func-name + languages: + - go + message: Do not use "DataExchange" in func name inside dataexchange package + paths: + include: + - internal/service/dataexchange + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DataExchange" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: dataexchange-in-test-name + languages: + - go + message: Include "DataExchange" in test name + paths: + include: + - internal/service/dataexchange/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDataExchange" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: dataexchange-in-const-name + languages: + - go + message: Do not use "DataExchange" in const name inside dataexchange package + paths: + include: + - internal/service/dataexchange + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DataExchange" + severity: WARNING + - id: dataexchange-in-var-name + languages: + - go + message: Do not use "DataExchange" in var name inside dataexchange package + paths: + include: + - internal/service/dataexchange + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DataExchange" + severity: WARNING + - id: datapipeline-in-func-name + languages: + - go + message: Do not use "DataPipeline" in func name inside datapipeline package + paths: + include: + - internal/service/datapipeline + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DataPipeline" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: datapipeline-in-test-name + languages: + - go + message: Include "DataPipeline" in test name + paths: + include: + - internal/service/datapipeline/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDataPipeline" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: datapipeline-in-const-name + languages: + - go + message: Do not use "DataPipeline" in const name inside datapipeline package + paths: + include: + - internal/service/datapipeline + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DataPipeline" + severity: WARNING + - id: datapipeline-in-var-name + languages: + - go + message: Do not use "DataPipeline" in var name inside datapipeline package + paths: + include: + - internal/service/datapipeline + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DataPipeline" + severity: WARNING + - id: datasync-in-func-name + languages: + - go + message: Do not use "DataSync" in func name inside datasync package + paths: + include: + - internal/service/datasync + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DataSync" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: datasync-in-test-name + languages: + - go + message: Include "DataSync" in test name + paths: + include: + - internal/service/datasync/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDataSync" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: datasync-in-const-name + languages: + - go + message: Do not use "DataSync" in const name inside datasync package + paths: + include: + - internal/service/datasync + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DataSync" + severity: WARNING + - id: datasync-in-var-name + languages: + - go + message: Do not use "DataSync" in var name inside datasync package + paths: + include: + - internal/service/datasync + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DataSync" + severity: WARNING + - id: dax-in-func-name + languages: + - go + message: Do not use "DAX" in func name inside dax package + paths: + include: + - internal/service/dax + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DAX" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: dax-in-test-name + languages: + - go + message: Include "DAX" in test name + paths: + include: + - internal/service/dax/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDAX" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: dax-in-const-name + languages: + - go + message: Do not use "DAX" in const name inside dax package + paths: + include: + - internal/service/dax + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DAX" + severity: WARNING + - id: dax-in-var-name + languages: + - go + message: Do not use "DAX" in var name inside dax package + paths: + include: + - internal/service/dax + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DAX" + severity: WARNING + - id: deploy-in-func-name + languages: + - go + message: Do not use "Deploy" in func name inside deploy package + paths: + include: + - internal/service/deploy + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Deploy" + - pattern-not-regex: Deployment(Group|Config|Style) + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: deploy-in-test-name + languages: + - go + message: Include "Deploy" in test name + paths: + include: + - internal/service/deploy/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDeploy" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: deploy-in-const-name + languages: + - go + message: Do not use "Deploy" in const name inside deploy package + paths: + include: + - internal/service/deploy + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Deploy" + severity: WARNING + - id: deploy-in-var-name + languages: + - go + message: Do not use "Deploy" in var name inside deploy package + paths: + include: + - internal/service/deploy + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Deploy" + severity: WARNING + - id: detective-in-func-name + languages: + - go + message: Do not use "Detective" in func name inside detective package + paths: + include: + - internal/service/detective + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Detective" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: detective-in-test-name + languages: + - go + message: Include "Detective" in test name + paths: + include: + - internal/service/detective/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDetective" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: detective-in-const-name + languages: + - go + message: Do not use "Detective" in const name inside detective package + paths: + include: + - internal/service/detective + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Detective" + severity: WARNING + - id: detective-in-var-name + languages: + - go + message: Do not use "Detective" in var name inside detective package + paths: + include: + - internal/service/detective + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Detective" + severity: WARNING + - id: devicefarm-in-func-name + languages: + - go + message: Do not use "DeviceFarm" in func name inside devicefarm package + paths: + include: + - internal/service/devicefarm + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DeviceFarm" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: devicefarm-in-test-name + languages: + - go + message: Include "DeviceFarm" in test name + paths: + include: + - internal/service/devicefarm/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDeviceFarm" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: devicefarm-in-const-name + languages: + - go + message: Do not use "DeviceFarm" in const name inside devicefarm package + paths: + include: + - internal/service/devicefarm + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DeviceFarm" + severity: WARNING + - id: devicefarm-in-var-name + languages: + - go + message: Do not use "DeviceFarm" in var name inside devicefarm package + paths: + include: + - internal/service/devicefarm + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DeviceFarm" + severity: WARNING + - id: directconnect-in-func-name + languages: + - go + message: Do not use "DirectConnect" in func name inside directconnect package + paths: + include: + - internal/service/directconnect + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DirectConnect" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: directconnect-in-test-name + languages: + - go + message: Include "DirectConnect" in test name + paths: + include: + - internal/service/directconnect/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDirectConnect" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: directconnect-in-const-name + languages: + - go + message: Do not use "DirectConnect" in const name inside directconnect package + paths: + include: + - internal/service/directconnect + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DirectConnect" + severity: WARNING + - id: directconnect-in-var-name + languages: + - go + message: Do not use "DirectConnect" in var name inside directconnect package + paths: + include: + - internal/service/directconnect + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DirectConnect" + severity: WARNING + - id: directoryservice-in-func-name + languages: + - go + message: Do not use "directoryservice" in func name inside ds package + paths: + include: + - internal/service/ds + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)directoryservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: directoryservice-in-const-name + languages: + - go + message: Do not use "directoryservice" in const name inside ds package + paths: + include: + - internal/service/ds + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)directoryservice" + severity: WARNING + - id: directoryservice-in-var-name + languages: + - go + message: Do not use "directoryservice" in var name inside ds package + paths: + include: + - internal/service/ds + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)directoryservice" + severity: WARNING + - id: dlm-in-func-name + languages: + - go + message: Do not use "DLM" in func name inside dlm package + paths: + include: + - internal/service/dlm + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DLM" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: dlm-in-test-name + languages: + - go + message: Include "DLM" in test name + paths: + include: + - internal/service/dlm/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDLM" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: dlm-in-const-name + languages: + - go + message: Do not use "DLM" in const name inside dlm package + paths: + include: + - internal/service/dlm + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DLM" + severity: WARNING + - id: dlm-in-var-name + languages: + - go + message: Do not use "DLM" in var name inside dlm package + paths: + include: + - internal/service/dlm + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DLM" + severity: WARNING + - id: dms-in-func-name + languages: + - go + message: Do not use "DMS" in func name inside dms package + paths: + include: + - internal/service/dms + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DMS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: dms-in-test-name + languages: + - go + message: Include "DMS" in test name + paths: + include: + - internal/service/dms/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDMS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: dms-in-const-name + languages: + - go + message: Do not use "DMS" in const name inside dms package + paths: + include: + - internal/service/dms + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DMS" + severity: WARNING + - id: dms-in-var-name + languages: + - go + message: Do not use "DMS" in var name inside dms package + paths: + include: + - internal/service/dms + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DMS" + severity: WARNING + - id: docdb-in-func-name + languages: + - go + message: Do not use "DocDB" in func name inside docdb package + paths: + include: + - internal/service/docdb + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DocDB" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: docdb-in-test-name + languages: + - go + message: Include "DocDB" in test name + paths: + include: + - internal/service/docdb/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDocDB" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: docdb-in-const-name + languages: + - go + message: Do not use "DocDB" in const name inside docdb package + paths: + include: + - internal/service/docdb + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DocDB" + severity: WARNING + - id: docdb-in-var-name + languages: + - go + message: Do not use "DocDB" in var name inside docdb package + paths: + include: + - internal/service/docdb + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DocDB" + severity: WARNING + - id: ds-in-func-name + languages: + - go + message: Do not use "DS" in func name inside ds package + paths: + include: + - internal/service/ds + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ds-in-test-name + languages: + - go + message: Include "DS" in test name + paths: + include: + - internal/service/ds/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ds-in-const-name + languages: + - go + message: Do not use "DS" in const name inside ds package + paths: + include: + - internal/service/ds + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DS" + severity: WARNING + - id: ds-in-var-name + languages: + - go + message: Do not use "DS" in var name inside ds package + paths: + include: + - internal/service/ds + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DS" + severity: WARNING + - id: dynamodb-in-func-name + languages: + - go + message: Do not use "DynamoDB" in func name inside dynamodb package + paths: + include: + - internal/service/dynamodb + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DynamoDB" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: dynamodb-in-test-name + languages: + - go + message: Include "DynamoDB" in test name + paths: + include: + - internal/service/dynamodb/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccDynamoDB" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: dynamodb-in-const-name + languages: + - go + message: Do not use "DynamoDB" in const name inside dynamodb package + paths: + include: + - internal/service/dynamodb + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DynamoDB" + severity: WARNING + - id: dynamodb-in-var-name + languages: + - go + message: Do not use "DynamoDB" in var name inside dynamodb package + paths: + include: + - internal/service/dynamodb + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)DynamoDB" + severity: WARNING + - id: ec2-in-test-name + languages: + - go + message: Include "EC2" in test name + paths: + include: + - internal/service/ec2/ec2_*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccEC2" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ec2ebs-in-test-name + languages: + - go + message: Include "EC2EBS" in test name + paths: + include: + - internal/service/ec2/ebs_*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccEC2EBS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ec2outposts-in-test-name + languages: + - go + message: Include "EC2Outposts" in test name + paths: + include: + - internal/service/ec2/outposts_*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccEC2Outposts" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ecr-in-func-name + languages: + - go + message: Do not use "ECR" in func name inside ecr package + paths: + include: + - internal/service/ecr + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ECR" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ecr-in-test-name + languages: + - go + message: Include "ECR" in test name + paths: + include: + - internal/service/ecr/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccECR" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ecr-in-const-name + languages: + - go + message: Do not use "ECR" in const name inside ecr package + paths: + include: + - internal/service/ecr + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ECR" + severity: WARNING + - id: ecr-in-var-name + languages: + - go + message: Do not use "ECR" in var name inside ecr package + paths: + include: + - internal/service/ecr + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ECR" + severity: WARNING + - id: ecrpublic-in-func-name + languages: + - go + message: Do not use "ECRPublic" in func name inside ecrpublic package + paths: + include: + - internal/service/ecrpublic + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ECRPublic" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ecrpublic-in-test-name + languages: + - go + message: Include "ECRPublic" in test name + paths: + include: + - internal/service/ecrpublic/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccECRPublic" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ecrpublic-in-const-name + languages: + - go + message: Do not use "ECRPublic" in const name inside ecrpublic package + paths: + include: + - internal/service/ecrpublic + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ECRPublic" + severity: WARNING + - id: ecrpublic-in-var-name + languages: + - go + message: Do not use "ECRPublic" in var name inside ecrpublic package + paths: + include: + - internal/service/ecrpublic + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ECRPublic" + severity: WARNING + - id: ecs-in-func-name + languages: + - go + message: Do not use "ECS" in func name inside ecs package + paths: + include: + - internal/service/ecs + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ECS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ecs-in-test-name + languages: + - go + message: Include "ECS" in test name + paths: + include: + - internal/service/ecs/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccECS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ecs-in-const-name + languages: + - go + message: Do not use "ECS" in const name inside ecs package + paths: + include: + - internal/service/ecs + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ECS" + severity: WARNING + - id: ecs-in-var-name + languages: + - go + message: Do not use "ECS" in var name inside ecs package + paths: + include: + - internal/service/ecs + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ECS" + severity: WARNING + - id: efs-in-func-name + languages: + - go + message: Do not use "EFS" in func name inside efs package + paths: + include: + - internal/service/efs + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EFS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: efs-in-test-name + languages: + - go + message: Include "EFS" in test name + paths: + include: + - internal/service/efs/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccEFS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: efs-in-const-name + languages: + - go + message: Do not use "EFS" in const name inside efs package + paths: + include: + - internal/service/efs + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EFS" + severity: WARNING + - id: efs-in-var-name + languages: + - go + message: Do not use "EFS" in var name inside efs package + paths: + include: + - internal/service/efs + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EFS" + severity: WARNING + - id: eks-in-func-name + languages: + - go + message: Do not use "EKS" in func name inside eks package + paths: + include: + - internal/service/eks + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EKS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: eks-in-test-name + languages: + - go + message: Include "EKS" in test name + paths: + include: + - internal/service/eks/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccEKS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: eks-in-const-name + languages: + - go + message: Do not use "EKS" in const name inside eks package + paths: + include: + - internal/service/eks + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EKS" + severity: WARNING + - id: eks-in-var-name + languages: + - go + message: Do not use "EKS" in var name inside eks package + paths: + include: + - internal/service/eks + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EKS" + severity: WARNING + - id: elasticache-in-func-name + languages: + - go + message: Do not use "ElastiCache" in func name inside elasticache package + paths: + include: + - internal/service/elasticache + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ElastiCache" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: elasticache-in-test-name + languages: + - go + message: Include "ElastiCache" in test name + paths: + include: + - internal/service/elasticache/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccElastiCache" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: elasticache-in-const-name + languages: + - go + message: Do not use "ElastiCache" in const name inside elasticache package + paths: + include: + - internal/service/elasticache + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ElastiCache" + severity: WARNING + - id: elasticache-in-var-name + languages: + - go + message: Do not use "ElastiCache" in var name inside elasticache package + paths: + include: + - internal/service/elasticache + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ElastiCache" + severity: WARNING + - id: elasticbeanstalk-in-func-name + languages: + - go + message: Do not use "ElasticBeanstalk" in func name inside elasticbeanstalk package + paths: + include: + - internal/service/elasticbeanstalk + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ElasticBeanstalk" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: elasticbeanstalk-in-test-name + languages: + - go + message: Include "ElasticBeanstalk" in test name + paths: + include: + - internal/service/elasticbeanstalk/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccElasticBeanstalk" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: elasticbeanstalk-in-const-name + languages: + - go + message: Do not use "ElasticBeanstalk" in const name inside elasticbeanstalk package + paths: + include: + - internal/service/elasticbeanstalk + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ElasticBeanstalk" + severity: WARNING + - id: elasticbeanstalk-in-var-name + languages: + - go + message: Do not use "ElasticBeanstalk" in var name inside elasticbeanstalk package + paths: + include: + - internal/service/elasticbeanstalk + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ElasticBeanstalk" + severity: WARNING + - id: elasticloadbalancing-in-func-name + languages: + - go + message: Do not use "elasticloadbalancing" in func name inside elb package + paths: + include: + - internal/service/elb + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)elasticloadbalancing" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: elasticloadbalancing-in-const-name + languages: + - go + message: Do not use "elasticloadbalancing" in const name inside elb package + paths: + include: + - internal/service/elb + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)elasticloadbalancing" + severity: WARNING + - id: elasticloadbalancing-in-var-name + languages: + - go + message: Do not use "elasticloadbalancing" in var name inside elb package + paths: + include: + - internal/service/elb + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)elasticloadbalancing" + severity: WARNING + - id: elasticloadbalancingv2-in-func-name + languages: + - go + message: Do not use "elasticloadbalancingv2" in func name inside elbv2 package + paths: + include: + - internal/service/elbv2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)elasticloadbalancingv2" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: elasticloadbalancingv2-in-const-name + languages: + - go + message: Do not use "elasticloadbalancingv2" in const name inside elbv2 package + paths: + include: + - internal/service/elbv2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)elasticloadbalancingv2" + severity: WARNING + - id: elasticloadbalancingv2-in-var-name + languages: + - go + message: Do not use "elasticloadbalancingv2" in var name inside elbv2 package + paths: + include: + - internal/service/elbv2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)elasticloadbalancingv2" + severity: WARNING + - id: elasticsearch-in-func-name + languages: + - go + message: Do not use "Elasticsearch" in func name inside elasticsearch package + paths: + include: + - internal/service/elasticsearch + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Elasticsearch" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: elasticsearch-in-test-name + languages: + - go + message: Include "Elasticsearch" in test name + paths: + include: + - internal/service/elasticsearch/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccElasticsearch" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: elasticsearch-in-const-name + languages: + - go + message: Do not use "Elasticsearch" in const name inside elasticsearch package + paths: + include: + - internal/service/elasticsearch + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Elasticsearch" + severity: WARNING + - id: elasticsearch-in-var-name + languages: + - go + message: Do not use "Elasticsearch" in var name inside elasticsearch package + paths: + include: + - internal/service/elasticsearch + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Elasticsearch" + severity: WARNING + - id: elasticsearchservice-in-func-name + languages: + - go + message: Do not use "elasticsearchservice" in func name inside elasticsearch package + paths: + include: + - internal/service/elasticsearch + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)elasticsearchservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: elasticsearchservice-in-const-name + languages: + - go + message: Do not use "elasticsearchservice" in const name inside elasticsearch package + paths: + include: + - internal/service/elasticsearch + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)elasticsearchservice" + severity: WARNING + - id: elasticsearchservice-in-var-name + languages: + - go + message: Do not use "elasticsearchservice" in var name inside elasticsearch package + paths: + include: + - internal/service/elasticsearch + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)elasticsearchservice" + severity: WARNING + - id: elastictranscoder-in-func-name + languages: + - go + message: Do not use "ElasticTranscoder" in func name inside elastictranscoder package + paths: + include: + - internal/service/elastictranscoder + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ElasticTranscoder" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: elastictranscoder-in-test-name + languages: + - go + message: Include "ElasticTranscoder" in test name + paths: + include: + - internal/service/elastictranscoder/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccElasticTranscoder" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: elastictranscoder-in-const-name + languages: + - go + message: Do not use "ElasticTranscoder" in const name inside elastictranscoder package + paths: + include: + - internal/service/elastictranscoder + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ElasticTranscoder" + severity: WARNING + - id: elastictranscoder-in-var-name + languages: + - go + message: Do not use "ElasticTranscoder" in var name inside elastictranscoder package + paths: + include: + - internal/service/elastictranscoder + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ElasticTranscoder" + severity: WARNING + - id: elb-in-func-name + languages: + - go + message: Do not use "ELB" in func name inside elb package + paths: + include: + - internal/service/elb + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ELB" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: elb-in-test-name + languages: + - go + message: Include "ELB" in test name + paths: + include: + - internal/service/elb/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccELB" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: elb-in-const-name + languages: + - go + message: Do not use "ELB" in const name inside elb package + paths: + include: + - internal/service/elb + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ELB" + severity: WARNING + - id: elb-in-var-name + languages: + - go + message: Do not use "ELB" in var name inside elb package + paths: + include: + - internal/service/elb + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ELB" + severity: WARNING + - id: elbv2-in-func-name + languages: + - go + message: Do not use "ELBV2" in func name inside elbv2 package + paths: + include: + - internal/service/elbv2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ELBV2" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: elbv2-in-test-name + languages: + - go + message: Include "ELBV2" in test name + paths: + include: + - internal/service/elbv2/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccELBV2" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: elbv2-in-const-name + languages: + - go + message: Do not use "ELBV2" in const name inside elbv2 package + paths: + include: + - internal/service/elbv2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ELBV2" + severity: WARNING + - id: elbv2-in-var-name + languages: + - go + message: Do not use "ELBV2" in var name inside elbv2 package + paths: + include: + - internal/service/elbv2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ELBV2" + severity: WARNING + - id: emr-in-func-name + languages: + - go + message: Do not use "EMR" in func name inside emr package + paths: + include: + - internal/service/emr + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EMR" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: emr-in-test-name + languages: + - go + message: Include "EMR" in test name + paths: + include: + - internal/service/emr/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccEMR" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: emr-in-const-name + languages: + - go + message: Do not use "EMR" in const name inside emr package + paths: + include: + - internal/service/emr + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EMR" + severity: WARNING + - id: emr-in-var-name + languages: + - go + message: Do not use "EMR" in var name inside emr package + paths: + include: + - internal/service/emr + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EMR" + severity: WARNING + - id: emrcontainers-in-func-name + languages: + - go + message: Do not use "EMRContainers" in func name inside emrcontainers package + paths: + include: + - internal/service/emrcontainers + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EMRContainers" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: emrcontainers-in-test-name + languages: + - go + message: Include "EMRContainers" in test name + paths: + include: + - internal/service/emrcontainers/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccEMRContainers" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: emrcontainers-in-const-name + languages: + - go + message: Do not use "EMRContainers" in const name inside emrcontainers package + paths: + include: + - internal/service/emrcontainers + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EMRContainers" + severity: WARNING + - id: emrcontainers-in-var-name + languages: + - go + message: Do not use "EMRContainers" in var name inside emrcontainers package + paths: + include: + - internal/service/emrcontainers + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EMRContainers" + severity: WARNING + - id: emrserverless-in-func-name + languages: + - go + message: Do not use "EMRServerless" in func name inside emrserverless package + paths: + include: + - internal/service/emrserverless + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EMRServerless" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: emrserverless-in-test-name + languages: + - go + message: Include "EMRServerless" in test name + paths: + include: + - internal/service/emrserverless/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccEMRServerless" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: emrserverless-in-const-name + languages: + - go + message: Do not use "EMRServerless" in const name inside emrserverless package + paths: + include: + - internal/service/emrserverless + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EMRServerless" + severity: WARNING + - id: emrserverless-in-var-name + languages: + - go + message: Do not use "EMRServerless" in var name inside emrserverless package + paths: + include: + - internal/service/emrserverless + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EMRServerless" + severity: WARNING + - id: eventbridge-in-func-name + languages: + - go + message: Do not use "eventbridge" in func name inside events package + paths: + include: + - internal/service/events + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)eventbridge" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: eventbridge-in-const-name + languages: + - go + message: Do not use "eventbridge" in const name inside events package + paths: + include: + - internal/service/events + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)eventbridge" + severity: WARNING + - id: eventbridge-in-var-name + languages: + - go + message: Do not use "eventbridge" in var name inside events package + paths: + include: + - internal/service/events + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)eventbridge" + severity: WARNING + - id: events-in-func-name + languages: + - go + message: Do not use "Events" in func name inside events package + paths: + include: + - internal/service/events + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Events" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: events-in-test-name + languages: + - go + message: Include "Events" in test name + paths: + include: + - internal/service/events/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccEvents" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: events-in-const-name + languages: + - go + message: Do not use "Events" in const name inside events package + paths: + include: + - internal/service/events + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Events" + severity: WARNING + - id: events-in-var-name + languages: + - go + message: Do not use "Events" in var name inside events package + paths: + include: + - internal/service/events + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Events" + severity: WARNING + - id: firehose-in-func-name + languages: + - go + message: Do not use "Firehose" in func name inside firehose package + paths: + include: + - internal/service/firehose + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Firehose" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: firehose-in-test-name + languages: + - go + message: Include "Firehose" in test name + paths: + include: + - internal/service/firehose/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccFirehose" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: firehose-in-const-name + languages: + - go + message: Do not use "Firehose" in const name inside firehose package + paths: + include: + - internal/service/firehose + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Firehose" + severity: WARNING + - id: firehose-in-var-name + languages: + - go + message: Do not use "Firehose" in var name inside firehose package + paths: + include: + - internal/service/firehose + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Firehose" + severity: WARNING + - id: fms-in-func-name + languages: + - go + message: Do not use "FMS" in func name inside fms package + paths: + include: + - internal/service/fms + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)FMS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: fms-in-test-name + languages: + - go + message: Include "FMS" in test name + paths: + include: + - internal/service/fms/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccFMS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: fms-in-const-name + languages: + - go + message: Do not use "FMS" in const name inside fms package + paths: + include: + - internal/service/fms + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)FMS" + severity: WARNING + - id: fms-in-var-name + languages: + - go + message: Do not use "FMS" in var name inside fms package + paths: + include: + - internal/service/fms + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)FMS" + severity: WARNING + - id: fsx-in-func-name + languages: + - go + message: Do not use "FSx" in func name inside fsx package + paths: + include: + - internal/service/fsx + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)FSx" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: fsx-in-test-name + languages: + - go + message: Include "FSx" in test name + paths: + include: + - internal/service/fsx/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccFSx" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: fsx-in-const-name + languages: + - go + message: Do not use "FSx" in const name inside fsx package + paths: + include: + - internal/service/fsx + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)FSx" + severity: WARNING + - id: fsx-in-var-name + languages: + - go + message: Do not use "FSx" in var name inside fsx package + paths: + include: + - internal/service/fsx + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)FSx" + severity: WARNING + - id: gamelift-in-func-name + languages: + - go + message: Do not use "GameLift" in func name inside gamelift package + paths: + include: + - internal/service/gamelift + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)GameLift" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: gamelift-in-test-name + languages: + - go + message: Include "GameLift" in test name + paths: + include: + - internal/service/gamelift/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccGameLift" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: gamelift-in-const-name + languages: + - go + message: Do not use "GameLift" in const name inside gamelift package + paths: + include: + - internal/service/gamelift + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)GameLift" + severity: WARNING + - id: gamelift-in-var-name + languages: + - go + message: Do not use "GameLift" in var name inside gamelift package + paths: + include: + - internal/service/gamelift + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)GameLift" + severity: WARNING + - id: glacier-in-func-name + languages: + - go + message: Do not use "Glacier" in func name inside glacier package + paths: + include: + - internal/service/glacier + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Glacier" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: glacier-in-test-name + languages: + - go + message: Include "Glacier" in test name + paths: + include: + - internal/service/glacier/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccGlacier" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: glacier-in-const-name + languages: + - go + message: Do not use "Glacier" in const name inside glacier package + paths: + include: + - internal/service/glacier + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Glacier" + severity: WARNING + - id: glacier-in-var-name + languages: + - go + message: Do not use "Glacier" in var name inside glacier package + paths: + include: + - internal/service/glacier + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Glacier" + severity: WARNING + - id: globalaccelerator-in-func-name + languages: + - go + message: Do not use "GlobalAccelerator" in func name inside globalaccelerator package + paths: + include: + - internal/service/globalaccelerator + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)GlobalAccelerator" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: globalaccelerator-in-test-name + languages: + - go + message: Include "GlobalAccelerator" in test name + paths: + include: + - internal/service/globalaccelerator/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccGlobalAccelerator" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: globalaccelerator-in-const-name + languages: + - go + message: Do not use "GlobalAccelerator" in const name inside globalaccelerator package + paths: + include: + - internal/service/globalaccelerator + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)GlobalAccelerator" + severity: WARNING + - id: globalaccelerator-in-var-name + languages: + - go + message: Do not use "GlobalAccelerator" in var name inside globalaccelerator package + paths: + include: + - internal/service/globalaccelerator + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)GlobalAccelerator" + severity: WARNING + - id: glue-in-func-name + languages: + - go + message: Do not use "Glue" in func name inside glue package + paths: + include: + - internal/service/glue + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Glue" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: glue-in-test-name + languages: + - go + message: Include "Glue" in test name + paths: + include: + - internal/service/glue/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccGlue" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: glue-in-const-name + languages: + - go + message: Do not use "Glue" in const name inside glue package + paths: + include: + - internal/service/glue + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Glue" + severity: WARNING + - id: glue-in-var-name + languages: + - go + message: Do not use "Glue" in var name inside glue package + paths: + include: + - internal/service/glue + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Glue" + severity: WARNING + - id: grafana-in-func-name + languages: + - go + message: Do not use "Grafana" in func name inside grafana package + paths: + include: + - internal/service/grafana + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Grafana" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: grafana-in-test-name + languages: + - go + message: Include "Grafana" in test name + paths: + include: + - internal/service/grafana/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccGrafana" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: grafana-in-const-name + languages: + - go + message: Do not use "Grafana" in const name inside grafana package + paths: + include: + - internal/service/grafana + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Grafana" + severity: WARNING + - id: grafana-in-var-name + languages: + - go + message: Do not use "Grafana" in var name inside grafana package + paths: + include: + - internal/service/grafana + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Grafana" + severity: WARNING + - id: greengrass-in-func-name + languages: + - go + message: Do not use "Greengrass" in func name inside greengrass package + paths: + include: + - internal/service/greengrass + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Greengrass" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: greengrass-in-test-name + languages: + - go + message: Include "Greengrass" in test name + paths: + include: + - internal/service/greengrass/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccGreengrass" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: greengrass-in-const-name + languages: + - go + message: Do not use "Greengrass" in const name inside greengrass package + paths: + include: + - internal/service/greengrass + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Greengrass" + severity: WARNING + - id: greengrass-in-var-name + languages: + - go + message: Do not use "Greengrass" in var name inside greengrass package + paths: + include: + - internal/service/greengrass + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Greengrass" + severity: WARNING + - id: guardduty-in-func-name + languages: + - go + message: Do not use "GuardDuty" in func name inside guardduty package + paths: + include: + - internal/service/guardduty + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)GuardDuty" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: guardduty-in-test-name + languages: + - go + message: Include "GuardDuty" in test name + paths: + include: + - internal/service/guardduty/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccGuardDuty" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: guardduty-in-const-name + languages: + - go + message: Do not use "GuardDuty" in const name inside guardduty package + paths: + include: + - internal/service/guardduty + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)GuardDuty" + severity: WARNING + - id: guardduty-in-var-name + languages: + - go + message: Do not use "GuardDuty" in var name inside guardduty package + paths: + include: + - internal/service/guardduty + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)GuardDuty" + severity: WARNING + - id: iam-in-func-name + languages: + - go + message: Do not use "IAM" in func name inside iam package + paths: + include: + - internal/service/iam + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IAM" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: iam-in-test-name + languages: + - go + message: Include "IAM" in test name + paths: + include: + - internal/service/iam/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccIAM" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: iam-in-const-name + languages: + - go + message: Do not use "IAM" in const name inside iam package + paths: + include: + - internal/service/iam + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IAM" + severity: WARNING + - id: iam-in-var-name + languages: + - go + message: Do not use "IAM" in var name inside iam package + paths: + include: + - internal/service/iam + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IAM" + severity: WARNING + - id: identitystore-in-func-name + languages: + - go + message: Do not use "IdentityStore" in func name inside identitystore package + paths: + include: + - internal/service/identitystore + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IdentityStore" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: identitystore-in-test-name + languages: + - go + message: Include "IdentityStore" in test name + paths: + include: + - internal/service/identitystore/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccIdentityStore" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: identitystore-in-const-name + languages: + - go + message: Do not use "IdentityStore" in const name inside identitystore package + paths: + include: + - internal/service/identitystore + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IdentityStore" + severity: WARNING + - id: identitystore-in-var-name + languages: + - go + message: Do not use "IdentityStore" in var name inside identitystore package + paths: + include: + - internal/service/identitystore + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IdentityStore" + severity: WARNING diff --git a/.semgrep-service-name2.yml b/.semgrep-service-name2.yml new file mode 100644 index 00000000000..d4e47ee013c --- /dev/null +++ b/.semgrep-service-name2.yml @@ -0,0 +1,2913 @@ +# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. +rules: + - id: imagebuilder-in-func-name + languages: + - go + message: Do not use "ImageBuilder" in func name inside imagebuilder package + paths: + include: + - internal/service/imagebuilder + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ImageBuilder" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: imagebuilder-in-test-name + languages: + - go + message: Include "ImageBuilder" in test name + paths: + include: + - internal/service/imagebuilder/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccImageBuilder" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: imagebuilder-in-const-name + languages: + - go + message: Do not use "ImageBuilder" in const name inside imagebuilder package + paths: + include: + - internal/service/imagebuilder + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ImageBuilder" + severity: WARNING + - id: imagebuilder-in-var-name + languages: + - go + message: Do not use "ImageBuilder" in var name inside imagebuilder package + paths: + include: + - internal/service/imagebuilder + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ImageBuilder" + severity: WARNING + - id: inspector-in-func-name + languages: + - go + message: Do not use "Inspector" in func name inside inspector package + paths: + include: + - internal/service/inspector + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Inspector" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: inspector-in-test-name + languages: + - go + message: Include "Inspector" in test name + paths: + include: + - internal/service/inspector/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccInspector" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: inspector-in-const-name + languages: + - go + message: Do not use "Inspector" in const name inside inspector package + paths: + include: + - internal/service/inspector + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Inspector" + severity: WARNING + - id: inspector-in-var-name + languages: + - go + message: Do not use "Inspector" in var name inside inspector package + paths: + include: + - internal/service/inspector + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Inspector" + severity: WARNING + - id: iot-in-func-name + languages: + - go + message: Do not use "IoT" in func name inside iot package + paths: + include: + - internal/service/iot + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IoT" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: iot-in-test-name + languages: + - go + message: Include "IoT" in test name + paths: + include: + - internal/service/iot/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccIoT" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: iot-in-const-name + languages: + - go + message: Do not use "IoT" in const name inside iot package + paths: + include: + - internal/service/iot + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IoT" + severity: WARNING + - id: iot-in-var-name + languages: + - go + message: Do not use "IoT" in var name inside iot package + paths: + include: + - internal/service/iot + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IoT" + severity: WARNING + - id: iotanalytics-in-func-name + languages: + - go + message: Do not use "IoTAnalytics" in func name inside iotanalytics package + paths: + include: + - internal/service/iotanalytics + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IoTAnalytics" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: iotanalytics-in-test-name + languages: + - go + message: Include "IoTAnalytics" in test name + paths: + include: + - internal/service/iotanalytics/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccIoTAnalytics" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: iotanalytics-in-const-name + languages: + - go + message: Do not use "IoTAnalytics" in const name inside iotanalytics package + paths: + include: + - internal/service/iotanalytics + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IoTAnalytics" + severity: WARNING + - id: iotanalytics-in-var-name + languages: + - go + message: Do not use "IoTAnalytics" in var name inside iotanalytics package + paths: + include: + - internal/service/iotanalytics + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IoTAnalytics" + severity: WARNING + - id: iotevents-in-func-name + languages: + - go + message: Do not use "IoTEvents" in func name inside iotevents package + paths: + include: + - internal/service/iotevents + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IoTEvents" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: iotevents-in-test-name + languages: + - go + message: Include "IoTEvents" in test name + paths: + include: + - internal/service/iotevents/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccIoTEvents" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: iotevents-in-const-name + languages: + - go + message: Do not use "IoTEvents" in const name inside iotevents package + paths: + include: + - internal/service/iotevents + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IoTEvents" + severity: WARNING + - id: iotevents-in-var-name + languages: + - go + message: Do not use "IoTEvents" in var name inside iotevents package + paths: + include: + - internal/service/iotevents + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)IoTEvents" + severity: WARNING + - id: ipam-in-test-name + languages: + - go + message: Include "IPAM" in test name + paths: + include: + - internal/service/ec2/ipam_*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccIPAM" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: kafka-in-func-name + languages: + - go + message: Do not use "Kafka" in func name inside kafka package + paths: + include: + - internal/service/kafka + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Kafka" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: kafka-in-test-name + languages: + - go + message: Include "Kafka" in test name + paths: + include: + - internal/service/kafka/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccKafka" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: kafka-in-const-name + languages: + - go + message: Do not use "Kafka" in const name inside kafka package + paths: + include: + - internal/service/kafka + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Kafka" + severity: WARNING + - id: kafka-in-var-name + languages: + - go + message: Do not use "Kafka" in var name inside kafka package + paths: + include: + - internal/service/kafka + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Kafka" + severity: WARNING + - id: kafkaconnect-in-func-name + languages: + - go + message: Do not use "KafkaConnect" in func name inside kafkaconnect package + paths: + include: + - internal/service/kafkaconnect + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KafkaConnect" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: kafkaconnect-in-test-name + languages: + - go + message: Include "KafkaConnect" in test name + paths: + include: + - internal/service/kafkaconnect/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccKafkaConnect" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: kafkaconnect-in-const-name + languages: + - go + message: Do not use "KafkaConnect" in const name inside kafkaconnect package + paths: + include: + - internal/service/kafkaconnect + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KafkaConnect" + severity: WARNING + - id: kafkaconnect-in-var-name + languages: + - go + message: Do not use "KafkaConnect" in var name inside kafkaconnect package + paths: + include: + - internal/service/kafkaconnect + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KafkaConnect" + severity: WARNING + - id: kendra-in-func-name + languages: + - go + message: Do not use "Kendra" in func name inside kendra package + paths: + include: + - internal/service/kendra + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Kendra" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: kendra-in-test-name + languages: + - go + message: Include "Kendra" in test name + paths: + include: + - internal/service/kendra/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccKendra" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: kendra-in-const-name + languages: + - go + message: Do not use "Kendra" in const name inside kendra package + paths: + include: + - internal/service/kendra + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Kendra" + severity: WARNING + - id: kendra-in-var-name + languages: + - go + message: Do not use "Kendra" in var name inside kendra package + paths: + include: + - internal/service/kendra + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Kendra" + severity: WARNING + - id: keyspaces-in-func-name + languages: + - go + message: Do not use "Keyspaces" in func name inside keyspaces package + paths: + include: + - internal/service/keyspaces + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Keyspaces" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: keyspaces-in-test-name + languages: + - go + message: Include "Keyspaces" in test name + paths: + include: + - internal/service/keyspaces/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccKeyspaces" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: keyspaces-in-const-name + languages: + - go + message: Do not use "Keyspaces" in const name inside keyspaces package + paths: + include: + - internal/service/keyspaces + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Keyspaces" + severity: WARNING + - id: keyspaces-in-var-name + languages: + - go + message: Do not use "Keyspaces" in var name inside keyspaces package + paths: + include: + - internal/service/keyspaces + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Keyspaces" + severity: WARNING + - id: kinesis-in-func-name + languages: + - go + message: Do not use "Kinesis" in func name inside kinesis package + paths: + include: + - internal/service/kinesis + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Kinesis" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: kinesis-in-test-name + languages: + - go + message: Include "Kinesis" in test name + paths: + include: + - internal/service/kinesis/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccKinesis" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: kinesis-in-const-name + languages: + - go + message: Do not use "Kinesis" in const name inside kinesis package + paths: + include: + - internal/service/kinesis + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Kinesis" + severity: WARNING + - id: kinesis-in-var-name + languages: + - go + message: Do not use "Kinesis" in var name inside kinesis package + paths: + include: + - internal/service/kinesis + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Kinesis" + severity: WARNING + - id: kinesisanalytics-in-func-name + languages: + - go + message: Do not use "KinesisAnalytics" in func name inside kinesisanalytics package + paths: + include: + - internal/service/kinesisanalytics + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KinesisAnalytics" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: kinesisanalytics-in-test-name + languages: + - go + message: Include "KinesisAnalytics" in test name + paths: + include: + - internal/service/kinesisanalytics/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccKinesisAnalytics" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: kinesisanalytics-in-const-name + languages: + - go + message: Do not use "KinesisAnalytics" in const name inside kinesisanalytics package + paths: + include: + - internal/service/kinesisanalytics + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KinesisAnalytics" + severity: WARNING + - id: kinesisanalytics-in-var-name + languages: + - go + message: Do not use "KinesisAnalytics" in var name inside kinesisanalytics package + paths: + include: + - internal/service/kinesisanalytics + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KinesisAnalytics" + severity: WARNING + - id: kinesisanalyticsv2-in-func-name + languages: + - go + message: Do not use "KinesisAnalyticsV2" in func name inside kinesisanalyticsv2 package + paths: + include: + - internal/service/kinesisanalyticsv2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KinesisAnalyticsV2" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: kinesisanalyticsv2-in-test-name + languages: + - go + message: Include "KinesisAnalyticsV2" in test name + paths: + include: + - internal/service/kinesisanalyticsv2/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccKinesisAnalyticsV2" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: kinesisanalyticsv2-in-const-name + languages: + - go + message: Do not use "KinesisAnalyticsV2" in const name inside kinesisanalyticsv2 package + paths: + include: + - internal/service/kinesisanalyticsv2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KinesisAnalyticsV2" + severity: WARNING + - id: kinesisanalyticsv2-in-var-name + languages: + - go + message: Do not use "KinesisAnalyticsV2" in var name inside kinesisanalyticsv2 package + paths: + include: + - internal/service/kinesisanalyticsv2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KinesisAnalyticsV2" + severity: WARNING + - id: kinesisvideo-in-func-name + languages: + - go + message: Do not use "KinesisVideo" in func name inside kinesisvideo package + paths: + include: + - internal/service/kinesisvideo + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KinesisVideo" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: kinesisvideo-in-test-name + languages: + - go + message: Include "KinesisVideo" in test name + paths: + include: + - internal/service/kinesisvideo/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccKinesisVideo" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: kinesisvideo-in-const-name + languages: + - go + message: Do not use "KinesisVideo" in const name inside kinesisvideo package + paths: + include: + - internal/service/kinesisvideo + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KinesisVideo" + severity: WARNING + - id: kinesisvideo-in-var-name + languages: + - go + message: Do not use "KinesisVideo" in var name inside kinesisvideo package + paths: + include: + - internal/service/kinesisvideo + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KinesisVideo" + severity: WARNING + - id: kms-in-func-name + languages: + - go + message: Do not use "KMS" in func name inside kms package + paths: + include: + - internal/service/kms + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KMS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: kms-in-test-name + languages: + - go + message: Include "KMS" in test name + paths: + include: + - internal/service/kms/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccKMS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: kms-in-const-name + languages: + - go + message: Do not use "KMS" in const name inside kms package + paths: + include: + - internal/service/kms + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KMS" + severity: WARNING + - id: kms-in-var-name + languages: + - go + message: Do not use "KMS" in var name inside kms package + paths: + include: + - internal/service/kms + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)KMS" + severity: WARNING + - id: lakeformation-in-func-name + languages: + - go + message: Do not use "LakeFormation" in func name inside lakeformation package + paths: + include: + - internal/service/lakeformation + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)LakeFormation" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: lakeformation-in-test-name + languages: + - go + message: Include "LakeFormation" in test name + paths: + include: + - internal/service/lakeformation/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccLakeFormation" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: lakeformation-in-const-name + languages: + - go + message: Do not use "LakeFormation" in const name inside lakeformation package + paths: + include: + - internal/service/lakeformation + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)LakeFormation" + severity: WARNING + - id: lakeformation-in-var-name + languages: + - go + message: Do not use "LakeFormation" in var name inside lakeformation package + paths: + include: + - internal/service/lakeformation + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)LakeFormation" + severity: WARNING + - id: lambda-in-func-name + languages: + - go + message: Do not use "Lambda" in func name inside lambda package + paths: + include: + - internal/service/lambda + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Lambda" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: lambda-in-test-name + languages: + - go + message: Include "Lambda" in test name + paths: + include: + - internal/service/lambda/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccLambda" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: lambda-in-const-name + languages: + - go + message: Do not use "Lambda" in const name inside lambda package + paths: + include: + - internal/service/lambda + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Lambda" + severity: WARNING + - id: lambda-in-var-name + languages: + - go + message: Do not use "Lambda" in var name inside lambda package + paths: + include: + - internal/service/lambda + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Lambda" + severity: WARNING + - id: lex-in-func-name + languages: + - go + message: Do not use "lex" in func name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)lex" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: lex-in-const-name + languages: + - go + message: Do not use "lex" in const name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)lex" + severity: WARNING + - id: lex-in-var-name + languages: + - go + message: Do not use "lex" in var name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)lex" + severity: WARNING + - id: lexmodelbuilding-in-func-name + languages: + - go + message: Do not use "lexmodelbuilding" in func name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)lexmodelbuilding" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: lexmodelbuilding-in-const-name + languages: + - go + message: Do not use "lexmodelbuilding" in const name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)lexmodelbuilding" + severity: WARNING + - id: lexmodelbuilding-in-var-name + languages: + - go + message: Do not use "lexmodelbuilding" in var name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)lexmodelbuilding" + severity: WARNING + - id: lexmodelbuildingservice-in-func-name + languages: + - go + message: Do not use "lexmodelbuildingservice" in func name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)lexmodelbuildingservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: lexmodelbuildingservice-in-const-name + languages: + - go + message: Do not use "lexmodelbuildingservice" in const name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)lexmodelbuildingservice" + severity: WARNING + - id: lexmodelbuildingservice-in-var-name + languages: + - go + message: Do not use "lexmodelbuildingservice" in var name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)lexmodelbuildingservice" + severity: WARNING + - id: lexmodels-in-func-name + languages: + - go + message: Do not use "LexModels" in func name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)LexModels" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: lexmodels-in-test-name + languages: + - go + message: Include "LexModels" in test name + paths: + include: + - internal/service/lexmodels/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccLexModels" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: lexmodels-in-const-name + languages: + - go + message: Do not use "LexModels" in const name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)LexModels" + severity: WARNING + - id: lexmodels-in-var-name + languages: + - go + message: Do not use "LexModels" in var name inside lexmodels package + paths: + include: + - internal/service/lexmodels + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)LexModels" + severity: WARNING + - id: licensemanager-in-func-name + languages: + - go + message: Do not use "LicenseManager" in func name inside licensemanager package + paths: + include: + - internal/service/licensemanager + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)LicenseManager" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: licensemanager-in-test-name + languages: + - go + message: Include "LicenseManager" in test name + paths: + include: + - internal/service/licensemanager/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccLicenseManager" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: licensemanager-in-const-name + languages: + - go + message: Do not use "LicenseManager" in const name inside licensemanager package + paths: + include: + - internal/service/licensemanager + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)LicenseManager" + severity: WARNING + - id: licensemanager-in-var-name + languages: + - go + message: Do not use "LicenseManager" in var name inside licensemanager package + paths: + include: + - internal/service/licensemanager + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)LicenseManager" + severity: WARNING + - id: lightsail-in-func-name + languages: + - go + message: Do not use "Lightsail" in func name inside lightsail package + paths: + include: + - internal/service/lightsail + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Lightsail" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: lightsail-in-test-name + languages: + - go + message: Include "Lightsail" in test name + paths: + include: + - internal/service/lightsail/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccLightsail" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: lightsail-in-const-name + languages: + - go + message: Do not use "Lightsail" in const name inside lightsail package + paths: + include: + - internal/service/lightsail + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Lightsail" + severity: WARNING + - id: lightsail-in-var-name + languages: + - go + message: Do not use "Lightsail" in var name inside lightsail package + paths: + include: + - internal/service/lightsail + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Lightsail" + severity: WARNING + - id: location-in-func-name + languages: + - go + message: Do not use "Location" in func name inside location package + paths: + include: + - internal/service/location + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Location" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: location-in-test-name + languages: + - go + message: Include "Location" in test name + paths: + include: + - internal/service/location/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccLocation" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: location-in-const-name + languages: + - go + message: Do not use "Location" in const name inside location package + paths: + include: + - internal/service/location + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Location" + severity: WARNING + - id: location-in-var-name + languages: + - go + message: Do not use "Location" in var name inside location package + paths: + include: + - internal/service/location + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Location" + severity: WARNING + - id: locationservice-in-func-name + languages: + - go + message: Do not use "locationservice" in func name inside location package + paths: + include: + - internal/service/location + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)locationservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: locationservice-in-const-name + languages: + - go + message: Do not use "locationservice" in const name inside location package + paths: + include: + - internal/service/location + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)locationservice" + severity: WARNING + - id: locationservice-in-var-name + languages: + - go + message: Do not use "locationservice" in var name inside location package + paths: + include: + - internal/service/location + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)locationservice" + severity: WARNING + - id: logs-in-func-name + languages: + - go + message: Do not use "Logs" in func name inside logs package + paths: + include: + - internal/service/logs + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Logs" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: logs-in-test-name + languages: + - go + message: Include "Logs" in test name + paths: + include: + - internal/service/logs/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccLogs" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: logs-in-const-name + languages: + - go + message: Do not use "Logs" in const name inside logs package + paths: + include: + - internal/service/logs + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Logs" + severity: WARNING + - id: logs-in-var-name + languages: + - go + message: Do not use "Logs" in var name inside logs package + paths: + include: + - internal/service/logs + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Logs" + severity: WARNING + - id: macie-in-func-name + languages: + - go + message: Do not use "Macie" in func name inside macie package + paths: + include: + - internal/service/macie + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Macie" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: macie-in-test-name + languages: + - go + message: Include "Macie" in test name + paths: + include: + - internal/service/macie/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMacie" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: macie-in-const-name + languages: + - go + message: Do not use "Macie" in const name inside macie package + paths: + include: + - internal/service/macie + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Macie" + severity: WARNING + - id: macie-in-var-name + languages: + - go + message: Do not use "Macie" in var name inside macie package + paths: + include: + - internal/service/macie + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Macie" + severity: WARNING + - id: macie2-in-func-name + languages: + - go + message: Do not use "Macie2" in func name inside macie2 package + paths: + include: + - internal/service/macie2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Macie2" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: macie2-in-test-name + languages: + - go + message: Include "Macie2" in test name + paths: + include: + - internal/service/macie2/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMacie2" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: macie2-in-const-name + languages: + - go + message: Do not use "Macie2" in const name inside macie2 package + paths: + include: + - internal/service/macie2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Macie2" + severity: WARNING + - id: macie2-in-var-name + languages: + - go + message: Do not use "Macie2" in var name inside macie2 package + paths: + include: + - internal/service/macie2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Macie2" + severity: WARNING + - id: managedgrafana-in-func-name + languages: + - go + message: Do not use "managedgrafana" in func name inside grafana package + paths: + include: + - internal/service/grafana + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)managedgrafana" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: managedgrafana-in-const-name + languages: + - go + message: Do not use "managedgrafana" in const name inside grafana package + paths: + include: + - internal/service/grafana + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)managedgrafana" + severity: WARNING + - id: managedgrafana-in-var-name + languages: + - go + message: Do not use "managedgrafana" in var name inside grafana package + paths: + include: + - internal/service/grafana + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)managedgrafana" + severity: WARNING + - id: mediaconnect-in-func-name + languages: + - go + message: Do not use "MediaConnect" in func name inside mediaconnect package + paths: + include: + - internal/service/mediaconnect + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaConnect" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: mediaconnect-in-test-name + languages: + - go + message: Include "MediaConnect" in test name + paths: + include: + - internal/service/mediaconnect/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMediaConnect" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: mediaconnect-in-const-name + languages: + - go + message: Do not use "MediaConnect" in const name inside mediaconnect package + paths: + include: + - internal/service/mediaconnect + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaConnect" + severity: WARNING + - id: mediaconnect-in-var-name + languages: + - go + message: Do not use "MediaConnect" in var name inside mediaconnect package + paths: + include: + - internal/service/mediaconnect + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaConnect" + severity: WARNING + - id: mediaconvert-in-func-name + languages: + - go + message: Do not use "MediaConvert" in func name inside mediaconvert package + paths: + include: + - internal/service/mediaconvert + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaConvert" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: mediaconvert-in-test-name + languages: + - go + message: Include "MediaConvert" in test name + paths: + include: + - internal/service/mediaconvert/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMediaConvert" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: mediaconvert-in-const-name + languages: + - go + message: Do not use "MediaConvert" in const name inside mediaconvert package + paths: + include: + - internal/service/mediaconvert + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaConvert" + severity: WARNING + - id: mediaconvert-in-var-name + languages: + - go + message: Do not use "MediaConvert" in var name inside mediaconvert package + paths: + include: + - internal/service/mediaconvert + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaConvert" + severity: WARNING + - id: medialive-in-func-name + languages: + - go + message: Do not use "MediaLive" in func name inside medialive package + paths: + include: + - internal/service/medialive + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaLive" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: medialive-in-test-name + languages: + - go + message: Include "MediaLive" in test name + paths: + include: + - internal/service/medialive/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMediaLive" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: medialive-in-const-name + languages: + - go + message: Do not use "MediaLive" in const name inside medialive package + paths: + include: + - internal/service/medialive + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaLive" + severity: WARNING + - id: medialive-in-var-name + languages: + - go + message: Do not use "MediaLive" in var name inside medialive package + paths: + include: + - internal/service/medialive + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaLive" + severity: WARNING + - id: mediapackage-in-func-name + languages: + - go + message: Do not use "MediaPackage" in func name inside mediapackage package + paths: + include: + - internal/service/mediapackage + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaPackage" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: mediapackage-in-test-name + languages: + - go + message: Include "MediaPackage" in test name + paths: + include: + - internal/service/mediapackage/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMediaPackage" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: mediapackage-in-const-name + languages: + - go + message: Do not use "MediaPackage" in const name inside mediapackage package + paths: + include: + - internal/service/mediapackage + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaPackage" + severity: WARNING + - id: mediapackage-in-var-name + languages: + - go + message: Do not use "MediaPackage" in var name inside mediapackage package + paths: + include: + - internal/service/mediapackage + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaPackage" + severity: WARNING + - id: mediastore-in-func-name + languages: + - go + message: Do not use "MediaStore" in func name inside mediastore package + paths: + include: + - internal/service/mediastore + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaStore" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: mediastore-in-test-name + languages: + - go + message: Include "MediaStore" in test name + paths: + include: + - internal/service/mediastore/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMediaStore" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: mediastore-in-const-name + languages: + - go + message: Do not use "MediaStore" in const name inside mediastore package + paths: + include: + - internal/service/mediastore + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaStore" + severity: WARNING + - id: mediastore-in-var-name + languages: + - go + message: Do not use "MediaStore" in var name inside mediastore package + paths: + include: + - internal/service/mediastore + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MediaStore" + severity: WARNING + - id: memorydb-in-func-name + languages: + - go + message: Do not use "MemoryDB" in func name inside memorydb package + paths: + include: + - internal/service/memorydb + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MemoryDB" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: memorydb-in-test-name + languages: + - go + message: Include "MemoryDB" in test name + paths: + include: + - internal/service/memorydb/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMemoryDB" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: memorydb-in-const-name + languages: + - go + message: Do not use "MemoryDB" in const name inside memorydb package + paths: + include: + - internal/service/memorydb + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MemoryDB" + severity: WARNING + - id: memorydb-in-var-name + languages: + - go + message: Do not use "MemoryDB" in var name inside memorydb package + paths: + include: + - internal/service/memorydb + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MemoryDB" + severity: WARNING + - id: meta-in-func-name + languages: + - go + message: Do not use "Meta" in func name inside meta package + paths: + include: + - internal/service/meta + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Meta" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: meta-in-test-name + languages: + - go + message: Include "Meta" in test name + paths: + include: + - internal/service/meta/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMeta" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: meta-in-const-name + languages: + - go + message: Do not use "Meta" in const name inside meta package + paths: + include: + - internal/service/meta + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Meta" + severity: WARNING + - id: meta-in-var-name + languages: + - go + message: Do not use "Meta" in var name inside meta package + paths: + include: + - internal/service/meta + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Meta" + severity: WARNING + - id: mq-in-func-name + languages: + - go + message: Do not use "MQ" in func name inside mq package + paths: + include: + - internal/service/mq + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MQ" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: mq-in-test-name + languages: + - go + message: Include "MQ" in test name + paths: + include: + - internal/service/mq/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMQ" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: mq-in-const-name + languages: + - go + message: Do not use "MQ" in const name inside mq package + paths: + include: + - internal/service/mq + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MQ" + severity: WARNING + - id: mq-in-var-name + languages: + - go + message: Do not use "MQ" in var name inside mq package + paths: + include: + - internal/service/mq + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MQ" + severity: WARNING + - id: msk-in-func-name + languages: + - go + message: Do not use "msk" in func name inside kafka package + paths: + include: + - internal/service/kafka + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)msk" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: msk-in-const-name + languages: + - go + message: Do not use "msk" in const name inside kafka package + paths: + include: + - internal/service/kafka + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)msk" + severity: WARNING + - id: msk-in-var-name + languages: + - go + message: Do not use "msk" in var name inside kafka package + paths: + include: + - internal/service/kafka + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)msk" + severity: WARNING + - id: mwaa-in-func-name + languages: + - go + message: Do not use "MWAA" in func name inside mwaa package + paths: + include: + - internal/service/mwaa + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MWAA" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: mwaa-in-test-name + languages: + - go + message: Include "MWAA" in test name + paths: + include: + - internal/service/mwaa/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccMWAA" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: mwaa-in-const-name + languages: + - go + message: Do not use "MWAA" in const name inside mwaa package + paths: + include: + - internal/service/mwaa + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MWAA" + severity: WARNING + - id: mwaa-in-var-name + languages: + - go + message: Do not use "MWAA" in var name inside mwaa package + paths: + include: + - internal/service/mwaa + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)MWAA" + severity: WARNING + - id: neptune-in-func-name + languages: + - go + message: Do not use "Neptune" in func name inside neptune package + paths: + include: + - internal/service/neptune + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Neptune" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: neptune-in-test-name + languages: + - go + message: Include "Neptune" in test name + paths: + include: + - internal/service/neptune/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccNeptune" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: neptune-in-const-name + languages: + - go + message: Do not use "Neptune" in const name inside neptune package + paths: + include: + - internal/service/neptune + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Neptune" + severity: WARNING + - id: neptune-in-var-name + languages: + - go + message: Do not use "Neptune" in var name inside neptune package + paths: + include: + - internal/service/neptune + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Neptune" + severity: WARNING + - id: networkfirewall-in-func-name + languages: + - go + message: Do not use "NetworkFirewall" in func name inside networkfirewall package + paths: + include: + - internal/service/networkfirewall + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)NetworkFirewall" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: networkfirewall-in-test-name + languages: + - go + message: Include "NetworkFirewall" in test name + paths: + include: + - internal/service/networkfirewall/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccNetworkFirewall" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: networkfirewall-in-const-name + languages: + - go + message: Do not use "NetworkFirewall" in const name inside networkfirewall package + paths: + include: + - internal/service/networkfirewall + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)NetworkFirewall" + severity: WARNING + - id: networkfirewall-in-var-name + languages: + - go + message: Do not use "NetworkFirewall" in var name inside networkfirewall package + paths: + include: + - internal/service/networkfirewall + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)NetworkFirewall" + severity: WARNING + - id: networkmanager-in-func-name + languages: + - go + message: Do not use "NetworkManager" in func name inside networkmanager package + paths: + include: + - internal/service/networkmanager + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)NetworkManager" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: networkmanager-in-test-name + languages: + - go + message: Include "NetworkManager" in test name + paths: + include: + - internal/service/networkmanager/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccNetworkManager" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: networkmanager-in-const-name + languages: + - go + message: Do not use "NetworkManager" in const name inside networkmanager package + paths: + include: + - internal/service/networkmanager + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)NetworkManager" + severity: WARNING + - id: networkmanager-in-var-name + languages: + - go + message: Do not use "NetworkManager" in var name inside networkmanager package + paths: + include: + - internal/service/networkmanager + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)NetworkManager" + severity: WARNING + - id: opensearch-in-func-name + languages: + - go + message: Do not use "OpenSearch" in func name inside opensearch package + paths: + include: + - internal/service/opensearch + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)OpenSearch" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: opensearch-in-test-name + languages: + - go + message: Include "OpenSearch" in test name + paths: + include: + - internal/service/opensearch/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccOpenSearch" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: opensearch-in-const-name + languages: + - go + message: Do not use "OpenSearch" in const name inside opensearch package + paths: + include: + - internal/service/opensearch + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)OpenSearch" + severity: WARNING + - id: opensearch-in-var-name + languages: + - go + message: Do not use "OpenSearch" in var name inside opensearch package + paths: + include: + - internal/service/opensearch + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)OpenSearch" + severity: WARNING + - id: opensearchservice-in-func-name + languages: + - go + message: Do not use "opensearchservice" in func name inside opensearch package + paths: + include: + - internal/service/opensearch + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)opensearchservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: opensearchservice-in-const-name + languages: + - go + message: Do not use "opensearchservice" in const name inside opensearch package + paths: + include: + - internal/service/opensearch + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)opensearchservice" + severity: WARNING + - id: opensearchservice-in-var-name + languages: + - go + message: Do not use "opensearchservice" in var name inside opensearch package + paths: + include: + - internal/service/opensearch + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)opensearchservice" + severity: WARNING + - id: opsworks-in-func-name + languages: + - go + message: Do not use "OpsWorks" in func name inside opsworks package + paths: + include: + - internal/service/opsworks + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)OpsWorks" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: opsworks-in-test-name + languages: + - go + message: Include "OpsWorks" in test name + paths: + include: + - internal/service/opsworks/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccOpsWorks" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: opsworks-in-const-name + languages: + - go + message: Do not use "OpsWorks" in const name inside opsworks package + paths: + include: + - internal/service/opsworks + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)OpsWorks" + severity: WARNING + - id: opsworks-in-var-name + languages: + - go + message: Do not use "OpsWorks" in var name inside opsworks package + paths: + include: + - internal/service/opsworks + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)OpsWorks" + severity: WARNING + - id: organizations-in-func-name + languages: + - go + message: Do not use "Organizations" in func name inside organizations package + paths: + include: + - internal/service/organizations + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Organizations" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: organizations-in-test-name + languages: + - go + message: Include "Organizations" in test name + paths: + include: + - internal/service/organizations/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccOrganizations" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: organizations-in-const-name + languages: + - go + message: Do not use "Organizations" in const name inside organizations package + paths: + include: + - internal/service/organizations + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Organizations" + severity: WARNING + - id: organizations-in-var-name + languages: + - go + message: Do not use "Organizations" in var name inside organizations package + paths: + include: + - internal/service/organizations + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Organizations" + severity: WARNING + - id: outposts-in-func-name + languages: + - go + message: Do not use "Outposts" in func name inside outposts package + paths: + include: + - internal/service/outposts + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Outposts" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: outposts-in-test-name + languages: + - go + message: Include "Outposts" in test name + paths: + include: + - internal/service/outposts/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccOutposts" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: outposts-in-const-name + languages: + - go + message: Do not use "Outposts" in const name inside outposts package + paths: + include: + - internal/service/outposts + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Outposts" + severity: WARNING + - id: outposts-in-var-name + languages: + - go + message: Do not use "Outposts" in var name inside outposts package + paths: + include: + - internal/service/outposts + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Outposts" + severity: WARNING + - id: pinpoint-in-func-name + languages: + - go + message: Do not use "Pinpoint" in func name inside pinpoint package + paths: + include: + - internal/service/pinpoint + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Pinpoint" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: pinpoint-in-test-name + languages: + - go + message: Include "Pinpoint" in test name + paths: + include: + - internal/service/pinpoint/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccPinpoint" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: pinpoint-in-const-name + languages: + - go + message: Do not use "Pinpoint" in const name inside pinpoint package + paths: + include: + - internal/service/pinpoint + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Pinpoint" + severity: WARNING + - id: pinpoint-in-var-name + languages: + - go + message: Do not use "Pinpoint" in var name inside pinpoint package + paths: + include: + - internal/service/pinpoint + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Pinpoint" + severity: WARNING + - id: pricing-in-func-name + languages: + - go + message: Do not use "Pricing" in func name inside pricing package + paths: + include: + - internal/service/pricing + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Pricing" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: pricing-in-test-name + languages: + - go + message: Include "Pricing" in test name + paths: + include: + - internal/service/pricing/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccPricing" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: pricing-in-const-name + languages: + - go + message: Do not use "Pricing" in const name inside pricing package + paths: + include: + - internal/service/pricing + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Pricing" + severity: WARNING + - id: pricing-in-var-name + languages: + - go + message: Do not use "Pricing" in var name inside pricing package + paths: + include: + - internal/service/pricing + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Pricing" + severity: WARNING + - id: prometheus-in-func-name + languages: + - go + message: Do not use "prometheus" in func name inside amp package + paths: + include: + - internal/service/amp + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)prometheus" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: prometheus-in-const-name + languages: + - go + message: Do not use "prometheus" in const name inside amp package + paths: + include: + - internal/service/amp + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)prometheus" + severity: WARNING + - id: prometheus-in-var-name + languages: + - go + message: Do not use "prometheus" in var name inside amp package + paths: + include: + - internal/service/amp + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)prometheus" + severity: WARNING + - id: prometheusservice-in-func-name + languages: + - go + message: Do not use "prometheusservice" in func name inside amp package + paths: + include: + - internal/service/amp + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)prometheusservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: prometheusservice-in-const-name + languages: + - go + message: Do not use "prometheusservice" in const name inside amp package + paths: + include: + - internal/service/amp + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)prometheusservice" + severity: WARNING + - id: prometheusservice-in-var-name + languages: + - go + message: Do not use "prometheusservice" in var name inside amp package + paths: + include: + - internal/service/amp + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)prometheusservice" + severity: WARNING + - id: qldb-in-func-name + languages: + - go + message: Do not use "QLDB" in func name inside qldb package + paths: + include: + - internal/service/qldb + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)QLDB" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: qldb-in-test-name + languages: + - go + message: Include "QLDB" in test name + paths: + include: + - internal/service/qldb/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccQLDB" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: qldb-in-const-name + languages: + - go + message: Do not use "QLDB" in const name inside qldb package + paths: + include: + - internal/service/qldb + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)QLDB" + severity: WARNING + - id: qldb-in-var-name + languages: + - go + message: Do not use "QLDB" in var name inside qldb package + paths: + include: + - internal/service/qldb + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)QLDB" + severity: WARNING + - id: quicksight-in-func-name + languages: + - go + message: Do not use "QuickSight" in func name inside quicksight package + paths: + include: + - internal/service/quicksight + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)QuickSight" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: quicksight-in-test-name + languages: + - go + message: Include "QuickSight" in test name + paths: + include: + - internal/service/quicksight/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccQuickSight" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: quicksight-in-const-name + languages: + - go + message: Do not use "QuickSight" in const name inside quicksight package + paths: + include: + - internal/service/quicksight + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)QuickSight" + severity: WARNING + - id: quicksight-in-var-name + languages: + - go + message: Do not use "QuickSight" in var name inside quicksight package + paths: + include: + - internal/service/quicksight + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)QuickSight" + severity: WARNING + - id: ram-in-func-name + languages: + - go + message: Do not use "RAM" in func name inside ram package + paths: + include: + - internal/service/ram + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RAM" + - pattern-not-regex: ^TestAcc.* + severity: WARNING diff --git a/.semgrep-service-name3.yml b/.semgrep-service-name3.yml new file mode 100644 index 00000000000..6839cf7c37a --- /dev/null +++ b/.semgrep-service-name3.yml @@ -0,0 +1,2915 @@ +# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. +rules: + - id: ram-in-test-name + languages: + - go + message: Include "RAM" in test name + paths: + include: + - internal/service/ram/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRAM" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ram-in-const-name + languages: + - go + message: Do not use "RAM" in const name inside ram package + paths: + include: + - internal/service/ram + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RAM" + severity: WARNING + - id: ram-in-var-name + languages: + - go + message: Do not use "RAM" in var name inside ram package + paths: + include: + - internal/service/ram + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RAM" + severity: WARNING + - id: rds-in-func-name + languages: + - go + message: Do not use "RDS" in func name inside rds package + paths: + include: + - internal/service/rds + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RDS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: rds-in-test-name + languages: + - go + message: Include "RDS" in test name + paths: + include: + - internal/service/rds/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRDS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: rds-in-const-name + languages: + - go + message: Do not use "RDS" in const name inside rds package + paths: + include: + - internal/service/rds + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RDS" + severity: WARNING + - id: rds-in-var-name + languages: + - go + message: Do not use "RDS" in var name inside rds package + paths: + include: + - internal/service/rds + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RDS" + severity: WARNING + - id: redshift-in-func-name + languages: + - go + message: Do not use "Redshift" in func name inside redshift package + paths: + include: + - internal/service/redshift + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Redshift" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: redshift-in-test-name + languages: + - go + message: Include "Redshift" in test name + paths: + include: + - internal/service/redshift/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRedshift" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: redshift-in-const-name + languages: + - go + message: Do not use "Redshift" in const name inside redshift package + paths: + include: + - internal/service/redshift + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Redshift" + severity: WARNING + - id: redshift-in-var-name + languages: + - go + message: Do not use "Redshift" in var name inside redshift package + paths: + include: + - internal/service/redshift + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Redshift" + severity: WARNING + - id: redshiftdata-in-func-name + languages: + - go + message: Do not use "RedshiftData" in func name inside redshiftdata package + paths: + include: + - internal/service/redshiftdata + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RedshiftData" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: redshiftdata-in-test-name + languages: + - go + message: Include "RedshiftData" in test name + paths: + include: + - internal/service/redshiftdata/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRedshiftData" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: redshiftdata-in-const-name + languages: + - go + message: Do not use "RedshiftData" in const name inside redshiftdata package + paths: + include: + - internal/service/redshiftdata + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RedshiftData" + severity: WARNING + - id: redshiftdata-in-var-name + languages: + - go + message: Do not use "RedshiftData" in var name inside redshiftdata package + paths: + include: + - internal/service/redshiftdata + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RedshiftData" + severity: WARNING + - id: redshiftdataapiservice-in-func-name + languages: + - go + message: Do not use "redshiftdataapiservice" in func name inside redshiftdata package + paths: + include: + - internal/service/redshiftdata + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)redshiftdataapiservice" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: redshiftdataapiservice-in-const-name + languages: + - go + message: Do not use "redshiftdataapiservice" in const name inside redshiftdata package + paths: + include: + - internal/service/redshiftdata + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)redshiftdataapiservice" + severity: WARNING + - id: redshiftdataapiservice-in-var-name + languages: + - go + message: Do not use "redshiftdataapiservice" in var name inside redshiftdata package + paths: + include: + - internal/service/redshiftdata + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)redshiftdataapiservice" + severity: WARNING + - id: resourcegroups-in-func-name + languages: + - go + message: Do not use "ResourceGroups" in func name inside resourcegroups package + paths: + include: + - internal/service/resourcegroups + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ResourceGroups" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: resourcegroups-in-test-name + languages: + - go + message: Include "ResourceGroups" in test name + paths: + include: + - internal/service/resourcegroups/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccResourceGroups" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: resourcegroups-in-const-name + languages: + - go + message: Do not use "ResourceGroups" in const name inside resourcegroups package + paths: + include: + - internal/service/resourcegroups + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ResourceGroups" + severity: WARNING + - id: resourcegroups-in-var-name + languages: + - go + message: Do not use "ResourceGroups" in var name inside resourcegroups package + paths: + include: + - internal/service/resourcegroups + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ResourceGroups" + severity: WARNING + - id: resourcegroupstagging-in-func-name + languages: + - go + message: Do not use "resourcegroupstagging" in func name inside resourcegroupstaggingapi package + paths: + include: + - internal/service/resourcegroupstaggingapi + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)resourcegroupstagging" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: resourcegroupstagging-in-const-name + languages: + - go + message: Do not use "resourcegroupstagging" in const name inside resourcegroupstaggingapi package + paths: + include: + - internal/service/resourcegroupstaggingapi + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)resourcegroupstagging" + severity: WARNING + - id: resourcegroupstagging-in-var-name + languages: + - go + message: Do not use "resourcegroupstagging" in var name inside resourcegroupstaggingapi package + paths: + include: + - internal/service/resourcegroupstaggingapi + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)resourcegroupstagging" + severity: WARNING + - id: resourcegroupstaggingapi-in-func-name + languages: + - go + message: Do not use "ResourceGroupsTaggingAPI" in func name inside resourcegroupstaggingapi package + paths: + include: + - internal/service/resourcegroupstaggingapi + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ResourceGroupsTaggingAPI" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: resourcegroupstaggingapi-in-test-name + languages: + - go + message: Include "ResourceGroupsTaggingAPI" in test name + paths: + include: + - internal/service/resourcegroupstaggingapi/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccResourceGroupsTaggingAPI" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: resourcegroupstaggingapi-in-const-name + languages: + - go + message: Do not use "ResourceGroupsTaggingAPI" in const name inside resourcegroupstaggingapi package + paths: + include: + - internal/service/resourcegroupstaggingapi + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ResourceGroupsTaggingAPI" + severity: WARNING + - id: resourcegroupstaggingapi-in-var-name + languages: + - go + message: Do not use "ResourceGroupsTaggingAPI" in var name inside resourcegroupstaggingapi package + paths: + include: + - internal/service/resourcegroupstaggingapi + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ResourceGroupsTaggingAPI" + severity: WARNING + - id: route53-in-func-name + languages: + - go + message: Do not use "Route53" in func name inside route53 package + paths: + include: + - internal/service/route53 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: route53-in-test-name + languages: + - go + message: Include "Route53" in test name + paths: + include: + - internal/service/route53/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRoute53" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: route53-in-const-name + languages: + - go + message: Do not use "Route53" in const name inside route53 package + paths: + include: + - internal/service/route53 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53" + severity: WARNING + - id: route53-in-var-name + languages: + - go + message: Do not use "Route53" in var name inside route53 package + paths: + include: + - internal/service/route53 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53" + severity: WARNING + - id: route53domains-in-func-name + languages: + - go + message: Do not use "Route53Domains" in func name inside route53domains package + paths: + include: + - internal/service/route53domains + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53Domains" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: route53domains-in-test-name + languages: + - go + message: Include "Route53Domains" in test name + paths: + include: + - internal/service/route53domains/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRoute53Domains" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: route53domains-in-const-name + languages: + - go + message: Do not use "Route53Domains" in const name inside route53domains package + paths: + include: + - internal/service/route53domains + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53Domains" + severity: WARNING + - id: route53domains-in-var-name + languages: + - go + message: Do not use "Route53Domains" in var name inside route53domains package + paths: + include: + - internal/service/route53domains + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53Domains" + severity: WARNING + - id: route53recoverycontrolconfig-in-func-name + languages: + - go + message: Do not use "Route53RecoveryControlConfig" in func name inside route53recoverycontrolconfig package + paths: + include: + - internal/service/route53recoverycontrolconfig + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53RecoveryControlConfig" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: route53recoverycontrolconfig-in-test-name + languages: + - go + message: Include "Route53RecoveryControlConfig" in test name + paths: + include: + - internal/service/route53recoverycontrolconfig/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRoute53RecoveryControlConfig" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: route53recoverycontrolconfig-in-const-name + languages: + - go + message: Do not use "Route53RecoveryControlConfig" in const name inside route53recoverycontrolconfig package + paths: + include: + - internal/service/route53recoverycontrolconfig + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53RecoveryControlConfig" + severity: WARNING + - id: route53recoverycontrolconfig-in-var-name + languages: + - go + message: Do not use "Route53RecoveryControlConfig" in var name inside route53recoverycontrolconfig package + paths: + include: + - internal/service/route53recoverycontrolconfig + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53RecoveryControlConfig" + severity: WARNING + - id: route53recoveryreadiness-in-func-name + languages: + - go + message: Do not use "Route53RecoveryReadiness" in func name inside route53recoveryreadiness package + paths: + include: + - internal/service/route53recoveryreadiness + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53RecoveryReadiness" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: route53recoveryreadiness-in-test-name + languages: + - go + message: Include "Route53RecoveryReadiness" in test name + paths: + include: + - internal/service/route53recoveryreadiness/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRoute53RecoveryReadiness" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: route53recoveryreadiness-in-const-name + languages: + - go + message: Do not use "Route53RecoveryReadiness" in const name inside route53recoveryreadiness package + paths: + include: + - internal/service/route53recoveryreadiness + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53RecoveryReadiness" + severity: WARNING + - id: route53recoveryreadiness-in-var-name + languages: + - go + message: Do not use "Route53RecoveryReadiness" in var name inside route53recoveryreadiness package + paths: + include: + - internal/service/route53recoveryreadiness + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53RecoveryReadiness" + severity: WARNING + - id: route53resolver-in-func-name + languages: + - go + message: Do not use "Route53Resolver" in func name inside route53resolver package + paths: + include: + - internal/service/route53resolver + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53Resolver" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: route53resolver-in-test-name + languages: + - go + message: Include "Route53Resolver" in test name + paths: + include: + - internal/service/route53resolver/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRoute53Resolver" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: route53resolver-in-const-name + languages: + - go + message: Do not use "Route53Resolver" in const name inside route53resolver package + paths: + include: + - internal/service/route53resolver + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53Resolver" + severity: WARNING + - id: route53resolver-in-var-name + languages: + - go + message: Do not use "Route53Resolver" in var name inside route53resolver package + paths: + include: + - internal/service/route53resolver + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Route53Resolver" + severity: WARNING + - id: rum-in-func-name + languages: + - go + message: Do not use "RUM" in func name inside rum package + paths: + include: + - internal/service/rum + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RUM" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: rum-in-test-name + languages: + - go + message: Include "RUM" in test name + paths: + include: + - internal/service/rum/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccRUM" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: rum-in-const-name + languages: + - go + message: Do not use "RUM" in const name inside rum package + paths: + include: + - internal/service/rum + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RUM" + severity: WARNING + - id: rum-in-var-name + languages: + - go + message: Do not use "RUM" in var name inside rum package + paths: + include: + - internal/service/rum + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)RUM" + severity: WARNING + - id: s3-in-func-name + languages: + - go + message: Do not use "S3" in func name inside s3 package + paths: + include: + - internal/service/s3 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)S3" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: s3-in-test-name + languages: + - go + message: Include "S3" in test name + paths: + include: + - internal/service/s3/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccS3" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: s3-in-const-name + languages: + - go + message: Do not use "S3" in const name inside s3 package + paths: + include: + - internal/service/s3 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)S3" + severity: WARNING + - id: s3-in-var-name + languages: + - go + message: Do not use "S3" in var name inside s3 package + paths: + include: + - internal/service/s3 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)S3" + severity: WARNING + - id: s3api-in-func-name + languages: + - go + message: Do not use "s3api" in func name inside s3 package + paths: + include: + - internal/service/s3 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)s3api" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: s3api-in-const-name + languages: + - go + message: Do not use "s3api" in const name inside s3 package + paths: + include: + - internal/service/s3 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)s3api" + severity: WARNING + - id: s3api-in-var-name + languages: + - go + message: Do not use "s3api" in var name inside s3 package + paths: + include: + - internal/service/s3 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)s3api" + severity: WARNING + - id: s3control-in-func-name + languages: + - go + message: Do not use "S3Control" in func name inside s3control package + paths: + include: + - internal/service/s3control + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)S3Control" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: s3control-in-test-name + languages: + - go + message: Include "S3Control" in test name + paths: + include: + - internal/service/s3control/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccS3Control" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: s3control-in-const-name + languages: + - go + message: Do not use "S3Control" in const name inside s3control package + paths: + include: + - internal/service/s3control + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)S3Control" + severity: WARNING + - id: s3control-in-var-name + languages: + - go + message: Do not use "S3Control" in var name inside s3control package + paths: + include: + - internal/service/s3control + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)S3Control" + severity: WARNING + - id: s3outposts-in-func-name + languages: + - go + message: Do not use "S3Outposts" in func name inside s3outposts package + paths: + include: + - internal/service/s3outposts + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)S3Outposts" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: s3outposts-in-test-name + languages: + - go + message: Include "S3Outposts" in test name + paths: + include: + - internal/service/s3outposts/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccS3Outposts" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: s3outposts-in-const-name + languages: + - go + message: Do not use "S3Outposts" in const name inside s3outposts package + paths: + include: + - internal/service/s3outposts + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)S3Outposts" + severity: WARNING + - id: s3outposts-in-var-name + languages: + - go + message: Do not use "S3Outposts" in var name inside s3outposts package + paths: + include: + - internal/service/s3outposts + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)S3Outposts" + severity: WARNING + - id: sagemaker-in-func-name + languages: + - go + message: Do not use "SageMaker" in func name inside sagemaker package + paths: + include: + - internal/service/sagemaker + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SageMaker" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: sagemaker-in-test-name + languages: + - go + message: Include "SageMaker" in test name + paths: + include: + - internal/service/sagemaker/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSageMaker" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: sagemaker-in-const-name + languages: + - go + message: Do not use "SageMaker" in const name inside sagemaker package + paths: + include: + - internal/service/sagemaker + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SageMaker" + severity: WARNING + - id: sagemaker-in-var-name + languages: + - go + message: Do not use "SageMaker" in var name inside sagemaker package + paths: + include: + - internal/service/sagemaker + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SageMaker" + severity: WARNING + - id: schemas-in-func-name + languages: + - go + message: Do not use "Schemas" in func name inside schemas package + paths: + include: + - internal/service/schemas + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Schemas" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: schemas-in-test-name + languages: + - go + message: Include "Schemas" in test name + paths: + include: + - internal/service/schemas/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSchemas" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: schemas-in-const-name + languages: + - go + message: Do not use "Schemas" in const name inside schemas package + paths: + include: + - internal/service/schemas + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Schemas" + severity: WARNING + - id: schemas-in-var-name + languages: + - go + message: Do not use "Schemas" in var name inside schemas package + paths: + include: + - internal/service/schemas + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Schemas" + severity: WARNING + - id: sdb-in-func-name + languages: + - go + message: Do not use "sdb" in func name inside simpledb package + paths: + include: + - internal/service/simpledb + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)sdb" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: sdb-in-const-name + languages: + - go + message: Do not use "sdb" in const name inside simpledb package + paths: + include: + - internal/service/simpledb + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)sdb" + severity: WARNING + - id: sdb-in-var-name + languages: + - go + message: Do not use "sdb" in var name inside simpledb package + paths: + include: + - internal/service/simpledb + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)sdb" + severity: WARNING + - id: secretsmanager-in-func-name + languages: + - go + message: Do not use "SecretsManager" in func name inside secretsmanager package + paths: + include: + - internal/service/secretsmanager + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SecretsManager" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: secretsmanager-in-test-name + languages: + - go + message: Include "SecretsManager" in test name + paths: + include: + - internal/service/secretsmanager/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSecretsManager" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: secretsmanager-in-const-name + languages: + - go + message: Do not use "SecretsManager" in const name inside secretsmanager package + paths: + include: + - internal/service/secretsmanager + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SecretsManager" + severity: WARNING + - id: secretsmanager-in-var-name + languages: + - go + message: Do not use "SecretsManager" in var name inside secretsmanager package + paths: + include: + - internal/service/secretsmanager + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SecretsManager" + severity: WARNING + - id: securityhub-in-func-name + languages: + - go + message: Do not use "SecurityHub" in func name inside securityhub package + paths: + include: + - internal/service/securityhub + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SecurityHub" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: securityhub-in-test-name + languages: + - go + message: Include "SecurityHub" in test name + paths: + include: + - internal/service/securityhub/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSecurityHub" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: securityhub-in-const-name + languages: + - go + message: Do not use "SecurityHub" in const name inside securityhub package + paths: + include: + - internal/service/securityhub + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SecurityHub" + severity: WARNING + - id: securityhub-in-var-name + languages: + - go + message: Do not use "SecurityHub" in var name inside securityhub package + paths: + include: + - internal/service/securityhub + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SecurityHub" + severity: WARNING + - id: serverlessapplicationrepository-in-func-name + languages: + - go + message: Do not use "serverlessapplicationrepository" in func name inside serverlessrepo package + paths: + include: + - internal/service/serverlessrepo + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)serverlessapplicationrepository" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: serverlessapplicationrepository-in-const-name + languages: + - go + message: Do not use "serverlessapplicationrepository" in const name inside serverlessrepo package + paths: + include: + - internal/service/serverlessrepo + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)serverlessapplicationrepository" + severity: WARNING + - id: serverlessapplicationrepository-in-var-name + languages: + - go + message: Do not use "serverlessapplicationrepository" in var name inside serverlessrepo package + paths: + include: + - internal/service/serverlessrepo + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)serverlessapplicationrepository" + severity: WARNING + - id: serverlessapprepo-in-func-name + languages: + - go + message: Do not use "serverlessapprepo" in func name inside serverlessrepo package + paths: + include: + - internal/service/serverlessrepo + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)serverlessapprepo" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: serverlessapprepo-in-const-name + languages: + - go + message: Do not use "serverlessapprepo" in const name inside serverlessrepo package + paths: + include: + - internal/service/serverlessrepo + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)serverlessapprepo" + severity: WARNING + - id: serverlessapprepo-in-var-name + languages: + - go + message: Do not use "serverlessapprepo" in var name inside serverlessrepo package + paths: + include: + - internal/service/serverlessrepo + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)serverlessapprepo" + severity: WARNING + - id: serverlessrepo-in-func-name + languages: + - go + message: Do not use "ServerlessRepo" in func name inside serverlessrepo package + paths: + include: + - internal/service/serverlessrepo + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServerlessRepo" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: serverlessrepo-in-test-name + languages: + - go + message: Include "ServerlessRepo" in test name + paths: + include: + - internal/service/serverlessrepo/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccServerlessRepo" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: serverlessrepo-in-const-name + languages: + - go + message: Do not use "ServerlessRepo" in const name inside serverlessrepo package + paths: + include: + - internal/service/serverlessrepo + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServerlessRepo" + severity: WARNING + - id: serverlessrepo-in-var-name + languages: + - go + message: Do not use "ServerlessRepo" in var name inside serverlessrepo package + paths: + include: + - internal/service/serverlessrepo + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServerlessRepo" + severity: WARNING + - id: servicecatalog-in-func-name + languages: + - go + message: Do not use "ServiceCatalog" in func name inside servicecatalog package + paths: + include: + - internal/service/servicecatalog + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServiceCatalog" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: servicecatalog-in-test-name + languages: + - go + message: Include "ServiceCatalog" in test name + paths: + include: + - internal/service/servicecatalog/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccServiceCatalog" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: servicecatalog-in-const-name + languages: + - go + message: Do not use "ServiceCatalog" in const name inside servicecatalog package + paths: + include: + - internal/service/servicecatalog + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServiceCatalog" + severity: WARNING + - id: servicecatalog-in-var-name + languages: + - go + message: Do not use "ServiceCatalog" in var name inside servicecatalog package + paths: + include: + - internal/service/servicecatalog + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServiceCatalog" + severity: WARNING + - id: servicediscovery-in-func-name + languages: + - go + message: Do not use "ServiceDiscovery" in func name inside servicediscovery package + paths: + include: + - internal/service/servicediscovery + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServiceDiscovery" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: servicediscovery-in-test-name + languages: + - go + message: Include "ServiceDiscovery" in test name + paths: + include: + - internal/service/servicediscovery/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccServiceDiscovery" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: servicediscovery-in-const-name + languages: + - go + message: Do not use "ServiceDiscovery" in const name inside servicediscovery package + paths: + include: + - internal/service/servicediscovery + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServiceDiscovery" + severity: WARNING + - id: servicediscovery-in-var-name + languages: + - go + message: Do not use "ServiceDiscovery" in var name inside servicediscovery package + paths: + include: + - internal/service/servicediscovery + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServiceDiscovery" + severity: WARNING + - id: servicequotas-in-func-name + languages: + - go + message: Do not use "ServiceQuotas" in func name inside servicequotas package + paths: + include: + - internal/service/servicequotas + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServiceQuotas" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: servicequotas-in-test-name + languages: + - go + message: Include "ServiceQuotas" in test name + paths: + include: + - internal/service/servicequotas/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccServiceQuotas" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: servicequotas-in-const-name + languages: + - go + message: Do not use "ServiceQuotas" in const name inside servicequotas package + paths: + include: + - internal/service/servicequotas + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServiceQuotas" + severity: WARNING + - id: servicequotas-in-var-name + languages: + - go + message: Do not use "ServiceQuotas" in var name inside servicequotas package + paths: + include: + - internal/service/servicequotas + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)ServiceQuotas" + severity: WARNING + - id: ses-in-func-name + languages: + - go + message: Do not use "SES" in func name inside ses package + paths: + include: + - internal/service/ses + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SES" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ses-in-test-name + languages: + - go + message: Include "SES" in test name + paths: + include: + - internal/service/ses/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSES" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ses-in-const-name + languages: + - go + message: Do not use "SES" in const name inside ses package + paths: + include: + - internal/service/ses + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SES" + severity: WARNING + - id: ses-in-var-name + languages: + - go + message: Do not use "SES" in var name inside ses package + paths: + include: + - internal/service/ses + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SES" + severity: WARNING + - id: sfn-in-func-name + languages: + - go + message: Do not use "SFN" in func name inside sfn package + paths: + include: + - internal/service/sfn + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SFN" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: sfn-in-test-name + languages: + - go + message: Include "SFN" in test name + paths: + include: + - internal/service/sfn/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSFN" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: sfn-in-const-name + languages: + - go + message: Do not use "SFN" in const name inside sfn package + paths: + include: + - internal/service/sfn + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SFN" + severity: WARNING + - id: sfn-in-var-name + languages: + - go + message: Do not use "SFN" in var name inside sfn package + paths: + include: + - internal/service/sfn + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SFN" + severity: WARNING + - id: shield-in-func-name + languages: + - go + message: Do not use "Shield" in func name inside shield package + paths: + include: + - internal/service/shield + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Shield" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: shield-in-test-name + languages: + - go + message: Include "Shield" in test name + paths: + include: + - internal/service/shield/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccShield" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: shield-in-const-name + languages: + - go + message: Do not use "Shield" in const name inside shield package + paths: + include: + - internal/service/shield + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Shield" + severity: WARNING + - id: shield-in-var-name + languages: + - go + message: Do not use "Shield" in var name inside shield package + paths: + include: + - internal/service/shield + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Shield" + severity: WARNING + - id: signer-in-func-name + languages: + - go + message: Do not use "Signer" in func name inside signer package + paths: + include: + - internal/service/signer + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Signer" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: signer-in-test-name + languages: + - go + message: Include "Signer" in test name + paths: + include: + - internal/service/signer/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSigner" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: signer-in-const-name + languages: + - go + message: Do not use "Signer" in const name inside signer package + paths: + include: + - internal/service/signer + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Signer" + severity: WARNING + - id: signer-in-var-name + languages: + - go + message: Do not use "Signer" in var name inside signer package + paths: + include: + - internal/service/signer + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Signer" + severity: WARNING + - id: simpledb-in-func-name + languages: + - go + message: Do not use "SimpleDB" in func name inside simpledb package + paths: + include: + - internal/service/simpledb + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SimpleDB" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: simpledb-in-test-name + languages: + - go + message: Include "SimpleDB" in test name + paths: + include: + - internal/service/simpledb/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSimpleDB" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: simpledb-in-const-name + languages: + - go + message: Do not use "SimpleDB" in const name inside simpledb package + paths: + include: + - internal/service/simpledb + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SimpleDB" + severity: WARNING + - id: simpledb-in-var-name + languages: + - go + message: Do not use "SimpleDB" in var name inside simpledb package + paths: + include: + - internal/service/simpledb + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SimpleDB" + severity: WARNING + - id: sns-in-func-name + languages: + - go + message: Do not use "SNS" in func name inside sns package + paths: + include: + - internal/service/sns + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SNS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: sns-in-test-name + languages: + - go + message: Include "SNS" in test name + paths: + include: + - internal/service/sns/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSNS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: sns-in-const-name + languages: + - go + message: Do not use "SNS" in const name inside sns package + paths: + include: + - internal/service/sns + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SNS" + severity: WARNING + - id: sns-in-var-name + languages: + - go + message: Do not use "SNS" in var name inside sns package + paths: + include: + - internal/service/sns + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SNS" + severity: WARNING + - id: sqs-in-func-name + languages: + - go + message: Do not use "SQS" in func name inside sqs package + paths: + include: + - internal/service/sqs + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SQS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: sqs-in-test-name + languages: + - go + message: Include "SQS" in test name + paths: + include: + - internal/service/sqs/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSQS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: sqs-in-const-name + languages: + - go + message: Do not use "SQS" in const name inside sqs package + paths: + include: + - internal/service/sqs + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SQS" + severity: WARNING + - id: sqs-in-var-name + languages: + - go + message: Do not use "SQS" in var name inside sqs package + paths: + include: + - internal/service/sqs + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SQS" + severity: WARNING + - id: ssm-in-func-name + languages: + - go + message: Do not use "SSM" in func name inside ssm package + paths: + include: + - internal/service/ssm + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SSM" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ssm-in-test-name + languages: + - go + message: Include "SSM" in test name + paths: + include: + - internal/service/ssm/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSSM" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ssm-in-const-name + languages: + - go + message: Do not use "SSM" in const name inside ssm package + paths: + include: + - internal/service/ssm + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SSM" + severity: WARNING + - id: ssm-in-var-name + languages: + - go + message: Do not use "SSM" in var name inside ssm package + paths: + include: + - internal/service/ssm + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SSM" + severity: WARNING + - id: ssoadmin-in-func-name + languages: + - go + message: Do not use "SSOAdmin" in func name inside ssoadmin package + paths: + include: + - internal/service/ssoadmin + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SSOAdmin" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ssoadmin-in-test-name + languages: + - go + message: Include "SSOAdmin" in test name + paths: + include: + - internal/service/ssoadmin/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSSOAdmin" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: ssoadmin-in-const-name + languages: + - go + message: Do not use "SSOAdmin" in const name inside ssoadmin package + paths: + include: + - internal/service/ssoadmin + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SSOAdmin" + severity: WARNING + - id: ssoadmin-in-var-name + languages: + - go + message: Do not use "SSOAdmin" in var name inside ssoadmin package + paths: + include: + - internal/service/ssoadmin + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SSOAdmin" + severity: WARNING + - id: stepfunctions-in-func-name + languages: + - go + message: Do not use "stepfunctions" in func name inside sfn package + paths: + include: + - internal/service/sfn + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)stepfunctions" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: stepfunctions-in-const-name + languages: + - go + message: Do not use "stepfunctions" in const name inside sfn package + paths: + include: + - internal/service/sfn + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)stepfunctions" + severity: WARNING + - id: stepfunctions-in-var-name + languages: + - go + message: Do not use "stepfunctions" in var name inside sfn package + paths: + include: + - internal/service/sfn + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)stepfunctions" + severity: WARNING + - id: storagegateway-in-func-name + languages: + - go + message: Do not use "StorageGateway" in func name inside storagegateway package + paths: + include: + - internal/service/storagegateway + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)StorageGateway" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: storagegateway-in-test-name + languages: + - go + message: Include "StorageGateway" in test name + paths: + include: + - internal/service/storagegateway/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccStorageGateway" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: storagegateway-in-const-name + languages: + - go + message: Do not use "StorageGateway" in const name inside storagegateway package + paths: + include: + - internal/service/storagegateway + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)StorageGateway" + severity: WARNING + - id: storagegateway-in-var-name + languages: + - go + message: Do not use "StorageGateway" in var name inside storagegateway package + paths: + include: + - internal/service/storagegateway + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)StorageGateway" + severity: WARNING + - id: sts-in-func-name + languages: + - go + message: Do not use "STS" in func name inside sts package + paths: + include: + - internal/service/sts + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)STS" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: sts-in-test-name + languages: + - go + message: Include "STS" in test name + paths: + include: + - internal/service/sts/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSTS" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: sts-in-const-name + languages: + - go + message: Do not use "STS" in const name inside sts package + paths: + include: + - internal/service/sts + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)STS" + severity: WARNING + - id: sts-in-var-name + languages: + - go + message: Do not use "STS" in var name inside sts package + paths: + include: + - internal/service/sts + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)STS" + severity: WARNING + - id: swf-in-func-name + languages: + - go + message: Do not use "SWF" in func name inside swf package + paths: + include: + - internal/service/swf + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SWF" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: swf-in-test-name + languages: + - go + message: Include "SWF" in test name + paths: + include: + - internal/service/swf/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSWF" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: swf-in-const-name + languages: + - go + message: Do not use "SWF" in const name inside swf package + paths: + include: + - internal/service/swf + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SWF" + severity: WARNING + - id: swf-in-var-name + languages: + - go + message: Do not use "SWF" in var name inside swf package + paths: + include: + - internal/service/swf + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)SWF" + severity: WARNING + - id: synthetics-in-func-name + languages: + - go + message: Do not use "Synthetics" in func name inside synthetics package + paths: + include: + - internal/service/synthetics + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Synthetics" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: synthetics-in-test-name + languages: + - go + message: Include "Synthetics" in test name + paths: + include: + - internal/service/synthetics/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSynthetics" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: synthetics-in-const-name + languages: + - go + message: Do not use "Synthetics" in const name inside synthetics package + paths: + include: + - internal/service/synthetics + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Synthetics" + severity: WARNING + - id: synthetics-in-var-name + languages: + - go + message: Do not use "Synthetics" in var name inside synthetics package + paths: + include: + - internal/service/synthetics + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Synthetics" + severity: WARNING + - id: timestreamwrite-in-func-name + languages: + - go + message: Do not use "TimestreamWrite" in func name inside timestreamwrite package + paths: + include: + - internal/service/timestreamwrite + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)TimestreamWrite" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: timestreamwrite-in-test-name + languages: + - go + message: Include "TimestreamWrite" in test name + paths: + include: + - internal/service/timestreamwrite/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccTimestreamWrite" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: timestreamwrite-in-const-name + languages: + - go + message: Do not use "TimestreamWrite" in const name inside timestreamwrite package + paths: + include: + - internal/service/timestreamwrite + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)TimestreamWrite" + severity: WARNING + - id: timestreamwrite-in-var-name + languages: + - go + message: Do not use "TimestreamWrite" in var name inside timestreamwrite package + paths: + include: + - internal/service/timestreamwrite + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)TimestreamWrite" + severity: WARNING + - id: transfer-in-func-name + languages: + - go + message: Do not use "Transfer" in func name inside transfer package + paths: + include: + - internal/service/transfer + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Transfer" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: transfer-in-test-name + languages: + - go + message: Include "Transfer" in test name + paths: + include: + - internal/service/transfer/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccTransfer" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: transfer-in-const-name + languages: + - go + message: Do not use "Transfer" in const name inside transfer package + paths: + include: + - internal/service/transfer + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Transfer" + severity: WARNING + - id: transfer-in-var-name + languages: + - go + message: Do not use "Transfer" in var name inside transfer package + paths: + include: + - internal/service/transfer + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)Transfer" + severity: WARNING + - id: transitgateway-in-test-name + languages: + - go + message: Include "TransitGateway" in test name + paths: + include: + - internal/service/ec2/transitgateway_*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccTransitGateway" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: vpc-in-test-name + languages: + - go + message: Include "VPC" in test name + paths: + include: + - internal/service/ec2/vpc_*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccVPC" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: vpnclient-in-test-name + languages: + - go + message: Include "ClientVPN" in test name + paths: + include: + - internal/service/ec2/vpnclient_*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccClientVPN" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: vpnsite-in-test-name + languages: + - go + message: Include "SiteVPN" in test name + paths: + include: + - internal/service/ec2/vpnsite_*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccSiteVPN" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: waf-in-func-name + languages: + - go + message: Do not use "WAF" in func name inside waf package + paths: + include: + - internal/service/waf + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WAF" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: waf-in-test-name + languages: + - go + message: Include "WAF" in test name + paths: + include: + - internal/service/waf/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccWAF" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: waf-in-const-name + languages: + - go + message: Do not use "WAF" in const name inside waf package + paths: + include: + - internal/service/waf + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WAF" + severity: WARNING + - id: waf-in-var-name + languages: + - go + message: Do not use "WAF" in var name inside waf package + paths: + include: + - internal/service/waf + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WAF" + severity: WARNING + - id: wafregional-in-func-name + languages: + - go + message: Do not use "WAFRegional" in func name inside wafregional package + paths: + include: + - internal/service/wafregional + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WAFRegional" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: wafregional-in-test-name + languages: + - go + message: Include "WAFRegional" in test name + paths: + include: + - internal/service/wafregional/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccWAFRegional" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: wafregional-in-const-name + languages: + - go + message: Do not use "WAFRegional" in const name inside wafregional package + paths: + include: + - internal/service/wafregional + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WAFRegional" + severity: WARNING + - id: wafregional-in-var-name + languages: + - go + message: Do not use "WAFRegional" in var name inside wafregional package + paths: + include: + - internal/service/wafregional + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WAFRegional" + severity: WARNING + - id: wafv2-in-func-name + languages: + - go + message: Do not use "WAFV2" in func name inside wafv2 package + paths: + include: + - internal/service/wafv2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WAFV2" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: wafv2-in-test-name + languages: + - go + message: Include "WAFV2" in test name + paths: + include: + - internal/service/wafv2/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccWAFV2" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: wafv2-in-const-name + languages: + - go + message: Do not use "WAFV2" in const name inside wafv2 package + paths: + include: + - internal/service/wafv2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WAFV2" + severity: WARNING + - id: wafv2-in-var-name + languages: + - go + message: Do not use "WAFV2" in var name inside wafv2 package + paths: + include: + - internal/service/wafv2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WAFV2" + severity: WARNING + - id: wavelength-in-test-name + languages: + - go + message: Include "Wavelength" in test name + paths: + include: + - internal/service/ec2/wavelength_*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccWavelength" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: worklink-in-func-name + languages: + - go + message: Do not use "WorkLink" in func name inside worklink package + paths: + include: + - internal/service/worklink + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WorkLink" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: worklink-in-test-name + languages: + - go + message: Include "WorkLink" in test name + paths: + include: + - internal/service/worklink/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccWorkLink" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: worklink-in-const-name + languages: + - go + message: Do not use "WorkLink" in const name inside worklink package + paths: + include: + - internal/service/worklink + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WorkLink" + severity: WARNING + - id: worklink-in-var-name + languages: + - go + message: Do not use "WorkLink" in var name inside worklink package + paths: + include: + - internal/service/worklink + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WorkLink" + severity: WARNING + - id: workspaces-in-func-name + languages: + - go + message: Do not use "WorkSpaces" in func name inside workspaces package + paths: + include: + - internal/service/workspaces + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WorkSpaces" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: workspaces-in-test-name + languages: + - go + message: Include "WorkSpaces" in test name + paths: + include: + - internal/service/workspaces/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccWorkSpaces" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: workspaces-in-const-name + languages: + - go + message: Do not use "WorkSpaces" in const name inside workspaces package + paths: + include: + - internal/service/workspaces + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WorkSpaces" + severity: WARNING + - id: workspaces-in-var-name + languages: + - go + message: Do not use "WorkSpaces" in var name inside workspaces package + paths: + include: + - internal/service/workspaces + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)WorkSpaces" + severity: WARNING + - id: xray-in-func-name + languages: + - go + message: Do not use "XRay" in func name inside xray package + paths: + include: + - internal/service/xray + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)XRay" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: xray-in-test-name + languages: + - go + message: Include "XRay" in test name + paths: + include: + - internal/service/xray/*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAccXRay" + - pattern-regex: ^TestAcc.* + severity: WARNING + - id: xray-in-const-name + languages: + - go + message: Do not use "XRay" in const name inside xray package + paths: + include: + - internal/service/xray + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)XRay" + severity: WARNING + - id: xray-in-var-name + languages: + - go + message: Do not use "XRay" in var name inside xray package + paths: + include: + - internal/service/xray + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)XRay" + severity: WARNING diff --git a/.semgrep.yml b/.semgrep.yml index 9197c832b78..3853f50ad23 100644 --- a/.semgrep.yml +++ b/.semgrep.yml @@ -270,22 +270,62 @@ rules: - id: helper-schema-ResourceData-SetId-empty-without-IsNewResource-check languages: [go] - message: Calling `d.SetId("")` should ensure `!d.IsNewResource()` is also checked + message: Calling `d.SetId("")` should ensure `!d.IsNewResource()` is also checked. See https://github.com/hashicorp/terraform-provider-aws/blob/main/docs/contributing/error-handling.md#disnewresource-checks paths: include: - internal/service exclude: - internal/service/**/*_data_source.go - - internal/service/[be-g]* - - internal/service/d[a-df-z]* + - internal/service/backup + - internal/service/batch + - internal/service/d[a-d]* - internal/service/devicefarm - - internal/service/i* - - internal/service/[k-r]* - - internal/service/s[a-df-z3]* + - internal/service/directconnect + - internal/service/dlm + - internal/service/dms + - internal/service/ds + - internal/service/dynamodb + - internal/service/ec2 + - internal/service/ecs + - internal/service/efs + - internal/service/elasticache + - internal/service/elasticbeanstalk + - internal/service/elastictranscoder + - internal/service/elbv2 + - internal/service/emr + - internal/service/g* + - internal/service/inspector + - internal/service/iot + - internal/service/kafka + - internal/service/kms + - internal/service/lambda + - internal/service/lexmodels + - internal/service/licensemanager + - internal/service/lightsail + - internal/service/logs + - internal/service/macie + - internal/service/macie2 + - internal/service/mediastore + - internal/service/mq + - internal/service/neptune + - internal/service/opsworks + - internal/service/organizations + - internal/service/pinpoint + - internal/service/rds + - internal/service/resourcegroups + - internal/service/route53 + - internal/service/route53resolver + - internal/service/s[a-df-rt]* - internal/service/se[d-z]* - internal/service/sec[a-t]* - internal/service/securityhub - - internal/service/[t-x]* + - internal/service/ssoadmin + - internal/service/swf + - internal/service/[t-v]* + - internal/service/waf + - internal/service/wafv2 + - internal/service/workspaces + - internal/service/xray patterns: - pattern-either: - pattern: | @@ -664,6 +704,23 @@ rules: regex: "^resource\\w*(Create|Put|Set|Upsert|Enable)$" severity: WARNING + - id: calling-SetId-with-empty-string-in-resource-update + languages: [go] + message: Do not call `d.SetId("")` inside a resource update function + paths: + include: + - internal/service/ + patterns: + - pattern: | + func $FUNC(...) { + ... + d.SetId("") + } + - metavariable-regex: + metavariable: "$FUNC" + regex: "^resource\\w*(Update)$|^update\\w*$" # Put and Upsert variants are handled in calling-SetId-with-empty-string-in-resource-create above + severity: WARNING + - id: calling-SetId-in-resource-delete languages: [go] message: Do not call `d.SetId(...)` inside a resource delete function diff --git a/CHANGELOG.md b/CHANGELOG.md index e1622aff482..219e05471ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,231 @@ -## 4.15.0 (Unreleased) +## 4.21.0 (Unreleased) + +BUG FIXES: + +* resource/aws_default_vpc_dhcp_options: Fix `missing expected [` error introduced in [v4.20.0](https://github.com/hashicorp/terraform-provider-aws/blob/main/CHANGELOG.md#4200-june-23-2022) ([#25562](https://github.com/hashicorp/terraform-provider-aws/issues/25562)) + +## 4.20.0 (June 23, 2022) + +FEATURES: + +* **New Data Source:** `aws_kendra_faq` ([#25523](https://github.com/hashicorp/terraform-provider-aws/issues/25523)) +* **New Data Source:** `aws_kendra_index` ([#25473](https://github.com/hashicorp/terraform-provider-aws/issues/25473)) +* **New Data Source:** `aws_outposts_asset` ([#25476](https://github.com/hashicorp/terraform-provider-aws/issues/25476)) +* **New Data Source:** `aws_outposts_assets` ([#25476](https://github.com/hashicorp/terraform-provider-aws/issues/25476)) +* **New Resource:** `aws_applicationinsights_application` ([#25195](https://github.com/hashicorp/terraform-provider-aws/issues/25195)) +* **New Resource:** `aws_ce_anomaly_monitor` ([#25177](https://github.com/hashicorp/terraform-provider-aws/issues/25177)) +* **New Resource:** `aws_ce_anomaly_subscription` ([#25224](https://github.com/hashicorp/terraform-provider-aws/issues/25224)) +* **New Resource:** `aws_ce_cost_allocation_tag` ([#25272](https://github.com/hashicorp/terraform-provider-aws/issues/25272)) +* **New Resource:** `aws_cloudwatchrum_app_monitor` ([#25180](https://github.com/hashicorp/terraform-provider-aws/issues/25180)) +* **New Resource:** `aws_cognito_risk_configuration` ([#25282](https://github.com/hashicorp/terraform-provider-aws/issues/25282)) +* **New Resource:** `aws_kendra_experience` ([#25315](https://github.com/hashicorp/terraform-provider-aws/issues/25315)) +* **New Resource:** `aws_kendra_faq` ([#25515](https://github.com/hashicorp/terraform-provider-aws/issues/25515)) +* **New Resource:** `aws_kendra_query_suggestions_block_list` ([#25198](https://github.com/hashicorp/terraform-provider-aws/issues/25198)) +* **New Resource:** `aws_kendra_thesaurus` ([#25199](https://github.com/hashicorp/terraform-provider-aws/issues/25199)) +* **New Resource:** `aws_lakeformation_lf_tag` ([#19523](https://github.com/hashicorp/terraform-provider-aws/issues/19523)) +* **New Resource:** `aws_location_tracker` ([#25466](https://github.com/hashicorp/terraform-provider-aws/issues/25466)) + +ENHANCEMENTS: + +* data-source/aws_instance: Add `disable_api_stop` attribute ([#25185](https://github.com/hashicorp/terraform-provider-aws/issues/25185)) +* data-source/aws_instance: Add `private_dns_name_options` attribute ([#25161](https://github.com/hashicorp/terraform-provider-aws/issues/25161)) +* data-source/aws_instance: Correctly set `credit_specification` for T4g instances ([#25161](https://github.com/hashicorp/terraform-provider-aws/issues/25161)) +* data-source/aws_launch_template: Add `disable_api_stop` attribute ([#25185](https://github.com/hashicorp/terraform-provider-aws/issues/25185)) +* data-source/aws_launch_template: Correctly set `credit_specification` for T4g instances ([#25161](https://github.com/hashicorp/terraform-provider-aws/issues/25161)) +* data-source/aws_vpc_endpoint: Add `dns_options` and `ip_address_type` attributes ([#25190](https://github.com/hashicorp/terraform-provider-aws/issues/25190)) +* data-source/aws_vpc_endpoint_service: Add `supported_ip_address_types` attribute ([#25189](https://github.com/hashicorp/terraform-provider-aws/issues/25189)) +* resource/aws_cloudwatch_event_api_destination: Remove validation of a maximum value for the `invocation_rate_limit_per_second` argument ([#25277](https://github.com/hashicorp/terraform-provider-aws/issues/25277)) +* resource/aws_datasync_location_efs: Add `access_point_arn`, `file_system_access_role_arn`, and `in_transit_encryption` arguments ([#25182](https://github.com/hashicorp/terraform-provider-aws/issues/25182)) +* resource/aws_datasync_location_efs: Add plan time validations for `ec2_config.security_group_arns` ([#25182](https://github.com/hashicorp/terraform-provider-aws/issues/25182)) +* resource/aws_ec2_host: Add `outpost_arn` argument ([#25464](https://github.com/hashicorp/terraform-provider-aws/issues/25464)) +* resource/aws_instance: Add `disable_api_stop` argument ([#25185](https://github.com/hashicorp/terraform-provider-aws/issues/25185)) +* resource/aws_instance: Add `private_dns_name_options` argument ([#25161](https://github.com/hashicorp/terraform-provider-aws/issues/25161)) +* resource/aws_instance: Correctly handle `credit_specification` for T4g instances ([#25161](https://github.com/hashicorp/terraform-provider-aws/issues/25161)) +* resource/aws_launch_template: Add `disable_api_stop` argument ([#25185](https://github.com/hashicorp/terraform-provider-aws/issues/25185)) +* resource/aws_launch_template: Correctly handle `credit_specification` for T4g instances ([#25161](https://github.com/hashicorp/terraform-provider-aws/issues/25161)) +* resource/aws_s3_bucket_metric: Add validation to ensure name is <= 64 characters. ([#25260](https://github.com/hashicorp/terraform-provider-aws/issues/25260)) +* resource/aws_sagemaker_endpoint_configuration: Add `serverless_config` argument ([#25218](https://github.com/hashicorp/terraform-provider-aws/issues/25218)) +* resource/aws_sagemaker_endpoint_configuration: Make `production_variants.initial_instance_count` and `production_variants.instance_type` arguments optional ([#25218](https://github.com/hashicorp/terraform-provider-aws/issues/25218)) +* resource/aws_sagemaker_notebook_instance: Add `instance_metadata_service_configuration` argument ([#25236](https://github.com/hashicorp/terraform-provider-aws/issues/25236)) +* resource/aws_sagemaker_notebook_instance: Support `notebook-al2-v2` value for `platform_identifier` ([#25236](https://github.com/hashicorp/terraform-provider-aws/issues/25236)) +* resource/aws_synthetics_canary: Add `delete_lambda` argument ([#25284](https://github.com/hashicorp/terraform-provider-aws/issues/25284)) +* resource/aws_vpc_endpoint: Add `dns_options` and `ip_address_type` arguments ([#25190](https://github.com/hashicorp/terraform-provider-aws/issues/25190)) +* resource/aws_vpc_endpoint_service: Add `supported_ip_address_types` argument ([#25189](https://github.com/hashicorp/terraform-provider-aws/issues/25189)) +* resource/aws_vpn_connection: Add `outside_ip_address_type` and `transport_transit_gateway_attachment_id` arguments in support of [Private IP VPNs](https://docs.aws.amazon.com/vpn/latest/s2svpn/private-ip-dx.html) ([#25529](https://github.com/hashicorp/terraform-provider-aws/issues/25529)) + +BUG FIXES: + +* data-source/aws_ecr_repository: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* data-source/aws_elasticache_cluster: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* data-source/aws_iam_policy: Add validation to prevent setting incompatible parameters. ([#25538](https://github.com/hashicorp/terraform-provider-aws/issues/25538)) +* data-source/aws_iam_policy: Now loads tags. ([#25538](https://github.com/hashicorp/terraform-provider-aws/issues/25538)) +* data-source/aws_lb: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* data-source/aws_lb_listener: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* data-source/aws_lb_target_group: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* data-source/aws_sqs_queue: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_api_gateway_model: Suppress whitespace differences between model schemas ([#25245](https://github.com/hashicorp/terraform-provider-aws/issues/25245)) +* resource/aws_ce_cost_category: Allow duplicate values in `split_charge_rule.parameter.values` argument ([#25488](https://github.com/hashicorp/terraform-provider-aws/issues/25488)) +* resource/aws_ce_cost_category: Fix error passing `split_charge_rule.parameter` to the AWS API ([#25488](https://github.com/hashicorp/terraform-provider-aws/issues/25488)) +* resource/aws_cloudwatch_composite_alarm: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_cloudwatch_event_bus: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_cloudwatch_event_rule: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_cloudwatch_metric_alarm: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_cloudwatch_metric_stream: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_cognito_user_pool: Correctly handle missing or empty `account_recovery_setting` attribute ([#25184](https://github.com/hashicorp/terraform-provider-aws/issues/25184)) +* resource/aws_ecr_repository: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_ecs_capacity_provider: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_ecs_cluster: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_ecs_service: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_ecs_task_definition: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_ecs_task_set: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_elasticache_cluster: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_elasticache_parameter_group: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_elasticache_replication_group: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_elasticache_subnet_group: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_elasticache_user: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_elasticache_user_group: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_iam_instance_profile: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_iam_openid_connect_provider: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_iam_policy: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_iam_role: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_iam_saml_provider: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_iam_server_certificate: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_iam_service_linked_role: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_iam_user: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_iam_virtual_mfa_device: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_keyspaces_table: Relax validation of the `schema_definition.column.type` argument to allow collection types ([#25230](https://github.com/hashicorp/terraform-provider-aws/issues/25230)) +* resource/aws_launch_configuration: Remove default value for `associate_public_ip_address` argument and mark as Computed. This fixes a regression introduced in [v4.17.0](https://github.com/hashicorp/terraform-provider-aws/blob/main/CHANGELOG.md#4170-june--3-2022) via [#17695](https://github.com/hashicorp/terraform-provider-aws/issues/17695) when no value is configured, whilst honoring any configured value ([#25450](https://github.com/hashicorp/terraform-provider-aws/issues/25450)) +* resource/aws_lb: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_lb_listener: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_lb_listener_rule: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_lb_target_group: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_sns_topic: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) +* resource/aws_sqs_queue: Prevent ISO-partition tagging precautions from eating legit errors ([#25549](https://github.com/hashicorp/terraform-provider-aws/issues/25549)) + +## 4.19.0 (June 17, 2022) + +FEATURES: + +* **New Resource:** `aws_kendra_index` ([#24920](https://github.com/hashicorp/terraform-provider-aws/issues/24920)) +* **New Resource:** `aws_lightsail_container_service` ([#20625](https://github.com/hashicorp/terraform-provider-aws/issues/20625)) +* **New Resource:** `aws_lightsail_container_service_deployment_version` ([#20625](https://github.com/hashicorp/terraform-provider-aws/issues/20625)) + +BUG FIXES: + +* resource/aws_dynamodb_table_item: Fix to remove attribute from table item on update ([#25326](https://github.com/hashicorp/terraform-provider-aws/issues/25326)) +* resource/aws_ec2_managed_prefix_list_entry: Fix error when attempting to create or delete multiple list entries ([#25046](https://github.com/hashicorp/terraform-provider-aws/issues/25046)) + +## 4.18.0 (June 10, 2022) + +FEATURES: + +* **New Resource:** `aws_ce_anomaly_monitor` ([#25177](https://github.com/hashicorp/terraform-provider-aws/issues/25177)) +* **New Resource:** `aws_emrserverless_application` ([#25144](https://github.com/hashicorp/terraform-provider-aws/issues/25144)) + +ENHANCEMENTS: + +* data-source/aws_cloudwatch_logs_groups: Make `log_group_name_prefix` optional ([#25187](https://github.com/hashicorp/terraform-provider-aws/issues/25187)) +* data-source/aws_cognito_user_pool_client: Add `enable_propagate_additional_user_context_data` argument ([#25181](https://github.com/hashicorp/terraform-provider-aws/issues/25181)) +* data-source/aws_ram_resource_share: Add `resource_share_status` argument. ([#25159](https://github.com/hashicorp/terraform-provider-aws/issues/25159)) +* resource/aws_cognito_user_pool_client: Add `enable_propagate_additional_user_context_data` argument ([#25181](https://github.com/hashicorp/terraform-provider-aws/issues/25181)) +* resource/aws_ebs_snapshot_copy: Add support for `timeouts` configuration block. ([#20912](https://github.com/hashicorp/terraform-provider-aws/issues/20912)) +* resource/aws_ebs_volume: Add `final_snapshot` argument ([#21916](https://github.com/hashicorp/terraform-provider-aws/issues/21916)) +* resource/aws_s3_bucket: Add error handling for `ErrCodeNotImplemented` and `ErrCodeXNotImplemented` errors when ready bucket information. ([#24764](https://github.com/hashicorp/terraform-provider-aws/issues/24764)) +* resource/aws_vpc_ipam_pool_cidr_allocation: improve internal search mechanism ([#25257](https://github.com/hashicorp/terraform-provider-aws/issues/25257)) + +BUG FIXES: + +* resource/aws_snapshot_create_volume_permission: Error if `account_id` is the snapshot's owner ([#12103](https://github.com/hashicorp/terraform-provider-aws/issues/12103)) +* resource/aws_ssm_parameter: Allow `Intelligent-Tiering` to upgrade to `Advanced` tier as needed. ([#25174](https://github.com/hashicorp/terraform-provider-aws/issues/25174)) + +## 4.17.1 (June 3, 2022) + +BUG FIXES: + +* resource/aws_ram_resource_share: Fix regression in v4.17.0 where `permission_arns` would get clobbered if already set ([#25158](https://github.com/hashicorp/terraform-provider-aws/issues/25158)) + +## 4.17.0 (June 3, 2022) + +FEATURES: + +* **New Data Source:** `aws_redshift_cluster_credentials` ([#25092](https://github.com/hashicorp/terraform-provider-aws/issues/25092)) +* **New Resource:** `aws_acmpca_policy` ([#25109](https://github.com/hashicorp/terraform-provider-aws/issues/25109)) +* **New Resource:** `aws_redshift_cluster_iam_roles` ([#25096](https://github.com/hashicorp/terraform-provider-aws/issues/25096)) +* **New Resource:** `aws_redshift_hsm_configuration` ([#25093](https://github.com/hashicorp/terraform-provider-aws/issues/25093)) +* **New Resource:** `aws_redshiftdata_statement` ([#25104](https://github.com/hashicorp/terraform-provider-aws/issues/25104)) + +ENHANCEMENTS: + +* resource/aws_dms_endpoint: Add `redshift_settings` configuration block ([#21846](https://github.com/hashicorp/terraform-provider-aws/issues/21846)) +* resource/aws_dms_endpoint: Add ability to use AWS Secrets Manager with the `aurora-postgresql` and `mongodb` engines ([#23691](https://github.com/hashicorp/terraform-provider-aws/issues/23691)) +* resource/aws_dms_endpoint: Add ability to use AWS Secrets Manager with the `aurora`, `mariadb` and `mysql` engines ([#24846](https://github.com/hashicorp/terraform-provider-aws/issues/24846)) +* resource/aws_dms_endpoint: Add ability to use AWS Secrets Manager with the `redshift` engine ([#25080](https://github.com/hashicorp/terraform-provider-aws/issues/25080)) +* resource/aws_dms_endpoint: Add ability to use AWS Secrets Manager with the `sqlserver` engine ([#22646](https://github.com/hashicorp/terraform-provider-aws/issues/22646)) +* resource/aws_guardduty_detector: Add `kubernetes` attribute to the `datasources` configuration block ([#22859](https://github.com/hashicorp/terraform-provider-aws/issues/22859)) +* resource/aws_ram_resource_share: Add `permission_arns` argument. ([#25113](https://github.com/hashicorp/terraform-provider-aws/issues/25113)) +* resource/aws_redshift_cluster: The `default_iam_role_arn` argument is now Computed ([#25096](https://github.com/hashicorp/terraform-provider-aws/issues/25096)) + +BUG FIXES: + +* data-source/aws_launch_configuration: Correct data type for `ebs_block_device.throughput` and `root_block_device.throughput` attributes ([#25097](https://github.com/hashicorp/terraform-provider-aws/issues/25097)) +* resource/aws_db_instance_role_association: Extend timeout to 10 minutes ([#25145](https://github.com/hashicorp/terraform-provider-aws/issues/25145)) +* resource/aws_ebs_volume: Fix to preserve `iops` when changing EBS volume type (`io1`, `io2`, `gp3`) ([#23280](https://github.com/hashicorp/terraform-provider-aws/issues/23280)) +* resource/aws_launch_configuration: Honor associate_public_ip_address = false ([#17695](https://github.com/hashicorp/terraform-provider-aws/issues/17695)) +* resource/aws_rds_cluster_role_association: Extend timeout to 10 minutes ([#25145](https://github.com/hashicorp/terraform-provider-aws/issues/25145)) +* resource/aws_servicecatalog_provisioned_product: Correctly handle resources in a `TAINTED` state ([#25130](https://github.com/hashicorp/terraform-provider-aws/issues/25130)) + +## 4.16.0 (May 27, 2022) + +FEATURES: + +* **New Data Source:** `aws_location_place_index` ([#24980](https://github.com/hashicorp/terraform-provider-aws/issues/24980)) +* **New Data Source:** `aws_redshift_subnet_group` ([#25053](https://github.com/hashicorp/terraform-provider-aws/issues/25053)) +* **New Resource:** `aws_efs_replication_configuration` ([#22844](https://github.com/hashicorp/terraform-provider-aws/issues/22844)) +* **New Resource:** `aws_location_place_index` ([#24821](https://github.com/hashicorp/terraform-provider-aws/issues/24821)) +* **New Resource:** `aws_redshift_authentication_profile` ([#24907](https://github.com/hashicorp/terraform-provider-aws/issues/24907)) +* **New Resource:** `aws_redshift_endpoint_access` ([#25073](https://github.com/hashicorp/terraform-provider-aws/issues/25073)) +* **New Resource:** `aws_redshift_hsm_client_certificate` ([#24906](https://github.com/hashicorp/terraform-provider-aws/issues/24906)) +* **New Resource:** `aws_redshift_usage_limit` ([#24916](https://github.com/hashicorp/terraform-provider-aws/issues/24916)) + +ENHANCEMENTS: + +* data-source/aws_ami: Add `tpm_support` attribute ([#25045](https://github.com/hashicorp/terraform-provider-aws/issues/25045)) +* data-source/aws_redshift_cluster: Add `aqua_configuration_status` attribute. ([#24856](https://github.com/hashicorp/terraform-provider-aws/issues/24856)) +* data-source/aws_redshift_cluster: Add `arn`, `cluster_nodes`, `cluster_nodes`, `maintenance_track_name`, `manual_snapshot_retention_period`, `log_destination_type`, and `log_exports` attributes. ([#24982](https://github.com/hashicorp/terraform-provider-aws/issues/24982)) +* data-source/aws_cloudfront_response_headers_policy: Add `server_timing_headers_config` attribute ([#24913](https://github.com/hashicorp/terraform-provider-aws/issues/24913)) +* resource/aws_ami: Add `tpm_support` argument ([#25045](https://github.com/hashicorp/terraform-provider-aws/issues/25045)) +* resource/aws_ami_copy: Add `tpm_support` argument ([#25045](https://github.com/hashicorp/terraform-provider-aws/issues/25045)) +* resource/aws_ami_from_instance: Add `tpm_support` argument ([#25045](https://github.com/hashicorp/terraform-provider-aws/issues/25045)) +* resource/aws_autoscaling_group: Add `context` argument ([#24951](https://github.com/hashicorp/terraform-provider-aws/issues/24951)) +* resource/aws_autoscaling_group: Add `mixed_instances_policy.launch_template.override.instance_requirements` argument ([#24795](https://github.com/hashicorp/terraform-provider-aws/issues/24795)) +* resource/aws_cloudfront_response_headers_policy: Add `server_timing_headers_config` argument ([#24913](https://github.com/hashicorp/terraform-provider-aws/issues/24913)) +* resource/aws_cloudsearch_domain: Add `index_field.source_fields` argument ([#24915](https://github.com/hashicorp/terraform-provider-aws/issues/24915)) +* resource/aws_cloudwatch_metric_stream: Add `statistics_configuration` argument ([#24882](https://github.com/hashicorp/terraform-provider-aws/issues/24882)) +* resource/aws_elasticache_global_replication_group: Add support for upgrading `engine_version`. ([#25077](https://github.com/hashicorp/terraform-provider-aws/issues/25077)) +* resource/aws_msk_cluster: Support multiple attribute updates by refreshing `current_version` after each update ([#25062](https://github.com/hashicorp/terraform-provider-aws/issues/25062)) +* resource/aws_redshift_cluster: Add `aqua_configuration_status` and `apply_immediately` arguments. ([#24856](https://github.com/hashicorp/terraform-provider-aws/issues/24856)) +* resource/aws_redshift_cluster: Add `default_iam_role_arn`, `maintenance_track_name`, and `manual_snapshot_retention_period` arguments. ([#24982](https://github.com/hashicorp/terraform-provider-aws/issues/24982)) +* resource/aws_redshift_cluster: Add `logging.log_destination_type` and `logging.log_exports` arguments. ([#24886](https://github.com/hashicorp/terraform-provider-aws/issues/24886)) +* resource/aws_redshift_cluster: Add plan-time validation for `iam_roles`, `owner_account`, and `port`. ([#24856](https://github.com/hashicorp/terraform-provider-aws/issues/24856)) +* resource/aws_redshift_event_subscription: Add plan time validations for `event_categories`, `source_type`, and `severity`. ([#24909](https://github.com/hashicorp/terraform-provider-aws/issues/24909)) +* resource/aws_transfer_server: Add support for `TransferSecurityPolicy-2022-03` `security_policy_name` value ([#25060](https://github.com/hashicorp/terraform-provider-aws/issues/25060)) + +BUG FIXES: + +* resource/aws_appflow_flow: Amend `task_properties` validation to avoid conflicting type assumption ([#24889](https://github.com/hashicorp/terraform-provider-aws/issues/24889)) +* resource/aws_db_proxy_target: Fix `InvalidDBInstanceState: DB Instance is in an unsupported state - CREATING, needs to be in [AVAILABLE, MODIFYING, BACKING_UP]` error on resource Create ([#24875](https://github.com/hashicorp/terraform-provider-aws/issues/24875)) +* resource/aws_instance: Correctly delete instance on destroy when `disable_api_termination` is `true` ([#19277](https://github.com/hashicorp/terraform-provider-aws/issues/19277)) +* resource/aws_instance: Prevent error `InvalidParameterCombination: The parameter GroupName within placement information cannot be specified when instanceInterruptionBehavior is set to 'STOP'` when using a launch template that sets `instance_interruption_behavior` to `stop` ([#24695](https://github.com/hashicorp/terraform-provider-aws/issues/24695)) +* resource/aws_msk_cluster: Prevent crash on apply when `client_authentication.tls` is empty ([#25072](https://github.com/hashicorp/terraform-provider-aws/issues/25072)) +* resource/aws_servicecatalog_provisioned_product: Add possible `TAINTED` target state for resource update and remove one of the internal waiters during read ([#24804](https://github.com/hashicorp/terraform-provider-aws/issues/24804)) + +## 4.15.1 (May 20, 2022) + +BUG FIXES: + +* resource/aws_organizations_account: Fix reading account state for existing accounts ([#24899](https://github.com/hashicorp/terraform-provider-aws/issues/24899)) + +## 4.15.0 (May 20, 2022) BREAKING CHANGES: @@ -13,7 +240,7 @@ FEATURES: ENHANCEMENTS: -* datasource/aws_route53_resolver_rules: add `name_regex` argument ([#24582](https://github.com/hashicorp/terraform-provider-aws/issues/24582)) +* data-source/aws_route53_resolver_rules: add `name_regex` argument ([#24582](https://github.com/hashicorp/terraform-provider-aws/issues/24582)) * resource/aws_autoscaling_group: Add `instance_refresh.preferences.skip_matching` argument ([#23059](https://github.com/hashicorp/terraform-provider-aws/issues/23059)) * resource/aws_autoscaling_policy: Add `enabled` argument ([#12625](https://github.com/hashicorp/terraform-provider-aws/issues/12625)) * resource/aws_ec2_fleet: Add `arn` attribute ([#24732](https://github.com/hashicorp/terraform-provider-aws/issues/24732)) @@ -456,7 +683,7 @@ ENHANCEMENTS: * data-source/aws_launch_template: Add `capacity_reservation_specification`, `cpu_options`, `elastic_inference_accelerator` and `license_specification` attributes ([#23365](https://github.com/hashicorp/terraform-provider-aws/issues/23365)) * data-source/aws_launch_template: Add `ipv4_prefixes`, `ipv4_prefix_count`, `ipv6_prefixes` and `ipv6_prefix_count` attributes to the `network_interfaces` configuration block ([#23365](https://github.com/hashicorp/terraform-provider-aws/issues/23365)) * data-source/aws_launch_template: Add `private_dns_name_options` attribute ([#23365](https://github.com/hashicorp/terraform-provider-aws/issues/23365)) -* data_source/aws_redshift_cluster: Add `availability_zone_relocation_enabled` attribute. ([#20812](https://github.com/hashicorp/terraform-provider-aws/issues/20812)) +* data-source/aws_redshift_cluster: Add `availability_zone_relocation_enabled` attribute. ([#20812](https://github.com/hashicorp/terraform-provider-aws/issues/20812)) * resource/aws_appconfig_configuration_profile: Add `type` argument to support [AWS AppConfig Feature Flags](https://aws.amazon.com/blogs/mt/using-aws-appconfig-feature-flags/) ([#23719](https://github.com/hashicorp/terraform-provider-aws/issues/23719)) * resource/aws_athena_database: Add `acl_configuration` and `expected_bucket_owner` arguments ([#23745](https://github.com/hashicorp/terraform-provider-aws/issues/23745)) * resource/aws_athena_database: Add `comment` argument to support database descriptions ([#23745](https://github.com/hashicorp/terraform-provider-aws/issues/23745)) @@ -705,9 +932,9 @@ ENHANCEMENTS: * resource/aws_cloudformation_stack_set: Add `call_as` argument ([#22440](https://github.com/hashicorp/terraform-provider-aws/issues/22440)) * resource/aws_elastic_transcoder_preset: Add plan time validations to `audio.audio_packing_mode`, `audio.channels`, `audio.codec`,`audio.sample_rate`, `audio_codec_options.bit_depth`, `audio_codec_options.bit_order`, -`audio_codec_options.profile`, `audio_codec_options.signed`, `audio_codec_options.signed`, +`audio_codec_options.profile`, `audio_codec_options.signed`, `audio_codec_options.signed`, `container`, `thumbnails.aspect_ratio`, `thumbnails.format`, `thumbnails.padding_policy`, `thumbnails.sizing_policy`, -`type`, `video.aspect_ratio`, `video.codec`, `video.display_aspect_ratio`, `video.fixed_gop`, `video.frame_rate`, `video.max_frame_rate`, `video.padding_policy`, `video.sizing_policy`, `video_watermarks.horizontal_align`, +`type`, `video.aspect_ratio`, `video.codec`, `video.display_aspect_ratio`, `video.fixed_gop`, `video.frame_rate`, `video.max_frame_rate`, `video.padding_policy`, `video.sizing_policy`, `video_watermarks.horizontal_align`, `video_watermarks.id`, `video_watermarks.sizing_policy`, `video_watermarks.target`, `video_watermarks.vertical_align` ([#13974](https://github.com/hashicorp/terraform-provider-aws/issues/13974)) * resource/aws_elastic_transcoder_preset: Allow `audio.bit_rate` to be computed. ([#13974](https://github.com/hashicorp/terraform-provider-aws/issues/13974)) * resource/aws_gamelift_build: Add `object_version` argument to `storage_location` block. ([#22966](https://github.com/hashicorp/terraform-provider-aws/issues/22966)) @@ -728,7 +955,7 @@ ENHANCEMENTS: BUG FIXES: -* data_source/aws_vpc_ipam_pool: error if no pool found ([#23195](https://github.com/hashicorp/terraform-provider-aws/issues/23195)) +* data-source/aws_vpc_ipam_pool: error if no pool found ([#23195](https://github.com/hashicorp/terraform-provider-aws/issues/23195)) * provider: Support `ap-northeast-3`, `ap-southeast-3` and `us-iso-west-1` as valid AWS Regions ([#23191](https://github.com/hashicorp/terraform-provider-aws/issues/23191)) * provider: Use AWS HTTP client which allows IMDS authentication in container environments and custom RootCAs in ISO regions ([#23191](https://github.com/hashicorp/terraform-provider-aws/issues/23191)) * resource/aws_appmesh_route: Handle zero `max_retries` ([#23035](https://github.com/hashicorp/terraform-provider-aws/issues/23035)) @@ -809,7 +1036,7 @@ NOTES: * resource/aws_budgets_budget: The `cost_filters` attribute has been deprecated. Use the `cost_filter` attribute instead. ([#22888](https://github.com/hashicorp/terraform-provider-aws/issues/22888)) * resource/aws_connect_hours_of_operation: Timeout support has been removed as it is not needed for this resource ([#22375](https://github.com/hashicorp/terraform-provider-aws/issues/22375)) * resource/aws_customer_gateway: `ip_address` can no longer be set to `""` ([#22926](https://github.com/hashicorp/terraform-provider-aws/issues/22926)) -* resource/aws_db_instance The `name` argument has been deprecated. All configurations using `name` should be updated to use the `db_name` argument instead ([#22668](https://github.com/hashicorp/terraform-provider-aws/issues/22668)) +* resource/aws_db_instance: The `name` argument has been deprecated. All configurations using `name` should be updated to use the `db_name` argument instead ([#22668](https://github.com/hashicorp/terraform-provider-aws/issues/22668)) * resource/aws_default_subnet: If no default subnet exists in the specified Availability Zone one is now created. The `force_destroy` destroy argument has been added (defaults to `false`). Setting this argument to `true` deletes the default subnet on `terraform destroy` ([#22253](https://github.com/hashicorp/terraform-provider-aws/issues/22253)) * resource/aws_default_vpc: If no default VPC exists in the current AWS Region one is now created. The `force_destroy` destroy argument has been added (defaults to `false`). Setting this argument to `true` deletes the default VPC on `terraform destroy` ([#22253](https://github.com/hashicorp/terraform-provider-aws/issues/22253)) * resource/aws_ec2_client_vpn_endpoint: The `status` attribute has been deprecated ([#22887](https://github.com/hashicorp/terraform-provider-aws/issues/22887)) @@ -919,6 +1146,90 @@ NOTES: * **Merge upstream v4.0.0** +## 3.75.2 (May 20, 2022) + +ENHANCEMENTS: + +* resource/aws_lambda_function: Add support for `nodejs16.x` `runtime` value ([#24874](https://github.com/hashicorp/terraform-provider-aws/issues/24874)) +* resource/aws_lambda_layer_version: Add support for `nodejs16.x` `compatible_runtimes` value ([#24874](https://github.com/hashicorp/terraform-provider-aws/issues/24874)) +* resource/aws_s3_bucket_website_configuration: Add `routing_rules` parameter to be used instead of `routing_rule` to support configurations with empty String values ([#24199](https://github.com/hashicorp/terraform-provider-aws/issues/24199)) + +## 3.75.1 (March 24, 2022) + +BUG FIXES: + +* resource/aws_route_table_association: Retry resource Read for EC2 eventual consistency ([#23806](https://github.com/hashicorp/terraform-provider-aws/issues/23806)) + +## 3.75.0 (March 18, 2022) + +NOTES: + +* resource/aws_s3_bucket: The `acceleration_status` argument has been deprecated. Use the `aws_s3_bucket_accelerate_configuration` resource instead. ([#23471](https://github.com/hashicorp/terraform-provider-aws/issues/23471)) +* resource/aws_s3_bucket: The `acl` and `grant` arguments have been deprecated. Use the `aws_s3_bucket_acl` resource instead. ([#23419](https://github.com/hashicorp/terraform-provider-aws/issues/23419)) +* resource/aws_s3_bucket: The `cors_rule` argument has been deprecated. Use the `aws_s3_bucket_cors_configuration` resource instead. ([#23434](https://github.com/hashicorp/terraform-provider-aws/issues/23434)) +* resource/aws_s3_bucket: The `lifecycle_rule` argument has been deprecated. Use the `aws_s3_bucket_lifecycle_configuration` resource instead. ([#23445](https://github.com/hashicorp/terraform-provider-aws/issues/23445)) +* resource/aws_s3_bucket: The `logging` argument has been deprecated. Use the `aws_s3_bucket_logging` resource instead. ([#23430](https://github.com/hashicorp/terraform-provider-aws/issues/23430)) +* resource/aws_s3_bucket: The `object_lock_configuration.object_lock_enabled` argument has been deprecated. Use the top-level argument `object_lock_enabled` instead. ([#23449](https://github.com/hashicorp/terraform-provider-aws/issues/23449)) +* resource/aws_s3_bucket: The `object_lock_configuration.rule` argument has been deprecated. Use the `aws_s3_bucket_object_lock_configuration` resource instead. ([#23449](https://github.com/hashicorp/terraform-provider-aws/issues/23449)) +* resource/aws_s3_bucket: The `replication_configuration` argument has been deprecated. Use the `aws_s3_bucket_replication_configuration` resource instead. ([#23716](https://github.com/hashicorp/terraform-provider-aws/issues/23716)) +* resource/aws_s3_bucket: The `request_payer` argument has been deprecated. Use the `aws_s3_bucket_request_payment_configuration` resource instead. ([#23473](https://github.com/hashicorp/terraform-provider-aws/issues/23473)) +* resource/aws_s3_bucket: The `server_side_encryption_configuration` argument has been deprecated. Use the `aws_s3_bucket_server_side_encryption_configuration` resource instead. ([#23476](https://github.com/hashicorp/terraform-provider-aws/issues/23476)) +* resource/aws_s3_bucket: The `versioning` argument has been deprecated. Use the `aws_s3_bucket_versioning` resource instead. ([#23432](https://github.com/hashicorp/terraform-provider-aws/issues/23432)) +* resource/aws_s3_bucket: The `website`, `website_domain`, and `website_endpoint` arguments have been deprecated. Use the `aws_s3_bucket_website_configuration` resource instead. ([#23435](https://github.com/hashicorp/terraform-provider-aws/issues/23435)) + +FEATURES: + +* **New Resource:** `aws_s3_bucket_accelerate_configuration` ([#23471](https://github.com/hashicorp/terraform-provider-aws/issues/23471)) +* **New Resource:** `aws_s3_bucket_acl` ([#23419](https://github.com/hashicorp/terraform-provider-aws/issues/23419)) +* **New Resource:** `aws_s3_bucket_cors_configuration` ([#23434](https://github.com/hashicorp/terraform-provider-aws/issues/23434)) +* **New Resource:** `aws_s3_bucket_lifecycle_configuration` ([#23445](https://github.com/hashicorp/terraform-provider-aws/issues/23445)) +* **New Resource:** `aws_s3_bucket_logging` ([#23430](https://github.com/hashicorp/terraform-provider-aws/issues/23430)) +* **New Resource:** `aws_s3_bucket_object_lock_configuration` ([#23449](https://github.com/hashicorp/terraform-provider-aws/issues/23449)) +* **New Resource:** `aws_s3_bucket_request_payment_configuration` ([#23473](https://github.com/hashicorp/terraform-provider-aws/issues/23473)) +* **New Resource:** `aws_s3_bucket_server_side_encryption_configuration` ([#23476](https://github.com/hashicorp/terraform-provider-aws/issues/23476)) +* **New Resource:** `aws_s3_bucket_versioning` ([#23432](https://github.com/hashicorp/terraform-provider-aws/issues/23432)) +* **New Resource:** `aws_s3_bucket_website_configuration` ([#23435](https://github.com/hashicorp/terraform-provider-aws/issues/23435)) + +ENHANCEMENTS: + +* resource/aws_lambda_function: Add support for `dotnet6` `runtime` value ([#23670](https://github.com/hashicorp/terraform-provider-aws/issues/23670)) +* resource/aws_lambda_layer_version: Add support for `dotnet6` `compatible_runtimes` value ([#23670](https://github.com/hashicorp/terraform-provider-aws/issues/23670)) +* resource/aws_s3_bucket: Add top-level `object_lock_enabled` parameter ([#23449](https://github.com/hashicorp/terraform-provider-aws/issues/23449)) +* resource/aws_s3_bucket_acl: Support resource import for S3 bucket names consisting of uppercase letters, underscores, and a maximum of 255 characters ([#23679](https://github.com/hashicorp/terraform-provider-aws/issues/23679)) +* resource/aws_s3_bucket_lifecycle_configuration: Support empty string filtering (default behavior of the `aws_s3_bucket.lifecycle_rule` parameter in provider versions prior to v4.0) ([#23750](https://github.com/hashicorp/terraform-provider-aws/issues/23750)) +* resource/aws_s3_bucket_replication_configuration: Add `token` field to specify +x-amz-bucket-object-lock-token for enabling replication on object lock enabled +buckets or enabling object lock on an existing bucket. ([#23716](https://github.com/hashicorp/terraform-provider-aws/issues/23716)) +* resource/aws_s3_bucket_versioning: Add missing support for `Disabled` bucket versioning ([#23731](https://github.com/hashicorp/terraform-provider-aws/issues/23731)) + +BUG FIXES: + +* resource/aws_s3_bucket: Prevent panic when expanding the bucket's list of `cors_rule` ([#7547](https://github.com/hashicorp/terraform-provider-aws/issues/7547)) +* resource/aws_s3_bucket_replication_configuration: Change `rule` configuration block to list instead of set ([#23737](https://github.com/hashicorp/terraform-provider-aws/issues/23737)) +* resource/aws_s3_bucket_replication_configuration: Correctly configure empty `rule.filter` configuration block in API requests ([#23716](https://github.com/hashicorp/terraform-provider-aws/issues/23716)) +* resource/aws_s3_bucket_replication_configuration: Ensure both `key` and `value` arguments of the `rule.filter.tag` configuration block are correctly populated in the outgoing API request and terraform state. ([#23716](https://github.com/hashicorp/terraform-provider-aws/issues/23716)) +* resource/aws_s3_bucket_replication_configuration: Prevent inconsistent final plan when `rule.filter.prefix` is an empty string ([#23716](https://github.com/hashicorp/terraform-provider-aws/issues/23716)) +* resource/aws_s3_bucket_replication_configuration: Set `rule.id` as Computed to prevent drift when the value is not configured ([#23737](https://github.com/hashicorp/terraform-provider-aws/issues/23737)) + +## 3.74.3 (February 17, 2022) + +BUG FIXES: + +* resource/aws_ecs_capacity_provider: Fix tagging error preventing use in ISO partitions ([#23030](https://github.com/hashicorp/terraform-provider-aws/issues/23030)) +* resource/aws_ecs_cluster: Fix tagging error preventing use in ISO partitions ([#23030](https://github.com/hashicorp/terraform-provider-aws/issues/23030)) +* resource/aws_ecs_service: Fix tagging error preventing use in ISO partitions ([#23030](https://github.com/hashicorp/terraform-provider-aws/issues/23030)) +* resource/aws_ecs_task_definition: Fix tagging error preventing use in ISO partitions ([#23030](https://github.com/hashicorp/terraform-provider-aws/issues/23030)) +* resource/aws_ecs_task_set: Fix tagging error preventing use in ISO partitions ([#23030](https://github.com/hashicorp/terraform-provider-aws/issues/23030)) +* resource/aws_waf_rule_group: Prevent panic when expanding the rule group's set of `activated_rule` ([#22978](https://github.com/hashicorp/terraform-provider-aws/issues/22978)) +* resource/aws_wafregional_rule_group: Prevent panic when expanding the rule group's set of `activated_rule` ([#22978](https://github.com/hashicorp/terraform-provider-aws/issues/22978)) + +## 3.74.2 (February 11, 2022) + +BUG FIXES: + +* resource/aws_rds_cluster: Fix crash when configured `engine_version` string is shorter than the `EngineVersion` string returned from the AWS API ([#23039](https://github.com/hashicorp/terraform-provider-aws/issues/23039)) +* resource/aws_vpn_connection: Add support for `ipsec.1-aes256` connection type ([#23127](https://github.com/hashicorp/terraform-provider-aws/issues/23127)) + ## 3.74.1 (February 7, 2022) BUG FIXES: @@ -1522,7 +1833,7 @@ ENHANCEMENTS: * data-source/aws_launch_template: Add `network_card_index` attribute to `network_interfaces` configuration block ([#21555](https://github.com/hashicorp/terraform-provider-aws/issues/21555)) * data-source/aws_network_interface: Add `arn` attribute ([#21265](https://github.com/hashicorp/terraform-provider-aws/issues/21265)) * data-source/aws_s3_bucket: Return `hosted_zone_id` attribute for `cn-northwest-1` (Ningxia) region ([#21337](https://github.com/hashicorp/terraform-provider-aws/issues/21337)) -* resource/aws_apigateway_usage_plan : Add `throttle` argument for `api_stages` block. ([#21461](https://github.com/hashicorp/terraform-provider-aws/issues/21461)) +* resource/aws_apigateway_usage_plan: Add `throttle` argument for `api_stages` block. ([#21461](https://github.com/hashicorp/terraform-provider-aws/issues/21461)) * resource/aws_batch_compute_environment: Add `ec2_configuration` argument to `compute_resources` configuration block ([#21565](https://github.com/hashicorp/terraform-provider-aws/issues/21565)) * resource/aws_cloudfront_distribution: Add `response_headers_policy_id` argument to `default_cache_behavior` configuration block ([#21620](https://github.com/hashicorp/terraform-provider-aws/issues/21620)) * resource/aws_cloudfront_distribution: Add `response_headers_policy_id` argument to `ordered_cache_behavior` configuration block ([#21620](https://github.com/hashicorp/terraform-provider-aws/issues/21620)) @@ -2801,7 +3112,7 @@ ENHANCEMENTS: * resource/aws_ec2_capacity_reservation: Add `owner_id` attribute ([#17129](https://github.com/hashicorp/terraform-provider-aws/issues/17129)) * resource/aws_ec2_traffic_mirror_filter: Add `arn` attribute. ([#13948](https://github.com/hashicorp/terraform-provider-aws/issues/13948)) * resource/aws_ec2_traffic_mirror_filter_rule: Add arn attribute. ([#13949](https://github.com/hashicorp/terraform-provider-aws/issues/13949)) -* resource/aws_ec2_traffic_mirror_filter_rule: Add plan time validation to `destination_port_range.from_port`, +* resource/aws_ec2_traffic_mirror_filter_rule: Add plan time validation to `destination_port_range.from_port`, `destination_port_range.to_port`, `source_port_range.from_port`, and `source_port_range.to_port`. ([#13949](https://github.com/hashicorp/terraform-provider-aws/issues/13949)) * resource/aws_elastictranscoder_pipeline: Add plan time validations to `content_config.storage_class`, `content_config_permissions.access`, `content_config_permissions.grantee_type`, `notifications.completed`, `notifications.error`, `notifications.progressing`, `notifications.warning`, @@ -2942,7 +3253,7 @@ ENHANCEMENTS * resource/aws_lightsail_instance: Add `ipv6_addresses` attribute ([#17155](https://github.com/hashicorp/terraform-provider-aws/issues/17155)) * resource/aws_sagemaker_domain: Delete implicit EFS file system ([#17123](https://github.com/hashicorp/terraform-provider-aws/issues/17123)) -BUG FIXES +BUG FIXES * data-source/aws_lambda_function: Prevent error when getting Code Signing Config for container image based lambdas during read ([#17180](https://github.com/hashicorp/terraform-provider-aws/issues/17180)) * provider: Fix error messages for missing required blocks not including the block name ([#17211](https://github.com/hashicorp/terraform-provider-aws/issues/17211)) @@ -3006,7 +3317,7 @@ BUG FIXES * resource/aws_instance: Prevent `volume_tags` from improperly interfering with `tags` in `aws_ebs_volume` ([#15474](https://github.com/hashicorp/terraform-provider-aws/issues/15474)) * resource/aws_networkfirewall_rule_group: Prevent resource recreation due to `stateful_rule` changes after creation ([#16884](https://github.com/hashicorp/terraform-provider-aws/issues/16884)) * resource/aws_route53_zone_association: Prevent deletion errors for missing Hosted Zone or VPC association ([#17023](https://github.com/hashicorp/terraform-provider-aws/issues/17023)) -* resource/aws_sagemaker_image - fix error on wait for delete when image does not exist ([#16077](https://github.com/hashicorp/terraform-provider-aws/issues/16077)) +* resource/aws_sagemaker_image: fix error on wait for delete when image does not exist ([#16077](https://github.com/hashicorp/terraform-provider-aws/issues/16077)) * resource/aws_s3_bucket_inventory: Prevent crashes with empty `destination`, `filter`, and `schedule` configuration blocks ([#17055](https://github.com/hashicorp/terraform-provider-aws/issues/17055)) * service/apigateway: All operations will now automatically retry on `ConflictException: Unable to complete operation due to concurrent modification. Please try again later.` errors. @@ -3132,10 +3443,10 @@ ENHANCEMENTS * resource/aws_eks_node_group: Make `capacity_type` a `Computed` attribute ([#16552](https://github.com/hashicorp/terraform-provider-aws/issues/16552)) * resource/aws_lambda_event_source_mapping: Add support for updating `maximum_batching_window_in_seconds` for SQS queue event sources ([#16518](https://github.com/hashicorp/terraform-provider-aws/issues/16518)) * resource/aws_ssm_maintenance_window_target: Add plan-time validation for `owner_information` and `targets` arguments ([#16478](https://github.com/hashicorp/terraform-provider-aws/issues/16478)) -* resource/aws_storagegateway_gateway - add `timeout_in_seconds`, `organizational_unit`, `domain_controllers` arguments for `smb_active_directory_settings` block. ([#16472](https://github.com/hashicorp/terraform-provider-aws/issues/16472)) -* resource/aws_storagegateway_gateway - add `smb_active_directory_settings. active_directory_status`, `ec2_instance_id`, `endpoint_type`, `host_environment`, and `gateway_network_interface` attributes. ([#16472](https://github.com/hashicorp/terraform-provider-aws/issues/16472)) -* resource/aws_storagegateway_gateway - add plan time validations for `smb_guest_password`, `smb_active_directory_settings. username`, `smb_active_directory_settings. password`, `smb_active_directory_settings. domain_name`, `gateway_timezone`, and `gateway_name`. ([#16472](https://github.com/hashicorp/terraform-provider-aws/issues/16472)) -* resource/aws_storagegateway_gateway - add support for `medium_changer_type` value `medium_changer_type`. ([#16472](https://github.com/hashicorp/terraform-provider-aws/issues/16472)) +* resource/aws_storagegateway_gateway: add `timeout_in_seconds`, `organizational_unit`, `domain_controllers` arguments for `smb_active_directory_settings` block. ([#16472](https://github.com/hashicorp/terraform-provider-aws/issues/16472)) +* resource/aws_storagegateway_gateway: add `smb_active_directory_settings. active_directory_status`, `ec2_instance_id`, `endpoint_type`, `host_environment`, and `gateway_network_interface` attributes. ([#16472](https://github.com/hashicorp/terraform-provider-aws/issues/16472)) +* resource/aws_storagegateway_gateway: add plan time validations for `smb_guest_password`, `smb_active_directory_settings. username`, `smb_active_directory_settings. password`, `smb_active_directory_settings. domain_name`, `gateway_timezone`, and `gateway_name`. ([#16472](https://github.com/hashicorp/terraform-provider-aws/issues/16472)) +* resource/aws_storagegateway_gateway: add support for `medium_changer_type` value `medium_changer_type`. ([#16472](https://github.com/hashicorp/terraform-provider-aws/issues/16472)) BUG FIXES @@ -3157,8 +3468,8 @@ ENHANCEMENTS * resource/aws_apigatewayv2_domain_name: Add `mutual_tls_authentication` attribute to support mutual TLS authentication ([#15249](https://github.com/hashicorp/terraform-provider-aws/issues/15249)) * resource/aws_appmesh_virtual_gateway: Add `listener.connection_pool` attribute ([#16168](https://github.com/hashicorp/terraform-provider-aws/issues/16168)) * data-source/aws_eks_cluster: add `kubernetes_network_config` attribute ([#15518](https://github.com/hashicorp/terraform-provider-aws/issues/15518)) -* resource/aws_storagegateway_smb_file_share - add support for `notification_policy` and `access_based_enumeration`. ([#16414](https://github.com/hashicorp/terraform-provider-aws/issues/16414)) -* resource/aws_storagegateway_smb_file_share - add plan time validation to `invalid_user_list` and `valid_user_list`. ([#16414](https://github.com/hashicorp/terraform-provider-aws/issues/16414)) +* resource/aws_storagegateway_smb_file_share: add support for `notification_policy` and `access_based_enumeration`. ([#16414](https://github.com/hashicorp/terraform-provider-aws/issues/16414)) +* resource/aws_storagegateway_smb_file_share: add plan time validation to `invalid_user_list` and `valid_user_list`. ([#16414](https://github.com/hashicorp/terraform-provider-aws/issues/16414)) * resource/aws_cognito_user_pool: add support for account recovery setting. ([#12444](https://github.com/hashicorp/terraform-provider-aws/issues/12444)) * resource/aws_eks_cluster: add `kubernetes_network_config` argument ([#15518](https://github.com/hashicorp/terraform-provider-aws/issues/15518)) * resource/aws_eks_node_group: Add `capacity_type` argument and support multiple `instance_types` (Support Spot Node Groups) ([#16510](https://github.com/hashicorp/terraform-provider-aws/issues/16510)) @@ -3262,7 +3573,7 @@ BUG FIXES * data-source/aws_s3_bucket: Use provider credentials when getting the bucket region (fix AWS China non-ICP S3 Buckets and other restrictive environments) ([#15481](https://github.com/hashicorp/terraform-provider-aws/issues/15481)) * resource/aws_apigatewayv2_stage: Correctly handle deletion of route_settings ([#16133](https://github.com/hashicorp/terraform-provider-aws/issues/16133)) -* resource/aws_backup_plan - `lifecycle` block in `copy_action` is optional ([#16116](https://github.com/hashicorp/terraform-provider-aws/issues/16116)) +* resource/aws_backup_plan: `lifecycle` block in `copy_action` is optional ([#16116](https://github.com/hashicorp/terraform-provider-aws/issues/16116)) * resource/aws_eks_fargate_profile: Serialize multiple profile creation and deletion to prevent `ResourceInUseException` errors ([#14020](https://github.com/hashicorp/terraform-provider-aws/issues/14020)) * resource/aws_organizations_organization: Prevent recreation when `feature_set` is updated to `ALL` ([#15473](https://github.com/hashicorp/terraform-provider-aws/issues/15473)) * resource/aws_s3_bucket: Use provider credentials when getting the bucket region (fix AWS China non-ICP S3 Buckets and other restrictive environments) ([#15481](https://github.com/hashicorp/terraform-provider-aws/issues/15481)) @@ -3455,7 +3766,7 @@ FEATURES ENHANCEMENTS * resource/aws_cloudwatch_event_target: Add validation to `input_transformer.input_paths` map ([#15669](https://github.com/hashicorp/terraform-provider-aws/issues/15669)) -* resource/aws_codeartifact_repository - support external connections ([#15569](https://github.com/hashicorp/terraform-provider-aws/issues/15569)) +* resource/aws_codeartifact_repository: support external connections ([#15569](https://github.com/hashicorp/terraform-provider-aws/issues/15569)) * resource/aws_fsx_lustre_file_system: Add `copy_tags_to_backups` support ([#15687](https://github.com/hashicorp/terraform-provider-aws/issues/15687)) * resource/aws_fsx_lustre_file_system: Increased maximum `automatic_backup_retention_days` from 35 to 90 ([#15641](https://github.com/hashicorp/terraform-provider-aws/issues/15641)) * resource/aws_fsx_windows_file_system: Increased maximum `automatic_backup_retention_days` from 35 to 90 ([#15641](https://github.com/hashicorp/terraform-provider-aws/issues/15641)) @@ -3848,7 +4159,7 @@ ENHANCEMENTS BUG FIXES * data-source/aws_launch_template: Prevent type error with `network_interfaces` `delete_on_termination` attribute ([#14599](https://github.com/hashicorp/terraform-provider-aws/issues/14599)) -* resource/aws_acm_certificate_validation: Prevent panic with missing `DomainValidationOptions` `ResourceRecord` attribute in API response [[#14590](https://github.com/hashicorp/terraform-provider-aws/issues/14590)] +* resource/aws_acm_certificate_validation: Prevent panic with missing `DomainValidationOptions` `ResourceRecord` attribute in API response [[#14590](https://github.com/hashicorp/terraform-provider-aws/issues/14590)] * resource/aws_ecr_repository: Prevent panic with missing `EncryptionConfiguration` attribute in API response ([#14584](https://github.com/hashicorp/terraform-provider-aws/issues/14584)) * resource/aws_wafv2_rule_group: Prevent unnecessary resource recreation with `rule` updates ([#14617](https://github.com/hashicorp/terraform-provider-aws/issues/14617)) * resource/aws_wafv2_web_acl: Prevent unnecessary resource recreation with `rule` updates ([#14616](https://github.com/hashicorp/terraform-provider-aws/issues/14616)) diff --git a/GNUmakefile b/GNUmakefile index 0e0c99864bd..d6536947646 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -14,6 +14,10 @@ ifneq ($(origin TESTS), undefined) RUNARGS = -run='$(TESTS)' endif +ifneq ($(origin SWEEPERS), undefined) + SWEEPARGS = -sweep-run='$(SWEEPERS)' +endif + default: build build: fmtcheck @@ -27,8 +31,12 @@ gen: rm -f internal/service/**/*_gen.go rm -f internal/sweep/sweep_test.go rm -f names/*_gen.go + rm -f names/caps.md rm -f website/allowed-subcategories.txt rm -f website/docs/guides/custom-service-endpoints.html.md + rm -f .semgrep-caps-aws-ec2.yml + rm -f .semgrep-configs.yml + rm -f .semgrep-service-name*.yml go generate ./... sweep: @@ -163,7 +171,7 @@ website-link-check: @scripts/markdown-link-check.sh website-link-check-ghrc: - @LINK_CHECK_CONTAINER="ghcr.io/tcort/markdown-link-check:stable" scripts/markdown-link-check.sh + @LINK_CHECK_CONTAINER="ghcr.io/tcort/markdown-link-check:stable" scripts/markdown-link-check.sh website-lint: @echo "==> Checking website against linters..." @@ -191,4 +199,14 @@ semgrep: @echo "==> Running Semgrep static analysis..." @docker run --rm --volume "${PWD}:/src" returntocorp/semgrep --config .semgrep.yml +semall: + @echo "==> Running Semgrep checks locally (must have semgrep installed)..." + @semgrep -c .semgrep.yml + @semgrep -c .semgrep-caps-aws-ec2.yml + @semgrep -c .semgrep-configs.yml + @semgrep -c .semgrep-service-name0.yml + @semgrep -c .semgrep-service-name1.yml + @semgrep -c .semgrep-service-name2.yml + @semgrep -c .semgrep-service-name3.yml + .PHONY: providerlint build gen generate-changelog gh-workflows-lint golangci-lint sweep test testacc fmt fmtcheck lint tools test-compile website-link-check website-lint website-lint-fix depscheck docscheck semgrep diff --git a/docs/contributing/contribution-checklists.md b/docs/contributing/contribution-checklists.md index 43bd219dec4..5801d282e3f 100644 --- a/docs/contributing/contribution-checklists.md +++ b/docs/contributing/contribution-checklists.md @@ -595,11 +595,11 @@ filters := namevaluesfilters.New(map[string]string{ "internet-gateway-id": d.Get("internet_gateway_id").(string), }) // Add filters based on keyvalue tags (N.B. Not applicable to all AWS services that support filtering) -filters.Add(namevaluesfilters.Ec2Tags(keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map())) +filters.Add(namevaluesfilters.EC2Tags(keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map())) // Add filters based on the custom filtering "filter" attribute. filters.Add(d.Get("filter").(*schema.Set)) -input.Filters = filters.Ec2Filters() +input.Filters = filters.EC2Filters() ``` ### Resource Filtering Documentation Implementation diff --git a/docs/contributing/data-handling-and-conversion.md b/docs/contributing/data-handling-and-conversion.md index a8d2d410483..91c7d032c26 100644 --- a/docs/contributing/data-handling-and-conversion.md +++ b/docs/contributing/data-handling-and-conversion.md @@ -619,7 +619,7 @@ To read: func expandStructure(tfMap map[string]interface{}) *service.Structure { // ... - if v, ok := tfMap["nested_attribute_name"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["nested_attribute_name"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.NestedAttributeName = expandStructure(v[0].(map[string]interface{})) } diff --git a/docs/contributing/naming.md b/docs/contributing/naming.md index 351280b1473..43666a2953d 100644 --- a/docs/contributing/naming.md +++ b/docs/contributing/naming.md @@ -99,9 +99,11 @@ A correct example is `accessanalyzer_analyzer.html.markdown`. An incorrect examp Write multiword names in Go using _MixedCaps_ (or _mixedCaps_) rather than underscores. +For more details on capitalizations we enforce with CI Semgrep tests, see the [Caps List](../../names/caps.md). + Initialisms and other abbreviations are a key difference between many camel/Pascal case interpretations and mixedCaps. **Abbreviations in mixedCaps should be the correct, human-readable case.** After all, names in code _are for humans_. (The mixedCaps convention aligns with HashiCorp's emphasis on pragmatism and beauty.) -For example, an initialism such as "VPC" should either be all capitalized ("VPC") or all lower case ("vpc"), never "Vpc" or "vPC." Similarly, in mixedCaps, "DynamoDB" should either be "DynamoDB" or "dynamoDB", depending on whether an initial cap is needed or not, and never "dynamoDb" or "DynamoDb." Some services in the AWS SDK for Go, typically older services, do not follow this Go convention. +For example, an initialism such as "VPC" should either be all capitalized ("VPC") or all lower case ("vpc"), never "Vpc" or "vPC." Similarly, in mixedCaps, "DynamoDB" should either be "DynamoDB" or "dynamoDB", depending on whether an initial cap is needed or not, and never "dynamoDb" or "DynamoDb." ### Rule diff --git a/docs/contributing/running-and-writing-acceptance-tests.md b/docs/contributing/running-and-writing-acceptance-tests.md index b1809d7eb6d..ab81b8941d1 100644 --- a/docs/contributing/running-and-writing-acceptance-tests.md +++ b/docs/contributing/running-and-writing-acceptance-tests.md @@ -55,10 +55,25 @@ Terraform Providers, see the [Extending Terraform documentation](https://www.ter ## Acceptance Tests Often Cost Money to Run -Because acceptance tests create real resources, they often cost money to run. +Our acceptance test suite creates real resources, and as a result they cost real money to run. Because the resources only exist for a short period of time, the total amount -of money required is usually a relatively small. Nevertheless, we don't want -financial limitations to be a barrier to contribution, so if you are unable to +of money required is usually a relatively small amount. That said there are particular services +which are very expensive to run and its important to be prepared for those costs. + +Some services which can be cost prohibitive include (among others): + +- WorkSpaces +- Glue +- OpenSearch +- RDS +- ACM (Amazon Certificate Manager) +- FSx +- Kinesis Analytics +- EC2 +- ElastiCache +- Storage Gateway + +We don't want financial limitations to be a barrier to contribution, so if you are unable to pay to run acceptance tests for your contribution, mention this in your pull request. We will happily accept "best effort" implementations of acceptance tests and run them for you on our side. This might mean that your PR @@ -433,7 +448,7 @@ resource "aws_example_thing" "test" { These test configurations are typical implementations we have found or allow testing to implement best practices easier, since the Terraform AWS Provider testing is expected to run against various AWS Regions and Partitions. - `acctest.AvailableEC2InstanceTypeForRegion("type1", "type2", ...)`: Typically used to replace hardcoded EC2 Instance Types. Uses `aws_ec2_instance_type_offering` data source to return an available EC2 Instance Type in preferred ordering. Reference the instance type via: `data.aws_ec2_instance_type_offering.available.instance_type`. Use `acctest.AvailableEC2InstanceTypeForRegionNamed("name", "type1", "type2", ...)` to specify a name for the data source -- `acctest.ConfigLatestAmazonLinuxHvmEbsAmi()`: Typically used to replace hardcoded EC2 Image IDs (`ami-12345678`). Uses `aws_ami` data source to find the latest Amazon Linux image. Reference the AMI ID via: `data.aws_ami.amzn-ami-minimal-hvm-ebs.id` +- `acctest.ConfigLatestAmazonLinuxHVMEBSAMI()`: Typically used to replace hardcoded EC2 Image IDs (`ami-12345678`). Uses `aws_ami` data source to find the latest Amazon Linux image. Reference the AMI ID via: `data.aws_ami.amzn-ami-minimal-hvm-ebs.id` #### Randomized Naming @@ -1432,18 +1447,18 @@ resource "aws_backup_selection" "test" { #### Hardcoded AMI IDs - [ ] __Uses aws_ami Data Source__: Any hardcoded AMI ID configuration, e.g. `ami-12345678`, should be replaced with the [`aws_ami` data source](https://www.terraform.io/docs/providers/aws/d/ami.html) pointing to an Amazon Linux image. The package `internal/acctest` includes test configuration helper functions to simplify these lookups: - - `acctest.ConfigLatestAmazonLinuxHvmEbsAmi()`: The recommended AMI for most situations, using Amazon Linux, HVM virtualization, and EBS storage. To reference the AMI ID in the test configuration: `data.aws_ami.amzn-ami-minimal-hvm-ebs.id`. + - `acctest.ConfigLatestAmazonLinuxHVMEBSAMI()`: The recommended AMI for most situations, using Amazon Linux, HVM virtualization, and EBS storage. To reference the AMI ID in the test configuration: `data.aws_ami.amzn-ami-minimal-hvm-ebs.id`. - `testAccLatestAmazonLinuxHVMInstanceStoreAMIConfig()` (EC2): AMI lookup using Amazon Linux, HVM virtualization, and Instance Store storage. Should only be used in testing that requires Instance Store storage rather than EBS. To reference the AMI ID in the test configuration: `data.aws_ami.amzn-ami-minimal-hvm-instance-store.id`. - `testAccLatestAmazonLinuxPVEBSAMIConfig()` (EC2): AMI lookup using Amazon Linux, Paravirtual virtualization, and EBS storage. Should only be used in testing that requires Paravirtual over Hardware Virtual Machine (HVM) virtualization. To reference the AMI ID in the test configuration: `data.aws_ami.amzn-ami-minimal-pv-ebs.id`. - `configLatestAmazonLinuxPvInstanceStoreAmi` (EC2): AMI lookup using Amazon Linux, Paravirtual virtualization, and Instance Store storage. Should only be used in testing that requires Paravirtual virtualization over HVM and Instance Store storage over EBS. To reference the AMI ID in the test configuration: `data.aws_ami.amzn-ami-minimal-pv-instance-store.id`. - `testAccLatestWindowsServer2016CoreAMIConfig()` (EC2): AMI lookup using Windows Server 2016 Core, HVM virtualization, and EBS storage. Should only be used in testing that requires Windows. To reference the AMI ID in the test configuration: `data.aws_ami.win2016core-ami.id`. -Here's an example of using `acctest.ConfigLatestAmazonLinuxHvmEbsAmi()` and `data.aws_ami.amzn-ami-minimal-hvm-ebs.id`: +Here's an example of using `acctest.ConfigLatestAmazonLinuxHVMEBSAMI()` and `data.aws_ami.amzn-ami-minimal-hvm-ebs.id`: ```go func testAccLaunchConfigurationDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q diff --git a/go.mod b/go.mod index be358af6f6b..259cac77b22 100644 --- a/go.mod +++ b/go.mod @@ -4,21 +4,22 @@ go 1.17 require ( github.com/ProtonMail/go-crypto v0.0.0-20210428141323-04723f9f07d7 - github.com/aws/aws-sdk-go v1.44.15 - github.com/aws/aws-sdk-go-v2 v1.16.3 - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.4 - github.com/aws/aws-sdk-go-v2/service/route53domains v1.12.4 + github.com/aws/aws-sdk-go v1.44.39 + github.com/aws/aws-sdk-go-v2 v1.16.5 + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.6 + github.com/aws/aws-sdk-go-v2/service/kendra v1.28.1 + github.com/aws/aws-sdk-go-v2/service/route53domains v1.12.6 github.com/beevik/etree v1.1.0 github.com/google/go-cmp v0.5.8 - github.com/hashicorp/aws-cloudformation-resource-schema-sdk-go v0.16.0 + github.com/hashicorp/aws-cloudformation-resource-schema-sdk-go v0.17.0 github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.16 github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2 v2.0.0-beta.17 github.com/hashicorp/awspolicyequivalence v1.5.0 github.com/hashicorp/go-cleanhttp v0.5.2 github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 github.com/hashicorp/go-multierror v1.1.1 - github.com/hashicorp/go-version v1.4.0 - github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0 + github.com/hashicorp/go-version v1.5.0 + github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 github.com/mattbaird/jsonpatch v0.0.0-20200820163806-098863c1fc24 github.com/mitchellh/copystructure v1.2.0 github.com/mitchellh/go-homedir v1.1.0 @@ -36,14 +37,14 @@ require ( github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect github.com/aws/aws-sdk-go-v2/config v1.15.4 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.12.0 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.10 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.4 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.12 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.6 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.3.11 // indirect github.com/aws/aws-sdk-go-v2/service/iam v1.18.4 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.4 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.11.4 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.16.4 // indirect - github.com/aws/smithy-go v1.11.2 // indirect + github.com/aws/smithy-go v1.11.3 // indirect github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/evanphx/json-patch v0.5.2 // indirect @@ -52,14 +53,14 @@ require ( github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-checkpoint v0.5.0 // indirect github.com/hashicorp/go-hclog v1.2.0 // indirect - github.com/hashicorp/go-plugin v1.4.3 // indirect + github.com/hashicorp/go-plugin v1.4.4 // indirect github.com/hashicorp/go-uuid v1.0.3 // indirect github.com/hashicorp/hc-install v0.3.2 // indirect github.com/hashicorp/hcl/v2 v2.12.0 // indirect github.com/hashicorp/logutils v1.0.0 // indirect github.com/hashicorp/terraform-exec v0.16.1 // indirect - github.com/hashicorp/terraform-json v0.13.0 // indirect - github.com/hashicorp/terraform-plugin-go v0.9.0 // indirect + github.com/hashicorp/terraform-json v0.14.0 // indirect + github.com/hashicorp/terraform-plugin-go v0.9.1 // indirect github.com/hashicorp/terraform-plugin-log v0.4.0 // indirect github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896 // indirect github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 // indirect @@ -85,6 +86,6 @@ require ( golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/appengine v1.6.6 // indirect google.golang.org/genproto v0.0.0-20200711021454-869866162049 // indirect - google.golang.org/grpc v1.45.0 // indirect + google.golang.org/grpc v1.46.0 // indirect google.golang.org/protobuf v1.28.0 // indirect ) diff --git a/go.sum b/go.sum index af207d96853..b61982f2f64 100644 --- a/go.sum +++ b/go.sum @@ -26,34 +26,41 @@ github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkE github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/aws/aws-sdk-go v1.42.18/go.mod h1:585smgzpB/KqRA+K3y/NL/oYRqQvpNJYvLm+LY1U59Q= github.com/aws/aws-sdk-go v1.42.52/go.mod h1:OGr6lGMAKGlG9CVrYnWYDKIyb829c6EVBRjxqjmPepc= -github.com/aws/aws-sdk-go v1.44.15 h1:z02BVeV6k7hZMfWEQmKh3X23s3F9PBHFCcIVfNlut7A= -github.com/aws/aws-sdk-go v1.44.15/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= -github.com/aws/aws-sdk-go-v2 v1.16.3 h1:0W1TSJ7O6OzwuEvIXAtJGvOeQ0SGAhcpxPN2/NK5EhM= +github.com/aws/aws-sdk-go v1.44.39 h1:pMxYLqnuDidT0ZTDAhYC66fb3W3Yc+oShmfzEL4fTDI= +github.com/aws/aws-sdk-go v1.44.39/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= github.com/aws/aws-sdk-go-v2 v1.16.3/go.mod h1:ytwTPBG6fXTZLxxeeCCWj2/EMYp/xDUgX+OET6TLNNU= +github.com/aws/aws-sdk-go-v2 v1.16.5 h1:Ah9h1TZD9E2S1LzHpViBO3Jz9FPL5+rmflmb8hXirtI= +github.com/aws/aws-sdk-go-v2 v1.16.5/go.mod h1:Wh7MEsmEApyL5hrWzpDkba4gwAPc5/piwLVLFnCxp48= github.com/aws/aws-sdk-go-v2/config v1.15.4 h1:P4mesY1hYUxru4f9SU0XxNKXmzfxsD0FtMIPRBjkH7Q= github.com/aws/aws-sdk-go-v2/config v1.15.4/go.mod h1:ZijHHh0xd/A+ZY53az0qzC5tT46kt4JVCePf2NX9Lk4= github.com/aws/aws-sdk-go-v2/credentials v1.12.0 h1:4R/NqlcRFSkR0wxOhgHi+agGpbEr5qMCjn7VqUIJY+E= github.com/aws/aws-sdk-go-v2/credentials v1.12.0/go.mod h1:9YWk7VW+eyKsoIL6/CljkTrNVWBSK9pkqOPUuijid4A= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.4 h1:FP8gquGeGHHdfY6G5llaMQDF+HAf20VKc8opRwmjf04= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.4/go.mod h1:u/s5/Z+ohUQOPXl00m2yJVyioWDECsbpXTQlaqSlufc= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.10 h1:uFWgo6mGJI1n17nbcvSc6fxVuR3xLNqvXt12JCnEcT8= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.6 h1:+NZzDh/RpcQTpo9xMFUgkseIam6PC+YJbdhbQp1NOXI= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.6/go.mod h1:ClLMcuQA/wcHPmOIfNzNI4Y1Q0oDbmEkbYhMFOzHDh8= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.10/go.mod h1:F+EZtuIwjlv35kRJPyBGcsA4f7bnSoz15zOQ2lJq1Z4= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.4 h1:cnsvEKSoHN4oAN7spMMr0zhEW2MHnhAVpmqQg8E6UcM= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.12 h1:Zt7DDk5V7SyQULUUwIKzsROtVzp/kVvcz15uQx/Tkow= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.12/go.mod h1:Afj/U8svX6sJ77Q+FPWMzabJ9QjbwP32YlopgKALUpg= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.4/go.mod h1:8glyUqVIM4AmeenIsPo0oVh3+NUwnsQml2OFupfQW+0= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.6 h1:eeXdGVtXEe+2Jc49+/vAzna3FAQnUD4AagAw8tzbmfc= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.6/go.mod h1:FwpAKI+FBPIELJIdmQzlLtRe8LQSOreMcM2wBsPMvvc= github.com/aws/aws-sdk-go-v2/internal/ini v1.3.11 h1:6cZRymlLEIlDTEB0+5+An6Zj1CKt6rSE69tOmFeu1nk= github.com/aws/aws-sdk-go-v2/internal/ini v1.3.11/go.mod h1:0MR+sS1b/yxsfAPvAESrw8NfwUoxMinDyw6EYR9BS2U= github.com/aws/aws-sdk-go-v2/service/iam v1.18.4 h1:E41guA79mjEbwJdh0zXz1d8+Zt4zxRr+b1ipiVbKXzs= github.com/aws/aws-sdk-go-v2/service/iam v1.18.4/go.mod h1:FpNvAfCZyIQ3qeNJUOw4CShKvdizHblXqAvSk0qmyL4= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.4 h1:b16QW0XWl0jWjLABFc1A+uh145Oqv+xDcObNk0iQgUk= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.4/go.mod h1:uKkN7qmSIsNJVyMtxNQoCEYMvFEXbOg9fwCJPdfp2u8= -github.com/aws/aws-sdk-go-v2/service/route53domains v1.12.4 h1:jfv+dUsxVtv/e0Nlw93Gltd1IZ1P9k5qmcizz43kkzM= -github.com/aws/aws-sdk-go-v2/service/route53domains v1.12.4/go.mod h1:EfCWWmp+qWzwBON1SeWld+iFizfk+J1Y7YMvrPbxZP0= +github.com/aws/aws-sdk-go-v2/service/kendra v1.28.1 h1:Zd6mXhsHclO95seFAuI3rG2FIdVsi+eUezfT7DHK2mE= +github.com/aws/aws-sdk-go-v2/service/kendra v1.28.1/go.mod h1:X65PE/R8p6R3G8z+7kiw4VIuiXGXqpFLTgucSouVAwQ= +github.com/aws/aws-sdk-go-v2/service/route53domains v1.12.6 h1:72/ajL/TX9tqXgi5PJdljikQAnHePsEPSB7vyd+sbm0= +github.com/aws/aws-sdk-go-v2/service/route53domains v1.12.6/go.mod h1:3jGaTlaOTt2+qVc7mUwRhEWiZQ2al+Rga4lINIloO7g= github.com/aws/aws-sdk-go-v2/service/sso v1.11.4 h1:Uw5wBybFQ1UeA9ts0Y07gbv0ncZnIAyw858tDW0NP2o= github.com/aws/aws-sdk-go-v2/service/sso v1.11.4/go.mod h1:cPDwJwsP4Kff9mldCXAmddjJL6JGQqtA3Mzer2zyr88= github.com/aws/aws-sdk-go-v2/service/sts v1.16.4 h1:+xtV90n3abQmgzk1pS++FdxZTrPEDgQng6e4/56WR2A= github.com/aws/aws-sdk-go-v2/service/sts v1.16.4/go.mod h1:lfSYenAXtavyX2A1LsViglqlG9eEFYxNryTZS5rn3QE= -github.com/aws/smithy-go v1.11.2 h1:eG/N+CcUMAvsdffgMvjMKwfyDzIkjM6pfxMJ8Mzc6mE= github.com/aws/smithy-go v1.11.2/go.mod h1:3xHYmszWVx2c0kIwQeEVf9uSm4fYZt67FBJnwub1bgM= +github.com/aws/smithy-go v1.11.3 h1:DQixirEFM9IaKxX1olZ3ke3nvxRS2xMDteKIDWxozW8= +github.com/aws/smithy-go v1.11.3/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/beevik/etree v1.1.0 h1:T0xke/WvNtMoCqgzPhkX2r4rjY3GDZFi+FjpRZY2Jbs= github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A= github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI= @@ -64,8 +71,8 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= -github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -77,7 +84,7 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/evanphx/json-patch v0.5.2 h1:xVCHIVMUu1wtM/VkR9jVZ45N3FhZfYMMYGorLCR8P3k= github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= @@ -128,8 +135,8 @@ github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/hashicorp/aws-cloudformation-resource-schema-sdk-go v0.16.0 h1:r2RUzeK2gAitl0HY9SLH1axAEu+6aPBY20g1jOoBepM= -github.com/hashicorp/aws-cloudformation-resource-schema-sdk-go v0.16.0/go.mod h1:C6GVuO9RWOrt6QCGTmLCOYuSHpkfQSBDuRqTteOlo0g= +github.com/hashicorp/aws-cloudformation-resource-schema-sdk-go v0.17.0 h1:Hdg5SicobWjKu3qhEZ4b3h6aMJlh4F9KON97Ugxz7s4= +github.com/hashicorp/aws-cloudformation-resource-schema-sdk-go v0.17.0/go.mod h1:C6GVuO9RWOrt6QCGTmLCOYuSHpkfQSBDuRqTteOlo0g= github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.16 h1:Ac/qv9kXBBeyIAGkZdy+Idmw4Avb3mdxPVdT0rI/+aY= github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.16/go.mod h1:xySJRdcDB8hVSmboo3X+evGhZPzBYwPmZbQxLgfGfBw= github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2 v2.0.0-beta.17 h1:hUG69tIA35oNI2hoeURCnShSViDNCmcQdLSngP89124= @@ -152,15 +159,16 @@ github.com/hashicorp/go-hclog v1.2.0 h1:La19f8d7WIlm4ogzNHB0JGqs5AUDAZ2UfCY4sJXc github.com/hashicorp/go-hclog v1.2.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-plugin v1.4.3 h1:DXmvivbWD5qdiBts9TpBC7BYL1Aia5sxbRgQB+v6UZM= -github.com/hashicorp/go-plugin v1.4.3/go.mod h1:5fGEH17QVwTTcR0zV7yhDPLLmFX9YSZ38b18Udy6vYQ= +github.com/hashicorp/go-plugin v1.4.4 h1:NVdrSdFRt3SkZtNckJ6tog7gbpRrcbOjQi/rgF7JYWQ= +github.com/hashicorp/go-plugin v1.4.4/go.mod h1:viDMjcLJuDui6pXb8U4HVfb8AamCWhHGUjr2IrTF67s= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.4.0 h1:aAQzgqIrRKRa7w75CKpbBxYsmUoPjzVm1W59ca1L0J4= github.com/hashicorp/go-version v1.4.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.5.0 h1:O293SZ2Eg+AAYijkVK3jR786Am1bhDEh2GHT0tIVE5E= +github.com/hashicorp/go-version v1.5.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/hc-install v0.3.1/go.mod h1:3LCdWcCDS1gaHC9mhHCGbkYfoY6vdsKohGjugbZdZak= github.com/hashicorp/hc-install v0.3.2 h1:oiQdJZvXmkNcRcEOOfM5n+VTsvNjWQeOjfAoO6dKSH8= github.com/hashicorp/hc-install v0.3.2/go.mod h1:xMG6Tr8Fw1WFjlxH0A9v61cW15pFwgEGqEz0V4jisHs= @@ -170,15 +178,15 @@ github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/terraform-exec v0.16.1 h1:NAwZFJW2L2SaCBVZoVaH8LPImLOGbPLkSHy0IYbs2uE= github.com/hashicorp/terraform-exec v0.16.1/go.mod h1:aj0lVshy8l+MHhFNoijNHtqTJQI3Xlowv5EOsEaGO7M= -github.com/hashicorp/terraform-json v0.13.0 h1:Li9L+lKD1FO5RVFRM1mMMIBDoUHslOniyEi5CM+FWGY= github.com/hashicorp/terraform-json v0.13.0/go.mod h1:y5OdLBCT+rxbwnpxZs9kGL7R9ExU76+cpdY8zHwoazk= -github.com/hashicorp/terraform-plugin-go v0.9.0 h1:FvLY/3z4SNVatPZdoFcyrlNbCar+WyyOTv5X4Tp+WZc= -github.com/hashicorp/terraform-plugin-go v0.9.0/go.mod h1:EawBkgjBWNf7jiKnVoyDyF39OSV+u6KUX+Y73EPj3oM= -github.com/hashicorp/terraform-plugin-log v0.3.0/go.mod h1:EjueSP/HjlyFAsDqt+okpCPjkT4NDynAe32AeDC4vps= +github.com/hashicorp/terraform-json v0.14.0 h1:sh9iZ1Y8IFJLx+xQiKHGud6/TSUCM0N8e17dKDpqV7s= +github.com/hashicorp/terraform-json v0.14.0/go.mod h1:5A9HIWPkk4e5aeeXIBbkcOvaZbIYnAIkEyqP2pNSckM= +github.com/hashicorp/terraform-plugin-go v0.9.1 h1:vXdHaQ6aqL+OF076nMSBV+JKPdmXlzG5mzVDD04WyPs= +github.com/hashicorp/terraform-plugin-go v0.9.1/go.mod h1:ItjVSlQs70otlzcCwlPcU8FRXLdO973oYFRZwAOxy8M= github.com/hashicorp/terraform-plugin-log v0.4.0 h1:F3eVnm8r2EfQCe2k9blPIiF/r2TT01SHijXnS7bujvc= github.com/hashicorp/terraform-plugin-log v0.4.0/go.mod h1:9KclxdunFownr4pIm1jdmwKRmE4d6HVG2c9XDq47rpg= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0 h1:9fjPgCenJqnbjo95SDcbJ+YdLyEC1N35cwKWcRWhJTQ= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0/go.mod h1:hLa0sTiySU/AWEgV2GxJh0/pQIqcCmm30IPja9N9lTg= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 h1:Qr5fWNg1SPSfCRMtou67Y6Kcy9UnMYRNlIJTKRuUvXU= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0/go.mod h1:b+LFg8WpYgFgvEBP/6Htk5H9/pJp1V1E8NJAekfH2Ws= github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896 h1:1FGtlkJw87UsTMg5s8jrekrHmUPUJaMcu6ELiVhQrNw= github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896/go.mod h1:bzBPnUIkI0RxauU8Dqo+2KrZZ28Cf48s8V6IHt3p4co= github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 h1:HKLsbzeOsfXmKNpr3GiT18XAblV0BjCbzL8KQAMZGa0= @@ -323,6 +331,7 @@ golang.org/x/net v0.0.0-20191009170851-d66e71096ffb/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210326060303-6b1517762897/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k= @@ -354,7 +363,9 @@ golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -407,8 +418,8 @@ google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8 google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.45.0 h1:NEpgUqV3Z+ZjkqMsxMg11IaDrXY4RY6CQukSGK0uI1M= -google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.46.0 h1:oCjezcn6g6A75TGoKYBPgKmVBLexhYLM6MebdrPApP8= +google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0/go.mod h1:DNq5QpG7LJqD2AamLZ7zvKE0DEpVl2BSEVjFycAAjRY= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= diff --git a/infrastructure/repository/labels-service.tf b/infrastructure/repository/labels-service.tf index fd2b04c4fe4..5b230193ac4 100644 --- a/infrastructure/repository/labels-service.tf +++ b/infrastructure/repository/labels-service.tf @@ -107,6 +107,7 @@ variable "service_labels" { "elbv2", "emr", "emrcontainers", + "emrserverless", "events", "evidently", "finspace", diff --git a/infrastructure/repository/main.tf b/infrastructure/repository/main.tf index a50a8208179..51432128d84 100644 --- a/infrastructure/repository/main.tf +++ b/infrastructure/repository/main.tf @@ -10,7 +10,7 @@ terraform { required_providers { github = { source = "integrations/github" - version = "4.24.1" + version = "4.26.1" } } diff --git a/internal/acctest/acctest.go b/internal/acctest/acctest.go index 7cf619f0e26..5c3ed092d4a 100644 --- a/internal/acctest/acctest.go +++ b/internal/acctest/acctest.go @@ -58,8 +58,8 @@ const ( ) const RFC3339RegexPattern = `^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?([Zz]|([+-]([01][0-9]|2[0-3]):[0-5][0-9]))$` -const awsRegionRegexp = `[a-z]{2}(-[a-z]+)+-\d` -const awsAccountIDRegexp = `(aws|aws-managed|\d{12})` +const regionRegexp = `[a-z]{2}(-[a-z]+)+-\d` +const accountIDRegexp = `(aws|aws-managed|\d{12})` // Skip implements a wrapper for (*testing.T).Skip() to prevent unused linting reports // @@ -193,7 +193,7 @@ func PreCheck(t *testing.T) { // Since we are outside the scope of the Terraform configuration we must // call Configure() to properly initialize the provider configuration. testAccProviderConfigure.Do(func() { - conns.FailIfAllEnvVarEmpty(t, []string{conns.EnvVarProfile, conns.EnvVarAccessKeyId, conns.EnvVarContainerCredentialsFullUri}, "credentials for running acceptance testing") + conns.FailIfAllEnvVarEmpty(t, []string{conns.EnvVarProfile, conns.EnvVarAccessKeyId, conns.EnvVarContainerCredentialsFullURI}, "credentials for running acceptance testing") if os.Getenv(conns.EnvVarAccessKeyId) != "" { conns.FailIfEnvVarEmpty(t, conns.EnvVarSecretAccessKey, "static credentials value when using "+conns.EnvVarAccessKeyId) @@ -459,9 +459,9 @@ func MatchResourceAttrGlobalARN(resourceName, attributeName, arnService string, func CheckResourceAttrRegionalARNIgnoreRegionAndAccount(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc { return func(s *terraform.State) error { arnRegexp := arn.ARN{ - AccountID: awsAccountIDRegexp, + AccountID: accountIDRegexp, Partition: Partition(), - Region: awsRegionRegexp, + Region: regionRegexp, Resource: arnResource, Service: arnService, }.String() @@ -1199,7 +1199,7 @@ provider "aws" { `, os.Getenv(conns.EnvVarAccAssumeRoleARN), policy) } -const testAccCheckAWSProviderConfigAssumeRoleEmpty = ` +const testAccProviderConfig_assumeRoleEmpty = ` provider "aws" { assume_role { } @@ -1668,10 +1668,10 @@ data "aws_ec2_instance_type_offering" "%[1]s" { `, name, strings.Join(preferredInstanceTypes, "\", \"")) } -// ConfigLatestAmazonLinuxHvmEbsAmi returns the configuration for a data source that +// ConfigLatestAmazonLinuxHVMEBSAMI returns the configuration for a data source that // describes the latest Amazon Linux AMI using HVM virtualization and an EBS root device. // The data source is named 'amzn-ami-minimal-hvm-ebs'. -func ConfigLatestAmazonLinuxHvmEbsAmi() string { +func ConfigLatestAmazonLinuxHVMEBSAMI() string { return ` data "aws_ami" "amzn-ami-minimal-hvm-ebs" { most_recent = true @@ -1690,6 +1690,44 @@ data "aws_ami" "amzn-ami-minimal-hvm-ebs" { ` } +func configLatestAmazonLinux2HVMEBSAMI(architecture string) string { + return fmt.Sprintf(` +data "aws_ami" "amzn2-ami-minimal-hvm-ebs-%[1]s" { + most_recent = true + owners = ["amazon"] + + filter { + name = "name" + values = ["amzn2-ami-minimal-hvm-*"] + } + + filter { + name = "root-device-type" + values = ["ebs"] + } + + filter { + name = "architecture" + values = [%[1]q] + } +} +`, architecture) +} + +// ConfigLatestAmazonLinux2HVMEBSX8664AMI returns the configuration for a data source that +// describes the latest Amazon Linux 2 x86_64 AMI using HVM virtualization and an EBS root device. +// The data source is named 'amzn2-ami-minimal-hvm-ebs-x86_64'. +func ConfigLatestAmazonLinux2HVMEBSX8664AMI() string { + return configLatestAmazonLinux2HVMEBSAMI(ec2.ArchitectureValuesX8664) +} + +// ConfigLatestAmazonLinux2HVMEBSARM64AMI returns the configuration for a data source that +// describes the latest Amazon Linux 2 arm64 AMI using HVM virtualization and an EBS root device. +// The data source is named 'amzn2-ami-minimal-hvm-ebs-arm64'. +func ConfigLatestAmazonLinux2HVMEBSARM64AMI() string { + return configLatestAmazonLinux2HVMEBSAMI(ec2.ArchitectureValuesArm64) +} + func ConfigLambdaBase(policyName, roleName, sgName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -1826,9 +1864,9 @@ resource "aws_security_group" "sg_for_lambda" { `, policyName, roleName, sgName) } -func ConfigVpcWithSubnets(rName string, subnetCount int) string { +func ConfigVPCWithSubnets(rName string, subnetCount int) string { return ConfigCompose( - ConfigAvailableAZsNoOptIn(), + ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/acctest/crypto_test.go b/internal/acctest/crypto_test.go index 15bdc73014e..38348214ba1 100644 --- a/internal/acctest/crypto_test.go +++ b/internal/acctest/crypto_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -func TestTlsRsaPrivateKeyPem(t *testing.T) { +func TestTLSRSAPrivateKeyPEM(t *testing.T) { key := TLSRSAPrivateKeyPEM(2048) if !strings.Contains(key, pemBlockTypeRsaPrivateKey) { @@ -13,7 +13,7 @@ func TestTlsRsaPrivateKeyPem(t *testing.T) { } } -func TestTlsRsaPublicKeyPem(t *testing.T) { +func TestTLSRSAPublicKeyPEM(t *testing.T) { privateKey := TLSRSAPrivateKeyPEM(2048) publicKey := TLSRSAPublicKeyPEM(privateKey) @@ -22,7 +22,7 @@ func TestTlsRsaPublicKeyPem(t *testing.T) { } } -func TestTlsRsaX509LocallySignedCertificatePem(t *testing.T) { +func TestTLSRSAX509LocallySignedCertificatePEM(t *testing.T) { caKey := TLSRSAPrivateKeyPEM(2048) caCertificate := TLSRSAX509SelfSignedCACertificatePEM(caKey) key := TLSRSAPrivateKeyPEM(2048) @@ -33,7 +33,7 @@ func TestTlsRsaX509LocallySignedCertificatePem(t *testing.T) { } } -func TestTlsRsaX509SelfSignedCaCertificatePem(t *testing.T) { +func TestTLSRSAX509SelfSignedCACertificatePEM(t *testing.T) { caKey := TLSRSAPrivateKeyPEM(2048) caCertificate := TLSRSAX509SelfSignedCACertificatePEM(caKey) @@ -42,7 +42,7 @@ func TestTlsRsaX509SelfSignedCaCertificatePem(t *testing.T) { } } -func TestTlsRsaX509SelfSignedCertificatePem(t *testing.T) { +func TestTLSRSAX509SelfSignedCertificatePEM(t *testing.T) { key := TLSRSAPrivateKeyPEM(2048) certificate := TLSRSAX509SelfSignedCertificatePEM(key, "example.com") @@ -51,7 +51,7 @@ func TestTlsRsaX509SelfSignedCertificatePem(t *testing.T) { } } -func TestTlsRsaX509CertificateRequestPem(t *testing.T) { +func TestTLSRSAX509CertificateRequestPEM(t *testing.T) { csr, key := TLSRSAX509CertificateRequestPEM(2048, "example.com") if !strings.Contains(csr, pemBlockTypeCertificateRequest) { diff --git a/internal/acctest/ec2_classic.go b/internal/acctest/ec2_classic.go index a813cbe23d9..954d4a12ec4 100644 --- a/internal/acctest/ec2_classic.go +++ b/internal/acctest/ec2_classic.go @@ -17,7 +17,7 @@ import ( const ( // EC2-Classic region testing environment variable name - Ec2ClassicRegionEnvVar = "AWS_EC2_CLASSIC_REGION" + ec2ClassicRegionEnvVar = "AWS_EC2_CLASSIC_REGION" ) // ProviderEC2Classic is the EC2-Classic provider instance @@ -67,7 +67,7 @@ func ConfigEC2ClassicRegionProvider() string { // EC2ClassicRegion returns the EC2-Classic region for testing func EC2ClassicRegion() string { - v := os.Getenv(Ec2ClassicRegionEnvVar) + v := os.Getenv(ec2ClassicRegionEnvVar) if v != "" { return v diff --git a/internal/acctest/provider_test.go b/internal/acctest/provider_test.go index b32b03eac6a..22f3b25c9e2 100644 --- a/internal/acctest/provider_test.go +++ b/internal/acctest/provider_test.go @@ -80,7 +80,7 @@ func TestAccProvider_DefaultTags_emptyBlock(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccDefaultTagsEmptyConfigurationBlockConfig(), + Config: testAccProviderConfig_defaultTagsEmptyConfigurationBlock(), Check: resource.ComposeTestCheckFunc( testAccCheckProviderDefaultTags_Tags(&providers, map[string]string{}), ), @@ -98,7 +98,7 @@ func TestAccProvider_DefaultTagsTags_none(t *testing.T) { ProviderFactories: FactoriesInternal(&providers), CheckDestroy: nil, Steps: []resource.TestStep{ - { + { // nosemgrep:test-config-funcs-correct-form Config: ConfigDefaultTags_Tags0(), Check: resource.ComposeTestCheckFunc( testAccCheckProviderDefaultTags_Tags(&providers, map[string]string{}), @@ -117,7 +117,7 @@ func TestAccProvider_DefaultTagsTags_one(t *testing.T) { ProviderFactories: FactoriesInternal(&providers), CheckDestroy: nil, Steps: []resource.TestStep{ - { + { // nosemgrep:test-config-funcs-correct-form Config: ConfigDefaultTags_Tags1("test", "value"), Check: resource.ComposeTestCheckFunc( testAccCheckProviderDefaultTags_Tags(&providers, map[string]string{"test": "value"}), @@ -136,7 +136,7 @@ func TestAccProvider_DefaultTagsTags_multiple(t *testing.T) { ProviderFactories: FactoriesInternal(&providers), CheckDestroy: nil, Steps: []resource.TestStep{ - { + { // nosemgrep:test-config-funcs-correct-form Config: ConfigDefaultTags_Tags2("test1", "value1", "test2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckProviderDefaultTags_Tags(&providers, map[string]string{ @@ -159,7 +159,7 @@ func TestAccProvider_DefaultAndIgnoreTags_emptyBlocks(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccDefaultAndIgnoreTagsEmptyConfigurationBlockConfig(), + Config: testAccProviderConfig_defaultAndIgnoreTagsEmptyConfigurationBlock(), Check: resource.ComposeTestCheckFunc( testAccCheckProviderDefaultTags_Tags(&providers, map[string]string{}), testAccCheckIgnoreTagsKeys(&providers, []string{}), @@ -186,7 +186,7 @@ func TestAccProvider_endpoints(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccEndpointsConfig(endpoints.String()), + Config: testAccProviderConfig_endpoints(endpoints.String()), Check: resource.ComposeTestCheckFunc( testAccCheckEndpoints(&providers), ), @@ -206,7 +206,7 @@ func TestAccProvider_fipsEndpoint(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccFIPSEndpointConfig(fmt.Sprintf("https://s3-fips.%s.%s", Region(), PartitionDNSSuffix()), rName), + Config: testAccProviderConfig_fipsEndpoint(fmt.Sprintf("https://s3-fips.%s.%s", Region(), PartitionDNSSuffix()), rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "bucket", rName), ), @@ -229,7 +229,7 @@ func TestAccProvider_unusualEndpoints(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccUnusualEndpointsConfig(unusual1, unusual2, unusual3), + Config: testAccProviderConfig_unusualEndpoints(unusual1, unusual2, unusual3), Check: resource.ComposeTestCheckFunc( testAccCheckUnusualEndpoints(&providers, unusual1, unusual2, unusual3), ), @@ -248,7 +248,7 @@ func TestAccProvider_IgnoreTags_emptyBlock(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIgnoreTagsEmptyConfigurationBlockConfig(), + Config: testAccProviderConfig_ignoreTagsEmptyConfigurationBlock(), Check: resource.ComposeTestCheckFunc( testAccCheckIgnoreTagsKeys(&providers, []string{}), testAccCheckIgnoreTagsKeyPrefixes(&providers, []string{}), @@ -268,7 +268,7 @@ func TestAccProvider_IgnoreTagsKeyPrefixes_none(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIgnoreTagsKeyPrefixes0Config(), + Config: testAccProviderConfig_ignoreTagsKeyPrefixes0(), Check: resource.ComposeTestCheckFunc( testAccCheckIgnoreTagsKeyPrefixes(&providers, []string{}), ), @@ -287,7 +287,7 @@ func TestAccProvider_IgnoreTagsKeyPrefixes_one(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIgnoreTagsKeyPrefixes3Config("test"), + Config: testAccProviderConfig_ignoreTagsKeyPrefixes3("test"), Check: resource.ComposeTestCheckFunc( testAccCheckIgnoreTagsKeyPrefixes(&providers, []string{"test"}), ), @@ -306,7 +306,7 @@ func TestAccProvider_IgnoreTagsKeyPrefixes_multiple(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIgnoreTagsKeyPrefixes2Config("test1", "test2"), + Config: testAccProviderConfig_ignoreTagsKeyPrefixes2("test1", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckIgnoreTagsKeyPrefixes(&providers, []string{"test1", "test2"}), ), @@ -325,7 +325,7 @@ func TestAccProvider_IgnoreTagsKeys_none(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIgnoreTagsKeys0Config(), + Config: testAccProviderConfig_ignoreTagsKeys0(), Check: resource.ComposeTestCheckFunc( testAccCheckIgnoreTagsKeys(&providers, []string{}), ), @@ -344,7 +344,7 @@ func TestAccProvider_IgnoreTagsKeys_one(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIgnoreTagsKeys1Config("test"), + Config: testAccProviderConfig_ignoreTagsKeys1("test"), Check: resource.ComposeTestCheckFunc( testAccCheckIgnoreTagsKeys(&providers, []string{"test"}), ), @@ -363,7 +363,7 @@ func TestAccProvider_IgnoreTagsKeys_multiple(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIgnoreTagsKeys2Config("test1", "test2"), + Config: testAccProviderConfig_ignoreTagsKeys2("test1", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckIgnoreTagsKeys(&providers, []string{"test1", "test2"}), ), @@ -372,7 +372,7 @@ func TestAccProvider_IgnoreTagsKeys_multiple(t *testing.T) { }) } -func TestAccProvider_Region_awsC2S(t *testing.T) { +func TestAccProvider_Region_c2s(t *testing.T) { var providers []*schema.Provider resource.ParallelTest(t, resource.TestCase{ @@ -382,7 +382,7 @@ func TestAccProvider_Region_awsC2S(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccRegionConfig(endpoints.UsIsoEast1RegionID), + Config: testAccProviderConfig_region(endpoints.UsIsoEast1RegionID), Check: resource.ComposeTestCheckFunc( testAccCheckDNSSuffix(&providers, "c2s.ic.gov"), testAccCheckPartition(&providers, endpoints.AwsIsoPartitionID), @@ -394,7 +394,7 @@ func TestAccProvider_Region_awsC2S(t *testing.T) { }) } -func TestAccProvider_Region_awsChina(t *testing.T) { +func TestAccProvider_Region_china(t *testing.T) { var providers []*schema.Provider resource.ParallelTest(t, resource.TestCase{ @@ -404,7 +404,7 @@ func TestAccProvider_Region_awsChina(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccRegionConfig(endpoints.CnNorthwest1RegionID), + Config: testAccProviderConfig_region(endpoints.CnNorthwest1RegionID), Check: resource.ComposeTestCheckFunc( testAccCheckDNSSuffix(&providers, "amazonaws.com.cn"), testAccCheckPartition(&providers, endpoints.AwsCnPartitionID), @@ -416,7 +416,7 @@ func TestAccProvider_Region_awsChina(t *testing.T) { }) } -func TestAccProvider_Region_awsCommercial(t *testing.T) { +func TestAccProvider_Region_commercial(t *testing.T) { var providers []*schema.Provider resource.ParallelTest(t, resource.TestCase{ @@ -426,7 +426,7 @@ func TestAccProvider_Region_awsCommercial(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccRegionConfig(endpoints.UsWest2RegionID), + Config: testAccProviderConfig_region(endpoints.UsWest2RegionID), Check: resource.ComposeTestCheckFunc( testAccCheckDNSSuffix(&providers, "amazonaws.com"), testAccCheckPartition(&providers, endpoints.AwsPartitionID), @@ -438,7 +438,7 @@ func TestAccProvider_Region_awsCommercial(t *testing.T) { }) } -func TestAccProvider_Region_awsGovCloudUs(t *testing.T) { +func TestAccProvider_Region_govCloud(t *testing.T) { var providers []*schema.Provider resource.ParallelTest(t, resource.TestCase{ @@ -448,7 +448,7 @@ func TestAccProvider_Region_awsGovCloudUs(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccRegionConfig(endpoints.UsGovWest1RegionID), + Config: testAccProviderConfig_region(endpoints.UsGovWest1RegionID), Check: resource.ComposeTestCheckFunc( testAccCheckDNSSuffix(&providers, "amazonaws.com"), testAccCheckPartition(&providers, endpoints.AwsUsGovPartitionID), @@ -460,7 +460,7 @@ func TestAccProvider_Region_awsGovCloudUs(t *testing.T) { }) } -func TestAccProvider_Region_awsSC2S(t *testing.T) { +func TestAccProvider_Region_sc2s(t *testing.T) { var providers []*schema.Provider resource.ParallelTest(t, resource.TestCase{ @@ -470,7 +470,7 @@ func TestAccProvider_Region_awsSC2S(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccRegionConfig(endpoints.UsIsobEast1RegionID), + Config: testAccProviderConfig_region(endpoints.UsIsobEast1RegionID), Check: resource.ComposeTestCheckFunc( testAccCheckDNSSuffix(&providers, "sc2s.sgov.gov"), testAccCheckPartition(&providers, endpoints.AwsIsoBPartitionID), @@ -492,7 +492,7 @@ func TestAccProvider_Region_stsRegion(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccSTSRegionConfig(endpoints.UsEast1RegionID, endpoints.UsWest2RegionID), + Config: testAccProviderConfig_stsRegion(endpoints.UsEast1RegionID, endpoints.UsWest2RegionID), Check: resource.ComposeTestCheckFunc( testAccCheckRegion(&providers, endpoints.UsEast1RegionID), testAccCheckSTSRegion(&providers, endpoints.UsWest2RegionID), @@ -513,7 +513,7 @@ func TestAccProvider_AssumeRole_empty(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccCheckAWSProviderConfigAssumeRoleEmpty, + Config: testAccProviderConfig_assumeRoleEmpty, Check: resource.ComposeTestCheckFunc( CheckCallerIdentityAccountID("data.aws_caller_identity.current"), ), @@ -944,7 +944,7 @@ func testAccCheckUnusualEndpoints(providers *[]*schema.Provider, unusual1, unusu } } -func testAccEndpointsConfig(endpoints string) string { +func testAccProviderConfig_endpoints(endpoints string) string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -962,7 +962,7 @@ provider "aws" { `, endpoints)) } -func testAccFIPSEndpointConfig(endpoint, rName string) string { +func testAccProviderConfig_fipsEndpoint(endpoint, rName string) string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -985,7 +985,7 @@ resource "aws_s3_bucket_acl" "test" { `, endpoint, rName)) } -func testAccUnusualEndpointsConfig(unusual1, unusual2, unusual3 []string) string { +func testAccProviderConfig_unusualEndpoints(unusual1, unusual2, unusual3 []string) string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1005,7 +1005,7 @@ provider "aws" { `, unusual1[0], unusual1[2], unusual2[0], unusual2[2], unusual3[0], unusual3[2])) } -func testAccIgnoreTagsKeys0Config() string { +func testAccProviderConfig_ignoreTagsKeys0() string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1019,7 +1019,7 @@ provider "aws" { `) } -func testAccIgnoreTagsKeys1Config(tag1 string) string { +func testAccProviderConfig_ignoreTagsKeys1(tag1 string) string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1037,7 +1037,7 @@ provider "aws" { `, tag1)) } -func testAccIgnoreTagsKeys2Config(tag1, tag2 string) string { +func testAccProviderConfig_ignoreTagsKeys2(tag1, tag2 string) string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1055,7 +1055,7 @@ provider "aws" { `, tag1, tag2)) } -func testAccIgnoreTagsKeyPrefixes0Config() string { +func testAccProviderConfig_ignoreTagsKeyPrefixes0() string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1069,7 +1069,7 @@ provider "aws" { `) } -func testAccIgnoreTagsKeyPrefixes3Config(tagPrefix1 string) string { +func testAccProviderConfig_ignoreTagsKeyPrefixes3(tagPrefix1 string) string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1087,7 +1087,7 @@ provider "aws" { `, tagPrefix1)) } -func testAccIgnoreTagsKeyPrefixes2Config(tagPrefix1, tagPrefix2 string) string { +func testAccProviderConfig_ignoreTagsKeyPrefixes2(tagPrefix1, tagPrefix2 string) string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1105,7 +1105,7 @@ provider "aws" { `, tagPrefix1, tagPrefix2)) } -func testAccDefaultTagsEmptyConfigurationBlockConfig() string { +func testAccProviderConfig_defaultTagsEmptyConfigurationBlock() string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1121,7 +1121,7 @@ provider "aws" { `) } -func testAccDefaultAndIgnoreTagsEmptyConfigurationBlockConfig() string { +func testAccProviderConfig_defaultAndIgnoreTagsEmptyConfigurationBlock() string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1138,7 +1138,7 @@ provider "aws" { `) } -func testAccIgnoreTagsEmptyConfigurationBlockConfig() string { +func testAccProviderConfig_ignoreTagsEmptyConfigurationBlock() string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1154,7 +1154,7 @@ provider "aws" { `) } -func testAccRegionConfig(region string) string { +func testAccProviderConfig_region(region string) string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, @@ -1169,7 +1169,7 @@ provider "aws" { `, region)) } -func testAccSTSRegionConfig(region, stsRegion string) string { +func testAccProviderConfig_stsRegion(region, stsRegion string) string { //lintignore:AT004 return ConfigCompose( testAccProviderConfigBase, diff --git a/internal/attrmap/attrmap.go b/internal/attrmap/attrmap.go index 84805adf3b3..50298e30f99 100644 --- a/internal/attrmap/attrmap.go +++ b/internal/attrmap/attrmap.go @@ -45,8 +45,8 @@ func New(attrMap map[string]string, schemaMap map[string]*schema.Schema) Attribu return attributeMap } -// ApiAttributesToResourceData sets Terraform ResourceData from a map of AWS API attributes. -func (m AttributeMap) ApiAttributesToResourceData(apiAttributes map[string]string, d *schema.ResourceData) error { +// APIAttributesToResourceData sets Terraform ResourceData from a map of AWS API attributes. +func (m AttributeMap) APIAttributesToResourceData(apiAttributes map[string]string, d *schema.ResourceData) error { for tfAttributeName, attributeInfo := range m { if v, ok := apiAttributes[attributeInfo.apiAttributeName]; ok { var err error @@ -92,9 +92,9 @@ func (m AttributeMap) ApiAttributesToResourceData(apiAttributes map[string]strin return nil } -// ResourceDataToApiAttributesCreate returns a map of AWS API attributes from Terraform ResourceData. +// ResourceDataToAPIAttributesCreate returns a map of AWS API attributes from Terraform ResourceData. // The API attributes map is suitable for resource create. -func (m AttributeMap) ResourceDataToApiAttributesCreate(d *schema.ResourceData) (map[string]string, error) { +func (m AttributeMap) ResourceDataToAPIAttributesCreate(d *schema.ResourceData) (map[string]string, error) { apiAttributes := map[string]string{} for tfAttributeName, attributeInfo := range m { @@ -140,9 +140,9 @@ func (m AttributeMap) ResourceDataToApiAttributesCreate(d *schema.ResourceData) return apiAttributes, nil } -// ResourceDataToApiAttributesUpdate returns a map of AWS API attributes from Terraform ResourceData. +// ResourceDataToAPIAttributesUpdate returns a map of AWS API attributes from Terraform ResourceData. // The API attributes map is suitable for resource update. -func (m AttributeMap) ResourceDataToApiAttributesUpdate(d *schema.ResourceData) (map[string]string, error) { +func (m AttributeMap) ResourceDataToAPIAttributesUpdate(d *schema.ResourceData) (map[string]string, error) { apiAttributes := map[string]string{} for tfAttributeName, attributeInfo := range m { @@ -184,8 +184,8 @@ func (m AttributeMap) ResourceDataToApiAttributesUpdate(d *schema.ResourceData) return apiAttributes, nil } -// ApiAttributeNames returns the AWS API attribute names. -func (m AttributeMap) ApiAttributeNames() []string { +// APIAttributeNames returns the AWS API attribute names. +func (m AttributeMap) APIAttributeNames() []string { apiAttributeNames := []string{} for _, attributeInfo := range m { diff --git a/internal/conns/awsclient_gen.go b/internal/conns/awsclient_gen.go index d0362c0f3fb..d676b742950 100644 --- a/internal/conns/awsclient_gen.go +++ b/internal/conns/awsclient_gen.go @@ -4,6 +4,7 @@ package conns import ( "fmt" + "github.com/aws/aws-sdk-go-v2/service/kendra" "github.com/aws/aws-sdk-go-v2/service/route53domains" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/accessanalyzer" @@ -114,6 +115,7 @@ import ( "github.com/aws/aws-sdk-go/service/elbv2" "github.com/aws/aws-sdk-go/service/emr" "github.com/aws/aws-sdk-go/service/emrcontainers" + "github.com/aws/aws-sdk-go/service/emrserverless" "github.com/aws/aws-sdk-go/service/eventbridge" "github.com/aws/aws-sdk-go/service/finspace" "github.com/aws/aws-sdk-go/service/finspacedata" @@ -159,7 +161,6 @@ import ( "github.com/aws/aws-sdk-go/service/ivs" "github.com/aws/aws-sdk-go/service/kafka" "github.com/aws/aws-sdk-go/service/kafkaconnect" - "github.com/aws/aws-sdk-go/service/kendra" "github.com/aws/aws-sdk-go/service/keyspaces" "github.com/aws/aws-sdk-go/service/kinesis" "github.com/aws/aws-sdk-go/service/kinesisanalytics" @@ -420,6 +421,7 @@ type AWSClient struct { ELBV2Conn *elbv2.ELBV2 EMRConn *emr.EMR EMRContainersConn *emrcontainers.EMRContainers + EMRServerlessConn *emrserverless.EMRServerless ElastiCacheConn *elasticache.ElastiCache ElasticBeanstalkConn *elasticbeanstalk.ElasticBeanstalk ElasticInferenceConn *elasticinference.ElasticInference @@ -472,7 +474,7 @@ type AWSClient struct { KMSConn *kms.KMS KafkaConn *kafka.Kafka KafkaConnectConn *kafkaconnect.KafkaConnect - KendraConn *kendra.Kendra + KendraConn *kendra.Client KeyspacesConn *keyspaces.Keyspaces KinesisConn *kinesis.Kinesis KinesisAnalyticsConn *kinesisanalytics.KinesisAnalytics diff --git a/internal/conns/awsclient_test.go b/internal/conns/awsclient_test.go index 768353151d9..1a27ff0a7de 100644 --- a/internal/conns/awsclient_test.go +++ b/internal/conns/awsclient_test.go @@ -4,7 +4,7 @@ import ( "testing" ) -func TestAWSClientPartitionHostname(t *testing.T) { +func TestAWSClientPartitionHostname(t *testing.T) { // nosemgrep:aws-in-func-name testCases := []struct { Name string AWSClient *AWSClient @@ -40,7 +40,7 @@ func TestAWSClientPartitionHostname(t *testing.T) { } } -func TestAWSClientRegionalHostname(t *testing.T) { +func TestAWSClientRegionalHostname(t *testing.T) { // nosemgrep:aws-in-func-name testCases := []struct { Name string AWSClient *AWSClient diff --git a/internal/conns/config.go b/internal/conns/config.go index f78faf39c5b..7bfd3100fdf 100644 --- a/internal/conns/config.go +++ b/internal/conns/config.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" + "github.com/aws/aws-sdk-go-v2/service/kendra" "github.com/aws/aws-sdk-go-v2/service/route53domains" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/endpoints" @@ -23,6 +24,7 @@ import ( "github.com/aws/aws-sdk-go/service/globalaccelerator" "github.com/aws/aws-sdk-go/service/kafka" "github.com/aws/aws-sdk-go/service/kinesis" + "github.com/aws/aws-sdk-go/service/lightsail" "github.com/aws/aws-sdk-go/service/organizations" "github.com/aws/aws-sdk-go/service/route53" "github.com/aws/aws-sdk-go/service/route53recoverycontrolconfig" @@ -188,6 +190,12 @@ func (c *Config) Client(ctx context.Context) (interface{}, diag.Diagnostics) { client.Session = sess client.TerraformVersion = c.TerraformVersion + client.KendraConn = kendra.NewFromConfig(cfg, func(o *kendra.Options) { + if endpoint := c.Endpoints[names.Kendra]; endpoint != "" { + o.EndpointResolver = kendra.EndpointResolverFromURL(endpoint) + } + }) + client.Route53DomainsConn = route53domains.NewFromConfig(cfg, func(o *route53domains.Options) { if endpoint := c.Endpoints[names.Route53Domains]; endpoint != "" { o.EndpointResolver = route53domains.EndpointResolverFromURL(endpoint) @@ -443,6 +451,20 @@ func (c *Config) Client(ctx context.Context) (interface{}, diag.Diagnostics) { } }) + client.LightsailConn.Handlers.Retry.PushBack(func(r *request.Request) { + switch r.Operation.Name { + case "CreateContainerService", "UpdateContainerService", "CreateContainerServiceDeployment": + if tfawserr.ErrMessageContains(r.Error, lightsail.ErrCodeInvalidInputException, "Please try again in a few minutes") { + r.Retryable = aws.Bool(true) + } + case "DeleteContainerService": + if tfawserr.ErrMessageContains(r.Error, lightsail.ErrCodeInvalidInputException, "Please try again in a few minutes") || + tfawserr.ErrMessageContains(r.Error, lightsail.ErrCodeInvalidInputException, "Please wait for it to complete before trying again") { + r.Retryable = aws.Bool(true) + } + } + }) + client.OrganizationsConn.Handlers.Retry.PushBack(func(r *request.Request) { // Retry on the following error: // ConcurrentModificationException: AWS Organizations can't complete your request because it conflicts with another attempt to modify the same entity. Try again later. diff --git a/internal/conns/config_gen.go b/internal/conns/config_gen.go index b53eeb7fe21..24878b82d85 100644 --- a/internal/conns/config_gen.go +++ b/internal/conns/config_gen.go @@ -112,6 +112,7 @@ import ( "github.com/aws/aws-sdk-go/service/elbv2" "github.com/aws/aws-sdk-go/service/emr" "github.com/aws/aws-sdk-go/service/emrcontainers" + "github.com/aws/aws-sdk-go/service/emrserverless" "github.com/aws/aws-sdk-go/service/eventbridge" "github.com/aws/aws-sdk-go/service/finspace" "github.com/aws/aws-sdk-go/service/finspacedata" @@ -156,7 +157,6 @@ import ( "github.com/aws/aws-sdk-go/service/ivs" "github.com/aws/aws-sdk-go/service/kafka" "github.com/aws/aws-sdk-go/service/kafkaconnect" - "github.com/aws/aws-sdk-go/service/kendra" "github.com/aws/aws-sdk-go/service/keyspaces" "github.com/aws/aws-sdk-go/service/kinesis" "github.com/aws/aws-sdk-go/service/kinesisanalytics" @@ -399,6 +399,7 @@ func (c *Config) clientConns(sess *session.Session) *AWSClient { ELBV2Conn: elbv2.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.ELBV2])})), EMRConn: emr.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.EMR])})), EMRContainersConn: emrcontainers.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.EMRContainers])})), + EMRServerlessConn: emrserverless.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.EMRServerless])})), ElastiCacheConn: elasticache.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.ElastiCache])})), ElasticBeanstalkConn: elasticbeanstalk.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.ElasticBeanstalk])})), ElasticInferenceConn: elasticinference.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.ElasticInference])})), @@ -450,7 +451,6 @@ func (c *Config) clientConns(sess *session.Session) *AWSClient { KMSConn: kms.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.KMS])})), KafkaConn: kafka.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.Kafka])})), KafkaConnectConn: kafkaconnect.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.KafkaConnect])})), - KendraConn: kendra.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.Kendra])})), KeyspacesConn: keyspaces.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.Keyspaces])})), KinesisConn: kinesis.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.Kinesis])})), KinesisAnalyticsConn: kinesisanalytics.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints[names.KinesisAnalytics])})), diff --git a/internal/conns/envvar.go b/internal/conns/envvar.go index f201a2c4085..74113c36e71 100644 --- a/internal/conns/envvar.go +++ b/internal/conns/envvar.go @@ -16,7 +16,7 @@ const ( // Container credentials endpoint // See also AWS_ACCESS_KEY_ID and AWS_PROFILE - EnvVarContainerCredentialsFullUri = "AWS_CONTAINER_CREDENTIALS_FULL_URI" + EnvVarContainerCredentialsFullURI = "AWS_CONTAINER_CREDENTIALS_FULL_URI" // Default AWS region for tests (AWS Go SDK does not provide this as constant) EnvVarDefaultRegion = "AWS_DEFAULT_REGION" diff --git a/internal/generate/namescapslist/generate.go b/internal/generate/namescapslist/generate.go new file mode 100644 index 00000000000..ab2d50fb3cd --- /dev/null +++ b/internal/generate/namescapslist/generate.go @@ -0,0 +1,4 @@ +//go:generate go run main.go +// ONLY generate directives and package declaration! Do not add anything else to this file. + +package namescapslist diff --git a/internal/generate/namescapslist/header.tmpl b/internal/generate/namescapslist/header.tmpl new file mode 100644 index 00000000000..dd77e98a28b --- /dev/null +++ b/internal/generate/namescapslist/header.tmpl @@ -0,0 +1,23 @@ +# Caps List + + +In Terraform AWS Provider code, we have two guiding principles for capitalization in function, constant, and variable names: + +1. We use [Go-idiomatic MixedCaps](https://go.dev/doc/effective_go#mixed-caps), with [idiomatic treatment of initialisms](https://github.com/golang/go/wiki/CodeReviewComments#initialisms). +2. We follow AWS's preferred capitalization for service names (_e.g._, ["SageMaker"](https://aws.amazon.com/sagemaker/) rather than "Sagemaker"). + +For _principle 1_, the [golang/go Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments#initialisms) are instructive: + +> Words in names that are initialisms or acronyms (e.g. "URL" or "NATO") have a consistent case. For example, "URL" should appear as "URL" or "url" (as in "urlPony", or "URLPony"), never as "Url". As an example: ServeHTTP not ServeHttp. For identifiers with multiple initialized "words", use for example "xmlHTTPRequest" or "XMLHTTPRequest". + +> This rule also applies to "ID" when it is short for "identifier" (which is pretty much all cases when it's not the "id" as in "ego", "superego"), so write "appID" instead of "appId". + +For _principle 2_, take a look at the AWS website for a service to see the capitalization that AWS prefers. For example, [GameLift](https://aws.amazon.com/gamelift/) rather than "Gamelift". + +To help enforce these principles, we are using [semgrep](https://semgrep.dev/) rules. Below, you will find a list of the specific caps cases we look for currently. This list is generated from the [same source](caps.csv) as the semgrep rules. + +**NOTE:** Please do NOT add "Id" to the list. Use "ID" or "id", never "Id", but we have found linter enforcement of this initialism to be too error prone because of the number of false positives for "Id" (_e.g._, "Identifier"). + +**NOTE:** Capitalization rules are all found in the ".semgrep-service-name0.yml" configuration file are named `-in-func-name`, `-in-var-name`, or `-in-const-name`, where `Test#` comes from the table below. + +**NOTE:** The `Test#` order is _wonky_ because we need to match on longer names first. In the future, with an option to automatically correct problems, fixing the longest possible initialism first is important (_e.g._, `HTTPS` needs to be fixed before `HTTP` to avoid something like `HTTPs`). diff --git a/internal/generate/namescapslist/main.go b/internal/generate/namescapslist/main.go new file mode 100644 index 00000000000..8e7c37ad6f5 --- /dev/null +++ b/internal/generate/namescapslist/main.go @@ -0,0 +1,146 @@ +//go:build generate +// +build generate + +package main + +import ( + "bytes" + _ "embed" + "encoding/csv" + "fmt" + "log" + "os" + "sort" + "strings" + "text/template" +) + +//go:embed header.tmpl +var header string + +const ( + filename = "../../../names/caps.md" + capsDataFile = "../../../names/caps.csv" + maxBadCaps = 31 +) + +type CapsDatum struct { + Wrong string + Right string + Test string +} + +type TemplateData struct { + BadCaps []CapsDatum +} + +func main() { + fmt.Printf("Generating %s\n", strings.TrimPrefix(filename, "../../../")) + + badCaps := readBadCaps() + + td := TemplateData{} + td.BadCaps = badCaps + + writeTemplate(header+tmpl, "namescapslist", td) +} + +func readBadCaps() []CapsDatum { + cf, err := os.Open(capsDataFile) + if err != nil { + log.Fatal(err) + } + + defer cf.Close() + + csvReader := csv.NewReader(cf) + + caps, err := csvReader.ReadAll() + if err != nil { + log.Fatal(err) + } + + var capsList []CapsDatum + + for i, row := range caps { + if i < 1 { // skip header + continue + } + + // 0 - wrong + // 1 - right + + if row[0] == "" { + continue + } + + capsList = append(capsList, CapsDatum{ + Wrong: row[0], + Right: row[1], + }) + } + + sort.SliceStable(capsList, func(i, j int) bool { + if len(capsList[i].Wrong) == len(capsList[j].Wrong) { + return capsList[i].Wrong < capsList[j].Wrong + } + return len(capsList[j].Wrong) < len(capsList[i].Wrong) + }) + + onChunk := -1 + + for i := range capsList { + if i%maxBadCaps == 0 { + onChunk++ + } + + capsList[i].Test = fmt.Sprintf(`%s%d`, "caps", onChunk) + } + + sort.SliceStable(capsList, func(i, j int) bool { + if strings.EqualFold(capsList[i].Wrong, capsList[j].Wrong) { + return capsList[i].Wrong < capsList[j].Wrong + } + return strings.ToLower(capsList[i].Wrong) < strings.ToLower(capsList[j].Wrong) + }) + + return capsList +} + +func writeTemplate(body string, templateName string, td TemplateData) { + // If the file doesn't exist, create it, or append to the file + f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + log.Fatalf("error opening file (%s): %s", filename, err) + } + + tplate, err := template.New(templateName).Parse(body) + if err != nil { + log.Fatalf("error parsing template: %s", err) + } + + var buffer bytes.Buffer + err = tplate.Execute(&buffer, td) + if err != nil { + log.Fatalf("error executing template: %s", err) + } + + if _, err := f.Write(buffer.Bytes()); err != nil { + f.Close() + log.Fatalf("error writing to file (%s): %s", filename, err) + } + + if err := f.Close(); err != nil { + log.Fatalf("error closing file (%s): %s", filename, err) + } +} + +var tmpl = ` +The caps enforced are as follows: + +| Wrong | Right | Test# | +| --- | --- | --- | +{{- range .BadCaps }} +| {{ .Wrong }} | {{ .Right }} | {{ .Test }} | +{{- end }} +` diff --git a/internal/generate/namevaluesfilters/ec2_filters.go b/internal/generate/namevaluesfilters/ec2_filters.go index b6a6628ba25..290e2cbdbd1 100644 --- a/internal/generate/namevaluesfilters/ec2_filters.go +++ b/internal/generate/namevaluesfilters/ec2_filters.go @@ -9,8 +9,8 @@ import ( // Custom EC2 filter functions. -// Ec2Tags creates NameValuesFilters from a map of keyvalue tags. -func Ec2Tags(tags map[string]string) NameValuesFilters { +// EC2Tags creates NameValuesFilters from a map of keyvalue tags. +func EC2Tags(tags map[string]string) NameValuesFilters { m := make(map[string]string, len(tags)) for k, v := range tags { diff --git a/internal/generate/namevaluesfilters/ec2_filters_test.go b/internal/generate/namevaluesfilters/ec2_filters_test.go index 5755b9bee41..8350bd3bbb7 100644 --- a/internal/generate/namevaluesfilters/ec2_filters_test.go +++ b/internal/generate/namevaluesfilters/ec2_filters_test.go @@ -7,7 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" ) -func TestNameValuesFiltersEc2Tags(t *testing.T) { +func TestNameValuesFiltersEC2Tags(t *testing.T) { testCases := []struct { name string filters namevaluesfilters.NameValuesFilters @@ -15,17 +15,17 @@ func TestNameValuesFiltersEc2Tags(t *testing.T) { }{ { name: "nil", - filters: namevaluesfilters.Ec2Tags(nil), + filters: namevaluesfilters.EC2Tags(nil), want: map[string][]string{}, }, { name: "nil", - filters: namevaluesfilters.Ec2Tags(map[string]string{}), + filters: namevaluesfilters.EC2Tags(map[string]string{}), want: map[string][]string{}, }, { name: "tags", - filters: namevaluesfilters.Ec2Tags(map[string]string{ + filters: namevaluesfilters.EC2Tags(map[string]string{ "Name": acctest.ResourcePrefix, "Purpose": "testing", }), diff --git a/internal/generate/namevaluesfilters/generators/servicefilters/README.md b/internal/generate/namevaluesfilters/generators/servicefilters/README.md index fc6680660a6..7c24dc7df11 100644 --- a/internal/generate/namevaluesfilters/generators/servicefilters/README.md +++ b/internal/generate/namevaluesfilters/generators/servicefilters/README.md @@ -11,8 +11,8 @@ To run this code generator, execute `go generate ./...` from the root of the rep ## Example Output ```go -// DocdbFilters returns docdb service filters. -func (filters NameValuesFilters) DocdbFilters() []*docdb.Filter { +// DocDBFilters returns docdb service filters. +func (filters NameValuesFilters) DocDBFilters() []*docdb.Filter { m := filters.Map() if len(m) == 0 { diff --git a/internal/generate/namevaluesfilters/service_filters_gen.go b/internal/generate/namevaluesfilters/service_filters_gen.go index 0ce9b51dc44..e93919bfa03 100644 --- a/internal/generate/namevaluesfilters/service_filters_gen.go +++ b/internal/generate/namevaluesfilters/service_filters_gen.go @@ -22,8 +22,8 @@ import ( // nosemgrep: aws-sdk-go-multiple-service-imports // []*SERVICE.Filter handling -// AutoscalingFilters returns autoscaling service filters. -func (filters NameValuesFilters) AutoscalingFilters() []*autoscaling.Filter { +// AutoScalingFilters returns autoscaling service filters. +func (filters NameValuesFilters) AutoScalingFilters() []*autoscaling.Filter { m := filters.Map() if len(m) == 0 { @@ -66,8 +66,8 @@ func (filters NameValuesFilters) DatabasemigrationserviceFilters() []*databasemi return result } -// DocdbFilters returns docdb service filters. -func (filters NameValuesFilters) DocdbFilters() []*docdb.Filter { +// DocDBFilters returns docdb service filters. +func (filters NameValuesFilters) DocDBFilters() []*docdb.Filter { m := filters.Map() if len(m) == 0 { @@ -88,8 +88,8 @@ func (filters NameValuesFilters) DocdbFilters() []*docdb.Filter { return result } -// Ec2Filters returns ec2 service filters. -func (filters NameValuesFilters) Ec2Filters() []*ec2.Filter { +// EC2Filters returns ec2 service filters. +func (filters NameValuesFilters) EC2Filters() []*ec2.Filter { m := filters.Map() if len(m) == 0 { @@ -154,8 +154,8 @@ func (filters NameValuesFilters) ElasticsearchserviceFilters() []*elasticsearchs return result } -// FsxFilters returns fsx service filters. -func (filters NameValuesFilters) FsxFilters() []*fsx.Filter { +// FSxFilters returns fsx service filters. +func (filters NameValuesFilters) FSxFilters() []*fsx.Filter { m := filters.Map() if len(m) == 0 { @@ -242,8 +242,8 @@ func (filters NameValuesFilters) NeptuneFilters() []*neptune.Filter { return result } -// RdsFilters returns rds service filters. -func (filters NameValuesFilters) RdsFilters() []*rds.Filter { +// RDSFilters returns rds service filters. +func (filters NameValuesFilters) RDSFilters() []*rds.Filter { m := filters.Map() if len(m) == 0 { diff --git a/internal/generate/servicesemgrep/configs.tmpl b/internal/generate/servicesemgrep/configs.tmpl new file mode 100644 index 00000000000..c98fce788eb --- /dev/null +++ b/internal/generate/servicesemgrep/configs.tmpl @@ -0,0 +1,80 @@ +# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. +rules: + - id: test-config-funcs-correct-form + languages: + - go + message: "Config funcs should follow form testAccConfig_" + paths: + include: + - internal/service/**/*_test.go + patterns: + - pattern-inside: "[]resource.TestStep{ ... }" + - pattern: "{..., $KEY:$VALUE, ...}" + - metavariable-pattern: + metavariable: "$KEY" + patterns: + - pattern: "Config" + - metavariable-pattern: + metavariable: "$VALUE" + patterns: + - pattern-not-regex: "testAcc[a-zA-Z0-9]+Config(_[a-zA-Z0-9_]+_|_)[a-z0-9].*" + - pattern-not: acctest.ConfigCompose(...) + severity: WARNING + - id: test-configcompose-funcs-correct-form + languages: + - go + message: "Config funcs should follow form testAccConfig_" + paths: + include: + - internal/service/**/*_test.go + patterns: + - pattern-inside: "[]resource.TestStep{ ... }" + - pattern: "{..., $KEY: acctest.ConfigCompose(..., $VALUE, ...), ...}" + - metavariable-pattern: + metavariable: "$KEY" + patterns: + - pattern: "Config" + - metavariable-pattern: + metavariable: "$VALUE" + patterns: + - pattern-not-regex: "testAcc[a-zA-Z0-9]+Config(_[a-zA-Z0-9_]+_|_)[a-z0-9].*" + - pattern-not-regex: "acctest\\..*" + severity: WARNING + - id: test-config-funcs-check + languages: + - go + message: "Config funcs should not begin with 'testAccCheck'" + paths: + include: + - internal/service/**/*_test.go + patterns: + - pattern-inside: "[]resource.TestStep{ ... }" + - pattern: "{..., $KEY:$VALUE, ...}" + - metavariable-pattern: + metavariable: "$KEY" + patterns: + - pattern: "Config" + - metavariable-pattern: + metavariable: "$VALUE" + patterns: + - pattern-regex: "testAccCheck.*" + severity: WARNING + - id: test-configcompose-funcs-check + languages: + - go + message: "Config funcs should not begin with 'testAccCheck'" + paths: + include: + - internal/service/**/*_test.go + patterns: + - pattern-inside: "[]resource.TestStep{ ... }" + - pattern: "{..., $KEY: acctest.ConfigCompose(..., $VALUE, ...), ...}" + - metavariable-pattern: + metavariable: "$KEY" + patterns: + - pattern: "Config" + - metavariable-pattern: + metavariable: "$VALUE" + patterns: + - pattern-regex: "testAccCheck.*" + severity: WARNING diff --git a/internal/generate/servicesemgrep/generate.go b/internal/generate/servicesemgrep/generate.go new file mode 100644 index 00000000000..713230e67d6 --- /dev/null +++ b/internal/generate/servicesemgrep/generate.go @@ -0,0 +1,4 @@ +//go:generate go run main.go +// ONLY generate directives and package declaration! Do not add anything else to this file. + +package namesreadme diff --git a/internal/generate/servicesemgrep/main.go b/internal/generate/servicesemgrep/main.go new file mode 100644 index 00000000000..ebbbd2d847d --- /dev/null +++ b/internal/generate/servicesemgrep/main.go @@ -0,0 +1,615 @@ +//go:build generate +// +build generate + +package main + +import ( + "bufio" + "bytes" + _ "embed" + "encoding/csv" + "fmt" + "io" + "log" + "os" + "regexp" + "sort" + "strings" + "text/template" + + "github.com/hashicorp/terraform-provider-aws/names" +) + +//go:embed semgrep_header.tmpl +var header string + +//go:embed configs.tmpl +var configs string + +const ( + filename = `../../../.semgrep-service-name.yml` + filenameCAE = `../../../.semgrep-caps-aws-ec2.yml` + filenameConfigs = `../../../.semgrep-configs.yml` + namesDataFile = "../../../names/names_data.csv" + capsDataFile = "../../../names/caps.csv" + maxBadCaps = 21 + semgrepConfigChunks = 4 +) + +type ServiceDatum struct { + ProviderPackage string + ServiceAlias string + LowerAlias string + MainAlias bool + FilePrefix string +} + +type TemplateData struct { + Services []ServiceDatum +} + +type CAEData struct { + BadCaps []string +} + +func main() { + fmt.Printf("Generating %s\n", strings.TrimPrefix(filenameCAE, "../../../")) + + badCaps := readBadCaps() + + cd := CAEData{} + cd.BadCaps = badCaps + + writeCAE(tmplCAE, "caps-aws-ec2", cd) + + fmt.Printf("Generating %s\n", strings.TrimPrefix(filenameConfigs, "../../../")) + + writeConfigs() + + fmt.Printf("Generating %s\n", strings.TrimPrefix(filename, "../../../")) + + td := TemplateData{} + + f, err := os.Open(namesDataFile) + if err != nil { + log.Fatal(err) + } + + defer f.Close() + + csvReader := csv.NewReader(f) + + data, err := csvReader.ReadAll() + if err != nil { + log.Fatal(err) + } + + for i, l := range data { + if i < 1 { // no header + continue + } + + if l[names.ColExclude] != "" && l[names.ColAllowedSubcategory] == "" { + continue + } + + if l[names.ColProviderPackageActual] == "" && l[names.ColProviderPackageCorrect] == "" { + continue + } + + p := l[names.ColProviderPackageCorrect] + + if l[names.ColProviderPackageActual] != "" { + p = l[names.ColProviderPackageActual] + } + + rp := p + + if l[names.ColSplitPackageRealPackage] != "" { + rp = l[names.ColSplitPackageRealPackage] + } + + if _, err := os.Stat(fmt.Sprintf("../../service/%s", rp)); err != nil || os.IsNotExist(err) { + continue + } + + if l[names.ColAliases] != "" { + for _, v := range strings.Split(l[names.ColAliases], ";") { + if strings.ToLower(v) == "es" { + continue // "es" is too short to usefully grep + } + + if strings.ToLower(v) == "config" { + continue // "config" is too ubiquitous + } + + sd := ServiceDatum{ + ProviderPackage: rp, + ServiceAlias: v, + LowerAlias: strings.ToLower(v), + MainAlias: false, + } + + td.Services = append(td.Services, sd) + } + } + + sd := ServiceDatum{ + ProviderPackage: rp, + ServiceAlias: l[names.ColProviderNameUpper], + LowerAlias: strings.ToLower(p), + MainAlias: true, + } + + if l[names.ColFilePrefix] != "" { + sd.FilePrefix = l[names.ColFilePrefix] + } + + td.Services = append(td.Services, sd) + } + + sort.SliceStable(td.Services, func(i, j int) bool { + if td.Services[i].LowerAlias == td.Services[j].LowerAlias { + return len(td.Services[i].ServiceAlias) > len(td.Services[j].ServiceAlias) + } + return td.Services[i].LowerAlias < td.Services[j].LowerAlias + }) + + writeTemplate(tmpl, "servicesemgrep", td) + + breakUpBigFile() + + fmt.Printf(" Removing %s\n", strings.TrimPrefix(filename, "../../../")) + err = os.Remove(filename) + if err != nil { + log.Fatal(err) + } +} + +func readBadCaps() []string { + cf, err := os.Open(capsDataFile) + if err != nil { + log.Fatal(err) + } + + defer cf.Close() + + csvReader := csv.NewReader(cf) + + caps, err := csvReader.ReadAll() + if err != nil { + log.Fatal(err) + } + + var capsList []string + + for i, row := range caps { + if i < 1 { // skip header + continue + } + + // 0 - wrong + // 1 - right + + if row[0] == "" { + continue + } + + capsList = append(capsList, row[0]) + } + + sort.SliceStable(capsList, func(i, j int) bool { + if len(capsList[i]) == len(capsList[j]) { + return capsList[i] < capsList[j] + } + return len(capsList[j]) < len(capsList[i]) + }) + + var chunks [][]string + onChunk := -1 + + for i, v := range capsList { + if i%maxBadCaps == 0 { + onChunk++ + chunks = append(chunks, []string{}) + } + + chunks[onChunk] = append(chunks[onChunk], v) + } + + var strChunks []string + + for _, v := range chunks { + strChunks = append(strChunks, strings.Join(v, "|")) + } + + return strChunks +} + +func writeCAE(body string, templateName string, cd CAEData) { + // If the file doesn't exist, create it, or append to the file + f, err := os.OpenFile(filenameCAE, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) + if err != nil { + log.Fatalf("error opening file (%s): %s", filename, err) + } + + tplate, err := template.New(templateName).Parse(body) + if err != nil { + log.Fatalf("error parsing template: %s", err) + } + + var buffer bytes.Buffer + err = tplate.Execute(&buffer, cd) + if err != nil { + log.Fatalf("error executing template: %s", err) + } + + if _, err := f.Write(buffer.Bytes()); err != nil { + f.Close() + log.Fatalf("error writing to file (%s): %s", filename, err) + } + + if err := f.Close(); err != nil { + log.Fatalf("error closing file (%s): %s", filename, err) + } +} + +func writeConfigs() { + // If the file doesn't exist, create it, or append to the file + f, err := os.OpenFile(filenameConfigs, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) + if err != nil { + log.Fatalf("error opening file (%s): %s", filename, err) + } + + if _, err := f.Write([]byte(configs)); err != nil { + f.Close() + log.Fatalf("error writing to file (%s): %s", filename, err) + } + + if err := f.Close(); err != nil { + log.Fatalf("error closing file (%s): %s", filename, err) + } +} + +func writeTemplate(body string, templateName string, td TemplateData) { + // If the file doesn't exist, create it, or append to the file + f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) + if err != nil { + log.Fatalf("error opening file (%s): %s", filename, err) + } + + tplate, err := template.New(templateName).Parse(body) + if err != nil { + log.Fatalf("error parsing template: %s", err) + } + + var buffer bytes.Buffer + err = tplate.Execute(&buffer, td) + if err != nil { + log.Fatalf("error executing template: %s", err) + } + + if _, err := f.Write(buffer.Bytes()); err != nil { + f.Close() + log.Fatalf("error writing to file (%s): %s", filename, err) + } + + if err := f.Close(); err != nil { + log.Fatalf("error closing file (%s): %s", filename, err) + } +} + +func breakUpBigFile() { + f, err := os.Open(filename) + if err != nil { + log.Fatal(err) + } + defer f.Close() + + lines, err := lineCounter(f) + if err != nil { + log.Fatal(err) + } + + _, err = f.Seek(0, 0) + if err != nil { + log.Fatal(err) + } + + scanner := bufio.NewScanner(f) + + l := 0 + chunk := 0 + var w *bufio.Writer + var piece *os.File + var cfile string + passedChunk := false + + re := regexp.MustCompile(`^ - id: `) + + for scanner.Scan() { + if l%(lines/semgrepConfigChunks) == 0 { + passedChunk = true + } + + if passedChunk && scanner.Text() != "" && re.MatchString(scanner.Text()) { + passedChunk = false + + if w != nil { + w.Flush() + } + + if piece != nil { + piece.Close() + } + + cfile = fmt.Sprintf("%s%d.yml", strings.TrimSuffix(filename, ".yml"), chunk) + fmt.Printf(" Splitting into %s\n", strings.TrimPrefix(cfile, "../../../")) + chunk++ + + var err error + piece, err = os.OpenFile(cfile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) + if err != nil { + log.Fatalf("error opening file (%s): %s", cfile, err) + } + + w = bufio.NewWriter(piece) + _, err = w.WriteString(header) + if err != nil { + log.Fatalf("error writing header to file (%s): %s", cfile, err) + } + w.Flush() + } + + if w != nil { + _, err = w.WriteString(fmt.Sprintf("%s\n", scanner.Text())) + if err != nil { + log.Fatalf("error writing to file (%s): %s", cfile, err) + } + } + + l++ + } + + if w != nil { + w.Flush() + } +} + +func lineCounter(r io.Reader) (int, error) { + buf := make([]byte, 32*1024) + count := 0 + lineSep := []byte{'\n'} + + for { + c, err := r.Read(buf) + count += bytes.Count(buf[:c], lineSep) + + switch { + case err == io.EOF: + return count, nil + + case err != nil: + return count, err + } + } +} + +var tmplCAE = `# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. +rules: + - id: aws-in-func-name + languages: + - go + message: Do not use "AWS" in func name inside AWS Provider + paths: + include: + - internal + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AWS" + severity: WARNING + - id: aws-in-const-name + languages: + - go + message: Do not use "AWS" in const name inside AWS Provider + paths: + include: + - internal + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AWS" + severity: WARNING + - id: aws-in-var-name + languages: + - go + message: Do not use "AWS" in var name inside AWS Provider + paths: + include: + - internal + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)AWS" + severity: WARNING +{{- range $i, $s := .BadCaps }} + - id: caps{{- $i }}-in-func-name + languages: + - go + message: Use correct caps in func name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "({{ $s }})" + severity: WARNING + - id: caps{{- $i }}-in-const-name + languages: + - go + message: Use correct caps in const name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "({{ $s }})" + severity: WARNING + - id: caps{{- $i }}-in-var-name + languages: + - go + message: Use correct caps in var name (i.e., HTTPS or https, not Https) (see list at https://github.com/hashicorp/terraform-provider-aws/tree/main/names/caps.md) + paths: + include: + - internal + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "({{ $s }})" + severity: WARNING +{{- end }} + - id: ec2-in-func-name + languages: + - go + message: Do not use "EC2" in func name inside ec2 package + paths: + include: + - internal/service/ec2 + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EC2" + - pattern-not-regex: ^TestAcc.* + severity: WARNING + - id: ec2-in-const-name + languages: + - go + message: Do not use "EC2" in const name inside ec2 package + paths: + include: + - internal/service/ec2 + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EC2" + severity: WARNING + - id: ec2-in-var-name + languages: + - go + message: Do not use "EC2" in var name inside ec2 package + paths: + include: + - internal/service/ec2 + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i)EC2" + severity: WARNING +` + +var tmpl = `{{- range .Services }} +{{- if not .FilePrefix }} + - id: {{ .LowerAlias }}-in-func-name + languages: + - go + message: Do not use "{{ .ServiceAlias }}" in func name inside {{ .ProviderPackage }} package + paths: + include: + - internal/service/{{ .ProviderPackage }} + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i){{ .ServiceAlias }}" + {{- if eq .ServiceAlias "Deploy" }} + - pattern-not-regex: Deployment(Group|Config|Style) + {{- end }} + {{- if eq .ServiceAlias "CE" }} + - pattern-not-regex: ource + {{- end }} + {{- if eq .ServiceAlias "Connect" }} + - pattern-not-regex: .*uickConnect.* + {{- end }} + {{- if eq .ServiceAlias "CloudTrail" }} + - pattern-not-regex: ^testAccCloudTrailConfig_.* + {{- end }} + - pattern-not-regex: ^TestAcc.* + severity: WARNING +{{- end }} +{{- if .MainAlias }} + - id: {{ .LowerAlias }}-in-test-name + languages: + - go + message: Include "{{ .ServiceAlias }}" in test name + paths: + include: + - internal/service/{{ .ProviderPackage }}/{{ .FilePrefix }}*_test.go + patterns: + - pattern: func $NAME( ... ) { ... } + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-not-regex: "^TestAcc{{ .ServiceAlias }}" + - pattern-regex: ^TestAcc.* + severity: WARNING +{{- end }} +{{- if not .FilePrefix }} + - id: {{ .LowerAlias }}-in-const-name + languages: + - go + message: Do not use "{{ .ServiceAlias }}" in const name inside {{ .ProviderPackage }} package + paths: + include: + - internal/service/{{ .ProviderPackage }} + patterns: + - pattern: const $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i){{ .ServiceAlias }}" + {{- if eq .ServiceAlias "Connect" }} + - pattern-not-regex: .*uickConnect.* + {{- end }} + severity: WARNING + - id: {{ .LowerAlias }}-in-var-name + languages: + - go + message: Do not use "{{ .ServiceAlias }}" in var name inside {{ .ProviderPackage }} package + paths: + include: + - internal/service/{{ .ProviderPackage }} + patterns: + - pattern: var $NAME = ... + - metavariable-pattern: + metavariable: $NAME + patterns: + - pattern-regex: "(?i){{ .ServiceAlias }}" + {{- if eq .ServiceAlias "Connect" }} + - pattern-not-regex: .*uickConnect.* + {{- end }} + severity: WARNING +{{- end }} +{{- end }} +` diff --git a/internal/generate/servicesemgrep/semgrep_header.tmpl b/internal/generate/servicesemgrep/semgrep_header.tmpl new file mode 100644 index 00000000000..6882845f553 --- /dev/null +++ b/internal/generate/servicesemgrep/semgrep_header.tmpl @@ -0,0 +1,2 @@ +# Generated by internal/generate/servicesemgrep/main.go; DO NOT EDIT. +rules: diff --git a/internal/provider/provider.go b/internal/provider/provider.go index cb03638b3ff..cccc08412c9 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -27,6 +27,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/service/appconfig" "github.com/hashicorp/terraform-provider-aws/internal/service/appflow" "github.com/hashicorp/terraform-provider-aws/internal/service/appintegrations" + "github.com/hashicorp/terraform-provider-aws/internal/service/applicationinsights" "github.com/hashicorp/terraform-provider-aws/internal/service/appmesh" "github.com/hashicorp/terraform-provider-aws/internal/service/apprunner" "github.com/hashicorp/terraform-provider-aws/internal/service/appstream" @@ -85,6 +86,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/service/elbv2" "github.com/hashicorp/terraform-provider-aws/internal/service/emr" "github.com/hashicorp/terraform-provider-aws/internal/service/emrcontainers" + "github.com/hashicorp/terraform-provider-aws/internal/service/emrserverless" "github.com/hashicorp/terraform-provider-aws/internal/service/events" "github.com/hashicorp/terraform-provider-aws/internal/service/firehose" "github.com/hashicorp/terraform-provider-aws/internal/service/fms" @@ -102,6 +104,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/service/iot" "github.com/hashicorp/terraform-provider-aws/internal/service/kafka" "github.com/hashicorp/terraform-provider-aws/internal/service/kafkaconnect" + "github.com/hashicorp/terraform-provider-aws/internal/service/kendra" "github.com/hashicorp/terraform-provider-aws/internal/service/keyspaces" "github.com/hashicorp/terraform-provider-aws/internal/service/kinesis" "github.com/hashicorp/terraform-provider-aws/internal/service/kinesisanalytics" @@ -138,6 +141,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/service/ram" "github.com/hashicorp/terraform-provider-aws/internal/service/rds" "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/service/redshiftdata" "github.com/hashicorp/terraform-provider-aws/internal/service/resourcegroups" "github.com/hashicorp/terraform-provider-aws/internal/service/resourcegroupstaggingapi" "github.com/hashicorp/terraform-provider-aws/internal/service/route53" @@ -145,6 +149,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/service/route53recoverycontrolconfig" "github.com/hashicorp/terraform-provider-aws/internal/service/route53recoveryreadiness" "github.com/hashicorp/terraform-provider-aws/internal/service/route53resolver" + "github.com/hashicorp/terraform-provider-aws/internal/service/rum" "github.com/hashicorp/terraform-provider-aws/internal/service/s3" "github.com/hashicorp/terraform-provider-aws/internal/service/s3control" "github.com/hashicorp/terraform-provider-aws/internal/service/s3outposts" @@ -706,6 +711,9 @@ func Provider() *schema.Provider { "aws_mskconnect_custom_plugin": kafkaconnect.DataSourceCustomPlugin(), "aws_mskconnect_worker_configuration": kafkaconnect.DataSourceWorkerConfiguration(), + "aws_kendra_faq": kendra.DataSourceFaq(), + "aws_kendra_index": kendra.DataSourceIndex(), + "aws_kinesis_stream": kinesis.DataSourceStream(), "aws_kinesis_stream_consumer": kinesis.DataSourceStreamConsumer(), @@ -732,7 +740,8 @@ func Provider() *schema.Provider { "aws_lex_intent": lexmodels.DataSourceIntent(), "aws_lex_slot_type": lexmodels.DataSourceSlotType(), - "aws_location_map": location.DataSourceMap(), + "aws_location_map": location.DataSourceMap(), + "aws_location_place_index": location.DataSourcePlaceIndex(), "aws_arn": meta.DataSourceARN(), "aws_billing_service_account": meta.DataSourceBillingServiceAccount(), @@ -776,6 +785,8 @@ func Provider() *schema.Provider { "aws_organizations_organizational_units": organizations.DataSourceOrganizationalUnits(), "aws_organizations_resource_tags": organizations.DataSourceResourceTags(), + "aws_outposts_asset": outposts.DataSourceOutpostAsset(), + "aws_outposts_assets": outposts.DataSourceOutpostAssets(), "aws_outposts_outpost": outposts.DataSourceOutpost(), "aws_outposts_outpost_instance_type": outposts.DataSourceOutpostInstanceType(), "aws_outposts_outpost_instance_types": outposts.DataSourceOutpostInstanceTypes(), @@ -804,9 +815,11 @@ func Provider() *schema.Provider { "aws_rds_engine_version": rds.DataSourceEngineVersion(), "aws_rds_orderable_db_instance": rds.DataSourceOrderableInstance(), - "aws_redshift_cluster": redshift.DataSourceCluster(), - "aws_redshift_orderable_cluster": redshift.DataSourceOrderableCluster(), - "aws_redshift_service_account": redshift.DataSourceServiceAccount(), + "aws_redshift_cluster": redshift.DataSourceCluster(), + "aws_redshift_cluster_credentials": redshift.DataSourceClusterCredentials(), + "aws_redshift_orderable_cluster": redshift.DataSourceOrderableCluster(), + "aws_redshift_service_account": redshift.DataSourceServiceAccount(), + "aws_redshift_subnet_group": redshift.DataSourceSubnetGroup(), "aws_resourcegroupstaggingapi_resources": resourcegroupstaggingapi.DataSourceResources(), @@ -904,6 +917,9 @@ func Provider() *schema.Provider { "aws_acmpca_certificate": acmpca.ResourceCertificate(), "aws_acmpca_certificate_authority": acmpca.ResourceCertificateAuthority(), "aws_acmpca_certificate_authority_certificate": acmpca.ResourceCertificateAuthorityCertificate(), + "aws_acmpca_policy": acmpca.ResourcePolicy(), + + "aws_applicationinsights_application": applicationinsights.ResourceApplication(), "aws_prometheus_workspace": amp.ResourceWorkspace(), "aws_prometheus_alert_manager_definition": amp.ResourceAlertManagerDefinition(), @@ -977,7 +993,7 @@ func Provider() *schema.Provider { "aws_appmesh_virtual_router": appmesh.ResourceVirtualRouter(), "aws_appmesh_virtual_service": appmesh.ResourceVirtualService(), - "aws_apprunner_vpc_connector": apprunner.ResourceVpcConnector(), + "aws_apprunner_vpc_connector": apprunner.ResourceVPCConnector(), "aws_apprunner_auto_scaling_configuration_version": apprunner.ResourceAutoScalingConfigurationVersion(), "aws_apprunner_connection": apprunner.ResourceConnection(), "aws_apprunner_custom_domain_association": apprunner.ResourceCustomDomainAssociation(), @@ -995,7 +1011,7 @@ func Provider() *schema.Provider { "aws_appsync_api_key": appsync.ResourceAPIKey(), "aws_appsync_datasource": appsync.ResourceDataSource(), "aws_appsync_domain_name": appsync.ResourceDomainName(), - "aws_appsync_domain_name_api_association": appsync.ResourceDomainNameApiAssociation(), + "aws_appsync_domain_name_api_association": appsync.ResourceDomainNameAPIAssociation(), "aws_appsync_function": appsync.ResourceFunction(), "aws_appsync_graphql_api": appsync.ResourceGraphQLAPI(), "aws_appsync_resolver": appsync.ResourceResolver(), @@ -1035,7 +1051,10 @@ func Provider() *schema.Provider { "aws_budgets_budget": budgets.ResourceBudget(), "aws_budgets_budget_action": budgets.ResourceBudgetAction(), - "aws_ce_cost_category": ce.ResourceCostCategory(), + "aws_ce_anomaly_monitor": ce.ResourceAnomalyMonitor(), + "aws_ce_anomaly_subscription": ce.ResourceAnomalySubscription(), + "aws_ce_cost_allocation_tag": ce.ResourceCostAllocationTag(), + "aws_ce_cost_category": ce.ResourceCostCategory(), "aws_chime_voice_connector": chime.ResourceVoiceConnector(), "aws_chime_voice_connector_group": chime.ResourceVoiceConnectorGroup(), @@ -1100,6 +1119,8 @@ func Provider() *schema.Provider { "aws_cloudwatch_log_subscription_filter": logs.ResourceSubscriptionFilter(), "aws_cloudwatch_query_definition": logs.ResourceQueryDefinition(), + "aws_rum_app_monitor": rum.ResourceAppMonitor(), + "aws_codeartifact_domain": codeartifact.ResourceDomain(), "aws_codeartifact_domain_permissions_policy": codeartifact.ResourceDomainPermissionsPolicy(), "aws_codeartifact_repository": codeartifact.ResourceRepository(), @@ -1134,6 +1155,7 @@ func Provider() *schema.Provider { "aws_cognito_identity_provider": cognitoidp.ResourceIdentityProvider(), "aws_cognito_resource_server": cognitoidp.ResourceResourceServer(), + "aws_cognito_risk_configuration": cognitoidp.ResourceRiskConfiguration(), "aws_cognito_user": cognitoidp.ResourceUser(), "aws_cognito_user_group": cognitoidp.ResourceUserGroup(), "aws_cognito_user_in_group": cognitoidp.ResourceUserInGroup(), @@ -1381,11 +1403,12 @@ func Provider() *schema.Provider { "aws_ecs_task_definition": ecs.ResourceTaskDefinition(), "aws_ecs_task_set": ecs.ResourceTaskSet(), - "aws_efs_access_point": efs.ResourceAccessPoint(), - "aws_efs_backup_policy": efs.ResourceBackupPolicy(), - "aws_efs_file_system": efs.ResourceFileSystem(), - "aws_efs_file_system_policy": efs.ResourceFileSystemPolicy(), - "aws_efs_mount_target": efs.ResourceMountTarget(), + "aws_efs_access_point": efs.ResourceAccessPoint(), + "aws_efs_backup_policy": efs.ResourceBackupPolicy(), + "aws_efs_file_system": efs.ResourceFileSystem(), + "aws_efs_file_system_policy": efs.ResourceFileSystemPolicy(), + "aws_efs_mount_target": efs.ResourceMountTarget(), + "aws_efs_replication_configuration": efs.ResourceReplicationConfiguration(), "aws_eks_addon": eks.ResourceAddon(), "aws_eks_cluster": eks.ResourceCluster(), @@ -1448,6 +1471,8 @@ func Provider() *schema.Provider { "aws_emrcontainers_virtual_cluster": emrcontainers.ResourceVirtualCluster(), + "aws_emrserverless_application": emrserverless.ResourceApplication(), + "aws_kinesis_firehose_delivery_stream": firehose.ResourceDeliveryStream(), "aws_fms_admin_account": fms.ResourceAdminAccount(), @@ -1500,7 +1525,7 @@ func Provider() *schema.Provider { "aws_grafana_license_association": grafana.ResourceLicenseAssociation(), "aws_grafana_role_association": grafana.ResourceRoleAssociation(), "aws_grafana_workspace": grafana.ResourceWorkspace(), - "aws_grafana_workspace_saml_configuration": grafana.ResourceWorkspaceSamlConfiguration(), + "aws_grafana_workspace_saml_configuration": grafana.ResourceWorkspaceSAMLConfiguration(), "aws_guardduty_detector": guardduty.ResourceDetector(), "aws_guardduty_filter": guardduty.ResourceFilter(), @@ -1575,6 +1600,12 @@ func Provider() *schema.Provider { "aws_mskconnect_custom_plugin": kafkaconnect.ResourceCustomPlugin(), "aws_mskconnect_worker_configuration": kafkaconnect.ResourceWorkerConfiguration(), + "aws_kendra_experience": kendra.ResourceExperience(), + "aws_kendra_faq": kendra.ResourceFaq(), + "aws_kendra_index": kendra.ResourceIndex(), + "aws_kendra_query_suggestions_block_list": kendra.ResourceQuerySuggestionsBlockList(), + "aws_kendra_thesaurus": kendra.ResourceThesaurus(), + "aws_keyspaces_keyspace": keyspaces.ResourceKeyspace(), "aws_keyspaces_table": keyspaces.ResourceTable(), @@ -1596,6 +1627,7 @@ func Provider() *schema.Provider { "aws_kms_replica_key": kms.ResourceReplicaKey(), "aws_lakeformation_data_lake_settings": lakeformation.ResourceDataLakeSettings(), + "aws_lakeformation_lf_tag": lakeformation.ResourceLFTag(), "aws_lakeformation_permissions": lakeformation.ResourcePermissions(), "aws_lakeformation_resource": lakeformation.ResourceResource(), @@ -1604,7 +1636,7 @@ func Provider() *schema.Provider { "aws_lambda_event_source_mapping": lambda.ResourceEventSourceMapping(), "aws_lambda_function": lambda.ResourceFunction(), "aws_lambda_function_event_invoke_config": lambda.ResourceFunctionEventInvokeConfig(), - "aws_lambda_function_url": lambda.ResourceFunctionUrl(), + "aws_lambda_function_url": lambda.ResourceFunctionURL(), "aws_lambda_invocation": lambda.ResourceInvocation(), "aws_lambda_layer_version": lambda.ResourceLayerVersion(), "aws_lambda_layer_version_permission": lambda.ResourceLayerVersionPermission(), @@ -1619,14 +1651,18 @@ func Provider() *schema.Provider { "aws_licensemanager_association": licensemanager.ResourceAssociation(), "aws_licensemanager_license_configuration": licensemanager.ResourceLicenseConfiguration(), - "aws_lightsail_domain": lightsail.ResourceDomain(), - "aws_lightsail_instance": lightsail.ResourceInstance(), - "aws_lightsail_instance_public_ports": lightsail.ResourceInstancePublicPorts(), - "aws_lightsail_key_pair": lightsail.ResourceKeyPair(), - "aws_lightsail_static_ip": lightsail.ResourceStaticIP(), - "aws_lightsail_static_ip_attachment": lightsail.ResourceStaticIPAttachment(), + "aws_lightsail_container_service": lightsail.ResourceContainerService(), + "aws_lightsail_container_service_deployment_version": lightsail.ResourceContainerServiceDeploymentVersion(), + "aws_lightsail_domain": lightsail.ResourceDomain(), + "aws_lightsail_instance": lightsail.ResourceInstance(), + "aws_lightsail_instance_public_ports": lightsail.ResourceInstancePublicPorts(), + "aws_lightsail_key_pair": lightsail.ResourceKeyPair(), + "aws_lightsail_static_ip": lightsail.ResourceStaticIP(), + "aws_lightsail_static_ip_attachment": lightsail.ResourceStaticIPAttachment(), - "aws_location_map": location.ResourceMap(), + "aws_location_map": location.ResourceMap(), + "aws_location_place_index": location.ResourcePlaceIndex(), + "aws_location_tracker": location.ResourceTracker(), "aws_macie_member_account_association": macie.ResourceMemberAccountAssociation(), "aws_macie_s3_bucket_association": macie.ResourceS3BucketAssociation(), @@ -1760,8 +1796,13 @@ func Provider() *schema.Provider { "aws_rds_cluster_role_association": rds.ResourceClusterRoleAssociation(), "aws_rds_global_cluster": rds.ResourceGlobalCluster(), + "aws_redshift_authentication_profile": redshift.ResourceAuthenticationProfile(), "aws_redshift_cluster": redshift.ResourceCluster(), + "aws_redshift_cluster_iam_roles": redshift.ResourceClusterIAMRoles(), + "aws_redshift_endpoint_access": redshift.ResourceEndpointAccess(), "aws_redshift_event_subscription": redshift.ResourceEventSubscription(), + "aws_redshift_hsm_client_certificate": redshift.ResourceHSMClientCertificate(), + "aws_redshift_hsm_configuration": redshift.ResourceHSMConfiguration(), "aws_redshift_parameter_group": redshift.ResourceParameterGroup(), "aws_redshift_scheduled_action": redshift.ResourceScheduledAction(), "aws_redshift_security_group": redshift.ResourceSecurityGroup(), @@ -1769,6 +1810,9 @@ func Provider() *schema.Provider { "aws_redshift_snapshot_schedule": redshift.ResourceSnapshotSchedule(), "aws_redshift_snapshot_schedule_association": redshift.ResourceSnapshotScheduleAssociation(), "aws_redshift_subnet_group": redshift.ResourceSubnetGroup(), + "aws_redshift_usage_limit": redshift.ResourceUsageLimit(), + + "aws_redshiftdata_statement": redshiftdata.ResourceStatement(), "aws_resourcegroups_group": resourcegroups.ResourceGroup(), diff --git a/internal/service/accessanalyzer/analyzer_test.go b/internal/service/accessanalyzer/analyzer_test.go index 40ca1d3cf99..6bef5c04723 100644 --- a/internal/service/accessanalyzer/analyzer_test.go +++ b/internal/service/accessanalyzer/analyzer_test.go @@ -27,7 +27,7 @@ func testAccAnalyzer_basic(t *testing.T) { CheckDestroy: testAccCheckAnalyzerDestroy, Steps: []resource.TestStep{ { - Config: testAccAnalyzerAnalyzerNameConfig(rName), + Config: testAccAnalyzerConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAnalyzerExists(resourceName, &analyzer), resource.TestCheckResourceAttr(resourceName, "analyzer_name", rName), @@ -58,7 +58,7 @@ func testAccAnalyzer_disappears(t *testing.T) { CheckDestroy: testAccCheckAnalyzerDestroy, Steps: []resource.TestStep{ { - Config: testAccAnalyzerAnalyzerNameConfig(rName), + Config: testAccAnalyzerConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAnalyzerExists(resourceName, &analyzer), testAccCheckAnalyzerDisappears(&analyzer), @@ -82,7 +82,7 @@ func testAccAnalyzer_Tags(t *testing.T) { CheckDestroy: testAccCheckAnalyzerDestroy, Steps: []resource.TestStep{ { - Config: testAccAnalyzerTags1Config(rName, "key1", "value1"), + Config: testAccAnalyzerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAnalyzerExists(resourceName, &analyzer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -95,7 +95,7 @@ func testAccAnalyzer_Tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAnalyzerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAnalyzerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAnalyzerExists(resourceName, &analyzer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -104,7 +104,7 @@ func testAccAnalyzer_Tags(t *testing.T) { ), }, { - Config: testAccAnalyzerTags1Config(rName, "key2", "value2"), + Config: testAccAnalyzerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAnalyzerExists(resourceName, &analyzer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -132,7 +132,7 @@ func testAccAnalyzer_Type_Organization(t *testing.T) { CheckDestroy: testAccCheckAnalyzerDestroy, Steps: []resource.TestStep{ { - Config: testAccAnalyzerTypeOrganizationConfig(rName), + Config: testAccAnalyzerConfig_typeOrganization(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAnalyzerExists(resourceName, &analyzer), resource.TestCheckResourceAttr(resourceName, "type", accessanalyzer.TypeOrganization), @@ -221,7 +221,7 @@ func testAccCheckAnalyzerExists(resourceName string, analyzer *accessanalyzer.An } } -func testAccAnalyzerAnalyzerNameConfig(rName string) string { +func testAccAnalyzerConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_accessanalyzer_analyzer" "test" { analyzer_name = %[1]q @@ -229,7 +229,7 @@ resource "aws_accessanalyzer_analyzer" "test" { `, rName) } -func testAccAnalyzerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAnalyzerConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_accessanalyzer_analyzer" "test" { analyzer_name = %[1]q @@ -241,7 +241,7 @@ resource "aws_accessanalyzer_analyzer" "test" { `, rName, tagKey1, tagValue1) } -func testAccAnalyzerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAnalyzerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_accessanalyzer_analyzer" "test" { analyzer_name = %[1]q @@ -254,7 +254,7 @@ resource "aws_accessanalyzer_analyzer" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccAnalyzerTypeOrganizationConfig(rName string) string { +func testAccAnalyzerConfig_typeOrganization(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/account/alternate_contact_test.go b/internal/service/account/alternate_contact_test.go index 8daf247e2b3..71c04552be7 100644 --- a/internal/service/account/alternate_contact_test.go +++ b/internal/service/account/alternate_contact_test.go @@ -28,12 +28,12 @@ func TestAccAccountAlternateContact_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, account.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccountAlternateContactDestroy, + CheckDestroy: testAccAlternateContactDestroy, Steps: []resource.TestStep{ { - Config: testAccountAlternateContactConfig(rName1, emailAddress1), + Config: testAccAlternateContactConfig_basic(rName1, emailAddress1), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAccountAlternateContactExists(resourceName), + testAccCheckAlternateContactExists(resourceName), resource.TestCheckResourceAttr(resourceName, "account_id", ""), resource.TestCheckResourceAttr(resourceName, "alternate_contact_type", "OPERATIONS"), resource.TestCheckResourceAttr(resourceName, "email_address", emailAddress1), @@ -48,9 +48,9 @@ func TestAccAccountAlternateContact_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccountAlternateContactConfig(rName2, emailAddress2), + Config: testAccAlternateContactConfig_basic(rName2, emailAddress2), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAccountAlternateContactExists(resourceName), + testAccCheckAlternateContactExists(resourceName), resource.TestCheckResourceAttr(resourceName, "account_id", ""), resource.TestCheckResourceAttr(resourceName, "alternate_contact_type", "OPERATIONS"), resource.TestCheckResourceAttr(resourceName, "email_address", emailAddress2), @@ -73,12 +73,12 @@ func TestAccAccountAlternateContact_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, account.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccountAlternateContactDestroy, + CheckDestroy: testAccAlternateContactDestroy, Steps: []resource.TestStep{ { - Config: testAccountAlternateContactConfig(rName, emailAddress), + Config: testAccAlternateContactConfig_basic(rName, emailAddress), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAccountAlternateContactExists(resourceName), + testAccCheckAlternateContactExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfaccount.ResourceAlternateContact(), resourceName), ), ExpectNonEmptyPlan: true, @@ -105,12 +105,12 @@ func TestAccAccountAlternateContact_accountID(t *testing.T) { }, ErrorCheck: acctest.ErrorCheck(t, account.EndpointsID), ProviderFactories: acctest.FactoriesAlternate(&providers), - CheckDestroy: testAccountAlternateContactDestroy, + CheckDestroy: testAccAlternateContactDestroy, Steps: []resource.TestStep{ { - Config: testAccountAlternateContactOrganizationConfig(rName1, emailAddress1), + Config: testAccAlternateContactConfig_organization(rName1, emailAddress1), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAccountAlternateContactExists(resourceName), + testAccCheckAlternateContactExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "account_id"), resource.TestCheckResourceAttr(resourceName, "alternate_contact_type", "OPERATIONS"), resource.TestCheckResourceAttr(resourceName, "email_address", emailAddress1), @@ -125,9 +125,9 @@ func TestAccAccountAlternateContact_accountID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccountAlternateContactOrganizationConfig(rName2, emailAddress2), + Config: testAccAlternateContactConfig_organization(rName2, emailAddress2), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAccountAlternateContactExists(resourceName), + testAccCheckAlternateContactExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "account_id"), resource.TestCheckResourceAttr(resourceName, "alternate_contact_type", "OPERATIONS"), resource.TestCheckResourceAttr(resourceName, "email_address", emailAddress2), @@ -140,7 +140,7 @@ func TestAccAccountAlternateContact_accountID(t *testing.T) { }) } -func testAccountAlternateContactDestroy(s *terraform.State) error { +func testAccAlternateContactDestroy(s *terraform.State) error { ctx := context.TODO() conn := acctest.Provider.Meta().(*conns.AWSClient).AccountConn @@ -172,7 +172,7 @@ func testAccountAlternateContactDestroy(s *terraform.State) error { } -func testAccCheckAccountAlternateContactExists(n string) resource.TestCheckFunc { +func testAccCheckAlternateContactExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -202,7 +202,7 @@ func testAccCheckAccountAlternateContactExists(n string) resource.TestCheckFunc } } -func testAccountAlternateContactConfig(rName, emailAddress string) string { +func testAccAlternateContactConfig_basic(rName, emailAddress string) string { return fmt.Sprintf(` resource "aws_account_alternate_contact" "test" { alternate_contact_type = "OPERATIONS" @@ -215,7 +215,7 @@ resource "aws_account_alternate_contact" "test" { `, rName, emailAddress) } -func testAccountAlternateContactOrganizationConfig(rName, emailAddress string) string { +func testAccAlternateContactConfig_organization(rName, emailAddress string) string { return acctest.ConfigCompose(acctest.ConfigAlternateAccountProvider(), fmt.Sprintf(` data "aws_caller_identity" "test" { provider = "awsalternate" diff --git a/internal/service/account/find.go b/internal/service/account/find.go index 312daa34d32..27fce4aac5f 100644 --- a/internal/service/account/find.go +++ b/internal/service/account/find.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func FindAlternateContactByAccountIDAndContactType(ctx context.Context, conn *account.Account, accountID, contactType string) (*account.AlternateContact, error) { +func FindAlternateContactByAccountIDAndContactType(ctx context.Context, conn *account.Account, accountID, contactType string) (*account.AlternateContact, error) { // nosemgrep:account-in-func-name input := &account.GetAlternateContactInput{ AlternateContactType: aws.String(contactType), } diff --git a/internal/service/acm/certificate.go b/internal/service/acm/certificate.go index b5999d419ff..6bfb5c11125 100644 --- a/internal/service/acm/certificate.go +++ b/internal/service/acm/certificate.go @@ -29,11 +29,11 @@ import ( const ( // Maximum amount of time for ACM Certificate cross-service reference propagation. // Removal of ACM Certificates from API Gateway Custom Domains can take >15 minutes. - AcmCertificateCrossServicePropagationTimeout = 20 * time.Minute + certificateCrossServicePropagationTimeout = 20 * time.Minute // Maximum amount of time for ACM Certificate asynchronous DNS validation record assignment. // This timeout is unrelated to any creation or validation of those assigned DNS records. - AcmCertificateDnsValidationAssignmentTimeout = 5 * time.Minute + certificateDNSValidationAssignmentTimeout = 5 * time.Minute certificateValidationMethodNone = "NONE" ) @@ -107,7 +107,7 @@ func ResourceCertificate() *schema.Resource { }, }, }, - Set: acmDomainValidationOptionsHash, + Set: domainValidationOptionsHash, }, "options": { Type: schema.TypeList, @@ -229,7 +229,7 @@ func ResourceCertificate() *schema.Resource { } } - if err := diff.SetNew("domain_validation_options", schema.NewSet(acmDomainValidationOptionsHash, domainValidationOptionsList)); err != nil { + if err := diff.SetNew("domain_validation_options", schema.NewSet(domainValidationOptionsHash, domainValidationOptionsList)); err != nil { return fmt.Errorf("error setting new domain_validation_options diff: %w", err) } } @@ -330,7 +330,7 @@ func resourceCertificateCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(aws.StringValue(output.CertificateArn)) } - if _, err := waitCertificateDomainValidationsAvailable(conn, d.Id(), AcmCertificateDnsValidationAssignmentTimeout); err != nil { + if _, err := waitCertificateDomainValidationsAvailable(conn, d.Id(), certificateDNSValidationAssignmentTimeout); err != nil { return fmt.Errorf("waiting for ACM Certificate (%s) to be issued: %w", d.Id(), err) } @@ -438,7 +438,7 @@ func resourceCertificateDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ACMConn log.Printf("[INFO] Deleting ACM Certificate: %s", d.Id()) - _, err := tfresource.RetryWhenAWSErrCodeEquals(AcmCertificateCrossServicePropagationTimeout, + _, err := tfresource.RetryWhenAWSErrCodeEquals(certificateCrossServicePropagationTimeout, func() (interface{}, error) { return conn.DeleteCertificate(&acm.DeleteCertificateInput{ CertificateArn: aws.String(d.Id()), @@ -468,7 +468,7 @@ func certificateValidationMethod(certificate *acm.CertificateDetail) string { return certificateValidationMethodNone } -func acmDomainValidationOptionsHash(v interface{}) int { +func domainValidationOptionsHash(v interface{}) int { m, ok := v.(map[string]interface{}) if !ok { diff --git a/internal/service/acm/certificate_data_source.go b/internal/service/acm/certificate_data_source.go index 3499b759ad4..16a992bd74e 100644 --- a/internal/service/acm/certificate_data_source.go +++ b/internal/service/acm/certificate_data_source.go @@ -143,7 +143,7 @@ func dataSourceCertificateRead(d *schema.ResourceData, meta interface{}) error { // At this point, we already have a candidate certificate // Check if we are filtering by most recent and update if necessary if filterMostRecent { - matchedCertificate, err = mostRecentAcmCertificate(certificate, matchedCertificate) + matchedCertificate, err = mostRecentCertificate(certificate, matchedCertificate) if err != nil { return err } @@ -163,7 +163,7 @@ func dataSourceCertificateRead(d *schema.ResourceData, meta interface{}) error { // At this point, we already have a candidate certificate // Check if we are filtering by most recent and update if necessary if filterMostRecent { - matchedCertificate, err = mostRecentAcmCertificate(certificate, matchedCertificate) + matchedCertificate, err = mostRecentCertificate(certificate, matchedCertificate) if err != nil { return err } @@ -211,7 +211,7 @@ func dataSourceCertificateRead(d *schema.ResourceData, meta interface{}) error { return nil } -func mostRecentAcmCertificate(i, j *acm.CertificateDetail) (*acm.CertificateDetail, error) { +func mostRecentCertificate(i, j *acm.CertificateDetail) (*acm.CertificateDetail, error) { if aws.StringValue(i.Status) != aws.StringValue(j.Status) { return nil, fmt.Errorf("most_recent filtering on different ACM certificate statues is not supported") } diff --git a/internal/service/acm/certificate_data_source_test.go b/internal/service/acm/certificate_data_source_test.go index e844189638e..94f2655839c 100644 --- a/internal/service/acm/certificate_data_source_test.go +++ b/internal/service/acm/certificate_data_source_test.go @@ -12,7 +12,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" ) -const ACMCertificateRe = `^arn:[^:]+:acm:[^:]+:[^:]+:certificate/.+$` +const certificateRE = `^arn:[^:]+:acm:[^:]+:[^:]+:certificate/.+$` func TestAccACMCertificateDataSource_singleIssued(t *testing.T) { if os.Getenv("ACM_CERTIFICATE_ROOT_DOMAIN") == "" { @@ -25,7 +25,7 @@ func TestAccACMCertificateDataSource_singleIssued(t *testing.T) { if os.Getenv("ACM_CERTIFICATE_SINGLE_ISSUED_MOST_RECENT_ARN") != "" { arnRe = regexp.MustCompile(fmt.Sprintf("^%s$", os.Getenv("ACM_CERTIFICATE_SINGLE_ISSUED_MOST_RECENT_ARN"))) } else { - arnRe = regexp.MustCompile(ACMCertificateRe) + arnRe = regexp.MustCompile(certificateRE) } if os.Getenv("ACM_CERTIFICATE_SINGLE_ISSUED_DOMAIN") != "" { @@ -42,7 +42,7 @@ func TestAccACMCertificateDataSource_singleIssued(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckCertificateDataSourceConfig(domain), + Config: testAccCertificateDataSourceConfig_basic(domain), Check: resource.ComposeTestCheckFunc( //lintignore:AWSAT001 resource.TestMatchResourceAttr(resourceName, "arn", arnRe), @@ -52,7 +52,7 @@ func TestAccACMCertificateDataSource_singleIssued(t *testing.T) { ), }, { - Config: testAccCheckCertificateWithStatusDataSourceConfig(domain, acm.CertificateStatusIssued), + Config: testAccCertificateDataSourceConfig_status(domain, acm.CertificateStatusIssued), Check: resource.ComposeTestCheckFunc( //lintignore:AWSAT001 resource.TestMatchResourceAttr(resourceName, "arn", arnRe), @@ -62,7 +62,7 @@ func TestAccACMCertificateDataSource_singleIssued(t *testing.T) { ), }, { - Config: testAccCheckCertificateWithTypesDataSourceConfig(domain, acm.CertificateTypeAmazonIssued), + Config: testAccCertificateDataSourceConfig_types(domain, acm.CertificateTypeAmazonIssued), Check: resource.ComposeTestCheckFunc( //lintignore:AWSAT001 resource.TestMatchResourceAttr(resourceName, "arn", arnRe), @@ -71,7 +71,7 @@ func TestAccACMCertificateDataSource_singleIssued(t *testing.T) { ), }, { - Config: testAccCheckCertificateWithMostRecentDataSourceConfig(domain, true), + Config: testAccCertificateDataSourceConfig_mostRecent(domain, true), Check: resource.ComposeTestCheckFunc( //lintignore:AWSAT001 resource.TestMatchResourceAttr(resourceName, "arn", arnRe), @@ -80,7 +80,7 @@ func TestAccACMCertificateDataSource_singleIssued(t *testing.T) { ), }, { - Config: testAccCheckCertificateWithMostRecentAndStatusDataSourceConfig(domain, acm.CertificateStatusIssued, true), + Config: testAccCertificateDataSourceConfig_mostRecentAndStatus(domain, acm.CertificateStatusIssued, true), Check: resource.ComposeTestCheckFunc( //lintignore:AWSAT001 resource.TestMatchResourceAttr(resourceName, "arn", arnRe), @@ -89,7 +89,7 @@ func TestAccACMCertificateDataSource_singleIssued(t *testing.T) { ), }, { - Config: testAccCheckCertificateWithMostRecentAndTypesDataSourceConfig(domain, acm.CertificateTypeAmazonIssued, true), + Config: testAccCertificateDataSourceConfig_mostRecentAndTypes(domain, acm.CertificateTypeAmazonIssued, true), Check: resource.ComposeTestCheckFunc( //lintignore:AWSAT001 resource.TestMatchResourceAttr(resourceName, "arn", arnRe), @@ -112,7 +112,7 @@ func TestAccACMCertificateDataSource_multipleIssued(t *testing.T) { if os.Getenv("ACM_CERTIFICATE_MULTIPLE_ISSUED_MOST_RECENT_ARN") != "" { arnRe = regexp.MustCompile(fmt.Sprintf("^%s$", os.Getenv("ACM_CERTIFICATE_MULTIPLE_ISSUED_MOST_RECENT_ARN"))) } else { - arnRe = regexp.MustCompile(ACMCertificateRe) + arnRe = regexp.MustCompile(certificateRE) } if os.Getenv("ACM_CERTIFICATE_MULTIPLE_ISSUED_DOMAIN") != "" { @@ -129,33 +129,33 @@ func TestAccACMCertificateDataSource_multipleIssued(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckCertificateDataSourceConfig(domain), + Config: testAccCertificateDataSourceConfig_basic(domain), ExpectError: regexp.MustCompile(`Multiple certificates for domain`), }, { - Config: testAccCheckCertificateWithStatusDataSourceConfig(domain, acm.CertificateStatusIssued), + Config: testAccCertificateDataSourceConfig_status(domain, acm.CertificateStatusIssued), ExpectError: regexp.MustCompile(`Multiple certificates for domain`), }, { - Config: testAccCheckCertificateWithTypesDataSourceConfig(domain, acm.CertificateTypeAmazonIssued), + Config: testAccCertificateDataSourceConfig_types(domain, acm.CertificateTypeAmazonIssued), ExpectError: regexp.MustCompile(`Multiple certificates for domain`), }, { - Config: testAccCheckCertificateWithMostRecentDataSourceConfig(domain, true), + Config: testAccCertificateDataSourceConfig_mostRecent(domain, true), Check: resource.ComposeTestCheckFunc( //lintignore:AWSAT001 resource.TestMatchResourceAttr(resourceName, "arn", arnRe), ), }, { - Config: testAccCheckCertificateWithMostRecentAndStatusDataSourceConfig(domain, acm.CertificateStatusIssued, true), + Config: testAccCertificateDataSourceConfig_mostRecentAndStatus(domain, acm.CertificateStatusIssued, true), Check: resource.ComposeTestCheckFunc( //lintignore:AWSAT001 resource.TestMatchResourceAttr(resourceName, "arn", arnRe), ), }, { - Config: testAccCheckCertificateWithMostRecentAndTypesDataSourceConfig(domain, acm.CertificateTypeAmazonIssued, true), + Config: testAccCertificateDataSourceConfig_mostRecentAndTypes(domain, acm.CertificateTypeAmazonIssued, true), Check: resource.ComposeTestCheckFunc( //lintignore:AWSAT001 resource.TestMatchResourceAttr(resourceName, "arn", arnRe), @@ -178,27 +178,27 @@ func TestAccACMCertificateDataSource_noMatchReturnsError(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckCertificateDataSourceConfig(domain), + Config: testAccCertificateDataSourceConfig_basic(domain), ExpectError: regexp.MustCompile(`No certificate for domain`), }, { - Config: testAccCheckCertificateWithStatusDataSourceConfig(domain, acm.CertificateStatusIssued), + Config: testAccCertificateDataSourceConfig_status(domain, acm.CertificateStatusIssued), ExpectError: regexp.MustCompile(`No certificate for domain`), }, { - Config: testAccCheckCertificateWithTypesDataSourceConfig(domain, acm.CertificateTypeAmazonIssued), + Config: testAccCertificateDataSourceConfig_types(domain, acm.CertificateTypeAmazonIssued), ExpectError: regexp.MustCompile(`No certificate for domain`), }, { - Config: testAccCheckCertificateWithMostRecentDataSourceConfig(domain, true), + Config: testAccCertificateDataSourceConfig_mostRecent(domain, true), ExpectError: regexp.MustCompile(`No certificate for domain`), }, { - Config: testAccCheckCertificateWithMostRecentAndStatusDataSourceConfig(domain, acm.CertificateStatusIssued, true), + Config: testAccCertificateDataSourceConfig_mostRecentAndStatus(domain, acm.CertificateStatusIssued, true), ExpectError: regexp.MustCompile(`No certificate for domain`), }, { - Config: testAccCheckCertificateWithMostRecentAndTypesDataSourceConfig(domain, acm.CertificateTypeAmazonIssued, true), + Config: testAccCertificateDataSourceConfig_mostRecentAndTypes(domain, acm.CertificateTypeAmazonIssued, true), ExpectError: regexp.MustCompile(`No certificate for domain`), }, }, @@ -218,7 +218,7 @@ func TestAccACMCertificateDataSource_keyTypes(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCertificateKeyTypesDataSourceConfig(acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key), rName), + Config: testAccCertificateDataSourceConfig_keyTypes(acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key), rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "tags", dataSourceName, "tags"), @@ -228,7 +228,7 @@ func TestAccACMCertificateDataSource_keyTypes(t *testing.T) { }) } -func testAccCheckCertificateDataSourceConfig(domain string) string { +func testAccCertificateDataSourceConfig_basic(domain string) string { return fmt.Sprintf(` data "aws_acm_certificate" "test" { domain = "%s" @@ -236,7 +236,7 @@ data "aws_acm_certificate" "test" { `, domain) } -func testAccCheckCertificateWithStatusDataSourceConfig(domain, status string) string { +func testAccCertificateDataSourceConfig_status(domain, status string) string { return fmt.Sprintf(` data "aws_acm_certificate" "test" { domain = "%s" @@ -245,7 +245,7 @@ data "aws_acm_certificate" "test" { `, domain, status) } -func testAccCheckCertificateWithTypesDataSourceConfig(domain, certType string) string { +func testAccCertificateDataSourceConfig_types(domain, certType string) string { return fmt.Sprintf(` data "aws_acm_certificate" "test" { domain = "%s" @@ -254,7 +254,7 @@ data "aws_acm_certificate" "test" { `, domain, certType) } -func testAccCheckCertificateWithMostRecentDataSourceConfig(domain string, mostRecent bool) string { +func testAccCertificateDataSourceConfig_mostRecent(domain string, mostRecent bool) string { return fmt.Sprintf(` data "aws_acm_certificate" "test" { domain = "%s" @@ -263,7 +263,7 @@ data "aws_acm_certificate" "test" { `, domain, mostRecent) } -func testAccCheckCertificateWithMostRecentAndStatusDataSourceConfig(domain, status string, mostRecent bool) string { +func testAccCertificateDataSourceConfig_mostRecentAndStatus(domain, status string, mostRecent bool) string { return fmt.Sprintf(` data "aws_acm_certificate" "test" { domain = "%s" @@ -273,7 +273,7 @@ data "aws_acm_certificate" "test" { `, domain, status, mostRecent) } -func testAccCheckCertificateWithMostRecentAndTypesDataSourceConfig(domain, certType string, mostRecent bool) string { +func testAccCertificateDataSourceConfig_mostRecentAndTypes(domain, certType string, mostRecent bool) string { return fmt.Sprintf(` data "aws_acm_certificate" "test" { domain = "%s" @@ -283,7 +283,7 @@ data "aws_acm_certificate" "test" { `, domain, certType, mostRecent) } -func testAccCertificateKeyTypesDataSourceConfig(certificate, key, rName string) string { +func testAccCertificateDataSourceConfig_keyTypes(certificate, key, rName string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[1]s" diff --git a/internal/service/acm/certificate_test.go b/internal/service/acm/certificate_test.go index c79bd63a258..cd816c93986 100644 --- a/internal/service/acm/certificate_test.go +++ b/internal/service/acm/certificate_test.go @@ -26,12 +26,12 @@ func TestAccACMCertificate_emailValidation(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateConfig(domain, acm.ValidationMethodEmail), + Config: testAccCertificateConfig_basic(domain, acm.ValidationMethodEmail), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "0"), @@ -63,12 +63,12 @@ func TestAccACMCertificate_dnsValidation(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateConfig(domain, acm.ValidationMethodDns), + Config: testAccCertificateConfig_basic(domain, acm.ValidationMethodDns), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "1"), @@ -102,12 +102,12 @@ func TestAccACMCertificate_root(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateConfig(rootDomain, acm.ValidationMethodDns), + Config: testAccCertificateConfig_basic(rootDomain, acm.ValidationMethodDns), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", rootDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "1"), @@ -142,12 +142,12 @@ func TestAccACMCertificate_validationOptions(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateValidationOptionsConfig(rootDomain, domain), + Config: testAccCertificateConfig_validationOptions(rootDomain, domain), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "0"), @@ -181,12 +181,12 @@ func TestAccACMCertificate_privateCert(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificatePrivateCertConfig(commonName.String(), certificateDomainName), + Config: testAccCertificateConfig_privateCert(commonName.String(), certificateDomainName), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", certificateDomainName), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "0"), @@ -218,10 +218,10 @@ func TestAccACMCertificate_Root_trailingPeriod(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateConfig(domain, acm.ValidationMethodDns), + Config: testAccCertificateConfig_basic(domain, acm.ValidationMethodDns), ExpectError: regexp.MustCompile(`invalid value for domain_name \(cannot end with a period\)`), }, }, @@ -238,12 +238,12 @@ func TestAccACMCertificate_rootAndWildcardSan(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateSubjectAlternativeNamesConfig(rootDomain, strconv.Quote(wildcardDomain), acm.ValidationMethodDns), + Config: testAccCertificateConfig_subjectAlternativeNames(rootDomain, strconv.Quote(wildcardDomain), acm.ValidationMethodDns), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", rootDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "2"), @@ -280,10 +280,10 @@ func TestAccACMCertificate_SubjectAlternativeNames_emptyString(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateSubjectAlternativeNamesConfig(domain, strconv.Quote(""), acm.ValidationMethodDns), + Config: testAccCertificateConfig_subjectAlternativeNames(domain, strconv.Quote(""), acm.ValidationMethodDns), ExpectError: regexp.MustCompile(`expected length`), }, }, @@ -301,12 +301,12 @@ func TestAccACMCertificate_San_single(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateSubjectAlternativeNamesConfig(domain, strconv.Quote(sanDomain), acm.ValidationMethodDns), + Config: testAccCertificateConfig_subjectAlternativeNames(domain, strconv.Quote(sanDomain), acm.ValidationMethodDns), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "2"), @@ -347,12 +347,12 @@ func TestAccACMCertificate_San_multiple(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateSubjectAlternativeNamesConfig(domain, fmt.Sprintf("%q, %q", sanDomain1, sanDomain2), acm.ValidationMethodDns), + Config: testAccCertificateConfig_subjectAlternativeNames(domain, fmt.Sprintf("%q, %q", sanDomain1, sanDomain2), acm.ValidationMethodDns), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "3"), @@ -397,12 +397,12 @@ func TestAccACMCertificate_San_trailingPeriod(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateSubjectAlternativeNamesConfig(domain, strconv.Quote(sanDomain), acm.ValidationMethodDns), + Config: testAccCertificateConfig_subjectAlternativeNames(domain, strconv.Quote(sanDomain), acm.ValidationMethodDns), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile(`certificate/.+`)), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "2"), @@ -442,12 +442,12 @@ func TestAccACMCertificate_San_matches_domain(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateSubjectAlternativeNamesConfig(domain, strconv.Quote(sanDomain), acm.ValidationMethodDns), + Config: testAccCertificateConfig_subjectAlternativeNames(domain, strconv.Quote(sanDomain), acm.ValidationMethodDns), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile(`certificate/.+`)), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "2"), @@ -486,12 +486,12 @@ func TestAccACMCertificate_wildcard(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateConfig(wildcardDomain, acm.ValidationMethodDns), + Config: testAccCertificateConfig_basic(wildcardDomain, acm.ValidationMethodDns), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", wildcardDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "1"), @@ -525,12 +525,12 @@ func TestAccACMCertificate_wildcardAndRootSan(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateSubjectAlternativeNamesConfig(wildcardDomain, strconv.Quote(rootDomain), acm.ValidationMethodDns), + Config: testAccCertificateConfig_subjectAlternativeNames(wildcardDomain, strconv.Quote(rootDomain), acm.ValidationMethodDns), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", wildcardDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "2"), @@ -568,12 +568,12 @@ func TestAccACMCertificate_disableCTLogging(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateDisableCTLoggingConfig(rootDomain, acm.ValidationMethodDns), + Config: testAccCertificateConfig_disableCTLogging(rootDomain, acm.ValidationMethodDns), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", rootDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "1"), @@ -617,18 +617,18 @@ func TestAccACMCertificate_Imported_domainName(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificatePrivateKeyConfig(certificate, key, caCertificate), + Config: testAccCertificateConfig_privateKey(certificate, key, caCertificate), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), resource.TestCheckResourceAttr(resourceName, "domain_name", commonName), ), }, { - Config: testAccAcmCertificatePrivateKeyConfig(newCertificate, key, newCaCertificate), + Config: testAccCertificateConfig_privateKey(newCertificate, key, newCaCertificate), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusIssued), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -636,7 +636,7 @@ func TestAccACMCertificate_Imported_domainName(t *testing.T) { ), }, { - Config: testAccAcmCertificatePrivateKeyWithoutChainConfig(withoutChainDomain), + Config: testAccCertificateConfig_privateKeyNoChain(withoutChainDomain), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusIssued), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -663,12 +663,12 @@ func TestAccACMCertificate_Imported_ipAddress(t *testing.T) { // Reference: http PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificatePrivateKeyWithoutChainConfig("1.2.3.4"), + Config: testAccCertificateConfig_privateKeyNoChain("1.2.3.4"), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "domain_name", ""), resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusIssued), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "0"), @@ -698,12 +698,12 @@ func TestAccACMCertificate_PrivateKey_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateConfigTags1(certificate1, key1, "key1", "value1"), + Config: testAccCertificateConfig_tags1(certificate1, key1, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateExists(resourceName, &v), + testAccCheckCertificateExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), @@ -715,7 +715,7 @@ func TestAccACMCertificate_PrivateKey_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"private_key", "certificate_body"}, }, { - Config: testAccAcmCertificateConfigTags2(certificate1, key1, "key1", "value1updated", "key2", "value2"), + Config: testAccCertificateConfig_tags2(certificate1, key1, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), @@ -723,14 +723,14 @@ func TestAccACMCertificate_PrivateKey_tags(t *testing.T) { ), }, { - Config: testAccAcmCertificateConfigTags1(certificate1, key1, "key2", "value2"), + Config: testAccCertificateConfig_tags1(certificate1, key1, "key2", "value2"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { - Config: testAccAcmCertificateConfigTags1(certificate2, key2, "key1", "value1"), + Config: testAccCertificateConfig_tags1(certificate2, key2, "key1", "value1"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), @@ -740,7 +740,7 @@ func TestAccACMCertificate_PrivateKey_tags(t *testing.T) { }) } -func testAccCheckAcmCertificateExists(n string, v *acm.CertificateDetail) resource.TestCheckFunc { +func testAccCheckCertificateExists(n string, v *acm.CertificateDetail) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -765,7 +765,7 @@ func testAccCheckAcmCertificateExists(n string, v *acm.CertificateDetail) resour } } -func testAccCheckAcmCertificateDestroy(s *terraform.State) error { +func testAccCheckCertificateDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).ACMConn for _, rs := range s.RootModule().Resources { @@ -789,7 +789,7 @@ func testAccCheckAcmCertificateDestroy(s *terraform.State) error { return nil } -func testAccAcmCertificateConfig(domainName, validationMethod string) string { +func testAccCertificateConfig_basic(domainName, validationMethod string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[1]q @@ -798,7 +798,7 @@ resource "aws_acm_certificate" "test" { `, domainName, validationMethod) } -func testAccAcmCertificateValidationOptionsConfig(rootDomainName, domainName string) string { +func testAccCertificateConfig_validationOptions(rootDomainName, domainName string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[2]q @@ -812,7 +812,7 @@ resource "aws_acm_certificate" "test" { `, rootDomainName, domainName) } -func testAccAcmCertificatePrivateCertConfig(commonName, certificateDomainName string) string { +func testAccCertificateConfig_privateCert(commonName, certificateDomainName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "test" { permanent_deletion_time_in_days = 7 @@ -835,7 +835,7 @@ resource "aws_acm_certificate" "test" { `, commonName, certificateDomainName) } -func testAccAcmCertificateSubjectAlternativeNamesConfig(domainName, subjectAlternativeNames, validationMethod string) string { +func testAccCertificateConfig_subjectAlternativeNames(domainName, subjectAlternativeNames, validationMethod string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[1]q @@ -845,7 +845,7 @@ resource "aws_acm_certificate" "test" { `, domainName, subjectAlternativeNames, validationMethod) } -func testAccAcmCertificatePrivateKeyWithoutChainConfig(commonName string) string { +func testAccCertificateConfig_privateKeyNoChain(commonName string) string { key := acctest.TLSRSAPrivateKeyPEM(2048) certificate := acctest.TLSRSAX509SelfSignedCertificatePEM(key, commonName) @@ -857,7 +857,7 @@ resource "aws_acm_certificate" "test" { `, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key)) } -func testAccAcmCertificateConfigTags1(certificate, key, tagKey1, tagValue1 string) string { +func testAccCertificateConfig_tags1(certificate, key, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[1]s" @@ -870,7 +870,7 @@ resource "aws_acm_certificate" "test" { `, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key), tagKey1, tagValue1) } -func testAccAcmCertificateConfigTags2(certificate, key, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccCertificateConfig_tags2(certificate, key, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[1]s" @@ -884,7 +884,7 @@ resource "aws_acm_certificate" "test" { `, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key), tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccAcmCertificatePrivateKeyConfig(certificate, privateKey, chain string) string { +func testAccCertificateConfig_privateKey(certificate, privateKey, chain string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[1]s" @@ -894,7 +894,7 @@ resource "aws_acm_certificate" "test" { `, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(privateKey), acctest.TLSPEMEscapeNewlines(chain)) } -func testAccAcmCertificateDisableCTLoggingConfig(domainName, validationMethod string) string { +func testAccCertificateConfig_disableCTLogging(domainName, validationMethod string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[1]q diff --git a/internal/service/acm/certificate_validation_test.go b/internal/service/acm/certificate_validation_test.go index 6d117f778ed..d9e0e5d3b8b 100644 --- a/internal/service/acm/certificate_validation_test.go +++ b/internal/service/acm/certificate_validation_test.go @@ -24,13 +24,13 @@ func TestAccACMCertificateValidation_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ // Test that validation succeeds { - Config: testAccAcmCertificateValidationConfig(rootDomain, domain), + Config: testAccCertificateValidationConfig_basic(rootDomain, domain), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateValidationExists(resourceName), + testAccCheckCertificateValidationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, @@ -46,10 +46,10 @@ func TestAccACMCertificateValidation_timeout(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateValidationTimeoutConfig(domain), + Config: testAccCertificateValidationConfig_timeout(domain), ExpectError: regexp.MustCompile(`timeout while waiting for state to become 'ISSUED' \(last state: 'PENDING_VALIDATION'`), }, }, @@ -66,18 +66,18 @@ func TestAccACMCertificateValidation_validationRecordFQDNS(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ // Test that validation fails if given validation_fqdns don't match { - Config: testAccAcmCertificateValidationValidationRecordFQDNsWrongFQDNConfig(domain), + Config: testAccCertificateValidationConfig_recordFQDNsWrongFQDN(domain), ExpectError: regexp.MustCompile("missing .+ DNS validation record: .+"), }, // Test that validation succeeds with validation { - Config: testAccAcmCertificateValidationValidationRecordFQDNsOneRoute53RecordConfig(rootDomain, domain), + Config: testAccCertificateValidationConfig_recordFQDNsOneRoute53Record(rootDomain, domain), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateValidationExists(resourceName), + testAccCheckCertificateValidationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, @@ -93,10 +93,10 @@ func TestAccACMCertificateValidation_validationRecordFQDNSEmail(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateValidationValidationRecordFQDNsEmailValidationConfig(domain), + Config: testAccCertificateValidationConfig_recordFQDNsEmail(domain), ExpectError: regexp.MustCompile("validation_record_fqdns is not valid for EMAIL validation"), }, }, @@ -112,12 +112,12 @@ func TestAccACMCertificateValidation_validationRecordFQDNSRoot(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateValidationValidationRecordFQDNsOneRoute53RecordConfig(rootDomain, rootDomain), + Config: testAccCertificateValidationConfig_recordFQDNsOneRoute53Record(rootDomain, rootDomain), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateValidationExists(resourceName), + testAccCheckCertificateValidationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, @@ -135,12 +135,12 @@ func TestAccACMCertificateValidation_validationRecordFQDNSRootAndWildcard(t *tes PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateValidationValidationRecordFQDNsTwoRoute53RecordsConfig(rootDomain, rootDomain, strconv.Quote(wildcardDomain)), + Config: testAccCertificateValidationConfig_recordFQDNsTwoRoute53Records(rootDomain, rootDomain, strconv.Quote(wildcardDomain)), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateValidationExists(resourceName), + testAccCheckCertificateValidationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, @@ -159,12 +159,12 @@ func TestAccACMCertificateValidation_validationRecordFQDNSSan(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateValidationValidationRecordFQDNsTwoRoute53RecordsConfig(rootDomain, domain, strconv.Quote(sanDomain)), + Config: testAccCertificateValidationConfig_recordFQDNsTwoRoute53Records(rootDomain, domain, strconv.Quote(sanDomain)), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateValidationExists(resourceName), + testAccCheckCertificateValidationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, @@ -182,12 +182,12 @@ func TestAccACMCertificateValidation_validationRecordFQDNSWildcard(t *testing.T) PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateValidationValidationRecordFQDNsOneRoute53RecordConfig(rootDomain, wildcardDomain), + Config: testAccCertificateValidationConfig_recordFQDNsOneRoute53Record(rootDomain, wildcardDomain), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateValidationExists(resourceName), + testAccCheckCertificateValidationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), // ExpectNonEmptyPlan: true, // https://github.com/hashicorp/terraform-provider-aws/issues/16913 @@ -206,12 +206,12 @@ func TestAccACMCertificateValidation_validationRecordFQDNSWildcardAndRoot(t *tes PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, acm.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckAcmCertificateDestroy, + CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateValidationValidationRecordFQDNsTwoRoute53RecordsConfig(rootDomain, wildcardDomain, strconv.Quote(rootDomain)), + Config: testAccCertificateValidationConfig_recordFQDNsTwoRoute53Records(rootDomain, wildcardDomain, strconv.Quote(rootDomain)), Check: resource.ComposeTestCheckFunc( - testAccCheckAcmCertificateValidationExists(resourceName), + testAccCheckCertificateValidationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), // ExpectNonEmptyPlan: true, // https://github.com/hashicorp/terraform-provider-aws/issues/16913 @@ -220,7 +220,7 @@ func TestAccACMCertificateValidation_validationRecordFQDNSWildcardAndRoot(t *tes }) } -func testAccCheckAcmCertificateValidationExists(n string) resource.TestCheckFunc { +func testAccCheckCertificateValidationExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -243,7 +243,7 @@ func testAccCheckAcmCertificateValidationExists(n string) resource.TestCheckFunc } } -func testAccAcmCertificateValidationConfig(rootZoneDomain, domainName string) string { +func testAccCertificateValidationConfig_basic(rootZoneDomain, domainName string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[1]q @@ -292,7 +292,7 @@ resource "aws_acm_certificate_validation" "test" { `, domainName, rootZoneDomain) } -func testAccAcmCertificateValidationTimeoutConfig(domainName string) string { +func testAccCertificateValidationConfig_timeout(domainName string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[1]q @@ -309,7 +309,7 @@ resource "aws_acm_certificate_validation" "test" { `, domainName) } -func testAccAcmCertificateValidationValidationRecordFQDNsEmailValidationConfig(domainName string) string { +func testAccCertificateValidationConfig_recordFQDNsEmail(domainName string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[1]q @@ -323,7 +323,7 @@ resource "aws_acm_certificate_validation" "test" { `, domainName) } -func testAccAcmCertificateValidationValidationRecordFQDNsOneRoute53RecordConfig(rootZoneDomain, domainName string) string { +func testAccCertificateValidationConfig_recordFQDNsOneRoute53Record(rootZoneDomain, domainName string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[1]q @@ -376,7 +376,7 @@ resource "aws_acm_certificate_validation" "test" { `, domainName, rootZoneDomain) } -func testAccAcmCertificateValidationValidationRecordFQDNsTwoRoute53RecordsConfig(rootZoneDomain, domainName, subjectAlternativeNames string) string { +func testAccCertificateValidationConfig_recordFQDNsTwoRoute53Records(rootZoneDomain, domainName, subjectAlternativeNames string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[1]q @@ -439,7 +439,7 @@ resource "aws_acm_certificate_validation" "test" { `, domainName, subjectAlternativeNames, rootZoneDomain) } -func testAccAcmCertificateValidationValidationRecordFQDNsWrongFQDNConfig(domainName string) string { +func testAccCertificateValidationConfig_recordFQDNsWrongFQDN(domainName string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = %[1]q diff --git a/internal/service/acmpca/certificate_authority_certificate_test.go b/internal/service/acmpca/certificate_authority_certificate_test.go index bedb647271c..7954a2dedcf 100644 --- a/internal/service/acmpca/certificate_authority_certificate_test.go +++ b/internal/service/acmpca/certificate_authority_certificate_test.go @@ -26,7 +26,7 @@ func TestAccACMPCACertificateAuthorityCertificate_rootCA(t *testing.T) { CheckDestroy: nil, // Certificate authority certificates cannot be deleted Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityCertificate_RootCA(commonName), + Config: testAccCertificateAuthorityCertificateConfig_rootCA(commonName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCertificateAuthorityCertificateExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "certificate_authority_arn", "aws_acmpca_certificate_authority.test", "arn"), @@ -57,7 +57,7 @@ func TestAccACMPCACertificateAuthorityCertificate_updateRootCA(t *testing.T) { CheckDestroy: nil, // Certificate authority certificates cannot be deleted Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityCertificate_RootCA(commonName), + Config: testAccCertificateAuthorityCertificateConfig_rootCA(commonName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCertificateAuthorityCertificateExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "certificate_authority_arn", "aws_acmpca_certificate_authority.test", "arn"), @@ -66,7 +66,7 @@ func TestAccACMPCACertificateAuthorityCertificate_updateRootCA(t *testing.T) { ), }, { - Config: testAccCertificateAuthorityCertificate_UpdateRootCA(commonName), + Config: testAccCertificateAuthorityCertificateConfig_updateRootCA(commonName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCertificateAuthorityCertificateExists(updatedResourceName, &v), resource.TestCheckResourceAttrPair(updatedResourceName, "certificate_authority_arn", "aws_acmpca_certificate_authority.test", "arn"), @@ -91,7 +91,7 @@ func TestAccACMPCACertificateAuthorityCertificate_subordinateCA(t *testing.T) { CheckDestroy: nil, // Certificate authority certificates cannot be deleted Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityCertificate_SubordinateCA(commonName), + Config: testAccCertificateAuthorityCertificateConfig_subordinateCA(commonName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCertificateAuthorityCertificateExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "certificate_authority_arn", "aws_acmpca_certificate_authority.test", "arn"), @@ -131,7 +131,7 @@ func testAccCheckCertificateAuthorityCertificateExists(resourceName string, cert } } -func testAccCertificateAuthorityCertificate_RootCA(commonName string) string { +func testAccCertificateAuthorityCertificateConfig_rootCA(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority_certificate" "test" { certificate_authority_arn = aws_acmpca_certificate_authority.test.arn @@ -171,7 +171,7 @@ data "aws_partition" "current" {} `, commonName) } -func testAccCertificateAuthorityCertificate_UpdateRootCA(commonName string) string { +func testAccCertificateAuthorityCertificateConfig_updateRootCA(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority_certificate" "updated" { certificate_authority_arn = aws_acmpca_certificate_authority.test.arn @@ -211,7 +211,7 @@ data "aws_partition" "current" {} `, commonName) } -func testAccCertificateAuthorityCertificate_SubordinateCA(commonName string) string { +func testAccCertificateAuthorityCertificateConfig_subordinateCA(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority_certificate" "test" { certificate_authority_arn = aws_acmpca_certificate_authority.test.arn diff --git a/internal/service/acmpca/certificate_authority_data_source_test.go b/internal/service/acmpca/certificate_authority_data_source_test.go index 83ee0e45413..ac500033c4c 100644 --- a/internal/service/acmpca/certificate_authority_data_source_test.go +++ b/internal/service/acmpca/certificate_authority_data_source_test.go @@ -22,11 +22,11 @@ func TestAccACMPCACertificateAuthorityDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityDataSourceConfig_NonExistent, + Config: testAccCertificateAuthorityDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`(AccessDeniedException|ResourceNotFoundException)`), }, { - Config: testAccCertificateAuthorityDataSourceConfig_ARN(commonName), + Config: testAccCertificateAuthorityDataSourceConfig_arn(commonName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "certificate", resourceName, "certificate"), @@ -59,11 +59,11 @@ func TestAccACMPCACertificateAuthorityDataSource_s3ObjectACL(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityDataSourceConfig_NonExistent, + Config: testAccCertificateAuthorityDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`(AccessDeniedException|ResourceNotFoundException)`), }, { - Config: testAccCertificateAuthorityS3ObjectACLDataSourceConfig_ARN(commonName), + Config: testAccCertificateAuthorityDataSourceConfig_s3ObjectACLARN(commonName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "certificate", resourceName, "certificate"), @@ -88,7 +88,7 @@ func TestAccACMPCACertificateAuthorityDataSource_s3ObjectACL(t *testing.T) { }) } -func testAccCertificateAuthorityDataSourceConfig_ARN(commonName string) string { +func testAccCertificateAuthorityDataSourceConfig_arn(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "wrong" { permanent_deletion_time_in_days = 7 @@ -122,7 +122,7 @@ data "aws_acmpca_certificate_authority" "test" { `, commonName) } -func testAccCertificateAuthorityS3ObjectACLDataSourceConfig_ARN(commonName string) string { +func testAccCertificateAuthorityDataSourceConfig_s3ObjectACLARN(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "wrong" { permanent_deletion_time_in_days = 7 @@ -157,7 +157,7 @@ data "aws_acmpca_certificate_authority" "test" { } //lintignore:AWSAT003,AWSAT005 -const testAccCertificateAuthorityDataSourceConfig_NonExistent = ` +const testAccCertificateAuthorityDataSourceConfig_nonExistent = ` data "aws_acmpca_certificate_authority" "test" { arn = "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/tf-acc-test-does-not-exist" } diff --git a/internal/service/acmpca/certificate_authority_test.go b/internal/service/acmpca/certificate_authority_test.go index 0977552852f..bdcd5a6fb51 100644 --- a/internal/service/acmpca/certificate_authority_test.go +++ b/internal/service/acmpca/certificate_authority_test.go @@ -29,7 +29,7 @@ func TestAccACMPCACertificateAuthority_basic(t *testing.T) { CheckDestroy: testAccCheckCertificateAuthorityDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityConfig_Required(commonName), + Config: testAccCertificateAuthorityConfig_required(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm-pca", regexp.MustCompile(`certificate-authority/.+`)), @@ -76,7 +76,7 @@ func TestAccACMPCACertificateAuthority_disappears(t *testing.T) { CheckDestroy: testAccCheckCertificateAuthorityDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityConfig_Required(commonName), + Config: testAccCertificateAuthorityConfig_required(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), acctest.CheckResourceDisappears(acctest.Provider, tfacmpca.ResourceCertificateAuthority(), resourceName), @@ -100,7 +100,7 @@ func TestAccACMPCACertificateAuthority_enabledDeprecated(t *testing.T) { CheckDestroy: testAccCheckCertificateAuthorityDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityConfig_Enabled(commonName, acmpca.CertificateAuthorityTypeRoot, true), + Config: testAccCertificateAuthorityConfig_enabled(commonName, acmpca.CertificateAuthorityTypeRoot, true), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "type", acmpca.CertificateAuthorityTypeRoot), @@ -110,7 +110,7 @@ func TestAccACMPCACertificateAuthority_enabledDeprecated(t *testing.T) { ), }, { - Config: testAccCertificateAuthorityConfig_Enabled(commonName, acmpca.CertificateAuthorityTypeRoot, true), + Config: testAccCertificateAuthorityConfig_enabled(commonName, acmpca.CertificateAuthorityTypeRoot, true), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "type", acmpca.CertificateAuthorityTypeRoot), @@ -119,7 +119,7 @@ func TestAccACMPCACertificateAuthority_enabledDeprecated(t *testing.T) { ), }, { - Config: testAccCertificateAuthorityConfig_Enabled(commonName, acmpca.CertificateAuthorityTypeRoot, false), + Config: testAccCertificateAuthorityConfig_enabled(commonName, acmpca.CertificateAuthorityTypeRoot, false), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -151,7 +151,7 @@ func TestAccACMPCACertificateAuthority_deleteFromActiveState(t *testing.T) { CheckDestroy: testAccCheckCertificateAuthorityDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityConfig_WithRootCertificate(commonName), + Config: testAccCertificateAuthorityConfig_root(commonName), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "type", acmpca.CertificateAuthorityTypeRoot), @@ -183,7 +183,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_customCNAME(t *testing.T) { Steps: []resource.TestStep{ // Test creating revocation configuration on resource creation { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_CustomCNAME(rName, commonName, customCName), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationCustomCNAME(rName, commonName, customCName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -205,7 +205,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_customCNAME(t *testing.T) { }, // Test updating revocation configuration { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_CustomCNAME(rName, commonName, customCName2), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationCustomCNAME(rName, commonName, customCName2), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -218,7 +218,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_customCNAME(t *testing.T) { }, // Test removing custom cname on resource update { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_Enabled(rName, commonName, true), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationEnabled(rName, commonName, true), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -231,7 +231,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_customCNAME(t *testing.T) { }, // Test adding custom cname on resource update { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_CustomCNAME(rName, commonName, customCName), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationCustomCNAME(rName, commonName, customCName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -244,7 +244,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_customCNAME(t *testing.T) { }, // Test removing revocation configuration on resource update { - Config: testAccCertificateAuthorityConfig_Required(commonName), + Config: testAccCertificateAuthorityConfig_required(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -271,7 +271,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_enabled(t *testing.T) { Steps: []resource.TestStep{ // Test creating revocation configuration on resource creation { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_Enabled(rName, commonName, true), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationEnabled(rName, commonName, true), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -293,7 +293,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_enabled(t *testing.T) { }, // Test disabling revocation configuration { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_Enabled(rName, commonName, false), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationEnabled(rName, commonName, false), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -303,7 +303,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_enabled(t *testing.T) { }, // Test enabling revocation configuration { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_Enabled(rName, commonName, true), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationEnabled(rName, commonName, true), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -316,7 +316,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_enabled(t *testing.T) { }, // Test removing revocation configuration on resource update { - Config: testAccCertificateAuthorityConfig_Required(commonName), + Config: testAccCertificateAuthorityConfig_required(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -343,7 +343,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_expirationInDays(t *testing Steps: []resource.TestStep{ // Test creating revocation configuration on resource creation { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_ExpirationInDays(rName, commonName, 1), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationExpirationInDays(rName, commonName, 1), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -366,7 +366,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_expirationInDays(t *testing }, // Test updating revocation configuration { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_ExpirationInDays(rName, commonName, 2), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationExpirationInDays(rName, commonName, 2), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -378,7 +378,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_expirationInDays(t *testing }, // Test removing revocation configuration on resource update { - Config: testAccCertificateAuthorityConfig_Required(commonName), + Config: testAccCertificateAuthorityConfig_required(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -405,7 +405,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_s3ObjectACL(t *testing.T) { Steps: []resource.TestStep{ // Test creating revocation configuration on resource creation { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_s3ObjectACL(rName, commonName, "BUCKET_OWNER_FULL_CONTROL"), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationS3ObjectACL(rName, commonName, "BUCKET_OWNER_FULL_CONTROL"), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -427,7 +427,7 @@ func TestAccACMPCACertificateAuthority_RevocationCrl_s3ObjectACL(t *testing.T) { }, // Test updating revocation configuration { - Config: testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_s3ObjectACL(rName, commonName, "PUBLIC_READ"), + Config: testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationS3ObjectACL(rName, commonName, "PUBLIC_READ"), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "revocation_configuration.#", "1"), @@ -455,7 +455,7 @@ func TestAccACMPCACertificateAuthority_tags(t *testing.T) { CheckDestroy: testAccCheckCertificateAuthorityDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateAuthorityConfig_Tags_Single(commonName), + Config: testAccCertificateAuthorityConfig_tagsSingle(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -463,7 +463,7 @@ func TestAccACMPCACertificateAuthority_tags(t *testing.T) { ), }, { - Config: testAccCertificateAuthorityConfig_Tags_SingleUpdated(commonName), + Config: testAccCertificateAuthorityConfig_tagsSingleUpdated(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -471,7 +471,7 @@ func TestAccACMPCACertificateAuthority_tags(t *testing.T) { ), }, { - Config: testAccCertificateAuthorityConfig_Tags_Multiple(commonName), + Config: testAccCertificateAuthorityConfig_tagsMultiple(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -480,7 +480,7 @@ func TestAccACMPCACertificateAuthority_tags(t *testing.T) { ), }, { - Config: testAccCertificateAuthorityConfig_Tags_Single(commonName), + Config: testAccCertificateAuthorityConfig_tagsSingle(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(resourceName, &certificateAuthority), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -528,7 +528,7 @@ func testAccCheckCertificateAuthorityDestroy(s *terraform.State) error { return nil } -func testAccCertificateAuthorityConfig_Enabled(commonName, certificateAuthorityType string, enabled bool) string { +func testAccCertificateAuthorityConfig_enabled(commonName, certificateAuthorityType string, enabled bool) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "test" { enabled = %[1]t @@ -547,7 +547,7 @@ resource "aws_acmpca_certificate_authority" "test" { `, enabled, certificateAuthorityType, commonName) } -func testAccCertificateAuthorityConfig_WithRootCertificate(commonName string) string { +func testAccCertificateAuthorityConfig_root(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "test" { permanent_deletion_time_in_days = 7 @@ -587,7 +587,7 @@ data "aws_partition" "current" {} `, commonName) } -func testAccCertificateAuthorityConfig_Required(commonName string) string { +func testAccCertificateAuthorityConfig_required(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "test" { certificate_authority_configuration { @@ -602,7 +602,7 @@ resource "aws_acmpca_certificate_authority" "test" { `, commonName) } -func testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_CustomCNAME(rName, commonName, customCname string) string { +func testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationCustomCNAME(rName, commonName, customCname string) string { return acctest.ConfigCompose( testAccCertificateAuthorityConfig_S3Bucket(rName), fmt.Sprintf(` @@ -632,7 +632,7 @@ resource "aws_acmpca_certificate_authority" "test" { `, commonName, customCname)) } -func testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_Enabled(rName, commonName string, enabled bool) string { +func testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationEnabled(rName, commonName string, enabled bool) string { return acctest.ConfigCompose( testAccCertificateAuthorityConfig_S3Bucket(rName), fmt.Sprintf(` @@ -659,7 +659,7 @@ resource "aws_acmpca_certificate_authority" "test" { `, commonName, enabled)) } -func testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_ExpirationInDays(rName, commonName string, expirationInDays int) string { +func testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationExpirationInDays(rName, commonName string, expirationInDays int) string { return acctest.ConfigCompose( testAccCertificateAuthorityConfig_S3Bucket(rName), fmt.Sprintf(` @@ -686,7 +686,7 @@ resource "aws_acmpca_certificate_authority" "test" { `, commonName, expirationInDays)) } -func testAccCertificateAuthorityConfig_RevocationConfiguration_CrlConfiguration_s3ObjectACL(rName, commonName, s3ObjectAcl string) string { +func testAccCertificateAuthorityConfig_revocationConfigurationCrlConfigurationS3ObjectACL(rName, commonName, s3ObjectAcl string) string { return acctest.ConfigCompose( testAccCertificateAuthorityConfig_S3Bucket(rName), fmt.Sprintf(` @@ -751,7 +751,7 @@ resource "aws_s3_bucket_policy" "test" { `, rName) } -func testAccCertificateAuthorityConfig_Tags_Single(commonName string) string { +func testAccCertificateAuthorityConfig_tagsSingle(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "test" { permanent_deletion_time_in_days = 7 @@ -772,7 +772,7 @@ resource "aws_acmpca_certificate_authority" "test" { `, commonName) } -func testAccCertificateAuthorityConfig_Tags_SingleUpdated(commonName string) string { +func testAccCertificateAuthorityConfig_tagsSingleUpdated(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "test" { permanent_deletion_time_in_days = 7 @@ -793,7 +793,7 @@ resource "aws_acmpca_certificate_authority" "test" { `, commonName) } -func testAccCertificateAuthorityConfig_Tags_Multiple(commonName string) string { +func testAccCertificateAuthorityConfig_tagsMultiple(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "test" { permanent_deletion_time_in_days = 7 diff --git a/internal/service/acmpca/certificate_data_source_test.go b/internal/service/acmpca/certificate_data_source_test.go index 83c364a1314..51d03989ec9 100644 --- a/internal/service/acmpca/certificate_data_source_test.go +++ b/internal/service/acmpca/certificate_data_source_test.go @@ -22,11 +22,11 @@ func TestAccACMPCACertificateDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCertificateDataSourceConfig_NonExistent, + Config: testAccCertificateDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`ResourceNotFoundException`), }, { - Config: testAccCertificateDataSourceConfig_ARN(domain), + Config: testAccCertificateDataSourceConfig_arn(domain), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "certificate", resourceName, "certificate"), @@ -38,7 +38,7 @@ func TestAccACMPCACertificateDataSource_basic(t *testing.T) { }) } -func testAccCertificateDataSourceConfig_ARN(domain string) string { +func testAccCertificateDataSourceConfig_arn(domain string) string { return fmt.Sprintf(` data "aws_acmpca_certificate" "test" { arn = aws_acmpca_certificate.test.arn @@ -76,7 +76,7 @@ data "aws_partition" "current" {} `, domain) } -const testAccCertificateDataSourceConfig_NonExistent = ` +const testAccCertificateDataSourceConfig_nonExistent = ` data "aws_acmpca_certificate" "test" { arn = "arn:${data.aws_partition.current.partition}:acm-pca:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:certificate-authority/does-not-exist/certificate/does-not-exist" certificate_authority_arn = "arn:${data.aws_partition.current.partition}:acm-pca:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:certificate-authority/does-not-exist" diff --git a/internal/service/acmpca/certificate_test.go b/internal/service/acmpca/certificate_test.go index 331c6c2b454..b940291e885 100644 --- a/internal/service/acmpca/certificate_test.go +++ b/internal/service/acmpca/certificate_test.go @@ -30,7 +30,7 @@ func TestAccACMPCACertificate_rootCertificate(t *testing.T) { CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateConfig_RootCertificate(domain), + Config: testAccCertificateConfig_root(domain), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCertificateExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm-pca", regexp.MustCompile(`certificate-authority/.+/certificate/.+$`)), @@ -73,7 +73,7 @@ func TestAccACMPCACertificate_subordinateCertificate(t *testing.T) { CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateConfig_SubordinateCertificate(domain), + Config: testAccCertificateConfig_subordinate(domain), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCertificateExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm-pca", regexp.MustCompile(`certificate-authority/.+/certificate/.+$`)), @@ -116,7 +116,7 @@ func TestAccACMPCACertificate_endEntityCertificate(t *testing.T) { CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateConfig_EndEntityCertificate(domain, acctest.TLSPEMEscapeNewlines(csr)), + Config: testAccCertificateConfig_endEntity(domain, acctest.TLSPEMEscapeNewlines(csr)), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCertificateExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm-pca", regexp.MustCompile(`certificate-authority/.+/certificate/.+$`)), @@ -159,7 +159,7 @@ func TestAccACMPCACertificate_Validity_endDate(t *testing.T) { CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateConfig_Validity_EndDate(domain, acctest.TLSPEMEscapeNewlines(csr), later), + Config: testAccCertificateConfig_validityEndDate(domain, acctest.TLSPEMEscapeNewlines(csr), later), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCertificateExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm-pca", regexp.MustCompile(`certificate-authority/.+/certificate/.+$`)), @@ -202,7 +202,7 @@ func TestAccACMPCACertificate_Validity_absolute(t *testing.T) { CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateConfig_Validity_Absolute(domain, acctest.TLSPEMEscapeNewlines(csr), later), + Config: testAccCertificateConfig_validityAbsolute(domain, acctest.TLSPEMEscapeNewlines(csr), later), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCertificateExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "acm-pca", regexp.MustCompile(`certificate-authority/.+/certificate/.+$`)), @@ -290,7 +290,7 @@ func testAccCheckCertificateExists(resourceName string) resource.TestCheckFunc { } } -func testAccCertificateConfig_RootCertificate(domain string) string { +func testAccCertificateConfig_root(domain string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate" "test" { certificate_authority_arn = aws_acmpca_certificate_authority.test.arn @@ -323,7 +323,7 @@ data "aws_partition" "current" {} `, domain) } -func testAccCertificateConfig_SubordinateCertificate(domain string) string { +func testAccCertificateConfig_subordinate(domain string) string { return acctest.ConfigCompose( testAccCertificateBaseRootCAConfig(domain), fmt.Sprintf(` @@ -356,7 +356,7 @@ resource "aws_acmpca_certificate_authority" "test" { `, domain)) } -func testAccCertificateConfig_EndEntityCertificate(domain, csr string) string { +func testAccCertificateConfig_endEntity(domain, csr string) string { return acctest.ConfigCompose( testAccCertificateBaseRootCAConfig(domain), fmt.Sprintf(` @@ -375,7 +375,7 @@ resource "aws_acmpca_certificate" "test" { `, csr)) } -func testAccCertificateConfig_Validity_EndDate(domain, csr, expiry string) string { +func testAccCertificateConfig_validityEndDate(domain, csr, expiry string) string { return acctest.ConfigCompose( testAccCertificateBaseRootCAConfig(domain), fmt.Sprintf(` @@ -394,7 +394,7 @@ resource "aws_acmpca_certificate" "test" { `, csr, expiry)) } -func testAccCertificateConfig_Validity_Absolute(domain, csr string, expiry int64) string { +func testAccCertificateConfig_validityAbsolute(domain, csr string, expiry int64) string { return acctest.ConfigCompose( testAccCertificateBaseRootCAConfig(domain), fmt.Sprintf(` @@ -453,7 +453,7 @@ data "aws_partition" "current" {} `, domain) } -func TestValidateAcmPcaTemplateArn(t *testing.T) { +func TestValidateTemplateARN(t *testing.T) { validNames := []string{ "arn:aws:acm-pca:::template/EndEntityCertificate/V1", // lintignore:AWSAT005 "arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen0/V1", // lintignore:AWSAT005 @@ -482,7 +482,7 @@ func TestValidateAcmPcaTemplateArn(t *testing.T) { } } -func TestExpandAcmpcaValidityValue(t *testing.T) { +func TestExpandValidityValue(t *testing.T) { testCases := []struct { Type string Value string diff --git a/internal/service/acmpca/find.go b/internal/service/acmpca/find.go index 000b42de21a..382dd042d70 100644 --- a/internal/service/acmpca/find.go +++ b/internal/service/acmpca/find.go @@ -5,6 +5,7 @@ import ( "github.com/aws/aws-sdk-go/service/acmpca" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) // FindCertificateAuthorityByARN returns the certificate authority corresponding to the specified ARN. @@ -53,3 +54,28 @@ func FindCertificateAuthorityCertificateByARN(conn *acmpca.ACMPCA, arn string) ( return output, nil } + +func FindPolicyByARN(conn *acmpca.ACMPCA, arn string) (string, error) { + input := &acmpca.GetPolicyInput{ + ResourceArn: aws.String(arn), + } + + output, err := conn.GetPolicy(input) + + if tfawserr.ErrCodeEquals(err, acmpca.ErrCodeResourceNotFoundException) { + return "", &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return "", err + } + + if output == nil || output.Policy == nil { + return "", tfresource.NewEmptyResultError(input) + } + + return aws.StringValue(output.Policy), nil +} diff --git a/internal/service/acmpca/policy.go b/internal/service/acmpca/policy.go new file mode 100644 index 00000000000..de35f282c9d --- /dev/null +++ b/internal/service/acmpca/policy.go @@ -0,0 +1,117 @@ +package acmpca + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/acmpca" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourcePolicy() *schema.Resource { + return &schema.Resource{ + Create: resourcePolicyPut, + Read: resourcePolicyRead, + Update: resourcePolicyPut, + Delete: resourcePolicyDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "policy": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsJSON, + DiffSuppressFunc: verify.SuppressEquivalentPolicyDiffs, + StateFunc: func(v interface{}) string { + json, _ := structure.NormalizeJsonString(v) + return json + }, + }, + "resource_arn": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourcePolicyPut(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).ACMPCAConn + + policy, err := structure.NormalizeJsonString(d.Get("policy").(string)) + + if err != nil { + return fmt.Errorf("policy (%s) is invalid JSON: %w", d.Get("policy").(string), err) + } + + resourceARN := d.Get("resource_arn").(string) + input := &acmpca.PutPolicyInput{ + Policy: aws.String(policy), + ResourceArn: aws.String(resourceARN), + } + + log.Printf("[DEBUG] Putting ACM PCA Policy: %s", input) + _, err = conn.PutPolicy(input) + + if err != nil { + return fmt.Errorf("putting ACM PCA Policy (%s): %w", resourceARN, err) + } + + d.SetId(resourceARN) + + return resourcePolicyRead(d, meta) +} + +func resourcePolicyRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).ACMPCAConn + + policy, err := FindPolicyByARN(conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] ACM PCA Policy (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("reading ACM PCA Policy (%s): %w", d.Id(), err) + } + + d.Set("policy", policy) + d.Set("resource_arn", d.Id()) + + return nil +} + +func resourcePolicyDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).ACMPCAConn + + log.Printf("[DEBUG] Deleting ACM PCA Policy: %s", d.Id()) + _, err := conn.DeletePolicy(&acmpca.DeletePolicyInput{ + ResourceArn: aws.String(d.Id()), + }) + + if tfawserr.ErrCodeEquals(err, acmpca.ErrCodeResourceNotFoundException) || + tfawserr.ErrCodeEquals(err, acmpca.ErrCodeRequestAlreadyProcessedException) || + tfawserr.ErrCodeEquals(err, acmpca.ErrCodeRequestInProgressException) || + tfawserr.ErrMessageContains(err, acmpca.ErrCodeInvalidRequestException, "Self-signed policy can not be revoked") { + return nil + } + + if err != nil { + return fmt.Errorf("deleting ACM PCA Policy (%s): %w", d.Id(), err) + } + + return nil +} diff --git a/internal/service/acmpca/policy_test.go b/internal/service/acmpca/policy_test.go new file mode 100644 index 00000000000..682556cc7c5 --- /dev/null +++ b/internal/service/acmpca/policy_test.go @@ -0,0 +1,149 @@ +package acmpca_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/acmpca" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfacmpca "github.com/hashicorp/terraform-provider-aws/internal/service/acmpca" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccACMPCAPolicy_Basic(t *testing.T) { + resourceName := "aws_acmpca_policy.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, acmpca.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccPolicyConfig_basic(), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckPolicyExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "policy"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckPolicyDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).ACMPCAConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_acmpca_policy" { + continue + } + + _, err := tfacmpca.FindPolicyByARN(conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("ACM PCA Policy %s still exists", rs.Primary.ID) + } + + return nil +} + +func testAccCheckPolicyExists(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ACM PCA Policy ID is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).ACMPCAConn + + _, err := tfacmpca.FindPolicyByARN(conn, rs.Primary.ID) + + if err != nil { + return err + } + + return nil + } +} + +func testAccPolicyConfig_basic() string { + return ` +data "aws_caller_identity" "current" {} + +data "aws_partition" "current" {} + +resource "aws_acmpca_certificate_authority" "test" { + certificate_authority_configuration { + key_algorithm = "RSA_4096" + signing_algorithm = "SHA512WITHRSA" + + subject { + common_name = "example.com" + } + } + + permanent_deletion_time_in_days = 7 +} + +resource "aws_acmpca_policy" "test" { + resource_arn = aws_acmpca_certificate_authority.test.arn + policy = <"), @@ -358,7 +358,7 @@ func testAccApp_CustomRules(t *testing.T) { ), }, { - Config: testAccAppNameConfig(rName), + Config: testAccAppConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "custom_rule.#", "0"), @@ -380,7 +380,7 @@ func testAccApp_Description(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppDescriptionConfig(rName, "description 1"), + Config: testAccAppConfig_description(rName, "description 1"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app1), resource.TestCheckResourceAttr(resourceName, "description", "description 1"), @@ -392,7 +392,7 @@ func testAccApp_Description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAppDescriptionConfig(rName, "description 2"), + Config: testAccAppConfig_description(rName, "description 2"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app2), testAccCheckAppNotRecreated(&app1, &app2), @@ -400,7 +400,7 @@ func testAccApp_Description(t *testing.T) { ), }, { - Config: testAccAppNameConfig(rName), + Config: testAccAppConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app3), testAccCheckAppRecreated(&app2, &app3), @@ -423,7 +423,7 @@ func testAccApp_EnvironmentVariables(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppEnvironmentVariablesConfig(rName), + Config: testAccAppConfig_environmentVariables(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "environment_variables.%", "1"), @@ -436,7 +436,7 @@ func testAccApp_EnvironmentVariables(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAppEnvironmentVariablesUpdatedConfig(rName), + Config: testAccAppConfig_environmentVariablesUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "environment_variables.%", "2"), @@ -445,7 +445,7 @@ func testAccApp_EnvironmentVariables(t *testing.T) { ), }, { - Config: testAccAppNameConfig(rName), + Config: testAccAppConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "environment_variables.%", "0"), @@ -469,7 +469,7 @@ func testAccApp_IAMServiceRole(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppIAMServiceRoleARNConfig(rName), + Config: testAccAppConfig_iamServiceRoleARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app1), resource.TestCheckResourceAttrPair(resourceName, "iam_service_role_arn", iamRole1ResourceName, "arn")), @@ -480,7 +480,7 @@ func testAccApp_IAMServiceRole(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAppIAMServiceRoleARNUpdatedConfig(rName), + Config: testAccAppConfig_iamServiceRoleARNUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app2), testAccCheckAppNotRecreated(&app1, &app2), @@ -488,7 +488,7 @@ func testAccApp_IAMServiceRole(t *testing.T) { ), }, { - Config: testAccAppNameConfig(rName), + Config: testAccAppConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app3), testAccCheckAppRecreated(&app2, &app3), @@ -512,7 +512,7 @@ func testAccApp_Name(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppNameConfig(rName1), + Config: testAccAppConfig_name(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "name", rName1), @@ -524,7 +524,7 @@ func testAccApp_Name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAppNameConfig(rName2), + Config: testAccAppConfig_name(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "name", rName2), @@ -558,7 +558,7 @@ func testAccApp_Repository(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppRepositoryConfig(rName, repository, accessToken), + Config: testAccAppConfig_repository(rName, repository, accessToken), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "access_token", accessToken), @@ -652,7 +652,7 @@ func testAccCheckAppRecreated(before, after *amplify.App) resource.TestCheckFunc } } -func testAccAppNameConfig(rName string) string { +func testAccAppConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -660,7 +660,7 @@ resource "aws_amplify_app" "test" { `, rName) } -func testAccAppTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAppConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -672,7 +672,7 @@ resource "aws_amplify_app" "test" { `, rName, tagKey1, tagValue1) } -func testAccAppTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAppConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -685,7 +685,7 @@ resource "aws_amplify_app" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccAppAutoBranchCreationNoAutoBranchCreationConfig(rName string) string { +func testAccAppConfig_autoBranchCreationNoAutoBranchCreation(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -700,7 +700,7 @@ resource "aws_amplify_app" "test" { `, rName) } -func testAccAppAutoBranchCreationAutoBranchCreationConfig(rName, basicAuthCredentials string) string { +func testAccAppConfig_autoBranchCreationAutoBranchCreation(rName, basicAuthCredentials string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -732,7 +732,7 @@ resource "aws_amplify_app" "test" { `, rName, basicAuthCredentials) } -func testAccAppAutoBranchCreationAutoBranchCreationUpdatedConfig(rName string) string { +func testAccAppConfig_autoBranchCreationAutoBranchCreationUpdated(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -759,7 +759,7 @@ resource "aws_amplify_app" "test" { `, rName) } -func testAccAppBasicAuthCredentialsConfig(rName, basicAuthCredentials string) string { +func testAccAppConfig_basicAuthCredentials(rName, basicAuthCredentials string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -770,7 +770,7 @@ resource "aws_amplify_app" "test" { `, rName, basicAuthCredentials) } -func testAccAppBuildSpecConfig(rName, buildSpec string) string { +func testAccAppConfig_buildSpec(rName, buildSpec string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -780,7 +780,7 @@ resource "aws_amplify_app" "test" { `, rName, buildSpec) } -func testAccAppCustomRulesConfig(rName string) string { +func testAccAppConfig_customRules(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -794,7 +794,7 @@ resource "aws_amplify_app" "test" { `, rName) } -func testAccAppCustomRulesUpdatedConfig(rName string) string { +func testAccAppConfig_customRulesUpdated(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -815,7 +815,7 @@ resource "aws_amplify_app" "test" { `, rName) } -func testAccAppDescriptionConfig(rName, description string) string { +func testAccAppConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -825,7 +825,7 @@ resource "aws_amplify_app" "test" { `, rName, description) } -func testAccAppEnvironmentVariablesConfig(rName string) string { +func testAccAppConfig_environmentVariables(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -837,7 +837,7 @@ resource "aws_amplify_app" "test" { `, rName) } -func testAccAppEnvironmentVariablesUpdatedConfig(rName string) string { +func testAccAppConfig_environmentVariablesUpdated(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -888,7 +888,7 @@ POLICY `, rName) } -func testAccAppIAMServiceRoleARNConfig(rName string) string { +func testAccAppConfig_iamServiceRoleARN(rName string) string { return acctest.ConfigCompose(testAccAppIAMServiceRoleBaseConfig(rName), fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -898,7 +898,7 @@ resource "aws_amplify_app" "test" { `, rName)) } -func testAccAppIAMServiceRoleARNUpdatedConfig(rName string) string { +func testAccAppConfig_iamServiceRoleARNUpdated(rName string) string { return acctest.ConfigCompose(testAccAppIAMServiceRoleBaseConfig(rName), fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -908,7 +908,7 @@ resource "aws_amplify_app" "test" { `, rName)) } -func testAccAppRepositoryConfig(rName, repository, accessToken string) string { +func testAccAppConfig_repository(rName, repository, accessToken string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q diff --git a/internal/service/amplify/backend_environment_test.go b/internal/service/amplify/backend_environment_test.go index e2c3c41afb1..f89150ef4da 100644 --- a/internal/service/amplify/backend_environment_test.go +++ b/internal/service/amplify/backend_environment_test.go @@ -29,7 +29,7 @@ func testAccBackendEnvironment_basic(t *testing.T) { CheckDestroy: testAccCheckBackendEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBackendEnvironmentBasicConfig(rName, environmentName), + Config: testAccBackendEnvironmentConfig_basic(rName, environmentName), Check: resource.ComposeTestCheckFunc( testAccCheckBackendEnvironmentExists(resourceName, &env), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "amplify", regexp.MustCompile(`apps/[^/]+/backendenvironments/.+`)), @@ -61,7 +61,7 @@ func testAccBackendEnvironment_disappears(t *testing.T) { CheckDestroy: testAccCheckBackendEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBackendEnvironmentBasicConfig(rName, environmentName), + Config: testAccBackendEnvironmentConfig_basic(rName, environmentName), Check: resource.ComposeTestCheckFunc( testAccCheckBackendEnvironmentExists(resourceName, &env), acctest.CheckResourceDisappears(acctest.Provider, tfamplify.ResourceBackendEnvironment(), resourceName), @@ -86,7 +86,7 @@ func testAccBackendEnvironment_DeploymentArtifacts_StackName(t *testing.T) { CheckDestroy: testAccCheckBackendEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBackendEnvironmentDeploymentArtifactsAndStackNameConfig(rName, environmentName), + Config: testAccBackendEnvironmentConfig_deploymentArtifactsAndStackName(rName, environmentName), Check: resource.ComposeTestCheckFunc( testAccCheckBackendEnvironmentExists(resourceName, &env), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "amplify", regexp.MustCompile(`apps/[^/]+/backendenvironments/.+`)), @@ -165,7 +165,7 @@ func testAccCheckBackendEnvironmentDestroy(s *terraform.State) error { return nil } -func testAccBackendEnvironmentBasicConfig(rName string, environmentName string) string { +func testAccBackendEnvironmentConfig_basic(rName string, environmentName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -178,7 +178,7 @@ resource "aws_amplify_backend_environment" "test" { `, rName, environmentName) } -func testAccBackendEnvironmentDeploymentArtifactsAndStackNameConfig(rName string, environmentName string) string { +func testAccBackendEnvironmentConfig_deploymentArtifactsAndStackName(rName string, environmentName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q diff --git a/internal/service/amplify/branch_test.go b/internal/service/amplify/branch_test.go index c1bbee1d170..90d99ba4075 100644 --- a/internal/service/amplify/branch_test.go +++ b/internal/service/amplify/branch_test.go @@ -28,7 +28,7 @@ func testAccBranch_basic(t *testing.T) { CheckDestroy: testAccCheckBranchDestroy, Steps: []resource.TestStep{ { - Config: testAccBranchNameConfig(rName), + Config: testAccBranchConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "amplify", regexp.MustCompile(`apps/.+/branches/.+`)), @@ -75,7 +75,7 @@ func testAccBranch_disappears(t *testing.T) { CheckDestroy: testAccCheckBranchDestroy, Steps: []resource.TestStep{ { - Config: testAccBranchNameConfig(rName), + Config: testAccBranchConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), acctest.CheckResourceDisappears(acctest.Provider, tfamplify.ResourceBranch(), resourceName), @@ -98,7 +98,7 @@ func testAccBranch_Tags(t *testing.T) { CheckDestroy: testAccCheckBranchDestroy, Steps: []resource.TestStep{ { - Config: testAccBranchTags1Config(rName, "key1", "value1"), + Config: testAccBranchConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -111,7 +111,7 @@ func testAccBranch_Tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBranchTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccBranchConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -120,7 +120,7 @@ func testAccBranch_Tags(t *testing.T) { ), }, { - Config: testAccBranchTags1Config(rName, "key2", "value2"), + Config: testAccBranchConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -146,7 +146,7 @@ func testAccBranch_BasicAuthCredentials(t *testing.T) { CheckDestroy: testAccCheckBranchDestroy, Steps: []resource.TestStep{ { - Config: testAccBranchBasicAuthCredentialsConfig(rName, credentials1), + Config: testAccBranchConfig_basicAuthCredentials(rName, credentials1), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttr(resourceName, "basic_auth_credentials", credentials1), @@ -159,7 +159,7 @@ func testAccBranch_BasicAuthCredentials(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBranchBasicAuthCredentialsConfig(rName, credentials2), + Config: testAccBranchConfig_basicAuthCredentials(rName, credentials2), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttr(resourceName, "basic_auth_credentials", credentials2), @@ -167,7 +167,7 @@ func testAccBranch_BasicAuthCredentials(t *testing.T) { ), }, { - Config: testAccBranchNameConfig(rName), + Config: testAccBranchConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), // Clearing basic_auth_credentials not reflected in API. @@ -191,7 +191,7 @@ func testAccBranch_EnvironmentVariables(t *testing.T) { CheckDestroy: testAccCheckBranchDestroy, Steps: []resource.TestStep{ { - Config: testAccBranchEnvironmentVariablesConfig(rName), + Config: testAccBranchConfig_environmentVariables(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttr(resourceName, "environment_variables.%", "1"), @@ -204,7 +204,7 @@ func testAccBranch_EnvironmentVariables(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBranchEnvironmentVariablesUpdatedConfig(rName), + Config: testAccBranchConfig_environmentVariablesUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttr(resourceName, "environment_variables.%", "2"), @@ -213,7 +213,7 @@ func testAccBranch_EnvironmentVariables(t *testing.T) { ), }, { - Config: testAccBranchNameConfig(rName), + Config: testAccBranchConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttr(resourceName, "environment_variables.%", "0"), @@ -238,7 +238,7 @@ func testAccBranch_OptionalArguments(t *testing.T) { CheckDestroy: testAccCheckBranchDestroy, Steps: []resource.TestStep{ { - Config: testAccBranchOptionalArgumentsConfig(rName, environmentName), + Config: testAccBranchConfig_optionalArguments(rName, environmentName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttrPair(resourceName, "backend_environment_arn", backendEnvironment1ResourceName, "arn"), @@ -260,7 +260,7 @@ func testAccBranch_OptionalArguments(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBranchOptionalArgumentsUpdatedConfig(rName, environmentName), + Config: testAccBranchConfig_optionalArgumentsUpdated(rName, environmentName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBranchExists(resourceName, &branch), resource.TestCheckResourceAttrPair(resourceName, "backend_environment_arn", backendEnvironment2ResourceName, "arn"), @@ -341,7 +341,7 @@ func testAccCheckBranchDestroy(s *terraform.State) error { return nil } -func testAccBranchNameConfig(rName string) string { +func testAccBranchConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -354,7 +354,7 @@ resource "aws_amplify_branch" "test" { `, rName) } -func testAccBranchTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccBranchConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -371,7 +371,7 @@ resource "aws_amplify_branch" "test" { `, rName, tagKey1, tagValue1) } -func testAccBranchTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccBranchConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -389,7 +389,7 @@ resource "aws_amplify_branch" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccBranchBasicAuthCredentialsConfig(rName, basicAuthCredentials string) string { +func testAccBranchConfig_basicAuthCredentials(rName, basicAuthCredentials string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -405,7 +405,7 @@ resource "aws_amplify_branch" "test" { `, rName, basicAuthCredentials) } -func testAccBranchEnvironmentVariablesConfig(rName string) string { +func testAccBranchConfig_environmentVariables(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -422,7 +422,7 @@ resource "aws_amplify_branch" "test" { `, rName) } -func testAccBranchEnvironmentVariablesUpdatedConfig(rName string) string { +func testAccBranchConfig_environmentVariablesUpdated(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -440,7 +440,7 @@ resource "aws_amplify_branch" "test" { `, rName) } -func testAccBranchOptionalArgumentsConfig(rName, environmentName string) string { +func testAccBranchConfig_optionalArguments(rName, environmentName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -475,7 +475,7 @@ resource "aws_amplify_branch" "test" { `, rName, environmentName) } -func testAccBranchOptionalArgumentsUpdatedConfig(rName, environmentName string) string { +func testAccBranchConfig_optionalArgumentsUpdated(rName, environmentName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q diff --git a/internal/service/amplify/domain_association_test.go b/internal/service/amplify/domain_association_test.go index 78ee7e0e886..e1d904d3da5 100644 --- a/internal/service/amplify/domain_association_test.go +++ b/internal/service/amplify/domain_association_test.go @@ -34,7 +34,7 @@ func testAccDomainAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckDomainAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainAssociationConfig(rName, domainName, false), + Config: testAccDomainAssociationConfig_basic(rName, domainName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainAssociationExists(resourceName, &domain), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "amplify", regexp.MustCompile(`apps/.+/domains/.+`)), @@ -75,7 +75,7 @@ func testAccDomainAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckDomainAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainAssociationConfig(rName, domainName, false), + Config: testAccDomainAssociationConfig_basic(rName, domainName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainAssociationExists(resourceName, &domain), acctest.CheckResourceDisappears(acctest.Provider, tfamplify.ResourceDomainAssociation(), resourceName), @@ -104,7 +104,7 @@ func testAccDomainAssociation_update(t *testing.T) { CheckDestroy: testAccCheckDomainAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainAssociationConfig(rName, domainName, true), + Config: testAccDomainAssociationConfig_basic(rName, domainName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainAssociationExists(resourceName, &domain), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "amplify", regexp.MustCompile(`apps/.+/domains/.+`)), @@ -124,7 +124,7 @@ func testAccDomainAssociation_update(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_verification"}, }, { - Config: testAccDomainAssociationUpdatedConfig(rName, domainName, true), + Config: testAccDomainAssociationConfig_updated(rName, domainName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainAssociationExists(resourceName, &domain), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "amplify", regexp.MustCompile(`apps/.+/domains/.+`)), @@ -206,7 +206,7 @@ func testAccCheckDomainAssociationDestroy(s *terraform.State) error { return nil } -func testAccDomainAssociationConfig(rName, domainName string, waitForVerification bool) string { +func testAccDomainAssociationConfig_basic(rName, domainName string, waitForVerification bool) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -231,7 +231,7 @@ resource "aws_amplify_domain_association" "test" { `, rName, domainName, waitForVerification) } -func testAccDomainAssociationUpdatedConfig(rName, domainName string, waitForVerification bool) string { +func testAccDomainAssociationConfig_updated(rName, domainName string, waitForVerification bool) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q diff --git a/internal/service/amplify/webhook_test.go b/internal/service/amplify/webhook_test.go index 8764a4e4171..3afde908a8f 100644 --- a/internal/service/amplify/webhook_test.go +++ b/internal/service/amplify/webhook_test.go @@ -27,7 +27,7 @@ func testAccWebhook_basic(t *testing.T) { CheckDestroy: testAccCheckWebhookDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookConfig(rName), + Config: testAccWebhookConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "amplify", regexp.MustCompile(`apps/.+/webhooks/.+`)), @@ -57,7 +57,7 @@ func testAccWebhook_disappears(t *testing.T) { CheckDestroy: testAccCheckWebhookDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookConfig(rName), + Config: testAccWebhookConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), acctest.CheckResourceDisappears(acctest.Provider, tfamplify.ResourceWebhook(), resourceName), @@ -80,7 +80,7 @@ func testAccWebhook_update(t *testing.T) { CheckDestroy: testAccCheckWebhookDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookDescriptionConfig(rName), + Config: testAccWebhookConfig_description(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "branch_name", fmt.Sprintf("%s-1", rName)), @@ -93,7 +93,7 @@ func testAccWebhook_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccWebhookDescriptionUpdatedConfig(rName), + Config: testAccWebhookConfig_descriptionUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "branch_name", fmt.Sprintf("%s-2", rName)), @@ -153,7 +153,7 @@ func testAccCheckWebhookDestroy(s *terraform.State) error { return nil } -func testAccWebhookConfig(rName string) string { +func testAccWebhookConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -171,7 +171,7 @@ resource "aws_amplify_webhook" "test" { `, rName) } -func testAccWebhookDescriptionConfig(rName string) string { +func testAccWebhookConfig_description(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q @@ -195,7 +195,7 @@ resource "aws_amplify_webhook" "test" { `, rName) } -func testAccWebhookDescriptionUpdatedConfig(rName string) string { +func testAccWebhookConfig_descriptionUpdated(rName string) string { return fmt.Sprintf(` resource "aws_amplify_app" "test" { name = %[1]q diff --git a/internal/service/apigateway/api_key_data_source_test.go b/internal/service/apigateway/api_key_data_source_test.go index 71e26b4c9cb..ecbea8a3921 100644 --- a/internal/service/apigateway/api_key_data_source_test.go +++ b/internal/service/apigateway/api_key_data_source_test.go @@ -21,7 +21,7 @@ func TestAccAPIGatewayAPIKeyDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAPIKeyDataSourceConfig(rName), + Config: testAccAPIKeyDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName1, "id", dataSourceName1, "id"), resource.TestCheckResourceAttrPair(resourceName1, "name", dataSourceName1, "name"), @@ -37,7 +37,7 @@ func TestAccAPIGatewayAPIKeyDataSource_basic(t *testing.T) { }) } -func testAccAPIKeyDataSourceConfig(r string) string { +func testAccAPIKeyDataSourceConfig_basic(r string) string { return fmt.Sprintf(` resource "aws_api_gateway_api_key" "example_key" { name = "%s" diff --git a/internal/service/apigateway/api_key_test.go b/internal/service/apigateway/api_key_test.go index 4e36790f998..00fc970aacf 100644 --- a/internal/service/apigateway/api_key_test.go +++ b/internal/service/apigateway/api_key_test.go @@ -28,7 +28,7 @@ func TestAccAPIGatewayAPIKey_basic(t *testing.T) { CheckDestroy: testAccCheckAPIKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIKeyConfig(rName), + Config: testAccAPIKeyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey1), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/apikeys/+.`)), @@ -61,7 +61,7 @@ func TestAccAPIGatewayAPIKey_tags(t *testing.T) { CheckDestroy: testAccCheckAPIKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIKeyTags1Config(rName, "key1", "value1"), + Config: testAccAPIKeyConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -69,7 +69,7 @@ func TestAccAPIGatewayAPIKey_tags(t *testing.T) { ), }, { - Config: testAccAPIKeyTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAPIKeyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey1), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -78,7 +78,7 @@ func TestAccAPIGatewayAPIKey_tags(t *testing.T) { ), }, { - Config: testAccAPIKeyTags1Config(rName, "key2", "value2"), + Config: testAccAPIKeyConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -106,7 +106,7 @@ func TestAccAPIGatewayAPIKey_description(t *testing.T) { CheckDestroy: testAccCheckAPIKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIKeyDescriptionConfig(rName, "description1"), + Config: testAccAPIKeyConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey1), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -118,7 +118,7 @@ func TestAccAPIGatewayAPIKey_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAPIKeyDescriptionConfig(rName, "description2"), + Config: testAccAPIKeyConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey2), testAccCheckAPIKeyNotRecreated(&apiKey1, &apiKey2), @@ -141,7 +141,7 @@ func TestAccAPIGatewayAPIKey_enabled(t *testing.T) { CheckDestroy: testAccCheckAPIKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIKeyEnabledConfig(rName, false), + Config: testAccAPIKeyConfig_enabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey1), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -153,7 +153,7 @@ func TestAccAPIGatewayAPIKey_enabled(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAPIKeyEnabledConfig(rName, true), + Config: testAccAPIKeyConfig_enabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey2), testAccCheckAPIKeyNotRecreated(&apiKey1, &apiKey2), @@ -176,7 +176,7 @@ func TestAccAPIGatewayAPIKey_value(t *testing.T) { CheckDestroy: testAccCheckAPIKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIKeyValueConfig(rName, `MyCustomToken#@&\"'(§!ç)-_*$€¨^£%ù+=/:.;?,|`), + Config: testAccAPIKeyConfig_value(rName, `MyCustomToken#@&\"'(§!ç)-_*$€¨^£%ù+=/:.;?,|`), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey1), resource.TestCheckResourceAttr(resourceName, "value", `MyCustomToken#@&\"'(§!ç)-_*$€¨^£%ù+=/:.;?,|`), @@ -203,7 +203,7 @@ func TestAccAPIGatewayAPIKey_disappears(t *testing.T) { CheckDestroy: testAccCheckAPIKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIKeyConfig(rName), + Config: testAccAPIKeyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAPIKeyExists(resourceName, &apiKey1), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceAPIKey(), resourceName), @@ -286,7 +286,7 @@ func testAccCheckAPIKeyNotRecreated(i, j *apigateway.ApiKey) resource.TestCheckF } } -func testAccAPIKeyConfig(rName string) string { +func testAccAPIKeyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_api_key" "test" { name = %[1]q @@ -294,7 +294,7 @@ resource "aws_api_gateway_api_key" "test" { `, rName) } -func testAccAPIKeyTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAPIKeyConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_api_gateway_api_key" "test" { name = %[1]q @@ -306,7 +306,7 @@ resource "aws_api_gateway_api_key" "test" { `, rName, tagKey1, tagValue1) } -func testAccAPIKeyTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAPIKeyConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_api_gateway_api_key" "test" { name = %[1]q @@ -319,7 +319,7 @@ resource "aws_api_gateway_api_key" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccAPIKeyDescriptionConfig(rName, description string) string { +func testAccAPIKeyConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_api_gateway_api_key" "test" { description = %[2]q @@ -328,7 +328,7 @@ resource "aws_api_gateway_api_key" "test" { `, rName, description) } -func testAccAPIKeyEnabledConfig(rName string, enabled bool) string { +func testAccAPIKeyConfig_enabled(rName string, enabled bool) string { return fmt.Sprintf(` resource "aws_api_gateway_api_key" "test" { enabled = %[2]t @@ -337,7 +337,7 @@ resource "aws_api_gateway_api_key" "test" { `, rName, enabled) } -func testAccAPIKeyValueConfig(rName, value string) string { +func testAccAPIKeyConfig_value(rName, value string) string { return fmt.Sprintf(` resource "aws_api_gateway_api_key" "test" { name = %[1]q diff --git a/internal/service/apigateway/authorizer_test.go b/internal/service/apigateway/authorizer_test.go index 2cdb52c9f79..1e3424c1686 100644 --- a/internal/service/apigateway/authorizer_test.go +++ b/internal/service/apigateway/authorizer_test.go @@ -116,7 +116,7 @@ func TestAccAPIGatewayAuthorizer_Cognito_authorizerCredentials(t *testing.T) { CheckDestroy: testAccCheckAuthorizerDestroy, Steps: []resource.TestStep{ { - Config: testAccAuthorizerConfig_cognitoAuthorizerCredentials(rName), + Config: testAccAuthorizerConfig_cognitoCredentials(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "authorizer_credentials", iamRoleResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -531,7 +531,7 @@ resource "aws_api_gateway_authorizer" "test" { `, rName) } -func testAccAuthorizerConfig_cognitoAuthorizerCredentials(rName string) string { +func testAccAuthorizerConfig_cognitoCredentials(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/apigateway/base_path_mapping_test.go b/internal/service/apigateway/base_path_mapping_test.go index 793245a10c1..fbe7af385f1 100644 --- a/internal/service/apigateway/base_path_mapping_test.go +++ b/internal/service/apigateway/base_path_mapping_test.go @@ -14,7 +14,7 @@ import ( tfapigateway "github.com/hashicorp/terraform-provider-aws/internal/service/apigateway" ) -func TestDecodeApiGatewayBasePathMappingId(t *testing.T) { +func TestDecodeBasePathMappingID(t *testing.T) { var testCases = []struct { Input string DomainName string @@ -81,7 +81,7 @@ func TestAccAPIGatewayBasePathMapping_basic(t *testing.T) { CheckDestroy: testAccCheckBasePathDestroy(name), Steps: []resource.TestStep{ { - Config: testAccBasePathBasePathConfig(name, key, certificate, acctest.ResourcePrefix), + Config: testAccBasePathMappingConfig_basic(name, key, certificate, acctest.ResourcePrefix), Check: resource.ComposeTestCheckFunc( testAccCheckBasePathExists("aws_api_gateway_base_path_mapping.test", &conf), ), @@ -111,7 +111,7 @@ func TestAccAPIGatewayBasePathMapping_BasePath_empty(t *testing.T) { CheckDestroy: testAccCheckBasePathDestroy(name), Steps: []resource.TestStep{ { - Config: testAccBasePathBasePathConfig(name, key, certificate, ""), + Config: testAccBasePathMappingConfig_basic(name, key, certificate, ""), Check: resource.ComposeTestCheckFunc( testAccCheckBasePathExists("aws_api_gateway_base_path_mapping.test", &conf), ), @@ -140,24 +140,24 @@ func TestAccAPIGatewayBasePathMapping_updates(t *testing.T) { CheckDestroy: testAccCheckBasePathDestroy(name), Steps: []resource.TestStep{ { - Config: testAccBasePathBasePathConfig(name, key, certificate, ""), + Config: testAccBasePathMappingConfig_basic(name, key, certificate, ""), Check: resource.ComposeTestCheckFunc( testAccCheckBasePathExists(resourceName, &confFirst), testAccCheckBasePathStageAttribute(&confFirst, "test"), ), }, { - Config: testAccBasePathBasePathAltStageAndAPIConfig(name, key, certificate, ""), + Config: testAccBasePathMappingConfig_altStageAndAPI(name, key, certificate, ""), Check: resource.ComposeTestCheckFunc( testAccCheckBasePathExists(resourceName, &conf), testAccCheckBasePathBasePathAttribute(&conf, "(none)"), testAccCheckBasePathStageAttribute(&conf, "test2"), - testAccCheckRestAPIIdAttributeHasChanged(&conf, &confFirst), + testAccCheckRestAPIIDAttributeHasChanged(&conf, &confFirst), resource.TestCheckResourceAttr(resourceName, "stage_name", "test2"), ), }, { - Config: testAccBasePathBasePathAltStageAndAPIConfig(name, key, certificate, "thing"), + Config: testAccBasePathMappingConfig_altStageAndAPI(name, key, certificate, "thing"), Check: resource.ComposeTestCheckFunc( testAccCheckBasePathExists(resourceName, &conf), testAccCheckBasePathBasePathAttribute(&conf, "thing"), @@ -191,7 +191,7 @@ func TestAccAPIGatewayBasePathMapping_disappears(t *testing.T) { CheckDestroy: testAccCheckBasePathDestroy(name), Steps: []resource.TestStep{ { - Config: testAccBasePathBasePathConfig(name, key, certificate, acctest.ResourcePrefix), + Config: testAccBasePathMappingConfig_basic(name, key, certificate, acctest.ResourcePrefix), Check: resource.ComposeTestCheckFunc( testAccCheckBasePathExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceBasePathMapping(), resourceName), @@ -282,7 +282,7 @@ func testAccCheckBasePathStageAttribute(conf *apigateway.BasePathMapping, basePa } } -func testAccCheckRestAPIIdAttributeHasChanged(conf *apigateway.BasePathMapping, previousConf *apigateway.BasePathMapping) resource.TestCheckFunc { +func testAccCheckRestAPIIDAttributeHasChanged(conf *apigateway.BasePathMapping, previousConf *apigateway.BasePathMapping) resource.TestCheckFunc { return func(s *terraform.State) error { if conf.RestApiId == nil { return fmt.Errorf("attribute RestApiId should not be nil") @@ -362,7 +362,7 @@ resource "aws_api_gateway_deployment" "test" { `, domainName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key)) } -func testAccBasePathBasePathConfig(domainName, key, certificate, basePath string) string { +func testAccBasePathMappingConfig_basic(domainName, key, certificate, basePath string) string { return testAccBasePathBaseConfig(domainName, key, certificate) + fmt.Sprintf(` resource "aws_api_gateway_base_path_mapping" "test" { api_id = aws_api_gateway_rest_api.test.id @@ -373,7 +373,7 @@ resource "aws_api_gateway_base_path_mapping" "test" { `, basePath) } -func testAccBasePathBasePathAltStageAndAPIConfig(domainName, key, certificate, basePath string) string { +func testAccBasePathMappingConfig_altStageAndAPI(domainName, key, certificate, basePath string) string { return testAccBasePathBaseConfig(domainName, key, certificate) + fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test2" { diff --git a/internal/service/apigateway/client_certificate_test.go b/internal/service/apigateway/client_certificate_test.go index dc527d1ac42..edb7e44b29b 100644 --- a/internal/service/apigateway/client_certificate_test.go +++ b/internal/service/apigateway/client_certificate_test.go @@ -39,7 +39,7 @@ func TestAccAPIGatewayClientCertificate_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClientCertificateConfig_basic_updated, + Config: testAccClientCertificateConfig_basicUpdated, Check: resource.ComposeTestCheckFunc( testAccCheckClientCertificateExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/clientcertificates/+.`)), @@ -61,7 +61,7 @@ func TestAccAPIGatewayClientCertificate_tags(t *testing.T) { CheckDestroy: testAccCheckClientCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccClientCertificateTags1Config("key1", "value1"), + Config: testAccClientCertificateConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckClientCertificateExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -74,7 +74,7 @@ func TestAccAPIGatewayClientCertificate_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClientCertificateTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccClientCertificateConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClientCertificateExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -83,7 +83,7 @@ func TestAccAPIGatewayClientCertificate_tags(t *testing.T) { ), }, { - Config: testAccClientCertificateTags1Config("key2", "value2"), + Config: testAccClientCertificateConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClientCertificateExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -179,13 +179,13 @@ resource "aws_api_gateway_client_certificate" "test" { } ` -const testAccClientCertificateConfig_basic_updated = ` +const testAccClientCertificateConfig_basicUpdated = ` resource "aws_api_gateway_client_certificate" "test" { description = "Hello from TF acceptance test - updated" } ` -func testAccClientCertificateTags1Config(tagKey1, tagValue1 string) string { +func testAccClientCertificateConfig_tags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_api_gateway_client_certificate" "test" { description = "Hello from TF acceptance test" @@ -197,7 +197,7 @@ resource "aws_api_gateway_client_certificate" "test" { `, tagKey1, tagValue1) } -func testAccClientCertificateTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccClientCertificateConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_api_gateway_client_certificate" "test" { description = "Hello from TF acceptance test" diff --git a/internal/service/apigateway/deployment_test.go b/internal/service/apigateway/deployment_test.go index 6ca61ae479e..1623e657cda 100644 --- a/internal/service/apigateway/deployment_test.go +++ b/internal/service/apigateway/deployment_test.go @@ -29,7 +29,7 @@ func TestAccAPIGatewayDeployment_basic(t *testing.T) { CheckDestroy: testAccCheckDeploymentDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStageNameConfig(rName), + Config: testAccDeploymentConfig_stageName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment), resource.TestCheckResourceAttrSet(resourceName, "created_date"), @@ -60,7 +60,7 @@ func TestAccAPIGatewayDeployment_Disappears_restAPI(t *testing.T) { CheckDestroy: testAccCheckDeploymentDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStageNameConfig(rName), + Config: testAccDeploymentConfig_stageName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment), testAccCheckRestAPIExists(restApiResourceName, &restApi), @@ -84,7 +84,7 @@ func TestAccAPIGatewayDeployment_triggers(t *testing.T) { CheckDestroy: testAccCheckDeploymentDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentTriggersConfig("description1", "https://example.com"), + Config: testAccDeploymentConfig_triggers("description1", "https://example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment1), testAccCheckStageExists(resourceName, &stage), @@ -96,7 +96,7 @@ func TestAccAPIGatewayDeployment_triggers(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: testAccDeploymentTriggersConfig("description1", "https://example.com"), + Config: testAccDeploymentConfig_triggers("description1", "https://example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment2), testAccCheckDeploymentRecreated(&deployment1, &deployment2), @@ -106,7 +106,7 @@ func TestAccAPIGatewayDeployment_triggers(t *testing.T) { ), }, { - Config: testAccDeploymentTriggersConfig("description1", "https://example.com"), + Config: testAccDeploymentConfig_triggers("description1", "https://example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment3), testAccCheckDeploymentNotRecreated(&deployment2, &deployment3), @@ -116,7 +116,7 @@ func TestAccAPIGatewayDeployment_triggers(t *testing.T) { ), }, { - Config: testAccDeploymentTriggersConfig("description2", "https://example.org"), + Config: testAccDeploymentConfig_triggers("description2", "https://example.org"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment4), testAccCheckDeploymentRecreated(&deployment3, &deployment4), @@ -140,14 +140,14 @@ func TestAccAPIGatewayDeployment_description(t *testing.T) { CheckDestroy: testAccCheckDeploymentDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentDescriptionConfig("description1"), + Config: testAccDeploymentConfig_description("description1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment), resource.TestCheckResourceAttr(resourceName, "description", "description1"), ), }, { - Config: testAccDeploymentDescriptionConfig("description2"), + Config: testAccDeploymentConfig_description("description2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -169,7 +169,7 @@ func TestAccAPIGatewayDeployment_stageDescription(t *testing.T) { CheckDestroy: testAccCheckDeploymentDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStageDescriptionConfig("description1"), + Config: testAccDeploymentConfig_stageDescription("description1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment), testAccCheckStageExists(resourceName, &stage), @@ -192,7 +192,7 @@ func TestAccAPIGatewayDeployment_stageName(t *testing.T) { CheckDestroy: testAccCheckDeploymentDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStageNameConfig("test"), + Config: testAccDeploymentConfig_stageName("test"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment), testAccCheckStageExists(resourceName, &stage), @@ -200,7 +200,7 @@ func TestAccAPIGatewayDeployment_stageName(t *testing.T) { ), }, { - Config: testAccDeploymentRequiredConfig(), + Config: testAccDeploymentConfig_required(), Check: resource.ComposeTestCheckFunc( resource.TestCheckNoResourceAttr(resourceName, "stage_name"), ), @@ -220,7 +220,7 @@ func TestAccAPIGatewayDeployment_StageName_emptyString(t *testing.T) { CheckDestroy: testAccCheckDeploymentDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStageNameConfig(""), + Config: testAccDeploymentConfig_stageName(""), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment), resource.TestCheckResourceAttr(resourceName, "stage_name", ""), @@ -241,7 +241,7 @@ func TestAccAPIGatewayDeployment_variables(t *testing.T) { CheckDestroy: testAccCheckDeploymentDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentVariablesConfig("key1", "value1"), + Config: testAccDeploymentConfig_variables("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &deployment), resource.TestCheckResourceAttr(resourceName, "variables.%", "1"), @@ -382,7 +382,7 @@ resource "aws_api_gateway_integration_response" "test" { `, uri) } -func testAccDeploymentTriggersConfig(description string, url string) string { +func testAccDeploymentConfig_triggers(description string, url string) string { return testAccDeploymentBaseConfig(url) + fmt.Sprintf(` resource "aws_api_gateway_deployment" "test" { description = %[1]q @@ -401,7 +401,7 @@ resource "aws_api_gateway_deployment" "test" { `, description) } -func testAccDeploymentDescriptionConfig(description string) string { +func testAccDeploymentConfig_description(description string) string { return testAccDeploymentBaseConfig("http://example.com") + fmt.Sprintf(` resource "aws_api_gateway_deployment" "test" { depends_on = [aws_api_gateway_integration.test] @@ -412,7 +412,7 @@ resource "aws_api_gateway_deployment" "test" { `, description) } -func testAccDeploymentRequiredConfig() string { +func testAccDeploymentConfig_required() string { return testAccDeploymentBaseConfig("http://example.com") + ` resource "aws_api_gateway_deployment" "test" { depends_on = [aws_api_gateway_integration.test] @@ -422,7 +422,7 @@ resource "aws_api_gateway_deployment" "test" { ` } -func testAccDeploymentStageDescriptionConfig(stageDescription string) string { +func testAccDeploymentConfig_stageDescription(stageDescription string) string { return testAccDeploymentBaseConfig("http://example.com") + fmt.Sprintf(` resource "aws_api_gateway_deployment" "test" { depends_on = [aws_api_gateway_integration.test] @@ -434,7 +434,7 @@ resource "aws_api_gateway_deployment" "test" { `, stageDescription) } -func testAccDeploymentStageNameConfig(stageName string) string { +func testAccDeploymentConfig_stageName(stageName string) string { return testAccDeploymentBaseConfig("http://example.com") + fmt.Sprintf(` resource "aws_api_gateway_deployment" "test" { depends_on = [aws_api_gateway_integration.test] @@ -445,7 +445,7 @@ resource "aws_api_gateway_deployment" "test" { `, stageName) } -func testAccDeploymentVariablesConfig(key1, value1 string) string { +func testAccDeploymentConfig_variables(key1, value1 string) string { return testAccDeploymentBaseConfig("http://example.com") + fmt.Sprintf(` resource "aws_api_gateway_deployment" "test" { depends_on = [aws_api_gateway_integration.test] diff --git a/internal/service/apigateway/documentation_part.go b/internal/service/apigateway/documentation_part.go index c58b3d14116..067eeb8fdf5 100644 --- a/internal/service/apigateway/documentation_part.go +++ b/internal/service/apigateway/documentation_part.go @@ -77,7 +77,7 @@ func resourceDocumentationPartCreate(d *schema.ResourceData, meta interface{}) e apiId := d.Get("rest_api_id").(string) out, err := conn.CreateDocumentationPart(&apigateway.CreateDocumentationPartInput{ - Location: expandApiGatewayDocumentationPartLocation(d.Get("location").([]interface{})), + Location: expandDocumentationPartLocation(d.Get("location").([]interface{})), Properties: aws.String(d.Get("properties").(string)), RestApiId: aws.String(apiId), }) @@ -113,7 +113,7 @@ func resourceDocumentationPartRead(d *schema.ResourceData, meta interface{}) err } d.Set("rest_api_id", apiId) - d.Set("location", flattenApiGatewayDocumentationPartLocation(docPart.Location)) + d.Set("location", flattenDocumentationPartLocation(docPart.Location)) d.Set("properties", docPart.Properties) return nil @@ -171,7 +171,7 @@ func resourceDocumentationPartDelete(d *schema.ResourceData, meta interface{}) e return err } -func expandApiGatewayDocumentationPartLocation(l []interface{}) *apigateway.DocumentationPartLocation { +func expandDocumentationPartLocation(l []interface{}) *apigateway.DocumentationPartLocation { if len(l) == 0 { return nil } @@ -194,7 +194,7 @@ func expandApiGatewayDocumentationPartLocation(l []interface{}) *apigateway.Docu return out } -func flattenApiGatewayDocumentationPartLocation(l *apigateway.DocumentationPartLocation) []interface{} { +func flattenDocumentationPartLocation(l *apigateway.DocumentationPartLocation) []interface{} { if l == nil { return []interface{}{} } diff --git a/internal/service/apigateway/documentation_part_test.go b/internal/service/apigateway/documentation_part_test.go index b84e4969971..b662077c318 100644 --- a/internal/service/apigateway/documentation_part_test.go +++ b/internal/service/apigateway/documentation_part_test.go @@ -33,7 +33,7 @@ func TestAccAPIGatewayDocumentationPart_basic(t *testing.T) { CheckDestroy: testAccCheckDocumentationPartDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentationPartConfig(apiName, strconv.Quote(properties)), + Config: testAccDocumentationPartConfig_basic(apiName, strconv.Quote(properties)), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationPartExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "location.#", "1"), @@ -48,7 +48,7 @@ func TestAccAPIGatewayDocumentationPart_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentationPartConfig(apiName, strconv.Quote(uProperties)), + Config: testAccDocumentationPartConfig_basic(apiName, strconv.Quote(uProperties)), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationPartExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "location.#", "1"), @@ -78,7 +78,7 @@ func TestAccAPIGatewayDocumentationPart_method(t *testing.T) { CheckDestroy: testAccCheckDocumentationPartDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentationPartMethodConfig(apiName, strconv.Quote(properties)), + Config: testAccDocumentationPartConfig_method(apiName, strconv.Quote(properties)), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationPartExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "location.#", "1"), @@ -95,7 +95,7 @@ func TestAccAPIGatewayDocumentationPart_method(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentationPartMethodConfig(apiName, strconv.Quote(uProperties)), + Config: testAccDocumentationPartConfig_method(apiName, strconv.Quote(uProperties)), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationPartExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "location.#", "1"), @@ -127,7 +127,7 @@ func TestAccAPIGatewayDocumentationPart_responseHeader(t *testing.T) { CheckDestroy: testAccCheckDocumentationPartDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentationPartResponseHeaderConfig(apiName, strconv.Quote(properties)), + Config: testAccDocumentationPartConfig_responseHeader(apiName, strconv.Quote(properties)), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationPartExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "location.#", "1"), @@ -146,7 +146,7 @@ func TestAccAPIGatewayDocumentationPart_responseHeader(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentationPartResponseHeaderConfig(apiName, strconv.Quote(uProperties)), + Config: testAccDocumentationPartConfig_responseHeader(apiName, strconv.Quote(uProperties)), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationPartExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "location.#", "1"), @@ -179,7 +179,7 @@ func TestAccAPIGatewayDocumentationPart_disappears(t *testing.T) { CheckDestroy: testAccCheckDocumentationPartDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentationPartConfig(apiName, strconv.Quote(properties)), + Config: testAccDocumentationPartConfig_basic(apiName, strconv.Quote(properties)), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationPartExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceDocumentationPart(), resourceName), @@ -253,7 +253,7 @@ func testAccCheckDocumentationPartDestroy(s *terraform.State) error { return nil } -func testAccDocumentationPartConfig(apiName, properties string) string { +func testAccDocumentationPartConfig_basic(apiName, properties string) string { return fmt.Sprintf(` resource "aws_api_gateway_documentation_part" "test" { location { @@ -269,7 +269,7 @@ resource "aws_api_gateway_rest_api" "test" { `, properties, apiName) } -func testAccDocumentationPartMethodConfig(apiName, properties string) string { +func testAccDocumentationPartConfig_method(apiName, properties string) string { return fmt.Sprintf(` resource "aws_api_gateway_documentation_part" "test" { location { @@ -287,7 +287,7 @@ resource "aws_api_gateway_rest_api" "test" { `, properties, apiName) } -func testAccDocumentationPartResponseHeaderConfig(apiName, properties string) string { +func testAccDocumentationPartConfig_responseHeader(apiName, properties string) string { return fmt.Sprintf(` resource "aws_api_gateway_documentation_part" "test" { location { diff --git a/internal/service/apigateway/documentation_version_test.go b/internal/service/apigateway/documentation_version_test.go index 2e553fe1cb6..706d70e6f47 100644 --- a/internal/service/apigateway/documentation_version_test.go +++ b/internal/service/apigateway/documentation_version_test.go @@ -31,7 +31,7 @@ func TestAccAPIGatewayDocumentationVersion_basic(t *testing.T) { CheckDestroy: testAccCheckDocumentationVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentationVersionBasicConfig(version, apiName), + Config: testAccDocumentationVersionConfig_basic(version, apiName), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationVersionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "version", version), @@ -66,7 +66,7 @@ func TestAccAPIGatewayDocumentationVersion_allFields(t *testing.T) { CheckDestroy: testAccCheckDocumentationVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentationVersionAllFieldsConfig(version, apiName, stageName, description), + Config: testAccDocumentationVersionConfig_allFields(version, apiName, stageName, description), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationVersionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "version", version), @@ -80,7 +80,7 @@ func TestAccAPIGatewayDocumentationVersion_allFields(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentationVersionAllFieldsConfig(version, apiName, stageName, uDescription), + Config: testAccDocumentationVersionConfig_allFields(version, apiName, stageName, uDescription), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationVersionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "version", version), @@ -108,7 +108,7 @@ func TestAccAPIGatewayDocumentationVersion_disappears(t *testing.T) { CheckDestroy: testAccCheckDocumentationVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentationVersionBasicConfig(version, apiName), + Config: testAccDocumentationVersionConfig_basic(version, apiName), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentationVersionExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceDocumentationVersion(), resourceName), @@ -182,7 +182,7 @@ func testAccCheckDocumentationVersionDestroy(s *terraform.State) error { return nil } -func testAccDocumentationVersionBasicConfig(version, apiName string) string { +func testAccDocumentationVersionConfig_basic(version, apiName string) string { return fmt.Sprintf(` resource "aws_api_gateway_documentation_version" "test" { version = "%s" @@ -205,7 +205,7 @@ resource "aws_api_gateway_rest_api" "test" { `, version, apiName) } -func testAccDocumentationVersionAllFieldsConfig(version, apiName, stageName, description string) string { +func testAccDocumentationVersionConfig_allFields(version, apiName, stageName, description string) string { return fmt.Sprintf(` resource "aws_api_gateway_documentation_version" "test" { version = "%s" diff --git a/internal/service/apigateway/domain_name.go b/internal/service/apigateway/domain_name.go index 4018a41b569..48e102e81ca 100644 --- a/internal/service/apigateway/domain_name.go +++ b/internal/service/apigateway/domain_name.go @@ -213,7 +213,7 @@ func resourceDomainNameCreate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("endpoint_configuration"); ok { - params.EndpointConfiguration = expandApiGatewayEndpointConfiguration(v.([]interface{})) + params.EndpointConfiguration = expandEndpointConfiguration(v.([]interface{})) } if v, ok := d.GetOk("regional_certificate_arn"); ok { @@ -294,7 +294,7 @@ func resourceDomainNameRead(d *schema.ResourceData, meta interface{}) error { d.Set("security_policy", domainName.SecurityPolicy) d.Set("ownership_verification_certificate_arn", domainName.OwnershipVerificationCertificateArn) - if err := d.Set("endpoint_configuration", flattenApiGatewayEndpointConfiguration(domainName.EndpointConfiguration)); err != nil { + if err := d.Set("endpoint_configuration", flattenEndpointConfiguration(domainName.EndpointConfiguration)); err != nil { return fmt.Errorf("error setting endpoint_configuration: %s", err) } diff --git a/internal/service/apigateway/domain_name_data_source.go b/internal/service/apigateway/domain_name_data_source.go index 75ab730b5dd..d422248b6c2 100644 --- a/internal/service/apigateway/domain_name_data_source.go +++ b/internal/service/apigateway/domain_name_data_source.go @@ -122,7 +122,7 @@ func dataSourceDomainNameRead(d *schema.ResourceData, meta interface{}) error { d.Set("cloudfront_zone_id", cloudFrontRoute53ZoneID) d.Set("domain_name", domainName.DomainName) - if err := d.Set("endpoint_configuration", flattenApiGatewayEndpointConfiguration(domainName.EndpointConfiguration)); err != nil { + if err := d.Set("endpoint_configuration", flattenEndpointConfiguration(domainName.EndpointConfiguration)); err != nil { return fmt.Errorf("error setting endpoint_configuration: %w", err) } diff --git a/internal/service/apigateway/domain_name_data_source_test.go b/internal/service/apigateway/domain_name_data_source_test.go index da885abda97..2fc5c0661c4 100644 --- a/internal/service/apigateway/domain_name_data_source_test.go +++ b/internal/service/apigateway/domain_name_data_source_test.go @@ -24,7 +24,7 @@ func TestAccAPIGatewayDomainNameDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameDataSourceConfig_RegionalCertificateARN(rName, key, certificate), + Config: testAccDomainNameDataSourceConfig_regionalCertificateARN(rName, key, certificate), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", dataSourceName, "certificate_arn"), @@ -46,7 +46,7 @@ func TestAccAPIGatewayDomainNameDataSource_basic(t *testing.T) { }) } -func testAccDomainNameDataSourceConfig_RegionalCertificateARN(domainName, key, certificate string) string { +func testAccDomainNameDataSourceConfig_regionalCertificateARN(domainName, key, certificate string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[2]s" diff --git a/internal/service/apigateway/domain_name_test.go b/internal/service/apigateway/domain_name_test.go index 3f91d294d1f..e46b3b85940 100644 --- a/internal/service/apigateway/domain_name_test.go +++ b/internal/service/apigateway/domain_name_test.go @@ -32,7 +32,7 @@ func TestAccAPIGatewayDomainName_certificateARN(t *testing.T) { CheckDestroy: testAccCheckEdgeDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameConfig_CertificateARN(rootDomain, domain), + Config: testAccDomainNameConfig_certificateARN(rootDomain, domain), Check: resource.ComposeTestCheckFunc( testAccCheckEdgeDomainNameExists(resourceName, &domainName), testAccCheckResourceAttrRegionalARNEdgeDomainName(resourceName, "arn", "apigateway", domain), @@ -94,7 +94,7 @@ func TestAccAPIGatewayDomainName_certificateName(t *testing.T) { CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameConfig_CertificateName(domainName, certificatePrivateKey, certificateBody, certificateChain), + Config: testAccDomainNameConfig_certificate(domainName, certificatePrivateKey, certificateBody, certificateChain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/domainnames/+.`)), @@ -130,7 +130,7 @@ func TestAccAPIGatewayDomainName_regionalCertificateARN(t *testing.T) { CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameConfig_RegionalCertificateARN(rName, key, certificate), + Config: testAccDomainNameConfig_regionalCertificateARN(rName, key, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &domainName), testAccCheckResourceAttrRegionalARNRegionalDomainName(resourceName, "arn", "apigateway", rName), @@ -176,7 +176,7 @@ func TestAccAPIGatewayDomainName_regionalCertificateName(t *testing.T) { CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameConfig_RegionalCertificateName(rName, key, certificate, caCertificate), + Config: testAccDomainNameConfig_regionalCertificate(rName, key, certificate, caCertificate), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &domainName), testAccCheckResourceAttrRegionalARNRegionalDomainName(resourceName, "arn", "apigateway", rName), @@ -209,7 +209,7 @@ func TestAccAPIGatewayDomainName_securityPolicy(t *testing.T) { CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameConfig_SecurityPolicy(rName, key, certificate, apigateway.SecurityPolicyTls12), + Config: testAccDomainNameConfig_securityPolicy(rName, key, certificate, apigateway.SecurityPolicyTls12), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &domainName), resource.TestCheckResourceAttr(resourceName, "security_policy", apigateway.SecurityPolicyTls12), @@ -239,7 +239,7 @@ func TestAccAPIGatewayDomainName_tags(t *testing.T) { CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameTags1Config(rName, key, certificate, "key1", "value1"), + Config: testAccDomainNameConfig_tags1(rName, key, certificate, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &domainName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -247,7 +247,7 @@ func TestAccAPIGatewayDomainName_tags(t *testing.T) { ), }, { - Config: testAccDomainNameTags2Config(rName, key, certificate, "key1", "value1updated", "key2", "value2"), + Config: testAccDomainNameConfig_tags2(rName, key, certificate, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &domainName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -256,7 +256,7 @@ func TestAccAPIGatewayDomainName_tags(t *testing.T) { ), }, { - Config: testAccDomainNameTags1Config(rName, key, certificate, "key2", "value2"), + Config: testAccDomainNameConfig_tags1(rName, key, certificate, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &domainName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -287,7 +287,7 @@ func TestAccAPIGatewayDomainName_disappears(t *testing.T) { CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameConfig_RegionalCertificateARN(rName, key, certificate), + Config: testAccDomainNameConfig_regionalCertificateARN(rName, key, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &domainName), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceDomainName(), resourceName), @@ -315,7 +315,7 @@ func TestAccAPIGatewayDomainName_MutualTLSAuthentication_basic(t *testing.T) { CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameConfig_MutualTLSAuthentication(rName, rootDomain, domain), + Config: testAccDomainNameConfig_mutualTLSAuthentication(rName, rootDomain, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &v), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/domainnames/+.`)), @@ -332,7 +332,7 @@ func TestAccAPIGatewayDomainName_MutualTLSAuthentication_basic(t *testing.T) { }, // Test disabling mutual TLS authentication. { - Config: testAccDomainNameConfig_MutualTLSAuthenticationMissing(rootDomain, domain), + Config: testAccDomainNameConfig_mutualTLSAuthenticationMissing(rootDomain, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "domain_name", acmCertificateResourceName, "domain_name"), @@ -362,7 +362,7 @@ func TestAccAPIGatewayDomainName_MutualTLSAuthentication_ownership(t *testing.T) CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameConfig_MutualTlsOwnership(rName, rootDomain, domain, certificate, key), + Config: testAccDomainNameConfig_mutualTLSOwnership(rName, rootDomain, domain, certificate, key), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &v), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/domainnames/+.`)), @@ -546,7 +546,7 @@ resource "aws_acm_certificate_validation" "test" { `, rootDomain, domain) } -func testAccDomainNameConfig_CertificateARN(rootDomain string, domain string) string { +func testAccDomainNameConfig_certificateARN(rootDomain string, domain string) string { return acctest.ConfigCompose( testAccEdgeDomainNameRegionProviderConfig(), testAccDomainNamePublicCertConfig(rootDomain, domain), @@ -562,7 +562,7 @@ resource "aws_api_gateway_domain_name" "test" { `) } -func testAccDomainNameConfig_CertificateName(domainName, key, certificate, chainCertificate string) string { +func testAccDomainNameConfig_certificate(domainName, key, certificate, chainCertificate string) string { return fmt.Sprintf(` resource "aws_api_gateway_domain_name" "test" { domain_name = "%[1]s" @@ -574,7 +574,7 @@ resource "aws_api_gateway_domain_name" "test" { `, domainName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(chainCertificate), acctest.TLSPEMEscapeNewlines(key)) } -func testAccDomainNameConfig_RegionalCertificateARN(domainName, key, certificate string) string { +func testAccDomainNameConfig_regionalCertificateARN(domainName, key, certificate string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[2]s" @@ -592,7 +592,7 @@ resource "aws_api_gateway_domain_name" "test" { `, domainName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key)) } -func testAccDomainNameConfig_RegionalCertificateName(domainName, key, certificate, chainCertificate string) string { +func testAccDomainNameConfig_regionalCertificate(domainName, key, certificate, chainCertificate string) string { return fmt.Sprintf(` resource "aws_api_gateway_domain_name" "test" { certificate_body = "%[2]s" @@ -608,7 +608,7 @@ resource "aws_api_gateway_domain_name" "test" { `, domainName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(chainCertificate), acctest.TLSPEMEscapeNewlines(key)) } -func testAccDomainNameConfig_SecurityPolicy(domainName, key, certificate, securityPolicy string) string { +func testAccDomainNameConfig_securityPolicy(domainName, key, certificate, securityPolicy string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[2]s" @@ -627,7 +627,7 @@ resource "aws_api_gateway_domain_name" "test" { `, domainName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key), securityPolicy) } -func testAccDomainNameTags1Config(domainName, key, certificate, tagKey1, tagValue1 string) string { +func testAccDomainNameConfig_tags1(domainName, key, certificate, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[2]s" @@ -649,7 +649,7 @@ resource "aws_api_gateway_domain_name" "test" { `, domainName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key), tagKey1, tagValue1) } -func testAccDomainNameTags2Config(domainName, key, certificate, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDomainNameConfig_tags2(domainName, key, certificate, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[2]s" @@ -672,7 +672,7 @@ resource "aws_api_gateway_domain_name" "test" { `, domainName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key), tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccDomainNameConfig_MutualTLSAuthentication(rName, rootDomain, domain string) string { +func testAccDomainNameConfig_mutualTLSAuthentication(rName, rootDomain, domain string) string { return acctest.ConfigCompose( testAccDomainNamePublicCertConfig(rootDomain, domain), fmt.Sprintf(` @@ -712,7 +712,7 @@ resource "aws_api_gateway_domain_name" "test" { `, rName)) } -func testAccDomainNameConfig_MutualTLSAuthenticationMissing(rootDomain, domain string) string { +func testAccDomainNameConfig_mutualTLSAuthenticationMissing(rootDomain, domain string) string { return acctest.ConfigCompose( testAccDomainNamePublicCertConfig(rootDomain, domain), ` @@ -728,7 +728,7 @@ resource "aws_api_gateway_domain_name" "test" { `) } -func testAccDomainNameConfig_MutualTlsOwnership(rName, rootDomain, domain, certificate, key string) string { +func testAccDomainNameConfig_mutualTLSOwnership(rName, rootDomain, domain, certificate, key string) string { return acctest.ConfigCompose( testAccDomainNamePublicCertConfig(rootDomain, domain), fmt.Sprintf(` diff --git a/internal/service/apigateway/export_data_source_test.go b/internal/service/apigateway/export_data_source_test.go index 183f99f1b2e..5d75747c8e5 100644 --- a/internal/service/apigateway/export_data_source_test.go +++ b/internal/service/apigateway/export_data_source_test.go @@ -19,7 +19,7 @@ func TestAccAPIGatewayExportDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccExportDataSourceConfig(rName), + Config: testAccExportDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair("aws_api_gateway_stage.test", "rest_api_id", dataSourceName, "rest_api_id"), resource.TestCheckResourceAttrPair("aws_api_gateway_stage.test", "stage_name", dataSourceName, "stage_name"), @@ -32,7 +32,7 @@ func TestAccAPIGatewayExportDataSource_basic(t *testing.T) { }) } -func testAccExportDataSourceConfig(rName string) string { +func testAccExportDataSourceConfig_basic(rName string) string { return testAccStageConfig_base(rName) + ` resource "aws_api_gateway_stage" "test" { rest_api_id = aws_api_gateway_rest_api.test.id diff --git a/internal/service/apigateway/gateway_response_test.go b/internal/service/apigateway/gateway_response_test.go index b131172653a..094e442fa1a 100644 --- a/internal/service/apigateway/gateway_response_test.go +++ b/internal/service/apigateway/gateway_response_test.go @@ -28,7 +28,7 @@ func TestAccAPIGatewayGatewayResponse_basic(t *testing.T) { CheckDestroy: testAccCheckGatewayResponseDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayResponseConfig(rName), + Config: testAccGatewayResponseConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayResponseExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "status_code", "401"), @@ -39,7 +39,7 @@ func TestAccAPIGatewayGatewayResponse_basic(t *testing.T) { }, { - Config: testAccGatewayResponseUpdateConfig(rName), + Config: testAccGatewayResponseConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayResponseExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "status_code", "477"), @@ -71,7 +71,7 @@ func TestAccAPIGatewayGatewayResponse_disappears(t *testing.T) { CheckDestroy: testAccCheckGatewayResponseDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayResponseConfig(rName), + Config: testAccGatewayResponseConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayResponseExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceGatewayResponse(), resourceName), @@ -153,7 +153,7 @@ func testAccGatewayResponseImportStateIdFunc(resourceName string) resource.Impor } } -func testAccGatewayResponseConfig(rName string) string { +func testAccGatewayResponseConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -175,7 +175,7 @@ resource "aws_api_gateway_gateway_response" "test" { `, rName) } -func testAccGatewayResponseUpdateConfig(rName string) string { +func testAccGatewayResponseConfig_update(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" diff --git a/internal/service/apigateway/integration.go b/internal/service/apigateway/integration.go index 4a828e22142..8c3b339f7c4 100644 --- a/internal/service/apigateway/integration.go +++ b/internal/service/apigateway/integration.go @@ -231,7 +231,7 @@ func resourceIntegrationCreate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("tls_config"); ok && len(v.([]interface{})) > 0 { - input.TlsConfig = expandApiGatewayTlsConfig(v.([]interface{})) + input.TlsConfig = expandTLSConfig(v.([]interface{})) } if v, ok := d.GetOk("uri"); ok { @@ -299,7 +299,7 @@ func resourceIntegrationRead(d *schema.ResourceData, meta interface{}) error { d.Set("type", integration.Type) d.Set("uri", integration.Uri) - if err := d.Set("tls_config", flattenApiGatewayTlsConfig(integration.TlsConfig)); err != nil { + if err := d.Set("tls_config", flattenTLSConfig(integration.TlsConfig)); err != nil { return fmt.Errorf("error setting tls_config: %s", err) } @@ -516,7 +516,7 @@ func resourceIntegrationDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func expandApiGatewayTlsConfig(vConfig []interface{}) *apigateway.TlsConfig { +func expandTLSConfig(vConfig []interface{}) *apigateway.TlsConfig { config := &apigateway.TlsConfig{} if len(vConfig) == 0 || vConfig[0] == nil { @@ -530,7 +530,7 @@ func expandApiGatewayTlsConfig(vConfig []interface{}) *apigateway.TlsConfig { return config } -func flattenApiGatewayTlsConfig(config *apigateway.TlsConfig) []interface{} { +func flattenTLSConfig(config *apigateway.TlsConfig) []interface{} { if config == nil { return nil } diff --git a/internal/service/apigateway/integration_response_test.go b/internal/service/apigateway/integration_response_test.go index df01f670795..f616e2d8ba0 100644 --- a/internal/service/apigateway/integration_response_test.go +++ b/internal/service/apigateway/integration_response_test.go @@ -27,7 +27,7 @@ func TestAccAPIGatewayIntegrationResponse_basic(t *testing.T) { CheckDestroy: testAccCheckIntegrationResponseDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationResponseConfig(rName), + Config: testAccIntegrationResponseConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationResponseExists(resourceName, &conf), testAccCheckIntegrationResponseAttributes(&conf), @@ -41,7 +41,7 @@ func TestAccAPIGatewayIntegrationResponse_basic(t *testing.T) { }, { - Config: testAccIntegrationResponseUpdateConfig(rName), + Config: testAccIntegrationResponseConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationResponseExists(resourceName, &conf), testAccCheckIntegrationResponseAttributesUpdate(&conf), @@ -75,7 +75,7 @@ func TestAccAPIGatewayIntegrationResponse_disappears(t *testing.T) { CheckDestroy: testAccCheckIntegrationResponseDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationResponseConfig(rName), + Config: testAccIntegrationResponseConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationResponseExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceIntegrationResponse(), resourceName), @@ -204,7 +204,7 @@ func testAccIntegrationResponseImportStateIdFunc(resourceName string) resource.I } } -func testAccIntegrationResponseConfig(rName string) string { +func testAccIntegrationResponseConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -274,7 +274,7 @@ resource "aws_api_gateway_integration_response" "test" { `, rName) } -func testAccIntegrationResponseUpdateConfig(rName string) string { +func testAccIntegrationResponseConfig_update(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" diff --git a/internal/service/apigateway/integration_test.go b/internal/service/apigateway/integration_test.go index e69cb136b18..f2f806889bc 100644 --- a/internal/service/apigateway/integration_test.go +++ b/internal/service/apigateway/integration_test.go @@ -28,7 +28,7 @@ func TestAccAPIGatewayIntegration_basic(t *testing.T) { CheckDestroy: testAccCheckIntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationConfig(rName), + Config: testAccIntegrationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -49,7 +49,7 @@ func TestAccAPIGatewayIntegration_basic(t *testing.T) { }, { - Config: testAccIntegrationUpdateConfig(rName), + Config: testAccIntegrationConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -69,7 +69,7 @@ func TestAccAPIGatewayIntegration_basic(t *testing.T) { }, { - Config: testAccIntegrationUpdateURIConfig(rName), + Config: testAccIntegrationConfig_updateURI(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -89,7 +89,7 @@ func TestAccAPIGatewayIntegration_basic(t *testing.T) { }, { - Config: testAccIntegrationUpdateNoTemplatesConfig(rName), + Config: testAccIntegrationConfig_updateNoTemplates(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -105,7 +105,7 @@ func TestAccAPIGatewayIntegration_basic(t *testing.T) { }, { - Config: testAccIntegrationConfig(rName), + Config: testAccIntegrationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -144,7 +144,7 @@ func TestAccAPIGatewayIntegration_contentHandling(t *testing.T) { CheckDestroy: testAccCheckIntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationConfig(rName), + Config: testAccIntegrationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -163,7 +163,7 @@ func TestAccAPIGatewayIntegration_contentHandling(t *testing.T) { }, { - Config: testAccIntegrationUpdateContentHandlingConfig(rName), + Config: testAccIntegrationConfig_updateContentHandling(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -181,7 +181,7 @@ func TestAccAPIGatewayIntegration_contentHandling(t *testing.T) { ), }, { - Config: testAccIntegrationRemoveContentHandlingConfig(rName), + Config: testAccIntegrationConfig_removeContentHandling(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -220,7 +220,7 @@ func TestAccAPIGatewayIntegration_CacheKey_parameters(t *testing.T) { CheckDestroy: testAccCheckIntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationCacheKeyParametersConfig(rName), + Config: testAccIntegrationConfig_cacheKeyParameters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -263,7 +263,7 @@ func TestAccAPIGatewayIntegration_integrationType(t *testing.T) { CheckDestroy: testAccCheckIntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationConfig_IntegrationTypeInternet(rName), + Config: testAccIntegrationConfig_typeInternet(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "connection_type", "INTERNET"), @@ -271,7 +271,7 @@ func TestAccAPIGatewayIntegration_integrationType(t *testing.T) { ), }, { - Config: testAccIntegrationConfig_IntegrationTypeVPCLink(rName), + Config: testAccIntegrationConfig_typeVPCLink(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "connection_type", "VPC_LINK"), @@ -279,7 +279,7 @@ func TestAccAPIGatewayIntegration_integrationType(t *testing.T) { ), }, { - Config: testAccIntegrationConfig_IntegrationTypeInternet(rName), + Config: testAccIntegrationConfig_typeInternet(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "connection_type", "INTERNET"), @@ -308,7 +308,7 @@ func TestAccAPIGatewayIntegration_TLS_insecureSkipVerification(t *testing.T) { CheckDestroy: testAccCheckIntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationConfig_TLSConfig_InsecureSkipVerification(rName, true), + Config: testAccIntegrationConfig_tlsInsecureSkipVerification(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tls_config.#", "1"), @@ -322,7 +322,7 @@ func TestAccAPIGatewayIntegration_TLS_insecureSkipVerification(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccIntegrationConfig_TLSConfig_InsecureSkipVerification(rName, false), + Config: testAccIntegrationConfig_tlsInsecureSkipVerification(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tls_config.#", "1"), @@ -345,7 +345,7 @@ func TestAccAPIGatewayIntegration_disappears(t *testing.T) { CheckDestroy: testAccCheckIntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationConfig(rName), + Config: testAccIntegrationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceIntegration(), resourceName), @@ -429,7 +429,7 @@ func testAccIntegrationImportStateIdFunc(resourceName string) resource.ImportSta } } -func testAccIntegrationConfig(rName string) string { +func testAccIntegrationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -476,7 +476,7 @@ resource "aws_api_gateway_integration" "test" { `, rName) } -func testAccIntegrationUpdateConfig(rName string) string { +func testAccIntegrationConfig_update(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -524,7 +524,7 @@ resource "aws_api_gateway_integration" "test" { `, rName) } -func testAccIntegrationUpdateURIConfig(rName string) string { +func testAccIntegrationConfig_updateURI(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -572,7 +572,7 @@ resource "aws_api_gateway_integration" "test" { `, rName) } -func testAccIntegrationUpdateContentHandlingConfig(rName string) string { +func testAccIntegrationConfig_updateContentHandling(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -620,7 +620,7 @@ resource "aws_api_gateway_integration" "test" { `, rName) } -func testAccIntegrationRemoveContentHandlingConfig(rName string) string { +func testAccIntegrationConfig_removeContentHandling(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -667,7 +667,7 @@ resource "aws_api_gateway_integration" "test" { `, rName) } -func testAccIntegrationUpdateNoTemplatesConfig(rName string) string { +func testAccIntegrationConfig_updateNoTemplates(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -705,7 +705,7 @@ resource "aws_api_gateway_integration" "test" { `, rName) } -func testAccIntegrationCacheKeyParametersConfig(rName string) string { +func testAccIntegrationConfig_cacheKeyParameters(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -825,7 +825,7 @@ resource "aws_api_gateway_vpc_link" "test" { `, rName) } -func testAccIntegrationConfig_IntegrationTypeVPCLink(rName string) string { +func testAccIntegrationConfig_typeVPCLink(rName string) string { return testAccIntegrationConfig_IntegrationTypeBase(rName) + ` resource "aws_api_gateway_integration" "test" { rest_api_id = aws_api_gateway_rest_api.test.id @@ -844,7 +844,7 @@ resource "aws_api_gateway_integration" "test" { ` } -func testAccIntegrationConfig_IntegrationTypeInternet(rName string) string { +func testAccIntegrationConfig_typeInternet(rName string) string { return testAccIntegrationConfig_IntegrationTypeBase(rName) + ` resource "aws_api_gateway_integration" "test" { rest_api_id = aws_api_gateway_rest_api.test.id @@ -860,7 +860,7 @@ resource "aws_api_gateway_integration" "test" { ` } -func testAccIntegrationConfig_TLSConfig_InsecureSkipVerification(rName string, insecureSkipVerification bool) string { +func testAccIntegrationConfig_tlsInsecureSkipVerification(rName string, insecureSkipVerification bool) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q diff --git a/internal/service/apigateway/method_response_test.go b/internal/service/apigateway/method_response_test.go index bef1eb39678..6dd8dee8491 100644 --- a/internal/service/apigateway/method_response_test.go +++ b/internal/service/apigateway/method_response_test.go @@ -27,7 +27,7 @@ func TestAccAPIGatewayMethodResponse_basic(t *testing.T) { CheckDestroy: testAccCheckMethodResponseDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodResponseConfig(rName), + Config: testAccMethodResponseConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMethodResponseExists(resourceName, &conf), testAccCheckMethodResponseAttributes(&conf), @@ -39,7 +39,7 @@ func TestAccAPIGatewayMethodResponse_basic(t *testing.T) { }, { - Config: testAccMethodResponseUpdateConfig(rName), + Config: testAccMethodResponseConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMethodResponseExists(resourceName, &conf), testAccCheckMethodResponseAttributesUpdate(&conf), @@ -71,7 +71,7 @@ func TestAccAPIGatewayMethodResponse_disappears(t *testing.T) { CheckDestroy: testAccCheckMethodResponseDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodResponseConfig(rName), + Config: testAccMethodResponseConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMethodResponseExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceMethodResponse(), resourceName), @@ -199,7 +199,7 @@ func testAccMethodResponseImportStateIdFunc(resourceName string) resource.Import } } -func testAccMethodResponseConfig(rName string) string { +func testAccMethodResponseConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -239,7 +239,7 @@ resource "aws_api_gateway_method_response" "error" { `, rName) } -func testAccMethodResponseUpdateConfig(rName string) string { +func testAccMethodResponseConfig_update(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" diff --git a/internal/service/apigateway/method_settings_test.go b/internal/service/apigateway/method_settings_test.go index 2867a08a3af..f6e662e3b54 100644 --- a/internal/service/apigateway/method_settings_test.go +++ b/internal/service/apigateway/method_settings_test.go @@ -27,7 +27,7 @@ func TestAccAPIGatewayMethodSettings_basic(t *testing.T) { CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsLoggingLevelConfig(rName, "INFO"), + Config: testAccMethodSettingsConfig_loggingLevel(rName, "INFO"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -56,7 +56,7 @@ func TestAccAPIGatewayMethodSettings_Settings_cacheDataEncrypted(t *testing.T) { CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsCacheDataEncryptedConfig(rName, true), + Config: testAccMethodSettingsConfig_cacheDataEncrypted(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -64,7 +64,7 @@ func TestAccAPIGatewayMethodSettings_Settings_cacheDataEncrypted(t *testing.T) { ), }, { - Config: testAccMethodSettingsSettingsCacheDataEncryptedConfig(rName, false), + Config: testAccMethodSettingsConfig_cacheDataEncrypted(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -93,7 +93,7 @@ func TestAccAPIGatewayMethodSettings_Settings_cacheTTLInSeconds(t *testing.T) { CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsCacheTTLInSecondsConfig(rName, 0), + Config: testAccMethodSettingsConfig_cacheTTLInSeconds(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -101,7 +101,7 @@ func TestAccAPIGatewayMethodSettings_Settings_cacheTTLInSeconds(t *testing.T) { ), }, { - Config: testAccMethodSettingsSettingsCacheTTLInSecondsConfig(rName, 1), + Config: testAccMethodSettingsConfig_cacheTTLInSeconds(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -109,7 +109,7 @@ func TestAccAPIGatewayMethodSettings_Settings_cacheTTLInSeconds(t *testing.T) { ), }, { - Config: testAccMethodSettingsSettingsCacheTTLInSecondsConfig(rName, 2), + Config: testAccMethodSettingsConfig_cacheTTLInSeconds(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -138,7 +138,7 @@ func TestAccAPIGatewayMethodSettings_Settings_cachingEnabled(t *testing.T) { CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsCachingEnabledConfig(rName, true), + Config: testAccMethodSettingsConfig_cachingEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -146,7 +146,7 @@ func TestAccAPIGatewayMethodSettings_Settings_cachingEnabled(t *testing.T) { ), }, { - Config: testAccMethodSettingsSettingsCachingEnabledConfig(rName, false), + Config: testAccMethodSettingsConfig_cachingEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -175,7 +175,7 @@ func TestAccAPIGatewayMethodSettings_Settings_dataTraceEnabled(t *testing.T) { CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsDataTraceEnabledConfig(rName, true), + Config: testAccMethodSettingsConfig_dataTraceEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -183,7 +183,7 @@ func TestAccAPIGatewayMethodSettings_Settings_dataTraceEnabled(t *testing.T) { ), }, { - Config: testAccMethodSettingsSettingsDataTraceEnabledConfig(rName, false), + Config: testAccMethodSettingsConfig_dataTraceEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -212,7 +212,7 @@ func TestAccAPIGatewayMethodSettings_Settings_loggingLevel(t *testing.T) { CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsLoggingLevelConfig(rName, "INFO"), + Config: testAccMethodSettingsConfig_loggingLevel(rName, "INFO"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), testAccCheckMethodSettings_loggingLevel(&stage1, "test/GET", "INFO"), @@ -221,7 +221,7 @@ func TestAccAPIGatewayMethodSettings_Settings_loggingLevel(t *testing.T) { ), }, { - Config: testAccMethodSettingsSettingsLoggingLevelConfig(rName, "OFF"), + Config: testAccMethodSettingsConfig_loggingLevel(rName, "OFF"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), testAccCheckMethodSettings_loggingLevel(&stage2, "test/GET", "OFF"), @@ -251,7 +251,7 @@ func TestAccAPIGatewayMethodSettings_Settings_metricsEnabled(t *testing.T) { CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsMetricsEnabledConfig(rName, true), + Config: testAccMethodSettingsConfig_metricsEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), testAccCheckMethodSettings_metricsEnabled(&stage1, "test/GET", true), @@ -260,7 +260,7 @@ func TestAccAPIGatewayMethodSettings_Settings_metricsEnabled(t *testing.T) { ), }, { - Config: testAccMethodSettingsSettingsMetricsEnabledConfig(rName, false), + Config: testAccMethodSettingsConfig_metricsEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), testAccCheckMethodSettings_metricsEnabled(&stage2, "test/GET", false), @@ -290,7 +290,7 @@ func TestAccAPIGatewayMethodSettings_Settings_multiple(t *testing.T) { CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsMultipleConfig(rName, "INFO", true), + Config: testAccMethodSettingsConfig_multiple(rName, "INFO", true), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), testAccCheckMethodSettings_metricsEnabled(&stage1, "test/GET", true), @@ -301,7 +301,7 @@ func TestAccAPIGatewayMethodSettings_Settings_multiple(t *testing.T) { ), }, { - Config: testAccMethodSettingsSettingsMultipleConfig(rName, "OFF", false), + Config: testAccMethodSettingsConfig_multiple(rName, "OFF", false), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), testAccCheckMethodSettings_metricsEnabled(&stage2, "test/GET", false), @@ -333,7 +333,7 @@ func TestAccAPIGatewayMethodSettings_Settings_requireAuthorizationForCacheContro CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsRequireAuthorizationForCacheControlConfig(rName, true), + Config: testAccMethodSettingsConfig_requireAuthorizationForCacheControl(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -341,7 +341,7 @@ func TestAccAPIGatewayMethodSettings_Settings_requireAuthorizationForCacheContro ), }, { - Config: testAccMethodSettingsSettingsRequireAuthorizationForCacheControlConfig(rName, false), + Config: testAccMethodSettingsConfig_requireAuthorizationForCacheControl(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -370,7 +370,7 @@ func TestAccAPIGatewayMethodSettings_Settings_throttlingBurstLimit(t *testing.T) CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsThrottlingBurstLimitConfig(rName, 1), + Config: testAccMethodSettingsConfig_throttlingBurstLimit(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -378,7 +378,7 @@ func TestAccAPIGatewayMethodSettings_Settings_throttlingBurstLimit(t *testing.T) ), }, { - Config: testAccMethodSettingsSettingsThrottlingBurstLimitConfig(rName, 2), + Config: testAccMethodSettingsConfig_throttlingBurstLimit(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -408,7 +408,7 @@ func TestAccAPIGatewayMethodSettings_Settings_throttlingBurstLimitDisabledByDefa CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsLoggingLevelConfig(rName, "INFO"), + Config: testAccMethodSettingsConfig_loggingLevel(rName, "INFO"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -422,7 +422,7 @@ func TestAccAPIGatewayMethodSettings_Settings_throttlingBurstLimitDisabledByDefa ImportStateVerify: true, }, { - Config: testAccMethodSettingsSettingsThrottlingBurstLimitConfig(rName, 1), + Config: testAccMethodSettingsConfig_throttlingBurstLimit(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -445,7 +445,7 @@ func TestAccAPIGatewayMethodSettings_Settings_throttlingRateLimit(t *testing.T) CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsThrottlingRateLimitConfig(rName, 1.1), + Config: testAccMethodSettingsConfig_throttlingRateLimit(rName, 1.1), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -453,7 +453,7 @@ func TestAccAPIGatewayMethodSettings_Settings_throttlingRateLimit(t *testing.T) ), }, { - Config: testAccMethodSettingsSettingsThrottlingRateLimitConfig(rName, 2.2), + Config: testAccMethodSettingsConfig_throttlingRateLimit(rName, 2.2), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -483,7 +483,7 @@ func TestAccAPIGatewayMethodSettings_Settings_throttlingRateLimitDisabledByDefau CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsLoggingLevelConfig(rName, "INFO"), + Config: testAccMethodSettingsConfig_loggingLevel(rName, "INFO"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -497,7 +497,7 @@ func TestAccAPIGatewayMethodSettings_Settings_throttlingRateLimitDisabledByDefau ImportStateVerify: true, }, { - Config: testAccMethodSettingsSettingsThrottlingRateLimitConfig(rName, 1.1), + Config: testAccMethodSettingsConfig_throttlingRateLimit(rName, 1.1), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -520,7 +520,7 @@ func TestAccAPIGatewayMethodSettings_Settings_unauthorizedCacheControlHeaderStra CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsUnauthorizedCacheControlHeaderStrategyConfig(rName, "SUCCEED_WITH_RESPONSE_HEADER"), + Config: testAccMethodSettingsConfig_unauthorizedCacheControlHeaderStrategy(rName, "SUCCEED_WITH_RESPONSE_HEADER"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage1), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -528,7 +528,7 @@ func TestAccAPIGatewayMethodSettings_Settings_unauthorizedCacheControlHeaderStra ), }, { - Config: testAccMethodSettingsSettingsUnauthorizedCacheControlHeaderStrategyConfig(rName, "SUCCEED_WITHOUT_RESPONSE_HEADER"), + Config: testAccMethodSettingsConfig_unauthorizedCacheControlHeaderStrategy(rName, "SUCCEED_WITHOUT_RESPONSE_HEADER"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage2), resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), @@ -590,7 +590,7 @@ func TestAccAPIGatewayMethodSettings_disappears(t *testing.T) { CheckDestroy: testAccCheckMethodSettingsDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodSettingsSettingsLoggingLevelConfig(rName, "INFO"), + Config: testAccMethodSettingsConfig_loggingLevel(rName, "INFO"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceMethodSettings(), resourceName), @@ -690,7 +690,7 @@ resource "aws_api_gateway_deployment" "test" { `, rName) } -func testAccMethodSettingsSettingsCacheDataEncryptedConfig(rName string, cacheDataEncrypted bool) string { +func testAccMethodSettingsConfig_cacheDataEncrypted(rName string, cacheDataEncrypted bool) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" @@ -704,7 +704,7 @@ resource "aws_api_gateway_method_settings" "test" { `, cacheDataEncrypted) } -func testAccMethodSettingsSettingsCacheTTLInSecondsConfig(rName string, cacheTtlInSeconds int) string { +func testAccMethodSettingsConfig_cacheTTLInSeconds(rName string, cacheTtlInSeconds int) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" @@ -718,7 +718,7 @@ resource "aws_api_gateway_method_settings" "test" { `, cacheTtlInSeconds) } -func testAccMethodSettingsSettingsCachingEnabledConfig(rName string, cachingEnabled bool) string { +func testAccMethodSettingsConfig_cachingEnabled(rName string, cachingEnabled bool) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" @@ -732,7 +732,7 @@ resource "aws_api_gateway_method_settings" "test" { `, cachingEnabled) } -func testAccMethodSettingsSettingsDataTraceEnabledConfig(rName string, dataTraceEnabled bool) string { +func testAccMethodSettingsConfig_dataTraceEnabled(rName string, dataTraceEnabled bool) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" @@ -746,7 +746,7 @@ resource "aws_api_gateway_method_settings" "test" { `, dataTraceEnabled) } -func testAccMethodSettingsSettingsLoggingLevelConfig(rName, loggingLevel string) string { +func testAccMethodSettingsConfig_loggingLevel(rName, loggingLevel string) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" @@ -760,7 +760,7 @@ resource "aws_api_gateway_method_settings" "test" { `, loggingLevel) } -func testAccMethodSettingsSettingsMetricsEnabledConfig(rName string, metricsEnabled bool) string { +func testAccMethodSettingsConfig_metricsEnabled(rName string, metricsEnabled bool) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" @@ -774,7 +774,7 @@ resource "aws_api_gateway_method_settings" "test" { `, metricsEnabled) } -func testAccMethodSettingsSettingsMultipleConfig(rName, loggingLevel string, metricsEnabled bool) string { +func testAccMethodSettingsConfig_multiple(rName, loggingLevel string, metricsEnabled bool) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { rest_api_id = aws_api_gateway_rest_api.test.id @@ -789,7 +789,7 @@ resource "aws_api_gateway_method_settings" "test" { `, loggingLevel, metricsEnabled) } -func testAccMethodSettingsSettingsRequireAuthorizationForCacheControlConfig(rName string, requireAuthorizationForCacheControl bool) string { +func testAccMethodSettingsConfig_requireAuthorizationForCacheControl(rName string, requireAuthorizationForCacheControl bool) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" @@ -803,7 +803,7 @@ resource "aws_api_gateway_method_settings" "test" { `, requireAuthorizationForCacheControl) } -func testAccMethodSettingsSettingsThrottlingBurstLimitConfig(rName string, throttlingBurstLimit int) string { +func testAccMethodSettingsConfig_throttlingBurstLimit(rName string, throttlingBurstLimit int) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" @@ -817,7 +817,7 @@ resource "aws_api_gateway_method_settings" "test" { `, throttlingBurstLimit) } -func testAccMethodSettingsSettingsThrottlingRateLimitConfig(rName string, throttlingRateLimit float32) string { +func testAccMethodSettingsConfig_throttlingRateLimit(rName string, throttlingRateLimit float32) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" @@ -831,7 +831,7 @@ resource "aws_api_gateway_method_settings" "test" { `, throttlingRateLimit) } -func testAccMethodSettingsSettingsUnauthorizedCacheControlHeaderStrategyConfig(rName, unauthorizedCacheControlHeaderStrategy string) string { +func testAccMethodSettingsConfig_unauthorizedCacheControlHeaderStrategy(rName, unauthorizedCacheControlHeaderStrategy string) string { return testAccMethodSettingsBaseConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_method_settings" "test" { method_path = "${aws_api_gateway_resource.test.path_part}/${aws_api_gateway_method.test.http_method}" diff --git a/internal/service/apigateway/method_test.go b/internal/service/apigateway/method_test.go index eae615fa694..20cbf624601 100644 --- a/internal/service/apigateway/method_test.go +++ b/internal/service/apigateway/method_test.go @@ -28,7 +28,7 @@ func TestAccAPIGatewayMethod_basic(t *testing.T) { CheckDestroy: testAccCheckMethodDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodConfig(rInt), + Config: testAccMethodConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), testAccCheckMethodAttributes(&conf), @@ -45,7 +45,7 @@ func TestAccAPIGatewayMethod_basic(t *testing.T) { }, { - Config: testAccMethodUpdateConfig(rInt), + Config: testAccMethodConfig_update(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), testAccCheckMethodAttributesUpdate(&conf), @@ -67,7 +67,7 @@ func TestAccAPIGatewayMethod_customAuthorizer(t *testing.T) { CheckDestroy: testAccCheckMethodDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodWithCustomAuthorizerConfig(rInt), + Config: testAccMethodConfig_customAuthorizer(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), testAccCheckMethodAttributes(&conf), @@ -85,7 +85,7 @@ func TestAccAPIGatewayMethod_customAuthorizer(t *testing.T) { }, { - Config: testAccMethodUpdateConfig(rInt), + Config: testAccMethodConfig_update(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), testAccCheckMethodAttributesUpdate(&conf), @@ -109,7 +109,7 @@ func TestAccAPIGatewayMethod_cognitoAuthorizer(t *testing.T) { CheckDestroy: testAccCheckMethodDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodWithCognitoAuthorizerConfig(rInt), + Config: testAccMethodConfig_cognitoAuthorizer(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), testAccCheckMethodAttributes(&conf), @@ -122,7 +122,7 @@ func TestAccAPIGatewayMethod_cognitoAuthorizer(t *testing.T) { }, { - Config: testAccMethodWithCognitoAuthorizerUpdateConfig(rInt), + Config: testAccMethodConfig_cognitoAuthorizerUpdate(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), testAccCheckMethodAttributesUpdate(&conf), @@ -154,7 +154,7 @@ func TestAccAPIGatewayMethod_customRequestValidator(t *testing.T) { CheckDestroy: testAccCheckMethodDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodWithCustomRequestValidatorConfig(rInt), + Config: testAccMethodConfig_customRequestValidator(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), testAccCheckMethodAttributes(&conf), @@ -172,7 +172,7 @@ func TestAccAPIGatewayMethod_customRequestValidator(t *testing.T) { }, { - Config: testAccMethodWithCustomRequestValidatorUpdateConfig(rInt), + Config: testAccMethodConfig_customRequestValidatorUpdate(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), testAccCheckMethodAttributesUpdate(&conf), @@ -195,7 +195,7 @@ func TestAccAPIGatewayMethod_disappears(t *testing.T) { CheckDestroy: testAccCheckMethodDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodConfig(rInt), + Config: testAccMethodConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceMethod(), resourceName), @@ -218,7 +218,7 @@ func TestAccAPIGatewayMethod_operationName(t *testing.T) { CheckDestroy: testAccCheckMethodDestroy, Steps: []resource.TestStep{ { - Config: testAccMethodOperationNameConfig(rInt, "getTest"), + Config: testAccMethodConfig_operationName(rInt, "getTest"), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "operation_name", "getTest"), @@ -231,7 +231,7 @@ func TestAccAPIGatewayMethod_operationName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMethodOperationNameConfig(rInt, "describeTest"), + Config: testAccMethodConfig_operationName(rInt, "describeTest"), Check: resource.ComposeTestCheckFunc( testAccCheckMethodExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "operation_name", "describeTest"), @@ -362,7 +362,7 @@ func testAccMethodImportStateIdFunc(resourceName string) resource.ImportStateIdF } } -func testAccMethodWithCustomAuthorizerConfig(rInt int) string { +func testAccMethodConfig_customAuthorizer(rInt int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "tf-acc-test-custom-auth-%d" @@ -468,7 +468,7 @@ resource "aws_api_gateway_method" "test" { `, rInt, rInt, rInt, rInt, rInt) } -func testAccMethodWithCognitoAuthorizerConfig(rInt int) string { +func testAccMethodConfig_cognitoAuthorizer(rInt int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "tf-acc-test-cognito-auth-%d" @@ -553,7 +553,7 @@ resource "aws_api_gateway_method" "test" { `, rInt, rInt, rInt, rInt) } -func testAccMethodWithCognitoAuthorizerUpdateConfig(rInt int) string { +func testAccMethodConfig_cognitoAuthorizerUpdate(rInt int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "tf-acc-test-cognito-auth-%d" @@ -637,7 +637,7 @@ resource "aws_api_gateway_method" "test" { `, rInt, rInt, rInt, rInt) } -func testAccMethodConfig(rInt int) string { +func testAccMethodConfig_basic(rInt int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "tf-acc-test-apig-method-%d" @@ -667,7 +667,7 @@ resource "aws_api_gateway_method" "test" { `, rInt) } -func testAccMethodUpdateConfig(rInt int) string { +func testAccMethodConfig_update(rInt int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "tf-acc-test-apig-method-%d" @@ -696,7 +696,7 @@ resource "aws_api_gateway_method" "test" { `, rInt) } -func testAccMethodWithCustomRequestValidatorConfig(rInt int) string { +func testAccMethodConfig_customRequestValidator(rInt int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "tf-acc-test-apig-method-custom-req-validator-%d" @@ -734,7 +734,7 @@ resource "aws_api_gateway_method" "test" { `, rInt) } -func testAccMethodWithCustomRequestValidatorUpdateConfig(rInt int) string { +func testAccMethodConfig_customRequestValidatorUpdate(rInt int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "tf-acc-test-apig-method-custom-req-validator-%d" @@ -769,7 +769,7 @@ resource "aws_api_gateway_method" "test" { `, rInt) } -func testAccMethodOperationNameConfig(rInt int, operationName string) string { +func testAccMethodConfig_operationName(rInt int, operationName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "tf-acc-test-apig-method-custom-op-name-%[1]d" diff --git a/internal/service/apigateway/model.go b/internal/service/apigateway/model.go index 6a4ebc8d66a..79093bedf6c 100644 --- a/internal/service/apigateway/model.go +++ b/internal/service/apigateway/model.go @@ -9,7 +9,10 @@ import ( "github.com/aws/aws-sdk-go/service/apigateway" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/verify" ) func ResourceModel() *schema.Resource { @@ -67,6 +70,15 @@ func ResourceModel() *schema.Resource { "schema": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.All( + validation.StringLenBetween(0, 32768), + validation.StringIsJSON, + ), + DiffSuppressFunc: verify.SuppressEquivalentJSONDiffs, + StateFunc: func(v interface{}) string { + json, _ := structure.NormalizeJsonString(v) + return json + }, }, "content_type": { diff --git a/internal/service/apigateway/model_test.go b/internal/service/apigateway/model_test.go index c2d09bb9567..4189747ec1a 100644 --- a/internal/service/apigateway/model_test.go +++ b/internal/service/apigateway/model_test.go @@ -29,7 +29,7 @@ func TestAccAPIGatewayModel_basic(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccModelConfig(rName, modelName), + Config: testAccModelConfig_basic(rName, modelName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName, modelName, &conf), testAccCheckModelAttributes(&conf, modelName), @@ -65,7 +65,7 @@ func TestAccAPIGatewayModel_disappears(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccModelConfig(rName, modelName), + Config: testAccModelConfig_basic(rName, modelName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName, modelName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceModel(), resourceName), @@ -168,7 +168,7 @@ func testAccModelImportStateIdFunc(resourceName string) resource.ImportStateIdFu } } -func testAccModelConfig(rName, modelName string) string { +func testAccModelConfig_basic(rName, modelName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" diff --git a/internal/service/apigateway/request_validator_test.go b/internal/service/apigateway/request_validator_test.go index 56862bc1a68..343a119980f 100644 --- a/internal/service/apigateway/request_validator_test.go +++ b/internal/service/apigateway/request_validator_test.go @@ -27,7 +27,7 @@ func TestAccAPIGatewayRequestValidator_basic(t *testing.T) { CheckDestroy: testAccCheckRequestValidatorDestroy, Steps: []resource.TestStep{ { - Config: testAccRequestValidatorConfig(rName), + Config: testAccRequestValidatorConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRequestValidatorExists(resourceName, &conf), testAccCheckRequestValidatorName(&conf, "tf-acc-test-request-validator"), @@ -39,7 +39,7 @@ func TestAccAPIGatewayRequestValidator_basic(t *testing.T) { ), }, { - Config: testAccRequestValidatorUpdatedConfig(rName), + Config: testAccRequestValidatorConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRequestValidatorExists(resourceName, &conf), testAccCheckRequestValidatorName(&conf, "tf-acc-test-request-validator_modified"), @@ -72,7 +72,7 @@ func TestAccAPIGatewayRequestValidator_disappears(t *testing.T) { CheckDestroy: testAccCheckRequestValidatorDestroy, Steps: []resource.TestStep{ { - Config: testAccRequestValidatorConfig(rName), + Config: testAccRequestValidatorConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRequestValidatorExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceRequestValidator(), resourceName), @@ -198,7 +198,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName) } -func testAccRequestValidatorConfig(rName string) string { +func testAccRequestValidatorConfig_basic(rName string) string { return fmt.Sprintf(testAccRequestValidatorConfig_base(rName) + ` resource "aws_api_gateway_request_validator" "test" { name = "tf-acc-test-request-validator" @@ -207,7 +207,7 @@ resource "aws_api_gateway_request_validator" "test" { `) } -func testAccRequestValidatorUpdatedConfig(rName string) string { +func testAccRequestValidatorConfig_updated(rName string) string { return fmt.Sprintf(testAccRequestValidatorConfig_base(rName) + ` resource "aws_api_gateway_request_validator" "test" { name = "tf-acc-test-request-validator_modified" diff --git a/internal/service/apigateway/resource_data_source_test.go b/internal/service/apigateway/resource_data_source_test.go index 87f480a1563..793b2fcc44f 100644 --- a/internal/service/apigateway/resource_data_source_test.go +++ b/internal/service/apigateway/resource_data_source_test.go @@ -23,7 +23,7 @@ func TestAccAPIGatewayResourceDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccResourceDataSourceConfig(rName), + Config: testAccResourceDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName1, "id", dataSourceName1, "id"), resource.TestCheckResourceAttrPair(resourceName1, "parent_id", dataSourceName1, "parent_id"), @@ -37,7 +37,7 @@ func TestAccAPIGatewayResourceDataSource_basic(t *testing.T) { }) } -func testAccResourceDataSourceConfig(r string) string { +func testAccResourceDataSourceConfig_basic(r string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "example" { name = "%s_example" diff --git a/internal/service/apigateway/resource_test.go b/internal/service/apigateway/resource_test.go index fdc35fbcd24..04d9db1b1a1 100644 --- a/internal/service/apigateway/resource_test.go +++ b/internal/service/apigateway/resource_test.go @@ -27,7 +27,7 @@ func TestAccAPIGatewayResource_basic(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceConfig(rName), + Config: testAccResourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceExists(resourceName, &conf), testAccCheckResourceAttributes(&conf, "/test"), @@ -59,7 +59,7 @@ func TestAccAPIGatewayResource_update(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceConfig(rName), + Config: testAccResourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceExists(resourceName, &conf), testAccCheckResourceAttributes(&conf, "/test"), @@ -103,7 +103,7 @@ func TestAccAPIGatewayResource_disappears(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceConfig(rName), + Config: testAccResourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceResource(), resourceName), @@ -201,7 +201,7 @@ func testAccResourceImportStateIdFunc(resourceName string) resource.ImportStateI } } -func testAccResourceConfig(rName string) string { +func testAccResourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" diff --git a/internal/service/apigateway/rest_api.go b/internal/service/apigateway/rest_api.go index c663d1c021c..6fab18b4a2b 100644 --- a/internal/service/apigateway/rest_api.go +++ b/internal/service/apigateway/rest_api.go @@ -169,7 +169,7 @@ func resourceRestAPICreate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("endpoint_configuration"); ok { - params.EndpointConfiguration = expandApiGatewayEndpointConfiguration(v.([]interface{})) + params.EndpointConfiguration = expandEndpointConfiguration(v.([]interface{})) } if v, ok := d.GetOk("api_key_source"); ok { @@ -280,7 +280,7 @@ func resourceRestAPICreate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("endpoint_configuration"); ok { - endpointConfiguration := expandApiGatewayEndpointConfiguration(v.([]interface{})) + endpointConfiguration := expandEndpointConfiguration(v.([]interface{})) if endpointConfiguration != nil && len(endpointConfiguration.VpcEndpointIds) > 0 { if output.EndpointConfiguration != nil { @@ -427,7 +427,7 @@ func resourceRestAPIRead(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Error setting created_date: %s", err) } - if err := d.Set("endpoint_configuration", flattenApiGatewayEndpointConfiguration(api.EndpointConfiguration)); err != nil { + if err := d.Set("endpoint_configuration", flattenEndpointConfiguration(api.EndpointConfiguration)); err != nil { return fmt.Errorf("error setting endpoint_configuration: %s", err) } @@ -661,7 +661,7 @@ func resourceRestAPIUpdate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("endpoint_configuration"); ok { - endpointConfiguration := expandApiGatewayEndpointConfiguration(v.([]interface{})) + endpointConfiguration := expandEndpointConfiguration(v.([]interface{})) if endpointConfiguration != nil && len(endpointConfiguration.VpcEndpointIds) > 0 { if output.EndpointConfiguration != nil { @@ -757,7 +757,7 @@ func resourceRestAPIDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func expandApiGatewayEndpointConfiguration(l []interface{}) *apigateway.EndpointConfiguration { +func expandEndpointConfiguration(l []interface{}) *apigateway.EndpointConfiguration { if len(l) == 0 { return nil } @@ -775,7 +775,7 @@ func expandApiGatewayEndpointConfiguration(l []interface{}) *apigateway.Endpoint return endpointConfiguration } -func flattenApiGatewayEndpointConfiguration(endpointConfiguration *apigateway.EndpointConfiguration) []interface{} { +func flattenEndpointConfiguration(endpointConfiguration *apigateway.EndpointConfiguration) []interface{} { if endpointConfiguration == nil { return []interface{}{} } diff --git a/internal/service/apigateway/rest_api_data_source.go b/internal/service/apigateway/rest_api_data_source.go index 2808fb09eaf..7c7751ddd47 100644 --- a/internal/service/apigateway/rest_api_data_source.go +++ b/internal/service/apigateway/rest_api_data_source.go @@ -126,7 +126,7 @@ func dataSourceRestAPIRead(d *schema.ResourceData, meta interface{}) error { d.Set("minimum_compression_size", match.MinimumCompressionSize) } - if err := d.Set("endpoint_configuration", flattenApiGatewayEndpointConfiguration(match.EndpointConfiguration)); err != nil { + if err := d.Set("endpoint_configuration", flattenEndpointConfiguration(match.EndpointConfiguration)); err != nil { return fmt.Errorf("error setting endpoint_configuration: %w", err) } diff --git a/internal/service/apigateway/rest_api_data_source_test.go b/internal/service/apigateway/rest_api_data_source_test.go index 2f1c6a3a5f7..bfe68c8728b 100644 --- a/internal/service/apigateway/rest_api_data_source_test.go +++ b/internal/service/apigateway/rest_api_data_source_test.go @@ -20,8 +20,8 @@ func TestAccAPIGatewayRestAPIDataSource_basic(t *testing.T) { Steps: []resource.TestStep{ { Config: acctest.ConfigCompose( - testAccRestAPIConfig_Name(rName), - testAccRestAPINameDataSourceConfig(), + testAccRestAPIConfig_name(rName), + testAccRestAPIDataSourceConfig_name(), ), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), @@ -52,8 +52,8 @@ func TestAccAPIGatewayRestAPIDataSource_Endpoint_vpcEndpointIDs(t *testing.T) { Steps: []resource.TestStep{ { Config: acctest.ConfigCompose( - testAccRestAPIEndpointConfigurationVPCEndpointIds1Config(rName), - testAccRestAPINameDataSourceConfig(), + testAccRestAPIConfig_vpcEndpointIDs1(rName), + testAccRestAPIDataSourceConfig_name(), ), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), @@ -74,7 +74,7 @@ func TestAccAPIGatewayRestAPIDataSource_Endpoint_vpcEndpointIDs(t *testing.T) { }) } -func testAccRestAPINameDataSourceConfig() string { +func testAccRestAPIDataSourceConfig_name() string { return ` data "aws_api_gateway_rest_api" "test" { name = aws_api_gateway_rest_api.test.name diff --git a/internal/service/apigateway/rest_api_policy_test.go b/internal/service/apigateway/rest_api_policy_test.go index 01f76094a5c..b9abac06062 100644 --- a/internal/service/apigateway/rest_api_policy_test.go +++ b/internal/service/apigateway/rest_api_policy_test.go @@ -29,7 +29,7 @@ func TestAccAPIGatewayRestAPIPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckRestAPIPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIPolicyConfig(rName), + Config: testAccRestAPIPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIPolicyExists(resourceName, &v), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(`"Action":"execute-api:Invoke".+`)), @@ -42,7 +42,7 @@ func TestAccAPIGatewayRestAPIPolicy_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"policy"}, }, { - Config: testAccRestAPIPolicyUpdatedConfig(rName), + Config: testAccRestAPIPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIPolicyExists(resourceName, &v), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(`"aws:SourceIp":"123.123.123.123/32".+`))), @@ -63,7 +63,7 @@ func TestAccAPIGatewayRestAPIPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckRestAPIPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIPolicyConfig(rName), + Config: testAccRestAPIPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIPolicyExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceRestAPIPolicy(), resourceName), @@ -86,7 +86,7 @@ func TestAccAPIGatewayRestAPIPolicy_Disappears_restAPI(t *testing.T) { CheckDestroy: testAccCheckRestAPIPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIPolicyConfig(rName), + Config: testAccRestAPIPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIPolicyExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceRestAPI(), "aws_api_gateway_rest_api.test"), @@ -163,7 +163,7 @@ func testAccCheckRestAPIPolicyDestroy(s *terraform.State) error { return nil } -func testAccRestAPIPolicyConfig(rName string) string { +func testAccRestAPIPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -187,7 +187,7 @@ resource "aws_api_gateway_rest_api_policy" "test" { `, rName) } -func testAccRestAPIPolicyUpdatedConfig(rName string) string { +func testAccRestAPIPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q diff --git a/internal/service/apigateway/rest_api_test.go b/internal/service/apigateway/rest_api_test.go index 526e43e1eed..e90a4f75618 100644 --- a/internal/service/apigateway/rest_api_test.go +++ b/internal/service/apigateway/rest_api_test.go @@ -28,7 +28,7 @@ func TestAccAPIGatewayRestAPI_basic(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPINameConfig(rName), + Config: testAccRestAPIConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "api_key_source", "HEADER"), @@ -68,7 +68,7 @@ func TestAccAPIGatewayRestAPI_tags(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPITags1Config(rName, "key1", "value1"), + Config: testAccRestAPIConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/restapis/+.`)), @@ -83,7 +83,7 @@ func TestAccAPIGatewayRestAPI_tags(t *testing.T) { }, { - Config: testAccRestAPITags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccRestAPIConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/restapis/+.`)), @@ -94,7 +94,7 @@ func TestAccAPIGatewayRestAPI_tags(t *testing.T) { }, { - Config: testAccRestAPITags1Config(rName, "key2", "value2"), + Config: testAccRestAPIConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/restapis/+.`)), @@ -118,7 +118,7 @@ func TestAccAPIGatewayRestAPI_disappears(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPINameConfig(rName), + Config: testAccRestAPIConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &restApi), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceRestAPI(), resourceName), @@ -141,7 +141,7 @@ func TestAccAPIGatewayRestAPI_endpoint(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIConfig_EndpointConfiguration(rName, "REGIONAL"), + Config: testAccRestAPIConfig_endpointConfiguration(rName, "REGIONAL"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &restApi), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -156,7 +156,7 @@ func TestAccAPIGatewayRestAPI_endpoint(t *testing.T) { }, // For backwards compatibility, test removing endpoint_configuration, which should do nothing { - Config: testAccRestAPIConfig_Name(rName), + Config: testAccRestAPIConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &restApi), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -193,7 +193,7 @@ func TestAccAPIGatewayRestAPI_endpoint(t *testing.T) { t.Fatal(err) } }, - Config: testAccRestAPIConfig_EndpointConfiguration(rName, "EDGE"), + Config: testAccRestAPIConfig_endpointConfiguration(rName, "EDGE"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &restApi), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -242,7 +242,7 @@ func TestAccAPIGatewayRestAPI_Endpoint_private(t *testing.T) { t.Fatal(err) } }, - Config: testAccRestAPIConfig_EndpointConfiguration(rName, "PRIVATE"), + Config: testAccRestAPIConfig_endpointConfiguration(rName, "PRIVATE"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &restApi), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -270,7 +270,7 @@ func TestAccAPIGatewayRestAPI_apiKeySource(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIAPIKeySourceConfig(rName, "AUTHORIZER"), + Config: testAccRestAPIConfig_keySource(rName, "AUTHORIZER"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "api_key_source", "AUTHORIZER"), ), @@ -281,13 +281,13 @@ func TestAccAPIGatewayRestAPI_apiKeySource(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRestAPIAPIKeySourceConfig(rName, "HEADER"), + Config: testAccRestAPIConfig_keySource(rName, "HEADER"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "api_key_source", "HEADER"), ), }, { - Config: testAccRestAPINameConfig(rName), + Config: testAccRestAPIConfig_name(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "api_key_source", "HEADER"), ), @@ -308,7 +308,7 @@ func TestAccAPIGatewayRestAPI_APIKeySource_overrideBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIAPIKeySourceOverrideBodyConfig(rName, "AUTHORIZER", "HEADER"), + Config: testAccRestAPIConfig_keySourceOverrideBody(rName, "AUTHORIZER", "HEADER"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "api_key_source", "AUTHORIZER"), @@ -322,7 +322,7 @@ func TestAccAPIGatewayRestAPI_APIKeySource_overrideBody(t *testing.T) { }, // Verify updated API key source still overrides { - Config: testAccRestAPIAPIKeySourceOverrideBodyConfig(rName, "HEADER", "HEADER"), + Config: testAccRestAPIConfig_keySourceOverrideBody(rName, "HEADER", "HEADER"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "api_key_source", "HEADER"), @@ -330,7 +330,7 @@ func TestAccAPIGatewayRestAPI_APIKeySource_overrideBody(t *testing.T) { }, // Verify updated body API key source is still overridden { - Config: testAccRestAPIAPIKeySourceOverrideBodyConfig(rName, "HEADER", "AUTHORIZER"), + Config: testAccRestAPIConfig_keySourceOverrideBody(rName, "HEADER", "AUTHORIZER"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "api_key_source", "HEADER"), @@ -352,7 +352,7 @@ func TestAccAPIGatewayRestAPI_APIKeySource_setByBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIAPIKeySourceSetByBodyConfig(rName, "AUTHORIZER"), + Config: testAccRestAPIConfig_keySourceSetByBody(rName, "AUTHORIZER"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "api_key_source", "AUTHORIZER"), @@ -380,7 +380,7 @@ func TestAccAPIGatewayRestAPI_binaryMediaTypes(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIBinaryMediaTypes1Config(rName, "application/octet-stream"), + Config: testAccRestAPIConfig_binaryMediaTypes1(rName, "application/octet-stream"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "binary_media_types.#", "1"), @@ -394,7 +394,7 @@ func TestAccAPIGatewayRestAPI_binaryMediaTypes(t *testing.T) { ImportStateVerifyIgnore: []string{"body"}, }, { - Config: testAccRestAPIBinaryMediaTypes1Config(rName, "application/octet"), + Config: testAccRestAPIConfig_binaryMediaTypes1(rName, "application/octet"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "binary_media_types.#", "1"), @@ -417,7 +417,7 @@ func TestAccAPIGatewayRestAPI_BinaryMediaTypes_overrideBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIBinaryMediaTypes1OverrideBodyConfig(rName, "application/octet-stream", "image/jpeg"), + Config: testAccRestAPIConfig_binaryMediaTypes1OverrideBody(rName, "application/octet-stream", "image/jpeg"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "binary_media_types.#", "1"), @@ -432,7 +432,7 @@ func TestAccAPIGatewayRestAPI_BinaryMediaTypes_overrideBody(t *testing.T) { }, // Verify updated minimum compression size still overrides { - Config: testAccRestAPIBinaryMediaTypes1OverrideBodyConfig(rName, "application/octet", "image/jpeg"), + Config: testAccRestAPIConfig_binaryMediaTypes1OverrideBody(rName, "application/octet", "image/jpeg"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "binary_media_types.#", "1"), @@ -441,7 +441,7 @@ func TestAccAPIGatewayRestAPI_BinaryMediaTypes_overrideBody(t *testing.T) { }, // Verify updated body minimum compression size is still overridden { - Config: testAccRestAPIBinaryMediaTypes1OverrideBodyConfig(rName, "application/octet", "image/png"), + Config: testAccRestAPIConfig_binaryMediaTypes1OverrideBody(rName, "application/octet", "image/png"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "binary_media_types.#", "1"), @@ -464,7 +464,7 @@ func TestAccAPIGatewayRestAPI_BinaryMediaTypes_setByBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIBinaryMediaTypes1SetByBodyConfig(rName, "application/octet-stream"), + Config: testAccRestAPIConfig_binaryMediaTypes1SetByBody(rName, "application/octet-stream"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "binary_media_types.#", "1"), @@ -494,7 +494,7 @@ func TestAccAPIGatewayRestAPI_body(t *testing.T) { Steps: []resource.TestStep{ // The body is expected to only set a title (name) and one route { - Config: testAccRestAPIBodyConfig(rName, "/test"), + Config: testAccRestAPIConfig_body(rName, "/test"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), testAccCheckRestAPIRoutes(&conf, []string{"/", "/test"}), @@ -512,7 +512,7 @@ func TestAccAPIGatewayRestAPI_body(t *testing.T) { ImportStateVerifyIgnore: []string{"body"}, }, { - Config: testAccRestAPIBodyConfig(rName, "/update"), + Config: testAccRestAPIConfig_body(rName, "/update"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), testAccCheckRestAPIRoutes(&conf, []string{"/", "/update"}), @@ -537,7 +537,7 @@ func TestAccAPIGatewayRestAPI_description(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIDescriptionConfig(rName, "description1"), + Config: testAccRestAPIConfig_description(rName, "description1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -550,7 +550,7 @@ func TestAccAPIGatewayRestAPI_description(t *testing.T) { ImportStateVerifyIgnore: []string{"body"}, }, { - Config: testAccRestAPIDescriptionConfig(rName, "description2"), + Config: testAccRestAPIConfig_description(rName, "description2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -572,7 +572,7 @@ func TestAccAPIGatewayRestAPI_Description_overrideBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIDescriptionOverrideBodyConfig(rName, "tfdescription1", "oasdescription1"), + Config: testAccRestAPIConfig_descriptionOverrideBody(rName, "tfdescription1", "oasdescription1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", "tfdescription1"), @@ -586,7 +586,7 @@ func TestAccAPIGatewayRestAPI_Description_overrideBody(t *testing.T) { }, // Verify updated description still overrides { - Config: testAccRestAPIDescriptionOverrideBodyConfig(rName, "tfdescription2", "oasdescription1"), + Config: testAccRestAPIConfig_descriptionOverrideBody(rName, "tfdescription2", "oasdescription1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", "tfdescription2"), @@ -594,7 +594,7 @@ func TestAccAPIGatewayRestAPI_Description_overrideBody(t *testing.T) { }, // Verify updated body description is still overridden { - Config: testAccRestAPIDescriptionOverrideBodyConfig(rName, "tfdescription2", "oasdescription2"), + Config: testAccRestAPIConfig_descriptionOverrideBody(rName, "tfdescription2", "oasdescription2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", "tfdescription2"), @@ -616,7 +616,7 @@ func TestAccAPIGatewayRestAPI_Description_setByBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIDescriptionSetByBodyConfig(rName, "oasdescription1"), + Config: testAccRestAPIConfig_descriptionSetByBody(rName, "oasdescription1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", "oasdescription1"), @@ -643,7 +643,7 @@ func TestAccAPIGatewayRestAPI_disableExecuteAPIEndpoint(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIDisableExecuteAPIEndpointConfig(rName, false), + Config: testAccRestAPIConfig_disableExecuteEndpoint(rName, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "disable_execute_api_endpoint", `false`), ), @@ -654,13 +654,13 @@ func TestAccAPIGatewayRestAPI_disableExecuteAPIEndpoint(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRestAPIDisableExecuteAPIEndpointConfig(rName, true), + Config: testAccRestAPIConfig_disableExecuteEndpoint(rName, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "disable_execute_api_endpoint", `true`), ), }, { - Config: testAccRestAPIDisableExecuteAPIEndpointConfig(rName, false), + Config: testAccRestAPIConfig_disableExecuteEndpoint(rName, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "disable_execute_api_endpoint", `false`), ), @@ -681,7 +681,7 @@ func TestAccAPIGatewayRestAPI_DisableExecuteAPIEndpoint_overrideBody(t *testing. CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIDisableExecuteAPIEndpointOverrideBodyConfig(rName, true, false), + Config: testAccRestAPIConfig_disableExecuteEndpointOverrideBody(rName, true, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "disable_execute_api_endpoint", "true"), @@ -695,7 +695,7 @@ func TestAccAPIGatewayRestAPI_DisableExecuteAPIEndpoint_overrideBody(t *testing. }, // Verify override can be unset (only for body set to false) { - Config: testAccRestAPIDisableExecuteAPIEndpointOverrideBodyConfig(rName, false, false), + Config: testAccRestAPIConfig_disableExecuteEndpointOverrideBody(rName, false, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "disable_execute_api_endpoint", "false"), @@ -703,7 +703,7 @@ func TestAccAPIGatewayRestAPI_DisableExecuteAPIEndpoint_overrideBody(t *testing. }, // Verify override can be reset { - Config: testAccRestAPIDisableExecuteAPIEndpointOverrideBodyConfig(rName, true, false), + Config: testAccRestAPIConfig_disableExecuteEndpointOverrideBody(rName, true, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "disable_execute_api_endpoint", "true"), @@ -725,7 +725,7 @@ func TestAccAPIGatewayRestAPI_DisableExecuteAPIEndpoint_setByBody(t *testing.T) CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIDisableExecuteAPIEndpointSetByBodyConfig(rName, true), + Config: testAccRestAPIConfig_disableExecuteEndpointSetByBody(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "disable_execute_api_endpoint", "true"), @@ -755,7 +755,7 @@ func TestAccAPIGatewayRestAPI_Endpoint_vpcEndpointIDs(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIEndpointConfigurationVPCEndpointIds1Config(rName), + Config: testAccRestAPIConfig_vpcEndpointIDs1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &restApi), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -772,7 +772,7 @@ func TestAccAPIGatewayRestAPI_Endpoint_vpcEndpointIDs(t *testing.T) { ImportStateVerifyIgnore: []string{"body"}, }, { - Config: testAccRestAPIEndpointConfigurationVPCEndpointIds2Config(rName), + Config: testAccRestAPIConfig_endpointConfigurationVPCEndpointIds2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &restApi), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -784,7 +784,7 @@ func TestAccAPIGatewayRestAPI_Endpoint_vpcEndpointIDs(t *testing.T) { ), }, { - Config: testAccRestAPIEndpointConfigurationVPCEndpointIds1Config(rName), + Config: testAccRestAPIConfig_vpcEndpointIDs1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &restApi), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -813,7 +813,7 @@ func TestAccAPIGatewayRestAPI_EndpointVPCEndpointIDs_overrideBody(t *testing.T) CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIEndpointConfigurationVPCEndpointIdsOverrideBodyConfig(rName, vpcEndpointResourceName1, vpcEndpointResourceName2), + Config: testAccRestAPIConfig_endpointConfigurationVPCEndpointIdsOverrideBody(rName, vpcEndpointResourceName1, vpcEndpointResourceName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -829,7 +829,7 @@ func TestAccAPIGatewayRestAPI_EndpointVPCEndpointIDs_overrideBody(t *testing.T) }, // Verify updated configuration value still overrides { - Config: testAccRestAPIEndpointConfigurationVPCEndpointIdsOverrideBodyConfig(rName, vpcEndpointResourceName3, vpcEndpointResourceName2), + Config: testAccRestAPIConfig_endpointConfigurationVPCEndpointIdsOverrideBody(rName, vpcEndpointResourceName3, vpcEndpointResourceName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -839,7 +839,7 @@ func TestAccAPIGatewayRestAPI_EndpointVPCEndpointIDs_overrideBody(t *testing.T) }, // Verify updated body value is still overridden { - Config: testAccRestAPIEndpointConfigurationVPCEndpointIdsOverrideBodyConfig(rName, vpcEndpointResourceName3, vpcEndpointResourceName1), + Config: testAccRestAPIConfig_endpointConfigurationVPCEndpointIdsOverrideBody(rName, vpcEndpointResourceName3, vpcEndpointResourceName1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -864,7 +864,7 @@ func TestAccAPIGatewayRestAPI_EndpointVPCEndpointIDs_setByBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIEndpointConfigurationVPCEndpointIdsSetByBodyConfig(rName), + Config: testAccRestAPIConfig_endpointConfigurationVPCEndpointIdsSetByBody(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "endpoint_configuration.#", "1"), @@ -894,7 +894,7 @@ func TestAccAPIGatewayRestAPI_minimumCompressionSize(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIMinimumCompressionSizeConfig(rName, 0), + Config: testAccRestAPIConfig_minimumCompressionSize(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "minimum_compression_size", "0"), @@ -907,14 +907,14 @@ func TestAccAPIGatewayRestAPI_minimumCompressionSize(t *testing.T) { ImportStateVerifyIgnore: []string{"body"}, }, { - Config: testAccRestAPIMinimumCompressionSizeConfig(rName, -1), + Config: testAccRestAPIConfig_minimumCompressionSize(rName, -1), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "minimum_compression_size", "-1"), ), }, { - Config: testAccRestAPIMinimumCompressionSizeConfig(rName, 5242880), + Config: testAccRestAPIConfig_minimumCompressionSize(rName, 5242880), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "minimum_compression_size", "5242880"), @@ -936,7 +936,7 @@ func TestAccAPIGatewayRestAPI_MinimumCompressionSize_overrideBody(t *testing.T) CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIMinimumCompressionSizeOverrideBodyConfig(rName, 1, 5242880), + Config: testAccRestAPIConfig_minimumCompressionSizeOverrideBody(rName, 1, 5242880), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "minimum_compression_size", "1"), @@ -950,7 +950,7 @@ func TestAccAPIGatewayRestAPI_MinimumCompressionSize_overrideBody(t *testing.T) }, // Verify updated minimum compression size still overrides { - Config: testAccRestAPIMinimumCompressionSizeOverrideBodyConfig(rName, 2, 5242880), + Config: testAccRestAPIConfig_minimumCompressionSizeOverrideBody(rName, 2, 5242880), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "minimum_compression_size", "2"), @@ -958,7 +958,7 @@ func TestAccAPIGatewayRestAPI_MinimumCompressionSize_overrideBody(t *testing.T) }, // Verify updated body minimum compression size is still overridden { - Config: testAccRestAPIMinimumCompressionSizeOverrideBodyConfig(rName, 2, 1048576), + Config: testAccRestAPIConfig_minimumCompressionSizeOverrideBody(rName, 2, 1048576), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "minimum_compression_size", "2"), @@ -980,7 +980,7 @@ func TestAccAPIGatewayRestAPI_MinimumCompressionSize_setByBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIMinimumCompressionSizeSetByBodyConfig(rName, 1048576), + Config: testAccRestAPIConfig_minimumCompressionSizeSetByBody(rName, 1048576), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "minimum_compression_size", "1048576"), @@ -1011,7 +1011,7 @@ func TestAccAPIGatewayRestAPI_Name_overrideBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPINameOverrideBodyConfig(rName, "title1"), + Config: testAccRestAPIConfig_nameOverrideBody(rName, "title1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -1025,7 +1025,7 @@ func TestAccAPIGatewayRestAPI_Name_overrideBody(t *testing.T) { }, // Verify updated name still overrides { - Config: testAccRestAPINameOverrideBodyConfig(rName2, "title1"), + Config: testAccRestAPIConfig_nameOverrideBody(rName2, "title1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName2), @@ -1033,7 +1033,7 @@ func TestAccAPIGatewayRestAPI_Name_overrideBody(t *testing.T) { }, // Verify updated title still overrides { - Config: testAccRestAPINameOverrideBodyConfig(rName2, "title2"), + Config: testAccRestAPIConfig_nameOverrideBody(rName2, "title2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName2), @@ -1055,7 +1055,7 @@ func TestAccAPIGatewayRestAPI_parameters(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIParameters1Config(rName, "basepath", "prepend"), + Config: testAccRestAPIConfig_parameters1(rName, "basepath", "prepend"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), testAccCheckRestAPIRoutes(&conf, []string{"/", "/foo", "/foo/bar", "/foo/bar/baz", "/foo/bar/baz/test"}), @@ -1068,7 +1068,7 @@ func TestAccAPIGatewayRestAPI_parameters(t *testing.T) { ImportStateVerifyIgnore: []string{"body", "parameters"}, }, { - Config: testAccRestAPIParameters1Config(rName, "basepath", "ignore"), + Config: testAccRestAPIConfig_parameters1(rName, "basepath", "ignore"), Check: resource.ComposeTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), testAccCheckRestAPIRoutes(&conf, []string{"/", "/test"}), @@ -1091,7 +1091,7 @@ func TestAccAPIGatewayRestAPI_Policy_basic(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIWithPolicyConfig(rName), + Config: testAccRestAPIConfig_policy(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "policy", expectedPolicyText), ), @@ -1103,7 +1103,7 @@ func TestAccAPIGatewayRestAPI_Policy_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"policy"}, }, { - Config: testAccRestAPIUpdatePolicyConfig(rName), + Config: testAccRestAPIConfig_updatePolicy(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "policy", expectedUpdatePolicyText), ), @@ -1124,13 +1124,13 @@ func TestAccAPIGatewayRestAPI_Policy_order(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIWithPolicyOrderConfig(rName), + Config: testAccRestAPIConfig_policyOrder(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "policy", expectedPolicyText), ), }, { - Config: testAccRestAPIWithPolicyNewOrderConfig(rName), + Config: testAccRestAPIConfig_policyNewOrder(rName), PlanOnly: true, }, }, @@ -1149,7 +1149,7 @@ func TestAccAPIGatewayRestAPI_Policy_overrideBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIPolicyOverrideBodyConfig(rName, "/test", "Allow"), + Config: testAccRestAPIConfig_policyOverrideBody(rName, "/test", "Allow"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), testAccCheckRestAPIRoutes(&conf, []string{"/", "/test"}), @@ -1164,7 +1164,7 @@ func TestAccAPIGatewayRestAPI_Policy_overrideBody(t *testing.T) { }, // Verify updated body still has override policy { - Config: testAccRestAPIPolicyOverrideBodyConfig(rName, "/test2", "Allow"), + Config: testAccRestAPIConfig_policyOverrideBody(rName, "/test2", "Allow"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), testAccCheckRestAPIRoutes(&conf, []string{"/", "/test2"}), @@ -1173,7 +1173,7 @@ func TestAccAPIGatewayRestAPI_Policy_overrideBody(t *testing.T) { }, // Verify updated policy still overrides body { - Config: testAccRestAPIPolicyOverrideBodyConfig(rName, "/test2", "Deny"), + Config: testAccRestAPIConfig_policyOverrideBody(rName, "/test2", "Deny"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), testAccCheckRestAPIRoutes(&conf, []string{"/", "/test2"}), @@ -1196,7 +1196,7 @@ func TestAccAPIGatewayRestAPI_Policy_setByBody(t *testing.T) { CheckDestroy: testAccCheckRestAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccRestAPIPolicySetByBodyConfig(rName, "Allow"), + Config: testAccRestAPIConfig_policySetByBody(rName, "Allow"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRestAPIExists(resourceName, &conf), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(`"Allow"`)), @@ -1298,7 +1298,7 @@ func testAccCheckRestAPIDestroy(s *terraform.State) error { return nil } -func testAccRestAPIConfig_EndpointConfiguration(rName, endpointType string) string { +func testAccRestAPIConfig_endpointConfiguration(rName, endpointType string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -1310,7 +1310,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, endpointType) } -func testAccRestAPIDisableExecuteAPIEndpointConfig(rName string, disableExecuteApiEndpoint bool) string { +func testAccRestAPIConfig_disableExecuteEndpoint(rName string, disableExecuteApiEndpoint bool) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { disable_execute_api_endpoint = %[2]t @@ -1319,7 +1319,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, disableExecuteApiEndpoint) } -func testAccRestAPIDisableExecuteAPIEndpointOverrideBodyConfig(rName string, configDisableExecuteApiEndpoint bool, bodyDisableExecuteApiEndpoint bool) string { +func testAccRestAPIConfig_disableExecuteEndpointOverrideBody(rName string, configDisableExecuteApiEndpoint bool, bodyDisableExecuteApiEndpoint bool) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { disable_execute_api_endpoint = %[2]t @@ -1361,7 +1361,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, configDisableExecuteApiEndpoint, bodyDisableExecuteApiEndpoint) } -func testAccRestAPIDisableExecuteAPIEndpointSetByBodyConfig(rName string, bodyDisableExecuteApiEndpoint bool) string { +func testAccRestAPIConfig_disableExecuteEndpointSetByBody(rName string, bodyDisableExecuteApiEndpoint bool) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -1402,15 +1402,15 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, bodyDisableExecuteApiEndpoint) } -func testAccRestAPIConfig_Name(rName string) string { +func testAccRestAPIConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { - name = "%s" + name = %[1]q } `, rName) } -func testAccRestAPIEndpointConfigurationVPCEndpointIds1Config(rName string) string { +func testAccRestAPIConfig_vpcEndpointIDs1(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1460,7 +1460,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName)) } -func testAccRestAPIEndpointConfigurationVPCEndpointIds2Config(rName string) string { +func testAccRestAPIConfig_endpointConfigurationVPCEndpointIds2(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1519,7 +1519,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName)) } -func testAccRestAPIEndpointConfigurationVPCEndpointIdsOverrideBodyConfig(rName string, configVpcEndpointResourceName string, bodyVpcEndpointResourceName string) string { +func testAccRestAPIConfig_endpointConfigurationVPCEndpointIdsOverrideBody(rName string, configVpcEndpointResourceName string, bodyVpcEndpointResourceName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1604,7 +1604,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, configVpcEndpointResourceName+".id", bodyVpcEndpointResourceName+".id")) } -func testAccRestAPIEndpointConfigurationVPCEndpointIdsSetByBodyConfig(rName string) string { +func testAccRestAPIConfig_endpointConfigurationVPCEndpointIdsSetByBody(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1686,7 +1686,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName)) } -func testAccRestAPITags1Config(rName, tagKey1, tagValue1 string) string { +func testAccRestAPIConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -1698,7 +1698,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, tagKey1, tagValue1) } -func testAccRestAPITags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccRestAPIConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = "%s" @@ -1711,7 +1711,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccRestAPIWithPolicyConfig(rName string) string { +func testAccRestAPIConfig_policy(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -1735,7 +1735,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName) } -func testAccRestAPIUpdatePolicyConfig(rName string) string { +func testAccRestAPIConfig_updatePolicy(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -1754,7 +1754,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName) } -func testAccRestAPIWithPolicyOrderConfig(rName string) string { +func testAccRestAPIConfig_policyOrder(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -1782,7 +1782,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName) } -func testAccRestAPIWithPolicyNewOrderConfig(rName string) string { +func testAccRestAPIConfig_policyNewOrder(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -1810,7 +1810,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName) } -func testAccRestAPIAPIKeySourceConfig(rName string, apiKeySource string) string { +func testAccRestAPIConfig_keySource(rName string, apiKeySource string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { api_key_source = %[2]q @@ -1819,7 +1819,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, apiKeySource) } -func testAccRestAPIAPIKeySourceOverrideBodyConfig(rName string, apiKeySource string, bodyApiKeySource string) string { +func testAccRestAPIConfig_keySourceOverrideBody(rName string, apiKeySource string, bodyApiKeySource string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { api_key_source = %[2]q @@ -1859,7 +1859,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, apiKeySource, bodyApiKeySource) } -func testAccRestAPIAPIKeySourceSetByBodyConfig(rName string, bodyApiKeySource string) string { +func testAccRestAPIConfig_keySourceSetByBody(rName string, bodyApiKeySource string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -1898,7 +1898,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, bodyApiKeySource) } -func testAccRestAPIBinaryMediaTypes1Config(rName string, binaryMediaTypes1 string) string { +func testAccRestAPIConfig_binaryMediaTypes1(rName string, binaryMediaTypes1 string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { binary_media_types = [%[2]q] @@ -1907,7 +1907,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, binaryMediaTypes1) } -func testAccRestAPIBinaryMediaTypes1OverrideBodyConfig(rName string, binaryMediaTypes1 string, bodyBinaryMediaTypes1 string) string { +func testAccRestAPIConfig_binaryMediaTypes1OverrideBody(rName string, binaryMediaTypes1 string, bodyBinaryMediaTypes1 string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { binary_media_types = [%[2]q] @@ -1947,7 +1947,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, binaryMediaTypes1, bodyBinaryMediaTypes1) } -func testAccRestAPIBinaryMediaTypes1SetByBodyConfig(rName string, bodyBinaryMediaTypes1 string) string { +func testAccRestAPIConfig_binaryMediaTypes1SetByBody(rName string, bodyBinaryMediaTypes1 string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -1986,7 +1986,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, bodyBinaryMediaTypes1) } -func testAccRestAPIBodyConfig(rName string, basePath string) string { +func testAccRestAPIConfig_body(rName string, basePath string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -2024,7 +2024,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, basePath) } -func testAccRestAPIDescriptionConfig(rName string, description string) string { +func testAccRestAPIConfig_description(rName string, description string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { description = %[2]q @@ -2033,7 +2033,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, description) } -func testAccRestAPIDescriptionOverrideBodyConfig(rName string, description string, bodyDescription string) string { +func testAccRestAPIConfig_descriptionOverrideBody(rName string, description string, bodyDescription string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { description = %[2]q @@ -2073,7 +2073,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, description, bodyDescription) } -func testAccRestAPIDescriptionSetByBodyConfig(rName string, bodyDescription string) string { +func testAccRestAPIConfig_descriptionSetByBody(rName string, bodyDescription string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -2112,7 +2112,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, bodyDescription) } -func testAccRestAPIMinimumCompressionSizeConfig(rName string, minimumCompressionSize int) string { +func testAccRestAPIConfig_minimumCompressionSize(rName string, minimumCompressionSize int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { minimum_compression_size = %[2]d @@ -2121,7 +2121,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, minimumCompressionSize) } -func testAccRestAPIMinimumCompressionSizeOverrideBodyConfig(rName string, minimumCompressionSize int, bodyMinimumCompressionSize int) string { +func testAccRestAPIConfig_minimumCompressionSizeOverrideBody(rName string, minimumCompressionSize int, bodyMinimumCompressionSize int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { minimum_compression_size = %[2]d @@ -2161,7 +2161,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, minimumCompressionSize, bodyMinimumCompressionSize) } -func testAccRestAPIMinimumCompressionSizeSetByBodyConfig(rName string, bodyMinimumCompressionSize int) string { +func testAccRestAPIConfig_minimumCompressionSizeSetByBody(rName string, bodyMinimumCompressionSize int) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -2200,15 +2200,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, bodyMinimumCompressionSize) } -func testAccRestAPINameConfig(rName string) string { - return fmt.Sprintf(` -resource "aws_api_gateway_rest_api" "test" { - name = %[1]q -} -`, rName) -} - -func testAccRestAPINameOverrideBodyConfig(rName string, title string) string { +func testAccRestAPIConfig_nameOverrideBody(rName string, title string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -2246,7 +2238,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, title) } -func testAccRestAPIParameters1Config(rName string, parameterKey1 string, parameterValue1 string) string { +func testAccRestAPIConfig_parameters1(rName string, parameterKey1 string, parameterValue1 string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -2289,7 +2281,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, parameterKey1, parameterValue1) } -func testAccRestAPIPolicyOverrideBodyConfig(rName string, bodyPath string, policyEffect string) string { +func testAccRestAPIConfig_policyOverrideBody(rName string, bodyPath string, policyEffect string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q @@ -2346,7 +2338,7 @@ resource "aws_api_gateway_rest_api" "test" { `, rName, bodyPath, policyEffect) } -func testAccRestAPIPolicySetByBodyConfig(rName string, bodyPolicyEffect string) string { +func testAccRestAPIConfig_policySetByBody(rName string, bodyPolicyEffect string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { name = %[1]q diff --git a/internal/service/apigateway/sdk_data_source_test.go b/internal/service/apigateway/sdk_data_source_test.go index f4840527639..ed9c6438426 100644 --- a/internal/service/apigateway/sdk_data_source_test.go +++ b/internal/service/apigateway/sdk_data_source_test.go @@ -19,7 +19,7 @@ func TestAccAPIGatewaySdkDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSdkDataSourceConfig(rName), + Config: testAccSdkDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair("aws_api_gateway_stage.test", "rest_api_id", dataSourceName, "rest_api_id"), resource.TestCheckResourceAttrPair("aws_api_gateway_stage.test", "stage_name", dataSourceName, "stage_name"), @@ -32,7 +32,7 @@ func TestAccAPIGatewaySdkDataSource_basic(t *testing.T) { }) } -func testAccSdkDataSourceConfig(rName string) string { +func testAccSdkDataSourceConfig_basic(rName string) string { return testAccStageConfig_base(rName) + ` resource "aws_api_gateway_stage" "test" { rest_api_id = aws_api_gateway_rest_api.test.id diff --git a/internal/service/apigateway/stage.go b/internal/service/apigateway/stage.go index 40dce370a69..1ce5c3c8491 100644 --- a/internal/service/apigateway/stage.go +++ b/internal/service/apigateway/stage.go @@ -186,7 +186,7 @@ func resourceStageCreate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("canary_settings"); ok { - input.CanarySettings = expandApiGatewayStageCanarySettings(v.([]interface{}), deploymentId) + input.CanarySettings = expandStageCanarySettings(v.([]interface{}), deploymentId) } if len(tags) > 0 { @@ -240,7 +240,7 @@ func resourceStageRead(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Received API Gateway Stage: %s", stage) - if err := d.Set("access_log_settings", flattenApiGatewayStageAccessLogSettings(stage.AccessLogSettings)); err != nil { + if err := d.Set("access_log_settings", flattenAccessLogSettings(stage.AccessLogSettings)); err != nil { return fmt.Errorf("error setting access_log_settings: %s", err) } @@ -260,7 +260,7 @@ func resourceStageRead(d *schema.ResourceData, meta interface{}) error { d.Set("xray_tracing_enabled", stage.TracingEnabled) d.Set("web_acl_arn", stage.WebAclArn) - if err := d.Set("canary_settings", flattenApiGatewayStageCanarySettings(stage.CanarySettings)); err != nil { + if err := d.Set("canary_settings", flattenCanarySettings(stage.CanarySettings)); err != nil { return fmt.Errorf("error setting canary_settings: %w", err) } @@ -491,7 +491,7 @@ func resourceStageDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func flattenApiGatewayStageAccessLogSettings(accessLogSettings *apigateway.AccessLogSettings) []map[string]interface{} { +func flattenAccessLogSettings(accessLogSettings *apigateway.AccessLogSettings) []map[string]interface{} { result := make([]map[string]interface{}, 0, 1) if accessLogSettings != nil { result = append(result, map[string]interface{}{ @@ -502,7 +502,7 @@ func flattenApiGatewayStageAccessLogSettings(accessLogSettings *apigateway.Acces return result } -func expandApiGatewayStageCanarySettings(l []interface{}, deploymentId string) *apigateway.CanarySettings { +func expandStageCanarySettings(l []interface{}, deploymentId string) *apigateway.CanarySettings { if len(l) == 0 { return nil } @@ -528,7 +528,7 @@ func expandApiGatewayStageCanarySettings(l []interface{}, deploymentId string) * return canarySettings } -func flattenApiGatewayStageCanarySettings(canarySettings *apigateway.CanarySettings) []interface{} { +func flattenCanarySettings(canarySettings *apigateway.CanarySettings) []interface{} { settings := make(map[string]interface{}) if canarySettings == nil { diff --git a/internal/service/apigateway/stage_test.go b/internal/service/apigateway/stage_test.go index 3621af846a8..52ce4737011 100644 --- a/internal/service/apigateway/stage_test.go +++ b/internal/service/apigateway/stage_test.go @@ -48,7 +48,7 @@ func TestAccAPIGatewayStage_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStageConfigUpdated(rName), + Config: testAccStageConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/restapis/.+/stages/prod`)), @@ -106,7 +106,7 @@ func TestAccAPIGatewayStage_cache(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStageConfigCacheConfig(rName, "0.5"), + Config: testAccStageConfig_cache(rName, "0.5"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "cache_cluster_size", "0.5"), @@ -115,7 +115,7 @@ func TestAccAPIGatewayStage_cache(t *testing.T) { }, { - Config: testAccStageConfigCacheConfig(rName, "1.6"), + Config: testAccStageConfig_cache(rName, "1.6"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "cache_cluster_size", "1.6"), @@ -134,7 +134,7 @@ func TestAccAPIGatewayStage_cache(t *testing.T) { } // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/22866 -func TestAccAPIGatewayStage_cache_size_cache_disabled(t *testing.T) { +func TestAccAPIGatewayStage_cacheSizeCacheDisabled(t *testing.T) { var conf apigateway.Stage rName := sdkacctest.RandString(5) resourceName := "aws_api_gateway_stage.test" @@ -159,7 +159,7 @@ func TestAccAPIGatewayStage_cache_size_cache_disabled(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStageConfigCacheSizeCacheDisabled(rName, "0.5"), + Config: testAccStageConfig_cacheSizeCacheDisabled(rName, "0.5"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "cache_cluster_size", "0.5"), @@ -167,7 +167,7 @@ func TestAccAPIGatewayStage_cache_size_cache_disabled(t *testing.T) { ), }, { - Config: testAccStageConfigCacheConfig(rName, "0.5"), + Config: testAccStageConfig_cache(rName, "0.5"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "cache_cluster_size", "0.5"), @@ -191,7 +191,7 @@ func TestAccAPIGatewayStage_Disappears_referencingDeployment(t *testing.T) { CheckDestroy: testAccCheckStageDestroy, Steps: []resource.TestStep{ { - Config: testAccStageReferencingDeploymentConfig(rName), + Config: testAccStageConfig_referencingDeployment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage), ), @@ -218,7 +218,7 @@ func TestAccAPIGatewayStage_tags(t *testing.T) { CheckDestroy: testAccCheckStageDestroy, Steps: []resource.TestStep{ { - Config: testAccStageConfigTags1(rName, "key1", "value1"), + Config: testAccStageConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -232,7 +232,7 @@ func TestAccAPIGatewayStage_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStageConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccStageConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -241,7 +241,7 @@ func TestAccAPIGatewayStage_tags(t *testing.T) { ), }, { - Config: testAccStageConfigTags1(rName, "key2", "value2"), + Config: testAccStageConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -264,7 +264,7 @@ func TestAccAPIGatewayStage_disappears(t *testing.T) { CheckDestroy: testAccCheckStageDestroy, Steps: []resource.TestStep{ { - Config: testAccStageReferencingDeploymentConfig(rName), + Config: testAccStageConfig_referencingDeployment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceStage(), resourceName), @@ -276,7 +276,7 @@ func TestAccAPIGatewayStage_disappears(t *testing.T) { }) } -func TestAccAPIGatewayStage_disappears_restApi(t *testing.T) { +func TestAccAPIGatewayStage_Disappears_restAPI(t *testing.T) { var stage apigateway.Stage rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_api_gateway_stage.test" @@ -288,7 +288,7 @@ func TestAccAPIGatewayStage_disappears_restApi(t *testing.T) { CheckDestroy: testAccCheckStageDestroy, Steps: []resource.TestStep{ { - Config: testAccStageReferencingDeploymentConfig(rName), + Config: testAccStageConfig_referencingDeployment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &stage), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceRestAPI(), "aws_api_gateway_rest_api.test"), @@ -688,7 +688,7 @@ resource "aws_api_gateway_deployment" "test" { `, rName, stageName) } -func testAccStageReferencingDeploymentConfig(rName string) string { +func testAccStageConfig_referencingDeployment(rName string) string { return acctest.ConfigCompose( testAccStageBaseDeploymentStageNameConfig(rName, ""), ` @@ -723,7 +723,7 @@ resource "aws_api_gateway_stage" "test" { ` } -func testAccStageConfigUpdated(rName string) string { +func testAccStageConfig_updated(rName string) string { return testAccStageConfig_base(rName) + ` resource "aws_api_gateway_stage" "test" { rest_api_id = aws_api_gateway_rest_api.test.id @@ -740,7 +740,7 @@ resource "aws_api_gateway_stage" "test" { ` } -func testAccStageConfigCacheSizeCacheDisabled(rName, size string) string { +func testAccStageConfig_cacheSizeCacheDisabled(rName, size string) string { return testAccStageConfig_base(rName) + fmt.Sprintf(` resource "aws_api_gateway_stage" "test" { rest_api_id = aws_api_gateway_rest_api.test.id @@ -751,7 +751,7 @@ resource "aws_api_gateway_stage" "test" { `, size) } -func testAccStageConfigCacheConfig(rName, size string) string { +func testAccStageConfig_cache(rName, size string) string { return testAccStageConfig_base(rName) + fmt.Sprintf(` resource "aws_api_gateway_stage" "test" { rest_api_id = aws_api_gateway_rest_api.test.id @@ -836,7 +836,7 @@ resource "aws_api_gateway_stage" "test" { `, rName, format) } -func testAccStageConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccStageConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccStageConfig_base(rName) + fmt.Sprintf(` resource "aws_api_gateway_stage" "test" { rest_api_id = aws_api_gateway_rest_api.test.id @@ -850,7 +850,7 @@ resource "aws_api_gateway_stage" "test" { `, tagKey1, tagValue1) } -func testAccStageConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccStageConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccStageConfig_base(rName) + fmt.Sprintf(` resource "aws_api_gateway_stage" "test" { rest_api_id = aws_api_gateway_rest_api.test.id diff --git a/internal/service/apigateway/status.go b/internal/service/apigateway/status.go index b9a96cbe403..dd816a98d46 100644 --- a/internal/service/apigateway/status.go +++ b/internal/service/apigateway/status.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func apiGatewayVpcLinkStatus(conn *apigateway.APIGateway, vpcLinkId string) resource.StateRefreshFunc { +func vpcLinkStatus(conn *apigateway.APIGateway, vpcLinkId string) resource.StateRefreshFunc { return func() (interface{}, string, error) { output, err := conn.GetVpcLink(&apigateway.GetVpcLinkInput{ VpcLinkId: aws.String(vpcLinkId), diff --git a/internal/service/apigateway/usage_plan.go b/internal/service/apigateway/usage_plan.go index 199ebc5ddf5..f2ce5db3e6f 100644 --- a/internal/service/apigateway/usage_plan.go +++ b/internal/service/apigateway/usage_plan.go @@ -158,7 +158,7 @@ func resourceUsagePlanCreate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("api_stages"); ok && v.(*schema.Set).Len() > 0 { - params.ApiStages = expandApiGatewayUsageApiStages(v.(*schema.Set)) + params.ApiStages = expandAPIStages(v.(*schema.Set)) } if v, ok := d.GetOk("quota_settings"); ok { @@ -173,11 +173,11 @@ func resourceUsagePlanCreate(d *schema.ResourceData, meta interface{}) error { return errors.New("At least one field is expected inside quota_settings") } - params.Quota = expandApiGatewayUsageQuotaSettings(v.([]interface{})) + params.Quota = expandQuotaSettings(v.([]interface{})) } if v, ok := d.GetOk("throttle_settings"); ok { - params.Throttle = expandApiGatewayUsageThrottleSettings(v.([]interface{})) + params.Throttle = expandThrottleSettings(v.([]interface{})) } if len(tags) > 0 { @@ -257,19 +257,19 @@ func resourceUsagePlanRead(d *schema.ResourceData, meta interface{}) error { d.Set("product_code", up.ProductCode) if up.ApiStages != nil { - if err := d.Set("api_stages", flattenApiGatewayUsageApiStages(up.ApiStages)); err != nil { + if err := d.Set("api_stages", flattenAPIStages(up.ApiStages)); err != nil { return fmt.Errorf("error setting api_stages error: %w", err) } } if up.Throttle != nil { - if err := d.Set("throttle_settings", flattenApiGatewayUsagePlanThrottling(up.Throttle)); err != nil { + if err := d.Set("throttle_settings", flattenThrottleSettings(up.Throttle)); err != nil { return fmt.Errorf("error setting throttle_settings error: %w", err) } } if up.Quota != nil { - if err := d.Set("quota_settings", flattenApiGatewayUsagePlanQuota(up.Quota)); err != nil { + if err := d.Set("quota_settings", flattenQuotaSettings(up.Quota)); err != nil { return fmt.Errorf("error setting quota_settings error: %w", err) } } @@ -532,7 +532,7 @@ func resourceUsagePlanDelete(d *schema.ResourceData, meta interface{}) error { } -func expandApiGatewayUsageApiStages(s *schema.Set) []*apigateway.ApiStage { +func expandAPIStages(s *schema.Set) []*apigateway.ApiStage { stages := []*apigateway.ApiStage{} for _, stageRaw := range s.List() { @@ -548,7 +548,7 @@ func expandApiGatewayUsageApiStages(s *schema.Set) []*apigateway.ApiStage { } if v, ok := mStage["throttle"].(*schema.Set); ok && v.Len() > 0 { - stage.Throttle = expandUsagePlanApiGatewayApiStagesThrottleSettings(v.List()) + stage.Throttle = expandThrottleSettingsList(v.List()) } stages = append(stages, stage) @@ -557,7 +557,7 @@ func expandApiGatewayUsageApiStages(s *schema.Set) []*apigateway.ApiStage { return stages } -func expandApiGatewayUsageQuotaSettings(l []interface{}) *apigateway.QuotaSettings { +func expandQuotaSettings(l []interface{}) *apigateway.QuotaSettings { if len(l) == 0 { return nil } @@ -581,7 +581,7 @@ func expandApiGatewayUsageQuotaSettings(l []interface{}) *apigateway.QuotaSettin return qs } -func expandApiGatewayUsageThrottleSettings(l []interface{}) *apigateway.ThrottleSettings { +func expandThrottleSettings(l []interface{}) *apigateway.ThrottleSettings { if len(l) == 0 { return nil } @@ -601,7 +601,7 @@ func expandApiGatewayUsageThrottleSettings(l []interface{}) *apigateway.Throttle return ts } -func flattenApiGatewayUsageApiStages(s []*apigateway.ApiStage) []map[string]interface{} { +func flattenAPIStages(s []*apigateway.ApiStage) []map[string]interface{} { stages := make([]map[string]interface{}, 0) for _, bd := range s { @@ -609,7 +609,7 @@ func flattenApiGatewayUsageApiStages(s []*apigateway.ApiStage) []map[string]inte stage := make(map[string]interface{}) stage["api_id"] = aws.StringValue(bd.ApiId) stage["stage"] = aws.StringValue(bd.Stage) - stage["throttle"] = flattenUsagePlanApiGatewayApiStagesThrottleSettings(bd.Throttle) + stage["throttle"] = flattenThrottleSettingsMap(bd.Throttle) stages = append(stages, stage) } @@ -622,7 +622,7 @@ func flattenApiGatewayUsageApiStages(s []*apigateway.ApiStage) []map[string]inte return nil } -func flattenApiGatewayUsagePlanThrottling(s *apigateway.ThrottleSettings) []map[string]interface{} { +func flattenThrottleSettings(s *apigateway.ThrottleSettings) []map[string]interface{} { settings := make(map[string]interface{}) if s == nil { @@ -640,7 +640,7 @@ func flattenApiGatewayUsagePlanThrottling(s *apigateway.ThrottleSettings) []map[ return []map[string]interface{}{settings} } -func flattenApiGatewayUsagePlanQuota(s *apigateway.QuotaSettings) []map[string]interface{} { +func flattenQuotaSettings(s *apigateway.QuotaSettings) []map[string]interface{} { settings := make(map[string]interface{}) if s == nil { @@ -662,7 +662,7 @@ func flattenApiGatewayUsagePlanQuota(s *apigateway.QuotaSettings) []map[string]i return []map[string]interface{}{settings} } -func expandUsagePlanApiGatewayApiStagesThrottleSettings(tfList []interface{}) map[string]*apigateway.ThrottleSettings { +func expandThrottleSettingsList(tfList []interface{}) map[string]*apigateway.ThrottleSettings { if len(tfList) == 0 { return nil } @@ -694,7 +694,7 @@ func expandUsagePlanApiGatewayApiStagesThrottleSettings(tfList []interface{}) ma return apiObjects } -func flattenUsagePlanApiGatewayApiStagesThrottleSettings(apiObjects map[string]*apigateway.ThrottleSettings) []interface{} { +func flattenThrottleSettingsMap(apiObjects map[string]*apigateway.ThrottleSettings) []interface{} { if len(apiObjects) == 0 { return nil } diff --git a/internal/service/apigateway/usage_plan_key_test.go b/internal/service/apigateway/usage_plan_key_test.go index 20bab344339..c23dc27bd9b 100644 --- a/internal/service/apigateway/usage_plan_key_test.go +++ b/internal/service/apigateway/usage_plan_key_test.go @@ -30,7 +30,7 @@ func TestAccAPIGatewayUsagePlanKey_basic(t *testing.T) { CheckDestroy: testAccCheckUsagePlanKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanKeyKeyTypeAPIKeyConfig(rName), + Config: testAccUsagePlanKeyConfig_typeAPI(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanKeyExists(resourceName, &conf), resource.TestCheckResourceAttrPair(resourceName, "key_id", apiGatewayApiKeyResourceName, "id"), @@ -62,7 +62,7 @@ func TestAccAPIGatewayUsagePlanKey_disappears(t *testing.T) { CheckDestroy: testAccCheckUsagePlanKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanKeyKeyTypeAPIKeyConfig(rName), + Config: testAccUsagePlanKeyConfig_typeAPI(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanKeyExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceUsagePlanKey(), resourceName), @@ -84,7 +84,7 @@ func TestAccAPIGatewayUsagePlanKey_KeyID_concurrency(t *testing.T) { CheckDestroy: testAccCheckUsagePlanKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanKeyKeyIdConcurrencyConfig(rName), + Config: testAccUsagePlanKeyConfig_idConcurrency(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanKeyExists("aws_api_gateway_usage_plan_key.test.0", &conf), testAccCheckUsagePlanKeyExists("aws_api_gateway_usage_plan_key.test.1", &conf), @@ -234,7 +234,7 @@ resource "aws_api_gateway_deployment" "test" { `, rName) } -func testAccUsagePlanKeyKeyTypeAPIKeyConfig(rName string) string { +func testAccUsagePlanKeyConfig_typeAPI(rName string) string { return acctest.ConfigCompose( testAccUsagePlanKeyBaseConfig(rName), fmt.Sprintf(` @@ -259,7 +259,7 @@ resource "aws_api_gateway_usage_plan_key" "test" { `, rName)) } -func testAccUsagePlanKeyKeyIdConcurrencyConfig(rName string) string { +func testAccUsagePlanKeyConfig_idConcurrency(rName string) string { return acctest.ConfigCompose( testAccUsagePlanKeyBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/apigateway/usage_plan_test.go b/internal/service/apigateway/usage_plan_test.go index 4e4f55f5369..1cd1a6e5ec8 100644 --- a/internal/service/apigateway/usage_plan_test.go +++ b/internal/service/apigateway/usage_plan_test.go @@ -29,7 +29,7 @@ func TestAccAPIGatewayUsagePlan_basic(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -47,7 +47,7 @@ func TestAccAPIGatewayUsagePlan_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUsagePlanBasicConfig(updatedName), + Config: testAccUsagePlanConfig_basic(updatedName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", updatedName), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -69,7 +69,7 @@ func TestAccAPIGatewayUsagePlan_tags(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanBasicTags1(rName, "key1", "value1"), + Config: testAccUsagePlanConfig_basicTags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -83,7 +83,7 @@ func TestAccAPIGatewayUsagePlan_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUsagePlanBasicTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccUsagePlanConfig_basicTags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -92,7 +92,7 @@ func TestAccAPIGatewayUsagePlan_tags(t *testing.T) { ), }, { - Config: testAccUsagePlanBasicTags1(rName, "key2", "value2"), + Config: testAccUsagePlanConfig_basicTags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -116,7 +116,7 @@ func TestAccAPIGatewayUsagePlan_description(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -128,27 +128,27 @@ func TestAccAPIGatewayUsagePlan_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUsagePlanDescriptionConfig(rName, "This is a description"), + Config: testAccUsagePlanConfig_description(rName, "This is a description"), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", "This is a description"), ), }, { - Config: testAccUsagePlanDescriptionConfig(rName, "This is a new description"), + Config: testAccUsagePlanConfig_description(rName, "This is a new description"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "description", "This is a new description"), ), }, { - Config: testAccUsagePlanDescriptionConfig(rName, "This is a description"), + Config: testAccUsagePlanConfig_description(rName, "This is a description"), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", "This is a description"), ), }, { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -170,7 +170,7 @@ func TestAccAPIGatewayUsagePlan_productCode(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanProductCodeConfig(rName, "MYCODE"), + Config: testAccUsagePlanConfig_productCode(rName, "MYCODE"), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "product_code", "MYCODE"), @@ -182,21 +182,21 @@ func TestAccAPIGatewayUsagePlan_productCode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUsagePlanProductCodeConfig(rName, "MYCODE2"), + Config: testAccUsagePlanConfig_productCode(rName, "MYCODE2"), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "product_code", "MYCODE2"), ), }, { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "product_code", ""), ), }, { - Config: testAccUsagePlanProductCodeConfig(rName, "MYCODE"), + Config: testAccUsagePlanConfig_productCode(rName, "MYCODE"), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "product_code", "MYCODE"), @@ -218,7 +218,7 @@ func TestAccAPIGatewayUsagePlan_throttling(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -231,7 +231,7 @@ func TestAccAPIGatewayUsagePlan_throttling(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUsagePlanThrottlingConfig(rName), + Config: testAccUsagePlanConfig_throttling(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -240,7 +240,7 @@ func TestAccAPIGatewayUsagePlan_throttling(t *testing.T) { ), }, { - Config: testAccUsagePlanThrottlingModifiedConfig(rName), + Config: testAccUsagePlanConfig_throttlingModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -249,7 +249,7 @@ func TestAccAPIGatewayUsagePlan_throttling(t *testing.T) { ), }, { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -273,7 +273,7 @@ func TestAccAPIGatewayUsagePlan_throttlingInitialRateLimit(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanThrottlingConfig(rName), + Config: testAccUsagePlanConfig_throttling(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "throttle_settings.0.rate_limit", "5"), @@ -300,7 +300,7 @@ func TestAccAPIGatewayUsagePlan_quota(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -313,7 +313,7 @@ func TestAccAPIGatewayUsagePlan_quota(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUsagePlanQuotaConfig(rName), + Config: testAccUsagePlanConfig_quota(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -323,7 +323,7 @@ func TestAccAPIGatewayUsagePlan_quota(t *testing.T) { ), }, { - Config: testAccUsagePlanQuotaModifiedConfig(rName), + Config: testAccUsagePlanConfig_quotaModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -333,7 +333,7 @@ func TestAccAPIGatewayUsagePlan_quota(t *testing.T) { ), }, { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -358,7 +358,7 @@ func TestAccAPIGatewayUsagePlan_apiStages(t *testing.T) { // Create UsagePlan WITH Stages as the API calls are different // when creating or updating. { - Config: testAccUsagePlanAPIStagesConfig(rName), + Config: testAccUsagePlanConfig_apiStages(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -374,7 +374,7 @@ func TestAccAPIGatewayUsagePlan_apiStages(t *testing.T) { }, // Handle api stages removal { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -383,7 +383,7 @@ func TestAccAPIGatewayUsagePlan_apiStages(t *testing.T) { }, // Handle api stages additions { - Config: testAccUsagePlanAPIStagesConfig(rName), + Config: testAccUsagePlanConfig_apiStages(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -394,7 +394,7 @@ func TestAccAPIGatewayUsagePlan_apiStages(t *testing.T) { }, // Handle api stages updates { - Config: testAccUsagePlanAPIStagesMultipleConfig(rName), + Config: testAccUsagePlanConfig_apiStagesMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -407,7 +407,7 @@ func TestAccAPIGatewayUsagePlan_apiStages(t *testing.T) { ), }, { - Config: testAccUsagePlanAPIStagesModifiedConfig(rName), + Config: testAccUsagePlanConfig_apiStagesModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -417,7 +417,7 @@ func TestAccAPIGatewayUsagePlan_apiStages(t *testing.T) { ), }, { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -440,7 +440,7 @@ func TestAccAPIGatewayUsagePlan_APIStages_multiple(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanAPIStagesMultipleConfig(rName), + Config: testAccUsagePlanConfig_apiStagesMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -473,7 +473,7 @@ func TestAccAPIGatewayUsagePlan_APIStages_throttle(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanAPIStagesConfigThrottle(rName), + Config: testAccUsagePlanConfig_apiStagesThrottle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -490,7 +490,7 @@ func TestAccAPIGatewayUsagePlan_APIStages_throttle(t *testing.T) { ), }, { - Config: testAccUsagePlanAPIStagesConfigThrottleMulti(rName), + Config: testAccUsagePlanConfig_apiStagesThrottleMulti(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -531,7 +531,7 @@ func TestAccAPIGatewayUsagePlan_disappears(t *testing.T) { CheckDestroy: testAccCheckUsagePlanDestroy, Steps: []resource.TestStep{ { - Config: testAccUsagePlanBasicConfig(rName), + Config: testAccUsagePlanConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUsagePlanExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceUsagePlan(), resourceName), @@ -671,7 +671,7 @@ resource "aws_api_gateway_deployment" "foo" { `, rName) } -func testAccUsagePlanBasicConfig(rName string) string { +func testAccUsagePlanConfig_basic(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -679,7 +679,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName) } -func testAccUsagePlanBasicTags1(rName, tagKey1, tagValue1 string) string { +func testAccUsagePlanConfig_basicTags1(rName, tagKey1, tagValue1 string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -691,7 +691,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName, tagKey1, tagValue1) } -func testAccUsagePlanBasicTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccUsagePlanConfig_basicTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -704,7 +704,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccUsagePlanDescriptionConfig(rName, desc string) string { +func testAccUsagePlanConfig_description(rName, desc string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = %[1]q @@ -713,7 +713,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName, desc) } -func testAccUsagePlanProductCodeConfig(rName, code string) string { +func testAccUsagePlanConfig_productCode(rName, code string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = %[1]q @@ -722,7 +722,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName, code) } -func testAccUsagePlanThrottlingConfig(rName string) string { +func testAccUsagePlanConfig_throttling(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -735,7 +735,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName) } -func testAccUsagePlanThrottlingModifiedConfig(rName string) string { +func testAccUsagePlanConfig_throttlingModified(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -748,7 +748,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName) } -func testAccUsagePlanQuotaConfig(rName string) string { +func testAccUsagePlanConfig_quota(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -762,7 +762,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName) } -func testAccUsagePlanQuotaModifiedConfig(rName string) string { +func testAccUsagePlanConfig_quotaModified(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -776,7 +776,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName) } -func testAccUsagePlanAPIStagesConfig(rName string) string { +func testAccUsagePlanConfig_apiStages(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -789,7 +789,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName) } -func testAccUsagePlanAPIStagesConfigThrottle(rName string) string { +func testAccUsagePlanConfig_apiStagesThrottle(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -813,7 +813,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName) } -func testAccUsagePlanAPIStagesConfigThrottleMulti(rName string) string { +func testAccUsagePlanConfig_apiStagesThrottleMulti(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -848,7 +848,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName) } -func testAccUsagePlanAPIStagesModifiedConfig(rName string) string { +func testAccUsagePlanConfig_apiStagesModified(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" @@ -861,7 +861,7 @@ resource "aws_api_gateway_usage_plan" "test" { `, rName) } -func testAccUsagePlanAPIStagesMultipleConfig(rName string) string { +func testAccUsagePlanConfig_apiStagesMultiple(rName string) string { return testAccUsagePlanConfig(rName) + fmt.Sprintf(` resource "aws_api_gateway_usage_plan" "test" { name = "%s" diff --git a/internal/service/apigateway/vpc_link.go b/internal/service/apigateway/vpc_link.go index a367b48bcdd..3437cf0380f 100644 --- a/internal/service/apigateway/vpc_link.go +++ b/internal/service/apigateway/vpc_link.go @@ -75,7 +75,7 @@ func resourceVPCLinkCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(aws.StringValue(resp.Id)) - if err := waitAPIGatewayVPCLinkAvailable(conn, d.Id()); err != nil { + if err := waitVPCLinkAvailable(conn, d.Id()); err != nil { return fmt.Errorf("error waiting for API Gateway VPC Link (%s) availability after creation: %w", d.Id(), err) } @@ -164,7 +164,7 @@ func resourceVPCLinkUpdate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error updating API Gateway VPC Link (%s): %w", d.Id(), err) } - if err := waitAPIGatewayVPCLinkAvailable(conn, d.Id()); err != nil { + if err := waitVPCLinkAvailable(conn, d.Id()); err != nil { return fmt.Errorf("error waiting for API Gateway VPC Link (%s) availability after update: %w", d.Id(), err) } @@ -188,7 +188,7 @@ func resourceVPCLinkDelete(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error deleting API Gateway VPC Link (%s): %w", d.Id(), err) } - if err := waitAPIGatewayVPCLinkDeleted(conn, d.Id()); err != nil { + if err := waitVPCLinkDeleted(conn, d.Id()); err != nil { return fmt.Errorf("error waiting for API Gateway VPC Link (%s) deletion: %w", d.Id(), err) } diff --git a/internal/service/apigateway/vpc_link_data_source_test.go b/internal/service/apigateway/vpc_link_data_source_test.go index c109b9401d5..8df7d71aff7 100644 --- a/internal/service/apigateway/vpc_link_data_source_test.go +++ b/internal/service/apigateway/vpc_link_data_source_test.go @@ -20,7 +20,7 @@ func TestAccAPIGatewayVPCLinkDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCLinkDataSourceConfig(rName), + Config: testAccVPCLinkDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), @@ -35,7 +35,7 @@ func TestAccAPIGatewayVPCLinkDataSource_basic(t *testing.T) { }) } -func testAccVPCLinkDataSourceConfig(r string) string { +func testAccVPCLinkDataSourceConfig_basic(r string) string { return fmt.Sprintf(` resource "aws_vpc" "apigateway_vpclink_test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/apigateway/vpc_link_test.go b/internal/service/apigateway/vpc_link_test.go index 97e5455810e..dbcffe683b9 100644 --- a/internal/service/apigateway/vpc_link_test.go +++ b/internal/service/apigateway/vpc_link_test.go @@ -29,7 +29,7 @@ func TestAccAPIGatewayVPCLink_basic(t *testing.T) { CheckDestroy: testAccCheckVPCLinkDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIGatewayVpcLinkConfig(rName, "test"), + Config: testAccVPCLinkConfig_basic(rName, "test"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCLinkExists(resourceName), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/vpclinks/.+`)), @@ -44,7 +44,7 @@ func TestAccAPIGatewayVPCLink_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAPIGatewayVpcLinkConfig_Update(rName, "test update"), + Config: testAccVPCLinkConfig_update(rName, "test update"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCLinkExists(resourceName), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/vpclinks/.+`)), @@ -70,7 +70,7 @@ func TestAccAPIGatewayVPCLink_tags(t *testing.T) { CheckDestroy: testAccCheckVPCLinkDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIGatewayVpcLinkConfigTags1(rName, description, "key1", "value1"), + Config: testAccVPCLinkConfig_tags1(rName, description, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCLinkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", vpcLinkName), @@ -86,7 +86,7 @@ func TestAccAPIGatewayVPCLink_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAPIGatewayVpcLinkConfigTags2(rName, description, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCLinkConfig_tags2(rName, description, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCLinkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", vpcLinkName), @@ -98,7 +98,7 @@ func TestAccAPIGatewayVPCLink_tags(t *testing.T) { ), }, { - Config: testAccAPIGatewayVpcLinkConfigTags1(rName, description, "key2", "value2"), + Config: testAccVPCLinkConfig_tags1(rName, description, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCLinkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", vpcLinkName), @@ -123,7 +123,7 @@ func TestAccAPIGatewayVPCLink_disappears(t *testing.T) { CheckDestroy: testAccCheckVPCLinkDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIGatewayVpcLinkConfig(rName, "test"), + Config: testAccVPCLinkConfig_basic(rName, "test"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCLinkExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfapigateway.ResourceVPCLink(), resourceName), @@ -178,7 +178,7 @@ func testAccCheckVPCLinkExists(name string) resource.TestCheckFunc { } } -func testAccAPIGatewayVpcLinkConfig_basis(rName string) string { +func testAccVPCLinkConfig_basis(rName string) string { return fmt.Sprintf(` resource "aws_lb" "test_a" { name = "tf-lb-%s" @@ -215,8 +215,8 @@ resource "aws_subnet" "test" { `, rName, rName) } -func testAccAPIGatewayVpcLinkConfig(rName, description string) string { - return testAccAPIGatewayVpcLinkConfig_basis(rName) + fmt.Sprintf(` +func testAccVPCLinkConfig_basic(rName, description string) string { + return testAccVPCLinkConfig_basis(rName) + fmt.Sprintf(` resource "aws_api_gateway_vpc_link" "test" { name = "tf-apigateway-%s" description = %q @@ -225,8 +225,8 @@ resource "aws_api_gateway_vpc_link" "test" { `, rName, description) } -func testAccAPIGatewayVpcLinkConfigTags1(rName, description, tagKey1, tagValue1 string) string { - return testAccAPIGatewayVpcLinkConfig_basis(rName) + fmt.Sprintf(` +func testAccVPCLinkConfig_tags1(rName, description, tagKey1, tagValue1 string) string { + return testAccVPCLinkConfig_basis(rName) + fmt.Sprintf(` resource "aws_api_gateway_vpc_link" "test" { name = "tf-apigateway-%s" description = %q @@ -239,8 +239,8 @@ resource "aws_api_gateway_vpc_link" "test" { `, rName, description, tagKey1, tagValue1) } -func testAccAPIGatewayVpcLinkConfigTags2(rName, description, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return testAccAPIGatewayVpcLinkConfig_basis(rName) + fmt.Sprintf(` +func testAccVPCLinkConfig_tags2(rName, description, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return testAccVPCLinkConfig_basis(rName) + fmt.Sprintf(` resource "aws_api_gateway_vpc_link" "test" { name = "tf-apigateway-%s" description = %q @@ -254,8 +254,8 @@ resource "aws_api_gateway_vpc_link" "test" { `, rName, description, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccAPIGatewayVpcLinkConfig_Update(rName, description string) string { - return testAccAPIGatewayVpcLinkConfig_basis(rName) + fmt.Sprintf(` +func testAccVPCLinkConfig_update(rName, description string) string { + return testAccVPCLinkConfig_basis(rName) + fmt.Sprintf(` resource "aws_api_gateway_vpc_link" "test" { name = "tf-apigateway-update-%s" description = %q diff --git a/internal/service/apigateway/wait.go b/internal/service/apigateway/wait.go index 88387a58324..a3224ea061b 100644 --- a/internal/service/apigateway/wait.go +++ b/internal/service/apigateway/wait.go @@ -9,24 +9,24 @@ import ( const ( // Maximum amount of time for VpcLink to become available - apiGatewayVPCLinkAvailableTimeout = 20 * time.Minute + vpcLinkAvailableTimeout = 20 * time.Minute // Maximum amount of time for VpcLink to delete - apiGatewayVPCLinkDeleteTimeout = 20 * time.Minute + vpcLinkDeleteTimeout = 20 * time.Minute // Maximum amount of time for Stage Cache to be available - apiGatewayStageCacheAvailableTimeout = 90 * time.Minute + stageCacheAvailableTimeout = 90 * time.Minute // Maximum amount of time for Stage Cache to update - apiGatewayStageCacheUpdateTimeout = 30 * time.Minute + stageCacheUpdateTimeout = 30 * time.Minute ) -func waitAPIGatewayVPCLinkAvailable(conn *apigateway.APIGateway, vpcLinkId string) error { +func waitVPCLinkAvailable(conn *apigateway.APIGateway, vpcLinkId string) error { stateConf := &resource.StateChangeConf{ Pending: []string{apigateway.VpcLinkStatusPending}, Target: []string{apigateway.VpcLinkStatusAvailable}, - Refresh: apiGatewayVpcLinkStatus(conn, vpcLinkId), - Timeout: apiGatewayVPCLinkAvailableTimeout, + Refresh: vpcLinkStatus(conn, vpcLinkId), + Timeout: vpcLinkAvailableTimeout, MinTimeout: 3 * time.Second, } @@ -35,7 +35,7 @@ func waitAPIGatewayVPCLinkAvailable(conn *apigateway.APIGateway, vpcLinkId strin return err } -func waitAPIGatewayVPCLinkDeleted(conn *apigateway.APIGateway, vpcLinkId string) error { +func waitVPCLinkDeleted(conn *apigateway.APIGateway, vpcLinkId string) error { stateConf := resource.StateChangeConf{ Pending: []string{ apigateway.VpcLinkStatusPending, @@ -43,9 +43,9 @@ func waitAPIGatewayVPCLinkDeleted(conn *apigateway.APIGateway, vpcLinkId string) apigateway.VpcLinkStatusDeleting, }, Target: []string{}, - Timeout: apiGatewayVPCLinkDeleteTimeout, + Timeout: vpcLinkDeleteTimeout, MinTimeout: 1 * time.Second, - Refresh: apiGatewayVpcLinkStatus(conn, vpcLinkId), + Refresh: vpcLinkStatus(conn, vpcLinkId), } _, err := stateConf.WaitForState() @@ -62,7 +62,7 @@ func waitStageCacheAvailable(conn *apigateway.APIGateway, restApiId, name string }, Target: []string{apigateway.CacheClusterStatusAvailable}, Refresh: stageCacheStatus(conn, restApiId, name), - Timeout: apiGatewayStageCacheAvailableTimeout, + Timeout: stageCacheAvailableTimeout, } outputRaw, err := stateConf.WaitForState() @@ -87,7 +87,7 @@ func waitStageCacheUpdated(conn *apigateway.APIGateway, restApiId, name string) apigateway.CacheClusterStatusDeleteInProgress, }, Refresh: stageCacheStatus(conn, restApiId, name), - Timeout: apiGatewayStageCacheUpdateTimeout, + Timeout: stageCacheUpdateTimeout, } outputRaw, err := stateConf.WaitForState() diff --git a/internal/service/apigatewayv2/api.go b/internal/service/apigatewayv2/api.go index 3d26273fc02..f0f6b60ebee 100644 --- a/internal/service/apigatewayv2/api.go +++ b/internal/service/apigatewayv2/api.go @@ -200,7 +200,7 @@ func resourceImportOpenAPI(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error deleting CORS configuration for API Gateway v2 API (%s): %s", d.Id(), err) } } else { - revertReq.CorsConfiguration = expandApiGateway2CorsConfiguration(corsConfiguration.([]interface{})) + revertReq.CorsConfiguration = expandCORSConfiguration(corsConfiguration.([]interface{})) } } @@ -233,7 +233,7 @@ func resourceAPICreate(d *schema.ResourceData, meta interface{}) error { req.ApiKeySelectionExpression = aws.String(v.(string)) } if v, ok := d.GetOk("cors_configuration"); ok { - req.CorsConfiguration = expandApiGateway2CorsConfiguration(v.([]interface{})) + req.CorsConfiguration = expandCORSConfiguration(v.([]interface{})) } if v, ok := d.GetOk("credentials_arn"); ok { req.CredentialsArn = aws.String(v.(string)) @@ -299,7 +299,7 @@ func resourceAPIRead(d *schema.ResourceData, meta interface{}) error { Resource: fmt.Sprintf("/apis/%s", d.Id()), }.String() d.Set("arn", apiArn) - if err := d.Set("cors_configuration", flattenApiGateway2CorsConfiguration(resp.CorsConfiguration)); err != nil { + if err := d.Set("cors_configuration", flattenCORSConfiguration(resp.CorsConfiguration)); err != nil { return fmt.Errorf("error setting cors_configuration: %s", err) } d.Set("description", resp.Description) @@ -360,7 +360,7 @@ func resourceAPIUpdate(d *schema.ResourceData, meta interface{}) error { req.ApiKeySelectionExpression = aws.String(d.Get("api_key_selection_expression").(string)) } if d.HasChange("cors_configuration") { - req.CorsConfiguration = expandApiGateway2CorsConfiguration(d.Get("cors_configuration").([]interface{})) + req.CorsConfiguration = expandCORSConfiguration(d.Get("cors_configuration").([]interface{})) } if d.HasChange("description") { req.Description = aws.String(d.Get("description").(string)) @@ -419,7 +419,7 @@ func resourceAPIDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func expandApiGateway2CorsConfiguration(vConfiguration []interface{}) *apigatewayv2.Cors { +func expandCORSConfiguration(vConfiguration []interface{}) *apigatewayv2.Cors { configuration := &apigatewayv2.Cors{} if len(vConfiguration) == 0 || vConfiguration[0] == nil { @@ -449,7 +449,7 @@ func expandApiGateway2CorsConfiguration(vConfiguration []interface{}) *apigatewa return configuration } -func flattenApiGateway2CorsConfiguration(configuration *apigatewayv2.Cors) []interface{} { +func flattenCORSConfiguration(configuration *apigatewayv2.Cors) []interface{} { if configuration == nil { return []interface{}{} } diff --git a/internal/service/apigatewayv2/api_data_source.go b/internal/service/apigatewayv2/api_data_source.go index 11921509518..763f04a0f10 100644 --- a/internal/service/apigatewayv2/api_data_source.go +++ b/internal/service/apigatewayv2/api_data_source.go @@ -130,7 +130,7 @@ func dataSourceAPIRead(d *schema.ResourceData, meta interface{}) error { Resource: fmt.Sprintf("/apis/%s", d.Id()), }.String() d.Set("arn", apiArn) - if err := d.Set("cors_configuration", flattenApiGateway2CorsConfiguration(api.CorsConfiguration)); err != nil { + if err := d.Set("cors_configuration", flattenCORSConfiguration(api.CorsConfiguration)); err != nil { return fmt.Errorf("error setting cors_configuration: %w", err) } d.Set("description", api.Description) diff --git a/internal/service/apigatewayv2/api_data_source_test.go b/internal/service/apigatewayv2/api_data_source_test.go index df922fdad24..5091ab8f0e4 100644 --- a/internal/service/apigatewayv2/api_data_source_test.go +++ b/internal/service/apigatewayv2/api_data_source_test.go @@ -22,7 +22,7 @@ func TestAccAPIGatewayV2APIDataSource_http(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccAPIHTTPDataSourceConfig(rName), + Config: testAccAPIDataSourceConfig_http(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "api_endpoint", resourceName, "api_endpoint"), resource.TestCheckResourceAttrPair(dataSourceName, "api_key_selection_expression", resourceName, "api_key_selection_expression"), @@ -62,7 +62,7 @@ func TestAccAPIGatewayV2APIDataSource_webSocket(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccAPIWebSocketDataSourceConfig(rName), + Config: testAccAPIDataSourceConfig_webSocket(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "api_endpoint", resourceName, "api_endpoint"), resource.TestCheckResourceAttrPair(dataSourceName, "api_key_selection_expression", resourceName, "api_key_selection_expression"), @@ -84,7 +84,7 @@ func TestAccAPIGatewayV2APIDataSource_webSocket(t *testing.T) { }) } -func testAccAPIHTTPDataSourceConfig(rName string) string { +func testAccAPIDataSourceConfig_http(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { description = "test description" @@ -110,7 +110,7 @@ data "aws_apigatewayv2_api" "test" { `, rName) } -func testAccAPIWebSocketDataSourceConfig(rName string) string { +func testAccAPIDataSourceConfig_webSocket(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { api_key_selection_expression = "$context.authorizer.usageIdentifierKey" diff --git a/internal/service/apigatewayv2/api_mapping_test.go b/internal/service/apigatewayv2/api_mapping_test.go index c1f6198a982..2646a1b2053 100644 --- a/internal/service/apigatewayv2/api_mapping_test.go +++ b/internal/service/apigatewayv2/api_mapping_test.go @@ -34,7 +34,7 @@ func TestAccAPIGatewayV2APIMapping_basic(t *testing.T) { testCases := map[string]func(t *testing.T, rName string, certificateArn *string){ "basic": testAccAPIMapping_basic, "disappears": testAccAPIMapping_disappears, - "ApiMappingKey": testAccAPIMapping_ApiMappingKey, + "ApiMappingKey": testAccAPIMapping_key, } for name, tc := range testCases { tc := tc @@ -51,7 +51,7 @@ func testAccAPIMapping_createCertificate(t *testing.T, rName string, certificate ProviderFactories: acctest.ProviderFactories, CheckDestroy: nil, Steps: []resource.TestStep{ - { + { // nosemgrep:test-config-funcs-correct-form Config: "# Dummy config.", Check: resource.ComposeTestCheckFunc( testAccCheckAPIMappingCreateCertificate(rName, certificateArn), @@ -116,7 +116,7 @@ func testAccAPIMapping_disappears(t *testing.T, rName string, certificateArn *st }) } -func testAccAPIMapping_ApiMappingKey(t *testing.T, rName string, certificateArn *string) { +func testAccAPIMapping_key(t *testing.T, rName string, certificateArn *string) { var domainName string var v apigatewayv2.GetApiMappingOutput resourceName := "aws_apigatewayv2_api_mapping.test" @@ -130,7 +130,7 @@ func testAccAPIMapping_ApiMappingKey(t *testing.T, rName string, certificateArn CheckDestroy: testAccCheckAPIMappingDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIMappingConfig_apiMappingKey(rName, *certificateArn, "$context.domainName"), + Config: testAccAPIMappingConfig_key(rName, *certificateArn, "$context.domainName"), Check: resource.ComposeTestCheckFunc( testAccCheckAPIMappingExists(resourceName, &domainName, &v), resource.TestCheckResourceAttr(resourceName, "api_mapping_key", "$context.domainName"), @@ -138,7 +138,7 @@ func testAccAPIMapping_ApiMappingKey(t *testing.T, rName string, certificateArn resource.TestCheckResourceAttrPair(resourceName, "stage", stageResourceName, "name")), }, { - Config: testAccAPIMappingConfig_apiMappingKey(rName, *certificateArn, "$context.apiId"), + Config: testAccAPIMappingConfig_key(rName, *certificateArn, "$context.apiId"), Check: resource.ComposeTestCheckFunc( testAccCheckAPIMappingExists(resourceName, &domainName, &v), resource.TestCheckResourceAttr(resourceName, "api_mapping_key", "$context.apiId"), @@ -281,7 +281,7 @@ resource "aws_apigatewayv2_api_mapping" "test" { ` } -func testAccAPIMappingConfig_apiMappingKey(rName, certificateArn, apiMappingKey string) string { +func testAccAPIMappingConfig_key(rName, certificateArn, apiMappingKey string) string { return testAccAPIMappingConfig_base(rName, certificateArn) + testAccStageConfig_basicWebSocket(rName) + fmt.Sprintf(` resource "aws_apigatewayv2_api_mapping" "test" { api_id = aws_apigatewayv2_api.test.id diff --git a/internal/service/apigatewayv2/api_test.go b/internal/service/apigatewayv2/api_test.go index 774b2af1f29..0b5d4c98bc0 100644 --- a/internal/service/apigatewayv2/api_test.go +++ b/internal/service/apigatewayv2/api_test.go @@ -291,7 +291,7 @@ func TestAccAPIGatewayV2API_openAPI(t *testing.T) { CheckDestroy: testAccCheckAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIConfig_OpenAPI(rName), + Config: testAccAPIConfig_open(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAPIExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "api_endpoint"), @@ -311,7 +311,7 @@ func TestAccAPIGatewayV2API_openAPI(t *testing.T) { ImportStateVerifyIgnore: []string{"body"}, }, { - Config: testAccAPIConfig_UpdatedOpenAPIYAML(rName), + Config: testAccAPIConfig_updatedOpenYAML(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "description", ""), resource.TestCheckResourceAttr(resourceName, "disable_execute_api_endpoint", "false"), @@ -338,7 +338,7 @@ func TestAccAPIGatewayV2API_OpenAPI_withTags(t *testing.T) { CheckDestroy: testAccCheckAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIConfig_OpenAPIYAML_tags(rName), + Config: testAccAPIConfig_openYAMLTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAPIExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "api_endpoint"), @@ -357,7 +357,7 @@ func TestAccAPIGatewayV2API_OpenAPI_withTags(t *testing.T) { ImportStateVerifyIgnore: []string{"body"}, }, { - Config: testAccAPIConfig_OpenAPIYAML_tagsUpdated(rName), + Config: testAccAPIConfig_openYAMLTagsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAPIExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "protocol_type", apigatewayv2.ProtocolTypeHttp), @@ -383,7 +383,7 @@ func TestAccAPIGatewayV2API_OpenAPI_withCors(t *testing.T) { CheckDestroy: testAccCheckAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIConfig_OpenAPIYAML_corsConfiguration(rName), + Config: testAccAPIConfig_openYAMLCorsConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAPIExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "api_endpoint"), @@ -402,7 +402,7 @@ func TestAccAPIGatewayV2API_OpenAPI_withCors(t *testing.T) { ImportStateVerifyIgnore: []string{"body"}, }, { - Config: testAccAPIConfig_OpenAPIYAML_corsConfigurationUpdated(rName), + Config: testAccAPIConfig_openYAMLCorsConfigurationUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAPIExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "protocol_type", apigatewayv2.ProtocolTypeHttp), @@ -411,7 +411,7 @@ func TestAccAPIGatewayV2API_OpenAPI_withCors(t *testing.T) { ), }, { - Config: testAccAPIConfig_OpenAPIYAML_corsConfigurationUpdated2(rName), + Config: testAccAPIConfig_openYAMLCorsConfigurationUpdated2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAPIExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "protocol_type", apigatewayv2.ProtocolTypeHttp), @@ -440,7 +440,7 @@ func TestAccAPIGatewayV2API_OpenAPI_withMoreFields(t *testing.T) { CheckDestroy: testAccCheckAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIConfig_OpenAPIYAML(rName), + Config: testAccAPIConfig_openYAML(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAPIExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "api_endpoint"), @@ -460,7 +460,7 @@ func TestAccAPIGatewayV2API_OpenAPI_withMoreFields(t *testing.T) { ImportStateVerifyIgnore: []string{"body"}, }, { - Config: testAccAPIConfig_UpdatedOpenAPI2(rName), + Config: testAccAPIConfig_updatedOpen2(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "description", "description test"), resource.TestCheckResourceAttr(resourceName, "disable_execute_api_endpoint", "false"), @@ -494,12 +494,12 @@ func TestAccAPIGatewayV2API_OpenAPI_failOnWarnings(t *testing.T) { Steps: []resource.TestStep{ // Invalid body should not be accepted when fail_on_warnings is enabled { - Config: testAccAPIConfig_FailOnWarnings(rName, "fail_on_warnings = true"), + Config: testAccAPIConfig_failOnWarnings(rName, "fail_on_warnings = true"), ExpectError: regexp.MustCompile(`BadRequestException: Warnings found during import`), }, // Warnings do not break the deployment when fail_on_warnings is disabled { - Config: testAccAPIConfig_FailOnWarnings(rName, "fail_on_warnings = false"), + Config: testAccAPIConfig_failOnWarnings(rName, "fail_on_warnings = false"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", rName), testAccCheckAPIExists(resourceName, &v), @@ -516,7 +516,7 @@ func TestAccAPIGatewayV2API_OpenAPI_failOnWarnings(t *testing.T) { }, // fail_on_warnings should be optional and false by default { - Config: testAccAPIConfig_FailOnWarnings(rName, ""), + Config: testAccAPIConfig_failOnWarnings(rName, ""), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", rName), testAccCheckAPIExists(resourceName, &v), @@ -1007,7 +1007,7 @@ resource "aws_apigatewayv2_api" "test" { `, rName) } -func testAccAPIConfig_OpenAPI(rName string) string { +func testAccAPIConfig_open(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = "%s" @@ -1037,7 +1037,7 @@ EOF `, rName, rName) } -func testAccAPIConfig_OpenAPIYAML(rName string) string { +func testAccAPIConfig_openYAML(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = "%s" @@ -1061,7 +1061,7 @@ EOF `, rName, rName) } -func testAccAPIConfig_OpenAPIYAML_corsConfiguration(rName string) string { +func testAccAPIConfig_openYAMLCorsConfiguration(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = "%s" @@ -1094,7 +1094,7 @@ EOF `, rName, rName) } -func testAccAPIConfig_OpenAPIYAML_corsConfigurationUpdated(rName string) string { +func testAccAPIConfig_openYAMLCorsConfigurationUpdated(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = "%s" @@ -1123,7 +1123,7 @@ EOF `, rName, rName) } -func testAccAPIConfig_OpenAPIYAML_corsConfigurationUpdated2(rName string) string { +func testAccAPIConfig_openYAMLCorsConfigurationUpdated2(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = "%s" @@ -1156,7 +1156,7 @@ EOF `, rName, rName) } -func testAccAPIConfig_OpenAPIYAML_tags(rName string) string { +func testAccAPIConfig_openYAMLTags(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = "%s" @@ -1187,7 +1187,7 @@ EOF `, rName, rName) } -func testAccAPIConfig_OpenAPIYAML_tagsUpdated(rName string) string { +func testAccAPIConfig_openYAMLTagsUpdated(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = "%s" @@ -1220,7 +1220,7 @@ EOF `, rName, rName) } -func testAccAPIConfig_UpdatedOpenAPIYAML(rName string) string { +func testAccAPIConfig_updatedOpenYAML(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = "%s" @@ -1244,7 +1244,7 @@ EOF `, rName, rName) } -func testAccAPIConfig_UpdatedOpenAPI2(rName string) string { +func testAccAPIConfig_updatedOpen2(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = "%s" @@ -1277,7 +1277,7 @@ EOF `, rName, rName) } -func testAccAPIConfig_FailOnWarnings(rName string, failOnWarnings string) string { +func testAccAPIConfig_failOnWarnings(rName string, failOnWarnings string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = %[1]q diff --git a/internal/service/apigatewayv2/apis_data_source_test.go b/internal/service/apigatewayv2/apis_data_source_test.go index 6f562bd7aa5..ca7fc12c781 100644 --- a/internal/service/apigatewayv2/apis_data_source_test.go +++ b/internal/service/apigatewayv2/apis_data_source_test.go @@ -23,7 +23,7 @@ func TestAccAPIGatewayV2APIsDataSource_name(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccAPIsNameDataSourceConfig(rName1, rName2), + Config: testAccAPIsDataSourceConfig_name(rName1, rName2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSource1Name, "ids.#", "1"), resource.TestCheckResourceAttr(dataSource2Name, "ids.#", "2"), @@ -46,7 +46,7 @@ func TestAccAPIGatewayV2APIsDataSource_protocolType(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccAPIsProtocolTypeDataSourceConfig(rName1, rName2), + Config: testAccAPIsDataSourceConfig_protocolType(rName1, rName2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSource1Name, "ids.#", "1"), resource.TestCheckResourceAttr(dataSource2Name, "ids.#", "1"), @@ -70,7 +70,7 @@ func TestAccAPIGatewayV2APIsDataSource_tags(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccAPIsTagsDataSourceConfig(rName1, rName2), + Config: testAccAPIsDataSourceConfig_tags(rName1, rName2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSource1Name, "ids.#", "1"), resource.TestCheckResourceAttr(dataSource2Name, "ids.#", "2"), @@ -113,7 +113,7 @@ resource "aws_apigatewayv2_api" "test3" { `, rName1, rName2) } -func testAccAPIsNameDataSourceConfig(rName1, rName2 string) string { +func testAccAPIsDataSourceConfig_name(rName1, rName2 string) string { return acctest.ConfigCompose( testAccAPIsBaseDataSourceConfig(rName1, rName2), ` @@ -129,7 +129,7 @@ data "aws_apigatewayv2_apis" "test2" { `) } -func testAccAPIsProtocolTypeDataSourceConfig(rName1, rName2 string) string { +func testAccAPIsDataSourceConfig_protocolType(rName1, rName2 string) string { return acctest.ConfigCompose( testAccAPIsBaseDataSourceConfig(rName1, rName2), fmt.Sprintf(` @@ -147,7 +147,7 @@ data "aws_apigatewayv2_apis" "test2" { `, rName1, rName2)) } -func testAccAPIsTagsDataSourceConfig(rName1, rName2 string) string { +func testAccAPIsDataSourceConfig_tags(rName1, rName2 string) string { return acctest.ConfigCompose( testAccAPIsBaseDataSourceConfig(rName1, rName2), ` diff --git a/internal/service/apigatewayv2/authorizer.go b/internal/service/apigatewayv2/authorizer.go index 940f0e4a525..1fc52824c4a 100644 --- a/internal/service/apigatewayv2/authorizer.go +++ b/internal/service/apigatewayv2/authorizer.go @@ -134,7 +134,7 @@ func resourceAuthorizerCreate(d *schema.ResourceData, meta interface{}) error { req.EnableSimpleResponses = aws.Bool(v.(bool)) } if v, ok := d.GetOk("jwt_configuration"); ok { - req.JwtConfiguration = expandApiGateway2JwtConfiguration(v.([]interface{})) + req.JwtConfiguration = expandJWTConfiguration(v.([]interface{})) } log.Printf("[DEBUG] Creating API Gateway v2 authorizer: %s", req) @@ -173,7 +173,7 @@ func resourceAuthorizerRead(d *schema.ResourceData, meta interface{}) error { if err := d.Set("identity_sources", flex.FlattenStringSet(resp.IdentitySource)); err != nil { return fmt.Errorf("error setting identity_sources: %s", err) } - if err := d.Set("jwt_configuration", flattenApiGateway2JwtConfiguration(resp.JwtConfiguration)); err != nil { + if err := d.Set("jwt_configuration", flattenJWTConfiguration(resp.JwtConfiguration)); err != nil { return fmt.Errorf("error setting jwt_configuration: %s", err) } d.Set("name", resp.Name) @@ -213,7 +213,7 @@ func resourceAuthorizerUpdate(d *schema.ResourceData, meta interface{}) error { req.Name = aws.String(d.Get("name").(string)) } if d.HasChange("jwt_configuration") { - req.JwtConfiguration = expandApiGateway2JwtConfiguration(d.Get("jwt_configuration").([]interface{})) + req.JwtConfiguration = expandJWTConfiguration(d.Get("jwt_configuration").([]interface{})) } log.Printf("[DEBUG] Updating API Gateway v2 authorizer: %s", req) @@ -255,7 +255,7 @@ func resourceAuthorizerImport(d *schema.ResourceData, meta interface{}) ([]*sche return []*schema.ResourceData{d}, nil } -func expandApiGateway2JwtConfiguration(vConfiguration []interface{}) *apigatewayv2.JWTConfiguration { +func expandJWTConfiguration(vConfiguration []interface{}) *apigatewayv2.JWTConfiguration { configuration := &apigatewayv2.JWTConfiguration{} if len(vConfiguration) == 0 || vConfiguration[0] == nil { @@ -273,7 +273,7 @@ func expandApiGateway2JwtConfiguration(vConfiguration []interface{}) *apigateway return configuration } -func flattenApiGateway2JwtConfiguration(configuration *apigatewayv2.JWTConfiguration) []interface{} { +func flattenJWTConfiguration(configuration *apigatewayv2.JWTConfiguration) []interface{} { if configuration == nil { return []interface{}{} } diff --git a/internal/service/apigatewayv2/authorizer_test.go b/internal/service/apigatewayv2/authorizer_test.go index 55a11e72766..c905be9d241 100644 --- a/internal/service/apigatewayv2/authorizer_test.go +++ b/internal/service/apigatewayv2/authorizer_test.go @@ -222,7 +222,7 @@ func TestAccAPIGatewayV2Authorizer_HTTPAPILambdaRequestAuthorizer_initialMissing CheckDestroy: testAccCheckAuthorizerDestroy, Steps: []resource.TestStep{ { - Config: testAccAuthorizerConfig_httpAPILambdaRequestAuthorizer(rName), + Config: testAccAuthorizerConfig_httpAPILambdaRequest(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAuthorizerExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "authorizer_credentials_arn", ""), @@ -244,7 +244,7 @@ func TestAccAPIGatewayV2Authorizer_HTTPAPILambdaRequestAuthorizer_initialMissing ImportStateVerify: true, }, { - Config: testAccAuthorizerConfig_httpAPILambdaRequestAuthorizerUpdated(rName, 3600), + Config: testAccAuthorizerConfig_httpAPILambdaRequestUpdated(rName, 3600), Check: resource.ComposeTestCheckFunc( testAccCheckAuthorizerExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "authorizer_credentials_arn", ""), @@ -261,7 +261,7 @@ func TestAccAPIGatewayV2Authorizer_HTTPAPILambdaRequestAuthorizer_initialMissing ), }, { - Config: testAccAuthorizerConfig_httpAPILambdaRequestAuthorizerUpdated(rName, 0), + Config: testAccAuthorizerConfig_httpAPILambdaRequestUpdated(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckAuthorizerExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "authorizer_credentials_arn", ""), @@ -295,7 +295,7 @@ func TestAccAPIGatewayV2Authorizer_HTTPAPILambdaRequestAuthorizer_initialZeroCac CheckDestroy: testAccCheckAuthorizerDestroy, Steps: []resource.TestStep{ { - Config: testAccAuthorizerConfig_httpAPILambdaRequestAuthorizerUpdated(rName, 0), + Config: testAccAuthorizerConfig_httpAPILambdaRequestUpdated(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckAuthorizerExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "authorizer_credentials_arn", ""), @@ -318,7 +318,7 @@ func TestAccAPIGatewayV2Authorizer_HTTPAPILambdaRequestAuthorizer_initialZeroCac ImportStateVerify: true, }, { - Config: testAccAuthorizerConfig_httpAPILambdaRequestAuthorizerUpdated(rName, 600), + Config: testAccAuthorizerConfig_httpAPILambdaRequestUpdated(rName, 600), Check: resource.ComposeTestCheckFunc( testAccCheckAuthorizerExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "authorizer_credentials_arn", ""), @@ -544,7 +544,7 @@ resource "aws_apigatewayv2_authorizer" "test" { `, rName)) } -func testAccAuthorizerConfig_httpAPILambdaRequestAuthorizer(rName string) string { +func testAccAuthorizerConfig_httpAPILambdaRequest(rName string) string { return acctest.ConfigCompose( testAccAuthorizerConfig_apiHTTP(rName), testAccAuthorizerConfig_baseLambda(rName), @@ -561,7 +561,7 @@ resource "aws_apigatewayv2_authorizer" "test" { `, rName)) } -func testAccAuthorizerConfig_httpAPILambdaRequestAuthorizerUpdated(rName string, authorizerResultTtl int) string { +func testAccAuthorizerConfig_httpAPILambdaRequestUpdated(rName string, authorizerResultTtl int) string { return acctest.ConfigCompose( testAccAuthorizerConfig_apiHTTP(rName), testAccAuthorizerConfig_baseLambda(rName), diff --git a/internal/service/apigatewayv2/deployment_test.go b/internal/service/apigatewayv2/deployment_test.go index 5f407a1f330..b97530a1d18 100644 --- a/internal/service/apigatewayv2/deployment_test.go +++ b/internal/service/apigatewayv2/deployment_test.go @@ -89,7 +89,7 @@ func TestAccAPIGatewayV2Deployment_triggers(t *testing.T) { CheckDestroy: testAccCheckDeploymentDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentTriggersConfig(rName, false), + Config: testAccDeploymentConfig_triggers(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &apiId, &deployment1), ), @@ -98,14 +98,14 @@ func TestAccAPIGatewayV2Deployment_triggers(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: testAccDeploymentTriggersConfig(rName, false), + Config: testAccDeploymentConfig_triggers(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &apiId, &deployment2), testAccCheckDeploymentRecreated(&deployment1, &deployment2), ), }, { - Config: testAccDeploymentTriggersConfig(rName, false), + Config: testAccDeploymentConfig_triggers(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &apiId, &deployment3), testAccCheckDeploymentNotRecreated(&deployment2, &deployment3), @@ -119,7 +119,7 @@ func TestAccAPIGatewayV2Deployment_triggers(t *testing.T) { ImportStateVerifyIgnore: []string{"triggers"}, }, { - Config: testAccDeploymentTriggersConfig(rName, true), + Config: testAccDeploymentConfig_triggers(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName, &apiId, &deployment4), testAccCheckDeploymentRecreated(&deployment3, &deployment4), @@ -238,7 +238,7 @@ resource "aws_apigatewayv2_deployment" "test" { `, description) } -func testAccDeploymentTriggersConfig(rName string, apiKeyRequired bool) string { +func testAccDeploymentConfig_triggers(rName string, apiKeyRequired bool) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = %[1]q diff --git a/internal/service/apigatewayv2/domain_name_test.go b/internal/service/apigatewayv2/domain_name_test.go index f23d5f9a42c..f329a7a0fe4 100644 --- a/internal/service/apigatewayv2/domain_name_test.go +++ b/internal/service/apigatewayv2/domain_name_test.go @@ -231,7 +231,7 @@ func TestAccAPIGatewayV2DomainName_MutualTLSAuthentication_basic(t *testing.T) { CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameMututalTLSAuthenticationObjectVersionConfig(rName, rootDomain, domain), + Config: testAccDomainNameConfig_mutualTLSAuthenticationObjectVersion(rName, rootDomain, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &v), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/domainnames/.+`)), @@ -249,7 +249,7 @@ func TestAccAPIGatewayV2DomainName_MutualTLSAuthentication_basic(t *testing.T) { ), }, { - Config: testAccDomainNameMututalTLSAuthenticationObjectVersionConfig(rName, rootDomain, domain), + Config: testAccDomainNameConfig_mutualTLSAuthenticationObjectVersion(rName, rootDomain, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &v), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/domainnames/.+`)), @@ -273,7 +273,7 @@ func TestAccAPIGatewayV2DomainName_MutualTLSAuthentication_basic(t *testing.T) { }, // Test disabling mutual TLS authentication. { - Config: testAccDomainNameMututalTLSAuthenticationMissingConfig(rootDomain, domain), + Config: testAccDomainNameConfig_mutualTLSAuthenticationMissing(rootDomain, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &v), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/domainnames/.+`)), @@ -308,7 +308,7 @@ func TestAccAPIGatewayV2DomainName_MutualTLSAuthentication_noVersion(t *testing. CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameMututalTLSAuthenticationNoObjectVersionConfig(rName, rootDomain, domain), + Config: testAccDomainNameConfig_mutualTLSAuthenticationNoObjectVersion(rName, rootDomain, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &v), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/domainnames/.+`)), @@ -349,7 +349,7 @@ func TestAccAPIGatewayV2DomainName_MutualTLSAuthentication_ownership(t *testing. CheckDestroy: testAccCheckDomainNameDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainNameConfigMututalTLSAuthenticationOwnershipVerificationCert(rName, rootDomain, domain, certificate, key), + Config: testAccDomainNameConfig_mutualTLSAuthenticationOwnershipVerificationCert(rName, rootDomain, domain, certificate, key), Check: resource.ComposeTestCheckFunc( testAccCheckDomainNameExists(resourceName, &v), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/domainnames/+.`)), @@ -525,7 +525,7 @@ resource "aws_apigatewayv2_domain_name" "test" { `, rName, index)) } -func testAccDomainNameMututalTLSAuthenticationNoObjectVersionConfig(rName, rootDomain, domain string) string { +func testAccDomainNameConfig_mutualTLSAuthenticationNoObjectVersion(rName, rootDomain, domain string) string { return acctest.ConfigCompose( testAccDomainNamePublicCertConfig(rootDomain, domain), fmt.Sprintf(` @@ -557,7 +557,7 @@ resource "aws_apigatewayv2_domain_name" "test" { `, rName)) } -func testAccDomainNameMututalTLSAuthenticationObjectVersionConfig(rName, rootDomain, domain string) string { +func testAccDomainNameConfig_mutualTLSAuthenticationObjectVersion(rName, rootDomain, domain string) string { return acctest.ConfigCompose( testAccDomainNamePublicCertConfig(rootDomain, domain), fmt.Sprintf(` @@ -597,7 +597,7 @@ resource "aws_apigatewayv2_domain_name" "test" { `, rName)) } -func testAccDomainNameMututalTLSAuthenticationMissingConfig(rootDomain, domain string) string { +func testAccDomainNameConfig_mutualTLSAuthenticationMissing(rootDomain, domain string) string { return acctest.ConfigCompose( testAccDomainNamePublicCertConfig(rootDomain, domain), ` @@ -613,7 +613,7 @@ resource "aws_apigatewayv2_domain_name" "test" { `) } -func testAccDomainNameConfigMututalTLSAuthenticationOwnershipVerificationCert(rName, rootDomain, domain, certificate, key string) string { +func testAccDomainNameConfig_mutualTLSAuthenticationOwnershipVerificationCert(rName, rootDomain, domain, certificate, key string) string { return acctest.ConfigCompose( testAccDomainNamePublicCertConfig(rootDomain, domain), fmt.Sprintf(` diff --git a/internal/service/apigatewayv2/export_data_source_test.go b/internal/service/apigatewayv2/export_data_source_test.go index 15a858a8e66..6ce9820b096 100644 --- a/internal/service/apigatewayv2/export_data_source_test.go +++ b/internal/service/apigatewayv2/export_data_source_test.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" ) -func TestAccExportGatewayV2ExportDataSource_basic(t *testing.T) { +func TestAccAPIGatewayV2ExportDataSource_basic(t *testing.T) { dataSourceName := "data.aws_apigatewayv2_export.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -21,7 +21,7 @@ func TestAccExportGatewayV2ExportDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccExportHTTPDataSourceBasicConfig(rName), + Config: testAccExportDataSourceConfig_httpBasic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "api_id", "aws_apigatewayv2_route.test", "api_id"), resource.TestCheckResourceAttrSet(dataSourceName, "body"), @@ -31,7 +31,7 @@ func TestAccExportGatewayV2ExportDataSource_basic(t *testing.T) { }) } -func TestAccExportGatewayV2ExportDataSource_stage(t *testing.T) { +func TestAccAPIGatewayV2ExportDataSource_stage(t *testing.T) { dataSourceName := "data.aws_apigatewayv2_export.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -42,7 +42,7 @@ func TestAccExportGatewayV2ExportDataSource_stage(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccExportHTTPDataSourceStageConfig(rName), + Config: testAccExportDataSourceConfig_httpStage(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "api_id", "aws_apigatewayv2_route.test", "api_id"), resource.TestCheckResourceAttrPair(dataSourceName, "stage_name", "aws_apigatewayv2_stage.test", "name"), @@ -76,7 +76,7 @@ resource "aws_apigatewayv2_route" "test" { `, rName) } -func testAccExportHTTPDataSourceBasicConfig(rName string) string { +func testAccExportDataSourceConfig_httpBasic(rName string) string { return acctest.ConfigCompose(testAccExportHTTPDataSourceConfigBase(rName), ` data "aws_apigatewayv2_export" "test" { api_id = aws_apigatewayv2_route.test.api_id @@ -86,7 +86,7 @@ data "aws_apigatewayv2_export" "test" { `) } -func testAccExportHTTPDataSourceStageConfig(rName string) string { +func testAccExportDataSourceConfig_httpStage(rName string) string { return acctest.ConfigCompose(testAccExportHTTPDataSourceConfigBase(rName), fmt.Sprintf(` resource "aws_apigatewayv2_stage" "test" { api_id = aws_apigatewayv2_deployment.test.api_id diff --git a/internal/service/apigatewayv2/integration.go b/internal/service/apigatewayv2/integration.go index 1965e34f9f0..67709059067 100644 --- a/internal/service/apigatewayv2/integration.go +++ b/internal/service/apigatewayv2/integration.go @@ -213,7 +213,7 @@ func resourceIntegrationCreate(d *schema.ResourceData, meta interface{}) error { req.RequestTemplates = flex.ExpandStringMap(v.(map[string]interface{})) } if v, ok := d.GetOk("response_parameters"); ok && v.(*schema.Set).Len() > 0 { - req.ResponseParameters = expandApiGateway2IntegrationResponseParameters(v.(*schema.Set).List()) + req.ResponseParameters = expandIntegrationResponseParameters(v.(*schema.Set).List()) } if v, ok := d.GetOk("template_selection_expression"); ok { req.TemplateSelectionExpression = aws.String(v.(string)) @@ -222,7 +222,7 @@ func resourceIntegrationCreate(d *schema.ResourceData, meta interface{}) error { req.TimeoutInMillis = aws.Int64(int64(v.(int))) } if v, ok := d.GetOk("tls_config"); ok { - req.TlsConfig = expandApiGateway2TlsConfig(v.([]interface{})) + req.TlsConfig = expandTLSConfig(v.([]interface{})) } log.Printf("[DEBUG] Creating API Gateway v2 integration: %s", req) @@ -272,13 +272,13 @@ func resourceIntegrationRead(d *schema.ResourceData, meta interface{}) error { if err != nil { return fmt.Errorf("error setting request_templates: %s", err) } - err = d.Set("response_parameters", flattenApiGateway2IntegrationResponseParameters(resp.ResponseParameters)) + err = d.Set("response_parameters", flattenIntegrationResponseParameters(resp.ResponseParameters)) if err != nil { return fmt.Errorf("error setting response_parameters: %s", err) } d.Set("template_selection_expression", resp.TemplateSelectionExpression) d.Set("timeout_milliseconds", resp.TimeoutInMillis) - if err := d.Set("tls_config", flattenApiGateway2TlsConfig(resp.TlsConfig)); err != nil { + if err := d.Set("tls_config", flattenTLSConfig(resp.TlsConfig)); err != nil { return fmt.Errorf("error setting tls_config: %s", err) } @@ -354,7 +354,7 @@ func resourceIntegrationUpdate(d *schema.ResourceData, meta interface{}) error { ns := n.(*schema.Set) del := os.Difference(ns).List() - req.ResponseParameters = expandApiGateway2IntegrationResponseParameters(ns.List()) + req.ResponseParameters = expandIntegrationResponseParameters(ns.List()) // Parameters are removed by setting the associated value to {}. for _, tfMapRaw := range del { @@ -379,7 +379,7 @@ func resourceIntegrationUpdate(d *schema.ResourceData, meta interface{}) error { req.TimeoutInMillis = aws.Int64(int64(d.Get("timeout_milliseconds").(int))) } if d.HasChange("tls_config") { - req.TlsConfig = expandApiGateway2TlsConfig(d.Get("tls_config").([]interface{})) + req.TlsConfig = expandTLSConfig(d.Get("tls_config").([]interface{})) } log.Printf("[DEBUG] Updating API Gateway v2 integration: %s", req) @@ -438,7 +438,7 @@ func resourceIntegrationImport(d *schema.ResourceData, meta interface{}) ([]*sch return []*schema.ResourceData{d}, nil } -func expandApiGateway2TlsConfig(vConfig []interface{}) *apigatewayv2.TlsConfigInput { +func expandTLSConfig(vConfig []interface{}) *apigatewayv2.TlsConfigInput { config := &apigatewayv2.TlsConfigInput{} if len(vConfig) == 0 || vConfig[0] == nil { @@ -453,7 +453,7 @@ func expandApiGateway2TlsConfig(vConfig []interface{}) *apigatewayv2.TlsConfigIn return config } -func flattenApiGateway2TlsConfig(config *apigatewayv2.TlsConfig) []interface{} { +func flattenTLSConfig(config *apigatewayv2.TlsConfig) []interface{} { if config == nil { return []interface{}{} } @@ -463,7 +463,7 @@ func flattenApiGateway2TlsConfig(config *apigatewayv2.TlsConfig) []interface{} { }} } -func expandApiGateway2IntegrationResponseParameters(tfList []interface{}) map[string]map[string]*string { +func expandIntegrationResponseParameters(tfList []interface{}) map[string]map[string]*string { if len(tfList) == 0 { return nil } @@ -487,7 +487,7 @@ func expandApiGateway2IntegrationResponseParameters(tfList []interface{}) map[st return responseParameters } -func flattenApiGateway2IntegrationResponseParameters(responseParameters map[string]map[string]*string) []interface{} { +func flattenIntegrationResponseParameters(responseParameters map[string]map[string]*string) []interface{} { if len(responseParameters) == 0 { return nil } diff --git a/internal/service/apigatewayv2/integration_test.go b/internal/service/apigatewayv2/integration_test.go index 17cc8093dd6..6f787bbd01e 100644 --- a/internal/service/apigatewayv2/integration_test.go +++ b/internal/service/apigatewayv2/integration_test.go @@ -234,7 +234,7 @@ func TestAccAPIGatewayV2Integration_integrationTypeHTTP(t *testing.T) { CheckDestroy: testAccCheckIntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationConfig_integrationTypeHTTP(rName), + Config: testAccIntegrationConfig_typeHTTP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "connection_id", ""), @@ -260,7 +260,7 @@ func TestAccAPIGatewayV2Integration_integrationTypeHTTP(t *testing.T) { ), }, { - Config: testAccIntegrationConfig_integrationTypeHTTPUpdated(rName), + Config: testAccIntegrationConfig_typeHTTPUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "connection_id", ""), @@ -516,7 +516,7 @@ func TestAccAPIGatewayV2Integration_vpcLinkHTTP(t *testing.T) { }) } -func TestAccAPIGatewayV2Integration_awsServiceIntegration(t *testing.T) { +func TestAccAPIGatewayV2Integration_serviceIntegration(t *testing.T) { var apiId string var v apigatewayv2.GetIntegrationOutput resourceName := "aws_apigatewayv2_integration.test" @@ -532,7 +532,7 @@ func TestAccAPIGatewayV2Integration_awsServiceIntegration(t *testing.T) { CheckDestroy: testAccCheckIntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccIntegrationConfig_sqsIntegration(rName, 0), + Config: testAccIntegrationConfig_sqs(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "connection_type", "INTERNET"), @@ -558,7 +558,7 @@ func TestAccAPIGatewayV2Integration_awsServiceIntegration(t *testing.T) { ), }, { - Config: testAccIntegrationConfig_sqsIntegration(rName, 1), + Config: testAccIntegrationConfig_sqs(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckIntegrationExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "connection_type", "INTERNET"), @@ -859,7 +859,7 @@ resource "aws_apigatewayv2_integration" "test" { ` } -func testAccIntegrationConfig_integrationTypeHTTP(rName string) string { +func testAccIntegrationConfig_typeHTTP(rName string) string { return testAccIntegrationConfig_apiWebSocket(rName) + ` resource "aws_apigatewayv2_integration" "test" { api_id = aws_apigatewayv2_api.test.id @@ -885,7 +885,7 @@ resource "aws_apigatewayv2_integration" "test" { ` } -func testAccIntegrationConfig_integrationTypeHTTPUpdated(rName string) string { +func testAccIntegrationConfig_typeHTTPUpdated(rName string) string { return testAccIntegrationConfig_apiWebSocket(rName) + ` resource "aws_apigatewayv2_integration" "test" { api_id = aws_apigatewayv2_api.test.id @@ -1071,7 +1071,7 @@ resource "aws_apigatewayv2_integration" "test" { `, rName)) } -func testAccIntegrationConfig_sqsIntegration(rName string, queueIndex int) string { +func testAccIntegrationConfig_sqs(rName string, queueIndex int) string { return acctest.ConfigCompose( testAccIntegrationConfig_apiHTTP(rName), fmt.Sprintf(` diff --git a/internal/service/apigatewayv2/route_test.go b/internal/service/apigatewayv2/route_test.go index 4aa266b3e4d..2dc20fb7033 100644 --- a/internal/service/apigatewayv2/route_test.go +++ b/internal/service/apigatewayv2/route_test.go @@ -437,7 +437,7 @@ func TestAccAPIGatewayV2Route_updateRouteKey(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteConfig_routeKey(rName, "GET /path"), + Config: testAccRouteConfig_key(rName, "GET /path"), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "api_key_required", "false"), @@ -453,7 +453,7 @@ func TestAccAPIGatewayV2Route_updateRouteKey(t *testing.T) { ), }, { - Config: testAccRouteConfig_routeKey(rName, "POST /new/path"), + Config: testAccRouteConfig_key(rName, "POST /new/path"), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "api_key_required", "false"), @@ -721,7 +721,7 @@ resource "aws_apigatewayv2_route" "test" { `) } -func testAccRouteConfig_routeKey(rName, routeKey string) string { +func testAccRouteConfig_key(rName, routeKey string) string { return acctest.ConfigCompose( testAccRouteConfig_apiHTTP(rName), fmt.Sprintf(` diff --git a/internal/service/apigatewayv2/stage.go b/internal/service/apigatewayv2/stage.go index 97130910136..a859bdc2700 100644 --- a/internal/service/apigatewayv2/stage.go +++ b/internal/service/apigatewayv2/stage.go @@ -18,7 +18,7 @@ import ( ) const ( - apigatewayv2DefaultStageName = "$default" + defaultStageName = "$default" ) func ResourceStage() *schema.Resource { @@ -321,7 +321,7 @@ func resourceStageRead(d *schema.ResourceData, meta interface{}) error { case apigatewayv2.ProtocolTypeWebsocket: d.Set("invoke_url", fmt.Sprintf("wss://%s.execute-api.%s.amazonaws.com/%s", apiId, region, stageName)) case apigatewayv2.ProtocolTypeHttp: - if stageName == apigatewayv2DefaultStageName { + if stageName == defaultStageName { d.Set("invoke_url", fmt.Sprintf("https://%s.execute-api.%s.amazonaws.com/", apiId, region)) } else { d.Set("invoke_url", fmt.Sprintf("https://%s.execute-api.%s.amazonaws.com/%s", apiId, region, stageName)) diff --git a/internal/service/apigatewayv2/stage_test.go b/internal/service/apigatewayv2/stage_test.go index ea049c61e2e..c57dbf85d17 100644 --- a/internal/service/apigatewayv2/stage_test.go +++ b/internal/service/apigatewayv2/stage_test.go @@ -122,7 +122,7 @@ func TestAccAPIGatewayV2Stage_defaultHTTPStage(t *testing.T) { CheckDestroy: testAccCheckStageDestroy, Steps: []resource.TestStep{ { - Config: testAccStageConfig_defaultHTTPStage(rName), + Config: testAccStageConfig_defaultHTTP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), @@ -869,7 +869,7 @@ func TestAccAPIGatewayV2Stage_RouteSettingsHTTP_withRoute(t *testing.T) { CheckDestroy: testAccCheckStageDestroy, Steps: []resource.TestStep{ { - Config: testAccStageConfig_routeSettingsHTTPWithRoute(rName, "GET /first"), + Config: testAccStageConfig_routeSettingsHTTPRoute(rName, "GET /first"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), @@ -900,7 +900,7 @@ func TestAccAPIGatewayV2Stage_RouteSettingsHTTP_withRoute(t *testing.T) { ), }, { - Config: testAccStageConfig_routeSettingsHTTPWithRoute(rName, "POST /second"), + Config: testAccStageConfig_routeSettingsHTTPRoute(rName, "POST /second"), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), @@ -953,7 +953,7 @@ func TestAccAPIGatewayV2Stage_stageVariables(t *testing.T) { CheckDestroy: testAccCheckStageDestroy, Steps: []resource.TestStep{ { - Config: testAccStageConfig_stageVariables(rName), + Config: testAccStageConfig_variables(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), @@ -1196,7 +1196,7 @@ resource "aws_apigatewayv2_stage" "test" { `, rName)) } -func testAccStageConfig_defaultHTTPStage(rName string) string { +func testAccStageConfig_defaultHTTP(rName string) string { return acctest.ConfigCompose( testAccStageConfig_apiHTTP(rName), ` @@ -1455,7 +1455,7 @@ resource "aws_apigatewayv2_stage" "test" { `, rName)) } -func testAccStageConfig_routeSettingsHTTPWithRoute(rName, routeKey string) string { +func testAccStageConfig_routeSettingsHTTPRoute(rName, routeKey string) string { return acctest.ConfigCompose( testAccStageConfig_apiHTTP(rName), fmt.Sprintf(` @@ -1485,7 +1485,7 @@ resource "aws_apigatewayv2_integration" "test" { `, rName, routeKey)) } -func testAccStageConfig_stageVariables(rName string) string { +func testAccStageConfig_variables(rName string) string { return acctest.ConfigCompose( testAccStageConfig_apiWebSocket(rName), fmt.Sprintf(` diff --git a/internal/service/appautoscaling/policy.go b/internal/service/appautoscaling/policy.go index 6de704002bf..933078d068f 100644 --- a/internal/service/appautoscaling/policy.go +++ b/internal/service/appautoscaling/policy.go @@ -429,7 +429,7 @@ func ValidPolicyImportInput(id string) ([]string, error) { // Takes the result of flatmap.Expand for an array of step adjustments and // returns a []*applicationautoscaling.StepAdjustment. -func expandAppautoscalingStepAdjustments(configured []interface{}) ([]*applicationautoscaling.StepAdjustment, error) { +func expandStepAdjustments(configured []interface{}) ([]*applicationautoscaling.StepAdjustment, error) { var adjustments []*applicationautoscaling.StepAdjustment // Loop over our configured step adjustments and create an array @@ -479,7 +479,7 @@ func expandAppautoscalingStepAdjustments(configured []interface{}) ([]*applicati return adjustments, nil } -func expandAppautoscalingCustomizedMetricSpecification(configured []interface{}) *applicationautoscaling.CustomizedMetricSpecification { +func expandCustomizedMetricSpecification(configured []interface{}) *applicationautoscaling.CustomizedMetricSpecification { spec := &applicationautoscaling.CustomizedMetricSpecification{} for _, raw := range configured { @@ -515,7 +515,7 @@ func expandAppautoscalingCustomizedMetricSpecification(configured []interface{}) return spec } -func expandAppautoscalingPredefinedMetricSpecification(configured []interface{}) *applicationautoscaling.PredefinedMetricSpecification { +func expandPredefinedMetricSpecification(configured []interface{}) *applicationautoscaling.PredefinedMetricSpecification { spec := &applicationautoscaling.PredefinedMetricSpecification{} for _, raw := range configured { @@ -577,11 +577,11 @@ func getPutScalingPolicyInput(d *schema.ResourceData) (applicationautoscaling.Pu } if v, ok := ttspCfg["customized_metric_specification"].([]interface{}); ok && len(v) > 0 { - cfg.CustomizedMetricSpecification = expandAppautoscalingCustomizedMetricSpecification(v) + cfg.CustomizedMetricSpecification = expandCustomizedMetricSpecification(v) } if v, ok := ttspCfg["predefined_metric_specification"].([]interface{}); ok && len(v) > 0 { - cfg.PredefinedMetricSpecification = expandAppautoscalingPredefinedMetricSpecification(v) + cfg.PredefinedMetricSpecification = expandPredefinedMetricSpecification(v) } params.TargetTrackingScalingPolicyConfiguration = cfg @@ -633,7 +633,7 @@ func expandStepScalingPolicyConfiguration(cfg []interface{}) *applicationautosca out.MinAdjustmentMagnitude = aws.Int64(int64(v)) } if v, ok := m["step_adjustment"].(*schema.Set); ok && v.Len() > 0 { - out.StepAdjustments, _ = expandAppautoscalingStepAdjustments(v.List()) + out.StepAdjustments, _ = expandStepAdjustments(v.List()) } return out @@ -675,13 +675,13 @@ func flattenStepScalingPolicyConfiguration(cfg *applicationautoscaling.StepScali }, }, } - m["step_adjustment"] = schema.NewSet(schema.HashResource(stepAdjustmentsResource), flattenAppautoscalingStepAdjustments(cfg.StepAdjustments)) + m["step_adjustment"] = schema.NewSet(schema.HashResource(stepAdjustmentsResource), flattenStepAdjustments(cfg.StepAdjustments)) } return []interface{}{m} } -func flattenAppautoscalingStepAdjustments(adjs []*applicationautoscaling.StepAdjustment) []interface{} { +func flattenStepAdjustments(adjs []*applicationautoscaling.StepAdjustment) []interface{} { out := make([]interface{}, len(adjs)) for i, adj := range adjs { diff --git a/internal/service/appautoscaling/policy_test.go b/internal/service/appautoscaling/policy_test.go index 2a21825f8db..9dcf00f413d 100644 --- a/internal/service/appautoscaling/policy_test.go +++ b/internal/service/appautoscaling/policy_test.go @@ -17,7 +17,7 @@ import ( tfappautoscaling "github.com/hashicorp/terraform-provider-aws/internal/service/appautoscaling" ) -func TestValidateAppAutoScalingPolicyImportInput(t *testing.T) { +func TestValidatePolicyImportInput(t *testing.T) { testCases := []struct { input string errorExpected bool @@ -93,7 +93,7 @@ func TestAccAppAutoScalingPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig(rName), + Config: testAccPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -133,7 +133,7 @@ func TestAccAppAutoScalingPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig(rName), + Config: testAccPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), testAccCheckPolicyDisappears(&policy), @@ -157,7 +157,7 @@ func TestAccAppAutoScalingPolicy_scaleOutAndIn(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyScaleOutAndInConfig(randClusterName, randPolicyNamePrefix), + Config: testAccPolicyConfig_scaleOutAndIn(randClusterName, randPolicyNamePrefix), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists("aws_appautoscaling_policy.foobar_out", &policy), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.adjustment_type", "PercentChangeInCapacity"), @@ -238,7 +238,7 @@ func TestAccAppAutoScalingPolicy_spotFleetRequest(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicySpotFleetRequestConfig(randPolicyName, validUntil), + Config: testAccPolicyConfig_spotFleetRequest(randPolicyName, validUntil), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists("aws_appautoscaling_policy.test", &policy), resource.TestCheckResourceAttr("aws_appautoscaling_policy.test", "name", randPolicyName), @@ -270,7 +270,7 @@ func TestAccAppAutoScalingPolicy_DynamoDB_table(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyDynamoDB(randPolicyName), + Config: testAccPolicyConfig_dynamoDB(randPolicyName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists("aws_appautoscaling_policy.dynamo_test", &policy), resource.TestCheckResourceAttr("aws_appautoscaling_policy.dynamo_test", "name", fmt.Sprintf("DynamoDBWriteCapacityUtilization:table/%s", randPolicyName)), @@ -302,7 +302,7 @@ func TestAccAppAutoScalingPolicy_DynamoDB_index(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyDynamoDBIndex(rName), + Config: testAccPolicyConfig_dynamoDBIndex(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("DynamoDBWriteCapacityUtilization:table/%s/index/GameTitleIndex", rName)), @@ -336,7 +336,7 @@ func TestAccAppAutoScalingPolicy_multiplePoliciesSameName(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicy_multiplePoliciesSameName(tableName1, tableName2, namePrefix), + Config: testAccPolicyConfig_multiplePoliciesSameName(tableName1, tableName2, namePrefix), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists("aws_appautoscaling_policy.read1", &readPolicy1), resource.TestCheckResourceAttr("aws_appautoscaling_policy.read1", "name", namePrefix+"-read"), @@ -369,7 +369,7 @@ func TestAccAppAutoScalingPolicy_multiplePoliciesSameResource(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicy_multiplePoliciesSameResource(tableName, namePrefix), + Config: testAccPolicyConfig_multiplePoliciesSameResource(tableName, namePrefix), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists("aws_appautoscaling_policy.read", &readPolicy), resource.TestCheckResourceAttr("aws_appautoscaling_policy.read", "name", namePrefix+"-read"), @@ -414,7 +414,7 @@ func TestAccAppAutoScalingPolicy_ResourceID_forceNew(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyResourceIdForceNew1Config(rName), + Config: testAccPolicyConfig_resourceIDForceNew1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttrPair(resourceName, "resource_id", appAutoscalingTargetResourceName, "resource_id"), @@ -423,7 +423,7 @@ func TestAccAppAutoScalingPolicy_ResourceID_forceNew(t *testing.T) { ), }, { - Config: testAccPolicyResourceIdForceNew2Config(rName), + Config: testAccPolicyConfig_resourceIDForceNew2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttrPair(resourceName, "resource_id", appAutoscalingTargetResourceName, "resource_id"), @@ -502,7 +502,7 @@ func testAccCheckPolicyDisappears(policy *applicationautoscaling.ScalingPolicy) } } -func testAccPolicyConfig(rName string) string { +func testAccPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -561,7 +561,7 @@ resource "aws_appautoscaling_policy" "test" { `, rName) } -func testAccPolicySpotFleetRequestConfig(randPolicyName, validUntil string) string { +func testAccPolicyConfig_spotFleetRequest(randPolicyName, validUntil string) string { return fmt.Sprintf(` data "aws_ami" "amzn-ami-minimal-hvm-ebs" { most_recent = true @@ -646,7 +646,7 @@ resource "aws_appautoscaling_policy" "test" { `, randPolicyName, validUntil) } -func testAccPolicyDynamoDB( +func testAccPolicyConfig_dynamoDB( randPolicyName string) string { return fmt.Sprintf(` resource "aws_dynamodb_table" "dynamodb_table_test" { @@ -691,7 +691,7 @@ resource "aws_appautoscaling_policy" "dynamo_test" { `, randPolicyName) } -func testAccPolicyDynamoDBIndex(rName string) string { +func testAccPolicyConfig_dynamoDBIndex(rName string) string { return fmt.Sprintf(` resource "aws_dynamodb_table" "test" { name = "%[1]s" @@ -754,7 +754,7 @@ resource "aws_appautoscaling_policy" "test" { `, rName) } -func testAccPolicy_multiplePoliciesSameName(tableName1, tableName2, namePrefix string) string { +func testAccPolicyConfig_multiplePoliciesSameName(tableName1, tableName2, namePrefix string) string { return fmt.Sprintf(` resource "aws_dynamodb_table" "dynamodb_table_test1" { name = "%[1]s" @@ -834,7 +834,7 @@ resource "aws_appautoscaling_policy" "read2" { `, tableName1, tableName2, namePrefix) } -func testAccPolicy_multiplePoliciesSameResource(tableName, namePrefix string) string { +func testAccPolicyConfig_multiplePoliciesSameResource(tableName, namePrefix string) string { return fmt.Sprintf(` resource "aws_dynamodb_table" "dynamodb_table_test" { name = "%s" @@ -906,7 +906,7 @@ resource "aws_appautoscaling_policy" "read" { `, tableName, namePrefix, namePrefix) } -func testAccPolicyScaleOutAndInConfig( +func testAccPolicyConfig_scaleOutAndIn( randClusterName string, randPolicyNamePrefix string) string { return fmt.Sprintf(` @@ -1013,7 +1013,7 @@ resource "aws_appautoscaling_policy" "foobar_in" { `, randClusterName, randPolicyNamePrefix, randPolicyNamePrefix) } -func testAccPolicyResourceIdForceNewBaseConfig(rName string) string { +func testAccPolicyConfig_resourceIDForceNewBase(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -1055,8 +1055,8 @@ resource "aws_ecs_service" "test2" { `, rName) } -func testAccPolicyResourceIdForceNew1Config(rName string) string { - return testAccPolicyResourceIdForceNewBaseConfig(rName) + fmt.Sprintf(` +func testAccPolicyConfig_resourceIDForceNew1(rName string) string { + return testAccPolicyConfig_resourceIDForceNewBase(rName) + fmt.Sprintf(` resource "aws_appautoscaling_target" "test" { max_capacity = 4 min_capacity = 0 @@ -1104,8 +1104,8 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccPolicyResourceIdForceNew2Config(rName string) string { - return testAccPolicyResourceIdForceNewBaseConfig(rName) + fmt.Sprintf(` +func testAccPolicyConfig_resourceIDForceNew2(rName string) string { + return testAccPolicyConfig_resourceIDForceNewBase(rName) + fmt.Sprintf(` resource "aws_appautoscaling_target" "test" { max_capacity = 4 min_capacity = 0 diff --git a/internal/service/appautoscaling/scheduled_action.go b/internal/service/appautoscaling/scheduled_action.go index 89a1bac779c..c12c3653c76 100644 --- a/internal/service/appautoscaling/scheduled_action.go +++ b/internal/service/appautoscaling/scheduled_action.go @@ -115,9 +115,9 @@ func resourceScheduledActionPut(d *schema.ResourceData, meta interface{}) error needsPut := true if d.IsNewResource() { - appautoscalingScheduledActionPopulateInputForCreate(input, d) + scheduledActionPopulateInputForCreate(input, d) } else { - needsPut = appautoscalingScheduledActionPopulateInputForUpdate(input, d) + needsPut = scheduledActionPopulateInputForUpdate(input, d) } if needsPut { @@ -146,7 +146,7 @@ func resourceScheduledActionPut(d *schema.ResourceData, meta interface{}) error return resourceScheduledActionRead(d, meta) } -func appautoscalingScheduledActionPopulateInputForCreate(input *applicationautoscaling.PutScheduledActionInput, d *schema.ResourceData) { +func scheduledActionPopulateInputForCreate(input *applicationautoscaling.PutScheduledActionInput, d *schema.ResourceData) { input.Schedule = aws.String(d.Get("schedule").(string)) input.ScalableTargetAction = expandScalableTargetAction(d.Get("scalable_target_action").([]interface{})) input.Timezone = aws.String(d.Get("timezone").(string)) @@ -161,7 +161,7 @@ func appautoscalingScheduledActionPopulateInputForCreate(input *applicationautos } } -func appautoscalingScheduledActionPopulateInputForUpdate(input *applicationautoscaling.PutScheduledActionInput, d *schema.ResourceData) bool { +func scheduledActionPopulateInputForUpdate(input *applicationautoscaling.PutScheduledActionInput, d *schema.ResourceData) bool { hasChange := false if d.HasChange("schedule") { diff --git a/internal/service/appautoscaling/scheduled_action_test.go b/internal/service/appautoscaling/scheduled_action_test.go index 0344438bdfc..3594e55e07c 100644 --- a/internal/service/appautoscaling/scheduled_action_test.go +++ b/internal/service/appautoscaling/scheduled_action_test.go @@ -32,7 +32,7 @@ func TestAccAppAutoScalingScheduledAction_dynamoDB(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_DynamoDB(rName, schedule1), + Config: testAccScheduledActionConfig_dynamoDB(rName, schedule1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -50,10 +50,10 @@ func TestAccAppAutoScalingScheduledAction_dynamoDB(t *testing.T) { ), }, { - Config: testAccAppautoscalingScheduledActionConfig_DynamoDB_Updated(rName, schedule2, updatedTimezone), + Config: testAccScheduledActionConfig_dynamoDBUpdated(rName, schedule2, updatedTimezone), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa2), - testAccCheckAppautoscalingScheduledActionNotRecreated(&sa1, &sa2), + testAccCheckScheduledActionNotRecreated(&sa1, &sa2), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrPair(resourceName, "service_namespace", autoscalingTargetResourceName, "service_namespace"), resource.TestCheckResourceAttrPair(resourceName, "resource_id", autoscalingTargetResourceName, "resource_id"), @@ -86,7 +86,7 @@ func TestAccAppAutoScalingScheduledAction_ecs(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_ECS(rName, ts), + Config: testAccScheduledActionConfig_ecs(rName, ts), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -119,7 +119,7 @@ func TestAccAppAutoScalingScheduledAction_emr(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_EMR(rName, ts), + Config: testAccScheduledActionConfig_emr(rName, ts), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -151,7 +151,7 @@ func TestAccAppAutoScalingScheduledAction_Name_duplicate(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_Name_Duplicate(rName), + Config: testAccScheduledActionConfig_duplicateName(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa1), testAccCheckScheduledActionExists(resourceName2, &sa2), @@ -176,7 +176,7 @@ func TestAccAppAutoScalingScheduledAction_spotFleet(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_SpotFleet(rName, ts, validUntil), + Config: testAccScheduledActionConfig_spotFleet(rName, ts, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -213,7 +213,7 @@ func TestAccAppAutoScalingScheduledAction_ScheduleAtExpression_timezone(t *testi CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_ScheduleWithTimezone(rName, at, timezone, startTime, endTime), + Config: testAccScheduledActionConfig_timezone(rName, at, timezone, startTime, endTime), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -248,7 +248,7 @@ func TestAccAppAutoScalingScheduledAction_ScheduleCronExpression_basic(t *testin CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_Schedule(rName, cron), + Config: testAccScheduledActionConfig_schedule(rName, cron), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -286,7 +286,7 @@ func TestAccAppAutoScalingScheduledAction_ScheduleCronExpression_timezone(t *tes CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_ScheduleWithTimezone(rName, cron, timezone, startTime, endTime), + Config: testAccScheduledActionConfig_timezone(rName, cron, timezone, startTime, endTime), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -328,7 +328,7 @@ func TestAccAppAutoScalingScheduledAction_ScheduleCronExpression_startEndTimeTim CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_ScheduleWithTimezone(rName, cron, scheduleTimezone, startTime.Format(time.RFC3339), endTime.Format(time.RFC3339)), + Config: testAccScheduledActionConfig_timezone(rName, cron, scheduleTimezone, startTime.Format(time.RFC3339), endTime.Format(time.RFC3339)), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -346,7 +346,7 @@ func TestAccAppAutoScalingScheduledAction_ScheduleCronExpression_startEndTimeTim ), }, { - Config: testAccAppautoscalingScheduledActionConfig_Schedule(rName, cron), + Config: testAccScheduledActionConfig_schedule(rName, cron), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -381,7 +381,7 @@ func TestAccAppAutoScalingScheduledAction_ScheduleRateExpression_basic(t *testin CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_Schedule(rName, rate), + Config: testAccScheduledActionConfig_schedule(rName, rate), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -419,7 +419,7 @@ func TestAccAppAutoScalingScheduledAction_ScheduleRateExpression_timezone(t *tes CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_ScheduleWithTimezone(rName, rate, timezone, startTime, endTime), + Config: testAccScheduledActionConfig_timezone(rName, rate, timezone, startTime, endTime), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -454,7 +454,7 @@ func TestAccAppAutoScalingScheduledAction_minCapacity(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_MinCapacity(rName, schedule, 1), + Config: testAccScheduledActionConfig_minCapacity(rName, schedule, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -472,20 +472,20 @@ func TestAccAppAutoScalingScheduledAction_minCapacity(t *testing.T) { ), }, { - Config: testAccAppautoscalingScheduledActionConfig_MinCapacity(rName, schedule, 2), + Config: testAccScheduledActionConfig_minCapacity(rName, schedule, 2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa2), - testAccCheckAppautoscalingScheduledActionNotRecreated(&sa1, &sa2), + testAccCheckScheduledActionNotRecreated(&sa1, &sa2), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.#", "1"), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.0.min_capacity", "2"), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.0.max_capacity", ""), ), }, { - Config: testAccAppautoscalingScheduledActionConfig_MaxCapacity(rName, schedule, 10), + Config: testAccScheduledActionConfig_maxCapacity(rName, schedule, 10), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa2), - testAccCheckAppautoscalingScheduledActionNotRecreated(&sa1, &sa2), + testAccCheckScheduledActionNotRecreated(&sa1, &sa2), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.#", "1"), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.0.min_capacity", ""), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.0.max_capacity", "10"), @@ -509,7 +509,7 @@ func TestAccAppAutoScalingScheduledAction_maxCapacity(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccAppautoscalingScheduledActionConfig_MaxCapacity(rName, schedule, 10), + Config: testAccScheduledActionConfig_maxCapacity(rName, schedule, 10), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -527,20 +527,20 @@ func TestAccAppAutoScalingScheduledAction_maxCapacity(t *testing.T) { ), }, { - Config: testAccAppautoscalingScheduledActionConfig_MaxCapacity(rName, schedule, 8), + Config: testAccScheduledActionConfig_maxCapacity(rName, schedule, 8), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa2), - testAccCheckAppautoscalingScheduledActionNotRecreated(&sa1, &sa2), + testAccCheckScheduledActionNotRecreated(&sa1, &sa2), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.#", "1"), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.0.min_capacity", ""), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.0.max_capacity", "8"), ), }, { - Config: testAccAppautoscalingScheduledActionConfig_MinCapacity(rName, schedule, 1), + Config: testAccScheduledActionConfig_minCapacity(rName, schedule, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &sa2), - testAccCheckAppautoscalingScheduledActionNotRecreated(&sa1, &sa2), + testAccCheckScheduledActionNotRecreated(&sa1, &sa2), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.#", "1"), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.0.min_capacity", "1"), resource.TestCheckResourceAttr(resourceName, "scalable_target_action.0.max_capacity", ""), @@ -598,7 +598,7 @@ func testAccCheckScheduledActionExists(name string, obj *applicationautoscaling. } } -func testAccCheckAppautoscalingScheduledActionNotRecreated(i, j *applicationautoscaling.ScheduledAction) resource.TestCheckFunc { +func testAccCheckScheduledActionNotRecreated(i, j *applicationautoscaling.ScheduledAction) resource.TestCheckFunc { return func(s *terraform.State) error { if !aws.TimeValue(i.CreationTime).Equal(aws.TimeValue(j.CreationTime)) { return fmt.Errorf("Application Auto Scaling scheduled action recreated") @@ -608,7 +608,7 @@ func testAccCheckAppautoscalingScheduledActionNotRecreated(i, j *applicationauto } } -func testAccAppautoscalingScheduledActionConfig_DynamoDB(rName, ts string) string { +func testAccScheduledActionConfig_dynamoDB(rName, ts string) string { return fmt.Sprintf(` resource "aws_appautoscaling_scheduled_action" "test" { name = %[1]q @@ -646,7 +646,7 @@ resource "aws_dynamodb_table" "test" { `, rName, ts) } -func testAccAppautoscalingScheduledActionConfig_DynamoDB_Updated(rName, ts, timezone string) string { +func testAccScheduledActionConfig_dynamoDBUpdated(rName, ts, timezone string) string { return fmt.Sprintf(` resource "aws_appautoscaling_scheduled_action" "test" { name = %[1]q @@ -685,7 +685,7 @@ resource "aws_dynamodb_table" "test" { `, rName, ts, timezone) } -func testAccAppautoscalingScheduledActionConfig_ECS(rName, ts string) string { +func testAccScheduledActionConfig_ecs(rName, ts string) string { return fmt.Sprintf(` resource "aws_appautoscaling_scheduled_action" "test" { name = %[1]q @@ -740,7 +740,7 @@ resource "aws_ecs_service" "test" { `, rName, ts) } -func testAccAppautoscalingScheduledActionConfig_EMR(rName, ts string) string { +func testAccScheduledActionConfig_emr(rName, ts string) string { return fmt.Sprintf(` resource "aws_appautoscaling_scheduled_action" "test" { name = %[1]q @@ -1072,7 +1072,7 @@ resource "aws_iam_role_policy_attachment" "autoscale_role" { `, rName, ts) } -func testAccAppautoscalingScheduledActionConfig_Name_Duplicate(rName string) string { +func testAccScheduledActionConfig_duplicateName(rName string) string { return fmt.Sprintf(` resource "aws_dynamodb_table" "test2" { name = "%[1]s-2" @@ -1142,7 +1142,7 @@ resource "aws_appautoscaling_scheduled_action" "test" { `, rName) } -func testAccAppautoscalingScheduledActionConfig_SpotFleet(rName, ts, validUntil string) string { +func testAccScheduledActionConfig_spotFleet(rName, ts, validUntil string) string { return fmt.Sprintf(` resource "aws_appautoscaling_scheduled_action" "test" { name = %[1]q @@ -1222,7 +1222,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, ts, validUntil) } -func testAccAppautoscalingScheduledActionConfig_Schedule(rName, schedule string) string { +func testAccScheduledActionConfig_schedule(rName, schedule string) string { return fmt.Sprintf(` resource "aws_appautoscaling_scheduled_action" "test" { name = %[1]q @@ -1259,7 +1259,7 @@ resource "aws_dynamodb_table" "test" { `, rName, schedule) } -func testAccAppautoscalingScheduledActionConfig_ScheduleWithTimezone(rName, schedule, timezone, startTime, endTime string) string { +func testAccScheduledActionConfig_timezone(rName, schedule, timezone, startTime, endTime string) string { return fmt.Sprintf(` resource "aws_appautoscaling_scheduled_action" "test" { name = %[1]q @@ -1300,7 +1300,7 @@ resource "aws_dynamodb_table" "test" { `, rName, timezone, schedule, startTime, endTime) } -func testAccAppautoscalingScheduledActionConfig_MinCapacity(rName, ts string, minCapacity int) string { +func testAccScheduledActionConfig_minCapacity(rName, ts string, minCapacity int) string { return fmt.Sprintf(` resource "aws_appautoscaling_scheduled_action" "test" { name = %[1]q @@ -1337,7 +1337,7 @@ resource "aws_dynamodb_table" "test" { `, rName, ts, minCapacity) } -func testAccAppautoscalingScheduledActionConfig_MaxCapacity(rName, ts string, maxCapacity int) string { +func testAccScheduledActionConfig_maxCapacity(rName, ts string, maxCapacity int) string { return fmt.Sprintf(` resource "aws_appautoscaling_scheduled_action" "test" { name = %[1]q diff --git a/internal/service/appautoscaling/target_test.go b/internal/service/appautoscaling/target_test.go index d336edf70f6..39001c3a354 100644 --- a/internal/service/appautoscaling/target_test.go +++ b/internal/service/appautoscaling/target_test.go @@ -27,7 +27,7 @@ func TestAccAppAutoScalingTarget_basic(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetConfig(randClusterName), + Config: testAccTargetConfig_basic(randClusterName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists("aws_appautoscaling_target.bar", &target), resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "service_namespace", "ecs"), @@ -38,7 +38,7 @@ func TestAccAppAutoScalingTarget_basic(t *testing.T) { }, { - Config: testAccTargetUpdateConfig(randClusterName), + Config: testAccTargetConfig_update(randClusterName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists("aws_appautoscaling_target.bar", &target), resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "min_capacity", "2"), @@ -67,7 +67,7 @@ func TestAccAppAutoScalingTarget_disappears(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetConfig(rName), + Config: testAccTargetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &target), acctest.CheckResourceDisappears(acctest.Provider, tfappautoscaling.ResourceTarget(), resourceName), @@ -89,7 +89,7 @@ func TestAccAppAutoScalingTarget_spotFleetRequest(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetSpotFleetRequestConfig(validUntil), + Config: testAccTargetConfig_spotFleetRequest(validUntil), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists("aws_appautoscaling_target.test", &target), resource.TestCheckResourceAttr("aws_appautoscaling_target.test", "service_namespace", "ec2"), @@ -117,7 +117,7 @@ func TestAccAppAutoScalingTarget_emrCluster(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetEMRClusterConfig(rInt), + Config: testAccTargetConfig_emrCluster(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists("aws_appautoscaling_target.bar", &target), resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "service_namespace", "elasticmapreduce"), @@ -148,7 +148,7 @@ func TestAccAppAutoScalingTarget_multipleTargets(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTarget_multipleTargets(tableName), + Config: testAccTargetConfig_multiple(tableName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists("aws_appautoscaling_target.write", &writeTarget), resource.TestCheckResourceAttr("aws_appautoscaling_target.write", "service_namespace", "dynamodb"), @@ -182,7 +182,7 @@ func TestAccAppAutoScalingTarget_optionalRoleARN(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTarget_optionalRoleARN(tableName), + Config: testAccTargetConfig_optionalRoleARN(tableName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists("aws_appautoscaling_target.read", &readTarget), acctest.CheckResourceAttrGlobalARN("aws_appautoscaling_target.read", "role_arn", "iam", @@ -242,7 +242,7 @@ func testAccCheckTargetExists(n string, v *applicationautoscaling.ScalableTarget } } -func testAccTargetConfig( +func testAccTargetConfig_basic( randClusterName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "foo" { @@ -285,7 +285,7 @@ resource "aws_appautoscaling_target" "bar" { `, randClusterName) } -func testAccTargetUpdateConfig( +func testAccTargetConfig_update( randClusterName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "foo" { @@ -328,7 +328,7 @@ resource "aws_appautoscaling_target" "bar" { `, randClusterName) } -func testAccTargetEMRClusterConfig(rInt int) string { +func testAccTargetConfig_emrCluster(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { # The requested instance type m3.xlarge is not supported in the requested availability zone. @@ -660,7 +660,7 @@ resource "aws_appautoscaling_target" "bar" { `, rInt, rInt, rInt, rInt, rInt, rInt, rInt, rInt) } -func testAccTargetSpotFleetRequestConfig(validUntil string) string { +func testAccTargetConfig_spotFleetRequest(validUntil string) string { return fmt.Sprintf(` data "aws_ami" "amzn-ami-minimal-hvm-ebs" { most_recent = true @@ -727,7 +727,7 @@ resource "aws_appautoscaling_target" "test" { `, validUntil) } -func testAccTarget_multipleTargets(tableName string) string { +func testAccTargetConfig_multiple(tableName string) string { return fmt.Sprintf(` resource "aws_dynamodb_table" "dynamodb_table_test" { name = "%s" @@ -759,7 +759,7 @@ resource "aws_appautoscaling_target" "read" { `, tableName) } -func testAccTarget_optionalRoleARN(tableName string) string { +func testAccTargetConfig_optionalRoleARN(tableName string) string { return fmt.Sprintf(` resource "aws_dynamodb_table" "dynamodb_table_test" { name = "%s" diff --git a/internal/service/appconfig/application_test.go b/internal/service/appconfig/application_test.go index aa3299fbb9c..3ae9b50e57f 100644 --- a/internal/service/appconfig/application_test.go +++ b/internal/service/appconfig/application_test.go @@ -27,7 +27,7 @@ func TestAccAppConfigApplication_basic(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationNameConfig(rName), + Config: testAccApplicationConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appconfig", regexp.MustCompile(`application/[a-z0-9]{4,7}`)), @@ -55,7 +55,7 @@ func TestAccAppConfigApplication_disappears(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationNameConfig(rName), + Config: testAccApplicationConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfappconfig.ResourceApplication(), resourceName), @@ -78,13 +78,13 @@ func TestAccAppConfigApplication_updateName(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationNameConfig(rName), + Config: testAccApplicationConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), ), }, { - Config: testAccApplicationNameConfig(rNameUpdated), + Config: testAccApplicationConfig_name(rNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), @@ -111,7 +111,7 @@ func TestAccAppConfigApplication_updateDescription(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationDescriptionConfig(rName, rName), + Config: testAccApplicationConfig_description(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -123,7 +123,7 @@ func TestAccAppConfigApplication_updateDescription(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccApplicationDescriptionConfig(rName, description), + Config: testAccApplicationConfig_description(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", description), @@ -136,7 +136,7 @@ func TestAccAppConfigApplication_updateDescription(t *testing.T) { }, { // Test Description Removal - Config: testAccApplicationNameConfig(rName), + Config: testAccApplicationConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), ), @@ -156,7 +156,7 @@ func TestAccAppConfigApplication_tags(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationTags1(rName, "key1", "value1"), + Config: testAccApplicationConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -169,7 +169,7 @@ func TestAccAppConfigApplication_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccApplicationTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccApplicationConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -178,7 +178,7 @@ func TestAccAppConfigApplication_tags(t *testing.T) { ), }, { - Config: testAccApplicationTags1(rName, "key2", "value2"), + Config: testAccApplicationConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -250,7 +250,7 @@ func testAccCheckApplicationExists(resourceName string) resource.TestCheckFunc { } } -func testAccApplicationNameConfig(rName string) string { +func testAccApplicationConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_appconfig_application" "test" { name = %[1]q @@ -258,7 +258,7 @@ resource "aws_appconfig_application" "test" { `, rName) } -func testAccApplicationDescriptionConfig(rName, description string) string { +func testAccApplicationConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_appconfig_application" "test" { name = %q @@ -267,7 +267,7 @@ resource "aws_appconfig_application" "test" { `, rName, description) } -func testAccApplicationTags1(rName, tagKey1, tagValue1 string) string { +func testAccApplicationConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_appconfig_application" "test" { name = %[1]q @@ -279,7 +279,7 @@ resource "aws_appconfig_application" "test" { `, rName, tagKey1, tagValue1) } -func testAccApplicationTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccApplicationConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_appconfig_application" "test" { name = %[1]q diff --git a/internal/service/appconfig/configuration_profile.go b/internal/service/appconfig/configuration_profile.go index d760f00e186..9816fecd5bc 100644 --- a/internal/service/appconfig/configuration_profile.go +++ b/internal/service/appconfig/configuration_profile.go @@ -69,7 +69,7 @@ func ResourceConfigurationProfile() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: ConfigurationProfileTypeAWSFreeform, + Default: configurationProfileTypeFreeform, ValidateFunc: validation.StringInSlice(ConfigurationProfileType_Values(), false), }, "validator": { diff --git a/internal/service/appconfig/configuration_profile_test.go b/internal/service/appconfig/configuration_profile_test.go index c9f8a58530b..295b3e4ef27 100644 --- a/internal/service/appconfig/configuration_profile_test.go +++ b/internal/service/appconfig/configuration_profile_test.go @@ -28,7 +28,7 @@ func TestAccAppConfigConfigurationProfile_basic(t *testing.T) { CheckDestroy: testAccCheckConfigurationProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationProfileNameConfig(rName), + Config: testAccConfigurationProfileConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "application_id", appResourceName, "id"), @@ -61,7 +61,7 @@ func TestAccAppConfigConfigurationProfile_disappears(t *testing.T) { CheckDestroy: testAccCheckConfigurationProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationProfileNameConfig(rName), + Config: testAccConfigurationProfileConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfappconfig.ResourceConfigurationProfile(), resourceName), @@ -83,7 +83,7 @@ func TestAccAppConfigConfigurationProfile_Validators_json(t *testing.T) { CheckDestroy: testAccCheckConfigurationProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationProfileValidatorConfig_JSON(rName), + Config: testAccConfigurationProfileConfig_validatorJSON(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "validator.#", "1"), @@ -98,7 +98,7 @@ func TestAccAppConfigConfigurationProfile_Validators_json(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationProfileValidatorConfig_NoJSONContent(rName), + Config: testAccConfigurationProfileConfig_validatorNoJSONContent(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "validator.#", "1"), @@ -115,7 +115,7 @@ func TestAccAppConfigConfigurationProfile_Validators_json(t *testing.T) { }, { // Test Validator Removal - Config: testAccConfigurationProfileNameConfig(rName), + Config: testAccConfigurationProfileConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "validator.#", "0"), @@ -136,7 +136,7 @@ func TestAccAppConfigConfigurationProfile_Validators_lambda(t *testing.T) { CheckDestroy: testAccCheckConfigurationProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationProfileValidatorConfig_Lambda(rName), + Config: testAccConfigurationProfileConfig_validatorLambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "validator.#", "1"), @@ -153,7 +153,7 @@ func TestAccAppConfigConfigurationProfile_Validators_lambda(t *testing.T) { }, { // Test Validator Removal - Config: testAccConfigurationProfileNameConfig(rName), + Config: testAccConfigurationProfileConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "validator.#", "0"), @@ -174,7 +174,7 @@ func TestAccAppConfigConfigurationProfile_Validators_multiple(t *testing.T) { CheckDestroy: testAccCheckConfigurationProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationProfileValidatorConfig_Multiple(rName), + Config: testAccConfigurationProfileConfig_validatorMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "validator.#", "2"), @@ -209,14 +209,14 @@ func TestAccAppConfigConfigurationProfile_updateName(t *testing.T) { CheckDestroy: testAccCheckConfigurationProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationProfileNameConfig(rName), + Config: testAccConfigurationProfileConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), ), }, { - Config: testAccConfigurationProfileNameConfig(rNameUpdated), + Config: testAccConfigurationProfileConfig_name(rNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), @@ -243,7 +243,7 @@ func TestAccAppConfigConfigurationProfile_updateDescription(t *testing.T) { CheckDestroy: testAccCheckConfigurationProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationProfileDescriptionConfig(rName, rName), + Config: testAccConfigurationProfileConfig_description(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -255,7 +255,7 @@ func TestAccAppConfigConfigurationProfile_updateDescription(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationProfileDescriptionConfig(rName, description), + Config: testAccConfigurationProfileConfig_description(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", description), @@ -281,7 +281,7 @@ func TestAccAppConfigConfigurationProfile_tags(t *testing.T) { CheckDestroy: testAccCheckConfigurationProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationProfileTags1(rName, "key1", "value1"), + Config: testAccConfigurationProfileConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -294,7 +294,7 @@ func TestAccAppConfigConfigurationProfile_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationProfileTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccConfigurationProfileConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -303,7 +303,7 @@ func TestAccAppConfigConfigurationProfile_tags(t *testing.T) { ), }, { - Config: testAccConfigurationProfileTags1(rName, "key2", "value2"), + Config: testAccConfigurationProfileConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationProfileExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -387,9 +387,9 @@ func testAccCheckConfigurationProfileExists(resourceName string) resource.TestCh } } -func testAccConfigurationProfileNameConfig(rName string) string { +func testAccConfigurationProfileConfig_name(rName string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_configuration_profile" "test" { application_id = aws_appconfig_application.test.id @@ -399,9 +399,9 @@ resource "aws_appconfig_configuration_profile" "test" { `, rName)) } -func testAccConfigurationProfileDescriptionConfig(rName, description string) string { +func testAccConfigurationProfileConfig_description(rName, description string) string { return acctest.ConfigCompose( - testAccApplicationDescriptionConfig(rName, description), + testAccApplicationConfig_description(rName, description), fmt.Sprintf(` resource "aws_appconfig_configuration_profile" "test" { application_id = aws_appconfig_application.test.id @@ -412,9 +412,9 @@ resource "aws_appconfig_configuration_profile" "test" { `, rName, description)) } -func testAccConfigurationProfileValidatorConfig_JSON(rName string) string { +func testAccConfigurationProfileConfig_validatorJSON(rName string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_configuration_profile" "test" { application_id = aws_appconfig_application.test.id @@ -442,9 +442,9 @@ resource "aws_appconfig_configuration_profile" "test" { `, rName)) } -func testAccConfigurationProfileValidatorConfig_NoJSONContent(rName string) string { +func testAccConfigurationProfileConfig_validatorNoJSONContent(rName string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_configuration_profile" "test" { application_id = aws_appconfig_application.test.id @@ -492,9 +492,9 @@ resource "aws_lambda_function" "test" { `, rName) } -func testAccConfigurationProfileValidatorConfig_Lambda(rName string) string { +func testAccConfigurationProfileConfig_validatorLambda(rName string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), testAccApplicationLambdaBaseConfig(rName), fmt.Sprintf(` resource "aws_appconfig_configuration_profile" "test" { @@ -510,9 +510,9 @@ resource "aws_appconfig_configuration_profile" "test" { `, rName)) } -func testAccConfigurationProfileValidatorConfig_Multiple(rName string) string { +func testAccConfigurationProfileConfig_validatorMultiple(rName string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), testAccApplicationLambdaBaseConfig(rName), fmt.Sprintf(` resource "aws_appconfig_configuration_profile" "test" { @@ -538,9 +538,9 @@ resource "aws_appconfig_configuration_profile" "test" { `, rName)) } -func testAccConfigurationProfileTags1(rName, tagKey1, tagValue1 string) string { +func testAccConfigurationProfileConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_configuration_profile" "test" { application_id = aws_appconfig_application.test.id @@ -554,9 +554,9 @@ resource "aws_appconfig_configuration_profile" "test" { `, rName, tagKey1, tagValue1)) } -func testAccConfigurationProfileTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccConfigurationProfileConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_configuration_profile" "test" { application_id = aws_appconfig_application.test.id diff --git a/internal/service/appconfig/deployment_strategy_test.go b/internal/service/appconfig/deployment_strategy_test.go index 32d4b370f32..14545cad694 100644 --- a/internal/service/appconfig/deployment_strategy_test.go +++ b/internal/service/appconfig/deployment_strategy_test.go @@ -27,7 +27,7 @@ func TestAccAppConfigDeploymentStrategy_basic(t *testing.T) { CheckDestroy: testAccCheckDeploymentStrategyDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStrategyNameConfig(rName), + Config: testAccDeploymentStrategyConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appconfig", regexp.MustCompile(`deploymentstrategy/[a-z0-9]{4,7}`)), @@ -59,14 +59,14 @@ func TestAccAppConfigDeploymentStrategy_updateDescription(t *testing.T) { CheckDestroy: testAccCheckDeploymentStrategyDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStrategyDescriptionConfig(rName, rName), + Config: testAccDeploymentStrategyConfig_description(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", rName), ), }, { - Config: testAccDeploymentStrategyDescriptionConfig(rName, description), + Config: testAccDeploymentStrategyConfig_description(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", description), @@ -92,7 +92,7 @@ func TestAccAppConfigDeploymentStrategy_updateFinalBakeTime(t *testing.T) { CheckDestroy: testAccCheckDeploymentStrategyDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStrategyFinalBakeTimeConfig(rName, 60), + Config: testAccDeploymentStrategyConfig_finalBakeTime(rName, 60), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "final_bake_time_in_minutes", "60"), @@ -104,7 +104,7 @@ func TestAccAppConfigDeploymentStrategy_updateFinalBakeTime(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeploymentStrategyFinalBakeTimeConfig(rName, 30), + Config: testAccDeploymentStrategyConfig_finalBakeTime(rName, 30), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "final_bake_time_in_minutes", "30"), @@ -117,7 +117,7 @@ func TestAccAppConfigDeploymentStrategy_updateFinalBakeTime(t *testing.T) { }, { // Test FinalBakeTimeInMinutes Removal - Config: testAccDeploymentStrategyNameConfig(rName), + Config: testAccDeploymentStrategyConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), ), @@ -137,7 +137,7 @@ func TestAccAppConfigDeploymentStrategy_disappears(t *testing.T) { CheckDestroy: testAccCheckDeploymentStrategyDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStrategyNameConfig(rName), + Config: testAccDeploymentStrategyConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfappconfig.ResourceDeploymentStrategy(), resourceName), @@ -159,7 +159,7 @@ func TestAccAppConfigDeploymentStrategy_tags(t *testing.T) { CheckDestroy: testAccCheckDeploymentStrategyDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentStrategyTags1(rName, "key1", "value1"), + Config: testAccDeploymentStrategyConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -172,7 +172,7 @@ func TestAccAppConfigDeploymentStrategy_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeploymentStrategyTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDeploymentStrategyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -181,7 +181,7 @@ func TestAccAppConfigDeploymentStrategy_tags(t *testing.T) { ), }, { - Config: testAccDeploymentStrategyTags1(rName, "key2", "value2"), + Config: testAccDeploymentStrategyConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentStrategyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -253,7 +253,7 @@ func testAccCheckDeploymentStrategyExists(resourceName string) resource.TestChec } } -func testAccDeploymentStrategyNameConfig(rName string) string { +func testAccDeploymentStrategyConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_appconfig_deployment_strategy" "test" { name = %[1]q @@ -264,7 +264,7 @@ resource "aws_appconfig_deployment_strategy" "test" { `, rName) } -func testAccDeploymentStrategyDescriptionConfig(rName, description string) string { +func testAccDeploymentStrategyConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_appconfig_deployment_strategy" "test" { name = %[1]q @@ -276,7 +276,7 @@ resource "aws_appconfig_deployment_strategy" "test" { `, rName, description) } -func testAccDeploymentStrategyFinalBakeTimeConfig(rName string, time int) string { +func testAccDeploymentStrategyConfig_finalBakeTime(rName string, time int) string { return fmt.Sprintf(` resource "aws_appconfig_deployment_strategy" "test" { name = %[1]q @@ -288,7 +288,7 @@ resource "aws_appconfig_deployment_strategy" "test" { `, rName, time) } -func testAccDeploymentStrategyTags1(rName, tagKey1, tagValue1 string) string { +func testAccDeploymentStrategyConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_appconfig_deployment_strategy" "test" { name = %[1]q @@ -303,7 +303,7 @@ resource "aws_appconfig_deployment_strategy" "test" { `, rName, tagKey1, tagValue1) } -func testAccDeploymentStrategyTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDeploymentStrategyConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_appconfig_deployment_strategy" "test" { name = %[1]q diff --git a/internal/service/appconfig/deployment_test.go b/internal/service/appconfig/deployment_test.go index 859538dea07..12680af7125 100644 --- a/internal/service/appconfig/deployment_test.go +++ b/internal/service/appconfig/deployment_test.go @@ -33,7 +33,7 @@ func TestAccAppConfigDeployment_basic(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentNameConfig(rName), + Config: testAccDeploymentConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appconfig", regexp.MustCompile(`application/[a-z0-9]{4,7}/environment/[a-z0-9]{4,7}/deployment/1`)), @@ -71,7 +71,7 @@ func TestAccAppConfigDeployment_predefinedStrategy(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentConfig_PredefinedStrategy(rName, strategy), + Config: testAccDeploymentConfig_predefinedStrategy(rName, strategy), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "deployment_strategy_id", strategy), @@ -102,7 +102,7 @@ func TestAccAppConfigDeployment_tags(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccDeploymentTags1(rName, "key1", "value1"), + Config: testAccDeploymentConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -115,7 +115,7 @@ func TestAccAppConfigDeployment_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeploymentTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDeploymentConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -124,7 +124,7 @@ func TestAccAppConfigDeployment_tags(t *testing.T) { ), }, { - Config: testAccDeploymentTags1(rName, "key2", "value2"), + Config: testAccDeploymentConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -212,7 +212,7 @@ resource "aws_appconfig_hosted_configuration_version" "test" { `, rName) } -func testAccDeploymentNameConfig(rName string) string { +func testAccDeploymentConfig_name(rName string) string { return acctest.ConfigCompose( testAccDeploymentBaseConfig(rName), fmt.Sprintf(` @@ -227,7 +227,7 @@ resource "aws_appconfig_deployment" "test"{ `, rName)) } -func testAccDeploymentConfig_PredefinedStrategy(rName, strategy string) string { +func testAccDeploymentConfig_predefinedStrategy(rName, strategy string) string { return acctest.ConfigCompose( testAccDeploymentBaseConfig(rName), fmt.Sprintf(` @@ -242,7 +242,7 @@ resource "aws_appconfig_deployment" "test"{ `, rName, strategy)) } -func testAccDeploymentTags1(rName, tagKey1, tagValue1 string) string { +func testAccDeploymentConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( testAccDeploymentBaseConfig(rName), fmt.Sprintf(` @@ -260,7 +260,7 @@ resource "aws_appconfig_deployment" "test"{ `, rName, tagKey1, tagValue1)) } -func testAccDeploymentTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDeploymentConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( testAccDeploymentBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/appconfig/enum.go b/internal/service/appconfig/enum.go index 133739ca070..7206bdac7a6 100644 --- a/internal/service/appconfig/enum.go +++ b/internal/service/appconfig/enum.go @@ -1,13 +1,13 @@ package appconfig const ( - ConfigurationProfileTypeAWSAppConfigFeatureFlags = "AWS.AppConfig.FeatureFlags" - ConfigurationProfileTypeAWSFreeform = "AWS.Freeform" + configurationProfileTypeFeatureFlags = "AWS.AppConfig.FeatureFlags" + configurationProfileTypeFreeform = "AWS.Freeform" ) func ConfigurationProfileType_Values() []string { return []string{ - ConfigurationProfileTypeAWSAppConfigFeatureFlags, - ConfigurationProfileTypeAWSFreeform, + configurationProfileTypeFeatureFlags, + configurationProfileTypeFreeform, } } diff --git a/internal/service/appconfig/environment_test.go b/internal/service/appconfig/environment_test.go index aadd117d981..76461a4564e 100644 --- a/internal/service/appconfig/environment_test.go +++ b/internal/service/appconfig/environment_test.go @@ -28,7 +28,7 @@ func TestAccAppConfigEnvironment_basic(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentBasicConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appconfig", regexp.MustCompile(`application/[a-z0-9]{4,7}/environment/[a-z0-9]{4,7}`)), @@ -59,7 +59,7 @@ func TestAccAppConfigEnvironment_disappears(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentBasicConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfappconfig.ResourceEnvironment(), resourceName), @@ -82,13 +82,13 @@ func TestAccAppConfigEnvironment_updateName(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentBasicConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), ), }, { - Config: testAccEnvironmentBasicConfig(rNameUpdated), + Config: testAccEnvironmentConfig_basic(rNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), @@ -115,7 +115,7 @@ func TestAccAppConfigEnvironment_updateDescription(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentDescriptionConfig(rName, rName), + Config: testAccEnvironmentConfig_description(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -127,7 +127,7 @@ func TestAccAppConfigEnvironment_updateDescription(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEnvironmentDescriptionConfig(rName, description), + Config: testAccEnvironmentConfig_description(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", description), @@ -140,7 +140,7 @@ func TestAccAppConfigEnvironment_updateDescription(t *testing.T) { }, { // Test Description Removal - Config: testAccEnvironmentBasicConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), ), @@ -160,7 +160,7 @@ func TestAccAppConfigEnvironment_monitors(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentWithMonitors(rName, 1), + Config: testAccEnvironmentConfig_monitors(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -176,7 +176,7 @@ func TestAccAppConfigEnvironment_monitors(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEnvironmentWithMonitors(rName, 2), + Config: testAccEnvironmentConfig_monitors(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -195,7 +195,7 @@ func TestAccAppConfigEnvironment_monitors(t *testing.T) { }, { // Test Monitor Removal - Config: testAccEnvironmentBasicConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "monitor.#", "0"), @@ -217,7 +217,7 @@ func TestAccAppConfigEnvironment_multipleEnvironments(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentMultipleConfig(rName), + Config: testAccEnvironmentConfig_multiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName1), testAccCheckEnvironmentExists(resourceName2), @@ -234,7 +234,7 @@ func TestAccAppConfigEnvironment_multipleEnvironments(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEnvironmentBasicConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName1), ), @@ -259,7 +259,7 @@ func TestAccAppConfigEnvironment_tags(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentTags1(rName, "key1", "value1"), + Config: testAccEnvironmentConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -272,7 +272,7 @@ func TestAccAppConfigEnvironment_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEnvironmentTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccEnvironmentConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -281,7 +281,7 @@ func TestAccAppConfigEnvironment_tags(t *testing.T) { ), }, { - Config: testAccEnvironmentTags1(rName, "key2", "value2"), + Config: testAccEnvironmentConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -367,9 +367,9 @@ func testAccCheckEnvironmentExists(resourceName string) resource.TestCheckFunc { } } -func testAccEnvironmentBasicConfig(rName string) string { +func testAccEnvironmentConfig_basic(rName string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_environment" "test" { name = %q @@ -378,9 +378,9 @@ resource "aws_appconfig_environment" "test" { `, rName)) } -func testAccEnvironmentDescriptionConfig(rName, description string) string { +func testAccEnvironmentConfig_description(rName, description string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_environment" "test" { name = %q @@ -390,9 +390,9 @@ resource "aws_appconfig_environment" "test" { `, rName, description)) } -func testAccEnvironmentWithMonitors(rName string, count int) string { +func testAccEnvironmentConfig_monitors(rName string, count int) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` data "aws_partition" "current" {} @@ -468,9 +468,9 @@ resource "aws_appconfig_environment" "test" { `, rName, count)) } -func testAccEnvironmentMultipleConfig(rName string) string { +func testAccEnvironmentConfig_multiple(rName string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_environment" "test" { name = %[1]q @@ -484,9 +484,9 @@ resource "aws_appconfig_environment" "test2" { `, rName)) } -func testAccEnvironmentTags1(rName, tagKey1, tagValue1 string) string { +func testAccEnvironmentConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_environment" "test" { name = %[1]q @@ -499,9 +499,9 @@ resource "aws_appconfig_environment" "test" { `, rName, tagKey1, tagValue1)) } -func testAccEnvironmentTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccEnvironmentConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccApplicationNameConfig(rName), + testAccApplicationConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_environment" "test" { name = %[1]q diff --git a/internal/service/appconfig/hosted_configuration_version_test.go b/internal/service/appconfig/hosted_configuration_version_test.go index 200b82a88aa..be03f36f1e1 100644 --- a/internal/service/appconfig/hosted_configuration_version_test.go +++ b/internal/service/appconfig/hosted_configuration_version_test.go @@ -27,7 +27,7 @@ func TestAccAppConfigHostedConfigurationVersion_basic(t *testing.T) { CheckDestroy: testAccCheckHostedConfigurationVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccHostedConfigurationVersion(rName), + Config: testAccHostedConfigurationVersionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckHostedConfigurationVersionExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appconfig", regexp.MustCompile(`application/[a-z0-9]{4,7}/configurationprofile/[a-z0-9]{4,7}/hostedconfigurationversion/[0-9]+`)), @@ -59,7 +59,7 @@ func TestAccAppConfigHostedConfigurationVersion_disappears(t *testing.T) { CheckDestroy: testAccCheckHostedConfigurationVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccHostedConfigurationVersion(rName), + Config: testAccHostedConfigurationVersionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckHostedConfigurationVersionExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfappconfig.ResourceHostedConfigurationVersion(), resourceName), @@ -145,9 +145,9 @@ func testAccCheckHostedConfigurationVersionExists(resourceName string) resource. } } -func testAccHostedConfigurationVersion(rName string) string { +func testAccHostedConfigurationVersionConfig_basic(rName string) string { return acctest.ConfigCompose( - testAccConfigurationProfileNameConfig(rName), + testAccConfigurationProfileConfig_name(rName), fmt.Sprintf(` resource "aws_appconfig_hosted_configuration_version" "test" { application_id = aws_appconfig_application.test.id diff --git a/internal/service/appflow/connector_profile.go b/internal/service/appflow/connector_profile.go index d0f83d97315..a24feb40c9c 100644 --- a/internal/service/appflow/connector_profile.go +++ b/internal/service/appflow/connector_profile.go @@ -1430,7 +1430,7 @@ func resourceConnectorProfileCreate(ctx context.Context, d *schema.ResourceData, func resourceConnectorProfileRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { conn := meta.(*conns.AWSClient).AppFlowConn - connectorProfile, err := FindConnectorProfileByArn(context.Background(), conn, d.Id()) + connectorProfile, err := FindConnectorProfileByARN(context.Background(), conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] AppFlow Connector Profile (%s) not found, removing from state", d.Id()) @@ -1484,7 +1484,7 @@ func resourceConnectorProfileUpdate(ctx context.Context, d *schema.ResourceData, func resourceConnectorProfileDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { conn := meta.(*conns.AWSClient).AppFlowConn - out, _ := FindConnectorProfileByArn(ctx, conn, d.Id()) + out, _ := FindConnectorProfileByARN(ctx, conn, d.Id()) log.Printf("[INFO] Deleting AppFlow Flow %s", d.Id()) @@ -1584,7 +1584,7 @@ func expandCustomConnectorProfileCredentials(m map[string]interface{}) *appflow. } if v, ok := m["api_key"].([]interface{}); ok && len(v) > 0 { - credentials.ApiKey = expandApiKeyCredentials(v[0].(map[string]interface{})) + credentials.ApiKey = expandAPIKeyCredentials(v[0].(map[string]interface{})) } if v, ok := m["basic"].([]interface{}); ok && len(v) > 0 { @@ -1816,7 +1816,7 @@ func expandOAuthRequest(m map[string]interface{}) *appflow.ConnectorOAuthRequest return &r } -func expandApiKeyCredentials(m map[string]interface{}) *appflow.ApiKeyCredentials { +func expandAPIKeyCredentials(m map[string]interface{}) *appflow.ApiKeyCredentials { credentials := appflow.ApiKeyCredentials{} if v, ok := m["api_key"].(string); ok && v != "" { diff --git a/internal/service/appflow/connector_profile_test.go b/internal/service/appflow/connector_profile_test.go index e49081a6ea0..d503330f5e8 100644 --- a/internal/service/appflow/connector_profile_test.go +++ b/internal/service/appflow/connector_profile_test.go @@ -34,7 +34,7 @@ func TestAccAppFlowConnectorProfile_basic(t *testing.T) { CheckDestroy: testAccCheckConnectorProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigConnectorProfile_basic(rName), + Config: testAccConnectorProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConnectorProfileExists(resourceName, &connectorProfiles), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appflow", regexp.MustCompile(`connectorprofile/.+`)), @@ -73,13 +73,13 @@ func TestAccAppFlowConnectorProfile_update(t *testing.T) { CheckDestroy: testAccCheckConnectorProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigConnectorProfile_basic(rName), + Config: testAccConnectorProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConnectorProfileExists(resourceName, &connectorProfiles), ), }, { - Config: testAccConfigConnectorProfile_update(rName, testPrefix), + Config: testAccConnectorProfileConfig_update(rName, testPrefix), Check: resource.ComposeTestCheckFunc( testAccCheckConnectorProfileExists(resourceName, &connectorProfiles), resource.TestCheckResourceAttr(resourceName, "connector_profile_config.0.connector_profile_properties.0.redshift.0.bucket_prefix", testPrefix), @@ -106,7 +106,7 @@ func TestAccAppFlowConnectorProfile_disappears(t *testing.T) { CheckDestroy: testAccCheckConnectorProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigConnectorProfile_basic(rName), + Config: testAccConnectorProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConnectorProfileExists(resourceName, &connectorProfiles), acctest.CheckResourceDisappears(acctest.Provider, tfappflow.ResourceConnectorProfile(), resourceName), @@ -125,7 +125,7 @@ func testAccCheckConnectorProfileDestroy(s *terraform.State) error { continue } - _, err := tfappflow.FindConnectorProfileByArn(context.Background(), conn, rs.Primary.ID) + _, err := tfappflow.FindConnectorProfileByARN(context.Background(), conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -278,7 +278,7 @@ resource "aws_redshift_cluster" "test" { `, connectorProfileName, redshiftPassword, redshiftUsername)) } -func testAccConfigConnectorProfile_basic(connectorProfileName string) string { +func testAccConnectorProfileConfig_basic(connectorProfileName string) string { const redshiftPassword = "testPassword123!" const redshiftUsername = "testusername" @@ -317,7 +317,7 @@ resource "aws_appflow_connector_profile" "test" { ) } -func testAccConfigConnectorProfile_update(connectorProfileName string, bucketPrefix string) string { +func testAccConnectorProfileConfig_update(connectorProfileName string, bucketPrefix string) string { const redshiftPassword = "testPassword123!" const redshiftUsername = "testusername" diff --git a/internal/service/appflow/find.go b/internal/service/appflow/find.go index 02e1a21c649..e9a792092aa 100644 --- a/internal/service/appflow/find.go +++ b/internal/service/appflow/find.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func FindFlowByArn(ctx context.Context, conn *appflow.Appflow, arn string) (*appflow.FlowDefinition, error) { +func FindFlowByARN(ctx context.Context, conn *appflow.Appflow, arn string) (*appflow.FlowDefinition, error) { in := &appflow.ListFlowsInput{} var result *appflow.FlowDefinition @@ -53,7 +53,7 @@ func FindFlowByArn(ctx context.Context, conn *appflow.Appflow, arn string) (*app return result, nil } -func FindConnectorProfileByArn(ctx context.Context, conn *appflow.Appflow, arn string) (*appflow.ConnectorProfile, error) { +func FindConnectorProfileByARN(ctx context.Context, conn *appflow.Appflow, arn string) (*appflow.ConnectorProfile, error) { params := &appflow.DescribeConnectorProfilesInput{} var result *appflow.ConnectorProfile diff --git a/internal/service/appflow/flow.go b/internal/service/appflow/flow.go index 7662dd94ddc..267ed1b9eb4 100644 --- a/internal/service/appflow/flow.go +++ b/internal/service/appflow/flow.go @@ -1113,12 +1113,11 @@ func ResourceFlow() *schema.Resource { }, }, "task_properties": { - Type: schema.TypeMap, - Optional: true, - ValidateFunc: validation.StringInSlice(appflow.OperatorPropertiesKeys_Values(), false), + Type: schema.TypeMap, + Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, - ValidateFunc: validation.All(validation.StringMatch(regexp.MustCompile(`\S+`), "must not contain any whitespace characters"), validation.StringLenBetween(0, 2048)), + ValidateFunc: validation.StringLenBetween(0, 2048), }, }, "task_type": { @@ -1248,7 +1247,7 @@ func resourceFlowCreate(ctx context.Context, d *schema.ResourceData, meta interf func resourceFlowRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { conn := meta.(*conns.AWSClient).AppFlowConn - out, err := FindFlowByArn(ctx, conn, d.Id()) + out, err := FindFlowByARN(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] AppFlow Flow (%s) not found, removing from state", d.Id()) @@ -1359,7 +1358,7 @@ func resourceFlowUpdate(ctx context.Context, d *schema.ResourceData, meta interf func resourceFlowDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { conn := meta.(*conns.AWSClient).AppFlowConn - out, _ := FindFlowByArn(ctx, conn, d.Id()) + out, _ := FindFlowByARN(ctx, conn, d.Id()) log.Printf("[INFO] Deleting AppFlow Flow %s", d.Id()) diff --git a/internal/service/appflow/flow_test.go b/internal/service/appflow/flow_test.go index 88ff55b166f..52657383810 100644 --- a/internal/service/appflow/flow_test.go +++ b/internal/service/appflow/flow_test.go @@ -30,7 +30,7 @@ func TestAccAppFlowFlow_basic(t *testing.T) { CheckDestroy: testAccCheckFlowDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigFlow_basic(rSourceName, rDestinationName, rFlowName), + Config: testAccFlowConfig_basic(rSourceName, rDestinationName, rFlowName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowExists(resourceName, &flowOutput), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appflow", regexp.MustCompile(`flow/.+`)), @@ -74,13 +74,13 @@ func TestAccAppFlowFlow_update(t *testing.T) { CheckDestroy: testAccCheckFlowDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigFlow_basic(rSourceName, rDestinationName, rFlowName), + Config: testAccFlowConfig_basic(rSourceName, rDestinationName, rFlowName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowExists(resourceName, &flowOutput), ), }, { - Config: testAccConfigFlow_update(rSourceName, rDestinationName, rFlowName, description), + Config: testAccFlowConfig_update(rSourceName, rDestinationName, rFlowName, description), Check: resource.ComposeTestCheckFunc( testAccCheckFlowExists(resourceName, &flowOutput), resource.TestCheckResourceAttr(resourceName, "description", description), @@ -90,6 +90,32 @@ func TestAccAppFlowFlow_update(t *testing.T) { }) } +func TestAccAppFlowFlow_TaskProperties(t *testing.T) { + var flowOutput appflow.FlowDefinition + rSourceName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rDestinationName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rFlowName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_appflow_flow.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, appflow.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckFlowDestroy, + Steps: []resource.TestStep{ + { + Config: testAccFlowConfig_taskProperties(rSourceName, rDestinationName, rFlowName), + Check: resource.ComposeTestCheckFunc( + testAccCheckFlowExists(resourceName, &flowOutput), + resource.TestCheckResourceAttr(resourceName, "task.0.task_properties.%", "2"), + resource.TestCheckResourceAttr(resourceName, "task.0.task_properties.SOURCE_DATA_TYPE", "CSV"), + resource.TestCheckResourceAttr(resourceName, "task.0.task_properties.DESTINATION_DATA_TYPE", "CSV"), + ), + }, + }, + }) +} + func TestAccAppFlowFlow_tags(t *testing.T) { var flowOutput appflow.FlowDefinition rSourceName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -104,7 +130,7 @@ func TestAccAppFlowFlow_tags(t *testing.T) { CheckDestroy: testAccCheckFlowDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigFlow_tags1(rSourceName, rDestinationName, rFlowName, "key1", "value1"), + Config: testAccFlowConfig_tags1(rSourceName, rDestinationName, rFlowName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFlowExists(resourceName, &flowOutput), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -117,7 +143,7 @@ func TestAccAppFlowFlow_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigFlow_tags2(rSourceName, rDestinationName, rFlowName, "key1", "value1updated", "key2", "value2"), + Config: testAccFlowConfig_tags2(rSourceName, rDestinationName, rFlowName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFlowExists(resourceName, &flowOutput), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -126,7 +152,7 @@ func TestAccAppFlowFlow_tags(t *testing.T) { ), }, { - Config: testAccConfigFlow_tags1(rSourceName, rDestinationName, rFlowName, "key2", "value2"), + Config: testAccFlowConfig_tags1(rSourceName, rDestinationName, rFlowName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFlowExists(resourceName, &flowOutput), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -151,7 +177,7 @@ func TestAccAppFlowFlow_disappears(t *testing.T) { CheckDestroy: testAccCheckFlowDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigFlow_basic(rSourceName, rDestinationName, rFlowName), + Config: testAccFlowConfig_basic(rSourceName, rDestinationName, rFlowName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowExists(resourceName, &flowOutput), acctest.CheckResourceDisappears(acctest.Provider, tfappflow.ResourceFlow(), resourceName), @@ -239,7 +265,7 @@ EOF `, rSourceName, rDestinationName) } -func testAccConfigFlow_basic(rSourceName string, rDestinationName string, rFlowName string) string { +func testAccFlowConfig_basic(rSourceName string, rDestinationName string, rFlowName string) string { return acctest.ConfigCompose( testAccConfigFlowBase(rSourceName, rDestinationName), fmt.Sprintf(` @@ -289,7 +315,7 @@ resource "aws_appflow_flow" "test" { ) } -func testAccConfigFlow_update(rSourceName string, rDestinationName string, rFlowName string, description string) string { +func testAccFlowConfig_update(rSourceName string, rDestinationName string, rFlowName string, description string) string { return acctest.ConfigCompose( testAccConfigFlowBase(rSourceName, rDestinationName), fmt.Sprintf(` @@ -340,7 +366,62 @@ resource "aws_appflow_flow" "test" { ) } -func testAccConfigFlow_tags1(rSourceName string, rDestinationName string, rFlowName string, tagKey1 string, tagValue1 string) string { +func testAccFlowConfig_taskProperties(rSourceName string, rDestinationName string, rFlowName string) string { + return acctest.ConfigCompose( + testAccConfigFlowBase(rSourceName, rDestinationName), + fmt.Sprintf(` +resource "aws_appflow_flow" "test" { + name = %[3]q + + source_flow_config { + connector_type = "S3" + source_connector_properties { + s3 { + bucket_name = aws_s3_bucket_policy.test_source.bucket + bucket_prefix = "flow" + } + } + } + + destination_flow_config { + connector_type = "S3" + destination_connector_properties { + s3 { + bucket_name = aws_s3_bucket_policy.test_destination.bucket + + s3_output_format_config { + prefix_config { + prefix_type = "PATH" + } + } + } + } + } + + task { + source_fields = ["testField"] + destination_field = "testField" + task_type = "Map" + + task_properties = { + SOURCE_DATA_TYPE = "CSV" + DESTINATION_DATA_TYPE = "CSV" + } + + connector_operator { + s3 = "NO_OP" + } + } + + trigger_config { + trigger_type = "OnDemand" + } +} +`, rSourceName, rDestinationName, rFlowName), + ) +} + +func testAccFlowConfig_tags1(rSourceName string, rDestinationName string, rFlowName string, tagKey1 string, tagValue1 string) string { return acctest.ConfigCompose( testAccConfigFlowBase(rSourceName, rDestinationName), fmt.Sprintf(` @@ -394,7 +475,7 @@ resource "aws_appflow_flow" "test" { ) } -func testAccConfigFlow_tags2(rSourceName string, rDestinationName string, rFlowName string, tagKey1 string, tagValue1 string, tagKey2 string, tagValue2 string) string { +func testAccFlowConfig_tags2(rSourceName string, rDestinationName string, rFlowName string, tagKey1 string, tagValue1 string, tagKey2 string, tagValue2 string) string { return acctest.ConfigCompose( testAccConfigFlowBase(rSourceName, rDestinationName), fmt.Sprintf(` @@ -457,7 +538,7 @@ func testAccCheckFlowExists(resourceName string, flow *appflow.FlowDefinition) r } conn := acctest.Provider.Meta().(*conns.AWSClient).AppFlowConn - resp, err := tfappflow.FindFlowByArn(context.Background(), conn, rs.Primary.ID) + resp, err := tfappflow.FindFlowByARN(context.Background(), conn, rs.Primary.ID) if err != nil { return err @@ -481,7 +562,7 @@ func testAccCheckFlowDestroy(s *terraform.State) error { continue } - _, err := tfappflow.FindFlowByArn(context.Background(), conn, rs.Primary.ID) + _, err := tfappflow.FindFlowByARN(context.Background(), conn, rs.Primary.ID) if tfresource.NotFound(err) { continue diff --git a/internal/service/appflow/status.go b/internal/service/appflow/status.go index a2d62409d06..b4e839148c9 100644 --- a/internal/service/appflow/status.go +++ b/internal/service/appflow/status.go @@ -11,7 +11,7 @@ import ( func FlowStatus(ctx context.Context, conn *appflow.Appflow, id string) resource.StateRefreshFunc { return func() (interface{}, string, error) { - out, err := FindFlowByArn(ctx, conn, id) + out, err := FindFlowByARN(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil diff --git a/internal/service/appintegrations/event_integration_test.go b/internal/service/appintegrations/event_integration_test.go index e2ac3e2372b..3dba75ac829 100644 --- a/internal/service/appintegrations/event_integration_test.go +++ b/internal/service/appintegrations/event_integration_test.go @@ -15,7 +15,7 @@ import ( tfappintegrations "github.com/hashicorp/terraform-provider-aws/internal/service/appintegrations" ) -func TestAccEventIntegration_basic(t *testing.T) { +func TestAccAppIntegrationsEventIntegration_basic(t *testing.T) { var eventIntegration appintegrationsservice.GetEventIntegrationOutput rName := sdkacctest.RandomWithPrefix("resource-test-terraform") @@ -74,7 +74,7 @@ func TestAccEventIntegration_basic(t *testing.T) { }) } -func TestAccEventIntegration_updateTags(t *testing.T) { +func TestAccAppIntegrationsEventIntegration_updateTags(t *testing.T) { var eventIntegration appintegrationsservice.GetEventIntegrationOutput rName := sdkacctest.RandomWithPrefix("resource-test-terraform") @@ -153,7 +153,7 @@ func TestAccEventIntegration_updateTags(t *testing.T) { }) } -func TestAccEventIntegration_disappears(t *testing.T) { +func TestAccAppIntegrationsEventIntegration_disappears(t *testing.T) { var eventIntegration appintegrationsservice.GetEventIntegrationOutput rName := sdkacctest.RandomWithPrefix("resource-test-terraform") diff --git a/internal/service/applicationinsights/application.go b/internal/service/applicationinsights/application.go new file mode 100644 index 00000000000..49129aaa031 --- /dev/null +++ b/internal/service/applicationinsights/application.go @@ -0,0 +1,230 @@ +package applicationinsights + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" + "github.com/aws/aws-sdk-go/service/applicationinsights" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "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" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceApplication() *schema.Resource { + return &schema.Resource{ + Create: resourceApplicationCreate, + Read: resourceApplicationRead, + Update: resourceApplicationUpdate, + Delete: resourceApplicationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "auto_config_enabled": { + Type: schema.TypeBool, + Optional: true, + }, + "auto_create": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "cwe_monitor_enabled": { + Type: schema.TypeBool, + Optional: true, + }, + "grouping_type": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(applicationinsights.GroupingType_Values(), false), + }, + "ops_center_enabled": { + Type: schema.TypeBool, + Optional: true, + }, + "ops_item_sns_topic_arn": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: verify.ValidARN, + }, + "resource_group_name": { + Type: schema.TypeString, + Required: true, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourceApplicationCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).ApplicationInsightsConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + input := &applicationinsights.CreateApplicationInput{ + AutoConfigEnabled: aws.Bool(d.Get("auto_config_enabled").(bool)), + AutoCreate: aws.Bool(d.Get("auto_create").(bool)), + CWEMonitorEnabled: aws.Bool(d.Get("cwe_monitor_enabled").(bool)), + OpsCenterEnabled: aws.Bool(d.Get("ops_center_enabled").(bool)), + ResourceGroupName: aws.String(d.Get("resource_group_name").(string)), + Tags: Tags(tags.IgnoreAWS()), + } + + if v, ok := d.GetOk("grouping_type"); ok { + input.GroupingType = aws.String(v.(string)) + } + + if v, ok := d.GetOk("ops_item_sns_topic_arn"); ok { + input.OpsItemSNSTopicArn = aws.String(v.(string)) + } + + out, err := conn.CreateApplication(input) + if err != nil { + return fmt.Errorf("Error creating ApplicationInsights Application: %w", err) + } + + d.SetId(aws.StringValue(out.ApplicationInfo.ResourceGroupName)) + + if _, err := waitApplicationCreated(conn, d.Id()); err != nil { + return fmt.Errorf("waiting for ApplicationInsights Application (%s) create: %w", d.Id(), err) + } + + return resourceApplicationRead(d, meta) +} + +func resourceApplicationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).ApplicationInsightsConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + application, err := FindApplicationByName(conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] ApplicationInsights Application (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error reading ApplicationInsights Application (%s): %w", d.Id(), err) + } + + arn := arn.ARN{ + AccountID: meta.(*conns.AWSClient).AccountID, + Partition: meta.(*conns.AWSClient).Partition, + Region: meta.(*conns.AWSClient).Region, + Resource: fmt.Sprintf("application/resource-group/%s", aws.StringValue(application.ResourceGroupName)), + Service: "applicationinsights", + }.String() + + d.Set("arn", arn) + d.Set("resource_group_name", application.ResourceGroupName) + d.Set("auto_config_enabled", application.AutoConfigEnabled) + d.Set("cwe_monitor_enabled", application.CWEMonitorEnabled) + d.Set("ops_center_enabled", application.OpsCenterEnabled) + d.Set("ops_item_sns_topic_arn", application.OpsItemSNSTopicArn) + + tags, err := ListTags(conn, arn) + + if err != nil { + return fmt.Errorf("error listing tags for ApplicationInsights Application (%s): %w", arn, err) + } + + tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %w", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return fmt.Errorf("error setting tags_all: %w", err) + } + + return nil +} + +func resourceApplicationUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).ApplicationInsightsConn + + if d.HasChangesExcept("tags", "tags_all") { + input := &applicationinsights.UpdateApplicationInput{ + ResourceGroupName: aws.String(d.Id()), + } + + if d.HasChange("auto_config_enabled") { + input.AutoConfigEnabled = aws.Bool(d.Get("auto_config_enabled").(bool)) + } + + if d.HasChange("cwe_monitor_enabled") { + input.CWEMonitorEnabled = aws.Bool(d.Get("cwe_monitor_enabled").(bool)) + } + + if d.HasChange("ops_center_enabled") { + input.OpsCenterEnabled = aws.Bool(d.Get("ops_center_enabled").(bool)) + } + + if d.HasChange("ops_item_sns_topic_arn") { + _, n := d.GetChange("ops_item_sns_topic_arn") + if n != nil { + input.OpsItemSNSTopicArn = aws.String(n.(string)) + } else { + input.RemoveSNSTopic = aws.Bool(true) + } + + } + + log.Printf("[DEBUG] Updating ApplicationInsights Application: %s", d.Id()) + _, err := conn.UpdateApplication(input) + if err != nil { + return fmt.Errorf("Error Updating ApplicationInsights Application: %w", err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating ApplicationInsights Application (%s) tags: %w", d.Get("arn").(string), err) + } + } + + return resourceApplicationRead(d, meta) +} + +func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).ApplicationInsightsConn + + input := &applicationinsights.DeleteApplicationInput{ + ResourceGroupName: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Deleting ApplicationInsights Application: %s", d.Id()) + _, err := conn.DeleteApplication(input) + if err != nil { + if tfawserr.ErrCodeEquals(err, applicationinsights.ErrCodeResourceNotFoundException) { + return nil + } + return fmt.Errorf("Error deleting ApplicationInsights Application: %w", err) + } + + if _, err := waitApplicationTerminated(conn, d.Id()); err != nil { + return fmt.Errorf("waiting for ApplicationInsights Application (%s) delete: %w", d.Id(), err) + } + + return nil +} diff --git a/internal/service/applicationinsights/application_test.go b/internal/service/applicationinsights/application_test.go new file mode 100644 index 00000000000..638d8b70c8a --- /dev/null +++ b/internal/service/applicationinsights/application_test.go @@ -0,0 +1,277 @@ +package applicationinsights_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/applicationinsights" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfapplicationinsights "github.com/hashicorp/terraform-provider-aws/internal/service/applicationinsights" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccApplicationInsightsApplication_basic(t *testing.T) { + var app applicationinsights.ApplicationInfo + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_applicationinsights_application.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, applicationinsights.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &app), + resource.TestCheckResourceAttr(resourceName, "resource_group_name", rName), + acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "applicationinsights", fmt.Sprintf("application/resource-group/%s", rName)), + resource.TestCheckResourceAttr(resourceName, "auto_config_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "cwe_monitor_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "ops_center_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccApplicationConfig_updated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &app), + resource.TestCheckResourceAttr(resourceName, "resource_group_name", rName), + acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "applicationinsights", fmt.Sprintf("application/resource-group/%s", rName)), + resource.TestCheckResourceAttr(resourceName, "auto_config_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "cwe_monitor_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "ops_center_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + }, + }) +} + +func TestAccApplicationInsightsApplication_autoConfig(t *testing.T) { + var app applicationinsights.ApplicationInfo + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_applicationinsights_application.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, applicationinsights.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_updated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &app), + resource.TestCheckResourceAttr(resourceName, "resource_group_name", rName), + acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "applicationinsights", fmt.Sprintf("application/resource-group/%s", rName)), + resource.TestCheckResourceAttr(resourceName, "auto_config_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "cwe_monitor_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "ops_center_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccApplicationInsightsApplication_tags(t *testing.T) { + var app applicationinsights.ApplicationInfo + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_applicationinsights_application.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, applicationinsights.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &app), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccApplicationConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &app), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccApplicationConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &app), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func TestAccApplicationInsightsApplication_disappears(t *testing.T) { + var app applicationinsights.ApplicationInfo + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_applicationinsights_application.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, applicationinsights.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &app), + acctest.CheckResourceDisappears(acctest.Provider, tfapplicationinsights.ResourceApplication(), resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfapplicationinsights.ResourceApplication(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckApplicationDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).ApplicationInsightsConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_applicationinsights_application" { + continue + } + + app, err := tfapplicationinsights.FindApplicationByName(conn, rs.Primary.ID) + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + if aws.StringValue(app.ResourceGroupName) == rs.Primary.ID { + return fmt.Errorf("applicationinsights Application %q still exists", rs.Primary.ID) + } + } + + return nil +} + +func testAccCheckApplicationExists(n string, app *applicationinsights.ApplicationInfo) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No applicationinsights Application ID is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).ApplicationInsightsConn + resp, err := tfapplicationinsights.FindApplicationByName(conn, rs.Primary.ID) + if err != nil { + return err + } + + *app = *resp + + return nil + } +} + +func testAccApplicationConfigBase(rName string) string { + return fmt.Sprintf(` +resource "aws_resourcegroups_group" "test" { + name = %[1]q + + resource_query { + query = < 0 { + input := &applicationinsights.UntagResourceInput{ + ResourceARN: aws.String(identifier), + TagKeys: aws.StringSlice(removedTags.IgnoreAWS().Keys()), + } + + _, err := conn.UntagResource(input) + + if err != nil { + return fmt.Errorf("error untagging resource (%s): %w", identifier, err) + } + } + + if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 { + input := &applicationinsights.TagResourceInput{ + ResourceARN: aws.String(identifier), + Tags: Tags(updatedTags.IgnoreAWS()), + } + + _, err := conn.TagResource(input) + + if err != nil { + return fmt.Errorf("error tagging resource (%s): %w", identifier, err) + } + } + + return nil +} diff --git a/internal/service/applicationinsights/wait.go b/internal/service/applicationinsights/wait.go new file mode 100644 index 00000000000..3731ebd3116 --- /dev/null +++ b/internal/service/applicationinsights/wait.go @@ -0,0 +1,46 @@ +package applicationinsights + +import ( + "time" + + "github.com/aws/aws-sdk-go/service/applicationinsights" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + ApplicationCreatedTimeout = 2 * time.Minute + + ApplicationDeletedTimeout = 2 * time.Minute +) + +func waitApplicationCreated(conn *applicationinsights.ApplicationInsights, name string) (*applicationinsights.ApplicationInfo, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{"CREATING"}, + Target: []string{"NOT_CONFIGURED"}, + Refresh: statusApplication(conn, name), + Timeout: ApplicationCreatedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + if output, ok := outputRaw.(*applicationinsights.ApplicationInfo); ok { + return output, err + } + + return nil, err +} + +func waitApplicationTerminated(conn *applicationinsights.ApplicationInsights, name string) (*applicationinsights.ApplicationInfo, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{"NOT_CONFIGURED", "DELETING"}, + Target: []string{}, + Refresh: statusApplication(conn, name), + Timeout: ApplicationDeletedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + if output, ok := outputRaw.(*applicationinsights.ApplicationInfo); ok { + return output, err + } + + return nil, err +} diff --git a/internal/service/appmesh/mesh_data_source_test.go b/internal/service/appmesh/mesh_data_source_test.go index ec672188a40..22ba64e411e 100644 --- a/internal/service/appmesh/mesh_data_source_test.go +++ b/internal/service/appmesh/mesh_data_source_test.go @@ -22,7 +22,7 @@ func TestAccAppMeshMeshDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckMeshDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckMeshDataSourceConfig(rName), + Config: testAccMeshDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "created_date", dataSourceName, "created_date"), @@ -50,7 +50,7 @@ func TestAccAppMeshMeshDataSource_meshOwner(t *testing.T) { CheckDestroy: testAccCheckMeshDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckMeshDataSourceConfig_meshOwner(rName), + Config: testAccMeshDataSourceConfig_meshOwner(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "created_date", dataSourceName, "created_date"), @@ -78,7 +78,7 @@ func TestAccAppMeshMeshDataSource_specAndTagsSet(t *testing.T) { CheckDestroy: testAccCheckMeshDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckMeshDataSourceConfig_specAndTagsSet(rName), + Config: testAccMeshDataSourceConfig_specAndTagsSet(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "created_date", dataSourceName, "created_date"), @@ -94,7 +94,7 @@ func TestAccAppMeshMeshDataSource_specAndTagsSet(t *testing.T) { }) } -func testAccCheckMeshDataSourceConfig(rName string) string { +func testAccMeshDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_appmesh_mesh" "test" { name = %[1]q @@ -106,7 +106,7 @@ data "aws_appmesh_mesh" "test" { `, rName) } -func testAccCheckMeshDataSourceConfig_meshOwner(rName string) string { +func testAccMeshDataSourceConfig_meshOwner(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -121,7 +121,7 @@ data "aws_appmesh_mesh" "test" { `, rName) } -func testAccCheckMeshDataSourceConfig_specAndTagsSet(rName string) string { +func testAccMeshDataSourceConfig_specAndTagsSet(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/appmesh/virtual_service_data_source_test.go b/internal/service/appmesh/virtual_service_data_source_test.go index 2c1ce0d18e9..8fc1411b9fb 100644 --- a/internal/service/appmesh/virtual_service_data_source_test.go +++ b/internal/service/appmesh/virtual_service_data_source_test.go @@ -23,7 +23,7 @@ func TestAccAppMeshVirtualServiceDataSource_virtualNode(t *testing.T) { CheckDestroy: testAccCheckVirtualServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckVirtualServiceDataSourceConfig_virtualNode(rName, vsName), + Config: testAccVirtualServiceDataSourceConfig_virtualNode(rName, vsName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "created_date", dataSourceName, "created_date"), @@ -53,7 +53,7 @@ func TestAccAppMeshVirtualServiceDataSource_virtualRouter(t *testing.T) { CheckDestroy: testAccCheckVirtualServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckVirtualServiceDataSourceConfig_virtualRouter(rName, vsName), + Config: testAccVirtualServiceDataSourceConfig_virtualRouter(rName, vsName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "created_date", dataSourceName, "created_date"), @@ -70,7 +70,7 @@ func TestAccAppMeshVirtualServiceDataSource_virtualRouter(t *testing.T) { }) } -func testAccCheckVirtualServiceDataSourceConfig_virtualNode(rName, vsName string) string { +func testAccVirtualServiceDataSourceConfig_virtualNode(rName, vsName string) string { return fmt.Sprintf(` resource "aws_appmesh_mesh" "test" { name = %[1]q @@ -108,7 +108,7 @@ data "aws_appmesh_virtual_service" "test" { `, rName, vsName) } -func testAccCheckVirtualServiceDataSourceConfig_virtualRouter(rName, vsName string) string { +func testAccVirtualServiceDataSourceConfig_virtualRouter(rName, vsName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/apprunner/status.go b/internal/service/apprunner/status.go index f19c1b300f7..c0308ae3972 100644 --- a/internal/service/apprunner/status.go +++ b/internal/service/apprunner/status.go @@ -12,9 +12,6 @@ const ( AutoScalingConfigurationStatusActive = "active" AutoScalingConfigurationStatusInactive = "inactive" - VpcConnectorStatusActive = "ACTIVE" - VpcConnectorStatusInactive = "INACTIVE" - CustomDomainAssociationStatusActive = "active" CustomDomainAssociationStatusCreating = "creating" CustomDomainAssociationStatusDeleting = "deleting" @@ -42,7 +39,7 @@ func StatusAutoScalingConfiguration(ctx context.Context, conn *apprunner.AppRunn } } -func StatusVpcConnector(ctx context.Context, conn *apprunner.AppRunner, arn string) resource.StateRefreshFunc { +func StatusVPCConnector(ctx context.Context, conn *apprunner.AppRunner, arn string) resource.StateRefreshFunc { return func() (interface{}, string, error) { input := &apprunner.DescribeVpcConnectorInput{ VpcConnectorArn: aws.String(arn), diff --git a/internal/service/apprunner/vpc_connector.go b/internal/service/apprunner/vpc_connector.go index fc03cb51095..1598fed9254 100644 --- a/internal/service/apprunner/vpc_connector.go +++ b/internal/service/apprunner/vpc_connector.go @@ -16,11 +16,11 @@ import ( tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" ) -func ResourceVpcConnector() *schema.Resource { +func ResourceVPCConnector() *schema.Resource { return &schema.Resource{ - CreateWithoutTimeout: resourceVpcConnectorCreate, - ReadWithoutTimeout: resourceVpcConnectorRead, - DeleteWithoutTimeout: resourceVpcConnectorDelete, + CreateWithoutTimeout: resourceVPCConnectorCreate, + ReadWithoutTimeout: resourceVPCConnectorRead, + DeleteWithoutTimeout: resourceVPCConnectorDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, @@ -64,7 +64,7 @@ func ResourceVpcConnector() *schema.Resource { } } -func resourceVpcConnectorCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceVPCConnectorCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { conn := meta.(*conns.AWSClient).AppRunnerConn defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) @@ -95,14 +95,14 @@ func resourceVpcConnectorCreate(ctx context.Context, d *schema.ResourceData, met d.SetId(aws.StringValue(output.VpcConnector.VpcConnectorArn)) - if err := WaitVpcConnectorActive(ctx, conn, d.Id()); err != nil { + if err := waitVPCConnectorActive(ctx, conn, d.Id()); err != nil { return diag.FromErr(fmt.Errorf("error waiting for creating App Runner vpc (%s) creation: %w", d.Id(), err)) } - return resourceVpcConnectorRead(ctx, d, meta) + return resourceVPCConnectorRead(ctx, d, meta) } -func resourceVpcConnectorRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceVPCConnectorRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { conn := meta.(*conns.AWSClient).AppRunnerConn defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig @@ -170,7 +170,7 @@ func resourceVpcConnectorRead(ctx context.Context, d *schema.ResourceData, meta return nil } -func resourceVpcConnectorDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceVPCConnectorDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { conn := meta.(*conns.AWSClient).AppRunnerConn input := &apprunner.DeleteVpcConnectorInput{ @@ -187,7 +187,7 @@ func resourceVpcConnectorDelete(ctx context.Context, d *schema.ResourceData, met return diag.FromErr(fmt.Errorf("error deleting App Runner vpc connector (%s): %w", d.Id(), err)) } - if err := WaitVpcConnectorInactive(ctx, conn, d.Id()); err != nil { + if err := waitVPCConnectorInactive(ctx, conn, d.Id()); err != nil { if tfawserr.ErrCodeEquals(err, apprunner.ErrCodeResourceNotFoundException) { return nil } diff --git a/internal/service/apprunner/vpc_connector_test.go b/internal/service/apprunner/vpc_connector_test.go index aae3628fe0e..85bcc57bd22 100644 --- a/internal/service/apprunner/vpc_connector_test.go +++ b/internal/service/apprunner/vpc_connector_test.go @@ -17,7 +17,7 @@ import ( tfapprunner "github.com/hashicorp/terraform-provider-aws/internal/service/apprunner" ) -func TestAccAppRunnerVpcConnector_basic(t *testing.T) { +func TestAccAppRunnerVPCConnector_basic(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_apprunner_vpc_connector.test" @@ -25,12 +25,12 @@ func TestAccAppRunnerVpcConnector_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheckVPCConnector(t) }, ErrorCheck: acctest.ErrorCheck(t, apprunner.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckVpcConnectorDestroy, + CheckDestroy: testAccCheckVPCConnectorDestroy, Steps: []resource.TestStep{ { Config: testAccVPCConnectorConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckVpcConnectorExists(resourceName), + testAccCheckVPCConnectorExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "apprunner", regexp.MustCompile(fmt.Sprintf(`vpcconnector/%s/1/.+`, rName))), resource.TestCheckResourceAttr(resourceName, "vpc_connector_name", rName), resource.TestCheckResourceAttr(resourceName, "subnets.#", "1"), @@ -47,7 +47,7 @@ func TestAccAppRunnerVpcConnector_basic(t *testing.T) { }) } -func TestAccAppRunnerVpcConnector_disappears(t *testing.T) { +func TestAccAppRunnerVPCConnector_disappears(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_apprunner_vpc_connector.test" @@ -55,13 +55,13 @@ func TestAccAppRunnerVpcConnector_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheckVPCConnector(t) }, ErrorCheck: acctest.ErrorCheck(t, apprunner.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckVpcConnectorDestroy, + CheckDestroy: testAccCheckVPCConnectorDestroy, Steps: []resource.TestStep{ { Config: testAccVPCConnectorConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckVpcConnectorExists(resourceName), - acctest.CheckResourceDisappears(acctest.Provider, tfapprunner.ResourceVpcConnector(), resourceName), + testAccCheckVPCConnectorExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfapprunner.ResourceVPCConnector(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -69,7 +69,7 @@ func TestAccAppRunnerVpcConnector_disappears(t *testing.T) { }) } -func TestAccAppRunnerVpcConnector_tags(t *testing.T) { +func TestAccAppRunnerVPCConnector_tags(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_apprunner_vpc_connector.test" @@ -77,12 +77,12 @@ func TestAccAppRunnerVpcConnector_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheckVPCConnector(t) }, ErrorCheck: acctest.ErrorCheck(t, apprunner.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckVpcConnectorDestroy, + CheckDestroy: testAccCheckVPCConnectorDestroy, Steps: []resource.TestStep{ { Config: testAccVPCConnectorConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckVpcConnectorExists(resourceName), + testAccCheckVPCConnectorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), @@ -96,7 +96,7 @@ func TestAccAppRunnerVpcConnector_tags(t *testing.T) { }) } -func testAccCheckVpcConnectorDestroy(s *terraform.State) error { +func testAccCheckVPCConnectorDestroy(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "aws_apprunner_vpc_connector" { continue @@ -126,7 +126,7 @@ func testAccCheckVpcConnectorDestroy(s *terraform.State) error { return nil } -func testAccCheckVpcConnectorExists(n string) resource.TestCheckFunc { +func testAccCheckVPCConnectorExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { diff --git a/internal/service/apprunner/wait.go b/internal/service/apprunner/wait.go index 24e186f4221..ef30d9926fe 100644 --- a/internal/service/apprunner/wait.go +++ b/internal/service/apprunner/wait.go @@ -17,8 +17,8 @@ const ( CustomDomainAssociationCreateTimeout = 5 * time.Minute CustomDomainAssociationDeleteTimeout = 5 * time.Minute - VpcConnectorCreateTimeout = 2 * time.Minute - VpcConnectorDeleteTimeout = 2 * time.Minute + vpcConnectorCreateTimeout = 2 * time.Minute + vpcConnectorDeleteTimeout = 2 * time.Minute ServiceCreateTimeout = 20 * time.Minute ServiceDeleteTimeout = 20 * time.Minute @@ -129,12 +129,12 @@ func WaitServiceDeleted(ctx context.Context, conn *apprunner.AppRunner, serviceA return err } -func WaitVpcConnectorActive(ctx context.Context, conn *apprunner.AppRunner, arn string) error { +func waitVPCConnectorActive(ctx context.Context, conn *apprunner.AppRunner, arn string) error { stateConf := &resource.StateChangeConf{ Pending: []string{}, - Target: []string{VpcConnectorStatusActive}, - Refresh: StatusVpcConnector(ctx, conn, arn), - Timeout: VpcConnectorCreateTimeout, + Target: []string{apprunner.VpcConnectorStatusActive}, + Refresh: StatusVPCConnector(ctx, conn, arn), + Timeout: vpcConnectorCreateTimeout, } _, err := stateConf.WaitForState() @@ -142,12 +142,12 @@ func WaitVpcConnectorActive(ctx context.Context, conn *apprunner.AppRunner, arn return err } -func WaitVpcConnectorInactive(ctx context.Context, conn *apprunner.AppRunner, arn string) error { +func waitVPCConnectorInactive(ctx context.Context, conn *apprunner.AppRunner, arn string) error { stateConf := &resource.StateChangeConf{ - Pending: []string{VpcConnectorStatusActive}, - Target: []string{VpcConnectorStatusInactive}, - Refresh: StatusVpcConnector(ctx, conn, arn), - Timeout: VpcConnectorDeleteTimeout, + Pending: []string{apprunner.VpcConnectorStatusActive}, + Target: []string{apprunner.VpcConnectorStatusInactive}, + Refresh: StatusVPCConnector(ctx, conn, arn), + Timeout: vpcConnectorDeleteTimeout, } _, err := stateConf.WaitForState() diff --git a/internal/service/appstream/directory_config_test.go b/internal/service/appstream/directory_config_test.go index 0b2851bfc7c..b072a62efdb 100644 --- a/internal/service/appstream/directory_config_test.go +++ b/internal/service/appstream/directory_config_test.go @@ -34,7 +34,7 @@ func TestAccAppStreamDirectoryConfig_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccDirectoryConfigConfig(rName, domain, rUserName, rPassword, orgUnitDN), + Config: testAccDirectoryConfigConfig_basic(rName, domain, rUserName, rPassword, orgUnitDN), Check: resource.ComposeTestCheckFunc( testAccCheckDirectoryConfigExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "directory_name", domain), @@ -47,7 +47,7 @@ func TestAccAppStreamDirectoryConfig_basic(t *testing.T) { ), }, { - Config: testAccDirectoryConfigConfig(rName, domain, rUserNameUpdated, rPasswordUpdated, orgUnitDN), + Config: testAccDirectoryConfigConfig_basic(rName, domain, rUserNameUpdated, rPasswordUpdated, orgUnitDN), Check: resource.ComposeTestCheckFunc( testAccCheckDirectoryConfigExists(resourceName, &v2), testAccCheckDirectoryConfigNotRecreated(&v1, &v2), @@ -86,7 +86,7 @@ func TestAccAppStreamDirectoryConfig_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccDirectoryConfigConfig(rName, domain, rUserName, rPassword, orgUnitDN), + Config: testAccDirectoryConfigConfig_basic(rName, domain, rUserName, rPassword, orgUnitDN), Check: resource.ComposeTestCheckFunc( testAccCheckDirectoryConfigExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfappstream.ResourceDirectoryConfig(), resourceName), @@ -114,7 +114,7 @@ func TestAccAppStreamDirectoryConfig_OrganizationalUnitDistinguishedNames(t *tes ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccDirectoryConfigConfig(rName, domain, rUserName, rPassword, orgUnitDN1), + Config: testAccDirectoryConfigConfig_basic(rName, domain, rUserName, rPassword, orgUnitDN1), Check: resource.ComposeTestCheckFunc( testAccCheckDirectoryConfigExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "directory_name", domain), @@ -123,7 +123,7 @@ func TestAccAppStreamDirectoryConfig_OrganizationalUnitDistinguishedNames(t *tes ), }, { - Config: testAccDirectoryConfig_OrganizationalUnitDistinguishedNamesConfig(rName, domain, rUserName, rPassword, orgUnitDN1, orgUnitDN2), + Config: testAccDirectoryConfigConfig_organizationalUnitDistinguishedNames(rName, domain, rUserName, rPassword, orgUnitDN1, orgUnitDN2), Check: resource.ComposeTestCheckFunc( testAccCheckDirectoryConfigExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "directory_name", domain), @@ -133,7 +133,7 @@ func TestAccAppStreamDirectoryConfig_OrganizationalUnitDistinguishedNames(t *tes ), }, { - Config: testAccDirectoryConfigConfig(rName, domain, rUserName, rPassword, orgUnitDN2), + Config: testAccDirectoryConfigConfig_basic(rName, domain, rUserName, rPassword, orgUnitDN2), Check: resource.ComposeTestCheckFunc( testAccCheckDirectoryConfigExists(resourceName, &v3), resource.TestCheckResourceAttr(resourceName, "directory_name", domain), @@ -214,9 +214,9 @@ func orgUnitFromDomain(orgUnit, domainName string) string { return sb.String() } -func testAccDirectoryConfigConfig(rName, domain, userName, password, orgUnitDN string) string { +func testAccDirectoryConfigConfig_basic(rName, domain, userName, password, orgUnitDN string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_appstream_directory_config" "test" { directory_name = %[1]q @@ -246,9 +246,9 @@ resource "aws_directory_service_directory" "test" { `, domain, userName, password, orgUnitDN)) } -func testAccDirectoryConfig_OrganizationalUnitDistinguishedNamesConfig(rName, domain, userName, password, orgUnitDN1, orgUnitDN2 string) string { +func testAccDirectoryConfigConfig_organizationalUnitDistinguishedNames(rName, domain, userName, password, orgUnitDN1, orgUnitDN2 string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_appstream_directory_config" "test" { directory_name = %[1]q diff --git a/internal/service/appstream/fleet.go b/internal/service/appstream/fleet.go index fbc8168e219..9084d3c6a6c 100644 --- a/internal/service/appstream/fleet.go +++ b/internal/service/appstream/fleet.go @@ -246,7 +246,7 @@ func resourceFleetCreate(ctx context.Context, d *schema.ResourceData, meta inter } if v, ok := d.GetOk("vpc_config"); ok { - input.VpcConfig = expandVpcConfig(v.([]interface{})) + input.VpcConfig = expandVPCConfig(v.([]interface{})) } if len(tags) > 0 { @@ -347,7 +347,7 @@ func resourceFleetRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set("state", fleet.State) d.Set("stream_view", fleet.StreamView) - if err = d.Set("vpc_config", flattenVpcConfig(fleet.VpcConfig)); err != nil { + if err = d.Set("vpc_config", flattenVPCConfig(fleet.VpcConfig)); err != nil { return diag.FromErr(fmt.Errorf("error setting `%s` for AppStream Fleet (%s): %w", "vpc_config", d.Id(), err)) } @@ -454,7 +454,7 @@ func resourceFleetUpdate(ctx context.Context, d *schema.ResourceData, meta inter } if d.HasChange("vpc_config") { - input.VpcConfig = expandVpcConfig(d.Get("vpc_config").([]interface{})) + input.VpcConfig = expandVPCConfig(d.Get("vpc_config").([]interface{})) } resp, err := conn.UpdateFleetWithContext(ctx, input) @@ -579,7 +579,7 @@ func flattenDomainInfo(apiObject *appstream.DomainJoinInfo) []interface{} { return []interface{}{tfList} } -func expandVpcConfig(tfList []interface{}) *appstream.VpcConfig { +func expandVPCConfig(tfList []interface{}) *appstream.VpcConfig { if len(tfList) == 0 { return nil } @@ -597,7 +597,7 @@ func expandVpcConfig(tfList []interface{}) *appstream.VpcConfig { return apiObject } -func flattenVpcConfig(apiObject *appstream.VpcConfig) []interface{} { +func flattenVPCConfig(apiObject *appstream.VpcConfig) []interface{} { if apiObject == nil { return nil } diff --git a/internal/service/appstream/fleet_stack_association_test.go b/internal/service/appstream/fleet_stack_association_test.go index a5ea54c5ab3..1a88626c99d 100644 --- a/internal/service/appstream/fleet_stack_association_test.go +++ b/internal/service/appstream/fleet_stack_association_test.go @@ -29,7 +29,7 @@ func TestAccAppStreamFleetStackAssociation_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccFleetStackAssociationConfig(rName), + Config: testAccFleetStackAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFleetStackAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "fleet_name", rName), @@ -59,7 +59,7 @@ func TestAccAppStreamFleetStackAssociation_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccFleetStackAssociationConfig(rName), + Config: testAccFleetStackAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFleetStackAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfappstream.ResourceFleetStackAssociation(), resourceName), @@ -127,7 +127,7 @@ func testAccCheckFleetStackAssociationDestroy(s *terraform.State) error { return nil } -func testAccFleetStackAssociationConfig(name string) string { +func testAccFleetStackAssociationConfig_basic(name string) string { // "Amazon-AppStream2-Sample-Image-02-04-2019" is not available in GovCloud return fmt.Sprintf(` resource "aws_appstream_fleet" "test" { diff --git a/internal/service/appstream/fleet_test.go b/internal/service/appstream/fleet_test.go index 28b7e3bab05..c01db2a0ab4 100644 --- a/internal/service/appstream/fleet_test.go +++ b/internal/service/appstream/fleet_test.go @@ -44,7 +44,7 @@ func TestAccAppStreamFleet_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccFleetConfig(rName, instanceType), + Config: testAccFleetConfig_basic(rName, instanceType), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleetOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -79,7 +79,7 @@ func TestAccAppStreamFleet_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccFleetConfig(rName, instanceType), + Config: testAccFleetConfig_basic(rName, instanceType), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleetOutput), acctest.CheckResourceDisappears(acctest.Provider, tfappstream.ResourceFleet(), resourceName), @@ -110,7 +110,7 @@ func TestAccAppStreamFleet_completeWithStop(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccFleetCompleteConfig(rName, description, fleetType, instanceType), + Config: testAccFleetConfig_complete(rName, description, fleetType, instanceType), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleetOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -122,7 +122,7 @@ func TestAccAppStreamFleet_completeWithStop(t *testing.T) { ), }, { - Config: testAccFleetCompleteConfig(rName, descriptionUpdated, fleetType, instanceTypeUpdate), + Config: testAccFleetConfig_complete(rName, descriptionUpdated, fleetType, instanceTypeUpdate), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleetOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -162,7 +162,7 @@ func TestAccAppStreamFleet_completeWithoutStop(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccFleetCompleteWithoutStoppingConfig(rName, description, fleetType, instanceType, displayName), + Config: testAccFleetConfig_completeNoStopping(rName, description, fleetType, instanceType, displayName), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleetOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -174,7 +174,7 @@ func TestAccAppStreamFleet_completeWithoutStop(t *testing.T) { ), }, { - Config: testAccFleetCompleteWithoutStoppingConfig(rName, description, fleetType, instanceType, displayNameUpdated), + Config: testAccFleetConfig_completeNoStopping(rName, description, fleetType, instanceType, displayNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleetOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -215,7 +215,7 @@ func TestAccAppStreamFleet_withTags(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccFleetWithTagsConfig(rName, description, fleetType, instanceType, displayName), + Config: testAccFleetConfig_tags(rName, description, fleetType, instanceType, displayName), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleetOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -230,7 +230,7 @@ func TestAccAppStreamFleet_withTags(t *testing.T) { ), }, { - Config: testAccFleetWithTagsConfig(rName, description, fleetType, instanceType, displayNameUpdated), + Config: testAccFleetConfig_tags(rName, description, fleetType, instanceType, displayNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleetOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -303,7 +303,7 @@ func testAccCheckFleetDestroy(s *terraform.State) error { return nil } -func testAccFleetConfig(name, instanceType string) string { +func testAccFleetConfig_basic(name, instanceType string) string { // "Amazon-AppStream2-Sample-Image-02-04-2019" is not available in GovCloud return fmt.Sprintf(` resource "aws_appstream_fleet" "test" { @@ -318,7 +318,7 @@ resource "aws_appstream_fleet" "test" { `, name, instanceType) } -func testAccFleetCompleteConfig(name, description, fleetType, instanceType string) string { +func testAccFleetConfig_complete(name, description, fleetType, instanceType string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -359,7 +359,7 @@ resource "aws_appstream_fleet" "test" { `, name, description, fleetType, instanceType)) } -func testAccFleetCompleteWithoutStoppingConfig(name, description, fleetType, instanceType, displayName string) string { +func testAccFleetConfig_completeNoStopping(name, description, fleetType, instanceType, displayName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -397,7 +397,7 @@ resource "aws_appstream_fleet" "test" { `, name, description, fleetType, instanceType, displayName)) } -func testAccFleetWithTagsConfig(name, description, fleetType, instanceType, displayName string) string { +func testAccFleetConfig_tags(name, description, fleetType, instanceType, displayName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` diff --git a/internal/service/appstream/image_builder.go b/internal/service/appstream/image_builder.go index f39274d6557..ccf93db29c6 100644 --- a/internal/service/appstream/image_builder.go +++ b/internal/service/appstream/image_builder.go @@ -218,7 +218,7 @@ func resourceImageBuilderCreate(ctx context.Context, d *schema.ResourceData, met } if v, ok := d.GetOk("vpc_config"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - input.VpcConfig = expandImageBuilderVpcConfig(v.([]interface{})) + input.VpcConfig = expandImageBuilderVPCConfig(v.([]interface{})) } if len(tags) > 0 { @@ -281,7 +281,7 @@ func resourceImageBuilderRead(ctx context.Context, d *schema.ResourceData, meta return diag.FromErr(fmt.Errorf("error setting `%s` for AppStream ImageBuilder (%s): %w", "domain_join_info", d.Id(), err)) } - if err = d.Set("vpc_config", flattenVpcConfig(imageBuilder.VpcConfig)); err != nil { + if err = d.Set("vpc_config", flattenVPCConfig(imageBuilder.VpcConfig)); err != nil { return diag.FromErr(fmt.Errorf("error setting `%s` for AppStream ImageBuilder (%s): %w", "vpc_config", d.Id(), err)) } @@ -347,7 +347,7 @@ func resourceImageBuilderDelete(ctx context.Context, d *schema.ResourceData, met return nil } -func expandImageBuilderVpcConfig(tfList []interface{}) *appstream.VpcConfig { +func expandImageBuilderVPCConfig(tfList []interface{}) *appstream.VpcConfig { if len(tfList) == 0 { return nil } diff --git a/internal/service/appstream/image_builder_test.go b/internal/service/appstream/image_builder_test.go index 8cd8ac27e78..0b661b0af85 100644 --- a/internal/service/appstream/image_builder_test.go +++ b/internal/service/appstream/image_builder_test.go @@ -27,7 +27,7 @@ func TestAccAppStreamImageBuilder_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccImageBuilderConfig(instanceType, rName), + Config: testAccImageBuilderConfig_basic(instanceType, rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageBuilderExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -57,7 +57,7 @@ func TestAccAppStreamImageBuilder_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccImageBuilderConfig(instanceType, rName), + Config: testAccImageBuilderConfig_basic(instanceType, rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageBuilderExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfappstream.ResourceImageBuilder(), resourceName), @@ -83,7 +83,7 @@ func TestAccAppStreamImageBuilder_complete(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccImageBuilderCompleteConfig(rName, description, instanceType), + Config: testAccImageBuilderConfig_complete(rName, description, instanceType), Check: resource.ComposeTestCheckFunc( testAccCheckImageBuilderExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -100,7 +100,7 @@ func TestAccAppStreamImageBuilder_complete(t *testing.T) { ImportStateVerifyIgnore: []string{"image_name"}, }, { - Config: testAccImageBuilderCompleteConfig(rName, descriptionUpdated, instanceTypeUpdate), + Config: testAccImageBuilderConfig_complete(rName, descriptionUpdated, instanceTypeUpdate), Check: resource.ComposeTestCheckFunc( testAccCheckImageBuilderExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -132,7 +132,7 @@ func TestAccAppStreamImageBuilder_tags(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccImageBuilderTags1Config(instanceType, rName, "key1", "value1"), + Config: testAccImageBuilderConfig_tags1(instanceType, rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckImageBuilderExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -146,7 +146,7 @@ func TestAccAppStreamImageBuilder_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"image_name"}, }, { - Config: testAccImageBuilderTags2Config(instanceType, rName, "key1", "value1updated", "key2", "value2"), + Config: testAccImageBuilderConfig_tags2(instanceType, rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckImageBuilderExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -155,7 +155,7 @@ func TestAccAppStreamImageBuilder_tags(t *testing.T) { ), }, { - Config: testAccImageBuilderTags1Config(instanceType, rName, "key2", "value2"), + Config: testAccImageBuilderConfig_tags1(instanceType, rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckImageBuilderExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -181,7 +181,7 @@ func TestAccAppStreamImageBuilder_imageARN(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccImageBuilderByImageARNConfig(rName, imageName, instanceType), + Config: testAccImageBuilderConfig_byARN(rName, imageName, instanceType), Check: resource.ComposeTestCheckFunc( testAccCheckImageBuilderExists(resourceName), acctest.CheckResourceAttrRegionalARNNoAccount(resourceName, "image_arn", "appstream", fmt.Sprintf("image/%s", imageName)), @@ -245,7 +245,7 @@ func testAccCheckImageBuilderDestroy(s *terraform.State) error { return nil } -func testAccImageBuilderConfig(instanceType, name string) string { +func testAccImageBuilderConfig_basic(instanceType, name string) string { return fmt.Sprintf(` resource "aws_appstream_image_builder" "test" { image_name = "AppStream-WinServer2012R2-07-19-2021" @@ -255,7 +255,7 @@ resource "aws_appstream_image_builder" "test" { `, instanceType, name) } -func testAccImageBuilderCompleteConfig(name, description, instanceType string) string { +func testAccImageBuilderConfig_complete(name, description, instanceType string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -282,7 +282,7 @@ resource "aws_appstream_image_builder" "test" { `, name, description, instanceType)) } -func testAccImageBuilderTags1Config(instanceType, name, key, value string) string { +func testAccImageBuilderConfig_tags1(instanceType, name, key, value string) string { return fmt.Sprintf(` resource "aws_appstream_image_builder" "test" { image_name = "AppStream-WinServer2012R2-07-19-2021" @@ -296,7 +296,7 @@ resource "aws_appstream_image_builder" "test" { `, instanceType, name, key, value) } -func testAccImageBuilderTags2Config(instanceType, name, key1, value1, key2, value2 string) string { +func testAccImageBuilderConfig_tags2(instanceType, name, key1, value1, key2, value2 string) string { return fmt.Sprintf(` resource "aws_appstream_image_builder" "test" { image_name = "AppStream-WinServer2012R2-07-19-2021" @@ -311,7 +311,7 @@ resource "aws_appstream_image_builder" "test" { `, instanceType, name, key1, value1, key2, value2) } -func testAccImageBuilderByImageARNConfig(rName, imageName, instanceType string) string { +func testAccImageBuilderConfig_byARN(rName, imageName, instanceType string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/appstream/stack_test.go b/internal/service/appstream/stack_test.go index f23df3134b2..49a036ffdc7 100644 --- a/internal/service/appstream/stack_test.go +++ b/internal/service/appstream/stack_test.go @@ -27,7 +27,7 @@ func TestAccAppStreamStack_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccStackConfig(rName), + Config: testAccStackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, &stackOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -55,7 +55,7 @@ func TestAccAppStreamStack_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccStackConfig(rName), + Config: testAccStackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, &stackOutput), acctest.CheckResourceDisappears(acctest.Provider, tfappstream.ResourceStack(), resourceName), @@ -80,7 +80,7 @@ func TestAccAppStreamStack_complete(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccStackCompleteConfig(rName, description), + Config: testAccStackConfig_complete(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, &stackOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -89,7 +89,7 @@ func TestAccAppStreamStack_complete(t *testing.T) { ), }, { - Config: testAccStackCompleteConfig(rName, descriptionUpdated), + Config: testAccStackConfig_complete(rName, descriptionUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, &stackOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -120,7 +120,7 @@ func TestAccAppStreamStack_withTags(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccStackCompleteConfig(rName, description), + Config: testAccStackConfig_complete(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, &stackOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -129,7 +129,7 @@ func TestAccAppStreamStack_withTags(t *testing.T) { ), }, { - Config: testAccStackWithTagsConfig(rName, descriptionUpdated), + Config: testAccStackConfig_tags(rName, descriptionUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, &stackOutput), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -201,7 +201,7 @@ func testAccCheckStackDestroy(s *terraform.State) error { } -func testAccStackConfig(name string) string { +func testAccStackConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_appstream_stack" "test" { name = %[1]q @@ -209,7 +209,7 @@ resource "aws_appstream_stack" "test" { `, name) } -func testAccStackCompleteConfig(name, description string) string { +func testAccStackConfig_complete(name, description string) string { return fmt.Sprintf(` resource "aws_appstream_stack" "test" { name = %[1]q @@ -247,7 +247,7 @@ resource "aws_appstream_stack" "test" { `, name, description) } -func testAccStackWithTagsConfig(name, description string) string { +func testAccStackConfig_tags(name, description string) string { return fmt.Sprintf(` resource "aws_appstream_stack" "test" { name = %[1]q diff --git a/internal/service/appstream/user_stack_association_test.go b/internal/service/appstream/user_stack_association_test.go index e2f9ea1d57a..c10b9816fbc 100644 --- a/internal/service/appstream/user_stack_association_test.go +++ b/internal/service/appstream/user_stack_association_test.go @@ -32,7 +32,7 @@ func TestAccAppStreamUserStackAssociation_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccUserStackAssociationConfig(rName, authType, rEmail), + Config: testAccUserStackAssociationConfig_basic(rName, authType, rEmail), Check: resource.ComposeTestCheckFunc( testAccCheckUserStackAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "authentication_type", authType), @@ -65,7 +65,7 @@ func TestAccAppStreamUserStackAssociation_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccUserStackAssociationConfig(rName, authType, rEmail), + Config: testAccUserStackAssociationConfig_basic(rName, authType, rEmail), Check: resource.ComposeTestCheckFunc( testAccCheckUserStackAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfappstream.ResourceUserStackAssociation(), resourceName), @@ -93,13 +93,13 @@ func TestAccAppStreamUserStackAssociation_complete(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccUserStackAssociationConfig(rName, authType, rEmail), + Config: testAccUserStackAssociationConfig_basic(rName, authType, rEmail), Check: resource.ComposeTestCheckFunc( testAccCheckUserStackAssociationExists(resourceName), ), }, { - Config: testAccUserStackAssociationConfig(rName, authType, rEmailUpdated), + Config: testAccUserStackAssociationConfig_basic(rName, authType, rEmailUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckUserStackAssociationExists(resourceName), ), @@ -180,7 +180,7 @@ func testAccCheckUserStackAssociationDestroy(s *terraform.State) error { return nil } -func testAccUserStackAssociationConfig(name, authType, userName string) string { +func testAccUserStackAssociationConfig_basic(name, authType, userName string) string { return fmt.Sprintf(` resource "aws_appstream_stack" "test" { name = %[1]q diff --git a/internal/service/appstream/user_test.go b/internal/service/appstream/user_test.go index 2f1eb2f318b..ced7c32133c 100644 --- a/internal/service/appstream/user_test.go +++ b/internal/service/appstream/user_test.go @@ -32,7 +32,7 @@ func TestAccAppStreamUser_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccUserConfig(authType, rEmail), + Config: testAccUserConfig_basic(authType, rEmail), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &userOutput), resource.TestCheckResourceAttr(resourceName, "authentication_type", authType), @@ -67,7 +67,7 @@ func TestAccAppStreamUser_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccUserConfig(authType, rEmail), + Config: testAccUserConfig_basic(authType, rEmail), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &userOutput), acctest.CheckResourceDisappears(acctest.Provider, tfappstream.ResourceUser(), resourceName), @@ -96,7 +96,7 @@ func TestAccAppStreamUser_complete(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, appstream.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccUserCompleteConfig(authType, rEmail, firstName, lastName, false), + Config: testAccUserConfig_complete(authType, rEmail, firstName, lastName, false), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &userOutput), resource.TestCheckResourceAttr(resourceName, "authentication_type", authType), @@ -112,7 +112,7 @@ func TestAccAppStreamUser_complete(t *testing.T) { ImportStateVerifyIgnore: []string{"send_email_notification"}, }, { - Config: testAccUserCompleteConfig(authType, rEmail, firstName, lastName, true), + Config: testAccUserConfig_complete(authType, rEmail, firstName, lastName, true), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &userOutput), resource.TestCheckResourceAttr(resourceName, "authentication_type", authType), @@ -122,7 +122,7 @@ func TestAccAppStreamUser_complete(t *testing.T) { ), }, { - Config: testAccUserCompleteConfig(authType, rEmail, firstName, lastName, false), + Config: testAccUserConfig_complete(authType, rEmail, firstName, lastName, false), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &userOutput), resource.TestCheckResourceAttr(resourceName, "authentication_type", authType), @@ -202,7 +202,7 @@ func testAccCheckUserDestroy(s *terraform.State) error { return nil } -func testAccUserConfig(authType, userName string) string { +func testAccUserConfig_basic(authType, userName string) string { return fmt.Sprintf(` resource "aws_appstream_user" "test" { authentication_type = %[1]q @@ -211,7 +211,7 @@ resource "aws_appstream_user" "test" { `, authType, userName) } -func testAccUserCompleteConfig(authType, userName, firstName, lastName string, enabled bool) string { +func testAccUserConfig_complete(authType, userName, firstName, lastName string, enabled bool) string { return fmt.Sprintf(` resource "aws_appstream_user" "test" { authentication_type = %[1]q diff --git a/internal/service/appsync/api_cache.go b/internal/service/appsync/api_cache.go index 1e1ba746c50..ad7b0efad94 100644 --- a/internal/service/appsync/api_cache.go +++ b/internal/service/appsync/api_cache.go @@ -84,7 +84,7 @@ func resourceAPICacheCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(apiID) - if err := waitApiCacheAvailable(conn, d.Id()); err != nil { + if err := waitAPICacheAvailable(conn, d.Id()); err != nil { return fmt.Errorf("error waiting for Appsync API Cache (%s) availability: %w", d.Id(), err) } @@ -94,7 +94,7 @@ func resourceAPICacheCreate(d *schema.ResourceData, meta interface{}) error { func resourceAPICacheRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).AppSyncConn - cache, err := FindApiCacheByID(conn, d.Id()) + cache, err := FindAPICacheByID(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] AppSync API Cache (%s) not found, removing from state", d.Id()) d.SetId("") @@ -139,7 +139,7 @@ func resourceAPICacheUpdate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error updating Appsync API Cache %q: %w", d.Id(), err) } - if err := waitApiCacheAvailable(conn, d.Id()); err != nil { + if err := waitAPICacheAvailable(conn, d.Id()); err != nil { return fmt.Errorf("error waiting for Appsync API Cache (%s) availability: %w", d.Id(), err) } @@ -161,7 +161,7 @@ func resourceAPICacheDelete(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error deleting Appsync API Cache: %w", err) } - if err := waitApiCacheDeleted(conn, d.Id()); err != nil { + if err := waitAPICacheDeleted(conn, d.Id()); err != nil { return fmt.Errorf("error waiting for Appsync API Cache (%s) to be deleted: %w", d.Id(), err) } diff --git a/internal/service/appsync/api_cache_test.go b/internal/service/appsync/api_cache_test.go index ab4cfec1748..87b946eb176 100644 --- a/internal/service/appsync/api_cache_test.go +++ b/internal/service/appsync/api_cache_test.go @@ -23,12 +23,12 @@ func testAccAPICache_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(appsync.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, appsync.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckApiCacheDestroy, + CheckDestroy: testAccCheckAPICacheDestroy, Steps: []resource.TestStep{ { Config: testAccAPICacheConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckApiCacheExists(resourceName, &apiCache), + testAccCheckAPICacheExists(resourceName, &apiCache), resource.TestCheckResourceAttrPair(resourceName, "api_id", "aws_appsync_graphql_api.test", "id"), resource.TestCheckResourceAttr(resourceName, "type", "SMALL"), resource.TestCheckResourceAttr(resourceName, "api_caching_behavior", "FULL_REQUEST_CACHING"), @@ -52,12 +52,12 @@ func testAccAPICache_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(appsync.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, appsync.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckApiCacheDestroy, + CheckDestroy: testAccCheckAPICacheDestroy, Steps: []resource.TestStep{ { Config: testAccAPICacheConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckApiCacheExists(resourceName, &apiCache), + testAccCheckAPICacheExists(resourceName, &apiCache), acctest.CheckResourceDisappears(acctest.Provider, tfappsync.ResourceAPICache(), resourceName), ), ExpectNonEmptyPlan: true, @@ -66,14 +66,14 @@ func testAccAPICache_disappears(t *testing.T) { }) } -func testAccCheckApiCacheDestroy(s *terraform.State) error { +func testAccCheckAPICacheDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).AppSyncConn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_appsync_api_cache" { continue } - _, err := tfappsync.FindApiCacheByID(conn, rs.Primary.ID) + _, err := tfappsync.FindAPICacheByID(conn, rs.Primary.ID) if err == nil { if tfresource.NotFound(err) { return nil @@ -87,7 +87,7 @@ func testAccCheckApiCacheDestroy(s *terraform.State) error { return nil } -func testAccCheckApiCacheExists(resourceName string, apiCache *appsync.ApiCache) resource.TestCheckFunc { +func testAccCheckAPICacheExists(resourceName string, apiCache *appsync.ApiCache) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] @@ -96,7 +96,7 @@ func testAccCheckApiCacheExists(resourceName string, apiCache *appsync.ApiCache) } conn := acctest.Provider.Meta().(*conns.AWSClient).AppSyncConn - cache, err := tfappsync.FindApiCacheByID(conn, rs.Primary.ID) + cache, err := tfappsync.FindAPICacheByID(conn, rs.Primary.ID) if err != nil { return err } diff --git a/internal/service/appsync/datasource.go b/internal/service/appsync/datasource.go index 25a3117ebf1..0f5292ef25c 100644 --- a/internal/service/appsync/datasource.go +++ b/internal/service/appsync/datasource.go @@ -254,7 +254,7 @@ func resourceDataSourceCreate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("elasticsearch_config"); ok { - input.ElasticsearchConfig = expandElasticSearchDataSourceConfig(v.([]interface{}), region) + input.ElasticsearchConfig = expandElasticsearchDataSourceConfig(v.([]interface{}), region) } if v, ok := d.GetOk("http_config"); ok { @@ -317,7 +317,7 @@ func resourceDataSourceRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting dynamodb_config: %w", err) } - if err := d.Set("elasticsearch_config", flattenElasticSearchDataSourceConfig(dataSource.ElasticsearchConfig)); err != nil { + if err := d.Set("elasticsearch_config", flattenElasticsearchDataSourceConfig(dataSource.ElasticsearchConfig)); err != nil { return fmt.Errorf("error setting elasticsearch_config: %w", err) } @@ -365,7 +365,7 @@ func resourceDataSourceUpdate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("elasticsearch_config"); ok { - input.ElasticsearchConfig = expandElasticSearchDataSourceConfig(v.([]interface{}), region) + input.ElasticsearchConfig = expandElasticsearchDataSourceConfig(v.([]interface{}), region) } if v, ok := d.GetOk("http_config"); ok { @@ -526,7 +526,7 @@ func flattenDynamoDBDataSourceDeltaSyncConfig(config *appsync.DeltaSyncConfig) [ return []map[string]interface{}{result} } -func expandElasticSearchDataSourceConfig(l []interface{}, currentRegion string) *appsync.ElasticsearchDataSourceConfig { +func expandElasticsearchDataSourceConfig(l []interface{}, currentRegion string) *appsync.ElasticsearchDataSourceConfig { if len(l) == 0 || l[0] == nil { return nil } @@ -545,7 +545,7 @@ func expandElasticSearchDataSourceConfig(l []interface{}, currentRegion string) return result } -func flattenElasticSearchDataSourceConfig(config *appsync.ElasticsearchDataSourceConfig) []map[string]interface{} { +func flattenElasticsearchDataSourceConfig(config *appsync.ElasticsearchDataSourceConfig) []map[string]interface{} { if config == nil { return nil } diff --git a/internal/service/appsync/datasource_test.go b/internal/service/appsync/datasource_test.go index efe46cbde71..09d0e0a9162 100644 --- a/internal/service/appsync/datasource_test.go +++ b/internal/service/appsync/datasource_test.go @@ -27,7 +27,7 @@ func testAccDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_Type_none(rName), + Config: testAccDataSourceConfig_typeNone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appsync", regexp.MustCompile(fmt.Sprintf("apis/.+/datasources/%s", rName))), @@ -94,7 +94,7 @@ func testAccDataSource_DynamoDB_region(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_DynamoDBConfig_region(rName, acctest.Region()), + Config: testAccDataSourceConfig_dynamoDBRegion(rName, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "dynamodb_config.#", "1"), @@ -102,7 +102,7 @@ func testAccDataSource_DynamoDB_region(t *testing.T) { ), }, { - Config: testAccDataSourceConfig_Type_dynamoDB(rName), + Config: testAccDataSourceConfig_typeDynamoDB(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "dynamodb_config.#", "1"), @@ -129,7 +129,7 @@ func testAccDataSource_DynamoDB_useCallerCredentials(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_DynamoDBConfig_useCallerCredentials(rName, true), + Config: testAccDataSourceConfig_dynamoDBUseCallerCredentials(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "dynamodb_config.#", "1"), @@ -137,7 +137,7 @@ func testAccDataSource_DynamoDB_useCallerCredentials(t *testing.T) { ), }, { - Config: testAccDataSourceConfig_DynamoDBConfig_useCallerCredentials(rName, false), + Config: testAccDataSourceConfig_dynamoDBUseCallerCredentials(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "dynamodb_config.#", "1"), @@ -165,7 +165,7 @@ func TestAccAppSyncDataSource_Elasticsearch_region(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_ElasticSearchConfig_region(rName, acctest.Region()), + Config: testAccDataSourceConfig_elasticSearchRegion(rName, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "elasticsearch_config.#", "1"), @@ -173,7 +173,7 @@ func TestAccAppSyncDataSource_Elasticsearch_region(t *testing.T) { ), }, { - Config: testAccDataSourceConfig_Type_elasticSearch(rName), + Config: testAccDataSourceConfig_typeElasticsearch(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "elasticsearch_config.#", "1"), @@ -200,7 +200,7 @@ func testAccDataSource_HTTP_endpoint(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_HTTPConfig_endpoint(rName, "http://example.com"), + Config: testAccDataSourceConfig_httpEndpoint(rName, "http://example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "http_config.#", "1"), @@ -209,7 +209,7 @@ func testAccDataSource_HTTP_endpoint(t *testing.T) { ), }, { - Config: testAccDataSourceConfig_HTTPConfig_endpoint(rName, "http://example.org"), + Config: testAccDataSourceConfig_httpEndpoint(rName, "http://example.org"), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "http_config.#", "1"), @@ -237,14 +237,14 @@ func testAccDataSource_type(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_Type_none(rName), + Config: testAccDataSourceConfig_typeNone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "type", "NONE"), ), }, { - Config: testAccDataSourceConfig_Type_http(rName), + Config: testAccDataSourceConfig_typeHTTP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), @@ -267,7 +267,7 @@ func testAccDataSource_Type_dynamoDB(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_Type_dynamoDB(rName), + Config: testAccDataSourceConfig_typeDynamoDB(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "dynamodb_config.#", "1"), @@ -299,7 +299,7 @@ func TestAccAppSyncDataSource_Type_elasticSearch(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_Type_elasticSearch(rName), + Config: testAccDataSourceConfig_typeElasticsearch(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "elasticsearch_config.#", "1"), @@ -329,7 +329,7 @@ func testAccDataSource_Type_http(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_Type_http(rName), + Config: testAccDataSourceConfig_typeHTTP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "http_config.#", "1"), @@ -357,7 +357,7 @@ func testAccDataSource_Type_httpAuth(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_Type_httpAuth(rName, acctest.Region()), + Config: testAccDataSourceConfig_typeHTTPAuth(rName, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "http_config.#", "1"), @@ -418,7 +418,7 @@ func testAccDataSource_Type_relationalDatabaseWithOptions(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_typeRelationalDatabaseWithOptions(rName), + Config: testAccDataSourceConfig_typeRelationalDatabaseOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "relational_database_config.0.http_endpoint_config.0.schema", "mydb"), @@ -450,7 +450,7 @@ func testAccDataSource_Type_lambda(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_Type_lambda(rName), + Config: testAccDataSourceConfig_typeLambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "lambda_config.#", "1"), @@ -479,7 +479,7 @@ func testAccDataSource_Type_none(t *testing.T) { CheckDestroy: testAccCheckDestroyDataSource, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_Type_none(rName), + Config: testAccDataSourceConfig_typeNone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExistsDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "type", "NONE"), @@ -608,7 +608,7 @@ EOF `, rName, rName) } -func testAccDataSourceConfig_Base_elasticSearch(rName string) string { +func testAccDataSourceConfig_Base_elasticsearch(rName string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = %q @@ -752,7 +752,7 @@ resource "aws_appsync_datasource" "test" { `, rName, description, rName) } -func testAccDataSourceConfig_DynamoDBConfig_region(rName, region string) string { +func testAccDataSourceConfig_dynamoDBRegion(rName, region string) string { return testAccDatasourceConfig_dynamoDBBase(rName) + fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" @@ -773,7 +773,7 @@ resource "aws_appsync_datasource" "test" { `, rName, rName, region) } -func testAccDataSourceConfig_DynamoDBConfig_useCallerCredentials(rName string, useCallerCredentials bool) string { +func testAccDataSourceConfig_dynamoDBUseCallerCredentials(rName string, useCallerCredentials bool) string { return testAccDatasourceConfig_dynamoDBBase(rName) + fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "AWS_IAM" @@ -794,8 +794,8 @@ resource "aws_appsync_datasource" "test" { `, rName, rName, useCallerCredentials) } -func testAccDataSourceConfig_ElasticSearchConfig_region(rName, region string) string { - return testAccDataSourceConfig_Base_elasticSearch(rName) + fmt.Sprintf(` +func testAccDataSourceConfig_elasticSearchRegion(rName, region string) string { + return testAccDataSourceConfig_Base_elasticsearch(rName) + fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" name = %q @@ -815,7 +815,7 @@ resource "aws_appsync_datasource" "test" { `, rName, rName, region) } -func testAccDataSourceConfig_HTTPConfig_endpoint(rName, endpoint string) string { +func testAccDataSourceConfig_httpEndpoint(rName, endpoint string) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" @@ -834,7 +834,7 @@ resource "aws_appsync_datasource" "test" { `, rName, rName, endpoint) } -func testAccDataSourceConfig_Type_dynamoDB(rName string) string { +func testAccDataSourceConfig_typeDynamoDB(rName string) string { return testAccDatasourceConfig_dynamoDBBase(rName) + fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" @@ -854,8 +854,8 @@ resource "aws_appsync_datasource" "test" { `, rName, rName) } -func testAccDataSourceConfig_Type_elasticSearch(rName string) string { - return testAccDataSourceConfig_Base_elasticSearch(rName) + fmt.Sprintf(` +func testAccDataSourceConfig_typeElasticsearch(rName string) string { + return testAccDataSourceConfig_Base_elasticsearch(rName) + fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" name = %q @@ -874,7 +874,7 @@ resource "aws_appsync_datasource" "test" { `, rName, rName) } -func testAccDataSourceConfig_Type_http(rName string) string { +func testAccDataSourceConfig_typeHTTP(rName string) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" @@ -893,7 +893,7 @@ resource "aws_appsync_datasource" "test" { `, rName) } -func testAccDataSourceConfig_Type_httpAuth(rName, region string) string { +func testAccDataSourceConfig_typeHTTPAuth(rName, region string) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" @@ -1046,7 +1046,7 @@ resource "aws_appsync_datasource" "test" { `, rName) } -func testAccDataSourceConfig_typeRelationalDatabaseWithOptions(rName string) string { +func testAccDataSourceConfig_typeRelationalDatabaseOptions(rName string) string { return testAccDataSourceConfigBaseRelationalDatabase(rName) + fmt.Sprintf(` resource "aws_appsync_datasource" "test" { api_id = aws_appsync_graphql_api.test.id @@ -1066,7 +1066,7 @@ resource "aws_appsync_datasource" "test" { `, rName) } -func testAccDataSourceConfig_Type_lambda(rName string) string { +func testAccDataSourceConfig_typeLambda(rName string) string { return testAccDatasourceConfig_lambdaBase(rName) + fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" @@ -1086,7 +1086,7 @@ resource "aws_appsync_datasource" "test" { `, rName, rName) } -func testAccDataSourceConfig_Type_none(rName string) string { +func testAccDataSourceConfig_typeNone(rName string) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" diff --git a/internal/service/appsync/domain_name_api_association.go b/internal/service/appsync/domain_name_api_association.go index 8d0e288032f..a1faa77bf07 100644 --- a/internal/service/appsync/domain_name_api_association.go +++ b/internal/service/appsync/domain_name_api_association.go @@ -11,13 +11,13 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/conns" ) -func ResourceDomainNameApiAssociation() *schema.Resource { +func ResourceDomainNameAPIAssociation() *schema.Resource { return &schema.Resource{ - Create: resourceDomainNameApiAssociationCreate, - Read: resourceDomainNameApiAssociationRead, - Update: resourceDomainNameApiAssociationUpdate, - Delete: resourceDomainNameApiAssociationDelete, + Create: resourceDomainNameAPIAssociationCreate, + Read: resourceDomainNameAPIAssociationRead, + Update: resourceDomainNameAPIAssociationUpdate, + Delete: resourceDomainNameAPIAssociationDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, @@ -36,7 +36,7 @@ func ResourceDomainNameApiAssociation() *schema.Resource { } } -func resourceDomainNameApiAssociationCreate(d *schema.ResourceData, meta interface{}) error { +func resourceDomainNameAPIAssociationCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).AppSyncConn params := &appsync.AssociateApiInput{ @@ -51,17 +51,17 @@ func resourceDomainNameApiAssociationCreate(d *schema.ResourceData, meta interfa d.SetId(aws.StringValue(resp.ApiAssociation.DomainName)) - if err := waitDomainNameApiAssociation(conn, d.Id()); err != nil { + if err := waitDomainNameAPIAssociation(conn, d.Id()); err != nil { return fmt.Errorf("error waiting for Appsync Domain Name API (%s) Association: %w", d.Id(), err) } - return resourceDomainNameApiAssociationRead(d, meta) + return resourceDomainNameAPIAssociationRead(d, meta) } -func resourceDomainNameApiAssociationRead(d *schema.ResourceData, meta interface{}) error { +func resourceDomainNameAPIAssociationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).AppSyncConn - association, err := FindDomainNameApiAssociationByID(conn, d.Id()) + association, err := FindDomainNameAPIAssociationByID(conn, d.Id()) if association == nil && !d.IsNewResource() { log.Printf("[WARN] Appsync Domain Name API Association (%s) not found, removing from state", d.Id()) d.SetId("") @@ -78,7 +78,7 @@ func resourceDomainNameApiAssociationRead(d *schema.ResourceData, meta interface return nil } -func resourceDomainNameApiAssociationUpdate(d *schema.ResourceData, meta interface{}) error { +func resourceDomainNameAPIAssociationUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).AppSyncConn params := &appsync.AssociateApiInput{ @@ -91,14 +91,14 @@ func resourceDomainNameApiAssociationUpdate(d *schema.ResourceData, meta interfa return fmt.Errorf("error creating Appsync Domain Name API Association: %w", err) } - if err := waitDomainNameApiAssociation(conn, d.Id()); err != nil { + if err := waitDomainNameAPIAssociation(conn, d.Id()); err != nil { return fmt.Errorf("error waiting for Appsync Domain Name API (%s) Association: %w", d.Id(), err) } - return resourceDomainNameApiAssociationRead(d, meta) + return resourceDomainNameAPIAssociationRead(d, meta) } -func resourceDomainNameApiAssociationDelete(d *schema.ResourceData, meta interface{}) error { +func resourceDomainNameAPIAssociationDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).AppSyncConn input := &appsync.DisassociateApiInput{ @@ -112,7 +112,7 @@ func resourceDomainNameApiAssociationDelete(d *schema.ResourceData, meta interfa return fmt.Errorf("error deleting Appsync Domain Name API Association: %w", err) } - if err := waitDomainNameApiDisassociation(conn, d.Id()); err != nil { + if err := waitDomainNameAPIDisassociation(conn, d.Id()); err != nil { return fmt.Errorf("error waiting for Appsync Domain Name API (%s) Disassociation: %w", d.Id(), err) } diff --git a/internal/service/appsync/domain_name_api_association_test.go b/internal/service/appsync/domain_name_api_association_test.go index 75711df23a4..571da1fb1ac 100644 --- a/internal/service/appsync/domain_name_api_association_test.go +++ b/internal/service/appsync/domain_name_api_association_test.go @@ -28,12 +28,12 @@ func testAccDomainNameAPIAssociation_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(appsync.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, appsync.EndpointsID), ProviderFactories: acctest.FactoriesAlternate(&providers), - CheckDestroy: testAccCheckDomainNameApiAssociationDestroy, + CheckDestroy: testAccCheckDomainNameAPIAssociationDestroy, Steps: []resource.TestStep{ { Config: testAccDomainNameAPIAssociationConfig_basic(appsyncCertDomain, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDomainNameApiAssociationExists(resourceName, &association), + testAccCheckDomainNameAPIAssociationExists(resourceName, &association), resource.TestCheckResourceAttrPair(resourceName, "domain_name", "aws_appsync_domain_name.test", "domain_name"), resource.TestCheckResourceAttrPair(resourceName, "api_id", "aws_appsync_graphql_api.test", "id"), ), @@ -46,7 +46,7 @@ func testAccDomainNameAPIAssociation_basic(t *testing.T) { { Config: testAccDomainNameAPIAssociationConfig_updated(appsyncCertDomain, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDomainNameApiAssociationExists(resourceName, &association), + testAccCheckDomainNameAPIAssociationExists(resourceName, &association), resource.TestCheckResourceAttrPair(resourceName, "domain_name", "aws_appsync_domain_name.test", "domain_name"), resource.TestCheckResourceAttrPair(resourceName, "api_id", "aws_appsync_graphql_api.test2", "id"), ), @@ -67,13 +67,13 @@ func testAccDomainNameAPIAssociation_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(appsync.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, appsync.EndpointsID), ProviderFactories: acctest.FactoriesAlternate(&providers), - CheckDestroy: testAccCheckDomainNameApiAssociationDestroy, + CheckDestroy: testAccCheckDomainNameAPIAssociationDestroy, Steps: []resource.TestStep{ { Config: testAccDomainNameAPIAssociationConfig_basic(appsyncCertDomain, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDomainNameApiAssociationExists(resourceName, &association), - acctest.CheckResourceDisappears(acctest.Provider, tfappsync.ResourceDomainNameApiAssociation(), resourceName), + testAccCheckDomainNameAPIAssociationExists(resourceName, &association), + acctest.CheckResourceDisappears(acctest.Provider, tfappsync.ResourceDomainNameAPIAssociation(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -81,14 +81,14 @@ func testAccDomainNameAPIAssociation_disappears(t *testing.T) { }) } -func testAccCheckDomainNameApiAssociationDestroy(s *terraform.State) error { +func testAccCheckDomainNameAPIAssociationDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).AppSyncConn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_appsync_domain_name" { continue } - association, err := tfappsync.FindDomainNameApiAssociationByID(conn, rs.Primary.ID) + association, err := tfappsync.FindDomainNameAPIAssociationByID(conn, rs.Primary.ID) if err == nil { if tfawserr.ErrCodeEquals(err, appsync.ErrCodeNotFoundException) { return nil @@ -106,7 +106,7 @@ func testAccCheckDomainNameApiAssociationDestroy(s *terraform.State) error { return nil } -func testAccCheckDomainNameApiAssociationExists(resourceName string, DomainNameApiAssociation *appsync.ApiAssociation) resource.TestCheckFunc { +func testAccCheckDomainNameAPIAssociationExists(resourceName string, DomainNameAPIAssociation *appsync.ApiAssociation) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] @@ -115,7 +115,7 @@ func testAccCheckDomainNameApiAssociationExists(resourceName string, DomainNameA } conn := acctest.Provider.Meta().(*conns.AWSClient).AppSyncConn - association, err := tfappsync.FindDomainNameApiAssociationByID(conn, rs.Primary.ID) + association, err := tfappsync.FindDomainNameAPIAssociationByID(conn, rs.Primary.ID) if err != nil { return err } @@ -124,7 +124,7 @@ func testAccCheckDomainNameApiAssociationExists(resourceName string, DomainNameA return fmt.Errorf("Appsync Domain Name %q not found", rs.Primary.ID) } - *DomainNameApiAssociation = *association + *DomainNameAPIAssociation = *association return nil } diff --git a/internal/service/appsync/find.go b/internal/service/appsync/find.go index ee373a19959..ec771590d73 100644 --- a/internal/service/appsync/find.go +++ b/internal/service/appsync/find.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func FindApiCacheByID(conn *appsync.AppSync, id string) (*appsync.ApiCache, error) { +func FindAPICacheByID(conn *appsync.AppSync, id string) (*appsync.ApiCache, error) { input := &appsync.GetApiCacheInput{ ApiId: aws.String(id), } @@ -56,7 +56,7 @@ func FindDomainNameByID(conn *appsync.AppSync, id string) (*appsync.DomainNameCo return out.DomainNameConfig, nil } -func FindDomainNameApiAssociationByID(conn *appsync.AppSync, id string) (*appsync.ApiAssociation, error) { +func FindDomainNameAPIAssociationByID(conn *appsync.AppSync, id string) (*appsync.ApiAssociation, error) { input := &appsync.GetApiAssociationInput{ DomainName: aws.String(id), } diff --git a/internal/service/appsync/function_test.go b/internal/service/appsync/function_test.go index 978f8350c4c..d568439960c 100644 --- a/internal/service/appsync/function_test.go +++ b/internal/service/appsync/function_test.go @@ -30,7 +30,7 @@ func testAccFunction_basic(t *testing.T) { CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccFunctionConfig(rName1, rName2, acctest.Region()), + Config: testAccFunctionConfig_basic(rName1, rName2, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &config), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appsync", regexp.MustCompile("apis/.+/functions/.+")), @@ -43,7 +43,7 @@ func testAccFunction_basic(t *testing.T) { ), }, { - Config: testAccFunctionConfig(rName1, rName3, acctest.Region()), + Config: testAccFunctionConfig_basic(rName1, rName3, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "name", rName3), @@ -70,7 +70,7 @@ func testAccFunction_syncConfig(t *testing.T) { CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccFunctionSyncConfig(rName, acctest.Region()), + Config: testAccFunctionConfig_sync(rName, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "sync_config.#", "1"), @@ -100,14 +100,14 @@ func testAccFunction_description(t *testing.T) { CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccFunctionDescriptionConfig(rName1, rName2, acctest.Region(), "test description 1"), + Config: testAccFunctionConfig_description(rName1, rName2, acctest.Region(), "test description 1"), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "description", "test description 1"), ), }, { - Config: testAccFunctionDescriptionConfig(rName1, rName2, acctest.Region(), "test description 2"), + Config: testAccFunctionConfig_description(rName1, rName2, acctest.Region(), "test description 2"), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "description", "test description 2"), @@ -135,7 +135,7 @@ func testAccFunction_responseMappingTemplate(t *testing.T) { CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccFunctionResponseMappingTemplateConfig(rName1, rName2, acctest.Region()), + Config: testAccFunctionConfig_responseMappingTemplate(rName1, rName2, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &config), ), @@ -162,7 +162,7 @@ func testAccFunction_disappears(t *testing.T) { CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccFunctionConfig(rName1, rName2, acctest.Region()), + Config: testAccFunctionConfig_basic(rName1, rName2, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &config), acctest.CheckResourceDisappears(acctest.Provider, tfappsync.ResourceFunction(), resourceName), @@ -232,7 +232,7 @@ func testAccCheckFunctionExists(name string, config *appsync.FunctionConfigurati } } -func testAccFunctionConfig(r1, r2, region string) string { +func testAccFunctionConfig_basic(r1, r2, region string) string { return fmt.Sprintf(` %[1]s @@ -259,10 +259,10 @@ EOF #end EOF } -`, testAccDataSourceConfig_DynamoDBConfig_region(r1, region), r2) +`, testAccDataSourceConfig_dynamoDBRegion(r1, region), r2) } -func testAccFunctionSyncConfig(rName, region string) string { +func testAccFunctionConfig_sync(rName, region string) string { return testAccDatasourceConfig_dynamoDBBase(rName) + fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" @@ -319,7 +319,7 @@ EOF `, rName, region) } -func testAccFunctionDescriptionConfig(r1, r2, region, description string) string { +func testAccFunctionConfig_description(r1, r2, region, description string) string { return fmt.Sprintf(` %[1]s @@ -347,10 +347,10 @@ EOF #end EOF } -`, testAccDataSourceConfig_DynamoDBConfig_region(r1, region), r2, description) +`, testAccDataSourceConfig_dynamoDBRegion(r1, region), r2, description) } -func testAccFunctionResponseMappingTemplateConfig(r1, r2, region string) string { +func testAccFunctionConfig_responseMappingTemplate(r1, r2, region string) string { return fmt.Sprintf(` %[1]s @@ -377,5 +377,5 @@ EOF #end EOF } -`, testAccDataSourceConfig_DynamoDBConfig_region(r1, region), r2) +`, testAccDataSourceConfig_dynamoDBRegion(r1, region), r2) } diff --git a/internal/service/appsync/graphql_api.go b/internal/service/appsync/graphql_api.go index c247d0038e7..2b20784e4ff 100644 --- a/internal/service/appsync/graphql_api.go +++ b/internal/service/appsync/graphql_api.go @@ -16,9 +16,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/verify" ) -var validateAuthorizerResultTtlInSeconds = validation.IntBetween(0, 3600) +var validateAuthorizerResultTTLInSeconds = validation.IntBetween(0, 3600) -const DefaultAuthorizerResultTtlInSeconds = 300 +const DefaultAuthorizerResultTTLInSeconds = 300 func ResourceGraphQLAPI() *schema.Resource { return &schema.Resource{ @@ -98,8 +98,8 @@ func ResourceGraphQLAPI() *schema.Resource { "authorizer_result_ttl_in_seconds": { Type: schema.TypeInt, Optional: true, - Default: DefaultAuthorizerResultTtlInSeconds, - ValidateFunc: validateAuthorizerResultTtlInSeconds, + Default: DefaultAuthorizerResultTTLInSeconds, + ValidateFunc: validateAuthorizerResultTTLInSeconds, }, "authorizer_uri": { Type: schema.TypeString, @@ -226,8 +226,8 @@ func ResourceGraphQLAPI() *schema.Resource { "authorizer_result_ttl_in_seconds": { Type: schema.TypeInt, Optional: true, - Default: DefaultAuthorizerResultTtlInSeconds, - ValidateFunc: validateAuthorizerResultTtlInSeconds, + Default: DefaultAuthorizerResultTTLInSeconds, + ValidateFunc: validateAuthorizerResultTTLInSeconds, }, "authorizer_uri": { Type: schema.TypeString, @@ -655,7 +655,7 @@ func flattenGraphQLAPILambdaAuthorizerConfig(lambdaAuthorizerConfig *appsync.Lam if lambdaAuthorizerConfig.AuthorizerResultTtlInSeconds != nil { m["authorizer_result_ttl_in_seconds"] = aws.Int64Value(lambdaAuthorizerConfig.AuthorizerResultTtlInSeconds) } else { - m["authorizer_result_ttl_in_seconds"] = DefaultAuthorizerResultTtlInSeconds + m["authorizer_result_ttl_in_seconds"] = DefaultAuthorizerResultTTLInSeconds } if lambdaAuthorizerConfig.IdentityValidationExpression != nil { diff --git a/internal/service/appsync/graphql_api_test.go b/internal/service/appsync/graphql_api_test.go index 074862ec4c6..3537209d53e 100644 --- a/internal/service/appsync/graphql_api_test.go +++ b/internal/service/appsync/graphql_api_test.go @@ -229,7 +229,7 @@ func testAccGraphQLAPI_AuthenticationType_amazonCognitoUserPools(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_UserPoolConfig_defaultAction(rName, "ALLOW"), + Config: testAccGraphQLAPIConfig_userPoolDefaultAction(rName, "ALLOW"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AMAZON_COGNITO_USER_POOLS"), @@ -260,7 +260,7 @@ func testAccGraphQLAPI_AuthenticationType_openIDConnect(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_OpenIDConnectConfig_issuer(rName, "https://example.com"), + Config: testAccGraphQLAPIConfig_openIDConnectIssuer(rName, "https://example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "OPENID_CONNECT"), @@ -290,13 +290,13 @@ func testAccGraphQLAPI_AuthenticationType_lambda(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_LambdaAuthorizerConfig_authorizerURI(rName, "aws_lambda_function.test.arn"), + Config: testAccGraphQLAPIConfig_lambdaAuthorizerAuthorizerURI(rName, "aws_lambda_function.test.arn"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AWS_LAMBDA"), resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.#", "1"), resource.TestCheckResourceAttrPair(resourceName, "lambda_authorizer_config.0.authorizer_uri", lambdaAuthorizerResourceName, "arn"), - resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.0.authorizer_result_ttl_in_seconds", strconv.Itoa(tfappsync.DefaultAuthorizerResultTtlInSeconds)), + resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.0.authorizer_result_ttl_in_seconds", strconv.Itoa(tfappsync.DefaultAuthorizerResultTTLInSeconds)), resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.0.identity_validation_expression", ""), ), }, @@ -322,7 +322,7 @@ func testAccGraphQLAPI_log(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_LogConfig_fieldLogLevel(rName, "ALL"), + Config: testAccGraphQLAPIConfig_logFieldLogLevel(rName, "ALL"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "log_config.#", "1"), @@ -353,7 +353,7 @@ func testAccGraphQLAPI_Log_fieldLogLevel(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_LogConfig_fieldLogLevel(rName, "ALL"), + Config: testAccGraphQLAPIConfig_logFieldLogLevel(rName, "ALL"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "log_config.#", "1"), @@ -363,7 +363,7 @@ func testAccGraphQLAPI_Log_fieldLogLevel(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_LogConfig_fieldLogLevel(rName, "ERROR"), + Config: testAccGraphQLAPIConfig_logFieldLogLevel(rName, "ERROR"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "log_config.#", "1"), @@ -373,7 +373,7 @@ func testAccGraphQLAPI_Log_fieldLogLevel(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_LogConfig_fieldLogLevel(rName, "NONE"), + Config: testAccGraphQLAPIConfig_logFieldLogLevel(rName, "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api3), resource.TestCheckResourceAttr(resourceName, "log_config.#", "1"), @@ -404,7 +404,7 @@ func testAccGraphQLAPI_Log_excludeVerboseContent(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_LogConfig_excludeVerboseContent(rName, false), + Config: testAccGraphQLAPIConfig_logExcludeVerboseContent(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "log_config.#", "1"), @@ -414,7 +414,7 @@ func testAccGraphQLAPI_Log_excludeVerboseContent(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_LogConfig_excludeVerboseContent(rName, true), + Config: testAccGraphQLAPIConfig_logExcludeVerboseContent(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "log_config.#", "1"), @@ -445,7 +445,7 @@ func testAccGraphQLAPI_OpenIDConnect_authTTL(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_OpenIDConnectConfig_authTTL(rName, 1000), + Config: testAccGraphQLAPIConfig_openIDConnectAuthTTL(rName, 1000), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "OPENID_CONNECT"), @@ -455,7 +455,7 @@ func testAccGraphQLAPI_OpenIDConnect_authTTL(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_OpenIDConnectConfig_authTTL(rName, 2000), + Config: testAccGraphQLAPIConfig_openIDConnectAuthTTL(rName, 2000), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "authentication_type", "OPENID_CONNECT"), @@ -485,7 +485,7 @@ func testAccGraphQLAPI_OpenIDConnect_clientID(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_OpenIDConnectConfig_clientID(rName, "ClientID1"), + Config: testAccGraphQLAPIConfig_openIDConnectClientID(rName, "ClientID1"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "OPENID_CONNECT"), @@ -495,7 +495,7 @@ func testAccGraphQLAPI_OpenIDConnect_clientID(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_OpenIDConnectConfig_clientID(rName, "ClientID2"), + Config: testAccGraphQLAPIConfig_openIDConnectClientID(rName, "ClientID2"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "authentication_type", "OPENID_CONNECT"), @@ -525,7 +525,7 @@ func testAccGraphQLAPI_OpenIDConnect_iatTTL(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_OpenIDConnectConfig_iatTTL(rName, 1000), + Config: testAccGraphQLAPIConfig_openIDConnectIatTTL(rName, 1000), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "OPENID_CONNECT"), @@ -535,7 +535,7 @@ func testAccGraphQLAPI_OpenIDConnect_iatTTL(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_OpenIDConnectConfig_iatTTL(rName, 2000), + Config: testAccGraphQLAPIConfig_openIDConnectIatTTL(rName, 2000), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "authentication_type", "OPENID_CONNECT"), @@ -565,7 +565,7 @@ func testAccGraphQLAPI_OpenIDConnect_issuer(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_OpenIDConnectConfig_issuer(rName, "https://example.com"), + Config: testAccGraphQLAPIConfig_openIDConnectIssuer(rName, "https://example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "OPENID_CONNECT"), @@ -574,7 +574,7 @@ func testAccGraphQLAPI_OpenIDConnect_issuer(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_OpenIDConnectConfig_issuer(rName, "https://example.org"), + Config: testAccGraphQLAPIConfig_openIDConnectIssuer(rName, "https://example.org"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "authentication_type", "OPENID_CONNECT"), @@ -634,7 +634,7 @@ func testAccGraphQLAPI_UserPool_region(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_UserPoolConfig_region(rName, acctest.Region()), + Config: testAccGraphQLAPIConfig_userPoolRegion(rName, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AMAZON_COGNITO_USER_POOLS"), @@ -645,7 +645,7 @@ func testAccGraphQLAPI_UserPool_region(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_UserPoolConfig_defaultAction(rName, "ALLOW"), + Config: testAccGraphQLAPIConfig_userPoolDefaultAction(rName, "ALLOW"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AMAZON_COGNITO_USER_POOLS"), @@ -677,7 +677,7 @@ func testAccGraphQLAPI_UserPool_defaultAction(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_UserPoolConfig_defaultAction(rName, "ALLOW"), + Config: testAccGraphQLAPIConfig_userPoolDefaultAction(rName, "ALLOW"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AMAZON_COGNITO_USER_POOLS"), @@ -688,7 +688,7 @@ func testAccGraphQLAPI_UserPool_defaultAction(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_UserPoolConfig_defaultAction(rName, "DENY"), + Config: testAccGraphQLAPIConfig_userPoolDefaultAction(rName, "DENY"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AMAZON_COGNITO_USER_POOLS"), @@ -720,7 +720,7 @@ func testAccGraphQLAPI_LambdaAuthorizerConfig_authorizerURI(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_LambdaAuthorizerConfig_authorizerURI(rName, "aws_lambda_function.test.arn"), + Config: testAccGraphQLAPIConfig_lambdaAuthorizerAuthorizerURI(rName, "aws_lambda_function.test.arn"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AWS_LAMBDA"), @@ -729,7 +729,7 @@ func testAccGraphQLAPI_LambdaAuthorizerConfig_authorizerURI(t *testing.T) { ), }, { - Config: testAccGraphQLAPIConfig_LambdaAuthorizerConfig_authorizerURI(rName, "aws_lambda_function.test.qualified_arn"), + Config: testAccGraphQLAPIConfig_lambdaAuthorizerAuthorizerURI(rName, "aws_lambda_function.test.qualified_arn"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AWS_LAMBDA"), @@ -759,7 +759,7 @@ func testAccGraphQLAPI_LambdaAuthorizerConfig_identityValidationExpression(t *te CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_LambdaAuthorizerConfig_identityValidationExpression(rName, "^test1$"), + Config: testAccGraphQLAPIConfig_lambdaAuthorizerIdentityValidationExpression(rName, "^test1$"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AWS_LAMBDA"), @@ -769,7 +769,7 @@ func testAccGraphQLAPI_LambdaAuthorizerConfig_identityValidationExpression(t *te ), }, { - Config: testAccGraphQLAPIConfig_LambdaAuthorizerConfig_identityValidationExpression(rName, "^test2$"), + Config: testAccGraphQLAPIConfig_lambdaAuthorizerIdentityValidationExpression(rName, "^test2$"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AWS_LAMBDA"), @@ -799,16 +799,16 @@ func testAccGraphQLAPI_LambdaAuthorizerConfig_authorizerResultTTLInSeconds(t *te CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_LambdaAuthorizerConfig_authorizerURI(rName, "aws_lambda_function.test.arn"), + Config: testAccGraphQLAPIConfig_lambdaAuthorizerAuthorizerURI(rName, "aws_lambda_function.test.arn"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AWS_LAMBDA"), resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.#", "1"), - resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.0.authorizer_result_ttl_in_seconds", strconv.Itoa(tfappsync.DefaultAuthorizerResultTtlInSeconds)), + resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.0.authorizer_result_ttl_in_seconds", strconv.Itoa(tfappsync.DefaultAuthorizerResultTTLInSeconds)), ), }, { - Config: testAccGraphQLAPIConfig_LambdaAuthorizerConfig_authorizerResultTTLInSeconds(rName, "123"), + Config: testAccGraphQLAPIConfig_lambdaAuthorizerAuthorizerResultTTLInSeconds(rName, "123"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api2), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AWS_LAMBDA"), @@ -817,7 +817,7 @@ func testAccGraphQLAPI_LambdaAuthorizerConfig_authorizerResultTTLInSeconds(t *te ), }, { - Config: testAccGraphQLAPIConfig_LambdaAuthorizerConfig_authorizerResultTTLInSeconds(rName, "0"), + Config: testAccGraphQLAPIConfig_lambdaAuthorizerAuthorizerResultTTLInSeconds(rName, "0"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api3), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AWS_LAMBDA"), @@ -826,12 +826,12 @@ func testAccGraphQLAPI_LambdaAuthorizerConfig_authorizerResultTTLInSeconds(t *te ), }, { - Config: testAccGraphQLAPIConfig_LambdaAuthorizerConfig_authorizerURI(rName, "aws_lambda_function.test.arn"), + Config: testAccGraphQLAPIConfig_lambdaAuthorizerAuthorizerURI(rName, "aws_lambda_function.test.arn"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api4), resource.TestCheckResourceAttr(resourceName, "authentication_type", "AWS_LAMBDA"), resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.#", "1"), - resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.0.authorizer_result_ttl_in_seconds", strconv.Itoa(tfappsync.DefaultAuthorizerResultTtlInSeconds)), + resource.TestCheckResourceAttr(resourceName, "lambda_authorizer_config.0.authorizer_result_ttl_in_seconds", strconv.Itoa(tfappsync.DefaultAuthorizerResultTTLInSeconds)), ), }, { @@ -896,7 +896,7 @@ func testAccGraphQLAPI_AdditionalAuthentication_apiKey(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_AdditionalAuth_authType(rName, "AWS_IAM", "API_KEY"), + Config: testAccGraphQLAPIConfig_additionalAuthAuthType(rName, "AWS_IAM", "API_KEY"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appsync", regexp.MustCompile(`apis/.+`)), @@ -930,7 +930,7 @@ func testAccGraphQLAPI_AdditionalAuthentication_iam(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_AdditionalAuth_authType(rName, "API_KEY", "AWS_IAM"), + Config: testAccGraphQLAPIConfig_additionalAuthAuthType(rName, "API_KEY", "AWS_IAM"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appsync", regexp.MustCompile(`apis/.+`)), @@ -965,7 +965,7 @@ func testAccGraphQLAPI_AdditionalAuthentication_cognitoUserPools(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_AdditionalAuth_userPoolConfig(rName), + Config: testAccGraphQLAPIConfig_additionalAuthUserPool(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appsync", regexp.MustCompile(`apis/.+`)), @@ -1000,7 +1000,7 @@ func testAccGraphQLAPI_AdditionalAuthentication_openIDConnect(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_AdditionalAuth_openIdConnect(rName, "https://example.com"), + Config: testAccGraphQLAPIConfig_additionalAuthOpenIdConnect(rName, "https://example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appsync", regexp.MustCompile(`apis/.+`)), @@ -1035,7 +1035,7 @@ func testAccGraphQLAPI_AdditionalAuthentication_lambda(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_AdditionalAuth_lambda(rName), + Config: testAccGraphQLAPIConfig_additionalAuthLambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appsync", regexp.MustCompile(`apis/.+`)), @@ -1047,7 +1047,7 @@ func testAccGraphQLAPI_AdditionalAuthentication_lambda(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "additional_authentication_provider.0.user_pool_config.#", "0"), resource.TestCheckResourceAttr(resourceName, "additional_authentication_provider.0.lambda_authorizer_config.#", "1"), resource.TestCheckResourceAttrPair(resourceName, "additional_authentication_provider.0.lambda_authorizer_config.0.authorizer_uri", lambdaAuthorizerResourceName, "arn"), - resource.TestCheckResourceAttr(resourceName, "additional_authentication_provider.0.lambda_authorizer_config.0.authorizer_result_ttl_in_seconds", strconv.Itoa(tfappsync.DefaultAuthorizerResultTtlInSeconds)), + resource.TestCheckResourceAttr(resourceName, "additional_authentication_provider.0.lambda_authorizer_config.0.authorizer_result_ttl_in_seconds", strconv.Itoa(tfappsync.DefaultAuthorizerResultTTLInSeconds)), resource.TestCheckResourceAttr(resourceName, "additional_authentication_provider.0.lambda_authorizer_config.0.identity_validation_expression", ""), ), }, @@ -1074,7 +1074,7 @@ func testAccGraphQLAPI_AdditionalAuthentication_multiple(t *testing.T) { CheckDestroy: testAccCheckGraphQLAPIDestroy, Steps: []resource.TestStep{ { - Config: testAccGraphQLAPIConfig_AdditionalAuth_multiple(rName, "https://example.com"), + Config: testAccGraphQLAPIConfig_additionalAuthMultiple(rName, "https://example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckGraphQLAPIExists(resourceName, &api1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "appsync", regexp.MustCompile(`apis/.+`)), @@ -1220,7 +1220,7 @@ resource "aws_appsync_graphql_api" "test" { `, authenticationType, rName) } -func testAccGraphQLAPIConfig_LogConfig_fieldLogLevel(rName, fieldLogLevel string) string { +func testAccGraphQLAPIConfig_logFieldLogLevel(rName, fieldLogLevel string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -1260,7 +1260,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, rName, fieldLogLevel) } -func testAccGraphQLAPIConfig_LogConfig_excludeVerboseContent(rName string, excludeVerboseContent bool) string { +func testAccGraphQLAPIConfig_logExcludeVerboseContent(rName string, excludeVerboseContent bool) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -1301,7 +1301,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, rName, excludeVerboseContent) } -func testAccGraphQLAPIConfig_OpenIDConnectConfig_authTTL(rName string, authTTL int) string { +func testAccGraphQLAPIConfig_openIDConnectAuthTTL(rName string, authTTL int) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "OPENID_CONNECT" @@ -1315,7 +1315,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, authTTL) } -func testAccGraphQLAPIConfig_OpenIDConnectConfig_clientID(rName, clientID string) string { +func testAccGraphQLAPIConfig_openIDConnectClientID(rName, clientID string) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "OPENID_CONNECT" @@ -1329,7 +1329,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, clientID) } -func testAccGraphQLAPIConfig_OpenIDConnectConfig_iatTTL(rName string, iatTTL int) string { +func testAccGraphQLAPIConfig_openIDConnectIatTTL(rName string, iatTTL int) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "OPENID_CONNECT" @@ -1343,7 +1343,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, iatTTL) } -func testAccGraphQLAPIConfig_OpenIDConnectConfig_issuer(rName, issuer string) string { +func testAccGraphQLAPIConfig_openIDConnectIssuer(rName, issuer string) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "OPENID_CONNECT" @@ -1356,7 +1356,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, issuer) } -func testAccGraphQLAPIConfig_UserPoolConfig_region(rName, awsRegion string) string { +func testAccGraphQLAPIConfig_userPoolRegion(rName, awsRegion string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %q @@ -1375,7 +1375,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, rName, awsRegion) } -func testAccGraphQLAPIConfig_UserPoolConfig_defaultAction(rName, defaultAction string) string { +func testAccGraphQLAPIConfig_userPoolDefaultAction(rName, defaultAction string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %q @@ -1431,7 +1431,7 @@ resource "aws_lambda_permission" "test" { `, rName) } -func testAccGraphQLAPIConfig_LambdaAuthorizerConfig_authorizerURI(rName, authorizerUri string) string { +func testAccGraphQLAPIConfig_lambdaAuthorizerAuthorizerURI(rName, authorizerUri string) string { return acctest.ConfigCompose(testAccGraphQLAPIConfig_LambdaAuthorizerConfig_base(rName), fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "AWS_LAMBDA" @@ -1444,7 +1444,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, authorizerUri)) } -func testAccGraphQLAPIConfig_LambdaAuthorizerConfig_identityValidationExpression(rName, identityValidationExpression string) string { +func testAccGraphQLAPIConfig_lambdaAuthorizerIdentityValidationExpression(rName, identityValidationExpression string) string { return acctest.ConfigCompose(testAccGraphQLAPIConfig_LambdaAuthorizerConfig_base(rName), fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "AWS_LAMBDA" @@ -1458,7 +1458,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, identityValidationExpression)) } -func testAccGraphQLAPIConfig_LambdaAuthorizerConfig_authorizerResultTTLInSeconds(rName, authorizerResultTtlInSeconds string) string { +func testAccGraphQLAPIConfig_lambdaAuthorizerAuthorizerResultTTLInSeconds(rName, authorizerResultTtlInSeconds string) string { return acctest.ConfigCompose(testAccGraphQLAPIConfig_LambdaAuthorizerConfig_base(rName), fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "AWS_LAMBDA" @@ -1521,7 +1521,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName) } -func testAccGraphQLAPIConfig_AdditionalAuth_authType(rName, defaultAuthType, additionalAuthType string) string { +func testAccGraphQLAPIConfig_additionalAuthAuthType(rName, defaultAuthType, additionalAuthType string) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = %q @@ -1533,7 +1533,7 @@ resource "aws_appsync_graphql_api" "test" { }`, defaultAuthType, rName, additionalAuthType) } -func testAccGraphQLAPIConfig_AdditionalAuth_userPoolConfig(rName string) string { +func testAccGraphQLAPIConfig_additionalAuthUserPool(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %q @@ -1554,7 +1554,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, rName) } -func testAccGraphQLAPIConfig_AdditionalAuth_openIdConnect(rName, issuer string) string { +func testAccGraphQLAPIConfig_additionalAuthOpenIdConnect(rName, issuer string) string { return fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" @@ -1571,7 +1571,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName, issuer) } -func testAccGraphQLAPIConfig_AdditionalAuth_lambda(rName string) string { +func testAccGraphQLAPIConfig_additionalAuthLambda(rName string) string { return acctest.ConfigCompose(testAccGraphQLAPIConfig_LambdaAuthorizerConfig_base(rName), fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" @@ -1588,7 +1588,7 @@ resource "aws_appsync_graphql_api" "test" { `, rName)) } -func testAccGraphQLAPIConfig_AdditionalAuth_multiple(rName, issuer string) string { +func testAccGraphQLAPIConfig_additionalAuthMultiple(rName, issuer string) string { return acctest.ConfigCompose(testAccGraphQLAPIConfig_LambdaAuthorizerConfig_base(rName), fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %q diff --git a/internal/service/appsync/resolver_test.go b/internal/service/appsync/resolver_test.go index 9c07e3c9512..fe0e1ccec3c 100644 --- a/internal/service/appsync/resolver_test.go +++ b/internal/service/appsync/resolver_test.go @@ -59,7 +59,7 @@ func testAccResolver_syncConfig(t *testing.T) { CheckDestroy: testAccCheckResolverDestroy, Steps: []resource.TestStep{ { - Config: testAccResolverConfig_syncConfig(rName), + Config: testAccResolverConfig_sync(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResolverExists(resourceName, &resolver1), resource.TestCheckResourceAttr(resourceName, "sync_config.#", "1"), @@ -243,7 +243,7 @@ func testAccResolver_multipleResolvers(t *testing.T) { CheckDestroy: testAccCheckResolverDestroy, Steps: []resource.TestStep{ { - Config: testAccResolverConfig_multipleResolvers(rName), + Config: testAccResolverConfig_multiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResolverExists(resourceName+"1", &resolver), testAccCheckResolverExists(resourceName+"2", &resolver), @@ -602,7 +602,7 @@ EOF `, statusCode) } -func testAccResolverConfig_multipleResolvers(rName string) string { +func testAccResolverConfig_multiple(rName string) string { var queryFields string var resolverResources string for i := 1; i <= 10; i++ { @@ -775,7 +775,7 @@ EOF ` } -func testAccResolverConfig_syncConfig(rName string) string { +func testAccResolverConfig_sync(rName string) string { return testAccDatasourceConfig_dynamoDBBase(rName) + fmt.Sprintf(` resource "aws_appsync_graphql_api" "test" { authentication_type = "API_KEY" diff --git a/internal/service/appsync/status.go b/internal/service/appsync/status.go index be0633493c2..2cda3dc9284 100644 --- a/internal/service/appsync/status.go +++ b/internal/service/appsync/status.go @@ -7,9 +7,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func StatusApiCache(conn *appsync.AppSync, name string) resource.StateRefreshFunc { +func StatusAPICache(conn *appsync.AppSync, name string) resource.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindApiCacheByID(conn, name) + output, err := FindAPICacheByID(conn, name) if tfresource.NotFound(err) { return nil, "", nil @@ -23,9 +23,9 @@ func StatusApiCache(conn *appsync.AppSync, name string) resource.StateRefreshFun } } -func statusDomainNameApiAssociation(conn *appsync.AppSync, id string) resource.StateRefreshFunc { +func statusDomainNameAPIAssociation(conn *appsync.AppSync, id string) resource.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindDomainNameApiAssociationByID(conn, id) + output, err := FindDomainNameAPIAssociationByID(conn, id) if tfresource.NotFound(err) { return nil, "", nil diff --git a/internal/service/appsync/sweep.go b/internal/service/appsync/sweep.go index 8a1bb342bd6..8284f10bbc2 100644 --- a/internal/service/appsync/sweep.go +++ b/internal/service/appsync/sweep.go @@ -172,7 +172,7 @@ func sweepDomainNameAssociations(region string) error { for _, dm := range output.DomainNameConfigs { - r := ResourceDomainNameApiAssociation() + r := ResourceDomainNameAPIAssociation() d := r.Data(nil) id := aws.StringValue(dm.DomainName) diff --git a/internal/service/appsync/wait.go b/internal/service/appsync/wait.go index 4046655042c..eff01aebbd3 100644 --- a/internal/service/appsync/wait.go +++ b/internal/service/appsync/wait.go @@ -10,15 +10,15 @@ import ( const ( apiCacheAvailableTimeout = 60 * time.Minute apiCacheDeletedTimeout = 60 * time.Minute - domainNameApiAssociationTimeout = 60 * time.Minute - domainNameApiDisassociationTimeout = 60 * time.Minute + domainNameAPIAssociationTimeout = 60 * time.Minute + domainNameAPIDisassociationTimeout = 60 * time.Minute ) -func waitApiCacheAvailable(conn *appsync.AppSync, id string) error { +func waitAPICacheAvailable(conn *appsync.AppSync, id string) error { stateConf := &resource.StateChangeConf{ Pending: []string{appsync.ApiCacheStatusCreating, appsync.ApiCacheStatusModifying}, Target: []string{appsync.ApiCacheStatusAvailable}, - Refresh: StatusApiCache(conn, id), + Refresh: StatusAPICache(conn, id), Timeout: apiCacheAvailableTimeout, } @@ -27,11 +27,11 @@ func waitApiCacheAvailable(conn *appsync.AppSync, id string) error { return err } -func waitApiCacheDeleted(conn *appsync.AppSync, id string) error { +func waitAPICacheDeleted(conn *appsync.AppSync, id string) error { stateConf := &resource.StateChangeConf{ Pending: []string{appsync.ApiCacheStatusDeleting}, Target: []string{}, - Refresh: StatusApiCache(conn, id), + Refresh: StatusAPICache(conn, id), Timeout: apiCacheDeletedTimeout, } @@ -40,12 +40,12 @@ func waitApiCacheDeleted(conn *appsync.AppSync, id string) error { return err } -func waitDomainNameApiAssociation(conn *appsync.AppSync, id string) error { +func waitDomainNameAPIAssociation(conn *appsync.AppSync, id string) error { stateConf := &resource.StateChangeConf{ Pending: []string{appsync.AssociationStatusProcessing}, Target: []string{appsync.AssociationStatusSuccess}, - Refresh: statusDomainNameApiAssociation(conn, id), - Timeout: domainNameApiAssociationTimeout, + Refresh: statusDomainNameAPIAssociation(conn, id), + Timeout: domainNameAPIAssociationTimeout, } _, err := stateConf.WaitForState() @@ -53,12 +53,12 @@ func waitDomainNameApiAssociation(conn *appsync.AppSync, id string) error { return err } -func waitDomainNameApiDisassociation(conn *appsync.AppSync, id string) error { +func waitDomainNameAPIDisassociation(conn *appsync.AppSync, id string) error { stateConf := &resource.StateChangeConf{ Pending: []string{appsync.AssociationStatusProcessing}, Target: []string{}, - Refresh: statusDomainNameApiAssociation(conn, id), - Timeout: domainNameApiDisassociationTimeout, + Refresh: statusDomainNameAPIAssociation(conn, id), + Timeout: domainNameAPIDisassociationTimeout, } _, err := stateConf.WaitForState() diff --git a/internal/service/athena/data_catalog_test.go b/internal/service/athena/data_catalog_test.go index 3f1c9777027..10cd4ce2a37 100644 --- a/internal/service/athena/data_catalog_test.go +++ b/internal/service/athena/data_catalog_test.go @@ -26,7 +26,7 @@ func TestAccAthenaDataCatalog_basic(t *testing.T) { CheckDestroy: testAccCheckDataCatalogDestroy, Steps: []resource.TestStep{ { - Config: testAccDataCatalogConfig(rName), + Config: testAccDataCatalogConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "athena", fmt.Sprintf("datacatalog/%s", rName)), @@ -59,7 +59,7 @@ func TestAccAthenaDataCatalog_disappears(t *testing.T) { CheckDestroy: testAccCheckDataCatalogDestroy, Steps: []resource.TestStep{ { - Config: testAccDataCatalogConfig(rName), + Config: testAccDataCatalogConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfathena.ResourceDataCatalog(), resourceName), @@ -81,7 +81,7 @@ func TestAccAthenaDataCatalog_tags(t *testing.T) { CheckDestroy: testAccCheckDataCatalogDestroy, Steps: []resource.TestStep{ { - Config: testAccDataCatalogConfigTags1(rName, "key1", "value1"), + Config: testAccDataCatalogConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -95,7 +95,7 @@ func TestAccAthenaDataCatalog_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"parameters"}, }, { - Config: testAccDataCatalogConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDataCatalogConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -104,7 +104,7 @@ func TestAccAthenaDataCatalog_tags(t *testing.T) { ), }, { - Config: testAccDataCatalogConfigTags1(rName, "key2", "value2"), + Config: testAccDataCatalogConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -126,7 +126,7 @@ func TestAccAthenaDataCatalog_type_lambda(t *testing.T) { CheckDestroy: testAccCheckDataCatalogDestroy, Steps: []resource.TestStep{ { - Config: testAccDataCatalogTypeLambdaConfig(rName), + Config: testAccDataCatalogConfig_typeLambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "A test data catalog using Lambda"), @@ -157,7 +157,7 @@ func TestAccAthenaDataCatalog_type_hive(t *testing.T) { CheckDestroy: testAccCheckDataCatalogDestroy, Steps: []resource.TestStep{ { - Config: testAccDataCatalogTypeHiveConfig(rName), + Config: testAccDataCatalogConfig_typeHive(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "A test data catalog using Hive"), @@ -187,7 +187,7 @@ func TestAccAthenaDataCatalog_type_glue(t *testing.T) { CheckDestroy: testAccCheckDataCatalogDestroy, Steps: []resource.TestStep{ { - Config: testAccDataCatalogTypeGlueConfig(rName), + Config: testAccDataCatalogConfig_typeGlue(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "A test data catalog using Glue"), @@ -217,7 +217,7 @@ func TestAccAthenaDataCatalog_parameters(t *testing.T) { CheckDestroy: testAccCheckDataCatalogDestroy, Steps: []resource.TestStep{ { - Config: testAccDataCatalogParametersConfig(rName), + Config: testAccDataCatalogConfig_parameters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameters.%", "1"), @@ -231,7 +231,7 @@ func TestAccAthenaDataCatalog_parameters(t *testing.T) { ImportStateVerifyIgnore: []string{"parameters"}, }, { - Config: testAccDataCatalogParametersUpdatedConfig(rName), + Config: testAccDataCatalogConfig_parametersUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameters.%", "2"), @@ -300,7 +300,7 @@ func testAccCheckDataCatalogDestroy(s *terraform.State) error { return nil } -func testAccDataCatalogConfig(rName string) string { +func testAccDataCatalogConfig_basic(rName string) string { //lintignore:AWSAT003,AWSAT005 return fmt.Sprintf(` resource "aws_athena_data_catalog" "test" { @@ -315,7 +315,7 @@ resource "aws_athena_data_catalog" "test" { `, rName) } -func testAccDataCatalogConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccDataCatalogConfig_tags1(rName, tagKey1, tagValue1 string) string { //lintignore:AWSAT003,AWSAT005 return fmt.Sprintf(` resource "aws_athena_data_catalog" "test" { @@ -335,7 +335,7 @@ resource "aws_athena_data_catalog" "test" { `, rName, tagKey1, tagValue1) } -func testAccDataCatalogConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDataCatalogConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { //lintignore:AWSAT003,AWSAT005 return fmt.Sprintf(` resource "aws_athena_data_catalog" "test" { @@ -356,7 +356,7 @@ resource "aws_athena_data_catalog" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccDataCatalogTypeLambdaConfig(rName string) string { +func testAccDataCatalogConfig_typeLambda(rName string) string { //lintignore:AWSAT003,AWSAT005 return fmt.Sprintf(` resource "aws_athena_data_catalog" "test" { @@ -372,7 +372,7 @@ resource "aws_athena_data_catalog" "test" { `, rName) } -func testAccDataCatalogTypeHiveConfig(rName string) string { +func testAccDataCatalogConfig_typeHive(rName string) string { //lintignore:AWSAT003,AWSAT005 return fmt.Sprintf(` resource "aws_athena_data_catalog" "test" { @@ -387,7 +387,7 @@ resource "aws_athena_data_catalog" "test" { `, rName) } -func testAccDataCatalogTypeGlueConfig(rName string) string { +func testAccDataCatalogConfig_typeGlue(rName string) string { return fmt.Sprintf(` resource "aws_athena_data_catalog" "test" { name = %[1]q @@ -401,7 +401,7 @@ resource "aws_athena_data_catalog" "test" { `, rName) } -func testAccDataCatalogParametersConfig(rName string) string { +func testAccDataCatalogConfig_parameters(rName string) string { //lintignore:AWSAT003,AWSAT005 return fmt.Sprintf(` resource "aws_athena_data_catalog" "test" { @@ -416,7 +416,7 @@ resource "aws_athena_data_catalog" "test" { `, rName) } -func testAccDataCatalogParametersUpdatedConfig(rName string) string { +func testAccDataCatalogConfig_parametersUpdated(rName string) string { //lintignore:AWSAT003,AWSAT005 return fmt.Sprintf(` resource "aws_athena_data_catalog" "test" { diff --git a/internal/service/athena/database.go b/internal/service/athena/database.go index 3fc0ee5ff84..f02efcc92ba 100644 --- a/internal/service/athena/database.go +++ b/internal/service/athena/database.go @@ -213,7 +213,7 @@ func expandResultConfiguration(d *schema.ResourceData) *athena.ResultConfigurati } if v, ok := d.GetOk("acl_configuration"); ok && len(v.([]interface{})) > 0 { - resultConfig.AclConfiguration = expandResultConfigurationAclConfig(v.([]interface{})) + resultConfig.AclConfiguration = expandResultConfigurationACLConfig(v.([]interface{})) } return resultConfig @@ -237,7 +237,7 @@ func expandResultConfigurationEncryptionConfig(config []interface{}) *athena.Enc return encryptionConfig } -func expandResultConfigurationAclConfig(config []interface{}) *athena.AclConfiguration { +func expandResultConfigurationACLConfig(config []interface{}) *athena.AclConfiguration { if len(config) <= 0 { return nil } diff --git a/internal/service/athena/database_test.go b/internal/service/athena/database_test.go index cdc4d3ea6bd..bfc92a31205 100644 --- a/internal/service/athena/database_test.go +++ b/internal/service/athena/database_test.go @@ -27,7 +27,7 @@ func TestAccAthenaDatabase_basic(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseConfig(rName, dbName, false), + Config: testAccDatabaseConfig_basic(rName, dbName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", dbName), @@ -59,7 +59,7 @@ func TestAccAthenaDatabase_properties(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabasePropertiesConfig(rName, dbName, false), + Config: testAccDatabaseConfig_properties(rName, dbName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", dbName), @@ -89,7 +89,7 @@ func TestAccAthenaDatabase_acl(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseAclConfig(rName, dbName, false), + Config: testAccDatabaseConfig_acl(rName, dbName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", dbName), @@ -119,7 +119,7 @@ func TestAccAthenaDatabase_encryption(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseWithKMSConfig(rName, dbName, false), + Config: testAccDatabaseConfig_kms(rName, dbName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists(resourceName), resource.TestCheckResourceAttr(resourceName, "encryption_configuration.#", "1"), @@ -149,7 +149,7 @@ func TestAccAthenaDatabase_nameStartsWithUnderscore(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseConfig(rName, dbName, false), + Config: testAccDatabaseConfig_basic(rName, dbName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", dbName), @@ -176,7 +176,7 @@ func TestAccAthenaDatabase_nameCantHaveUppercase(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseConfig(rName, dbName, false), + Config: testAccDatabaseConfig_basic(rName, dbName, false), ExpectError: regexp.MustCompile(`must be lowercase letters, numbers, or underscore \('_'\)`), }, }, @@ -194,7 +194,7 @@ func TestAccAthenaDatabase_destroyFailsIfTablesExist(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseConfig(rName, dbName, false), + Config: testAccDatabaseConfig_basic(rName, dbName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists("aws_athena_database.test"), testAccDatabaseCreateTables(dbName), @@ -217,7 +217,7 @@ func TestAccAthenaDatabase_forceDestroyAlwaysSucceeds(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseConfig(rName, dbName, true), + Config: testAccDatabaseConfig_basic(rName, dbName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists("aws_athena_database.test"), testAccDatabaseCreateTables(dbName), @@ -239,7 +239,7 @@ func TestAccAthenaDatabase_description(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseCommentConfig(rName, dbName, false), + Config: testAccDatabaseConfig_comment(rName, dbName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", dbName), @@ -268,7 +268,7 @@ func TestAccAthenaDatabase_unescaped_description(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseUnescapedCommentConfig(rName, dbName, false), + Config: testAccDatabaseConfig_unescapedComment(rName, dbName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", dbName), @@ -297,7 +297,7 @@ func TestAccAthenaDatabase_disppears(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccDatabaseConfig(rName, dbName, false), + Config: testAccDatabaseConfig_basic(rName, dbName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDatabaseExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfathena.ResourceDatabase(), resourceName), @@ -457,7 +457,7 @@ func testAccDatabaseFindBucketName(s *terraform.State, dbName string) (bucket st return bucket, err } -func testAccDatabaseConfig(rName string, dbName string, forceDestroy bool) string { +func testAccDatabaseConfig_basic(rName string, dbName string, forceDestroy bool) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -472,7 +472,7 @@ resource "aws_athena_database" "test" { `, rName, dbName, forceDestroy) } -func testAccDatabasePropertiesConfig(rName string, dbName string, forceDestroy bool) string { +func testAccDatabaseConfig_properties(rName string, dbName string, forceDestroy bool) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -491,7 +491,7 @@ resource "aws_athena_database" "test" { `, rName, dbName, forceDestroy) } -func testAccDatabaseAclConfig(rName string, dbName string, forceDestroy bool) string { +func testAccDatabaseConfig_acl(rName string, dbName string, forceDestroy bool) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -510,7 +510,7 @@ resource "aws_athena_database" "test" { `, rName, dbName, forceDestroy) } -func testAccDatabaseWithKMSConfig(rName string, dbName string, forceDestroy bool) string { +func testAccDatabaseConfig_kms(rName string, dbName string, forceDestroy bool) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 10 @@ -549,7 +549,7 @@ resource "aws_athena_database" "test" { `, rName, dbName, forceDestroy) } -func testAccDatabaseCommentConfig(rName string, dbName string, forceDestroy bool) string { +func testAccDatabaseConfig_comment(rName string, dbName string, forceDestroy bool) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -565,7 +565,7 @@ resource "aws_athena_database" "test" { `, rName, dbName, forceDestroy) } -func testAccDatabaseUnescapedCommentConfig(rName string, dbName string, forceDestroy bool) string { +func testAccDatabaseConfig_unescapedComment(rName string, dbName string, forceDestroy bool) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/athena/named_query_test.go b/internal/service/athena/named_query_test.go index e94dc852cc9..e92be825c96 100644 --- a/internal/service/athena/named_query_test.go +++ b/internal/service/athena/named_query_test.go @@ -24,7 +24,7 @@ func TestAccAthenaNamedQuery_basic(t *testing.T) { CheckDestroy: testAccCheckNamedQueryDestroy, Steps: []resource.TestStep{ { - Config: testAccNamedQueryConfig(sdkacctest.RandInt(), sdkacctest.RandString(5)), + Config: testAccNamedQueryConfig_basic(sdkacctest.RandInt(), sdkacctest.RandString(5)), Check: resource.ComposeTestCheckFunc( testAccCheckNamedQueryExists(resourceName), ), @@ -48,7 +48,7 @@ func TestAccAthenaNamedQuery_withWorkGroup(t *testing.T) { CheckDestroy: testAccCheckNamedQueryDestroy, Steps: []resource.TestStep{ { - Config: testAccNamedWorkGroupQueryConfig(sdkacctest.RandInt(), sdkacctest.RandString(5)), + Config: testAccNamedQueryConfig_workGroup(sdkacctest.RandInt(), sdkacctest.RandString(5)), Check: resource.ComposeTestCheckFunc( testAccCheckNamedQueryExists(resourceName), ), @@ -105,7 +105,7 @@ func testAccCheckNamedQueryExists(name string) resource.TestCheckFunc { } } -func testAccNamedQueryConfig(rInt int, rName string) string { +func testAccNamedQueryConfig_basic(rInt int, rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = "tf-test-athena-db-%s-%d" @@ -126,7 +126,7 @@ resource "aws_athena_named_query" "test" { `, rName, rInt, rName, rName) } -func testAccNamedWorkGroupQueryConfig(rInt int, rName string) string { +func testAccNamedQueryConfig_workGroup(rInt int, rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = "tf-test-athena-db-%s-%d" diff --git a/internal/service/athena/workgroup.go b/internal/service/athena/workgroup.go index beb96424f07..6622d43102c 100644 --- a/internal/service/athena/workgroup.go +++ b/internal/service/athena/workgroup.go @@ -441,7 +441,7 @@ func expandWorkGroupResultConfiguration(l []interface{}) *athena.ResultConfigura } if v, ok := m["acl_configuration"]; ok { - resultConfiguration.AclConfiguration = expandResultConfigurationAclConfig(v.([]interface{})) + resultConfiguration.AclConfiguration = expandResultConfigurationACLConfig(v.([]interface{})) } return resultConfiguration @@ -475,7 +475,7 @@ func expandWorkGroupResultConfigurationUpdates(l []interface{}) *athena.ResultCo } if v, ok := m["acl_configuration"]; ok { - resultConfigurationUpdates.AclConfiguration = expandResultConfigurationAclConfig(v.([]interface{})) + resultConfigurationUpdates.AclConfiguration = expandResultConfigurationACLConfig(v.([]interface{})) } else { resultConfigurationUpdates.RemoveAclConfiguration = aws.Bool(true) } @@ -548,7 +548,7 @@ func flattenWorkGroupResultConfiguration(resultConfiguration *athena.ResultConfi } if resultConfiguration.AclConfiguration != nil { - m["acl_configuration"] = flattenWorkGroupAclConfiguration(resultConfiguration.AclConfiguration) + m["acl_configuration"] = flattenWorkGroupACLConfiguration(resultConfiguration.AclConfiguration) } return []interface{}{m} @@ -567,7 +567,7 @@ func flattenWorkGroupEncryptionConfiguration(encryptionConfiguration *athena.Enc return []interface{}{m} } -func flattenWorkGroupAclConfiguration(aclConfig *athena.AclConfiguration) []interface{} { +func flattenWorkGroupACLConfiguration(aclConfig *athena.AclConfiguration) []interface{} { if aclConfig == nil { return []interface{}{} } diff --git a/internal/service/athena/workgroup_test.go b/internal/service/athena/workgroup_test.go index f13d28d947d..8e86024cd63 100644 --- a/internal/service/athena/workgroup_test.go +++ b/internal/service/athena/workgroup_test.go @@ -27,7 +27,7 @@ func TestAccAthenaWorkGroup_basic(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfig(rName), + Config: testAccWorkGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "athena", fmt.Sprintf("workgroup/%s", rName)), @@ -66,7 +66,7 @@ func TestAccAthenaWorkGroup_aclConfig(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationResultConfigurationAclConfig(rName), + Config: testAccWorkGroupConfig_configurationResultConfigurationACL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "athena", fmt.Sprintf("workgroup/%s", rName)), @@ -98,7 +98,7 @@ func TestAccAthenaWorkGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfig(rName), + Config: testAccWorkGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), acctest.CheckResourceDisappears(acctest.Provider, tfathena.ResourceWorkGroup(), resourceName), @@ -121,7 +121,7 @@ func TestAccAthenaWorkGroup_bytesScannedCutoffPerQuery(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationBytesScannedCutoffPerQuery(rName, 12582912), + Config: testAccWorkGroupConfig_configurationBytesScannedCutoffPerQuery(rName, 12582912), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -135,7 +135,7 @@ func TestAccAthenaWorkGroup_bytesScannedCutoffPerQuery(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigConfigurationBytesScannedCutoffPerQuery(rName, 10485760), + Config: testAccWorkGroupConfig_configurationBytesScannedCutoffPerQuery(rName, 10485760), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -158,7 +158,7 @@ func TestAccAthenaWorkGroup_enforceWorkGroup(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationEnforceWorkgroupConfiguration(rName, false), + Config: testAccWorkGroupConfig_enforce(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -172,7 +172,7 @@ func TestAccAthenaWorkGroup_enforceWorkGroup(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigConfigurationEnforceWorkgroupConfiguration(rName, true), + Config: testAccWorkGroupConfig_enforce(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -195,7 +195,7 @@ func TestAccAthenaWorkGroup_configurationEngineVersion(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationEngineVersion(rName, "Athena engine version 2"), + Config: testAccWorkGroupConfig_configurationEngineVersion(rName, "Athena engine version 2"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -211,7 +211,7 @@ func TestAccAthenaWorkGroup_configurationEngineVersion(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigConfigurationEngineVersion(rName, "AUTO"), + Config: testAccWorkGroupConfig_configurationEngineVersion(rName, "AUTO"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -227,7 +227,7 @@ func TestAccAthenaWorkGroup_configurationEngineVersion(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfig(rName), + Config: testAccWorkGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttrSet(resourceName, "configuration.0.engine_version.0.effective_engine_version"), @@ -250,7 +250,7 @@ func TestAccAthenaWorkGroup_publishCloudWatchMetricsEnabled(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationPublishCloudWatchMetricsEnabled(rName, false), + Config: testAccWorkGroupConfig_configurationPublishCloudWatchMetricsEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -264,7 +264,7 @@ func TestAccAthenaWorkGroup_publishCloudWatchMetricsEnabled(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigConfigurationPublishCloudWatchMetricsEnabled(rName, true), + Config: testAccWorkGroupConfig_configurationPublishCloudWatchMetricsEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -287,7 +287,7 @@ func TestAccAthenaWorkGroup_ResultEncryption_sseS3(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationResultConfigurationEncryptionConfigurationEncryptionOptionSseS3(rName), + Config: testAccWorkGroupConfig_configurationResultConfigurationEncryptionConfigurationEncryptionOptionSseS3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -320,7 +320,7 @@ func TestAccAthenaWorkGroup_ResultEncryption_kms(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationResultConfigurationEncryptionConfigurationEncryptionOptionWithKms(rName, rEncryption), + Config: testAccWorkGroupConfig_resultEncryptionEncryptionOptionKMS(rName, rEncryption), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -336,7 +336,7 @@ func TestAccAthenaWorkGroup_ResultEncryption_kms(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigConfigurationResultConfigurationEncryptionConfigurationEncryptionOptionWithKms(rName, rEncryption2), + Config: testAccWorkGroupConfig_resultEncryptionEncryptionOptionKMS(rName, rEncryption2), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -363,7 +363,7 @@ func TestAccAthenaWorkGroup_Result_outputLocation(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationResultConfigurationOutputLocation(rName, rOutputLocation1), + Config: testAccWorkGroupConfig_configurationResultConfigurationOutputLocation(rName, rOutputLocation1), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -378,7 +378,7 @@ func TestAccAthenaWorkGroup_Result_outputLocation(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigConfigurationResultConfigurationOutputLocation(rName, rOutputLocation2), + Config: testAccWorkGroupConfig_configurationResultConfigurationOutputLocation(rName, rOutputLocation2), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -402,7 +402,7 @@ func TestAccAthenaWorkGroup_requesterPaysEnabled(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationRequesterPaysEnabled(rName), + Config: testAccWorkGroupConfig_configurationRequesterPaysEnabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "athena", fmt.Sprintf("workgroup/%s", rName)), @@ -417,7 +417,7 @@ func TestAccAthenaWorkGroup_requesterPaysEnabled(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfig(rName), + Config: testAccWorkGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "athena", fmt.Sprintf("workgroup/%s", rName)), @@ -443,7 +443,7 @@ func TestAccAthenaWorkGroup_ResultOutputLocation_forceDestroy(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigConfigurationResultConfigurationOutputLocationForceDestroy(rName, rOutputLocation1), + Config: testAccWorkGroupConfig_configurationResultConfigurationOutputLocationForceDestroy(rName, rOutputLocation1), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -458,7 +458,7 @@ func TestAccAthenaWorkGroup_ResultOutputLocation_forceDestroy(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigConfigurationResultConfigurationOutputLocationForceDestroy(rName, rOutputLocation2), + Config: testAccWorkGroupConfig_configurationResultConfigurationOutputLocationForceDestroy(rName, rOutputLocation2), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -484,7 +484,7 @@ func TestAccAthenaWorkGroup_description(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigDescription(rName, rDescription), + Config: testAccWorkGroupConfig_description(rName, rDescription), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "description", rDescription), @@ -497,7 +497,7 @@ func TestAccAthenaWorkGroup_description(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigDescription(rName, rDescriptionUpdate), + Config: testAccWorkGroupConfig_description(rName, rDescriptionUpdate), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "description", rDescriptionUpdate), @@ -519,7 +519,7 @@ func TestAccAthenaWorkGroup_state(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigState(rName, athena.WorkGroupStateDisabled), + Config: testAccWorkGroupConfig_state(rName, athena.WorkGroupStateDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "state", athena.WorkGroupStateDisabled), @@ -532,14 +532,14 @@ func TestAccAthenaWorkGroup_state(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigState(rName, athena.WorkGroupStateEnabled), + Config: testAccWorkGroupConfig_state(rName, athena.WorkGroupStateEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "state", athena.WorkGroupStateEnabled), ), }, { - Config: testAccWorkGroupConfigState(rName, athena.WorkGroupStateDisabled), + Config: testAccWorkGroupConfig_state(rName, athena.WorkGroupStateDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup3), resource.TestCheckResourceAttr(resourceName, "state", athena.WorkGroupStateDisabled), @@ -564,7 +564,7 @@ func TestAccAthenaWorkGroup_forceDestroy(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigForceDestroy(rName, dbName), + Config: testAccWorkGroupConfig_forceDestroy(rName, dbName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup), testAccCheckCreateNamedQuery(&workgroup, dbName, queryName1, fmt.Sprintf("SELECT * FROM %s limit 10;", rName)), @@ -593,7 +593,7 @@ func TestAccAthenaWorkGroup_tags(t *testing.T) { CheckDestroy: testAccCheckWorkGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkGroupConfigTags1(rName, "key1", "value1"), + Config: testAccWorkGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -607,7 +607,7 @@ func TestAccAthenaWorkGroup_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccWorkGroupConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccWorkGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -616,7 +616,7 @@ func TestAccAthenaWorkGroup_tags(t *testing.T) { ), }, { - Config: testAccWorkGroupConfigTags1(rName, "key2", "value2"), + Config: testAccWorkGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkGroupExists(resourceName, &workgroup3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -700,7 +700,7 @@ func testAccCheckWorkGroupExists(name string, workgroup *athena.WorkGroup) resou } } -func testAccWorkGroupConfig(rName string) string { +func testAccWorkGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -708,7 +708,7 @@ resource "aws_athena_workgroup" "test" { `, rName) } -func testAccWorkGroupConfigDescription(rName string, description string) string { +func testAccWorkGroupConfig_description(rName string, description string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { description = %[2]q @@ -717,7 +717,7 @@ resource "aws_athena_workgroup" "test" { `, rName, description) } -func testAccWorkGroupConfigConfigurationBytesScannedCutoffPerQuery(rName string, bytesScannedCutoffPerQuery int) string { +func testAccWorkGroupConfig_configurationBytesScannedCutoffPerQuery(rName string, bytesScannedCutoffPerQuery int) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -729,7 +729,7 @@ resource "aws_athena_workgroup" "test" { `, rName, bytesScannedCutoffPerQuery) } -func testAccWorkGroupConfigConfigurationEnforceWorkgroupConfiguration(rName string, enforceWorkgroupConfiguration bool) string { +func testAccWorkGroupConfig_enforce(rName string, enforceWorkgroupConfiguration bool) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -741,7 +741,7 @@ resource "aws_athena_workgroup" "test" { `, rName, enforceWorkgroupConfiguration) } -func testAccWorkGroupConfigConfigurationEngineVersion(rName, engineVersion string) string { +func testAccWorkGroupConfig_configurationEngineVersion(rName, engineVersion string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -755,7 +755,7 @@ resource "aws_athena_workgroup" "test" { `, rName, engineVersion) } -func testAccWorkGroupConfigConfigurationPublishCloudWatchMetricsEnabled(rName string, publishCloudwatchMetricsEnabled bool) string { +func testAccWorkGroupConfig_configurationPublishCloudWatchMetricsEnabled(rName string, publishCloudwatchMetricsEnabled bool) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -767,7 +767,7 @@ resource "aws_athena_workgroup" "test" { `, rName, publishCloudwatchMetricsEnabled) } -func testAccWorkGroupConfigConfigurationResultConfigurationOutputLocation(rName string, bucketName string) string { +func testAccWorkGroupConfig_configurationResultConfigurationOutputLocation(rName string, bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[2]q @@ -786,7 +786,7 @@ resource "aws_athena_workgroup" "test" { `, rName, bucketName) } -func testAccWorkGroupConfigConfigurationRequesterPaysEnabled(rName string) string { +func testAccWorkGroupConfig_configurationRequesterPaysEnabled(rName string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -798,7 +798,7 @@ resource "aws_athena_workgroup" "test" { `, rName) } -func testAccWorkGroupConfigConfigurationResultConfigurationOutputLocationForceDestroy(rName string, bucketName string) string { +func testAccWorkGroupConfig_configurationResultConfigurationOutputLocationForceDestroy(rName string, bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[2]q @@ -819,7 +819,7 @@ resource "aws_athena_workgroup" "test" { `, rName, bucketName) } -func testAccWorkGroupConfigConfigurationResultConfigurationAclConfig(rName string) string { +func testAccWorkGroupConfig_configurationResultConfigurationACL(rName string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -835,7 +835,7 @@ resource "aws_athena_workgroup" "test" { `, rName) } -func testAccWorkGroupConfigConfigurationResultConfigurationEncryptionConfigurationEncryptionOptionSseS3(rName string) string { +func testAccWorkGroupConfig_configurationResultConfigurationEncryptionConfigurationEncryptionOptionSseS3(rName string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -851,7 +851,7 @@ resource "aws_athena_workgroup" "test" { `, rName) } -func testAccWorkGroupConfigConfigurationResultConfigurationEncryptionConfigurationEncryptionOptionWithKms(rName, encryptionOption string) string { +func testAccWorkGroupConfig_resultEncryptionEncryptionOptionKMS(rName, encryptionOption string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -873,7 +873,7 @@ resource "aws_athena_workgroup" "test" { `, rName, encryptionOption) } -func testAccWorkGroupConfigState(rName, state string) string { +func testAccWorkGroupConfig_state(rName, state string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -882,7 +882,7 @@ resource "aws_athena_workgroup" "test" { `, rName, state) } -func testAccWorkGroupConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccWorkGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -894,7 +894,7 @@ resource "aws_athena_workgroup" "test" { `, rName, tagKey1, tagValue1) } -func testAccWorkGroupConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccWorkGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q @@ -907,7 +907,7 @@ resource "aws_athena_workgroup" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccWorkGroupConfigForceDestroy(rName, dbName string) string { +func testAccWorkGroupConfig_forceDestroy(rName, dbName string) string { return fmt.Sprintf(` resource "aws_athena_workgroup" "test" { name = %[1]q diff --git a/internal/service/autoscaling/attachment_test.go b/internal/service/autoscaling/attachment_test.go index c6c87808561..5cac4664655 100644 --- a/internal/service/autoscaling/attachment_test.go +++ b/internal/service/autoscaling/attachment_test.go @@ -24,31 +24,31 @@ func TestAccAutoScalingAttachment_elb(t *testing.T) { CheckDestroy: testAccCheckAutocalingAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccAttachment_elb(rInt), + Config: testAccAttachmentConfig_elb(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingELBAttachmentExists("aws_autoscaling_group.asg", 0), ), }, { - Config: testAccAttachment_elb_associated(rInt), + Config: testAccAttachmentConfig_elbAssociated(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingELBAttachmentExists("aws_autoscaling_group.asg", 1), ), }, { - Config: testAccAttachment_elb_double_associated(rInt), + Config: testAccAttachmentConfig_elbDoubleAssociated(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingELBAttachmentExists("aws_autoscaling_group.asg", 2), ), }, { - Config: testAccAttachment_elb_associated(rInt), + Config: testAccAttachmentConfig_elbAssociated(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingELBAttachmentExists("aws_autoscaling_group.asg", 1), ), }, { - Config: testAccAttachment_elb(rInt), + Config: testAccAttachmentConfig_elb(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingELBAttachmentExists("aws_autoscaling_group.asg", 0), ), @@ -68,31 +68,31 @@ func TestAccAutoScalingAttachment_albTargetGroup(t *testing.T) { CheckDestroy: testAccCheckAutocalingAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccAttachment_alb(rInt), + Config: testAccAttachmentConfig_alb(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingAlbAttachmentExists("aws_autoscaling_group.asg", 0), ), }, { - Config: testAccAttachment_alb_associated(rInt), + Config: testAccAttachmentConfig_albAssociated(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingAlbAttachmentExists("aws_autoscaling_group.asg", 1), ), }, { - Config: testAccAttachment_alb_double_associated(rInt), + Config: testAccAttachmentConfig_albDoubleAssociated(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingAlbAttachmentExists("aws_autoscaling_group.asg", 2), ), }, { - Config: testAccAttachment_alb_associated(rInt), + Config: testAccAttachmentConfig_albAssociated(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingAlbAttachmentExists("aws_autoscaling_group.asg", 1), ), }, { - Config: testAccAttachment_alb(rInt), + Config: testAccAttachmentConfig_alb(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAutocalingAlbAttachmentExists("aws_autoscaling_group.asg", 0), ), @@ -179,8 +179,8 @@ func testAccCheckAutocalingAlbAttachmentExists(asgname string, targetGroupCount } } -func testAccAttachment_alb(rInt int) string { - return acctest.ConfigLatestAmazonLinuxHvmEbsAmi() + fmt.Sprintf(` +func testAccAttachmentConfig_alb(rInt int) string { + return acctest.ConfigLatestAmazonLinuxHVMEBSAMI() + fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -285,8 +285,8 @@ resource "aws_vpc" "test" { `, rInt, rInt, rInt, rInt) } -func testAccAttachment_elb(rInt int) string { - return acctest.ConfigLatestAmazonLinuxHvmEbsAmi() + fmt.Sprintf(` +func testAccAttachmentConfig_elb(rInt int) string { + return acctest.ConfigLatestAmazonLinuxHVMEBSAMI() + fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -347,32 +347,32 @@ resource "aws_autoscaling_group" "asg" { `, rInt, rInt) } -func testAccAttachment_elb_associated(rInt int) string { - return testAccAttachment_elb(rInt) + ` +func testAccAttachmentConfig_elbAssociated(rInt int) string { + return testAccAttachmentConfig_elb(rInt) + ` resource "aws_autoscaling_attachment" "asg_attachment_foo" { autoscaling_group_name = aws_autoscaling_group.asg.id elb = aws_elb.foo.id }` } -func testAccAttachment_alb_associated(rInt int) string { - return testAccAttachment_alb(rInt) + ` +func testAccAttachmentConfig_albAssociated(rInt int) string { + return testAccAttachmentConfig_alb(rInt) + ` resource "aws_autoscaling_attachment" "asg_attachment_foo" { autoscaling_group_name = aws_autoscaling_group.asg.id alb_target_group_arn = aws_lb_target_group.test.arn }` } -func testAccAttachment_elb_double_associated(rInt int) string { - return testAccAttachment_elb_associated(rInt) + ` +func testAccAttachmentConfig_elbDoubleAssociated(rInt int) string { + return testAccAttachmentConfig_elbAssociated(rInt) + ` resource "aws_autoscaling_attachment" "asg_attachment_bar" { autoscaling_group_name = aws_autoscaling_group.asg.id elb = aws_elb.bar.id }` } -func testAccAttachment_alb_double_associated(rInt int) string { - return testAccAttachment_alb_associated(rInt) + ` +func testAccAttachmentConfig_albDoubleAssociated(rInt int) string { + return testAccAttachmentConfig_albAssociated(rInt) + ` resource "aws_autoscaling_attachment" "asg_attachment_bar" { autoscaling_group_name = aws_autoscaling_group.asg.id alb_target_group_arn = aws_lb_target_group.another_test.arn diff --git a/internal/service/autoscaling/consts.go b/internal/service/autoscaling/consts.go index d4b3b165396..72aa4eebbba 100644 --- a/internal/service/autoscaling/consts.go +++ b/internal/service/autoscaling/consts.go @@ -10,6 +10,39 @@ const ( propagationTimeout = 2 * time.Minute ) +const ( + DefaultEnabledMetricsGranularity = "1Minute" +) + +const ( + DefaultTerminationPolicy = "Default" +) + +const ( + DefaultWarmPoolMaxGroupPreparedCapacity = -1 +) + +const ( + InstanceHealthStatusHealthy = "Healthy" + InstanceHealthStatusUnhealthy = "Unhealthy" +) + +const ( + LoadBalancerStateAdding = "Adding" + LoadBalancerStateAdded = "Added" + LoadBalancerStateInService = "InService" + LoadBalancerStateRemoving = "Removing" + LoadBalancerStateRemoved = "Removed" +) + +const ( + LoadBalancerTargetGroupStateAdding = "Adding" + LoadBalancerTargetGroupStateAdded = "Added" + LoadBalancerTargetGroupStateInService = "InService" + LoadBalancerTargetGroupStateRemoving = "Removing" + LoadBalancerTargetGroupStateRemoved = "Removed" +) + const ( PolicyTypePredictiveScaling = "PredictiveScaling" PolicyTypeSimpleScaling = "SimpleScaling" diff --git a/internal/service/autoscaling/flex.go b/internal/service/autoscaling/flex.go index 18c8bf8a54f..4cf62ffdd54 100644 --- a/internal/service/autoscaling/flex.go +++ b/internal/service/autoscaling/flex.go @@ -8,26 +8,6 @@ import ( "github.com/aws/aws-sdk-go/service/autoscaling" ) -func flattenASGEnabledMetrics(list []*autoscaling.EnabledMetric) []string { - strs := make([]string, 0, len(list)) - for _, r := range list { - if r.Metric != nil { - strs = append(strs, *r.Metric) - } - } - return strs -} - -func flattenASGSuspendedProcesses(list []*autoscaling.SuspendedProcess) []string { - strs := make([]string, 0, len(list)) - for _, r := range list { - if r.ProcessName != nil { - strs = append(strs, *r.ProcessName) - } - } - return strs -} - // Takes the result of flatmap.Expand for an array of step adjustments and // returns a []*autoscaling.StepAdjustment. func ExpandStepAdjustments(configured []interface{}) ([]*autoscaling.StepAdjustment, error) { diff --git a/internal/service/autoscaling/flex_test.go b/internal/service/autoscaling/flex_test.go index 86b142ae673..d50b1235ab4 100644 --- a/internal/service/autoscaling/flex_test.go +++ b/internal/service/autoscaling/flex_test.go @@ -8,27 +8,6 @@ import ( "github.com/aws/aws-sdk-go/service/autoscaling" ) -func TestFlattenEnabledMetrics(t *testing.T) { - expanded := []*autoscaling.EnabledMetric{ - {Granularity: aws.String("1Minute"), Metric: aws.String("GroupTotalInstances")}, - {Granularity: aws.String("1Minute"), Metric: aws.String("GroupMaxSize")}, - } - - result := flattenASGEnabledMetrics(expanded) - - if len(result) != 2 { - t.Fatalf("expected result had %d elements, but got %d", 2, len(result)) - } - - if result[0] != "GroupTotalInstances" { - t.Fatalf("expected id to be GroupTotalInstances, but was %s", result[0]) - } - - if result[1] != "GroupMaxSize" { - t.Fatalf("expected id to be GroupMaxSize, but was %s", result[1]) - } -} - func TestExpandStepAdjustments(t *testing.T) { expanded := []interface{}{ map[string]interface{}{ diff --git a/internal/service/autoscaling/generate.go b/internal/service/autoscaling/generate.go index 80cd1713122..85658864007 100644 --- a/internal/service/autoscaling/generate.go +++ b/internal/service/autoscaling/generate.go @@ -1,4 +1,5 @@ //go:generate go run ../../generate/tags/main.go -GetTag -ListTags -ListTagsOp=DescribeTags -ListTagsInFiltIDName=auto-scaling-group -ServiceTagsSlice -TagOp=CreateOrUpdateTags -TagResTypeElem=ResourceType -TagType2=TagDescription -TagTypeAddBoolElem=PropagateAtLaunch -TagTypeIDElem=ResourceId -UntagOp=DeleteTags -UntagInNeedTagType -UntagInTagsElem=Tags -UpdateTags +//go:generate go run ../../generate/listpages/main.go -ListOps=DescribeInstanceRefreshes,DescribeLoadBalancers,DescribeLoadBalancerTargetGroups,DescribeWarmPool // ONLY generate directives and package declaration! Do not add anything else to this file. package autoscaling diff --git a/internal/service/autoscaling/group.go b/internal/service/autoscaling/group.go index 830d6d044e3..7fa89888ec1 100644 --- a/internal/service/autoscaling/group.go +++ b/internal/service/autoscaling/group.go @@ -1,6 +1,6 @@ package autoscaling -import ( // nosemgrep: aws-sdk-go-multiple-service-imports +import ( "bytes" "context" "fmt" @@ -12,8 +12,6 @@ import ( // nosemgrep: aws-sdk-go-multiple-service-imports "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/aws/aws-sdk-go/service/elb" - "github.com/aws/aws-sdk-go/service/elbv2" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/go-cty/cty" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -35,39 +33,173 @@ func ResourceGroup() *schema.Resource { Read: resourceGroupRead, Update: resourceGroupUpdate, Delete: resourceGroupDelete, + Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ + Update: schema.DefaultTimeout(10 * time.Minute), Delete: schema.DefaultTimeout(10 * time.Minute), }, Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - ConflictsWith: []string{"name_prefix"}, - ValidateFunc: validation.StringLenBetween(0, 255), + "arn": { + Type: schema.TypeString, + Computed: true, }, - - "name_prefix": { - Type: schema.TypeString, + "availability_zones": { + Type: schema.TypeSet, Optional: true, Computed: true, - ForceNew: true, - ConflictsWith: []string{"name"}, - ValidateFunc: validation.StringLenBetween(0, 255-resource.UniqueIDSuffixLength), + Elem: &schema.Schema{Type: schema.TypeString}, + ConflictsWith: []string{"vpc_zone_identifier"}, + }, + "capacity_rebalance": { + Type: schema.TypeBool, + Optional: true, + }, + "context": { + Type: schema.TypeString, + Optional: true, + }, + "default_cooldown": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "desired_capacity": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "enabled_metrics": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "force_delete": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "force_delete_warm_pool": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "health_check_grace_period": { + Type: schema.TypeInt, + Optional: true, + Default: 300, + }, + "health_check_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "initial_lifecycle_hook": { + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "default_result": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "heartbeat_timeout": { + Type: schema.TypeInt, + Optional: true, + }, + "lifecycle_transition": { + Type: schema.TypeString, + Required: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + }, + "notification_metadata": { + Type: schema.TypeString, + Optional: true, + }, + "notification_target_arn": { + Type: schema.TypeString, + Optional: true, + }, + "role_arn": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "instance_refresh": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "preferences": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "checkpoint_delay": { + Type: nullable.TypeNullableInt, + Optional: true, + ValidateFunc: nullable.ValidateTypeStringNullableIntAtLeast(0), + }, + "checkpoint_percentages": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "instance_warmup": { + Type: nullable.TypeNullableInt, + Optional: true, + ValidateFunc: nullable.ValidateTypeStringNullableIntAtLeast(0), + }, + "min_healthy_percentage": { + Type: schema.TypeInt, + Optional: true, + Default: 90, + ValidateFunc: validation.IntBetween(0, 100), + }, + "skip_matching": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + }, + }, + }, + "strategy": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(autoscaling.RefreshStrategy_Values(), false), + }, + "triggers": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateDiagFunc: validateGroupInstanceRefreshTriggerFields, + }, + }, + }, + }, }, - "launch_configuration": { Type: schema.TypeString, Optional: true, ExactlyOneOf: []string{"launch_configuration", "launch_template", "mixed_instances_policy"}, }, - "launch_template": { Type: schema.TypeList, MaxItems: 1, @@ -78,15 +210,15 @@ func ResourceGroup() *schema.Resource { Type: schema.TypeString, Optional: true, Computed: true, - ConflictsWith: []string{"launch_template.0.name"}, ValidateFunc: verify.ValidLaunchTemplateID, + ConflictsWith: []string{"launch_template.0.name"}, }, "name": { Type: schema.TypeString, Optional: true, Computed: true, - ConflictsWith: []string{"launch_template.0.id"}, ValidateFunc: verify.ValidLaunchTemplateName, + ConflictsWith: []string{"launch_template.0.id"}, }, "version": { Type: schema.TypeString, @@ -97,7 +229,32 @@ func ResourceGroup() *schema.Resource { }, ExactlyOneOf: []string{"launch_configuration", "launch_template", "mixed_instances_policy"}, }, - + "load_balancers": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "max_instance_lifetime": { + Type: schema.TypeInt, + Optional: true, + }, + "max_size": { + Type: schema.TypeInt, + Required: true, + }, + "metrics_granularity": { + Type: schema.TypeString, + Optional: true, + Default: DefaultEnabledMetricsGranularity, + }, + "min_elb_capacity": { + Type: schema.TypeInt, + Optional: true, + }, + "min_size": { + Type: schema.TypeInt, + Required: true, + }, "mixed_instances_policy": { Type: schema.TypeList, Optional: true, @@ -190,6 +347,250 @@ func ResourceGroup() *schema.Resource { Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "instance_requirements": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "accelerator_count": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "max": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(0), + }, + "min": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + }, + }, + }, + "accelerator_manufacturers": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(autoscaling.AcceleratorManufacturer_Values(), false), + }, + }, + "accelerator_names": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(autoscaling.AcceleratorName_Values(), false), + }, + }, + "accelerator_total_memory_mib": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "max": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + "min": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + }, + }, + }, + "accelerator_types": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(autoscaling.AcceleratorType_Values(), false), + }, + }, + "bare_metal": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice(autoscaling.BareMetal_Values(), false), + }, + "baseline_ebs_bandwidth_mbps": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "max": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + "min": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + }, + }, + }, + "burstable_performance": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice(autoscaling.BurstablePerformance_Values(), false), + }, + "cpu_manufacturers": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(autoscaling.CpuManufacturer_Values(), false), + }, + }, + "excluded_instance_types": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 400, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "instance_generations": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(autoscaling.InstanceGeneration_Values(), false), + }, + }, + "local_storage": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice(autoscaling.LocalStorage_Values(), false), + }, + "local_storage_types": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(autoscaling.LocalStorageType_Values(), false), + }, + }, + "memory_gib_per_vcpu": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "max": { + Type: schema.TypeFloat, + Optional: true, + ValidateFunc: verify.FloatGreaterThan(0.0), + }, + "min": { + Type: schema.TypeFloat, + Optional: true, + ValidateFunc: verify.FloatGreaterThan(0.0), + }, + }, + }, + }, + "memory_mib": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "max": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + "min": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + }, + }, + }, + "network_interface_count": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "max": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + "min": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + }, + }, + }, + "on_demand_max_price_percentage_over_lowest_price": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + "require_hibernate_support": { + Type: schema.TypeBool, + Optional: true, + }, + "spot_max_price_percentage_over_lowest_price": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + "total_local_storage_gb": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "max": { + Type: schema.TypeFloat, + Optional: true, + ValidateFunc: verify.FloatGreaterThan(0.0), + }, + "min": { + Type: schema.TypeFloat, + Optional: true, + ValidateFunc: verify.FloatGreaterThan(0.0), + }, + }, + }, + }, + "vcpu_count": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "max": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + "min": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + }, + }, + }, + }, + }, + }, "instance_type": { Type: schema.TypeString, Optional: true, @@ -234,218 +635,58 @@ func ResourceGroup() *schema.Resource { }, ExactlyOneOf: []string{"launch_configuration", "launch_template", "mixed_instances_policy"}, }, - - "capacity_rebalance": { - Type: schema.TypeBool, - Optional: true, - }, - - "desired_capacity": { - Type: schema.TypeInt, - Optional: true, - Computed: true, + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(0, 255), + ConflictsWith: []string{"name_prefix"}, }, - - "min_elb_capacity": { - Type: schema.TypeInt, - Optional: true, - }, - - "min_size": { - Type: schema.TypeInt, - Required: true, - }, - - "max_size": { - Type: schema.TypeInt, - Required: true, - }, - - "max_instance_lifetime": { - Type: schema.TypeInt, - Optional: true, - }, - - "default_cooldown": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - - "force_delete": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - - "health_check_grace_period": { - Type: schema.TypeInt, - Optional: true, - Default: 300, - }, - - "health_check_type": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "availability_zones": { - Type: schema.TypeSet, + "name_prefix": { + Type: schema.TypeString, Optional: true, Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - ConflictsWith: []string{"vpc_zone_identifier"}, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(0, 255-resource.UniqueIDSuffixLength), + ConflictsWith: []string{"name"}, }, - "placement_group": { Type: schema.TypeString, Optional: true, }, - - "load_balancers": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "vpc_zone_identifier": { - Type: schema.TypeSet, - Optional: true, - Computed: true, - ConflictsWith: []string{"availability_zones"}, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "termination_policies": { - Type: schema.TypeList, + "protect_from_scale_in": { + Type: schema.TypeBool, Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Default: false, }, - - "wait_for_capacity_timeout": { + "service_linked_role_arn": { Type: schema.TypeString, Optional: true, - Default: "10m", - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - duration, err := time.ParseDuration(value) - if err != nil { - errors = append(errors, fmt.Errorf( - "%q cannot be parsed as a duration: %s", k, err)) - } - if duration < 0 { - errors = append(errors, fmt.Errorf( - "%q must be greater than zero", k)) - } - return - }, - }, - - "wait_for_elb_capacity": { - Type: schema.TypeInt, - Optional: true, - }, - - "enabled_metrics": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, + Computed: true, }, - "suspended_processes": { Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "metrics_granularity": { - Type: schema.TypeString, - Optional: true, - Default: "1Minute", - }, - - "protect_from_scale_in": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - - "target_group_arns": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "arn": { - Type: schema.TypeString, - Computed: true, }, - - "initial_lifecycle_hook": { + "tag": { Type: schema.TypeSet, Optional: true, - ForceNew: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - }, - "default_result": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - "heartbeat_timeout": { - Type: schema.TypeInt, - Optional: true, - }, - "lifecycle_transition": { + "key": { Type: schema.TypeString, Required: true, }, - "notification_metadata": { - Type: schema.TypeString, - Optional: true, - }, - "notification_target_arn": { - Type: schema.TypeString, - Optional: true, - }, - "role_arn": { - Type: schema.TypeString, - Optional: true, - }, - }, - }, - }, - - "tag": { - Type: schema.TypeSet, - Optional: true, - ConflictsWith: []string{"tags"}, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, + "propagate_at_launch": { + Type: schema.TypeBool, Required: true, }, - "value": { Type: schema.TypeString, Required: true, }, - - "propagate_at_launch": { - Type: schema.TypeBool, - Required: true, - }, }, }, // This should be removable, but wait until other tags work is being done. @@ -458,17 +699,16 @@ func ResourceGroup() *schema.Resource { return create.StringHashcode(buf.String()) }, + ConflictsWith: []string{"tags"}, }, - "tags": { - Type: schema.TypeSet, - Optional: true, + Deprecated: "Use tag instead", + Type: schema.TypeSet, + Optional: true, Elem: &schema.Schema{ Type: schema.TypeMap, Elem: &schema.Schema{Type: schema.TypeString}, }, - ConflictsWith: []string{"tag"}, - Deprecated: "Use tag instead", // Terraform 0.11 and earlier can provide incorrect type // information during difference handling, in which boolean // values are represented as "0" and "1". This Set function @@ -504,55 +744,48 @@ func ResourceGroup() *schema.Resource { return create.StringHashcode(buf.String()) }, + ConflictsWith: []string{"tag"}, }, - - "service_linked_role_arn": { - Type: schema.TypeString, + "target_group_arns": { + Type: schema.TypeSet, Optional: true, - Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, - - "instance_refresh": { + "termination_policies": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "vpc_zone_identifier": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + ConflictsWith: []string{"availability_zones"}, + }, + "wait_for_capacity_timeout": { + Type: schema.TypeString, + Optional: true, + Default: "10m", + ValidateFunc: verify.ValidDuration, + }, + "wait_for_elb_capacity": { + Type: schema.TypeInt, + Optional: true, + }, + "warm_pool": { Type: schema.TypeList, - MaxItems: 1, Optional: true, + MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "strategy": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(autoscaling.RefreshStrategy_Values(), false), - }, - "preferences": { + "instance_reuse_policy": { Type: schema.TypeList, - MaxItems: 1, Optional: true, + MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "checkpoint_delay": { - Type: nullable.TypeNullableInt, - Optional: true, - ValidateFunc: nullable.ValidateTypeStringNullableIntAtLeast(0), - }, - "checkpoint_percentages": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "instance_warmup": { - Type: nullable.TypeNullableInt, - Optional: true, - ValidateFunc: nullable.ValidateTypeStringNullableIntAtLeast(0), - }, - "min_healthy_percentage": { - Type: schema.TypeInt, - Optional: true, - Default: 90, - ValidateFunc: validation.IntBetween(0, 100), - }, - "skip_matching": { + "reuse_on_scale_in": { Type: schema.TypeBool, Optional: true, Default: false, @@ -560,64 +793,25 @@ func ResourceGroup() *schema.Resource { }, }, }, - "triggers": { - Type: schema.TypeSet, + "max_group_prepared_capacity": { + Type: schema.TypeInt, Optional: true, - Set: schema.HashString, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateDiagFunc: validateGroupInstanceRefreshTriggerFields, - }, + Default: DefaultWarmPoolMaxGroupPreparedCapacity, + }, + "min_size": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + }, + "pool_state": { + Type: schema.TypeString, + Optional: true, + Default: autoscaling.WarmPoolStateStopped, + ValidateFunc: validation.StringInSlice(autoscaling.WarmPoolState_Values(), false), }, }, }, }, - - "warm_pool": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "pool_state": { - Type: schema.TypeString, - Optional: true, - Default: "Stopped", - ValidateFunc: validation.StringInSlice(autoscaling.WarmPoolState_Values(), false), - }, - "min_size": { - Type: schema.TypeInt, - Optional: true, - Default: 0, - }, - "max_group_prepared_capacity": { - Type: schema.TypeInt, - Optional: true, - Default: -1, - }, - "instance_reuse_policy": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "reuse_on_scale_in": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - }, - }, - }, - }, - }, - }, - - "force_delete_warm_pool": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, }, CustomizeDiff: customdiff.Sequence( @@ -631,1726 +825,2476 @@ func ResourceGroup() *schema.Resource { } } -func generatePutLifecycleHookInputs(asgName string, cfgs []interface{}) []autoscaling.PutLifecycleHookInput { - res := make([]autoscaling.PutLifecycleHookInput, 0, len(cfgs)) +func resourceGroupCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).AutoScalingConn + + asgName := create.Name(d.Get("name").(string), d.Get("name_prefix").(string)) + createInput := &autoscaling.CreateAutoScalingGroupInput{ + AutoScalingGroupName: aws.String(asgName), + NewInstancesProtectedFromScaleIn: aws.Bool(d.Get("protect_from_scale_in").(bool)), + } + updateInput := &autoscaling.UpdateAutoScalingGroupInput{ + AutoScalingGroupName: aws.String(asgName), + } + + initialLifecycleHooks := d.Get("initial_lifecycle_hook").(*schema.Set).List() + twoPhases := len(initialLifecycleHooks) > 0 + + maxSize := aws.Int64(int64(d.Get("max_size").(int))) + minSize := aws.Int64(int64(d.Get("min_size").(int))) + + if twoPhases { + createInput.MaxSize = aws.Int64(0) + createInput.MinSize = aws.Int64(0) + + updateInput.MaxSize = maxSize + updateInput.MinSize = minSize - for _, raw := range cfgs { - cfg := raw.(map[string]interface{}) + if v, ok := d.GetOk("desired_capacity"); ok { + updateInput.DesiredCapacity = aws.Int64(int64(v.(int))) + } + } else { + createInput.MaxSize = maxSize + createInput.MinSize = minSize - input := autoscaling.PutLifecycleHookInput{ - AutoScalingGroupName: &asgName, - LifecycleHookName: aws.String(cfg["name"].(string)), + if v, ok := d.GetOk("desired_capacity"); ok { + createInput.DesiredCapacity = aws.Int64(int64(v.(int))) } + } + + if v, ok := d.GetOk("availability_zones"); ok && v.(*schema.Set).Len() > 0 { + createInput.AvailabilityZones = flex.ExpandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("capacity_rebalance"); ok { + createInput.CapacityRebalance = aws.Bool(v.(bool)) + } + + if v, ok := d.GetOk("context"); ok { + createInput.Context = aws.String(v.(string)) + } + + if v, ok := d.GetOk("default_cooldown"); ok { + createInput.DefaultCooldown = aws.Int64(int64(v.(int))) + } + + if v, ok := d.GetOk("health_check_type"); ok { + createInput.HealthCheckType = aws.String(v.(string)) + } + + if v, ok := d.GetOk("health_check_grace_period"); ok { + createInput.HealthCheckGracePeriod = aws.Int64(int64(v.(int))) + } + + if v, ok := d.GetOk("launch_configuration"); ok { + createInput.LaunchConfigurationName = aws.String(v.(string)) + } + + if v, ok := d.GetOk("launch_template"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + createInput.LaunchTemplate = expandLaunchTemplateSpecification(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("load_balancers"); ok && v.(*schema.Set).Len() > 0 { + createInput.LoadBalancerNames = flex.ExpandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("max_instance_lifetime"); ok { + createInput.MaxInstanceLifetime = aws.Int64(int64(v.(int))) + } + + if v, ok := d.GetOk("mixed_instances_policy"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + createInput.MixedInstancesPolicy = expandMixedInstancesPolicy(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("placement_group"); ok { + createInput.PlacementGroup = aws.String(v.(string)) + } + + if v, ok := d.GetOk("service_linked_role_arn"); ok { + createInput.ServiceLinkedRoleARN = aws.String(v.(string)) + } + + if v, ok := d.GetOk("tag"); ok { + createInput.Tags = Tags(KeyValueTags(v, asgName, TagResourceTypeGroup).IgnoreAWS()) + } + + if v, ok := d.GetOk("tags"); ok { + createInput.Tags = Tags(KeyValueTags(v, asgName, TagResourceTypeGroup).IgnoreAWS()) + } + + if v, ok := d.GetOk("target_group_arns"); ok && len(v.(*schema.Set).List()) > 0 { + createInput.TargetGroupARNs = flex.ExpandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("termination_policies"); ok && len(v.([]interface{})) > 0 { + createInput.TerminationPolicies = flex.ExpandStringList(v.([]interface{})) + } + + if v, ok := d.GetOk("vpc_zone_identifier"); ok && v.(*schema.Set).Len() > 0 { + createInput.VPCZoneIdentifier = expandVPCZoneIdentifiers(v.(*schema.Set).List()) + } + + log.Printf("[DEBUG] Creating Auto Scaling Group: %s", createInput) + _, err := tfresource.RetryWhenAWSErrMessageContains(propagationTimeout, + func() (interface{}, error) { + return conn.CreateAutoScalingGroup(createInput) + }, + // ValidationError: You must use a valid fully-formed launch template. Value (tf-acc-test-6643732652421074386) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name + ErrCodeValidationError, "Invalid IAM Instance Profile") + + if err != nil { + return fmt.Errorf("creating Auto Scaling Group (%s): %w", asgName, err) + } + + d.SetId(asgName) + + if twoPhases { + for _, input := range expandPutLifecycleHookInputs(asgName, initialLifecycleHooks) { + _, err := tfresource.RetryWhenAWSErrMessageContains(5*time.Minute, + func() (interface{}, error) { + return conn.PutLifecycleHook(input) + }, + ErrCodeValidationError, "Unable to publish test message to notification target") - if v, ok := cfg["default_result"]; ok && v.(string) != "" { - input.DefaultResult = aws.String(v.(string)) + if err != nil { + return fmt.Errorf("creating Auto Scaling Group (%s) Lifecycle Hook: %w", d.Id(), err) + } } - if v, ok := cfg["heartbeat_timeout"]; ok && v.(int) > 0 { - input.HeartbeatTimeout = aws.Int64(int64(v.(int))) + _, err = conn.UpdateAutoScalingGroup(updateInput) + + if err != nil { + return fmt.Errorf("setting Auto Scaling Group (%s) initial capacity: %w", d.Id(), err) } + } + + if err := waitForASGCapacity(d, meta, CapacitySatisfiedCreate); err != nil { + return err + } - if v, ok := cfg["lifecycle_transition"]; ok && v.(string) != "" { - input.LifecycleTransition = aws.String(v.(string)) + if v, ok := d.GetOk("suspended_processes"); ok && v.(*schema.Set).Len() > 0 { + input := &autoscaling.ScalingProcessQuery{ + AutoScalingGroupName: aws.String(d.Id()), + ScalingProcesses: flex.ExpandStringSet(v.(*schema.Set)), } - if v, ok := cfg["notification_metadata"]; ok && v.(string) != "" { - input.NotificationMetadata = aws.String(v.(string)) + _, err := conn.SuspendProcesses(input) + + if err != nil { + return fmt.Errorf("suspending Auto Scaling Group (%s) scaling processes: %w", d.Id(), err) } + } - if v, ok := cfg["notification_target_arn"]; ok && v.(string) != "" { - input.NotificationTargetARN = aws.String(v.(string)) + if v, ok := d.GetOk("enabled_metrics"); ok && v.(*schema.Set).Len() > 0 { + input := &autoscaling.EnableMetricsCollectionInput{ + AutoScalingGroupName: aws.String(d.Id()), + Granularity: aws.String(d.Get("metrics_granularity").(string)), + Metrics: flex.ExpandStringSet(v.(*schema.Set)), } - if v, ok := cfg["role_arn"]; ok && v.(string) != "" { - input.RoleARN = aws.String(v.(string)) + _, err := conn.EnableMetricsCollection(input) + + if err != nil { + return fmt.Errorf("enabling Auto Scaling Group (%s) metrics collection: %w", d.Id(), err) } + } + + if v, ok := d.GetOk("warm_pool"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + _, err := conn.PutWarmPool(expandPutWarmPoolInput(d.Id(), v.([]interface{})[0].(map[string]interface{}))) - res = append(res, input) + if err != nil { + return fmt.Errorf("creating Auto Scaling Warm Pool (%s): %w", d.Id(), err) + } } - return res + return resourceGroupRead(d, meta) } -func resourceGroupCreate(d *schema.ResourceData, meta interface{}) error { +func resourceGroupRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).AutoScalingConn + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - asgName := create.Name(d.Get("name").(string), d.Get("name_prefix").(string)) + g, err := FindGroupByName(conn, d.Id()) - createOpts := autoscaling.CreateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String(asgName), - MixedInstancesPolicy: expandMixedInstancesPolicy(d.Get("mixed_instances_policy").([]interface{})), - NewInstancesProtectedFromScaleIn: aws.Bool(d.Get("protect_from_scale_in").(bool)), + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Auto Scaling Group %s not found, removing from state", d.Id()) + d.SetId("") + return nil } - updateOpts := autoscaling.UpdateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String(asgName), + + if err != nil { + return fmt.Errorf("reading Auto Scaling Group (%s): %w", d.Id(), err) } - initialLifecycleHooks := d.Get("initial_lifecycle_hook").(*schema.Set).List() - twoPhases := len(initialLifecycleHooks) > 0 + d.Set("arn", g.AutoScalingGroupARN) + d.Set("availability_zones", aws.StringValueSlice(g.AvailabilityZones)) + d.Set("capacity_rebalance", g.CapacityRebalance) + d.Set("context", g.Context) + d.Set("default_cooldown", g.DefaultCooldown) + d.Set("desired_capacity", g.DesiredCapacity) + if len(g.EnabledMetrics) > 0 { + d.Set("enabled_metrics", flattenEnabledMetrics(g.EnabledMetrics)) + d.Set("metrics_granularity", g.EnabledMetrics[0].Granularity) + } else { + d.Set("enabled_metrics", nil) + d.Set("metrics_granularity", DefaultEnabledMetricsGranularity) + } + d.Set("health_check_grace_period", g.HealthCheckGracePeriod) + d.Set("health_check_type", g.HealthCheckType) + d.Set("load_balancers", aws.StringValueSlice(g.LoadBalancerNames)) + d.Set("launch_configuration", g.LaunchConfigurationName) + if g.LaunchTemplate != nil { + if err := d.Set("launch_template", []interface{}{flattenLaunchTemplateSpecification(g.LaunchTemplate)}); err != nil { + return fmt.Errorf("setting launch_template: %w", err) + } + } else { + d.Set("launch_template", nil) + } + d.Set("max_instance_lifetime", g.MaxInstanceLifetime) + d.Set("max_size", g.MaxSize) + d.Set("min_size", g.MinSize) + if g.MixedInstancesPolicy != nil { + if err := d.Set("mixed_instances_policy", []interface{}{flattenMixedInstancesPolicy(g.MixedInstancesPolicy)}); err != nil { + return fmt.Errorf("setting mixed_instances_policy: %w", err) + } + } else { + d.Set("mixed_instances_policy", nil) + } + d.Set("name", g.AutoScalingGroupName) + d.Set("name_prefix", create.NamePrefixFromName(aws.StringValue(g.AutoScalingGroupName))) + d.Set("placement_group", g.PlacementGroup) + d.Set("protect_from_scale_in", g.NewInstancesProtectedFromScaleIn) + d.Set("service_linked_role_arn", g.ServiceLinkedRoleARN) + d.Set("suspended_processes", flattenSuspendedProcesses(g.SuspendedProcesses)) + d.Set("target_group_arns", aws.StringValueSlice(g.TargetGroupARNs)) + // If no termination polices are explicitly configured and the upstream state + // is only using the "Default" policy, clear the state to make it consistent + // with the default AWS Create API behavior. + if _, ok := d.GetOk("termination_policies"); !ok && len(g.TerminationPolicies) == 1 && aws.StringValue(g.TerminationPolicies[0]) == DefaultTerminationPolicy { + d.Set("termination_policies", nil) + } else { + d.Set("termination_policies", aws.StringValueSlice(g.TerminationPolicies)) + } + if len(aws.StringValue(g.VPCZoneIdentifier)) > 0 { + d.Set("vpc_zone_identifier", strings.Split(aws.StringValue(g.VPCZoneIdentifier), ",")) + } else { + d.Set("vpc_zone_identifier", nil) + } + if g.WarmPoolConfiguration != nil { + if err := d.Set("warm_pool", []interface{}{flattenWarmPoolConfiguration(g.WarmPoolConfiguration)}); err != nil { + return fmt.Errorf("setting warm_pool: %w", err) + } + } else { + d.Set("warm_pool", nil) + } + + var tagOk, tagsOk bool + var v interface{} + + // Deprecated: In a future major version, this should always set all tags except those ignored. + // Remove d.GetOk() and Only() handling. + if v, tagOk = d.GetOk("tag"); tagOk { + proposedStateTags := KeyValueTags(v, d.Id(), TagResourceTypeGroup) + + if err := d.Set("tag", ListOfMap(KeyValueTags(g.Tags, d.Id(), TagResourceTypeGroup).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Only(proposedStateTags))); err != nil { + return fmt.Errorf("setting tag: %w", err) + } + } + + if v, tagsOk = d.GetOk("tags"); tagsOk { + proposedStateTags := KeyValueTags(v, d.Id(), TagResourceTypeGroup) + + if err := d.Set("tags", ListOfStringMap(KeyValueTags(g.Tags, d.Id(), TagResourceTypeGroup).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Only(proposedStateTags))); err != nil { + return fmt.Errorf("setting tags: %w", err) + } + } + + if !tagOk && !tagsOk { + if err := d.Set("tag", ListOfMap(KeyValueTags(g.Tags, d.Id(), TagResourceTypeGroup).IgnoreAWS().IgnoreConfig(ignoreTagsConfig))); err != nil { + return fmt.Errorf("setting tag: %w", err) + } + } + + return nil +} + +func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).AutoScalingConn + + var shouldWaitForCapacity bool + var shouldRefreshInstances bool + + if d.HasChangesExcept( + "enabled_metrics", + "load_balancers", + "suspended_processes", + "tag", + "tags", + "target_group_arns", + "warm_pool", + ) { + input := &autoscaling.UpdateAutoScalingGroupInput{ + AutoScalingGroupName: aws.String(d.Id()), + NewInstancesProtectedFromScaleIn: aws.Bool(d.Get("protect_from_scale_in").(bool)), + } + + if d.HasChange("availability_zones") { + if v, ok := d.GetOk("availability_zones"); ok && v.(*schema.Set).Len() > 0 { + input.AvailabilityZones = flex.ExpandStringSet(v.(*schema.Set)) + } + } + + if d.HasChange("capacity_rebalance") { + // If the capacity rebalance field is set to null, we need to explicitly set + // it back to "false", or the API won't reset it for us. + if v, ok := d.GetOk("capacity_rebalance"); ok { + input.CapacityRebalance = aws.Bool(v.(bool)) + } else { + input.CapacityRebalance = aws.Bool(false) + } + } + + if d.HasChange("context") { + input.Context = aws.String(d.Get("context").(string)) + } + + if d.HasChange("default_cooldown") { + input.DefaultCooldown = aws.Int64(int64(d.Get("default_cooldown").(int))) + } + + if d.HasChange("desired_capacity") { + input.DesiredCapacity = aws.Int64(int64(d.Get("desired_capacity").(int))) + shouldWaitForCapacity = true + } + + if d.HasChange("health_check_grace_period") { + input.HealthCheckGracePeriod = aws.Int64(int64(d.Get("health_check_grace_period").(int))) + } + + if d.HasChange("health_check_type") { + input.HealthCheckGracePeriod = aws.Int64(int64(d.Get("health_check_grace_period").(int))) + input.HealthCheckType = aws.String(d.Get("health_check_type").(string)) + } + + if d.HasChange("launch_configuration") { + if v, ok := d.GetOk("launch_configuration"); ok { + input.LaunchConfigurationName = aws.String(v.(string)) + } + shouldRefreshInstances = true + } + + if d.HasChange("launch_template") { + if v, ok := d.GetOk("launch_template"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.LaunchTemplate = expandLaunchTemplateSpecification(v.([]interface{})[0].(map[string]interface{})) + } + shouldRefreshInstances = true + } + + if d.HasChange("max_instance_lifetime") { + input.MaxInstanceLifetime = aws.Int64(int64(d.Get("max_instance_lifetime").(int))) + } + + if d.HasChange("max_size") { + input.MaxSize = aws.Int64(int64(d.Get("max_size").(int))) + } + + if d.HasChange("min_size") { + input.MinSize = aws.Int64(int64(d.Get("min_size").(int))) + shouldWaitForCapacity = true + } + + if d.HasChange("mixed_instances_policy") { + if v, ok := d.GetOk("mixed_instances_policy"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.MixedInstancesPolicy = expandMixedInstancesPolicy(v.([]interface{})[0].(map[string]interface{})) + } + shouldRefreshInstances = true + } + + if d.HasChange("placement_group") { + input.PlacementGroup = aws.String(d.Get("placement_group").(string)) + } + + if d.HasChange("service_linked_role_arn") { + input.ServiceLinkedRoleARN = aws.String(d.Get("service_linked_role_arn").(string)) + } + + if d.HasChange("termination_policies") { + // If the termination policy is set to null, we need to explicitly set + // it back to "Default", or the API won't reset it for us. + if v, ok := d.GetOk("termination_policies"); ok && len(v.([]interface{})) > 0 { + input.TerminationPolicies = flex.ExpandStringList(v.([]interface{})) + } else { + input.TerminationPolicies = aws.StringSlice([]string{DefaultTerminationPolicy}) + } + } + + if d.HasChange("vpc_zone_identifier") { + input.VPCZoneIdentifier = expandVPCZoneIdentifiers(d.Get("vpc_zone_identifier").(*schema.Set).List()) + } + + log.Printf("[DEBUG] Updating Auto Scaling Group: %s", input) + _, err := conn.UpdateAutoScalingGroup(input) + + if err != nil { + return fmt.Errorf("updating Auto Scaling Group (%s): %w", d.Id(), err) + } + } + + if d.HasChanges("tag", "tags") { + oTagRaw, nTagRaw := d.GetChange("tag") + oTagsRaw, nTagsRaw := d.GetChange("tags") + + oTag := KeyValueTags(oTagRaw, d.Id(), TagResourceTypeGroup) + oTags := KeyValueTags(oTagsRaw, d.Id(), TagResourceTypeGroup) + oldTags := Tags(oTag.Merge(oTags)) + + nTag := KeyValueTags(nTagRaw, d.Id(), TagResourceTypeGroup) + nTags := KeyValueTags(nTagsRaw, d.Id(), TagResourceTypeGroup) + newTags := Tags(nTag.Merge(nTags)) + + if err := UpdateTags(conn, d.Id(), TagResourceTypeGroup, oldTags, newTags); err != nil { + return fmt.Errorf("updating tags for Auto Scaling Group (%s): %w", d.Id(), err) + } + } + + if d.HasChange("load_balancers") { + o, n := d.GetChange("load_balancers") + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } + os := o.(*schema.Set) + ns := n.(*schema.Set) + + if remove := flex.ExpandStringSet(os.Difference(ns)); len(remove) > 0 { + // API only supports removing 10 at a time. + batchSize := 10 + + var batches [][]*string + + for batchSize < len(remove) { + remove, batches = remove[batchSize:], append(batches, remove[0:batchSize:batchSize]) + } + batches = append(batches, remove) + + for _, batch := range batches { + _, err := conn.DetachLoadBalancers(&autoscaling.DetachLoadBalancersInput{ + AutoScalingGroupName: aws.String(d.Id()), + LoadBalancerNames: batch, + }) + + if err != nil { + return fmt.Errorf("detaching Auto Scaling Group (%s) load balancers: %w", d.Id(), err) + } + + if _, err := waitLoadBalancersRemoved(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for Auto Scaling Group (%s) load balancers removed: %s", d.Id(), err) + } + } + } + + if add := flex.ExpandStringSet(ns.Difference(os)); len(add) > 0 { + // API only supports adding 10 at a time. + batchSize := 10 + + var batches [][]*string + + for batchSize < len(add) { + add, batches = add[batchSize:], append(batches, add[0:batchSize:batchSize]) + } + batches = append(batches, add) + + for _, batch := range batches { + _, err := conn.AttachLoadBalancers(&autoscaling.AttachLoadBalancersInput{ + AutoScalingGroupName: aws.String(d.Id()), + LoadBalancerNames: batch, + }) + + if err != nil { + return fmt.Errorf("attaching Auto Scaling Group (%s) load balancers: %w", d.Id(), err) + } + + if _, err := waitLoadBalancersAdded(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for Auto Scaling Group (%s) load balancers added: %s", d.Id(), err) + } + } + } + } + + if d.HasChange("target_group_arns") { + o, n := d.GetChange("target_group_arns") + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } + os := o.(*schema.Set) + ns := n.(*schema.Set) + + if remove := flex.ExpandStringSet(os.Difference(ns)); len(remove) > 0 { + // AWS API only supports adding/removing 10 at a time. + batchSize := 10 + + var batches [][]*string + + for batchSize < len(remove) { + remove, batches = remove[batchSize:], append(batches, remove[0:batchSize:batchSize]) + } + batches = append(batches, remove) + + for _, batch := range batches { + _, err := conn.DetachLoadBalancerTargetGroups(&autoscaling.DetachLoadBalancerTargetGroupsInput{ + AutoScalingGroupName: aws.String(d.Id()), + TargetGroupARNs: batch, + }) + + if err != nil { + return fmt.Errorf("detaching Auto Scaling Group (%s) target groups: %w", d.Id(), err) + } + + if _, err := waitLoadBalancerTargetGroupsRemoved(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for Auto Scaling Group (%s) target groups removed: %s", d.Id(), err) + } + } + + } + + if add := flex.ExpandStringSet(ns.Difference(os)); len(add) > 0 { + // AWS API only supports adding/removing 10 at a time. + batchSize := 10 + + var batches [][]*string + + for batchSize < len(add) { + add, batches = add[batchSize:], append(batches, add[0:batchSize:batchSize]) + } + batches = append(batches, add) + + for _, batch := range batches { + _, err := conn.AttachLoadBalancerTargetGroups(&autoscaling.AttachLoadBalancerTargetGroupsInput{ + AutoScalingGroupName: aws.String(d.Id()), + TargetGroupARNs: batch, + }) + + if err != nil { + return fmt.Errorf("attaching Auto Scaling Group (%s) target groups: %w", d.Id(), err) + } + + if _, err := waitLoadBalancerTargetGroupsAdded(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for Auto Scaling Group (%s) target groups added: %s", d.Id(), err) + } + } + } + } + + if v, ok := d.GetOk("instance_refresh"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + tfMap := v.([]interface{})[0].(map[string]interface{}) + + if !shouldRefreshInstances { + if v, ok := tfMap["triggers"].(*schema.Set); ok && v.Len() > 0 { + var triggers []string + + for _, v := range v.List() { + if v := v.(string); v != "" { + triggers = append(triggers, v) + } + } + + if v.Contains("tag") && !v.Contains("tags") { + triggers = append(triggers, "tags") // nozero + } else if !v.Contains("tag") && v.Contains("tags") { + triggers = append(triggers, "tag") // nozero + } + + shouldRefreshInstances = d.HasChanges(triggers...) + } + } + + if shouldRefreshInstances { + if err := startInstanceRefresh(conn, expandStartInstanceRefreshInput(d.Id(), tfMap)); err != nil { + return err + } + } + } + + if d.HasChange("warm_pool") { + w := d.Get("warm_pool").([]interface{}) + + // No warm pool exists in new config. Delete it. + if len(w) == 0 || w[0] == nil { + forceDeleteWarmPool := d.Get("force_delete").(bool) || d.Get("force_delete_warm_pool").(bool) + + if err := deleteWarmPool(conn, d.Id(), forceDeleteWarmPool, d.Timeout(schema.TimeoutUpdate)); err != nil { + return err + } + } else { + _, err := conn.PutWarmPool(expandPutWarmPoolInput(d.Id(), w[0].(map[string]interface{}))) + + if err != nil { + return fmt.Errorf("updating Auto Scaling Warm Pool (%s): %w", d.Id(), err) + } + } + } + + if shouldWaitForCapacity { + if err := waitForASGCapacity(d, meta, CapacitySatisfiedUpdate); err != nil { + return fmt.Errorf("error waiting for Auto Scaling Group Capacity: %w", err) + } + } + + if d.HasChange("enabled_metrics") { + o, n := d.GetChange("enabled_metrics") + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } + os := o.(*schema.Set) + ns := n.(*schema.Set) + + if disableMetrics := os.Difference(ns); disableMetrics.Len() != 0 { + input := &autoscaling.DisableMetricsCollectionInput{ + AutoScalingGroupName: aws.String(d.Id()), + Metrics: flex.ExpandStringSet(disableMetrics), + } + + _, err := conn.DisableMetricsCollection(input) + + if err != nil { + return fmt.Errorf("disabling Auto Scaling Group (%s) metrics collection: %w", d.Id(), err) + } + } + + if enableMetrics := ns.Difference(os); enableMetrics.Len() != 0 { + input := &autoscaling.EnableMetricsCollectionInput{ + AutoScalingGroupName: aws.String(d.Id()), + Granularity: aws.String(d.Get("metrics_granularity").(string)), + Metrics: flex.ExpandStringSet(enableMetrics), + } + + _, err := conn.EnableMetricsCollection(input) + + if err != nil { + return fmt.Errorf("enabling Auto Scaling Group (%s) metrics collection: %w", d.Id(), err) + } + } + } + + if d.HasChange("suspended_processes") { + o, n := d.GetChange("suspended_processes") + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } + os := o.(*schema.Set) + ns := n.(*schema.Set) + + if resumeProcesses := os.Difference(ns); resumeProcesses.Len() != 0 { + input := &autoscaling.ScalingProcessQuery{ + AutoScalingGroupName: aws.String(d.Id()), + ScalingProcesses: flex.ExpandStringSet(resumeProcesses), + } + + _, err := conn.ResumeProcesses(input) + + if err != nil { + return fmt.Errorf("resuming Auto Scaling Group (%s) scaling processes: %w", d.Id(), err) + } + } + + if suspendProcesses := ns.Difference(os); suspendProcesses.Len() != 0 { + input := &autoscaling.ScalingProcessQuery{ + AutoScalingGroupName: aws.String(d.Id()), + ScalingProcesses: flex.ExpandStringSet(suspendProcesses), + } + + _, err := conn.SuspendProcesses(input) + + if err != nil { + return fmt.Errorf("suspending Auto Scaling Group (%s) scaling processes: %w", d.Id(), err) + } + } + } + + return resourceGroupRead(d, meta) +} + +func resourceGroupDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).AutoScalingConn + + forceDeleteGroup := d.Get("force_delete").(bool) + forceDeleteWarmPool := forceDeleteGroup || d.Get("force_delete_warm_pool").(bool) + + group, err := FindGroupByName(conn, d.Id()) + + if tfresource.NotFound(err) { + return nil + } + + if err != nil { + return fmt.Errorf("reading Auto Scaling Group (%s): %w", d.Id(), err) + } + + if group.WarmPoolConfiguration != nil { + err = deleteWarmPool(conn, d.Id(), forceDeleteWarmPool, d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + } + + if !forceDeleteGroup { + err = drainGroup(conn, d.Id(), group.Instances, d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + } + + log.Printf("[DEBUG] Deleting Auto Scaling Group: %s", d.Id()) + _, err = tfresource.RetryWhenAWSErrCodeEquals(d.Timeout(schema.TimeoutDelete), + func() (interface{}, error) { + return conn.DeleteAutoScalingGroup(&autoscaling.DeleteAutoScalingGroupInput{ + AutoScalingGroupName: aws.String(d.Id()), + ForceDelete: aws.Bool(forceDeleteGroup), + }) + }, + autoscaling.ErrCodeResourceInUseFault, autoscaling.ErrCodeScalingActivityInProgressFault) + + if tfawserr.ErrMessageContains(err, ErrCodeValidationError, "not found") { + return nil + } + + if err != nil { + return fmt.Errorf("deleting Auto Scaling Group (%s): %w", d.Id(), err) + } + + _, err = tfresource.RetryUntilNotFound(d.Timeout(schema.TimeoutDelete), + func() (interface{}, error) { + return FindGroupByName(conn, d.Id()) + }) + + if err != nil { + return fmt.Errorf("waiting for Auto Scaling Group (%s) delete: %w", d.Id(), err) + } + + return nil +} + +func drainGroup(conn *autoscaling.AutoScaling, name string, instances []*autoscaling.Instance, timeout time.Duration) error { + input := &autoscaling.UpdateAutoScalingGroupInput{ + AutoScalingGroupName: aws.String(name), + DesiredCapacity: aws.Int64(0), + MinSize: aws.Int64(0), + MaxSize: aws.Int64(0), + } + + log.Printf("[DEBUG] Draining Auto Scaling Group: %s", name) + if _, err := conn.UpdateAutoScalingGroup(input); err != nil { + return fmt.Errorf("setting Auto Scaling Group (%s) capacity to 0: %w", name, err) + } + + // Next, ensure that instances are not prevented from scaling in. + // + // The ASG's own scale-in protection setting doesn't make a difference here, + // as it only affects new instances, which won't be launched now that the + // desired capacity is set to 0. There is also the possibility that this ASG + // no longer applies scale-in protection to new instances, but there's still + // old ones that have it. + + const chunkSize = 50 // API limit. + for i, n := 0, len(instances); i < n; i += chunkSize { + j := i + chunkSize + if j > n { + j = n + } + + var instanceIDs []string + + for k := i; k < j; k++ { + instanceIDs = append(instanceIDs, aws.StringValue(instances[k].InstanceId)) + } + + input := &autoscaling.SetInstanceProtectionInput{ + AutoScalingGroupName: aws.String(name), + InstanceIds: aws.StringSlice(instanceIDs), + ProtectedFromScaleIn: aws.Bool(false), + } + + if _, err := conn.SetInstanceProtection(input); err != nil { + return fmt.Errorf("disabling Auto Scaling Group (%s) scale-in protections: %w", name, err) + } + } + + if _, err := waitGroupDrained(conn, name, timeout); err != nil { + return fmt.Errorf("waiting for Auto Scaling Group (%s) drain: %w", name, err) + } + + return nil +} + +func deleteWarmPool(conn *autoscaling.AutoScaling, name string, force bool, timeout time.Duration) error { + if !force { + if err := drainWarmPool(conn, name, timeout); err != nil { + return err + } + } + + log.Printf("[DEBUG] Deleting Auto Scaling Warm Pool: %s", name) + _, err := tfresource.RetryWhenAWSErrCodeEquals(timeout, + func() (interface{}, error) { + return conn.DeleteWarmPool(&autoscaling.DeleteWarmPoolInput{ + AutoScalingGroupName: aws.String(name), + ForceDelete: aws.Bool(force), + }) + }, + autoscaling.ErrCodeResourceInUseFault, autoscaling.ErrCodeScalingActivityInProgressFault) + + if tfawserr.ErrMessageContains(err, ErrCodeValidationError, "No warm pool found") { + return nil + } + + if err != nil { + return fmt.Errorf("deleting Auto Scaling Warm Pool (%s): %w", name, err) + } + + if _, err := waitWarmPoolDeleted(conn, name, timeout); err != nil { + return fmt.Errorf("waiting for Auto Scaling Warm Pool (%s) delete: %w", name, err) + } + + return nil +} + +func drainWarmPool(conn *autoscaling.AutoScaling, name string, timeout time.Duration) error { + input := &autoscaling.PutWarmPoolInput{ + AutoScalingGroupName: aws.String(name), + MaxGroupPreparedCapacity: aws.Int64(0), + MinSize: aws.Int64(0), + } + + log.Printf("[DEBUG] Draining Auto Scaling Warm Pool: %s", name) + if _, err := conn.PutWarmPool(input); err != nil { + return fmt.Errorf("setting Auto Scaling Warm Pool (%s) capacity to 0: %w", name, err) + } + + if _, err := waitWarmPoolDrained(conn, name, timeout); err != nil { + return fmt.Errorf("waiting for Auto Scaling Warm Pool (%s) drain: %w", name, err) + } + + return nil +} + +func findGroup(conn *autoscaling.AutoScaling, input *autoscaling.DescribeAutoScalingGroupsInput) (*autoscaling.Group, error) { + output, err := findGroups(conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 || output[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output[0], nil +} + +func findGroups(conn *autoscaling.AutoScaling, input *autoscaling.DescribeAutoScalingGroupsInput) ([]*autoscaling.Group, error) { + var output []*autoscaling.Group + + err := conn.DescribeAutoScalingGroupsPages(input, func(page *autoscaling.DescribeAutoScalingGroupsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.AutoScalingGroups { + if v == nil { + continue + } + + output = append(output, v) + } + + return !lastPage + }) + + if err != nil { + return nil, err + } + + return output, nil +} + +func FindGroupByName(conn *autoscaling.AutoScaling, name string) (*autoscaling.Group, error) { + input := &autoscaling.DescribeAutoScalingGroupsInput{ + AutoScalingGroupNames: aws.StringSlice([]string{name}), + } + + output, err := findGroup(conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.StringValue(output.AutoScalingGroupName) != name { + return nil, &resource.NotFoundError{ + LastRequest: input, + } + } - minSize := aws.Int64(int64(d.Get("min_size").(int))) - maxSize := aws.Int64(int64(d.Get("max_size").(int))) + return output, nil +} - if twoPhases { - createOpts.MinSize = aws.Int64(0) - createOpts.MaxSize = aws.Int64(0) +func findLoadBalancerStates(conn *autoscaling.AutoScaling, name string) ([]*autoscaling.LoadBalancerState, error) { + input := &autoscaling.DescribeLoadBalancersInput{ + AutoScalingGroupName: aws.String(name), + } + var output []*autoscaling.LoadBalancerState - updateOpts.MinSize = minSize - updateOpts.MaxSize = maxSize + err := describeLoadBalancersPages(conn, input, func(page *autoscaling.DescribeLoadBalancersOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } - if v, ok := d.GetOk("desired_capacity"); ok { - updateOpts.DesiredCapacity = aws.Int64(int64(v.(int))) + for _, v := range page.LoadBalancers { + if v == nil { + continue + } + + output = append(output, v) } - } else { - createOpts.MinSize = minSize - createOpts.MaxSize = maxSize - if v, ok := d.GetOk("desired_capacity"); ok { - createOpts.DesiredCapacity = aws.Int64(int64(v.(int))) + return !lastPage + }) + + if tfawserr.ErrMessageContains(err, ErrCodeValidationError, "not found") { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, } } - if v, ok := d.GetOk("launch_configuration"); ok { - createOpts.LaunchConfigurationName = aws.String(v.(string)) + if err != nil { + return nil, err } - if v, ok := d.GetOk("launch_template"); ok { - createOpts.LaunchTemplate = expandLaunchTemplateSpecification(v.([]interface{})) - } + return output, nil +} - // Availability Zones are optional if VPC Zone Identifier(s) are specified - if v, ok := d.GetOk("availability_zones"); ok && v.(*schema.Set).Len() > 0 { - createOpts.AvailabilityZones = flex.ExpandStringSet(v.(*schema.Set)) +func findLoadBalancerTargetGroupStates(conn *autoscaling.AutoScaling, name string) ([]*autoscaling.LoadBalancerTargetGroupState, error) { + input := &autoscaling.DescribeLoadBalancerTargetGroupsInput{ + AutoScalingGroupName: aws.String(name), } + var output []*autoscaling.LoadBalancerTargetGroupState - if v, ok := d.GetOk("tag"); ok { - createOpts.Tags = Tags(KeyValueTags(v, asgName, TagResourceTypeGroup).IgnoreAWS()) - } + err := describeLoadBalancerTargetGroupsPages(conn, input, func(page *autoscaling.DescribeLoadBalancerTargetGroupsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } - if v, ok := d.GetOk("tags"); ok { - createOpts.Tags = Tags(KeyValueTags(v, asgName, TagResourceTypeGroup).IgnoreAWS()) - } + for _, v := range page.LoadBalancerTargetGroups { + if v == nil { + continue + } - if v, ok := d.GetOk("capacity_rebalance"); ok { - createOpts.CapacityRebalance = aws.Bool(v.(bool)) - } + output = append(output, v) + } - if v, ok := d.GetOk("default_cooldown"); ok { - createOpts.DefaultCooldown = aws.Int64(int64(v.(int))) - } + return !lastPage + }) - if v, ok := d.GetOk("health_check_type"); ok { - createOpts.HealthCheckType = aws.String(v.(string)) + if tfawserr.ErrMessageContains(err, ErrCodeValidationError, "not found") { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } } - if v, ok := d.GetOk("health_check_grace_period"); ok { - createOpts.HealthCheckGracePeriod = aws.Int64(int64(v.(int))) + if err != nil { + return nil, err } - if v, ok := d.GetOk("placement_group"); ok { - createOpts.PlacementGroup = aws.String(v.(string)) + return output, nil +} + +func findWarmPool(conn *autoscaling.AutoScaling, name string) (*autoscaling.DescribeWarmPoolOutput, error) { + input := &autoscaling.DescribeWarmPoolInput{ + AutoScalingGroupName: aws.String(name), } + var output *autoscaling.DescribeWarmPoolOutput - if v, ok := d.GetOk("load_balancers"); ok && v.(*schema.Set).Len() > 0 { - createOpts.LoadBalancerNames = flex.ExpandStringSet(v.(*schema.Set)) + err := describeWarmPoolPages(conn, input, func(page *autoscaling.DescribeWarmPoolOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + if output == nil { + output = page + } else { + output.Instances = append(output.Instances, page.Instances...) + } + + return !lastPage + }) + + if tfawserr.ErrMessageContains(err, ErrCodeValidationError, "not found") { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } } - if v, ok := d.GetOk("vpc_zone_identifier"); ok && v.(*schema.Set).Len() > 0 { - createOpts.VPCZoneIdentifier = expandVpcZoneIdentifiers(v.(*schema.Set).List()) + if err != nil { + return nil, err } - if v, ok := d.GetOk("termination_policies"); ok && len(v.([]interface{})) > 0 { - createOpts.TerminationPolicies = flex.ExpandStringList(v.([]interface{})) + if output == nil || output.WarmPoolConfiguration == nil { + return nil, tfresource.NewEmptyResultError(name) } - if v, ok := d.GetOk("target_group_arns"); ok && len(v.(*schema.Set).List()) > 0 { - createOpts.TargetGroupARNs = flex.ExpandStringSet(v.(*schema.Set)) + return output, nil +} + +func findInstanceRefresh(conn *autoscaling.AutoScaling, input *autoscaling.DescribeInstanceRefreshesInput) (*autoscaling.InstanceRefresh, error) { + output, err := FindInstanceRefreshes(conn, input) + + if err != nil { + return nil, err } - if v, ok := d.GetOk("service_linked_role_arn"); ok { - createOpts.ServiceLinkedRoleARN = aws.String(v.(string)) + if len(output) == 0 || output[0] == nil { + return nil, tfresource.NewEmptyResultError(input) } - if v, ok := d.GetOk("max_instance_lifetime"); ok { - createOpts.MaxInstanceLifetime = aws.Int64(int64(v.(int))) + if count := len(output); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) } - log.Printf("[DEBUG] Auto Scaling Group create configuration: %#v", createOpts) + return output[0], nil +} - // Retry for IAM eventual consistency - err := resource.Retry(propagationTimeout, func() *resource.RetryError { - _, err := conn.CreateAutoScalingGroup(&createOpts) +func FindInstanceRefreshes(conn *autoscaling.AutoScaling, input *autoscaling.DescribeInstanceRefreshesInput) ([]*autoscaling.InstanceRefresh, error) { + var output []*autoscaling.InstanceRefresh - // ValidationError: You must use a valid fully-formed launch template. Value (tf-acc-test-6643732652421074386) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name - if tfawserr.ErrMessageContains(err, "ValidationError", "Invalid IAM Instance Profile") { - return resource.RetryableError(err) + err := describeInstanceRefreshesPages(conn, input, func(page *autoscaling.DescribeInstanceRefreshesOutput, lastPage bool) bool { + if page == nil { + return !lastPage } - if err != nil { - return resource.NonRetryableError(err) + for _, v := range page.InstanceRefreshes { + if v == nil { + continue + } + + output = append(output, v) } - return nil + return !lastPage }) - if tfresource.TimedOut(err) { - _, err = conn.CreateAutoScalingGroup(&createOpts) + + if tfawserr.ErrMessageContains(err, ErrCodeValidationError, "not found") { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } } + if err != nil { - return fmt.Errorf("Error creating Auto Scaling Group: %s", err) + return nil, err } - d.SetId(asgName) - log.Printf("[INFO] Auto Scaling Group ID: %s", d.Id()) + return output, nil +} - if twoPhases { - for _, hook := range generatePutLifecycleHookInputs(asgName, initialLifecycleHooks) { - _, err := tfresource.RetryWhenAWSErrMessageContains(5*time.Minute, - func() (interface{}, error) { - return conn.PutLifecycleHook(&hook) - }, - ErrCodeValidationError, "Unable to publish test message to notification target") +func statusGroupInstanceCount(conn *autoscaling.AutoScaling, name string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindGroupByName(conn, name) - if err != nil { - return fmt.Errorf("creating Auto Scaling Group (%s) Lifecycle Hook: %w", d.Id(), err) - } + if tfresource.NotFound(err) { + return nil, "", nil } - _, err = conn.UpdateAutoScalingGroup(&updateOpts) if err != nil { - return fmt.Errorf("Error setting Auto Scaling Group initial capacity: %s", err) + return nil, "", err } - } - if err := waitForASGCapacity(d, meta, CapacitySatisfiedCreate); err != nil { - return err + return output, strconv.Itoa(len(output.Instances)), nil } +} - if _, ok := d.GetOk("suspended_processes"); ok { - suspendedProcessesErr := enableASGSuspendedProcesses(d, conn) - if suspendedProcessesErr != nil { - return suspendedProcessesErr +func statusInstanceRefresh(conn *autoscaling.AutoScaling, name, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + input := &autoscaling.DescribeInstanceRefreshesInput{ + AutoScalingGroupName: aws.String(name), + InstanceRefreshIds: aws.StringSlice([]string{id}), } - } - if _, ok := d.GetOk("enabled_metrics"); ok { - metricsErr := enableASGMetricsCollection(d, conn) - if metricsErr != nil { - return metricsErr - } - } + output, err := findInstanceRefresh(conn, input) - if _, ok := d.GetOk("warm_pool"); ok { - _, err := conn.PutWarmPool(CreatePutWarmPoolInput(d.Id(), d.Get("warm_pool").([]interface{}))) + if tfresource.NotFound(err) { + return nil, "", nil + } if err != nil { - return fmt.Errorf("error creating Warm Pool for Auto Scaling Group (%s), error: %s", d.Id(), err) + return nil, "", err } - log.Printf("[INFO] Successfully created Warm pool") - + return output, aws.StringValue(output.Status), nil } - - return resourceGroupRead(d, meta) } -// TODO: wrap all top-level error returns -func resourceGroupRead(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*conns.AWSClient).AutoScalingConn - ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig +func statusLoadBalancerInStateCount(conn *autoscaling.AutoScaling, name string, states ...string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findLoadBalancerStates(conn, name) - g, err := getGroup(d.Id(), conn) - if err != nil { - return err - } - if g == nil && !d.IsNewResource() { - log.Printf("[WARN] Auto Scaling Group (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } + if tfresource.NotFound(err) { + return nil, "", nil + } - if err := d.Set("availability_zones", flex.FlattenStringList(g.AvailabilityZones)); err != nil { - return fmt.Errorf("error setting availability_zones: %s", err) - } + if err != nil { + return nil, "", err + } - d.Set("arn", g.AutoScalingGroupARN) - d.Set("capacity_rebalance", g.CapacityRebalance) - d.Set("default_cooldown", g.DefaultCooldown) - d.Set("desired_capacity", g.DesiredCapacity) + var count int - d.Set("enabled_metrics", nil) - d.Set("metrics_granularity", "1Minute") - if g.EnabledMetrics != nil { - if err := d.Set("enabled_metrics", flattenASGEnabledMetrics(g.EnabledMetrics)); err != nil { - return fmt.Errorf("error setting enabled_metrics: %s", err) + for _, v := range output { + for _, state := range states { + if aws.StringValue(v.State) == state { + count++ + break + } + } } - d.Set("metrics_granularity", g.EnabledMetrics[0].Granularity) - } - - d.Set("health_check_grace_period", g.HealthCheckGracePeriod) - d.Set("health_check_type", g.HealthCheckType) - if err := d.Set("load_balancers", flex.FlattenStringList(g.LoadBalancerNames)); err != nil { - return fmt.Errorf("error setting load_balancers: %s", err) + return output, strconv.Itoa(count), nil } +} - d.Set("launch_configuration", g.LaunchConfigurationName) +func statusLoadBalancerTargetGroupInStateCount(conn *autoscaling.AutoScaling, name string, states ...string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findLoadBalancerTargetGroupStates(conn, name) - if err := d.Set("launch_template", flattenLaunchTemplateSpecificationMap(g.LaunchTemplate)); err != nil { - return fmt.Errorf("error setting launch_template: %s", err) - } + if tfresource.NotFound(err) { + return nil, "", nil + } - d.Set("max_size", g.MaxSize) - d.Set("min_size", g.MinSize) + if err != nil { + return nil, "", err + } - if err := d.Set("mixed_instances_policy", flattenMixedInstancesPolicy(g.MixedInstancesPolicy)); err != nil { - return fmt.Errorf("error setting mixed_instances_policy: %s", err) - } + var count int - d.Set("name", g.AutoScalingGroupName) - d.Set("name_prefix", create.NamePrefixFromName(aws.StringValue(g.AutoScalingGroupName))) - d.Set("placement_group", g.PlacementGroup) - d.Set("protect_from_scale_in", g.NewInstancesProtectedFromScaleIn) - d.Set("service_linked_role_arn", g.ServiceLinkedRoleARN) - d.Set("max_instance_lifetime", g.MaxInstanceLifetime) + for _, v := range output { + for _, state := range states { + if aws.StringValue(v.State) == state { + count++ + break + } + } + } - if err := d.Set("suspended_processes", flattenASGSuspendedProcesses(g.SuspendedProcesses)); err != nil { - return fmt.Errorf("error setting suspended_processes: %s", err) + return output, strconv.Itoa(count), nil } +} - var tagOk, tagsOk bool - var v interface{} +func statusWarmPool(conn *autoscaling.AutoScaling, name string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findWarmPool(conn, name) - // Deprecated: In a future major version, this should always set all tags except those ignored. - // Remove d.GetOk() and Only() handling. - if v, tagOk = d.GetOk("tag"); tagOk { - proposedStateTags := KeyValueTags(v, d.Id(), TagResourceTypeGroup) + if tfresource.NotFound(err) { + return nil, "", nil + } - if err := d.Set("tag", ListOfMap(KeyValueTags(g.Tags, d.Id(), TagResourceTypeGroup).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Only(proposedStateTags))); err != nil { - return fmt.Errorf("error setting tag: %w", err) + if err != nil { + return nil, "", err } + + return output.WarmPoolConfiguration, aws.StringValue(output.WarmPoolConfiguration.Status), nil } +} - if v, tagsOk = d.GetOk("tags"); tagsOk { - proposedStateTags := KeyValueTags(v, d.Id(), TagResourceTypeGroup) +func statusWarmPoolInstanceCount(conn *autoscaling.AutoScaling, name string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findWarmPool(conn, name) - if err := d.Set("tags", ListOfStringMap(KeyValueTags(g.Tags, d.Id(), TagResourceTypeGroup).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Only(proposedStateTags))); err != nil { - return fmt.Errorf("error setting tags: %w", err) + if tfresource.NotFound(err) { + return nil, "", nil } - } - if !tagOk && !tagsOk { - if err := d.Set("tag", ListOfMap(KeyValueTags(g.Tags, d.Id(), TagResourceTypeGroup).IgnoreAWS().IgnoreConfig(ignoreTagsConfig))); err != nil { - return fmt.Errorf("error setting tag: %w", err) + if err != nil { + return nil, "", err } - } - if err := d.Set("target_group_arns", flex.FlattenStringList(g.TargetGroupARNs)); err != nil { - return fmt.Errorf("error setting target_group_arns: %s", err) + return output, strconv.Itoa(len(output.Instances)), nil } +} - // If no termination polices are explicitly configured and the upstream state - // is only using the "Default" policy, clear the state to make it consistent - // with the default AWS create API behavior. - _, ok := d.GetOk("termination_policies") - if !ok && len(g.TerminationPolicies) == 1 && aws.StringValue(g.TerminationPolicies[0]) == "Default" { - d.Set("termination_policies", []interface{}{}) - } else { - if err := d.Set("termination_policies", flex.FlattenStringList(g.TerminationPolicies)); err != nil { - return fmt.Errorf("error setting termination_policies: %s", err) - } +func waitGroupDrained(conn *autoscaling.AutoScaling, name string, timeout time.Duration) (*autoscaling.Group, error) { + stateConf := &resource.StateChangeConf{ + Target: []string{"0"}, + Refresh: statusGroupInstanceCount(conn, name), + Timeout: timeout, } - d.Set("vpc_zone_identifier", []string{}) - if len(aws.StringValue(g.VPCZoneIdentifier)) > 0 { - if err := d.Set("vpc_zone_identifier", strings.Split(aws.StringValue(g.VPCZoneIdentifier), ",")); err != nil { - return fmt.Errorf("error setting vpc_zone_identifier: %s", err) - } - } + outputRaw, err := stateConf.WaitForState() - if err := d.Set("warm_pool", FlattenWarmPoolConfiguration(g.WarmPoolConfiguration)); err != nil { - return fmt.Errorf("error setting warm_pool for Auto Scaling Group (%s), error: %s", d.Id(), err) + if output, ok := outputRaw.(*autoscaling.Group); ok { + return output, err } - return nil + return nil, err } -func waitUntilGroupLoadBalancerTargetGroupsRemoved(conn *autoscaling.AutoScaling, asgName string) error { - input := &autoscaling.DescribeLoadBalancerTargetGroupsInput{ - AutoScalingGroupName: aws.String(asgName), +func waitLoadBalancersAdded(conn *autoscaling.AutoScaling, name string, timeout time.Duration) ([]*autoscaling.LoadBalancerState, error) { + stateConf := &resource.StateChangeConf{ + Target: []string{"0"}, + Refresh: statusLoadBalancerInStateCount(conn, name, LoadBalancerStateAdding), + Timeout: timeout, } - var tgRemoving bool - for { - output, err := conn.DescribeLoadBalancerTargetGroups(input) + outputRaw, err := stateConf.WaitForState() - if err != nil { - return err - } + if output, ok := outputRaw.([]*autoscaling.LoadBalancerState); ok { + return output, err + } - for _, tg := range output.LoadBalancerTargetGroups { - if aws.StringValue(tg.State) == "Removing" { - tgRemoving = true - break - } - } + return nil, err +} - if tgRemoving { - tgRemoving = false - input.NextToken = nil - continue - } +func waitLoadBalancersRemoved(conn *autoscaling.AutoScaling, name string, timeout time.Duration) ([]*autoscaling.LoadBalancerState, error) { + stateConf := &resource.StateChangeConf{ + Target: []string{"0"}, + Refresh: statusLoadBalancerInStateCount(conn, name, LoadBalancerStateRemoving), + Timeout: timeout, + } - if aws.StringValue(output.NextToken) == "" { - break - } + outputRaw, err := stateConf.WaitForState() - input.NextToken = output.NextToken + if output, ok := outputRaw.([]*autoscaling.LoadBalancerState); ok { + return output, err } - return nil + return nil, err } -func waitUntilGroupLoadBalancerTargetGroupsAdded(conn *autoscaling.AutoScaling, asgName string) error { - input := &autoscaling.DescribeLoadBalancerTargetGroupsInput{ - AutoScalingGroupName: aws.String(asgName), +func waitLoadBalancerTargetGroupsAdded(conn *autoscaling.AutoScaling, name string, timeout time.Duration) ([]*autoscaling.LoadBalancerTargetGroupState, error) { + stateConf := &resource.StateChangeConf{ + Target: []string{"0"}, + Refresh: statusLoadBalancerTargetGroupInStateCount(conn, name, LoadBalancerTargetGroupStateAdding), + Timeout: timeout, } - var tgAdding bool - for { - output, err := conn.DescribeLoadBalancerTargetGroups(input) + outputRaw, err := stateConf.WaitForState() - if err != nil { - return err - } + if output, ok := outputRaw.([]*autoscaling.LoadBalancerTargetGroupState); ok { + return output, err + } - for _, tg := range output.LoadBalancerTargetGroups { - if aws.StringValue(tg.State) == "Adding" { - tgAdding = true - break - } - } + return nil, err +} - if tgAdding { - tgAdding = false - input.NextToken = nil - continue - } +func waitLoadBalancerTargetGroupsRemoved(conn *autoscaling.AutoScaling, name string, timeout time.Duration) ([]*autoscaling.LoadBalancerTargetGroupState, error) { + stateConf := &resource.StateChangeConf{ + Target: []string{"0"}, + Refresh: statusLoadBalancerTargetGroupInStateCount(conn, name, LoadBalancerTargetGroupStateRemoving), + Timeout: timeout, + } - if aws.StringValue(output.NextToken) == "" { - break - } + outputRaw, err := stateConf.WaitForState() - input.NextToken = output.NextToken + if output, ok := outputRaw.([]*autoscaling.LoadBalancerTargetGroupState); ok { + return output, err } - return nil + return nil, err } -func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*conns.AWSClient).AutoScalingConn - shouldWaitForCapacity := false - shouldRefreshInstances := false +const ( + // Maximum amount of time to wait for an InstanceRefresh to be started + // Must be at least as long as instanceRefreshCancelledTimeout, since we try to cancel any + // existing Instance Refreshes when starting. + instanceRefreshStartedTimeout = instanceRefreshCancelledTimeout + + // Maximum amount of time to wait for an Instance Refresh to be Cancelled + instanceRefreshCancelledTimeout = 15 * time.Minute +) - opts := autoscaling.UpdateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String(d.Id()), +func waitInstanceRefreshCancelled(conn *autoscaling.AutoScaling, name, id string, timeout time.Duration) (*autoscaling.InstanceRefresh, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ + autoscaling.InstanceRefreshStatusCancelling, + autoscaling.InstanceRefreshStatusInProgress, + autoscaling.InstanceRefreshStatusPending, + }, + Target: []string{ + autoscaling.InstanceRefreshStatusCancelled, + autoscaling.InstanceRefreshStatusFailed, + autoscaling.InstanceRefreshStatusSuccessful, + }, + Refresh: statusInstanceRefresh(conn, name, id), + Timeout: timeout, } - opts.NewInstancesProtectedFromScaleIn = aws.Bool(d.Get("protect_from_scale_in").(bool)) + outputRaw, err := stateConf.WaitForState() - if d.HasChange("default_cooldown") { - opts.DefaultCooldown = aws.Int64(int64(d.Get("default_cooldown").(int))) + if output, ok := outputRaw.(*autoscaling.InstanceRefresh); ok { + return output, err } - if d.HasChange("capacity_rebalance") { - // If the capacity rebalance field is set to null, we need to explicitly set - // it back to "false", or the API won't reset it for us. - if v, ok := d.GetOk("capacity_rebalance"); ok { - opts.CapacityRebalance = aws.Bool(v.(bool)) - } else { - opts.CapacityRebalance = aws.Bool(false) - } - } + return nil, err +} - if d.HasChange("desired_capacity") { - opts.DesiredCapacity = aws.Int64(int64(d.Get("desired_capacity").(int))) - shouldWaitForCapacity = true +func waitWarmPoolDeleted(conn *autoscaling.AutoScaling, name string, timeout time.Duration) (*autoscaling.WarmPoolConfiguration, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{autoscaling.WarmPoolStatusPendingDelete}, + Target: []string{}, + Refresh: statusWarmPool(conn, name), + Timeout: timeout, } - if d.HasChange("launch_configuration") { - if v, ok := d.GetOk("launch_configuration"); ok { - opts.LaunchConfigurationName = aws.String(v.(string)) - } - shouldRefreshInstances = true - } + outputRaw, err := stateConf.WaitForState() - if d.HasChange("launch_template") { - if v, ok := d.GetOk("launch_template"); ok && len(v.([]interface{})) > 0 { - opts.LaunchTemplate = expandLaunchTemplateSpecification(v.([]interface{})) - } - shouldRefreshInstances = true + if output, ok := outputRaw.(*autoscaling.WarmPoolConfiguration); ok { + return output, err } - if d.HasChange("mixed_instances_policy") { - opts.MixedInstancesPolicy = expandMixedInstancesPolicy(d.Get("mixed_instances_policy").([]interface{})) - shouldRefreshInstances = true - } + return nil, err +} - if d.HasChange("min_size") { - opts.MinSize = aws.Int64(int64(d.Get("min_size").(int))) - shouldWaitForCapacity = true +func waitWarmPoolDrained(conn *autoscaling.AutoScaling, name string, timeout time.Duration) (*autoscaling.DescribeWarmPoolOutput, error) { + stateConf := &resource.StateChangeConf{ + Target: []string{"0"}, + Refresh: statusWarmPoolInstanceCount(conn, name), + Timeout: timeout, } - if d.HasChange("max_size") { - opts.MaxSize = aws.Int64(int64(d.Get("max_size").(int))) - } + outputRaw, err := stateConf.WaitForState() - if d.HasChange("max_instance_lifetime") { - opts.MaxInstanceLifetime = aws.Int64(int64(d.Get("max_instance_lifetime").(int))) + if output, ok := outputRaw.(*autoscaling.DescribeWarmPoolOutput); ok { + return output, err } - if d.HasChange("health_check_grace_period") { - opts.HealthCheckGracePeriod = aws.Int64(int64(d.Get("health_check_grace_period").(int))) + return nil, err +} + +func expandInstancesDistribution(tfMap map[string]interface{}) *autoscaling.InstancesDistribution { + if tfMap == nil { + return nil } - if d.HasChange("health_check_type") { - opts.HealthCheckGracePeriod = aws.Int64(int64(d.Get("health_check_grace_period").(int))) - opts.HealthCheckType = aws.String(d.Get("health_check_type").(string)) + apiObject := &autoscaling.InstancesDistribution{} + + if v, ok := tfMap["on_demand_allocation_strategy"].(string); ok && v != "" { + apiObject.OnDemandAllocationStrategy = aws.String(v) } - if d.HasChange("vpc_zone_identifier") { - opts.VPCZoneIdentifier = expandVpcZoneIdentifiers(d.Get("vpc_zone_identifier").(*schema.Set).List()) + if v, ok := tfMap["on_demand_base_capacity"].(int); ok { + apiObject.OnDemandBaseCapacity = aws.Int64(int64(v)) } - if d.HasChange("availability_zones") { - if v, ok := d.GetOk("availability_zones"); ok && v.(*schema.Set).Len() > 0 { - opts.AvailabilityZones = flex.ExpandStringSet(v.(*schema.Set)) - } + if v, ok := tfMap["on_demand_percentage_above_base_capacity"].(int); ok { + apiObject.OnDemandPercentageAboveBaseCapacity = aws.Int64(int64(v)) } - if d.HasChange("placement_group") { - opts.PlacementGroup = aws.String(d.Get("placement_group").(string)) + if v, ok := tfMap["spot_allocation_strategy"].(string); ok && v != "" { + apiObject.SpotAllocationStrategy = aws.String(v) } - if d.HasChange("termination_policies") { - // If the termination policy is set to null, we need to explicitly set - // it back to "Default", or the API won't reset it for us. - if v, ok := d.GetOk("termination_policies"); ok && len(v.([]interface{})) > 0 { - opts.TerminationPolicies = flex.ExpandStringList(v.([]interface{})) - } else { - log.Printf("[DEBUG] Explicitly setting null termination policy to 'Default'") - opts.TerminationPolicies = aws.StringSlice([]string{"Default"}) - } + if v, ok := tfMap["spot_instance_pools"].(int); ok && v != 0 { + apiObject.SpotInstancePools = aws.Int64(int64(v)) } - if d.HasChange("service_linked_role_arn") { - opts.ServiceLinkedRoleARN = aws.String(d.Get("service_linked_role_arn").(string)) + if v, ok := tfMap["spot_max_price"].(string); ok { + apiObject.SpotMaxPrice = aws.String(v) } - if d.HasChanges("tag", "tags") { - oTagRaw, nTagRaw := d.GetChange("tag") - oTagsRaw, nTagsRaw := d.GetChange("tags") + return apiObject +} - oTag := KeyValueTags(oTagRaw, d.Id(), TagResourceTypeGroup) - oTags := KeyValueTags(oTagsRaw, d.Id(), TagResourceTypeGroup) - oldTags := Tags(oTag.Merge(oTags)) +func expandLaunchTemplate(tfMap map[string]interface{}) *autoscaling.LaunchTemplate { + if tfMap == nil { + return nil + } - nTag := KeyValueTags(nTagRaw, d.Id(), TagResourceTypeGroup) - nTags := KeyValueTags(nTagsRaw, d.Id(), TagResourceTypeGroup) - newTags := Tags(nTag.Merge(nTags)) + apiObject := &autoscaling.LaunchTemplate{} - if err := UpdateTags(conn, d.Id(), TagResourceTypeGroup, oldTags, newTags); err != nil { - return fmt.Errorf("error updating tags for Auto Scaling Group (%s): %w", d.Id(), err) - } + if v, ok := tfMap["launch_template_specification"].([]interface{}); ok && len(v) > 0 { + apiObject.LaunchTemplateSpecification = expandLaunchTemplateSpecificationForMixedInstancesPolicy(v[0].(map[string]interface{})) } - log.Printf("[DEBUG] Auto Scaling Group update configuration: %#v", opts) - _, err := conn.UpdateAutoScalingGroup(&opts) - if err != nil { - return fmt.Errorf("Error updating Auto Scaling Group: %s", err) + if v, ok := tfMap["override"].([]interface{}); ok && len(v) > 0 { + apiObject.Overrides = expandLaunchTemplateOverrideses(v) } - if d.HasChange("load_balancers") { - - o, n := d.GetChange("load_balancers") - if o == nil { - o = new(schema.Set) - } - if n == nil { - n = new(schema.Set) - } + return apiObject +} - os := o.(*schema.Set) - ns := n.(*schema.Set) - remove := flex.ExpandStringSet(os.Difference(ns)) - add := flex.ExpandStringSet(ns.Difference(os)) +func expandLaunchTemplateOverrides(tfMap map[string]interface{}) *autoscaling.LaunchTemplateOverrides { + if tfMap == nil { + return nil + } - if len(remove) > 0 { - // API only supports removing 10 at a time - var batches [][]*string + apiObject := &autoscaling.LaunchTemplateOverrides{} - batchSize := 10 + if v, ok := tfMap["instance_requirements"].([]interface{}); ok && len(v) > 0 { + apiObject.InstanceRequirements = expandInstanceRequirements(v[0].(map[string]interface{})) + } - for batchSize < len(remove) { - remove, batches = remove[batchSize:], append(batches, remove[0:batchSize:batchSize]) - } - batches = append(batches, remove) + if v, ok := tfMap["launch_template_specification"].([]interface{}); ok && len(v) > 0 { + apiObject.LaunchTemplateSpecification = expandLaunchTemplateSpecificationForMixedInstancesPolicy(v[0].(map[string]interface{})) + } - for _, batch := range batches { - _, err := conn.DetachLoadBalancers(&autoscaling.DetachLoadBalancersInput{ - AutoScalingGroupName: aws.String(d.Id()), - LoadBalancerNames: batch, - }) + if v, ok := tfMap["instance_type"].(string); ok && v != "" { + apiObject.InstanceType = aws.String(v) + } - if err != nil { - return fmt.Errorf("error detaching Auto Scaling Group (%s) Load Balancers: %s", d.Id(), err) - } + if v, ok := tfMap["weighted_capacity"].(string); ok && v != "" { + apiObject.WeightedCapacity = aws.String(v) + } - if err := waitUntilGroupLoadBalancersRemoved(conn, d.Id()); err != nil { - return fmt.Errorf("error describing Auto Scaling Group (%s) Load Balancers being removed: %s", d.Id(), err) - } - } - } + return apiObject +} - if len(add) > 0 { - // API only supports adding 10 at a time - batchSize := 10 +func expandLaunchTemplateOverrideses(tfList []interface{}) []*autoscaling.LaunchTemplateOverrides { + if len(tfList) == 0 { + return nil + } - var batches [][]*string + var apiObjects []*autoscaling.LaunchTemplateOverrides - for batchSize < len(add) { - add, batches = add[batchSize:], append(batches, add[0:batchSize:batchSize]) - } - batches = append(batches, add) + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]interface{}) - for _, batch := range batches { - _, err := conn.AttachLoadBalancers(&autoscaling.AttachLoadBalancersInput{ - AutoScalingGroupName: aws.String(d.Id()), - LoadBalancerNames: batch, - }) + if !ok { + continue + } - if err != nil { - return fmt.Errorf("error attaching Auto Scaling Group (%s) Load Balancers: %s", d.Id(), err) - } + apiObject := expandLaunchTemplateOverrides(tfMap) - if err := waitUntilGroupLoadBalancersAdded(conn, d.Id()); err != nil { - return fmt.Errorf("error describing Auto Scaling Group (%s) Load Balancers being added: %s", d.Id(), err) - } - } + if apiObject == nil { + continue } - } - if d.HasChange("target_group_arns") { + apiObjects = append(apiObjects, apiObject) + } - o, n := d.GetChange("target_group_arns") - if o == nil { - o = new(schema.Set) - } - if n == nil { - n = new(schema.Set) - } + return apiObjects +} - os := o.(*schema.Set) - ns := n.(*schema.Set) - remove := flex.ExpandStringSet(os.Difference(ns)) - add := flex.ExpandStringSet(ns.Difference(os)) +func expandInstanceRequirements(tfMap map[string]interface{}) *autoscaling.InstanceRequirements { + if tfMap == nil { + return nil + } - if len(remove) > 0 { - // AWS API only supports adding/removing 10 at a time - var batches [][]*string + apiObject := &autoscaling.InstanceRequirements{} - batchSize := 10 + if v, ok := tfMap["accelerator_count"].([]interface{}); ok && len(v) > 0 { + apiObject.AcceleratorCount = expandAcceleratorCountRequest(v[0].(map[string]interface{})) + } - for batchSize < len(remove) { - remove, batches = remove[batchSize:], append(batches, remove[0:batchSize:batchSize]) - } - batches = append(batches, remove) + if v, ok := tfMap["accelerator_manufacturers"].(*schema.Set); ok && v.Len() > 0 { + apiObject.AcceleratorManufacturers = flex.ExpandStringSet(v) + } - for _, batch := range batches { - _, err := conn.DetachLoadBalancerTargetGroups(&autoscaling.DetachLoadBalancerTargetGroupsInput{ - AutoScalingGroupName: aws.String(d.Id()), - TargetGroupARNs: batch, - }) - if err != nil { - return fmt.Errorf("Error updating Load Balancers Target Groups for Auto Scaling Group (%s), error: %s", d.Id(), err) - } + if v, ok := tfMap["accelerator_names"].(*schema.Set); ok && v.Len() > 0 { + apiObject.AcceleratorNames = flex.ExpandStringSet(v) + } - if err := waitUntilGroupLoadBalancerTargetGroupsRemoved(conn, d.Id()); err != nil { - return fmt.Errorf("error describing Auto Scaling Group (%s) Load Balancer Target Groups being removed: %s", d.Id(), err) - } - } + if v, ok := tfMap["accelerator_total_memory_mib"].([]interface{}); ok && len(v) > 0 { + apiObject.AcceleratorTotalMemoryMiB = expandAcceleratorTotalMemoryMiBRequest(v[0].(map[string]interface{})) + } - } + if v, ok := tfMap["accelerator_types"].(*schema.Set); ok && v.Len() > 0 { + apiObject.AcceleratorTypes = flex.ExpandStringSet(v) + } - if len(add) > 0 { - batchSize := 10 + if v, ok := tfMap["bare_metal"].(string); ok && v != "" { + apiObject.BareMetal = aws.String(v) + } - var batches [][]*string + if v, ok := tfMap["baseline_ebs_bandwidth_mbps"].([]interface{}); ok && len(v) > 0 { + apiObject.BaselineEbsBandwidthMbps = expandBaselineEBSBandwidthMbpsRequest(v[0].(map[string]interface{})) + } - for batchSize < len(add) { - add, batches = add[batchSize:], append(batches, add[0:batchSize:batchSize]) - } - batches = append(batches, add) + if v, ok := tfMap["burstable_performance"].(string); ok && v != "" { + apiObject.BurstablePerformance = aws.String(v) + } - for _, batch := range batches { - _, err := conn.AttachLoadBalancerTargetGroups(&autoscaling.AttachLoadBalancerTargetGroupsInput{ - AutoScalingGroupName: aws.String(d.Id()), - TargetGroupARNs: batch, - }) + if v, ok := tfMap["cpu_manufacturers"].(*schema.Set); ok && v.Len() > 0 { + apiObject.CpuManufacturers = flex.ExpandStringSet(v) + } - if err != nil { - return fmt.Errorf("Error updating Load Balancers Target Groups for Auto Scaling Group (%s), error: %s", d.Id(), err) - } + if v, ok := tfMap["excluded_instance_types"].(*schema.Set); ok && v.Len() > 0 { + apiObject.ExcludedInstanceTypes = flex.ExpandStringSet(v) + } - if err := waitUntilGroupLoadBalancerTargetGroupsAdded(conn, d.Id()); err != nil { - return fmt.Errorf("error describing Auto Scaling Group (%s) Load Balancer Target Groups being added: %s", d.Id(), err) - } - } - } + if v, ok := tfMap["instance_generations"].(*schema.Set); ok && v.Len() > 0 { + apiObject.InstanceGenerations = flex.ExpandStringSet(v) } - if instanceRefreshRaw, ok := d.GetOk("instance_refresh"); ok { - instanceRefresh := instanceRefreshRaw.([]interface{}) - if !shouldRefreshInstances { - if len(instanceRefresh) > 0 && instanceRefresh[0] != nil { - m := instanceRefresh[0].(map[string]interface{}) - attrsSet := m["triggers"].(*schema.Set) - attrs := attrsSet.List() - strs := make([]string, len(attrs)) - for i, a := range attrs { - strs[i] = a.(string) - } - if attrsSet.Contains("tag") && !attrsSet.Contains("tags") { - strs = append(strs, "tags") // nozero - } else if !attrsSet.Contains("tag") && attrsSet.Contains("tags") { - strs = append(strs, "tag") // nozero - } - shouldRefreshInstances = d.HasChanges(strs...) - } - } - if shouldRefreshInstances { - if err := GroupRefreshInstances(conn, d.Id(), instanceRefresh); err != nil { - return fmt.Errorf("failed to start instance refresh of Auto Scaling Group %s: %w", d.Id(), err) - } - } + if v, ok := tfMap["local_storage"].(string); ok && v != "" { + apiObject.LocalStorage = aws.String(v) } - if d.HasChange("warm_pool") { - w := d.Get("warm_pool").([]interface{}) + if v, ok := tfMap["local_storage_types"].(*schema.Set); ok && v.Len() > 0 { + apiObject.LocalStorageTypes = flex.ExpandStringSet(v) + } - // No warm pool exists in new config. Delete it. - if len(w) == 0 || w[0] == nil { - g, err := getGroup(d.Id(), conn) - if err != nil { - return err - } + if v, ok := tfMap["memory_gib_per_vcpu"].([]interface{}); ok && len(v) > 0 { + apiObject.MemoryGiBPerVCpu = expandMemoryGiBPerVCPURequest(v[0].(map[string]interface{})) + } - if err := resourceGroupWarmPoolDelete(g, d, meta); err != nil { - return fmt.Errorf("error deleting Warm pool for Auto Scaling Group %s: %s", d.Id(), err) - } + if v, ok := tfMap["memory_mib"].([]interface{}); ok && len(v) > 0 { + apiObject.MemoryMiB = expandMemoryMiBRequest(v[0].(map[string]interface{})) + } - log.Printf("[INFO] Successfully removed Warm pool") - } else { - _, err := conn.PutWarmPool(CreatePutWarmPoolInput(d.Id(), d.Get("warm_pool").([]interface{}))) + if v, ok := tfMap["network_interface_count"].([]interface{}); ok && len(v) > 0 { + apiObject.NetworkInterfaceCount = expandNetworkInterfaceCountRequest(v[0].(map[string]interface{})) + } - if err != nil { - return fmt.Errorf("error updating Warm Pool for Auto Scaling Group (%s), error: %s", d.Id(), err) - } + if v, ok := tfMap["on_demand_max_price_percentage_over_lowest_price"].(int); ok && v != 0 { + apiObject.OnDemandMaxPricePercentageOverLowestPrice = aws.Int64(int64(v)) + } - log.Printf("[INFO] Successfully updated Warm pool") - } + if v, ok := tfMap["require_hibernate_support"].(bool); ok && v { + apiObject.RequireHibernateSupport = aws.Bool(v) } - if shouldWaitForCapacity { - if err := waitForASGCapacity(d, meta, CapacitySatisfiedUpdate); err != nil { - return fmt.Errorf("error waiting for Auto Scaling Group Capacity: %w", err) - } + if v, ok := tfMap["spot_max_price_percentage_over_lowest_price"].(int); ok && v != 0 { + apiObject.SpotMaxPricePercentageOverLowestPrice = aws.Int64(int64(v)) } - if d.HasChange("enabled_metrics") { - if err := updateASGMetricsCollection(d, conn); err != nil { - return fmt.Errorf("Error updating Auto Scaling Group Metrics collection: %s", err) - } + if v, ok := tfMap["total_local_storage_gb"].([]interface{}); ok && len(v) > 0 { + apiObject.TotalLocalStorageGB = expandTotalLocalStorageGBRequest(v[0].(map[string]interface{})) } - if d.HasChange("suspended_processes") { - if err := updateASGSuspendedProcesses(d, conn); err != nil { - return fmt.Errorf("Error updating Auto Scaling Group Suspended Processes: %s", err) - } + if v, ok := tfMap["vcpu_count"].([]interface{}); ok && len(v) > 0 { + apiObject.VCpuCount = expandVCPUCountRequest(v[0].(map[string]interface{})) } - return resourceGroupRead(d, meta) + return apiObject } -func resourceGroupDelete(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*conns.AWSClient).AutoScalingConn +func expandAcceleratorCountRequest(tfMap map[string]interface{}) *autoscaling.AcceleratorCountRequest { + if tfMap == nil { + return nil + } - // Read the Auto Scaling Group first. If it doesn't exist, we're done. - // We need the group in order to check if there are instances attached. - // If so, we need to remove those first. - g, err := getGroup(d.Id(), conn) - if err != nil { - return err + apiObject := &autoscaling.AcceleratorCountRequest{} + + var min int + if v, ok := tfMap["min"].(int); ok { + min = v + apiObject.Min = aws.Int64(int64(v)) + } + + if v, ok := tfMap["max"].(int); ok && v >= min { + apiObject.Max = aws.Int64(int64(v)) } - if g == nil { - log.Printf("[WARN] Auto Scaling Group (%s) not found, removing from state", d.Id()) + + return apiObject +} + +func expandAcceleratorTotalMemoryMiBRequest(tfMap map[string]interface{}) *autoscaling.AcceleratorTotalMemoryMiBRequest { + if tfMap == nil { return nil } - // Try deleting Warm pool first. - if err := resourceGroupWarmPoolDelete(g, d, meta); err != nil { - return fmt.Errorf("error deleting Warm pool for Auto Scaling Group %s: %s", d.Id(), err) + apiObject := &autoscaling.AcceleratorTotalMemoryMiBRequest{} + + var min int + if v, ok := tfMap["min"].(int); ok { + min = v + apiObject.Min = aws.Int64(int64(v)) } - if len(g.Instances) > 0 || aws.Int64Value(g.DesiredCapacity) > 0 { - if err := resourceGroupDrain(d, meta); err != nil { - return err - } + if v, ok := tfMap["max"].(int); ok && v >= min { + apiObject.Max = aws.Int64(int64(v)) } - log.Printf("[DEBUG] Auto Scaling Group destroy: %v", d.Id()) - deleteopts := autoscaling.DeleteAutoScalingGroupInput{ - AutoScalingGroupName: aws.String(d.Id()), - ForceDelete: aws.Bool(d.Get("force_delete").(bool)), + return apiObject +} + +func expandBaselineEBSBandwidthMbpsRequest(tfMap map[string]interface{}) *autoscaling.BaselineEbsBandwidthMbpsRequest { + if tfMap == nil { + return nil } - // We retry the delete operation to handle InUse/InProgress errors coming - // from scaling operations. We should be able to sneak in a delete in between - // scaling operations within 5m. - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - if _, err := conn.DeleteAutoScalingGroup(&deleteopts); err != nil { - if tfawserr.ErrCodeEquals(err, "InvalidGroup.NotFound") { - return nil - } + apiObject := &autoscaling.BaselineEbsBandwidthMbpsRequest{} - if tfawserr.ErrCodeEquals(err, "ResourceInUse", "ScalingActivityInProgress") { - return resource.RetryableError(err) - } + var min int + if v, ok := tfMap["min"].(int); ok { + min = v + apiObject.Min = aws.Int64(int64(v)) + } - // Didn't recognize the error, so shouldn't retry. - return resource.NonRetryableError(err) - } - // Successful delete + if v, ok := tfMap["max"].(int); ok && v >= min { + apiObject.Max = aws.Int64(int64(v)) + } + + return apiObject +} + +func expandMemoryGiBPerVCPURequest(tfMap map[string]interface{}) *autoscaling.MemoryGiBPerVCpuRequest { + if tfMap == nil { return nil - }) - if tfresource.TimedOut(err) { - _, err = conn.DeleteAutoScalingGroup(&deleteopts) - if tfawserr.ErrCodeEquals(err, "InvalidGroup.NotFound") { - return nil - } } - if err != nil { - return fmt.Errorf("Error deleting Auto Scaling Group: %s", err) + + apiObject := &autoscaling.MemoryGiBPerVCpuRequest{} + + var min float64 + if v, ok := tfMap["min"].(float64); ok { + min = v + apiObject.Min = aws.Float64(v) } - var group *autoscaling.Group - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - group, err = getGroup(d.Id(), conn) + if v, ok := tfMap["max"].(float64); ok && v >= min { + apiObject.Max = aws.Float64(v) + } - if group != nil { - return resource.RetryableError(fmt.Errorf("Auto Scaling Group still exists")) - } + return apiObject +} + +func expandMemoryMiBRequest(tfMap map[string]interface{}) *autoscaling.MemoryMiBRequest { + if tfMap == nil { return nil - }) - if tfresource.TimedOut(err) { - group, err = getGroup(d.Id(), conn) - if group != nil { - return fmt.Errorf("Auto Scaling Group still exists") - } } - if err != nil { - return fmt.Errorf("Error deleting Auto Scaling Group: %s", err) + + apiObject := &autoscaling.MemoryMiBRequest{} + + var min int + if v, ok := tfMap["min"].(int); ok { + min = v + apiObject.Min = aws.Int64(int64(v)) } - return nil -} -func resourceGroupWarmPoolDelete(g *autoscaling.Group, d *schema.ResourceData, meta interface{}) error { - conn := meta.(*conns.AWSClient).AutoScalingConn + if v, ok := tfMap["max"].(int); ok && v >= min { + apiObject.Max = aws.Int64(int64(v)) + } + + return apiObject +} - if g.WarmPoolConfiguration == nil { - // No warm pool configured. Skipping deletion. +func expandNetworkInterfaceCountRequest(tfMap map[string]interface{}) *autoscaling.NetworkInterfaceCountRequest { + if tfMap == nil { return nil } - log.Printf("[INFO] Auto Scaling Group has a Warm Pool. First deleting it.") + apiObject := &autoscaling.NetworkInterfaceCountRequest{} - if err := resourceGroupWarmPoolDrain(d, meta); err != nil { - return err + var min int + if v, ok := tfMap["min"].(int); ok { + min = v + apiObject.Min = aws.Int64(int64(v)) } - // Delete Warm Pool if it is not pending delete. - if g.WarmPoolConfiguration.Status == nil || aws.StringValue(g.WarmPoolConfiguration.Status) != "PendingDelete" { - deleteopts := autoscaling.DeleteWarmPoolInput{ - AutoScalingGroupName: aws.String(d.Id()), - ForceDelete: aws.Bool(d.Get("force_delete").(bool) || d.Get("force_delete_warm_pool").(bool)), - } - - err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - _, err := conn.DeleteWarmPool(&deleteopts) - if err != nil { - if tfawserr.ErrCodeEquals(err, "ResourceInUse", "ScalingActivityInProgress") { - return resource.RetryableError(err) - } + if v, ok := tfMap["max"].(int); ok && v >= min { + apiObject.Max = aws.Int64(int64(v)) + } - // Didn't recognize the error, so shouldn't retry. - return resource.NonRetryableError(err) - } - // Successful delete - return nil - }) + return apiObject +} - if tfresource.TimedOut(err) { - _, err = conn.DeleteWarmPool(&deleteopts) - } - if err != nil { - return fmt.Errorf("error deleting Warm Pool: %s", err) - } +func expandTotalLocalStorageGBRequest(tfMap map[string]interface{}) *autoscaling.TotalLocalStorageGBRequest { + if tfMap == nil { + return nil } - // Wait for Warm pool to be gone. - if err := waitForWarmPoolDeletion(conn, d); err != nil { - return fmt.Errorf("error waiting for Warm Pool deletion: %s", err) + apiObject := &autoscaling.TotalLocalStorageGBRequest{} + + var min float64 + if v, ok := tfMap["min"].(float64); ok { + min = v + apiObject.Min = aws.Float64(v) } - log.Printf("[INFO] Successfully removed Warm pool") + if v, ok := tfMap["max"].(float64); ok && v >= min { + apiObject.Max = aws.Float64(v) + } - return nil + return apiObject } -func waitForWarmPoolDeletion(conn *autoscaling.AutoScaling, d *schema.ResourceData) error { - stateConf := &resource.StateChangeConf{ - Pending: []string{"", autoscaling.WarmPoolStatusPendingDelete}, - Target: []string{"deleted"}, - Refresh: asgWarmPoolStateRefreshFunc(conn, d.Id()), - Timeout: d.Timeout(schema.TimeoutDelete), - NotFoundChecks: 1, +func expandVCPUCountRequest(tfMap map[string]interface{}) *autoscaling.VCpuCountRequest { + if tfMap == nil { + return nil } - log.Printf("[DEBUG] Waiting for Auto Scaling Group (%s) Warm Pool deletion", d.Id()) - _, err := stateConf.WaitForState() + apiObject := &autoscaling.VCpuCountRequest{} - if tfresource.NotFound(err) { - return nil + min := 0 + if v, ok := tfMap["min"].(int); ok { + min = v + apiObject.Min = aws.Int64(int64(v)) + } + + if v, ok := tfMap["max"].(int); ok && v >= min { + apiObject.Max = aws.Int64(int64(v)) } - return err + return apiObject } -func asgWarmPoolStateRefreshFunc(conn *autoscaling.AutoScaling, asgName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - g, err := getGroup(asgName, conn) +func expandLaunchTemplateSpecificationForMixedInstancesPolicy(tfMap map[string]interface{}) *autoscaling.LaunchTemplateSpecification { + if tfMap == nil { + return nil + } - if err != nil { - return nil, "", fmt.Errorf("error describing Auto Scaling Group (%s): %s", asgName, err) - } + apiObject := &autoscaling.LaunchTemplateSpecification{} - if g == nil || g.WarmPoolConfiguration == nil { - return nil, "deleted", nil - } - return asgName, aws.StringValue(g.WarmPoolConfiguration.Status), nil + // API returns both ID and name, which Terraform saves to state. Next update returns: + // ValidationError: Valid requests must contain either launchTemplateId or LaunchTemplateName + // Prefer the ID if we have both. + if v, ok := tfMap["launch_template_id"]; ok && v != "" { + apiObject.LaunchTemplateId = aws.String(v.(string)) + } else if v, ok := tfMap["launch_template_name"]; ok && v != "" { + apiObject.LaunchTemplateName = aws.String(v.(string)) } + + if v, ok := tfMap["version"].(string); ok && v != "" { + apiObject.Version = aws.String(v) + } + + return apiObject } -func getGroupWarmPool(asgName string, conn *autoscaling.AutoScaling) (*autoscaling.DescribeWarmPoolOutput, error) { - describeOpts := autoscaling.DescribeWarmPoolInput{ - AutoScalingGroupName: aws.String(asgName), +func expandLaunchTemplateSpecification(tfMap map[string]interface{}) *autoscaling.LaunchTemplateSpecification { + if tfMap == nil { + return nil } - log.Printf("[DEBUG] Warm Pool describe configuration input: %#v", describeOpts) - describeWarmPoolOutput, err := conn.DescribeWarmPool(&describeOpts) - if err != nil { - if tfawserr.ErrCodeEquals(err, "InvalidGroup.NotFound") { - return nil, nil - } + apiObject := &autoscaling.LaunchTemplateSpecification{} + + // DescribeAutoScalingGroups returns both name and id but LaunchTemplateSpecification + // allows only one of them to be set. + if v, ok := tfMap["id"]; ok && v != "" { + apiObject.LaunchTemplateId = aws.String(v.(string)) + } else if v, ok := tfMap["name"]; ok && v != "" { + apiObject.LaunchTemplateName = aws.String(v.(string)) + } - return nil, fmt.Errorf("error retrieving Warm Pool: %s", err) + if v, ok := tfMap["version"].(string); ok && v != "" { + apiObject.Version = aws.String(v) } - return describeWarmPoolOutput, nil + return apiObject } -func resourceGroupWarmPoolDrain(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*conns.AWSClient).AutoScalingConn +func expandMixedInstancesPolicy(tfMap map[string]interface{}) *autoscaling.MixedInstancesPolicy { + if tfMap == nil { + return nil + } + + apiObject := &autoscaling.MixedInstancesPolicy{} + + if v, ok := tfMap["instances_distribution"].([]interface{}); ok && len(v) > 0 { + apiObject.InstancesDistribution = expandInstancesDistribution(v[0].(map[string]interface{})) + } + + if v, ok := tfMap["launch_template"].([]interface{}); ok && len(v) > 0 { + apiObject.LaunchTemplate = expandLaunchTemplate(v[0].(map[string]interface{})) + } + + return apiObject +} - if d.Get("force_delete").(bool) || d.Get("force_delete_warm_pool").(bool) { - log.Printf("[DEBUG] Skipping Warm pool drain, force delete was set.") +func expandPutLifecycleHookInput(name string, tfMap map[string]interface{}) *autoscaling.PutLifecycleHookInput { + if tfMap == nil { return nil } - // First, set the max group prepared capacity and min size to zero for the pool to drain - log.Printf("[DEBUG] Reducing Warm pool capacity to zero") - opts := autoscaling.PutWarmPoolInput{ - AutoScalingGroupName: aws.String(d.Id()), - MaxGroupPreparedCapacity: aws.Int64(0), - MinSize: aws.Int64(0), + apiObject := &autoscaling.PutLifecycleHookInput{ + AutoScalingGroupName: aws.String(name), } - if _, err := conn.PutWarmPool(&opts); err != nil { - return fmt.Errorf("error setting capacity to zero to drain: %s", err) + + if v, ok := tfMap["default_result"].(string); ok && v != "" { + apiObject.DefaultResult = aws.String(v) } - // Next, wait for the Warm Pool to drain - log.Printf("[DEBUG] Waiting for warm pool to have zero instances") - var p *autoscaling.DescribeWarmPoolOutput - err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - p, err := getGroupWarmPool(d.Id(), conn) - if err != nil { - return resource.NonRetryableError(err) - } + if v, ok := tfMap["heartbeat_timeout"].(int); ok && v != 0 { + apiObject.HeartbeatTimeout = aws.Int64(int64(v)) + } - if len(p.Instances) == 0 { - return nil - } + if v, ok := tfMap["name"].(string); ok && v != "" { + apiObject.LifecycleHookName = aws.String(v) + } - return resource.RetryableError( - fmt.Errorf("Warm pool still has %d instances", len(p.Instances))) - }) + if v, ok := tfMap["lifecycle_transition"].(string); ok && v != "" { + apiObject.LifecycleTransition = aws.String(v) + } - if tfresource.TimedOut(err) { - p, err = getGroupWarmPool(d.Id(), conn) - if err != nil { - return fmt.Errorf("error getting Warm Pool info when draining Auto Scaling Group %s: %s", d.Id(), err) - } - if p != nil && len(p.Instances) > 0 { - return fmt.Errorf("Warm pool still has %d instances", len(p.Instances)) - } + if v, ok := tfMap["notification_metadata"].(string); ok && v != "" { + apiObject.NotificationMetadata = aws.String(v) } - if err != nil { - return fmt.Errorf("error draining Warm pool: %s", err) + + if v, ok := tfMap["notification_target_arn"].(string); ok && v != "" { + apiObject.NotificationTargetARN = aws.String(v) } - return nil + + if v, ok := tfMap["role_arn"].(string); ok && v != "" { + apiObject.RoleARN = aws.String(v) + } + + return apiObject } -// TODO: make this a finder -// TODO: this should return a NotFoundError if not found -func getGroup(asgName string, conn *autoscaling.AutoScaling) (*autoscaling.Group, error) { - describeOpts := autoscaling.DescribeAutoScalingGroupsInput{ - AutoScalingGroupNames: []*string{aws.String(asgName)}, +func expandPutLifecycleHookInputs(name string, tfList []interface{}) []*autoscaling.PutLifecycleHookInput { + if len(tfList) == 0 { + return nil } - log.Printf("[DEBUG] Auto Scaling Group describe configuration: %#v", describeOpts) - describeGroups, err := conn.DescribeAutoScalingGroups(&describeOpts) - if err != nil { - if tfawserr.ErrCodeEquals(err, "InvalidGroup.NotFound") { - return nil, nil + var apiObjects []*autoscaling.PutLifecycleHookInput + + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]interface{}) + + if !ok { + continue } - return nil, fmt.Errorf("Error retrieving Auto Scaling Groups: %s", err) - } + apiObject := expandPutLifecycleHookInput(name, tfMap) - // Search for the Auto Scaling Group - for idx, asc := range describeGroups.AutoScalingGroups { - if asc == nil { + if apiObject == nil { continue } - if aws.StringValue(asc.AutoScalingGroupName) == asgName { - return describeGroups.AutoScalingGroups[idx], nil - } + apiObjects = append(apiObjects, apiObject) } - return nil, nil + return apiObjects } -func resourceGroupDrain(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*conns.AWSClient).AutoScalingConn - - if d.Get("force_delete").(bool) { - log.Printf("[DEBUG] Skipping Auto Scaling Group drain, force_delete was set.") +func expandPutWarmPoolInput(name string, tfMap map[string]interface{}) *autoscaling.PutWarmPoolInput { + if tfMap == nil { return nil } - // First, set the capacity to zero so the group will drain - log.Printf("[DEBUG] Reducing Auto Scaling Group capacity to zero") - opts := autoscaling.UpdateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String(d.Id()), - DesiredCapacity: aws.Int64(0), - MinSize: aws.Int64(0), - MaxSize: aws.Int64(0), + apiObject := &autoscaling.PutWarmPoolInput{ + AutoScalingGroupName: aws.String(name), } - if _, err := conn.UpdateAutoScalingGroup(&opts); err != nil { - return fmt.Errorf("Error setting capacity to zero to drain: %s", err) + + if v, ok := tfMap["instance_reuse_policy"].([]interface{}); ok && len(v) > 0 { + apiObject.InstanceReusePolicy = expandInstanceReusePolicy(v[0].(map[string]interface{})) } - // Next, ensure that instances are not prevented from scaling in. - // - // The ASG's own scale-in protection setting doesn't make a difference here, - // as it only affects new instances, which won't be launched now that the - // desired capacity is set to 0. There is also the possibility that this ASG - // no longer applies scale-in protection to new instances, but there's still - // old ones that have it. - log.Printf("[DEBUG] Disabling scale-in protection for all instances in the group") - if err := disableASGScaleInProtections(d, conn); err != nil { - return fmt.Errorf("Error disabling scale-in protection for all instances: %s", err) + if v, ok := tfMap["max_group_prepared_capacity"].(int); ok && v != 0 { + apiObject.MaxGroupPreparedCapacity = aws.Int64(int64(v)) } - // Next, wait for the Auto Scaling Group to drain - log.Printf("[DEBUG] Waiting for group to have zero instances") - var g *autoscaling.Group - err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - g, err := getGroup(d.Id(), conn) - if err != nil { - return resource.NonRetryableError(err) - } - if g == nil { - return nil - } + if v, ok := tfMap["min_size"].(int); ok && v != 0 { + apiObject.MinSize = aws.Int64(int64(v)) + } - if len(g.Instances) == 0 { - return nil - } + if v, ok := tfMap["pool_state"].(string); ok && v != "" { + apiObject.PoolState = aws.String(v) + } - return resource.RetryableError( - fmt.Errorf("Group still has %d instances", len(g.Instances))) - }) - if tfresource.TimedOut(err) { - g, err = getGroup(d.Id(), conn) - if err != nil { - return fmt.Errorf("Error getting Auto Scaling Group info when draining: %s", err) - } - if g != nil && len(g.Instances) > 0 { - return fmt.Errorf("Group still has %d instances", len(g.Instances)) - } + return apiObject +} + +func expandInstanceReusePolicy(tfMap map[string]interface{}) *autoscaling.InstanceReusePolicy { + if tfMap == nil { + return nil } - if err != nil { - return fmt.Errorf("Error draining Auto Scaling Group: %s", err) + + apiObject := &autoscaling.InstanceReusePolicy{} + + if v, ok := tfMap["reuse_on_scale_in"].(bool); ok { + apiObject.ReuseOnScaleIn = aws.Bool(v) } - return nil + + return apiObject } -func enableASGSuspendedProcesses(d *schema.ResourceData, conn *autoscaling.AutoScaling) error { - props := &autoscaling.ScalingProcessQuery{ - AutoScalingGroupName: aws.String(d.Id()), - ScalingProcesses: flex.ExpandStringSet(d.Get("suspended_processes").(*schema.Set)), +func expandStartInstanceRefreshInput(name string, tfMap map[string]interface{}) *autoscaling.StartInstanceRefreshInput { + if tfMap == nil { + return nil } - _, err := conn.SuspendProcesses(props) - return err -} + apiObject := &autoscaling.StartInstanceRefreshInput{ + AutoScalingGroupName: aws.String(name), + } -func enableASGMetricsCollection(d *schema.ResourceData, conn *autoscaling.AutoScaling) error { - props := &autoscaling.EnableMetricsCollectionInput{ - AutoScalingGroupName: aws.String(d.Id()), - Granularity: aws.String(d.Get("metrics_granularity").(string)), - Metrics: flex.ExpandStringSet(d.Get("enabled_metrics").(*schema.Set)), + if v, ok := tfMap["preferences"].([]interface{}); ok && len(v) > 0 { + apiObject.Preferences = expandRefreshPreferences(v[0].(map[string]interface{})) } - log.Printf("[INFO] Enabling metrics collection for the Auto Scaling Group: %s", d.Id()) - _, metricsErr := conn.EnableMetricsCollection(props) - return metricsErr + if v, ok := tfMap["strategy"].(string); ok && v != "" { + apiObject.Strategy = aws.String(v) + } + return apiObject } -func updateASGSuspendedProcesses(d *schema.ResourceData, conn *autoscaling.AutoScaling) error { - o, n := d.GetChange("suspended_processes") - if o == nil { - o = new(schema.Set) - } - if n == nil { - n = new(schema.Set) +func expandRefreshPreferences(tfMap map[string]interface{}) *autoscaling.RefreshPreferences { + if tfMap == nil { + return nil } - os := o.(*schema.Set) - ns := n.(*schema.Set) + apiObject := &autoscaling.RefreshPreferences{} - resumeProcesses := os.Difference(ns) - if resumeProcesses.Len() != 0 { - props := &autoscaling.ScalingProcessQuery{ - AutoScalingGroupName: aws.String(d.Id()), - ScalingProcesses: flex.ExpandStringSet(resumeProcesses), + if v, ok := tfMap["checkpoint_delay"].(string); ok { + if v, null, _ := nullable.Int(v).Value(); !null { + apiObject.CheckpointDelay = aws.Int64(v) } + } - _, err := conn.ResumeProcesses(props) - if err != nil { - return fmt.Errorf("Error Resuming Processes for Auto Scaling Group %q: %s", d.Id(), err) - } + if v, ok := tfMap["checkpoint_percentages"].([]interface{}); ok && len(v) > 0 { + apiObject.CheckpointPercentages = flex.ExpandInt64List(v) } - suspendedProcesses := ns.Difference(os) - if suspendedProcesses.Len() != 0 { - props := &autoscaling.ScalingProcessQuery{ - AutoScalingGroupName: aws.String(d.Id()), - ScalingProcesses: flex.ExpandStringSet(suspendedProcesses), + if v, ok := tfMap["instance_warmup"].(string); ok { + if v, null, _ := nullable.Int(v).Value(); !null { + apiObject.InstanceWarmup = aws.Int64(v) } + } - _, err := conn.SuspendProcesses(props) - if err != nil { - return fmt.Errorf("Error Suspending Processes for Auto Scaling Group %q: %s", d.Id(), err) - } + if v, ok := tfMap["min_healthy_percentage"].(int); ok { + apiObject.MinHealthyPercentage = aws.Int64(int64(v)) } - return nil + if v, ok := tfMap["skip_matching"].(bool); ok { + apiObject.SkipMatching = aws.Bool(v) + } + return apiObject } -func updateASGMetricsCollection(d *schema.ResourceData, conn *autoscaling.AutoScaling) error { +func expandVPCZoneIdentifiers(tfList []interface{}) *string { + vpcZoneIDs := make([]string, len(tfList)) - o, n := d.GetChange("enabled_metrics") - if o == nil { - o = new(schema.Set) + for i, v := range tfList { + vpcZoneIDs[i] = v.(string) } - if n == nil { - n = new(schema.Set) - } - - os := o.(*schema.Set) - ns := n.(*schema.Set) - disableMetrics := os.Difference(ns) - if disableMetrics.Len() != 0 { - props := &autoscaling.DisableMetricsCollectionInput{ - AutoScalingGroupName: aws.String(d.Id()), - Metrics: flex.ExpandStringSet(disableMetrics), - } + return aws.String(strings.Join(vpcZoneIDs, ",")) +} - _, err := conn.DisableMetricsCollection(props) - if err != nil { - return fmt.Errorf("Failure to Disable metrics collection types for Auto Scaling Group %s: %s", d.Id(), err) - } - } +func flattenEnabledMetrics(apiObjects []*autoscaling.EnabledMetric) []string { + var tfList []string - enabledMetrics := ns.Difference(os) - if enabledMetrics.Len() != 0 { - props := &autoscaling.EnableMetricsCollectionInput{ - AutoScalingGroupName: aws.String(d.Id()), - Metrics: flex.ExpandStringSet(enabledMetrics), - Granularity: aws.String(d.Get("metrics_granularity").(string)), + for _, apiObject := range apiObjects { + if apiObject == nil { + continue } - _, err := conn.EnableMetricsCollection(props) - if err != nil { - return fmt.Errorf("Failure to Enable metrics collection types for Auto Scaling Group %s: %s", d.Id(), err) + if v := apiObject.Metric; v != nil { + tfList = append(tfList, aws.StringValue(v)) } } - return nil + return tfList } -// getELBInstanceStates returns a mapping of the instance states of all the ELBs attached to the -// provided ASG. -// -// Note that this is the instance state function for ELB Classic. -// -// Nested like: lbName -> instanceId -> instanceState -func getELBInstanceStates(g *autoscaling.Group, meta interface{}) (map[string]map[string]string, error) { - lbInstanceStates := make(map[string]map[string]string) - conn := meta.(*conns.AWSClient).ELBConn - - for _, lbName := range g.LoadBalancerNames { - lbInstanceStates[aws.StringValue(lbName)] = make(map[string]string) - opts := &elb.DescribeInstanceHealthInput{LoadBalancerName: lbName} - r, err := conn.DescribeInstanceHealth(opts) - if err != nil { - return nil, err - } - for _, is := range r.InstanceStates { - if is == nil || is.InstanceId == nil || is.State == nil { - continue - } - lbInstanceStates[aws.StringValue(lbName)][aws.StringValue(is.InstanceId)] = aws.StringValue(is.State) - } +func flattenLaunchTemplateSpecification(apiObject *autoscaling.LaunchTemplateSpecification) map[string]interface{} { + if apiObject == nil { + return nil } - return lbInstanceStates, nil -} + tfMap := map[string]interface{}{} -// getTargetGroupInstanceStates returns a mapping of the instance states of -// all the ALB target groups attached to the provided ASG. -// -// Note that this is the instance state function for Application Load -// Balancing (aka ELBv2). -// -// Nested like: targetGroupARN -> instanceId -> instanceState -func getTargetGroupInstanceStates(g *autoscaling.Group, meta interface{}) (map[string]map[string]string, error) { - targetInstanceStates := make(map[string]map[string]string) - conn := meta.(*conns.AWSClient).ELBV2Conn + if v := apiObject.LaunchTemplateId; v != nil { + tfMap["id"] = aws.StringValue(v) + } - for _, targetGroupARN := range g.TargetGroupARNs { - targetInstanceStates[aws.StringValue(targetGroupARN)] = make(map[string]string) - opts := &elbv2.DescribeTargetHealthInput{TargetGroupArn: targetGroupARN} - r, err := conn.DescribeTargetHealth(opts) - if err != nil { - return nil, err - } - for _, desc := range r.TargetHealthDescriptions { - if desc == nil || desc.Target == nil || desc.Target.Id == nil || desc.TargetHealth == nil || desc.TargetHealth.State == nil { - continue - } - targetInstanceStates[aws.StringValue(targetGroupARN)][aws.StringValue(desc.Target.Id)] = aws.StringValue(desc.TargetHealth.State) - } + if v := apiObject.LaunchTemplateName; v != nil { + tfMap["name"] = aws.StringValue(v) + } + + if v := apiObject.Version; v != nil { + tfMap["version"] = aws.StringValue(v) } - return targetInstanceStates, nil + return tfMap } -func expandVpcZoneIdentifiers(list []interface{}) *string { - strs := make([]string, len(list)) - for i, s := range list { - strs[i] = s.(string) +func flattenMixedInstancesPolicy(apiObject *autoscaling.MixedInstancesPolicy) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.InstancesDistribution; v != nil { + tfMap["instances_distribution"] = []interface{}{flattenInstancesDistribution(v)} } - return aws.String(strings.Join(strs, ",")) + + if v := apiObject.LaunchTemplate; v != nil { + tfMap["launch_template"] = []interface{}{flattenLaunchTemplate(v)} + } + + return tfMap } -func expandInstancesDistribution(l []interface{}) *autoscaling.InstancesDistribution { - if len(l) == 0 || l[0] == nil { +func flattenInstancesDistribution(apiObject *autoscaling.InstancesDistribution) map[string]interface{} { + if apiObject == nil { return nil } - m := l[0].(map[string]interface{}) - - instancesDistribution := &autoscaling.InstancesDistribution{} + tfMap := map[string]interface{}{} - if v, ok := m["on_demand_allocation_strategy"]; ok && v.(string) != "" { - instancesDistribution.OnDemandAllocationStrategy = aws.String(v.(string)) + if v := apiObject.OnDemandAllocationStrategy; v != nil { + tfMap["on_demand_allocation_strategy"] = aws.StringValue(v) } - if v, ok := m["on_demand_base_capacity"]; ok { - instancesDistribution.OnDemandBaseCapacity = aws.Int64(int64(v.(int))) + if v := apiObject.OnDemandBaseCapacity; v != nil { + tfMap["on_demand_base_capacity"] = aws.Int64Value(v) } - if v, ok := m["on_demand_percentage_above_base_capacity"]; ok { - instancesDistribution.OnDemandPercentageAboveBaseCapacity = aws.Int64(int64(v.(int))) + if v := apiObject.OnDemandPercentageAboveBaseCapacity; v != nil { + tfMap["on_demand_percentage_above_base_capacity"] = aws.Int64Value(v) } - if v, ok := m["spot_allocation_strategy"]; ok && v.(string) != "" { - instancesDistribution.SpotAllocationStrategy = aws.String(v.(string)) + if v := apiObject.SpotAllocationStrategy; v != nil { + tfMap["spot_allocation_strategy"] = aws.StringValue(v) } - if v, ok := m["spot_instance_pools"]; ok && v.(int) != 0 { - instancesDistribution.SpotInstancePools = aws.Int64(int64(v.(int))) + if v := apiObject.SpotInstancePools; v != nil { + tfMap["spot_instance_pools"] = aws.Int64Value(v) } - if v, ok := m["spot_max_price"]; ok { - instancesDistribution.SpotMaxPrice = aws.String(v.(string)) + if v := apiObject.SpotMaxPrice; v != nil { + tfMap["spot_max_price"] = aws.StringValue(v) } - return instancesDistribution + return tfMap } -func expandMixedInstancesLaunchTemplate(l []interface{}) *autoscaling.LaunchTemplate { - if len(l) == 0 || l[0] == nil { +func flattenLaunchTemplate(apiObject *autoscaling.LaunchTemplate) map[string]interface{} { + if apiObject == nil { return nil } - m := l[0].(map[string]interface{}) + tfMap := map[string]interface{}{} - launchTemplate := &autoscaling.LaunchTemplate{ - LaunchTemplateSpecification: expandMixedInstancesLaunchTemplateSpecification(m["launch_template_specification"].([]interface{})), + if v := apiObject.LaunchTemplateSpecification; v != nil { + tfMap["launch_template_specification"] = []interface{}{flattenLaunchTemplateSpecificationForMixedInstancesPolicy(v)} } - if v, ok := m["override"]; ok { - launchTemplate.Overrides = expandLaunchTemplateOverrides(v.([]interface{})) + if v := apiObject.Overrides; v != nil { + tfMap["override"] = flattenLaunchTemplateOverrideses(v) } - return launchTemplate + return tfMap } -func expandLaunchTemplateOverrides(l []interface{}) []*autoscaling.LaunchTemplateOverrides { - if len(l) == 0 { +func flattenLaunchTemplateSpecificationForMixedInstancesPolicy(apiObject *autoscaling.LaunchTemplateSpecification) map[string]interface{} { + if apiObject == nil { return nil } - launchTemplateOverrides := make([]*autoscaling.LaunchTemplateOverrides, len(l)) - for i, m := range l { - if m == nil { - launchTemplateOverrides[i] = &autoscaling.LaunchTemplateOverrides{} - continue - } - - launchTemplateOverrides[i] = expandLaunchTemplateOverride(m.(map[string]interface{})) - } - return launchTemplateOverrides -} - -func expandLaunchTemplateOverride(m map[string]interface{}) *autoscaling.LaunchTemplateOverrides { - launchTemplateOverrides := &autoscaling.LaunchTemplateOverrides{} + tfMap := map[string]interface{}{} - if v, ok := m["instance_type"]; ok && v.(string) != "" { - launchTemplateOverrides.InstanceType = aws.String(v.(string)) + if v := apiObject.LaunchTemplateId; v != nil { + tfMap["launch_template_id"] = aws.StringValue(v) } - if v, ok := m["launch_template_specification"]; ok && v.([]interface{}) != nil { - launchTemplateOverrides.LaunchTemplateSpecification = expandMixedInstancesLaunchTemplateSpecification(m["launch_template_specification"].([]interface{})) + if v := apiObject.LaunchTemplateName; v != nil { + tfMap["launch_template_name"] = aws.StringValue(v) } - if v, ok := m["weighted_capacity"]; ok && v.(string) != "" { - launchTemplateOverrides.WeightedCapacity = aws.String(v.(string)) + if v := apiObject.Version; v != nil { + tfMap["version"] = aws.StringValue(v) } - return launchTemplateOverrides + return tfMap } -func expandMixedInstancesLaunchTemplateSpecification(l []interface{}) *autoscaling.LaunchTemplateSpecification { - launchTemplateSpecification := &autoscaling.LaunchTemplateSpecification{} - - if len(l) == 0 || l[0] == nil { - return launchTemplateSpecification +func flattenLaunchTemplateOverrides(apiObject *autoscaling.LaunchTemplateOverrides) map[string]interface{} { + if apiObject == nil { + return nil } - m := l[0].(map[string]interface{}) + tfMap := map[string]interface{}{} - if v, ok := m["launch_template_id"]; ok && v.(string) != "" { - launchTemplateSpecification.LaunchTemplateId = aws.String(v.(string)) + if v := apiObject.InstanceRequirements; v != nil { + tfMap["instance_requirements"] = []interface{}{flattenInstanceRequirements(v)} } - // API returns both ID and name, which Terraform saves to state. Next update returns: - // ValidationError: Valid requests must contain either launchTemplateId or LaunchTemplateName - // Prefer the ID if we have both. - if v, ok := m["launch_template_name"]; ok && v.(string) != "" && launchTemplateSpecification.LaunchTemplateId == nil { - launchTemplateSpecification.LaunchTemplateName = aws.String(v.(string)) + if v := apiObject.InstanceType; v != nil { + tfMap["instance_type"] = aws.StringValue(v) + } + + if v := apiObject.LaunchTemplateSpecification; v != nil { + tfMap["launch_template_specification"] = []interface{}{flattenLaunchTemplateSpecificationForMixedInstancesPolicy(v)} } - if v, ok := m["version"]; ok && v.(string) != "" { - launchTemplateSpecification.Version = aws.String(v.(string)) + if v := apiObject.WeightedCapacity; v != nil { + tfMap["weighted_capacity"] = aws.StringValue(v) } - return launchTemplateSpecification + return tfMap } -func expandMixedInstancesPolicy(l []interface{}) *autoscaling.MixedInstancesPolicy { - if len(l) == 0 || l[0] == nil { +func flattenLaunchTemplateOverrideses(apiObjects []*autoscaling.LaunchTemplateOverrides) []interface{} { + if len(apiObjects) == 0 { return nil } - m := l[0].(map[string]interface{}) + var tfList []interface{} - mixedInstancesPolicy := &autoscaling.MixedInstancesPolicy{ - LaunchTemplate: expandMixedInstancesLaunchTemplate(m["launch_template"].([]interface{})), - } + for _, apiObject := range apiObjects { + if apiObject == nil { + continue + } - if v, ok := m["instances_distribution"]; ok { - mixedInstancesPolicy.InstancesDistribution = expandInstancesDistribution(v.([]interface{})) + tfList = append(tfList, flattenLaunchTemplateOverrides(apiObject)) } - return mixedInstancesPolicy + return tfList } -func flattenInstancesDistribution(instancesDistribution *autoscaling.InstancesDistribution) []interface{} { - if instancesDistribution == nil { - return []interface{}{} +func flattenInstanceRequirements(apiObject *autoscaling.InstanceRequirements) map[string]interface{} { + if apiObject == nil { + return nil } - m := map[string]interface{}{ - "on_demand_allocation_strategy": aws.StringValue(instancesDistribution.OnDemandAllocationStrategy), - "on_demand_base_capacity": aws.Int64Value(instancesDistribution.OnDemandBaseCapacity), - "on_demand_percentage_above_base_capacity": aws.Int64Value(instancesDistribution.OnDemandPercentageAboveBaseCapacity), - "spot_allocation_strategy": aws.StringValue(instancesDistribution.SpotAllocationStrategy), - "spot_instance_pools": aws.Int64Value(instancesDistribution.SpotInstancePools), - "spot_max_price": aws.StringValue(instancesDistribution.SpotMaxPrice), + tfMap := map[string]interface{}{} + + if v := apiObject.AcceleratorCount; v != nil { + tfMap["accelerator_count"] = []interface{}{flattenAcceleratorCount(v)} } - return []interface{}{m} -} + if v := apiObject.AcceleratorManufacturers; v != nil { + tfMap["accelerator_manufacturers"] = aws.StringValueSlice(v) + } -func flattenLaunchTemplate(launchTemplate *autoscaling.LaunchTemplate) []interface{} { - if launchTemplate == nil { - return []interface{}{} + if v := apiObject.AcceleratorNames; v != nil { + tfMap["accelerator_names"] = aws.StringValueSlice(v) } - m := map[string]interface{}{ - "launch_template_specification": flattenLaunchTemplateSpecification(launchTemplate.LaunchTemplateSpecification), - "override": flattenLaunchTemplateOverrides(launchTemplate.Overrides), + if v := apiObject.AcceleratorTotalMemoryMiB; v != nil { + tfMap["accelerator_total_memory_mib"] = []interface{}{flattenAcceleratorTotalMemoryMiB(v)} } - return []interface{}{m} -} + if v := apiObject.AcceleratorTypes; v != nil { + tfMap["accelerator_types"] = aws.StringValueSlice(v) + } -func flattenLaunchTemplateOverrides(launchTemplateOverrides []*autoscaling.LaunchTemplateOverrides) []interface{} { - l := make([]interface{}, len(launchTemplateOverrides)) + if v := apiObject.BareMetal; v != nil { + tfMap["bare_metal"] = aws.StringValue(v) + } - for i, launchTemplateOverride := range launchTemplateOverrides { - if launchTemplateOverride == nil { - l[i] = map[string]interface{}{} - continue - } - m := map[string]interface{}{ - "instance_type": aws.StringValue(launchTemplateOverride.InstanceType), - "launch_template_specification": flattenLaunchTemplateSpecification(launchTemplateOverride.LaunchTemplateSpecification), - "weighted_capacity": aws.StringValue(launchTemplateOverride.WeightedCapacity), - } - l[i] = m + if v := apiObject.BaselineEbsBandwidthMbps; v != nil { + tfMap["baseline_ebs_bandwidth_mbps"] = []interface{}{flattenBaselineEBSBandwidthMbps(v)} } - return l -} + if v := apiObject.BurstablePerformance; v != nil { + tfMap["burstable_performance"] = aws.StringValue(v) + } -func flattenLaunchTemplateSpecification(launchTemplateSpecification *autoscaling.LaunchTemplateSpecification) []interface{} { - if launchTemplateSpecification == nil { - return []interface{}{} + if v := apiObject.CpuManufacturers; v != nil { + tfMap["cpu_manufacturers"] = aws.StringValueSlice(v) } - m := map[string]interface{}{ - "launch_template_id": aws.StringValue(launchTemplateSpecification.LaunchTemplateId), - "launch_template_name": aws.StringValue(launchTemplateSpecification.LaunchTemplateName), - "version": aws.StringValue(launchTemplateSpecification.Version), + if v := apiObject.ExcludedInstanceTypes; v != nil { + tfMap["excluded_instance_types"] = aws.StringValueSlice(v) } - return []interface{}{m} -} + if v := apiObject.InstanceGenerations; v != nil { + tfMap["instance_generations"] = aws.StringValueSlice(v) + } -func flattenMixedInstancesPolicy(mixedInstancesPolicy *autoscaling.MixedInstancesPolicy) []interface{} { - if mixedInstancesPolicy == nil { - return []interface{}{} + if v := apiObject.LocalStorage; v != nil { + tfMap["local_storage"] = aws.StringValue(v) } - m := map[string]interface{}{ - "instances_distribution": flattenInstancesDistribution(mixedInstancesPolicy.InstancesDistribution), - "launch_template": flattenLaunchTemplate(mixedInstancesPolicy.LaunchTemplate), + if v := apiObject.LocalStorageTypes; v != nil { + tfMap["local_storage_types"] = aws.StringValueSlice(v) } - return []interface{}{m} -} + if v := apiObject.MemoryGiBPerVCpu; v != nil { + tfMap["memory_gib_per_vcpu"] = []interface{}{flattenMemoryGiBPerVCPU(v)} + } -func FlattenWarmPoolConfiguration(warmPoolConfiguration *autoscaling.WarmPoolConfiguration) []interface{} { - if warmPoolConfiguration == nil { - return []interface{}{} + if v := apiObject.MemoryMiB; v != nil { + tfMap["memory_mib"] = []interface{}{flattenMemoryMiB(v)} } - maxGroupPreparedCapacity := int64(-1) - if warmPoolConfiguration.MaxGroupPreparedCapacity != nil { - maxGroupPreparedCapacity = aws.Int64Value(warmPoolConfiguration.MaxGroupPreparedCapacity) + if v := apiObject.NetworkInterfaceCount; v != nil { + tfMap["network_interface_count"] = []interface{}{flattenNetworkInterfaceCount(v)} } - m := map[string]interface{}{ - "pool_state": aws.StringValue(warmPoolConfiguration.PoolState), - "min_size": aws.Int64Value(warmPoolConfiguration.MinSize), - "max_group_prepared_capacity": maxGroupPreparedCapacity, + if v := apiObject.OnDemandMaxPricePercentageOverLowestPrice; v != nil { + tfMap["on_demand_max_price_percentage_over_lowest_price"] = aws.Int64Value(v) } - if warmPoolConfiguration.InstanceReusePolicy != nil { - m["instance_reuse_policy"] = flattenWarmPoolInstanceReusePolicy(warmPoolConfiguration.InstanceReusePolicy) + if v := apiObject.RequireHibernateSupport; v != nil { + tfMap["require_hibernate_support"] = aws.BoolValue(v) } - return []interface{}{m} -} + if v := apiObject.SpotMaxPricePercentageOverLowestPrice; v != nil { + tfMap["spot_max_price_percentage_over_lowest_price"] = aws.Int64Value(v) + } -func flattenWarmPoolInstanceReusePolicy(instanceReusePolicy *autoscaling.InstanceReusePolicy) []interface{} { - if instanceReusePolicy == nil { - return []interface{}{} + if v := apiObject.TotalLocalStorageGB; v != nil { + tfMap["total_local_storage_gb"] = []interface{}{flattentTotalLocalStorageGB(v)} } - m := map[string]interface{}{ - "reuse_on_scale_in": aws.BoolValue(instanceReusePolicy.ReuseOnScaleIn), + if v := apiObject.VCpuCount; v != nil { + tfMap["vcpu_count"] = []interface{}{flattenVCPUCount(v)} } - return []interface{}{m} + return tfMap } -func waitUntilGroupLoadBalancersAdded(conn *autoscaling.AutoScaling, asgName string) error { - input := &autoscaling.DescribeLoadBalancersInput{ - AutoScalingGroupName: aws.String(asgName), +func flattenAcceleratorCount(apiObject *autoscaling.AcceleratorCountRequest) map[string]interface{} { + if apiObject == nil { + return nil } - var lbAdding bool - - for { - output, err := conn.DescribeLoadBalancers(input) - if err != nil { - return err - } + tfMap := map[string]interface{}{} - for _, tg := range output.LoadBalancers { - if aws.StringValue(tg.State) == "Adding" { - lbAdding = true - break - } - } + if v := apiObject.Max; v != nil { + tfMap["max"] = aws.Int64Value(v) + } - if lbAdding { - lbAdding = false - input.NextToken = nil - continue - } + if v := apiObject.Min; v != nil { + tfMap["min"] = aws.Int64Value(v) + } - if aws.StringValue(output.NextToken) == "" { - break - } + return tfMap +} - input.NextToken = output.NextToken +func flattenAcceleratorTotalMemoryMiB(apiObject *autoscaling.AcceleratorTotalMemoryMiBRequest) map[string]interface{} { + if apiObject == nil { + return nil } - return nil -} + tfMap := map[string]interface{}{} -func waitUntilGroupLoadBalancersRemoved(conn *autoscaling.AutoScaling, asgName string) error { - input := &autoscaling.DescribeLoadBalancersInput{ - AutoScalingGroupName: aws.String(asgName), + if v := apiObject.Max; v != nil { + tfMap["max"] = aws.Int64Value(v) } - var lbRemoving bool - for { - output, err := conn.DescribeLoadBalancers(input) + if v := apiObject.Min; v != nil { + tfMap["min"] = aws.Int64Value(v) + } - if err != nil { - return err - } + return tfMap +} - for _, tg := range output.LoadBalancers { - if aws.StringValue(tg.State) == "Removing" { - lbRemoving = true - break - } - } +func flattenBaselineEBSBandwidthMbps(apiObject *autoscaling.BaselineEbsBandwidthMbpsRequest) map[string]interface{} { + if apiObject == nil { + return nil + } - if lbRemoving { - lbRemoving = false - input.NextToken = nil - continue - } + tfMap := map[string]interface{}{} - if aws.StringValue(output.NextToken) == "" { - break - } + if v := apiObject.Max; v != nil { + tfMap["max"] = aws.Int64Value(v) + } - input.NextToken = output.NextToken + if v := apiObject.Min; v != nil { + tfMap["min"] = aws.Int64Value(v) } - return nil + return tfMap } -func CreatePutWarmPoolInput(asgName string, l []interface{}) *autoscaling.PutWarmPoolInput { - if len(l) == 0 || l[0] == nil { +func flattenMemoryGiBPerVCPU(apiObject *autoscaling.MemoryGiBPerVCpuRequest) map[string]interface{} { + if apiObject == nil { return nil } - m := l[0].(map[string]interface{}) + tfMap := map[string]interface{}{} - input := autoscaling.PutWarmPoolInput{ - AutoScalingGroupName: aws.String(asgName), + if v := apiObject.Max; v != nil { + tfMap["max"] = aws.Float64Value(v) } - if v, ok := m["pool_state"]; ok && v.(string) != "" { - input.PoolState = aws.String(v.(string)) + if v := apiObject.Min; v != nil { + tfMap["min"] = aws.Float64Value(v) } - if v, ok := m["min_size"]; ok && v.(int) > -1 { - input.MinSize = aws.Int64(int64(v.(int))) + return tfMap +} + +func flattenMemoryMiB(apiObject *autoscaling.MemoryMiBRequest) map[string]interface{} { + if apiObject == nil { + return nil } - if v, ok := m["max_group_prepared_capacity"]; ok && v.(int) > -2 { - input.MaxGroupPreparedCapacity = aws.Int64(int64(v.(int))) + tfMap := map[string]interface{}{} + + if v := apiObject.Max; v != nil { + tfMap["max"] = aws.Int64Value(v) } - if v, ok := m["instance_reuse_policy"]; ok && len(v.([]interface{})) > 0 { - input.InstanceReusePolicy = expandWarmPoolInstanceReusePolicy(v.([]interface{})) + if v := apiObject.Min; v != nil { + tfMap["min"] = aws.Int64Value(v) } - return &input + return tfMap } -func CreateGroupInstanceRefreshInput(asgName string, l []interface{}) *autoscaling.StartInstanceRefreshInput { - if len(l) == 0 || l[0] == nil { +func flattenNetworkInterfaceCount(apiObject *autoscaling.NetworkInterfaceCountRequest) map[string]interface{} { + if apiObject == nil { return nil } - m := l[0].(map[string]interface{}) + tfMap := map[string]interface{}{} - return &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String(m["strategy"].(string)), - Preferences: expandGroupInstanceRefreshPreferences(m["preferences"].([]interface{})), + if v := apiObject.Max; v != nil { + tfMap["max"] = aws.Int64Value(v) + } + + if v := apiObject.Min; v != nil { + tfMap["min"] = aws.Int64Value(v) } + + return tfMap } -func expandGroupInstanceRefreshPreferences(l []interface{}) *autoscaling.RefreshPreferences { - if len(l) == 0 || l[0] == nil { +func flattentTotalLocalStorageGB(apiObject *autoscaling.TotalLocalStorageGBRequest) map[string]interface{} { + if apiObject == nil { return nil } - m := l[0].(map[string]interface{}) + tfMap := map[string]interface{}{} - refreshPreferences := &autoscaling.RefreshPreferences{} + if v := apiObject.Max; v != nil { + tfMap["max"] = aws.Float64Value(v) + } - if v, ok := m["checkpoint_delay"]; ok { - if v, null, _ := nullable.Int(v.(string)).Value(); !null { - refreshPreferences.CheckpointDelay = aws.Int64(v) - } + if v := apiObject.Min; v != nil { + tfMap["min"] = aws.Float64Value(v) } - if l, ok := m["checkpoint_percentages"].([]interface{}); ok && len(l) > 0 { - p := make([]*int64, len(l)) - for i, v := range l { - p[i] = aws.Int64(int64(v.(int))) - } - refreshPreferences.CheckpointPercentages = p + return tfMap +} + +func flattenVCPUCount(apiObject *autoscaling.VCpuCountRequest) map[string]interface{} { + if apiObject == nil { + return nil } - if v, ok := m["instance_warmup"]; ok { - if v, null, _ := nullable.Int(v.(string)).Value(); !null { - refreshPreferences.InstanceWarmup = aws.Int64(v) - } + tfMap := map[string]interface{}{} + + if v := apiObject.Max; v != nil { + tfMap["max"] = aws.Int64Value(v) + } + + if v := apiObject.Min; v != nil { + tfMap["min"] = aws.Int64Value(v) } - if v, ok := m["min_healthy_percentage"]; ok { - refreshPreferences.MinHealthyPercentage = aws.Int64(int64(v.(int))) + return tfMap +} + +func flattenSuspendedProcesses(apiObjects []*autoscaling.SuspendedProcess) []string { + if len(apiObjects) == 0 { + return nil } - if v, ok := m["skip_matching"]; ok { - refreshPreferences.SkipMatching = aws.Bool(v.(bool)) + var tfList []string + + for _, apiObject := range apiObjects { + if v := apiObject.ProcessName; v != nil { + tfList = append(tfList, aws.StringValue(v)) + } } - return refreshPreferences + return tfList } -func expandWarmPoolInstanceReusePolicy(l []interface{}) *autoscaling.InstanceReusePolicy { - if len(l) == 0 || l[0] == nil { +func flattenWarmPoolConfiguration(apiObject *autoscaling.WarmPoolConfiguration) map[string]interface{} { + if apiObject == nil { return nil } - m := l[0].(map[string]interface{}) + tfMap := map[string]interface{}{} + + if v := apiObject.InstanceReusePolicy; v != nil { + tfMap["instance_reuse_policy"] = []interface{}{flattenWarmPoolInstanceReusePolicy(v)} + } + + if v := apiObject.MaxGroupPreparedCapacity; v != nil { + tfMap["max_group_prepared_capacity"] = aws.Int64Value(v) + } else { + tfMap["max_group_prepared_capacity"] = int64(DefaultWarmPoolMaxGroupPreparedCapacity) + } - instanceReusePolicy := &autoscaling.InstanceReusePolicy{} + if v := apiObject.MinSize; v != nil { + tfMap["min_size"] = aws.Int64Value(v) + } - if v, ok := m["reuse_on_scale_in"]; ok { - instanceReusePolicy.ReuseOnScaleIn = aws.Bool(v.(bool)) + if v := apiObject.PoolState; v != nil { + tfMap["pool_state"] = aws.StringValue(v) } - return instanceReusePolicy + return tfMap } -func GroupRefreshInstances(conn *autoscaling.AutoScaling, asgName string, refreshConfig []interface{}) error { - input := CreateGroupInstanceRefreshInput(asgName, refreshConfig) - err := resource.Retry(instanceRefreshStartedTimeout, func() *resource.RetryError { - _, err := conn.StartInstanceRefresh(input) - if tfawserr.ErrCodeEquals(err, autoscaling.ErrCodeInstanceRefreshInProgressFault) { - cancelErr := cancelInstanceRefresh(conn, asgName) - if cancelErr != nil { - return resource.NonRetryableError(cancelErr) - } - return resource.RetryableError(err) - } - if err != nil { - return resource.NonRetryableError(err) - } +func flattenWarmPoolInstanceReusePolicy(apiObject *autoscaling.InstanceReusePolicy) map[string]interface{} { + if apiObject == nil { return nil - }) - if tfresource.TimedOut(err) { - _, err = conn.StartInstanceRefresh(input) } - if err != nil { - return fmt.Errorf("error starting Instance Refresh: %w", err) + + tfMap := map[string]interface{}{} + + if v := apiObject.ReuseOnScaleIn; v != nil { + tfMap["reuse_on_scale_in"] = aws.BoolValue(v) } - return nil + return tfMap } -func cancelInstanceRefresh(conn *autoscaling.AutoScaling, asgName string) error { - input := autoscaling.CancelInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), +func cancelInstanceRefresh(conn *autoscaling.AutoScaling, name string) error { + input := &autoscaling.CancelInstanceRefreshInput{ + AutoScalingGroupName: aws.String(name), } - output, err := conn.CancelInstanceRefresh(&input) + + output, err := conn.CancelInstanceRefresh(input) + if tfawserr.ErrCodeEquals(err, autoscaling.ErrCodeActiveInstanceRefreshNotFoundFault) { return nil } + if err != nil { - return fmt.Errorf("error cancelling Instance Refresh on Auto Scaling Group (%s): %w", asgName, err) + return fmt.Errorf("cancelling Auto Scaling Group (%s) instance refresh: %w", name, err) } - if output == nil { - return fmt.Errorf("error cancelling Instance Refresh on Auto Scaling Group (%s): empty result", asgName) + + _, err = waitInstanceRefreshCancelled(conn, name, aws.StringValue(output.InstanceRefreshId), instanceRefreshCancelledTimeout) + + if err != nil { + return fmt.Errorf("waiting for Auto Scaling Group (%s) instance refresh cancel: %w", name, err) } - _, err = waitInstanceRefreshCancelled(conn, asgName, aws.StringValue(output.InstanceRefreshId)) + return nil +} + +func startInstanceRefresh(conn *autoscaling.AutoScaling, input *autoscaling.StartInstanceRefreshInput) error { + name := aws.StringValue(input.AutoScalingGroupName) + + _, err := tfresource.RetryWhen(instanceRefreshStartedTimeout, + func() (interface{}, error) { + return conn.StartInstanceRefresh(input) + }, + func(err error) (bool, error) { + if tfawserr.ErrCodeEquals(err, autoscaling.ErrCodeInstanceRefreshInProgressFault) { + if err := cancelInstanceRefresh(conn, name); err != nil { + return false, err + } + + return true, err + } + + return false, err + }) + if err != nil { - return fmt.Errorf("error waiting for cancellation of Instance Refresh (%s) on Auto Scaling Group (%s): %w", aws.StringValue(output.InstanceRefreshId), asgName, err) + return fmt.Errorf("starting Auto Scaling Group (%s) instance refresh: %w", name, err) } return nil @@ -2383,91 +3327,3 @@ func validateGroupInstanceRefreshTriggerFields(i interface{}, path cty.Path) dia return diag.Errorf("'%s' is not a recognized parameter name for aws_autoscaling_group", v) } - -func expandLaunchTemplateSpecification(specs []interface{}) *autoscaling.LaunchTemplateSpecification { - if len(specs) < 1 { - return nil - } - - spec := specs[0].(map[string]interface{}) - - idValue, idOk := spec["id"] - nameValue, nameOk := spec["name"] - - result := &autoscaling.LaunchTemplateSpecification{} - - // DescribeAutoScalingGroups returns both name and id but LaunchTemplateSpecification - // allows only one of them to be set - if idOk && idValue != "" { - result.LaunchTemplateId = aws.String(idValue.(string)) - } else if nameOk && nameValue != "" { - result.LaunchTemplateName = aws.String(nameValue.(string)) - } - - if v, ok := spec["version"]; ok && v != "" { - result.Version = aws.String(v.(string)) - } - - return result -} - -func flattenLaunchTemplateSpecificationMap(lt *autoscaling.LaunchTemplateSpecification) []map[string]interface{} { - if lt == nil { - return []map[string]interface{}{} - } - - attrs := map[string]interface{}{} - result := make([]map[string]interface{}, 0) - - // id and name are always returned by DescribeAutoscalingGroups - attrs["id"] = aws.StringValue(lt.LaunchTemplateId) - attrs["name"] = aws.StringValue(lt.LaunchTemplateName) - - // version is returned only if it was previously set - if lt.Version != nil { - attrs["version"] = aws.StringValue(lt.Version) - } else { - attrs["version"] = nil - } - - result = append(result, attrs) - - return result -} - -// disableASGScaleInProtections disables scale-in protection for all instances -// in the given Auto-Scaling Group. -func disableASGScaleInProtections(d *schema.ResourceData, conn *autoscaling.AutoScaling) error { - g, err := getGroup(d.Id(), conn) - if err != nil { - return fmt.Errorf("Error getting group %s: %s", d.Id(), err) - } - - var instanceIds []string - for _, instance := range g.Instances { - if aws.BoolValue(instance.ProtectedFromScaleIn) { - instanceIds = append(instanceIds, aws.StringValue(instance.InstanceId)) - } - } - - const chunkSize = 50 // API limit - - for i := 0; i < len(instanceIds); i += chunkSize { - j := i + chunkSize - if j > len(instanceIds) { - j = len(instanceIds) - } - - input := autoscaling.SetInstanceProtectionInput{ - AutoScalingGroupName: aws.String(d.Id()), - InstanceIds: aws.StringSlice(instanceIds[i:j]), - ProtectedFromScaleIn: aws.Bool(false), - } - - if _, err := conn.SetInstanceProtection(&input); err != nil { - return fmt.Errorf("Error disabling scale-in protections: %s", err) - } - } - - return nil -} diff --git a/internal/service/autoscaling/group_data_source.go b/internal/service/autoscaling/group_data_source.go index a5c8b7a1557..88829470d88 100644 --- a/internal/service/autoscaling/group_data_source.go +++ b/internal/service/autoscaling/group_data_source.go @@ -2,10 +2,8 @@ package autoscaling import ( "fmt" - "log" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -80,14 +78,6 @@ func DataSourceGroup() *schema.Resource { Type: schema.TypeString, }, }, - "name": { - Type: schema.TypeString, - Required: true, - }, - "new_instances_protected_from_scale_in": { - Type: schema.TypeBool, - Computed: true, - }, "max_size": { Type: schema.TypeInt, Computed: true, @@ -96,6 +86,14 @@ func DataSourceGroup() *schema.Resource { Type: schema.TypeInt, Computed: true, }, + "name": { + Type: schema.TypeString, + Required: true, + }, + "new_instances_protected_from_scale_in": { + Type: schema.TypeBool, + Computed: true, + }, "placement_group": { Type: schema.TypeString, Computed: true, @@ -134,72 +132,38 @@ func dataSourceGroupRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).AutoScalingConn groupName := d.Get("name").(string) - - input := &autoscaling.DescribeAutoScalingGroupsInput{ - AutoScalingGroupNames: []*string{ - aws.String(groupName), - }, - } - - log.Printf("[DEBUG] Reading Autoscaling Group: %s", input) - - result, err := conn.DescribeAutoScalingGroups(input) - - log.Printf("[DEBUG] Checking for error: %s", err) + group, err := FindGroupByName(conn, groupName) if err != nil { - return fmt.Errorf("error describing AutoScaling Groups: %w", err) - } - - log.Printf("[DEBUG] Found Autoscaling Group: %s", result) - - if len(result.AutoScalingGroups) < 1 { - return fmt.Errorf("Your query did not return any results. Please try a different search criteria.") - } - - if len(result.AutoScalingGroups) > 1 { - return fmt.Errorf("Your query returned more than one result. Please try a more " + - "specific search criteria.") + return fmt.Errorf("reading Auto Scaling Group (%s): %w", groupName, err) } - // If execution made it to this point, we have exactly one 1 group returned - // and this is a safe operation - group := result.AutoScalingGroups[0] - - log.Printf("[DEBUG] aws_autoscaling_group - Single Auto Scaling Group found: %s", *group.AutoScalingGroupName) - d.SetId(aws.StringValue(group.AutoScalingGroupName)) - d.Set("name", group.AutoScalingGroupName) d.Set("arn", group.AutoScalingGroupARN) - if err := d.Set("availability_zones", aws.StringValueSlice(group.AvailabilityZones)); err != nil { - return fmt.Errorf("error setting availability_zones: %w", err) - } + d.Set("availability_zones", aws.StringValueSlice(group.AvailabilityZones)) d.Set("default_cooldown", group.DefaultCooldown) d.Set("desired_capacity", group.DesiredCapacity) - if err := d.Set("enabled_metrics", flattenASGEnabledMetrics(group.EnabledMetrics)); err != nil { - return fmt.Errorf("error setting enabled_metrics: %w", err) - } + d.Set("enabled_metrics", flattenEnabledMetrics(group.EnabledMetrics)) d.Set("health_check_grace_period", group.HealthCheckGracePeriod) d.Set("health_check_type", group.HealthCheckType) d.Set("launch_configuration", group.LaunchConfigurationName) - if err := d.Set("launch_template", flattenLaunchTemplateSpecificationMap(group.LaunchTemplate)); err != nil { - return fmt.Errorf("error setting launch_template: %w", err) + if group.LaunchTemplate != nil { + if err := d.Set("launch_template", []interface{}{flattenLaunchTemplateSpecification(group.LaunchTemplate)}); err != nil { + return fmt.Errorf("setting launch_template: %w", err) + } + } else { + d.Set("launch_template", nil) } - if err := d.Set("load_balancers", aws.StringValueSlice(group.LoadBalancerNames)); err != nil { - return fmt.Errorf("error setting load_balancers: %w", err) - } - d.Set("new_instances_protected_from_scale_in", group.NewInstancesProtectedFromScaleIn) + d.Set("load_balancers", aws.StringValueSlice(group.LoadBalancerNames)) d.Set("max_size", group.MaxSize) d.Set("min_size", group.MinSize) + d.Set("name", group.AutoScalingGroupName) + d.Set("new_instances_protected_from_scale_in", group.NewInstancesProtectedFromScaleIn) d.Set("placement_group", group.PlacementGroup) d.Set("service_linked_role_arn", group.ServiceLinkedRoleARN) d.Set("status", group.Status) - if err := d.Set("target_group_arns", aws.StringValueSlice(group.TargetGroupARNs)); err != nil { - return fmt.Errorf("error setting target_group_arns: %w", err) - } - if err := d.Set("termination_policies", aws.StringValueSlice(group.TerminationPolicies)); err != nil { - return fmt.Errorf("error setting termination_policies: %w", err) - } + d.Set("target_group_arns", aws.StringValueSlice(group.TargetGroupARNs)) + d.Set("termination_policies", aws.StringValueSlice(group.TerminationPolicies)) d.Set("vpc_zone_identifier", group.VPCZoneIdentifier) return nil diff --git a/internal/service/autoscaling/group_data_source_test.go b/internal/service/autoscaling/group_data_source_test.go index 9409a1e2fbe..6b81785b148 100644 --- a/internal/service/autoscaling/group_data_source_test.go +++ b/internal/service/autoscaling/group_data_source_test.go @@ -12,7 +12,7 @@ import ( func TestAccAutoScalingGroupDataSource_basic(t *testing.T) { datasourceName := "data.aws_autoscaling_group.test" - resourceName := "aws_autoscaling_group.match" + resourceName := "aws_autoscaling_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ @@ -22,8 +22,7 @@ func TestAccAutoScalingGroupDataSource_basic(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccGroupDataSourceConfig_basic(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "availability_zones.#", resourceName, "availability_zones.#"), resource.TestCheckResourceAttrPair(datasourceName, "default_cooldown", resourceName, "default_cooldown"), @@ -32,13 +31,18 @@ func TestAccAutoScalingGroupDataSource_basic(t *testing.T) { resource.TestCheckResourceAttrPair(datasourceName, "health_check_grace_period", resourceName, "health_check_grace_period"), resource.TestCheckResourceAttrPair(datasourceName, "health_check_type", resourceName, "health_check_type"), resource.TestCheckResourceAttrPair(datasourceName, "launch_configuration", resourceName, "launch_configuration"), - resource.TestCheckResourceAttr(datasourceName, "launch_template.#", "0"), + resource.TestCheckResourceAttrPair(datasourceName, "launch_template.#", resourceName, "launch_template.#"), resource.TestCheckResourceAttrPair(datasourceName, "load_balancers.#", resourceName, "load_balancers.#"), - resource.TestCheckResourceAttr(datasourceName, "new_instances_protected_from_scale_in", "false"), resource.TestCheckResourceAttrPair(datasourceName, "max_size", resourceName, "max_size"), resource.TestCheckResourceAttrPair(datasourceName, "min_size", resourceName, "min_size"), + resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttr(datasourceName, "new_instances_protected_from_scale_in", "false"), + resource.TestCheckResourceAttrPair(datasourceName, "placement_group", resourceName, "placement_group"), + resource.TestCheckResourceAttrPair(datasourceName, "service_linked_role_arn", resourceName, "service_linked_role_arn"), + resource.TestCheckResourceAttr(datasourceName, "status", ""), // Only set when the DeleteAutoScalingGroup operation is in progress. resource.TestCheckResourceAttrPair(datasourceName, "target_group_arns.#", resourceName, "target_group_arns.#"), - resource.TestCheckResourceAttr(datasourceName, "vpc_zone_identifier", ""), + resource.TestCheckResourceAttr(datasourceName, "termination_policies.#", "1"), // Not set in resource. + resource.TestCheckResourceAttr(datasourceName, "vpc_zone_identifier", ""), // Not set in resource. ), }, }, @@ -48,6 +52,7 @@ func TestAccAutoScalingGroupDataSource_basic(t *testing.T) { func TestAccAutoScalingGroupDataSource_launchTemplate(t *testing.T) { datasourceName := "data.aws_autoscaling_group.test" resourceName := "aws_autoscaling_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -55,46 +60,32 @@ func TestAccAutoScalingGroupDataSource_launchTemplate(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccGroupDataSourceConfig_launchTemplate(), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), - resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), - resource.TestCheckResourceAttrPair(datasourceName, "availability_zones.#", resourceName, "availability_zones.#"), - resource.TestCheckResourceAttrPair(datasourceName, "default_cooldown", resourceName, "default_cooldown"), - resource.TestCheckResourceAttrPair(datasourceName, "desired_capacity", resourceName, "desired_capacity"), - resource.TestCheckResourceAttrPair(datasourceName, "enabled_metrics.#", resourceName, "enabled_metrics.#"), - resource.TestCheckResourceAttrPair(datasourceName, "health_check_grace_period", resourceName, "health_check_grace_period"), - resource.TestCheckResourceAttrPair(datasourceName, "health_check_type", resourceName, "health_check_type"), - resource.TestCheckResourceAttr(datasourceName, "launch_configuration", ""), + Config: testAccGroupDataSourceConfig_launchTemplate(rName), + Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "launch_template.#", resourceName, "launch_template.#"), - resource.TestCheckResourceAttrPair(datasourceName, "load_balancers.#", resourceName, "load_balancers.#"), - resource.TestCheckResourceAttrPair(datasourceName, "load_balancers.0.id", resourceName, "load_balancers.0.id"), - resource.TestCheckResourceAttrPair(datasourceName, "load_balancers.0.name", resourceName, "load_balancers.0.name"), - resource.TestCheckResourceAttrPair(datasourceName, "load_balancers.0.version", resourceName, "load_balancers.0.version"), - resource.TestCheckResourceAttr(datasourceName, "new_instances_protected_from_scale_in", "false"), - resource.TestCheckResourceAttrPair(datasourceName, "max_size", resourceName, "max_size"), - resource.TestCheckResourceAttrPair(datasourceName, "min_size", resourceName, "min_size"), - resource.TestCheckResourceAttrPair(datasourceName, "target_group_arns.#", resourceName, "target_group_arns.#"), - resource.TestCheckResourceAttr(datasourceName, "vpc_zone_identifier", ""), + resource.TestCheckResourceAttrPair(datasourceName, "launch_template.0.id", resourceName, "launch_template.0.id"), + resource.TestCheckResourceAttrPair(datasourceName, "launch_template.0.name", resourceName, "launch_template.0.name"), + resource.TestCheckResourceAttrPair(datasourceName, "launch_template.0.version", resourceName, "launch_template.0.version"), ), }, }, }) } -// Lookup based on AutoScalingGroupName func testAccGroupDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), fmt.Sprintf(` data "aws_autoscaling_group" "test" { - name = aws_autoscaling_group.match.name + name = aws_autoscaling_group.test.name + + depends_on = [aws_autoscaling_group.no_match] } -resource "aws_autoscaling_group" "match" { - name = "%[1]s_match" +resource "aws_autoscaling_group" "test" { + name = %[1]q max_size = 0 min_size = 0 health_check_grace_period = 300 @@ -102,12 +93,12 @@ resource "aws_autoscaling_group" "match" { desired_capacity = 0 enabled_metrics = ["GroupDesiredCapacity"] force_delete = true - launch_configuration = aws_launch_configuration.data_source_aws_autoscaling_group_test.name + launch_configuration = aws_launch_configuration.test.name availability_zones = [data.aws_availability_zones.available.names[0], data.aws_availability_zones.available.names[1]] } resource "aws_autoscaling_group" "no_match" { - name = "%[1]s_no_match" + name = "%[1]s-1" max_size = 0 min_size = 0 health_check_grace_period = 300 @@ -115,33 +106,35 @@ resource "aws_autoscaling_group" "no_match" { desired_capacity = 0 enabled_metrics = ["GroupDesiredCapacity", "GroupStandbyInstances"] force_delete = true - launch_configuration = aws_launch_configuration.data_source_aws_autoscaling_group_test.name + launch_configuration = aws_launch_configuration.test.name availability_zones = [data.aws_availability_zones.available.names[0], data.aws_availability_zones.available.names[1]] } -resource "aws_launch_configuration" "data_source_aws_autoscaling_group_test" { - name = "%[1]s" +resource "aws_launch_configuration" "test" { + name = %[1]q image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = data.aws_ec2_instance_type_offering.available.instance_type } `, rName)) } -func testAccGroupDataSourceConfig_launchTemplate() string { +func testAccGroupDataSourceConfig_launchTemplate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), - ` + fmt.Sprintf(` data "aws_autoscaling_group" "test" { name = aws_autoscaling_group.test.name } resource "aws_autoscaling_group" "test" { + name = %[1]q availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 + launch_template { id = aws_launch_template.test.id version = aws_launch_template.test.default_version @@ -149,9 +142,9 @@ resource "aws_autoscaling_group" "test" { } resource "aws_launch_template" "test" { - name_prefix = "test" + name = %[1]q image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = data.aws_ec2_instance_type_offering.available.instance_type } -`) +`, rName)) } diff --git a/internal/service/autoscaling/group_tag_test.go b/internal/service/autoscaling/group_tag_test.go index 6fd3b72c3da..00c000ebc44 100644 --- a/internal/service/autoscaling/group_tag_test.go +++ b/internal/service/autoscaling/group_tag_test.go @@ -157,7 +157,7 @@ func testAccCheckGroupTagExists(n string) resource.TestCheckFunc { func testAccGroupTagConfig_basic(key string, value string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_template" "test" { name_prefix = "terraform-test-" diff --git a/internal/service/autoscaling/group_test.go b/internal/service/autoscaling/group_test.go index be1e27d6152..c274b56acf3 100644 --- a/internal/service/autoscaling/group_test.go +++ b/internal/service/autoscaling/group_test.go @@ -3,10 +3,7 @@ package autoscaling_test import ( "errors" "fmt" - "reflect" "regexp" - "sort" - "strings" "testing" "github.com/aws/aws-sdk-go/aws" @@ -20,11 +17,11 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/create" tfautoscaling "github.com/hashicorp/terraform-provider-aws/internal/service/autoscaling" tfelbv2 "github.com/hashicorp/terraform-provider-aws/internal/service/elbv2" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func init() { acctest.RegisterServiceErrorCheckFunc(autoscaling.EndpointsID, testAccErrorCheckSkip) - } func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { @@ -33,11 +30,85 @@ func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { ) } +func testAccGroupImportStep(n string) resource.TestStep { + return resource.TestStep{ + ResourceName: n, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "force_delete", + "initial_lifecycle_hook", + "tag", + "tags", + "wait_for_capacity_timeout", + "wait_for_elb_capacity", + }, + } +} + func TestAccAutoScalingGroup_basic(t *testing.T) { var group autoscaling.Group - var lc autoscaling.LaunchConfiguration + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_basic(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "autoscaling", regexp.MustCompile(fmt.Sprintf(`autoScalingGroup:.+:autoScalingGroupName/%s`, rName))), + resource.TestCheckResourceAttr(resourceName, "availability_zones.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "availability_zones.*", "data.aws_availability_zones.available", "names.0"), + resource.TestCheckResourceAttr(resourceName, "capacity_rebalance", "false"), + resource.TestCheckResourceAttr(resourceName, "context", ""), + resource.TestCheckResourceAttr(resourceName, "default_cooldown", "300"), + resource.TestCheckResourceAttr(resourceName, "desired_capacity", "0"), + resource.TestCheckResourceAttr(resourceName, "enabled_metrics.#", "0"), + resource.TestCheckResourceAttr(resourceName, "force_delete", "false"), + resource.TestCheckResourceAttr(resourceName, "force_delete_warm_pool", "false"), + resource.TestCheckResourceAttr(resourceName, "health_check_grace_period", "300"), + resource.TestCheckResourceAttr(resourceName, "health_check_type", "EC2"), + resource.TestCheckResourceAttr(resourceName, "initial_lifecycle_hook.#", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", "aws_launch_configuration.test", "name"), + resource.TestCheckResourceAttr(resourceName, "launch_template.#", "0"), + resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "0"), + resource.TestCheckResourceAttr(resourceName, "max_instance_lifetime", "0"), + resource.TestCheckResourceAttr(resourceName, "max_size", "0"), + resource.TestCheckResourceAttr(resourceName, "metrics_granularity", "1Minute"), + resource.TestCheckNoResourceAttr(resourceName, "min_elb_capacity"), + resource.TestCheckResourceAttr(resourceName, "min_size", "0"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "0"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name_prefix", ""), + resource.TestCheckResourceAttr(resourceName, "placement_group", ""), + resource.TestCheckResourceAttr(resourceName, "protect_from_scale_in", "false"), + acctest.CheckResourceAttrGlobalARN(resourceName, "service_linked_role_arn", "iam", "role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling"), + resource.TestCheckResourceAttr(resourceName, "suspended_processes.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "tag.#"), + resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), + resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "0"), + resource.TestCheckResourceAttr(resourceName, "termination_policies.#", "0"), + resource.TestCheckResourceAttr(resourceName, "vpc_zone_identifier.#", "0"), + resource.TestCheckResourceAttr(resourceName, "wait_for_capacity_timeout", "10m"), + resource.TestCheckNoResourceAttr(resourceName, "wait_for_elb_capacity"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.#", "0"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) +} - randName := fmt.Sprintf("terraform-test-%s", sdkacctest.RandString(10)) +func TestAccAutoScalingGroup_disappears(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -46,87 +117,20 @@ func TestAccAutoScalingGroup_basic(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(randName), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckGroupHealthyCapacity(&group, 2), - testAccCheckGroupAttributes(&group, randName), - acctest.MatchResourceAttrRegionalARN("aws_autoscaling_group.bar", "arn", "autoscaling", regexp.MustCompile(`autoScalingGroup:.+`)), - resource.TestCheckTypeSetElemAttrPair("aws_autoscaling_group.bar", "availability_zones.*", "data.aws_availability_zones.available", "names.0"), - testAccCheckInstanceRefreshCount(&group, 0), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "default_cooldown", "300"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "desired_capacity", "4"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "enabled_metrics.#", "0"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "force_delete", "true"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "health_check_grace_period", "300"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "health_check_type", "ELB"), - resource.TestCheckNoResourceAttr("aws_autoscaling_group.bar", "initial_lifecycle_hook.#"), - resource.TestCheckResourceAttrPair("aws_autoscaling_group.bar", "launch_configuration", "aws_launch_configuration.foobar", "name"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "launch_template.#", "0"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "load_balancers.#", "0"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "max_size", "5"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "metrics_granularity", "1Minute"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "min_size", "2"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "mixed_instances_policy.#", "0"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "name", randName), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "placement_group", ""), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "protect_from_scale_in", "false"), - acctest.CheckResourceAttrGlobalARN("aws_autoscaling_group.bar", "service_linked_role_arn", "iam", "role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "suspended_processes.#", "0"), - resource.TestCheckNoResourceAttr("aws_autoscaling_group.bar", "tag.#"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "tags.#", "3"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "target_group_arns.#", "0"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "termination_policies.#", "2"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "termination_policies.0", "OldestInstance"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "termination_policies.1", "ClosestToNextInstanceHour"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "vpc_zone_identifier.#", "0"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "max_instance_lifetime", "0"), - resource.TestCheckNoResourceAttr("aws_autoscaling_group.bar", "instance_refresh.#"), - ), - }, - { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupUpdateConfig(randName), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckLaunchConfigurationExists("aws_launch_configuration.new", &lc), - testAccCheckInstanceRefreshCount(&group, 0), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "desired_capacity", "5"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "termination_policies.0", "ClosestToNextInstanceHour"), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "protect_from_scale_in", "true"), - testLaunchConfigurationName("aws_autoscaling_group.bar", &lc), - testAccCheckTags(&group.Tags, "FromTags1Changed", map[string]interface{}{ - "value": "value1changed", - "propagate_at_launch": true, - }), - testAccCheckTags(&group.Tags, "FromTags2", map[string]interface{}{ - "value": "value2changed", - "propagate_at_launch": true, - }), - testAccCheckTags(&group.Tags, "FromTags3", map[string]interface{}{ - "value": "value3", - "propagate_at_launch": true, - }), + Config: testAccGroupConfig_basic(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + acctest.CheckResourceDisappears(acctest.Provider, tfautoscaling.ResourceGroup(), resourceName), ), + ExpectNonEmptyPlan: true, }, }, }) } -func TestAccAutoScalingGroup_Name_generated(t *testing.T) { +func TestAccAutoScalingGroup_nameGenerated(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -136,32 +140,21 @@ func TestAccAutoScalingGroup_Name_generated(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupNameGeneratedConfig(), + Config: testAccGroupConfig_nameGenerated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), resource.TestCheckResourceAttr(resourceName, "name_prefix", "terraform-"), ), }, - { - ResourceName: "aws_autoscaling_group.test", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } func TestAccAutoScalingGroup_namePrefix(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -171,31 +164,23 @@ func TestAccAutoScalingGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupNamePrefixConfig("tf-acc-test-prefix-"), + Config: testAccGroupConfig_namePrefix(rName, "tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), resource.TestCheckResourceAttr(resourceName, "name_prefix", "tf-acc-test-prefix-"), ), }, - { - ResourceName: "aws_autoscaling_group.test", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } -func TestAccAutoScalingGroup_terminationPolicies(t *testing.T) { +func TestAccAutoScalingGroup_tags(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), @@ -203,71 +188,87 @@ func TestAccAutoScalingGroup_terminationPolicies(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_terminationPoliciesEmpty(), + Config: testAccGroupConfig_tags1(rName, "key1", "value1", true), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "termination_policies.#", "0"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "tag.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tag.*", map[string]string{ + "key": "key1", + "value": "value1", + "propagate_at_launch": "true", + }), + resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_terminationPoliciesUpdate(), + Config: testAccGroupConfig_tags2(rName, "key1", "value1updated", true, "key2", "value2", false), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "termination_policies.#", "1"), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "termination_policies.0", "OldestInstance"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "tag.#", "2"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tag.*", map[string]string{ + "key": "key1", + "value": "value1updated", + "propagate_at_launch": "true", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tag.*", map[string]string{ + "key": "key2", + "value": "value2", + "propagate_at_launch": "false", + }), + resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), ), }, { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_terminationPoliciesExplicitDefault(), + Config: testAccGroupConfig_tags1(rName, "key2", "value2", true), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "termination_policies.#", "1"), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "termination_policies.0", "Default"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "tag.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tag.*", map[string]string{ + "key": "key2", + "value": "value2", + "propagate_at_launch": "true", + }), + resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), ), }, + }, + }) +} + +func TestAccAutoScalingGroup_deprecatedTags(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ { - Config: testAccGroupConfig_terminationPoliciesEmpty(), + Config: testAccGroupConfig_deprecatedTags1(rName, "key1", "value1", true), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "termination_policies.#", "0"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "tag.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tags.*", map[string]string{ + "key": "key1", + "value": "value1", + "propagate_at_launch": "true", + }), ), }, + testAccGroupImportStep(resourceName), }, }) } -func TestAccAutoScalingGroup_tags(t *testing.T) { +func TestAccAutoScalingGroup_simple(t *testing.T) { var group autoscaling.Group - - randName := fmt.Sprintf("tf-test-%s", sdkacctest.RandString(5)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -276,53 +277,145 @@ func TestAccAutoScalingGroup_tags(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(randName), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckTags(&group.Tags, "FromTags1", map[string]interface{}{ - "value": "value1", - "propagate_at_launch": true, - }), - testAccCheckTags(&group.Tags, "FromTags2", map[string]interface{}{ - "value": "value2", - "propagate_at_launch": true, + Config: testAccGroupConfig_simple(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "autoscaling", regexp.MustCompile(fmt.Sprintf(`autoScalingGroup:.+:autoScalingGroupName/%s`, rName))), + resource.TestCheckResourceAttr(resourceName, "availability_zones.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "availability_zones.*", "data.aws_availability_zones.available", "names.0"), + resource.TestCheckResourceAttr(resourceName, "capacity_rebalance", "false"), + resource.TestCheckResourceAttr(resourceName, "default_cooldown", "300"), + resource.TestCheckResourceAttr(resourceName, "desired_capacity", "4"), + resource.TestCheckResourceAttr(resourceName, "enabled_metrics.#", "0"), + resource.TestCheckResourceAttr(resourceName, "force_delete", "true"), + resource.TestCheckResourceAttr(resourceName, "force_delete_warm_pool", "false"), + resource.TestCheckResourceAttr(resourceName, "health_check_grace_period", "300"), + resource.TestCheckResourceAttr(resourceName, "health_check_type", "ELB"), + resource.TestCheckResourceAttr(resourceName, "initial_lifecycle_hook.#", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", "aws_launch_configuration.test", "name"), + resource.TestCheckResourceAttr(resourceName, "launch_template.#", "0"), + resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "0"), + resource.TestCheckResourceAttr(resourceName, "max_instance_lifetime", "0"), + resource.TestCheckResourceAttr(resourceName, "max_size", "5"), + resource.TestCheckResourceAttr(resourceName, "metrics_granularity", "1Minute"), + resource.TestCheckNoResourceAttr(resourceName, "min_elb_capacity"), + resource.TestCheckResourceAttr(resourceName, "min_size", "2"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "0"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name_prefix", ""), + resource.TestCheckResourceAttr(resourceName, "placement_group", ""), + resource.TestCheckResourceAttr(resourceName, "protect_from_scale_in", "false"), + acctest.CheckResourceAttrGlobalARN(resourceName, "service_linked_role_arn", "iam", "role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling"), + resource.TestCheckResourceAttr(resourceName, "suspended_processes.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tag.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tag.*", map[string]string{ + "key": "Name", + "value": rName, + "propagate_at_launch": "true", }), - testAccCheckTags(&group.Tags, "FromTags3", map[string]interface{}{ - "value": "value3", - "propagate_at_launch": true, + resource.TestCheckNoResourceAttr(resourceName, "tags.#"), + resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "0"), + resource.TestCheckResourceAttr(resourceName, "termination_policies.#", "2"), + resource.TestCheckResourceAttr(resourceName, "termination_policies.0", "OldestInstance"), + resource.TestCheckResourceAttr(resourceName, "termination_policies.1", "ClosestToNextInstanceHour"), + resource.TestCheckResourceAttr(resourceName, "vpc_zone_identifier.#", "0"), + resource.TestCheckResourceAttr(resourceName, "wait_for_capacity_timeout", "10m"), + resource.TestCheckNoResourceAttr(resourceName, "wait_for_elb_capacity"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.#", "0"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_simpleUpdated(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "autoscaling", regexp.MustCompile(fmt.Sprintf(`autoScalingGroup:.+:autoScalingGroupName/%s`, rName))), + resource.TestCheckResourceAttr(resourceName, "availability_zones.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "availability_zones.*", "data.aws_availability_zones.available", "names.0"), + resource.TestCheckResourceAttr(resourceName, "capacity_rebalance", "false"), + resource.TestCheckResourceAttr(resourceName, "default_cooldown", "300"), + resource.TestCheckResourceAttr(resourceName, "desired_capacity", "4"), + resource.TestCheckResourceAttr(resourceName, "enabled_metrics.#", "0"), + resource.TestCheckResourceAttr(resourceName, "force_delete", "true"), + resource.TestCheckResourceAttr(resourceName, "force_delete_warm_pool", "false"), + resource.TestCheckResourceAttr(resourceName, "health_check_grace_period", "400"), + resource.TestCheckResourceAttr(resourceName, "health_check_type", "ELB"), + resource.TestCheckResourceAttr(resourceName, "initial_lifecycle_hook.#", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", "aws_launch_configuration.test2", "name"), + resource.TestCheckResourceAttr(resourceName, "launch_template.#", "0"), + resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "0"), + resource.TestCheckResourceAttr(resourceName, "max_instance_lifetime", "0"), + resource.TestCheckResourceAttr(resourceName, "max_size", "6"), + resource.TestCheckResourceAttr(resourceName, "metrics_granularity", "1Minute"), + resource.TestCheckNoResourceAttr(resourceName, "min_elb_capacity"), + resource.TestCheckResourceAttr(resourceName, "min_size", "3"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "0"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name_prefix", ""), + resource.TestCheckResourceAttr(resourceName, "placement_group", ""), + resource.TestCheckResourceAttr(resourceName, "protect_from_scale_in", "true"), + acctest.CheckResourceAttrGlobalARN(resourceName, "service_linked_role_arn", "iam", "role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling"), + resource.TestCheckResourceAttr(resourceName, "suspended_processes.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tag.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tag.*", map[string]string{ + "key": "Name", + "value": rName, + "propagate_at_launch": "true", }), + resource.TestCheckNoResourceAttr(resourceName, "tags.#"), + resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "0"), + resource.TestCheckResourceAttr(resourceName, "termination_policies.#", "1"), + resource.TestCheckResourceAttr(resourceName, "termination_policies.0", "ClosestToNextInstanceHour"), + resource.TestCheckResourceAttr(resourceName, "vpc_zone_identifier.#", "0"), + resource.TestCheckResourceAttr(resourceName, "wait_for_capacity_timeout", "10m"), + resource.TestCheckNoResourceAttr(resourceName, "wait_for_elb_capacity"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.#", "0"), + ), + }, + }, + }) +} + +func TestAccAutoScalingGroup_terminationPolicies(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_basic(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "termination_policies.#", "0"), ), }, { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, + Config: testAccGroupConfig_terminationPoliciesUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "termination_policies.#", "1"), + resource.TestCheckResourceAttr(resourceName, "termination_policies.0", "OldestInstance"), + ), }, { - Config: testAccGroupUpdateConfig(randName), + Config: testAccGroupConfig_terminationPoliciesExplicitDefault(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckTagNotExists(&group.Tags, "Foo"), - testAccCheckTags(&group.Tags, "FromTags1Changed", map[string]interface{}{ - "value": "value1changed", - "propagate_at_launch": true, - }), - testAccCheckTags(&group.Tags, "FromTags2", map[string]interface{}{ - "value": "value2changed", - "propagate_at_launch": true, - }), - testAccCheckTags(&group.Tags, "FromTags3", map[string]interface{}{ - "value": "value3", - "propagate_at_launch": true, - }), + resource.TestCheckResourceAttr(resourceName, "termination_policies.#", "1"), + resource.TestCheckResourceAttr(resourceName, "termination_policies.0", "Default"), + ), + }, + { + Config: testAccGroupConfig_basic(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "termination_policies.#", "0"), ), }, }, @@ -331,6 +424,8 @@ func TestAccAutoScalingGroup_tags(t *testing.T) { func TestAccAutoScalingGroup_vpcUpdates(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -339,39 +434,22 @@ func TestAccAutoScalingGroup_vpcUpdates(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupWithAZConfig(), + Config: testAccGroupConfig_az(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "availability_zones.#", "1"), - resource.TestCheckTypeSetElemAttrPair("aws_autoscaling_group.bar", "availability_zones.*", "data.aws_availability_zones.available", "names.0"), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "vpc_zone_identifier.#", "0"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "availability_zones.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "availability_zones.*", "data.aws_availability_zones.available", "names.0"), + resource.TestCheckResourceAttr(resourceName, "vpc_zone_identifier.#", "0"), ), }, { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupWithVPCIdentConfig(), + Config: testAccGroupConfig_vpcZoneIdentifier(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckGroupAttributesVPCZoneIdentifier(&group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "availability_zones.#", "1"), - resource.TestCheckTypeSetElemAttrPair("aws_autoscaling_group.bar", "availability_zones.*", "data.aws_availability_zones.available", "names.0"), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "vpc_zone_identifier.#", "1"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "availability_zones.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "availability_zones.*", "data.aws_availability_zones.available", "names.0"), + resource.TestCheckResourceAttr(resourceName, "vpc_zone_identifier.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "vpc_zone_identifier.*", "aws_subnet.test.0", "id"), ), }, }, @@ -380,6 +458,8 @@ func TestAccAutoScalingGroup_vpcUpdates(t *testing.T) { func TestAccAutoScalingGroup_withLoadBalancer(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -388,32 +468,28 @@ func TestAccAutoScalingGroup_withLoadBalancer(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupWithLoadBalancerConfig(), + Config: testAccGroupConfig_loadBalancer(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckGroupAttributesLoadBalancer(&group), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "force_delete", "true"), + resource.TestCheckResourceAttr(resourceName, "health_check_grace_period", "300"), + resource.TestCheckResourceAttr(resourceName, "health_check_type", "ELB"), + resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "load_balancers.*", "aws_elb.test", "name"), + resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "0"), + resource.TestCheckResourceAttr(resourceName, "vpc_zone_identifier.#", "1"), + resource.TestCheckResourceAttr(resourceName, "wait_for_elb_capacity", "2"), ), }, - { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } func TestAccAutoScalingGroup_WithLoadBalancer_toTargetGroup(t *testing.T) { var group autoscaling.Group - resourceName := "aws_autoscaling_group.bar" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -422,7 +498,7 @@ func TestAccAutoScalingGroup_WithLoadBalancer_toTargetGroup(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupWithLoadBalancerConfig(), + Config: testAccGroupConfig_loadBalancer(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "1"), @@ -430,68 +506,31 @@ func TestAccAutoScalingGroup_WithLoadBalancer_toTargetGroup(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupWithTargetGroupConfig(), + Config: testAccGroupConfig_target2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "1"), resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "0"), + resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "1"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupWithLoadBalancerConfig(), + Config: testAccGroupConfig_loadBalancer(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "1"), resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "0"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, }, }) } func TestAccAutoScalingGroup_withPlacementGroup(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" - randName := fmt.Sprintf("tf-test-%s", sdkacctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), @@ -499,32 +538,21 @@ func TestAccAutoScalingGroup_withPlacementGroup(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_withPlacementGroup(randName), + Config: testAccGroupConfig_placement(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr("aws_autoscaling_group.bar", "placement_group", randName), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttrPair(resourceName, "placement_group", "aws_placement_group.test", "name"), ), }, - { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } func TestAccAutoScalingGroup_enablingMetrics(t *testing.T) { var group autoscaling.Group - randName := fmt.Sprintf("terraform-test-%s", sdkacctest.RandString(10)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -533,41 +561,33 @@ func TestAccAutoScalingGroup_enablingMetrics(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(randName), + Config: testAccGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckNoResourceAttr( - "aws_autoscaling_group.bar", "enabled_metrics"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "enabled_metrics.#", "0"), ), }, { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccMetricsCollectionConfig_updatingMetricsCollected(), + Config: testAccGroupConfig_enabledMetrics(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "enabled_metrics.#", "5"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "enabled_metrics.#", "5"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupTotalInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupPendingInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupTerminatingInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupDesiredCapacity"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupMaxSize"), ), }, + testAccGroupImportStep(resourceName), }, }) } -func TestAccAutoScalingGroup_suspendingProcesses(t *testing.T) { +func TestAccAutoScalingGroup_withMetrics(t *testing.T) { var group autoscaling.Group - randName := fmt.Sprintf("terraform-test-%s", sdkacctest.RandString(10)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -576,48 +596,45 @@ func TestAccAutoScalingGroup_suspendingProcesses(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(randName), + Config: testAccGroupConfig_allMetricsEnabled(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "suspended_processes.#", "0"), - ), - }, - { - Config: testAccGroupWithSuspendedProcessesConfig(randName), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "suspended_processes.#", "2"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "enabled_metrics.#", "13"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupTotalInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupPendingInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupTerminatingInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupDesiredCapacity"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupInServiceInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupMinSize"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupMaxSize"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupPendingCapacity"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupInServiceCapacity"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupStandbyCapacity"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupTotalCapacity"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupTerminatingCapacity"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupStandbyInstances"), ), }, { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupWithSuspendedProcessesUpdatedConfig(randName), + Config: testAccGroupConfig_enabledMetrics(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "suspended_processes.#", "2"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "enabled_metrics.#", "5"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupTotalInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupPendingInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupTerminatingInstances"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupDesiredCapacity"), + resource.TestCheckTypeSetElemAttr(resourceName, "enabled_metrics.*", "GroupMaxSize"), ), }, }, }) } -func TestAccAutoScalingGroup_withMetrics(t *testing.T) { +func TestAccAutoScalingGroup_suspendingProcesses(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -626,32 +643,29 @@ func TestAccAutoScalingGroup_withMetrics(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricsCollectionConfig_allMetricsCollected(), + Config: testAccGroupConfig_simple(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "enabled_metrics.#", "13"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "suspended_processes.#", "0"), ), }, { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, + Config: testAccGroupConfig_suspendedProcesses(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "suspended_processes.#", "2"), + resource.TestCheckTypeSetElemAttr(resourceName, "suspended_processes.*", "AlarmNotification"), + resource.TestCheckTypeSetElemAttr(resourceName, "suspended_processes.*", "ScheduledActions"), + ), }, + testAccGroupImportStep(resourceName), { - Config: testAccMetricsCollectionConfig_updatingMetricsCollected(), + Config: testAccGroupConfig_suspendedProcessesUpdated(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "enabled_metrics.#", "5"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "suspended_processes.#", "2"), + resource.TestCheckTypeSetElemAttr(resourceName, "suspended_processes.*", "AZRebalance"), + resource.TestCheckTypeSetElemAttr(resourceName, "suspended_processes.*", "ScheduledActions"), ), }, }, @@ -660,6 +674,8 @@ func TestAccAutoScalingGroup_withMetrics(t *testing.T) { func TestAccAutoScalingGroup_serviceLinkedRoleARN(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -668,32 +684,21 @@ func TestAccAutoScalingGroup_serviceLinkedRoleARN(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_withServiceLinkedRoleARN(), + Config: testAccGroupConfig_serviceLinkedRoleARN(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttrSet( - "aws_autoscaling_group.bar", "service_linked_role_arn"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttrPair(resourceName, "service_linked_role_arn", "data.aws_iam_role.test", "arn"), ), }, - { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } func TestAccAutoScalingGroup_maxInstanceLifetime(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -702,65 +707,28 @@ func TestAccAutoScalingGroup_maxInstanceLifetime(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_withMaxInstanceLifetime(), + Config: testAccGroupConfig_maxInstanceLifetime(rName, 864000), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "max_instance_lifetime", "864000"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "max_instance_lifetime", "864000"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_withMaxInstanceLifetime_update(), + Config: testAccGroupConfig_maxInstanceLifetime(rName, 604800), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "max_instance_lifetime", "604800"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "max_instance_lifetime", "604800"), ), }, }, }) } -func TestAccAutoScalingGroup_ALB_targetGroups(t *testing.T) { +func TestAccAutoScalingGroup_initialLifecycleHook(t *testing.T) { var group autoscaling.Group - var tg elbv2.TargetGroup - var tg2 elbv2.TargetGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - - testCheck := func(targets []*elbv2.TargetGroup) resource.TestCheckFunc { - return func(*terraform.State) error { - var ts []string - var gs []string - for _, t := range targets { - ts = append(ts, *t.TargetGroupArn) - } - - for _, s := range group.TargetGroupARNs { - gs = append(gs, *s) - } - - sort.Strings(ts) - sort.Strings(gs) - - if !reflect.DeepEqual(ts, gs) { - return fmt.Errorf("Error: target group match not found!\nASG Target groups: %#v\nTarget Group: %#v", ts, gs) - } - return nil - } - } + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -769,58 +737,54 @@ func TestAccAutoScalingGroup_ALB_targetGroups(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_ALB_TargetGroup_pre(rName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckLBTargetGroupExists("aws_lb_target_group.test", &tg), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "target_group_arns.#", "0"), + Config: testAccGroupConfig_initialLifecycleHook(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + testAccCheckGroupHealthyInstanceCount(&group, 2), + resource.TestCheckResourceAttr(resourceName, "initial_lifecycle_hook.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "initial_lifecycle_hook.*", map[string]string{ + "default_result": "CONTINUE", + "heartbeat_timeout": "30", + "lifecycle_transition": "autoscaling:EC2_INSTANCE_LAUNCHING", + "name": "launching", + }), ), }, + testAccGroupImportStep(resourceName), + }, + }) +} +func TestAccAutoScalingGroup_launchTemplate(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ { - Config: testAccGroupConfig_ALB_TargetGroup_post_duo(rName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckLBTargetGroupExists("aws_lb_target_group.test", &tg), - testAccCheckLBTargetGroupExists("aws_lb_target_group.test_more", &tg2), - testCheck([]*elbv2.TargetGroup{&tg, &tg2}), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "target_group_arns.#", "2"), - ), - }, - { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_ALB_TargetGroup_post(rName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckLBTargetGroupExists("aws_lb_target_group.test", &tg), - testCheck([]*elbv2.TargetGroup{&tg}), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "target_group_arns.#", "1"), + Config: testAccGroupConfig_launchTemplate(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "launch_template.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", "aws_launch_template.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.name", "aws_launch_template.test", "name"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.version", "aws_launch_template.test", "default_version"), ), }, + testAccGroupImportStep(resourceName), }, }) } -// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/256 -func TestAccAutoScalingGroup_targetGroupARNs(t *testing.T) { +func TestAccAutoScalingGroup_LaunchTemplate_update(t *testing.T) { var group autoscaling.Group - resourceName := "aws_autoscaling_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -829,47 +793,66 @@ func TestAccAutoScalingGroup_targetGroupARNs(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_TargetGroupARNs(rName, 11), + Config: testAccGroupConfig_launchTemplate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "11"), + resource.TestCheckResourceAttr(resourceName, "launch_configuration", ""), + resource.TestCheckResourceAttr(resourceName, "launch_template.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", "aws_launch_template.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.name", "aws_launch_template.test", "name"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.version", "aws_launch_template.test", "default_version"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, + Config: testAccGroupConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", "aws_launch_configuration.test", "name"), + resource.TestCheckResourceAttr(resourceName, "launch_template.#", "0"), + ), }, { - Config: testAccGroupConfig_TargetGroupARNs(rName, 0), + Config: testAccGroupConfig_launchTemplateName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "0"), + resource.TestCheckResourceAttr(resourceName, "launch_configuration", ""), + resource.TestCheckResourceAttr(resourceName, "launch_template.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", "aws_launch_template.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.name", "aws_launch_template.test", "name"), + resource.TestCheckResourceAttr(resourceName, "launch_template.0.version", ""), + ), + }, + { + Config: testAccGroupConfig_launchTemplateLatestVersion(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "launch_configuration", ""), + resource.TestCheckResourceAttr(resourceName, "launch_template.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", "aws_launch_template.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.name", "aws_launch_template.test", "name"), + resource.TestCheckResourceAttr(resourceName, "launch_template.0.version", "$Latest"), ), }, { - Config: testAccGroupConfig_TargetGroupARNs(rName, 11), + Config: testAccGroupConfig_launchTemplate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "11"), + resource.TestCheckResourceAttr(resourceName, "launch_configuration", ""), + resource.TestCheckResourceAttr(resourceName, "launch_template.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", "aws_launch_template.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.name", "aws_launch_template.test", "name"), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.version", "aws_launch_template.test", "default_version"), ), }, }, }) } -func TestAccAutoScalingGroup_initialLifecycleHook(t *testing.T) { +func TestAccAutoScalingGroup_largeDesiredCapacity(t *testing.T) { var group autoscaling.Group - - randName := fmt.Sprintf("terraform-test-%s", sdkacctest.RandString(10)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -878,74 +861,22 @@ func TestAccAutoScalingGroup_initialLifecycleHook(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupWithHookConfig(randName), + Config: testAccGroupConfig_largeDesiredCapacity(rName, 101), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckGroupHealthyCapacity(&group, 2), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "initial_lifecycle_hook.#", "1"), - resource.TestCheckTypeSetElemNestedAttrs("aws_autoscaling_group.bar", "initial_lifecycle_hook.*", map[string]string{ - "default_result": "CONTINUE", - "name": "launching", - }), - ), - }, - { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - }, - }) -} - -func TestAccAutoScalingGroup_ALBTargetGroups_elbCapacity(t *testing.T) { - var group autoscaling.Group - var tg elbv2.TargetGroup - - rInt := sdkacctest.RandInt() - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), - ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGroupConfig_ALB_TargetGroup_ELBCapacity(rInt), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - testAccCheckLBTargetGroupExists("aws_lb_target_group.test", &tg), - testAccCheckALBTargetGroupHealthy(&tg), + testAccCheckGroupExists(resourceName, &group), + testAccCheckGroupHealthyInstanceCount(&group, 101), + resource.TestCheckResourceAttr(resourceName, "desired_capacity", "101"), + resource.TestCheckResourceAttr(resourceName, "max_size", "101"), + resource.TestCheckResourceAttr(resourceName, "min_size", "101"), ), }, - { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, }, }) } func TestAccAutoScalingGroup_InstanceRefresh_basic(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -955,60 +886,51 @@ func TestAccAutoScalingGroup_InstanceRefresh_basic(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_InstanceRefresh_Basic(), + Config: testAccGroupConfig_instanceRefreshBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "1"), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.#", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.triggers.#", "0"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "wait_for_capacity_timeout", - "instance_refresh", - }, - }, - { - Config: testAccGroupConfig_InstanceRefresh_MinHealthyPercentage(), + Config: testAccGroupConfig_instanceRefreshMinHealthyPercentage(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "1"), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.#", "1"), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.instance_warmup", ""), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.min_healthy_percentage", "0"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_delay", ""), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_percentages.#", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.instance_warmup", ""), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.min_healthy_percentage", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.skip_matching", "false"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.triggers.#", "0"), ), }, { - Config: testAccGroupConfig_InstanceRefresh_SkipMatching(), + Config: testAccGroupConfig_instanceRefreshSkipMatching(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "1"), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.#", "1"), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.instance_warmup", ""), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.min_healthy_percentage", "0"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_delay", ""), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_percentages.#", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.instance_warmup", ""), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.min_healthy_percentage", "0"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.skip_matching", "true"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.triggers.#", "0"), ), }, { - Config: testAccGroupConfig_InstanceRefresh_Full(), + Config: testAccGroupConfig_instanceRefreshFull(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "1"), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.#", "1"), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.instance_warmup", "10"), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.min_healthy_percentage", "50"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_delay", "25"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_percentages.#", "5"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_percentages.0", "1"), @@ -1016,13 +938,18 @@ func TestAccAutoScalingGroup_InstanceRefresh_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_percentages.2", "25"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_percentages.3", "50"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.checkpoint_percentages.4", "100"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.instance_warmup", "10"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.min_healthy_percentage", "50"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.0.skip_matching", "false"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.triggers.#", "0"), ), }, { - Config: testAccGroupConfig_InstanceRefresh_Disabled(), + Config: testAccGroupConfig_instanceRefreshDisabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckNoResourceAttr(resourceName, "instance_refresh.#"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "0"), ), }, }, @@ -1031,8 +958,9 @@ func TestAccAutoScalingGroup_InstanceRefresh_basic(t *testing.T) { func TestAccAutoScalingGroup_InstanceRefresh_start(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_autoscaling_group.test" - launchConfigurationName := "aws_launch_configuration.test" + launchConfigurationResourceName := "aws_launch_configuration.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1041,27 +969,27 @@ func TestAccAutoScalingGroup_InstanceRefresh_start(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_InstanceRefresh_Start("one"), + Config: testAccGroupConfig_instanceRefreshStart(rName, acctest.ResourcePrefix+"-1-"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", launchConfigurationName, "name"), + resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", launchConfigurationResourceName, "name"), testAccCheckInstanceRefreshCount(&group, 0), ), }, { - Config: testAccGroupConfig_InstanceRefresh_Start("two"), + Config: testAccGroupConfig_instanceRefreshStart(rName, acctest.ResourcePrefix+"-2-"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", launchConfigurationName, "name"), + resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", launchConfigurationResourceName, "name"), testAccCheckInstanceRefreshCount(&group, 1), testAccCheckInstanceRefreshStatus(&group, 0, autoscaling.InstanceRefreshStatusPending, autoscaling.InstanceRefreshStatusInProgress), ), }, { - Config: testAccGroupConfig_InstanceRefresh_Start("three"), + Config: testAccGroupConfig_instanceRefreshStart(rName, acctest.ResourcePrefix+"-3-"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", launchConfigurationName, "name"), + resource.TestCheckResourceAttrPair(resourceName, "launch_configuration", launchConfigurationResourceName, "name"), testAccCheckInstanceRefreshCount(&group, 2), testAccCheckInstanceRefreshStatus(&group, 0, autoscaling.InstanceRefreshStatusPending, autoscaling.InstanceRefreshStatusInProgress), testAccCheckInstanceRefreshStatus(&group, 1, autoscaling.InstanceRefreshStatusCancelled), @@ -1073,6 +1001,7 @@ func TestAccAutoScalingGroup_InstanceRefresh_start(t *testing.T) { func TestAccAutoScalingGroup_InstanceRefresh_triggers(t *testing.T) { var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -1082,18 +1011,23 @@ func TestAccAutoScalingGroup_InstanceRefresh_triggers(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_InstanceRefresh_Basic(), + Config: testAccGroupConfig_instanceRefreshBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "1"), - resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.#", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.triggers.#", "0"), ), }, { - Config: testAccGroupConfig_InstanceRefresh_Triggers(), + Config: testAccGroupConfig_instanceRefreshTriggers(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.#", "1"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.preferences.#", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.strategy", "Rolling"), resource.TestCheckResourceAttr(resourceName, "instance_refresh.0.triggers.#", "1"), resource.TestCheckTypeSetElemAttr(resourceName, "instance_refresh.0.triggers.*", "tags"), testAccCheckInstanceRefreshCount(&group, 1), @@ -1104,9 +1038,11 @@ func TestAccAutoScalingGroup_InstanceRefresh_triggers(t *testing.T) { }) } -func TestAccAutoScalingGroup_warmPool(t *testing.T) { +// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/256 +func TestAccAutoScalingGroup_loadBalancers(t *testing.T) { var group autoscaling.Group resourceName := "aws_autoscaling_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1115,305 +1051,35 @@ func TestAccAutoScalingGroup_warmPool(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_WarmPool_Empty(), + Config: testAccGroupConfig_loadBalancers(rName, 11), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "warm_pool.#", "1"), + resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "11"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "warm_pool", - "force_delete", - "wait_for_capacity_timeout", - }, - }, - { - Config: testAccGroupConfig_WarmPool_Full(), + Config: testAccGroupConfig_loadBalancers(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "warm_pool.#", "1"), - resource.TestCheckResourceAttr(resourceName, "warm_pool.0.pool_state", "Stopped"), - resource.TestCheckResourceAttr(resourceName, "warm_pool.0.min_size", "0"), - resource.TestCheckResourceAttr(resourceName, "warm_pool.0.max_group_prepared_capacity", "2"), - resource.TestCheckResourceAttr(resourceName, "warm_pool.0.instance_reuse_policy.#", "1"), - resource.TestCheckResourceAttr(resourceName, "warm_pool.0.instance_reuse_policy.0.reuse_on_scale_in", "true"), + resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "0"), ), }, { - Config: testAccGroupConfig_WarmPool_Remove(), + Config: testAccGroupConfig_loadBalancers(rName, 11), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckNoResourceAttr(resourceName, "warm_pool.#"), + resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "11"), ), }, }, }) } -func testAccCheckGroupExists(n string, group *autoscaling.Group) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No Auto Scaling Group ID is set") - } - - conn := acctest.Provider.Meta().(*conns.AWSClient).AutoScalingConn - - describeGroups, err := conn.DescribeAutoScalingGroups( - &autoscaling.DescribeAutoScalingGroupsInput{ - AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)}, - }) - - if err != nil { - return err - } - - if len(describeGroups.AutoScalingGroups) != 1 || - *describeGroups.AutoScalingGroups[0].AutoScalingGroupName != rs.Primary.ID { - return fmt.Errorf("Auto Scaling Group not found") - } - - *group = *describeGroups.AutoScalingGroups[0] - - return nil - } -} - -func testAccCheckGroupDestroy(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).AutoScalingConn - - for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_autoscaling_group" { - continue - } - - // Try to find the Group - describeGroups, err := conn.DescribeAutoScalingGroups( - &autoscaling.DescribeAutoScalingGroupsInput{ - AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)}, - }) - - if err == nil { - if len(describeGroups.AutoScalingGroups) != 0 && - *describeGroups.AutoScalingGroups[0].AutoScalingGroupName == rs.Primary.ID { - return fmt.Errorf("Auto Scaling Group still exists") - } - } - - if err != nil { - return err - } - } - - return nil -} - -func testAccCheckGroupAttributes(group *autoscaling.Group, name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *group.AutoScalingGroupName != name { - return fmt.Errorf("Bad Auto Scaling Group name, expected (%s), got (%s)", name, *group.AutoScalingGroupName) - } - - if *group.MaxSize != 5 { - return fmt.Errorf("Bad max_size: %d", *group.MaxSize) - } - - if *group.MinSize != 2 { - return fmt.Errorf("Bad max_size: %d", *group.MinSize) - } - - if *group.HealthCheckType != "ELB" { - return fmt.Errorf("Bad health_check_type,\nexpected: %s\ngot: %s", "ELB", *group.HealthCheckType) - } - - if *group.HealthCheckGracePeriod != 300 { - return fmt.Errorf("Bad health_check_grace_period: %d", *group.HealthCheckGracePeriod) - } - - if *group.DesiredCapacity != 4 { - return fmt.Errorf("Bad desired_capacity: %d", *group.DesiredCapacity) - } - - if *group.LaunchConfigurationName == "" { - return fmt.Errorf("Bad launch configuration name: %s", *group.LaunchConfigurationName) - } - - t := &autoscaling.TagDescription{ - Key: aws.String("FromTags1"), - Value: aws.String("value1"), - PropagateAtLaunch: aws.Bool(true), - ResourceType: aws.String("auto-scaling-group"), - ResourceId: group.AutoScalingGroupName, - } - - if !reflect.DeepEqual(group.Tags[0], t) { - return fmt.Errorf( - "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - group.Tags[0], - t) - } - - return nil - } -} - -func testAccCheckGroupAttributesLoadBalancer(group *autoscaling.Group) resource.TestCheckFunc { - return func(s *terraform.State) error { - if len(group.LoadBalancerNames) != 1 { - return fmt.Errorf("Bad load_balancers: %v", group.LoadBalancerNames) - } - - return nil - } -} - -func testLaunchConfigurationName(n string, lc *autoscaling.LaunchConfiguration) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - if *lc.LaunchConfigurationName != rs.Primary.Attributes["launch_configuration"] { - return fmt.Errorf("Launch configuration names do not match") - } - - return nil - } -} - -func testAccCheckGroupHealthyCapacity( - g *autoscaling.Group, exp int) resource.TestCheckFunc { - return func(s *terraform.State) error { - healthy := 0 - for _, i := range g.Instances { - if i.HealthStatus == nil { - continue - } - if strings.EqualFold(*i.HealthStatus, "Healthy") { - healthy++ - } - } - if healthy < exp { - return fmt.Errorf("Expected at least %d healthy, got %d.", exp, healthy) - } - return nil - } -} - -func testAccCheckGroupAttributesVPCZoneIdentifier(group *autoscaling.Group) resource.TestCheckFunc { - return func(s *terraform.State) error { - // Grab Subnet Ids - var subnets []string - for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_subnet" { - continue - } - subnets = append(subnets, rs.Primary.Attributes["id"]) - } - - if group.VPCZoneIdentifier == nil { - return fmt.Errorf("Bad VPC Zone Identifier\nexpected: %s\ngot nil", subnets) - } - - zones := strings.Split(*group.VPCZoneIdentifier, ",") - - remaining := len(zones) - for _, z := range zones { - for _, s := range subnets { - if z == s { - remaining-- - } - } - } - - if remaining != 0 { - return fmt.Errorf("Bad VPC Zone Identifier match\nexpected: %s\ngot:%s", zones, subnets) - } - - return nil - } -} - -// testAccCheckTags can be used to check the tags on a resource. -func testAccCheckTags( - ts *[]*autoscaling.TagDescription, key string, expected map[string]interface{}) resource.TestCheckFunc { - return func(s *terraform.State) error { - m := TagDescriptionsToMap(ts) - v, ok := m[key] - if !ok { - return fmt.Errorf("Missing tag: %s", key) - } - - if v["value"] != expected["value"].(string) || - v["propagate_at_launch"] != expected["propagate_at_launch"].(bool) { - return fmt.Errorf("%s: bad value: %s", key, v) - } - - return nil - } -} - -func testAccCheckTagNotExists(ts *[]*autoscaling.TagDescription, key string) resource.TestCheckFunc { - return func(s *terraform.State) error { - m := TagDescriptionsToMap(ts) - if _, ok := m[key]; ok { - return fmt.Errorf("Tag exists when it should not: %s", key) - } - - return nil - } -} - -// TagDescriptionsToMap turns the list of tags into a map. -func TagDescriptionsToMap(ts *[]*autoscaling.TagDescription) map[string]map[string]interface{} { - tags := make(map[string]map[string]interface{}) - for _, t := range *ts { - tag := map[string]interface{}{ - "key": aws.StringValue(t.Key), - "value": aws.StringValue(t.Value), - "propagate_at_launch": aws.BoolValue(t.PropagateAtLaunch), - } - tags[aws.StringValue(t.Key)] = tag - } - - return tags -} - -// testAccCheckALBTargetGroupHealthy checks an *elbv2.TargetGroup to make -// sure that all instances in it are healthy. -func testAccCheckALBTargetGroupHealthy(res *elbv2.TargetGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ELBV2Conn - - resp, err := conn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{ - TargetGroupArn: res.TargetGroupArn, - }) - - if err != nil { - return err - } - - for _, target := range resp.TargetHealthDescriptions { - if target.TargetHealth == nil || target.TargetHealth.State == nil || *target.TargetHealth.State != "healthy" { - return errors.New("Not all instances in target group are healthy yet, but should be") - } - } - - return nil - } -} - -func TestAccAutoScalingGroup_classicVPCZoneIdentifier(t *testing.T) { +func TestAccAutoScalingGroup_targetGroups(t *testing.T) { var group autoscaling.Group + resourceName := "aws_autoscaling_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1422,31 +1088,36 @@ func TestAccAutoScalingGroup_classicVPCZoneIdentifier(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_classicVPCZoneIdentifier(), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.test", &group), - resource.TestCheckResourceAttr("aws_autoscaling_group.test", "vpc_zone_identifier.#", "0"), + Config: testAccGroupConfig_target(rName, 0), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "0"), ), }, { - ResourceName: "aws_autoscaling_group.test", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, + Config: testAccGroupConfig_target(rName, 12), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "12"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_target(rName, 1), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "target_group_arns.#", "1"), + ), }, }, }) } -func TestAccAutoScalingGroup_launchTemplate(t *testing.T) { +func TestAccAutoScalingGroup_ALBTargetGroups_elbCapacity(t *testing.T) { var group autoscaling.Group + resourceName := "aws_autoscaling_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + var tg elbv2.TargetGroup resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1455,33 +1126,23 @@ func TestAccAutoScalingGroup_launchTemplate(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_withLaunchTemplate(), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttrSet( - "aws_autoscaling_group.bar", "launch_template.0.id"), + Config: testAccGroupConfig_targetELBCapacity(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + testAccCheckLBTargetGroupExists("aws_lb_target_group.test", &tg), + testAccCheckALBTargetGroupHealthy(&tg), ), }, - { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } -func TestAccAutoScalingGroup_LaunchTemplate_update(t *testing.T) { +func TestAccAutoScalingGroup_warmPool(t *testing.T) { var group autoscaling.Group - + resourceName := "aws_autoscaling_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), @@ -1489,74 +1150,41 @@ func TestAccAutoScalingGroup_LaunchTemplate_update(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_withLaunchTemplate(), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttrSet( - "aws_autoscaling_group.bar", "launch_template.0.name"), - ), - }, - { - ResourceName: "aws_autoscaling_group.bar", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_withLaunchTemplate_toLaunchConfig(), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttrSet( - "aws_autoscaling_group.bar", "launch_configuration"), - resource.TestCheckNoResourceAttr( - "aws_autoscaling_group.bar", "launch_template"), - ), - }, - - { - Config: testAccGroupConfig_withLaunchTemplate_toLaunchTemplateName(), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "launch_configuration", ""), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "launch_template.0.name", "foobar2"), - resource.TestCheckResourceAttrSet( - "aws_autoscaling_group.bar", "launch_template.0.id"), + Config: testAccGroupConfig_warmPoolEmpty(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "warm_pool.#", "1"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.0.instance_reuse_policy.#", "0"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.0.max_group_prepared_capacity", "-1"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.0.min_size", "0"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.0.pool_state", "Stopped"), ), }, - + testAccGroupImportStep(resourceName), { - Config: testAccGroupConfig_withLaunchTemplate_toLaunchTemplateVersion(), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "launch_template.0.version", "$Latest"), + Config: testAccGroupConfig_warmPoolFull(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "warm_pool.#", "1"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.0.instance_reuse_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.0.instance_reuse_policy.0.reuse_on_scale_in", "true"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.0.max_group_prepared_capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.0.min_size", "0"), + resource.TestCheckResourceAttr(resourceName, "warm_pool.0.pool_state", "Stopped"), ), }, - { - Config: testAccGroupConfig_withLaunchTemplate(), + Config: testAccGroupConfig_warmPoolNone(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.bar", &group), - resource.TestCheckResourceAttrSet( - "aws_autoscaling_group.bar", "launch_template.0.name"), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "launch_template.0.version", "1"), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckNoResourceAttr(resourceName, "warm_pool.#"), ), }, }, }) } -func TestAccAutoScalingGroup_LaunchTemplate_iamInstanceProfile(t *testing.T) { +func TestAccAutoScalingGroup_launchTempPartitionNum(t *testing.T) { var group autoscaling.Group resourceName := "aws_autoscaling_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1568,30 +1196,17 @@ func TestAccAutoScalingGroup_LaunchTemplate_iamInstanceProfile(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_LaunchTemplate_IAMInstanceProfile(rName), + Config: testAccGroupConfig_partition(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } -// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/256 -func TestAccAutoScalingGroup_loadBalancers(t *testing.T) { +func TestAccAutoScalingGroup_Destroy_whenProtectedFromScaleIn(t *testing.T) { var group autoscaling.Group resourceName := "aws_autoscaling_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1603,38 +1218,16 @@ func TestAccAutoScalingGroup_loadBalancers(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_LoadBalancers(rName, 11), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "11"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_LoadBalancers(rName, 0), + Config: testAccGroupConfig_destroyWhenProtectedFromScaleInBeforeDestroy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "0"), + testAccCheckGroupHealthyInstanceCount(&group, 2), + resource.TestCheckResourceAttr(resourceName, "protect_from_scale_in", "true"), ), }, { - Config: testAccGroupConfig_LoadBalancers(rName, 11), - Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "load_balancers.#", "11"), - ), + Config: testAccGroupConfig_destroyWhenProtectedFromScaleInAfterDestroy(rName), + // Reaching this step is good enough, as it indicates the ASG was destroyed successfully. }, }, }) @@ -1652,7 +1245,7 @@ func TestAccAutoScalingGroup_mixedInstancesPolicy(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy(rName), + Config: testAccGroupConfig_mixedInstancesPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1666,19 +1259,7 @@ func TestAccAutoScalingGroup_mixedInstancesPolicy(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.weighted_capacity", "2"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } @@ -1695,7 +1276,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicy_capacityRebalance(t *testing.T CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_CapacityRebalance(rName), + Config: testAccGroupConfig_mixedInstancesPolicyCapacityRebalance(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "capacity_rebalance", "true"), @@ -1704,25 +1285,15 @@ func TestAccAutoScalingGroup_MixedInstancesPolicy_capacityRebalance(t *testing.T resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.launch_template_specification.#", "1"), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.launch_template_specification.0.version", "$Default"), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "2"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "0"), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_type", "t2.micro"), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.weighted_capacity", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.instance_requirements.#", "0"), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.instance_type", "t3.small"), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.weighted_capacity", "2"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } @@ -1739,7 +1310,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_onDemandA CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandAllocationStrategy(rName, "prioritized"), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandAllocationStrategy(rName, "prioritized"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1747,19 +1318,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_onDemandA resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.on_demand_allocation_strategy", "prioritized"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } @@ -1776,7 +1335,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_onDemandB CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandBaseCapacity(rName, 1), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandBaseCapacity(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1784,21 +1343,9 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_onDemandB resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.on_demand_base_capacity", "1"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandBaseCapacity(rName, 2), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandBaseCapacity(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1807,7 +1354,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_onDemandB ), }, { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandBaseCapacity(rName, 0), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandBaseCapacity(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1832,7 +1379,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_updateToZ CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandBaseCapacity(rName, 1), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandBaseCapacity(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1840,21 +1387,9 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_updateToZ resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.on_demand_base_capacity", "1"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandBaseCapacity(rName, 0), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandBaseCapacity(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1862,19 +1397,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_updateToZ resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.on_demand_base_capacity", "0"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } @@ -1891,7 +1414,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_onDemandP CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandPercentageAboveBaseCapacity(rName, 1), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandPercentageAboveBaseCapacity(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1899,21 +1422,9 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_onDemandP resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.on_demand_percentage_above_base_capacity", "1"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandPercentageAboveBaseCapacity(rName, 2), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandPercentageAboveBaseCapacity(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1937,7 +1448,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_spotAlloc CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotAllocationStrategy(rName, "lowest-price"), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionSpotAllocationStrategy(rName, "lowest-price"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1945,19 +1456,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_spotAlloc resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.spot_allocation_strategy", "lowest-price"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } @@ -1974,7 +1473,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_spotInsta CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotInstancePools(rName, 2), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionSpotInstancePools(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -1982,21 +1481,9 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_spotInsta resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.spot_instance_pools", "2"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotInstancePools(rName, 3), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionSpotInstancePools(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2020,7 +1507,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_spotMaxPr CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotMaxPrice(rName, "0.50"), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionSpotMaxPrice(rName, "0.50"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2028,21 +1515,9 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_spotMaxPr resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.spot_max_price", "0.50"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotMaxPrice(rName, "0.51"), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionSpotMaxPrice(rName, "0.51"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2051,7 +1526,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyInstancesDistribution_spotMaxPr ), }, { - Config: testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotMaxPrice(rName, ""), + Config: testAccGroupConfig_mixedInstancesPolicyInstancesDistributionSpotMaxPrice(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2075,7 +1550,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateLaunchTemplateSpe CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_LaunchTemplateSpecification_LaunchTemplateName(rName), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateLaunchTemplateSpecificationLaunchTemplateName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2084,19 +1559,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateLaunchTemplateSpe resource.TestCheckResourceAttrSet(resourceName, "mixed_instances_policy.0.launch_template.0.launch_template_specification.0.launch_template_name"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } @@ -2113,7 +1576,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateLaunchTemplateSpe CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_LaunchTemplateSpecification_Version(rName, "1"), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateLaunchTemplateSpecificationVersion(rName, "1"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2122,21 +1585,9 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateLaunchTemplateSpe resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.launch_template_specification.0.version", "1"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_LaunchTemplateSpecification_Version(rName, "$Latest"), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateLaunchTemplateSpecificationVersion(rName, "$Latest"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2161,7 +1612,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instance CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_InstanceType(rName, "t3.small"), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceType(rName, "t3.small"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2171,21 +1622,9 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instance resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.instance_type", "t3.small"), ), }, + testAccGroupImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - { - Config: testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_InstanceType(rName, "t3.medium"), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceType(rName, "t3.medium"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2203,7 +1642,6 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instance var group autoscaling.Group resourceName := "aws_autoscaling_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -2212,7 +1650,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instance CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_InstanceType_With_LaunchTemplateSpecification(rName, rName2), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceTypeLaunchTemplateSpecification(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2220,24 +1658,11 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instance resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "2"), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_type", "t2.micro"), resource.TestCheckNoResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.launch_template_specification.#"), - resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.instance_type", "t4g.micro"), - resource.TestCheckResourceAttrPair(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.launch_template_specification.0.launch_template_id", "aws_launch_template.testarm", "id"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.instance_type", "t4g.small"), + resource.TestCheckResourceAttrPair(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.launch_template_specification.0.launch_template_id", "aws_launch_template.test-arm", "id"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "name_prefix", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } @@ -2254,7 +1679,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_weighted CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_WeightedCapacity(rName), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideWeightedCapacity(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2266,19 +1691,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_weighted resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.weighted_capacity", "4"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } @@ -2295,7 +1708,7 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_weighted CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_WeightedCapacity_WithELB(rName), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideWeightedCapacityELB(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), @@ -2307,27 +1720,15 @@ func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_weighted resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.1.weighted_capacity", "2"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, + testAccGroupImportStep(resourceName), }, }) } -func TestAccAutoScalingGroup_launchTempPartitionNum(t *testing.T) { +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_memoryMiBAndVCPUCount(t *testing.T) { var group autoscaling.Group - - randName := fmt.Sprintf("terraform-test-%s", sdkacctest.RandString(10)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -2336,31 +1737,62 @@ func TestAccAutoScalingGroup_launchTempPartitionNum(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupPartitionConfig(randName), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), Check: resource.ComposeTestCheckFunc( - testAccCheckGroupExists("aws_autoscaling_group.test", &group), + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), + + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_mib.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_mib.0.min", "500"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.vcpu_count.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.vcpu_count.0.min", "1"), ), }, - { - ResourceName: "aws_autoscaling_group.test", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `memory_mib { + min = 1000 + max = 10000 + } + vcpu_count { + min = 2 + max = 12 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), + + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_mib.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_mib.0.min", "1000"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_mib.0.max", "10000"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.vcpu_count.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.vcpu_count.0.min", "2"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.vcpu_count.0.max", "12"), + ), }, + testAccGroupImportStep(resourceName), }, }) } -func TestAccAutoScalingGroup_Destroy_whenProtectedFromScaleIn(t *testing.T) { +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_acceleratorCount(t *testing.T) { var group autoscaling.Group - rName := fmt.Sprintf("terraform-test-%s", sdkacctest.RandString(10)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_autoscaling_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -2370,1657 +1802,2289 @@ func TestAccAutoScalingGroup_Destroy_whenProtectedFromScaleIn(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_DestroyWhenProtectedFromScaleIn_beforeDestroy(rName), + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_count { + min = 2 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), - testAccCheckGroupHealthyCapacity(&group, 2), - resource.TestCheckResourceAttr(resourceName, "protect_from_scale_in", "true"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), + + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_count.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_count.0.min", "2"), ), }, - { - Config: testAccGroupConfig_DestroyWhenProtectedFromScaleIn_afterDestroy(), - // Reaching this step is good enough, as it indicates the ASG was destroyed successfully. + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_count { + min = 1 + max = 3 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), + + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_count.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_count.0.min", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_count.0.max", "3"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_count { + max = 0 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), + + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_count.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_count.0.max", "0"), + ), }, + testAccGroupImportStep(resourceName), }, }) } -func testAccGroupNameGeneratedConfig() string { - return acctest.ConfigCompose( - acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - ` -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" -} - -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - max_size = 0 - min_size = 0 - launch_configuration = aws_launch_configuration.test.name -} -`) -} - -func testAccGroupNamePrefixConfig(namePrefix string) string { - return acctest.ConfigCompose( - acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - fmt.Sprintf(` -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" -} - -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - max_size = 0 - min_size = 0 - name_prefix = %[1]q - launch_configuration = aws_launch_configuration.test.name -} -`, namePrefix)) -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_acceleratorManufacturers(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -func testAccGroupConfig_terminationPoliciesEmpty() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_manufacturers = ["amazon-web-services"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_manufacturers.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_manufacturers.*", "amazon-web-services"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_manufacturers = ["amazon-web-services", "amd", "nvidia", "xilinx"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), + + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_manufacturers.#", "4"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_manufacturers.*", "amazon-web-services"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_manufacturers.*", "amd"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_manufacturers.*", "nvidia"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_manufacturers.*", "xilinx"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_acceleratorNames(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - max_size = 0 - min_size = 0 - desired_capacity = 0 + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_names = ["a100"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - launch_configuration = aws_launch_configuration.foobar.name -} -`) + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.*", "a100"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_names = ["a100", "v100", "k80", "t4", "m60", "radeon-pro-v520", "vu9p"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), + + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.#", "7"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.*", "a100"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.*", "v100"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.*", "k80"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.*", "t4"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.*", "m60"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.*", "radeon-pro-v520"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_names.*", "vu9p"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -func testAccGroupConfig_terminationPoliciesExplicitDefault() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_acceleratorTotalMemoryMiB(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_total_memory_mib { + min = 32 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_total_memory_mib.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_total_memory_mib.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_total_memory_mib.0.min", "32"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_total_memory_mib { + max = 12000 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - max_size = 0 - min_size = 0 - desired_capacity = 0 - termination_policies = ["Default"] + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_total_memory_mib.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_total_memory_mib.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_total_memory_mib.0.max", "12000"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_total_memory_mib { + min = 32 + max = 12000 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - launch_configuration = aws_launch_configuration.foobar.name -} -`) + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_total_memory_mib.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_total_memory_mib.0.min", "32"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_total_memory_mib.0.max", "12000"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -func testAccGroupConfig_terminationPoliciesUpdate() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_acceleratorTypes(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} - -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} - -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - max_size = 0 - min_size = 0 - desired_capacity = 0 - termination_policies = ["OldestInstance"] - - launch_configuration = aws_launch_configuration.foobar.name -} -`) -} - -func testAccGroupConfig(name string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} - -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} - -# TODO: Unused? -resource "aws_placement_group" "test" { - name = "asg_pg_%s" - strategy = "cluster" -} - -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - name = "%s" - max_size = 5 - min_size = 2 - health_check_type = "ELB" - desired_capacity = 4 - force_delete = true - termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - - launch_configuration = aws_launch_configuration.foobar.name - - tags = [ - { - key = "FromTags1" - value = "value1" - propagate_at_launch = true - }, - { - key = "FromTags3" - value = "value3" - propagate_at_launch = true - }, - { - key = "FromTags2" - value = "value2" - propagate_at_launch = true - }, - ] -} -`, name, name) -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_types = ["fpga"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -func testAccGroupUpdateConfig(name string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_types.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_types.*", "fpga"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `accelerator_types = ["fpga", "gpu", "inference"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_types.#", "3"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_types.*", "fpga"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_types.*", "gpu"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.accelerator_types.*", "inference"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_bareMetal(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -resource "aws_launch_configuration" "new" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `bare_metal = "excluded" + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - name = "%s" - max_size = 5 - min_size = 2 - health_check_grace_period = 300 - health_check_type = "ELB" - desired_capacity = 5 - force_delete = true - termination_policies = ["ClosestToNextInstanceHour"] - protect_from_scale_in = true + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.bare_metal", "excluded"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `bare_metal = "included" + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - launch_configuration = aws_launch_configuration.new.name - - tags = [ - { - key = "FromTags1Changed" - value = "value1changed" - propagate_at_launch = true - }, - { - key = "FromTags2" - value = "value2changed" - propagate_at_launch = true - }, - { - key = "FromTags3" - value = "value3" - propagate_at_launch = true - }, - ] -} -`, name) -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.bare_metal", "included"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `bare_metal = "required" + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -func testAccGroupWithLoadBalancerConfig() string { - return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -resource "aws_vpc" "foo" { - cidr_block = "10.1.0.0/16" - tags = { - Name = "terraform-testacc-autoscaling-group-with-lb" - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.bare_metal", "required"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_internet_gateway" "gw" { - vpc_id = aws_vpc.foo.id -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_baselineEBSBandwidthMbps(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -resource "aws_subnet" "foo" { - availability_zone = data.aws_availability_zones.available.names[0] - cidr_block = "10.1.1.0/24" - vpc_id = aws_vpc.foo.id - tags = { - Name = "tf-acc-autoscaling-group-with-load-balancer" - } -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `baseline_ebs_bandwidth_mbps { + min = 10 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_security_group" "foo" { - vpc_id = aws_vpc.foo.id + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.baseline_ebs_bandwidth_mbps.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.baseline_ebs_bandwidth_mbps.0.min", "10"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `baseline_ebs_bandwidth_mbps { + max = 20000 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - ingress { - protocol = "-1" - from_port = 0 - to_port = 0 - cidr_blocks = ["0.0.0.0/0"] - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.baseline_ebs_bandwidth_mbps.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.baseline_ebs_bandwidth_mbps.0.max", "20000"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `baseline_ebs_bandwidth_mbps { + min = 10 + max = 20000 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - egress { - protocol = "-1" - from_port = 0 - to_port = 0 - cidr_blocks = ["0.0.0.0/0"] - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.baseline_ebs_bandwidth_mbps.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.baseline_ebs_bandwidth_mbps.0.min", "10"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.baseline_ebs_bandwidth_mbps.0.max", "20000"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_elb" "bar" { - subnets = [aws_subnet.foo.id] - security_groups = [aws_security_group.foo.id] - - listener { - instance_port = 80 - instance_protocol = "http" - lb_port = 80 - lb_protocol = "http" - } +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_burstablePerformance(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" - health_check { - healthy_threshold = 2 - unhealthy_threshold = 2 - target = "HTTP:80/" - interval = 5 - timeout = 2 - } + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `burstable_performance = "excluded" + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - depends_on = [aws_internet_gateway.gw] -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.burstable_performance", "excluded"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `burstable_performance = "included" + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" - security_groups = [aws_security_group.foo.id] + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.burstable_performance", "included"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `burstable_performance = "required" + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - # Need the instance to listen on port 80 at boot - user_data = < index.html -nohup python -m SimpleHTTPServer 80 & -EOF + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.burstable_performance", "required"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_autoscaling_group" "bar" { - vpc_zone_identifier = [aws_subnet.foo.id] - max_size = 2 - min_size = 2 - health_check_grace_period = 300 - health_check_type = "ELB" - wait_for_elb_capacity = 2 - force_delete = true - - launch_configuration = aws_launch_configuration.foobar.name - load_balancers = [aws_elb.bar.name] -} -`) -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_cpuManufacturers(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -func testAccGroupWithTargetGroupConfig() string { - return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -resource "aws_vpc" "foo" { - cidr_block = "10.1.0.0/16" - tags = { - Name = "terraform-testacc-autoscaling-group-with-lb" - } -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `cpu_manufacturers = ["amazon-web-services"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_internet_gateway" "gw" { - vpc_id = aws_vpc.foo.id -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.cpu_manufacturers.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.cpu_manufacturers.*", "amazon-web-services"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `cpu_manufacturers = ["amazon-web-services", "amd", "intel"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_subnet" "foo" { - availability_zone = data.aws_availability_zones.available.names[0] - cidr_block = "10.1.1.0/24" - vpc_id = aws_vpc.foo.id - tags = { - Name = "tf-acc-autoscaling-group-with-target-group" - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.cpu_manufacturers.#", "3"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.cpu_manufacturers.*", "amazon-web-services"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.cpu_manufacturers.*", "amd"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.cpu_manufacturers.*", "intel"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_security_group" "foo" { - vpc_id = aws_vpc.foo.id +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_excludedInstanceTypes(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" - ingress { - protocol = "-1" - from_port = 0 - to_port = 0 - cidr_blocks = ["0.0.0.0/0"] - } + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `excluded_instance_types = ["t2.nano"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - egress { - protocol = "-1" - from_port = 0 - to_port = 0 - cidr_blocks = ["0.0.0.0/0"] - } -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.excluded_instance_types.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.excluded_instance_types.*", "t2.nano"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `excluded_instance_types = ["t2.nano", "t3*", "t4g.*"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_lb_target_group" "foo" { - port = 80 - protocol = "HTTP" - vpc_id = aws_vpc.foo.id + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.excluded_instance_types.#", "3"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.excluded_instance_types.*", "t2.nano"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.excluded_instance_types.*", "t3*"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.excluded_instance_types.*", "t4g.*"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_elb" "bar" { - subnets = [aws_subnet.foo.id] - security_groups = [aws_security_group.foo.id] - - listener { - instance_port = 80 - instance_protocol = "http" - lb_port = 80 - lb_protocol = "http" - } - - health_check { - healthy_threshold = 2 - unhealthy_threshold = 2 - target = "HTTP:80/" - interval = 5 - timeout = 2 - } +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_instanceGenerations(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" - depends_on = [aws_internet_gateway.gw] -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `instance_generations = ["current"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" - security_groups = [aws_security_group.foo.id] + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.instance_generations.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.instance_generations.*", "current"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `instance_generations = ["current", "previous"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - # Need the instance to listen on port 80 at boot - user_data = < index.html -nohup python -m SimpleHTTPServer 80 & -EOF + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.instance_generations.#", "2"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.instance_generations.*", "current"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.instance_generations.*", "previous"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_autoscaling_group" "bar" { - vpc_zone_identifier = [aws_subnet.foo.id] - max_size = 2 - min_size = 2 - health_check_grace_period = 300 - health_check_type = "ELB" - wait_for_elb_capacity = 2 - force_delete = true - - launch_configuration = aws_launch_configuration.foobar.name - target_group_arns = [aws_lb_target_group.foo.arn] -} -`) -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_localStorage(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -func testAccGroupWithAZConfig() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -resource "aws_vpc" "default" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-autoscaling-group-with-az" - } -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `local_storage = "excluded" + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_subnet" "main" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] - tags = { - Name = "tf-acc-autoscaling-group-with-az" - } -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.local_storage", "excluded"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `local_storage = "included" + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.local_storage", "included"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `local_storage = "required" + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.local_storage", "required"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_localStorageTypes(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -resource "aws_autoscaling_group" "bar" { - availability_zones = [ - data.aws_availability_zones.available.names[0] - ] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = aws_launch_configuration.foobar.name -} -`) -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `local_storage_types = ["hdd"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -func testAccGroupWithVPCIdentConfig() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -resource "aws_vpc" "default" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-autoscaling-group-with-vpc-id" - } -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.local_storage_types.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.local_storage_types.*", "hdd"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `local_storage_types = ["hdd", "ssd"] + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_subnet" "main" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] - tags = { - Name = "tf-acc-autoscaling-group-with-vpc-id" - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.local_storage_types.#", "2"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.local_storage_types.*", "hdd"), + resource.TestCheckTypeSetElemAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.local_storage_types.*", "ssd"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_memoryGiBPerVCPU(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `memory_gib_per_vcpu { + min = 0.5 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_autoscaling_group" "bar" { - vpc_zone_identifier = [ - aws_subnet.main.id, - ] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = aws_launch_configuration.foobar.name -} -`) -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_gib_per_vcpu.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_gib_per_vcpu.0.min", "0.5"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `memory_gib_per_vcpu { + max = 9.5 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -func testAccGroupConfig_withPlacementGroup(name string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_gib_per_vcpu.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_gib_per_vcpu.0.max", "9.5"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `memory_gib_per_vcpu { + min = 0.5 + max = 9.5 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_gib_per_vcpu.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_gib_per_vcpu.0.min", "0.5"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.memory_gib_per_vcpu.0.max", "9.5"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "c3.large" -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_networkInterfaceCount(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -resource "aws_placement_group" "test" { - name = "%s" - strategy = "cluster" -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `network_interface_count { + min = 1 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - name = "%s" - max_size = 1 - min_size = 1 - health_check_grace_period = 300 - health_check_type = "ELB" - desired_capacity = 1 - force_delete = true - termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - placement_group = aws_placement_group.test.name + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.network_interface_count.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.network_interface_count.0.min", "1"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `network_interface_count { + max = 10 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - launch_configuration = aws_launch_configuration.foobar.name + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.network_interface_count.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.network_interface_count.0.max", "10"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `network_interface_count { + min = 1 + max = 10 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - tag { - key = "Foo" - value = "foo-bar" - propagate_at_launch = true - } -} -`, name, name) + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.network_interface_count.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.network_interface_count.0.min", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.network_interface_count.0.max", "10"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -func testAccGroupConfig_withServiceLinkedRoleARN() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_onDemandMaxPricePercentageOverLowestPrice(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -data "aws_iam_role" "autoscaling_service_linked_role" { - name = "AWSServiceRoleForAutoScaling" -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `on_demand_max_price_percentage_over_lowest_price = 50 + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.on_demand_max_price_percentage_over_lowest_price", "50"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = aws_launch_configuration.foobar.name - service_linked_role_arn = data.aws_iam_role.autoscaling_service_linked_role.arn -} -`) -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_requireHibernateSupport(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -func testAccGroupConfig_withMaxInstanceLifetime() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `require_hibernate_support = false + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.require_hibernate_support", "false"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `require_hibernate_support = true + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.require_hibernate_support", "true"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = aws_launch_configuration.foobar.name - max_instance_lifetime = "864000" -} -`) -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_spotMaxPricePercentageOverLowestPrice(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -func testAccGroupConfig_withMaxInstanceLifetime_update() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `spot_max_price_percentage_over_lowest_price = 75 + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.spot_max_price_percentage_over_lowest_price", "75"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} +func TestAccAutoScalingGroup_MixedInstancesPolicyLaunchTemplateOverride_instanceRequirements_totalLocalStorageGB(t *testing.T) { + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_autoscaling_group.test" -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = aws_launch_configuration.foobar.name - max_instance_lifetime = "604800" -} -`) -} + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `total_local_storage_gb { + min = 0.5 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -func testAccMetricsCollectionConfig_allMetricsCollected() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.total_local_storage_gb.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.total_local_storage_gb.0.min", "0.5"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `total_local_storage_gb { + max = 20.5 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.total_local_storage_gb.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.total_local_storage_gb.0.max", "20.5"), + ), + }, + testAccGroupImportStep(resourceName), + { + Config: testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName, + `total_local_storage_gb { + min = 0.5 + max = 20.5 + } + memory_mib { + min = 500 + } + vcpu_count { + min = 1 + }`), + Check: resource.ComposeTestCheckFunc( + testAccCheckGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.#", "1"), -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.total_local_storage_gb.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.total_local_storage_gb.0.min", "0.5"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.launch_template.0.override.0.instance_requirements.0.total_local_storage_gb.0.max", "20.5"), + ), + }, + testAccGroupImportStep(resourceName), + }, + }) } -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - max_size = 1 - min_size = 0 - health_check_grace_period = 300 - health_check_type = "EC2" - desired_capacity = 0 - force_delete = true - termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - launch_configuration = aws_launch_configuration.foobar.name - enabled_metrics = ["GroupTotalInstances", - "GroupPendingInstances", - "GroupTerminatingInstances", - "GroupDesiredCapacity", - "GroupInServiceInstances", - "GroupMinSize", - "GroupMaxSize", - "GroupPendingCapacity", - "GroupInServiceCapacity", - "GroupStandbyCapacity", - "GroupTotalCapacity", - "GroupTerminatingCapacity", - "GroupStandbyInstances" - ] - metrics_granularity = "1Minute" -} -`) -} +func testAccCheckGroupExists(n string, v *autoscaling.Group) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Auto Scaling Group ID is set") + } -func testAccMetricsCollectionConfig_updatingMetricsCollected() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + conn := acctest.Provider.Meta().(*conns.AWSClient).AutoScalingConn - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + output, err := tfautoscaling.FindGroupByName(conn, rs.Primary.ID) -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} + if err != nil { + return err + } -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - max_size = 1 - min_size = 0 - health_check_grace_period = 300 - health_check_type = "EC2" - desired_capacity = 0 - force_delete = true - termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - launch_configuration = aws_launch_configuration.foobar.name - enabled_metrics = ["GroupTotalInstances", - "GroupPendingInstances", - "GroupTerminatingInstances", - "GroupDesiredCapacity", - "GroupMaxSize" - ] - metrics_granularity = "1Minute" -} -`) + *v = *output + + return nil + } } -func testAccGroupConfig_ALB_TargetGroup_pre(rName string) string { - return acctest.ConfigCompose( - acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - fmt.Sprintf(` -resource "aws_vpc" "default" { - cidr_block = "10.0.0.0/16" +func testAccCheckGroupDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).AutoScalingConn - tags = { - Name = "terraform-testacc-autoscaling-group-alb-target-group" - } -} + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_autoscaling_group" { + continue + } -resource "aws_lb_target_group" "test" { - name = %[1]q - port = 80 - protocol = "HTTP" - vpc_id = aws_vpc.default.id -} + _, err := tfautoscaling.FindGroupByName(conn, rs.Primary.ID) -resource "aws_subnet" "main" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] + if tfresource.NotFound(err) { + continue + } - tags = { - Name = %[1]q - } -} + if err != nil { + return err + } -resource "aws_subnet" "alt" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] + return fmt.Errorf("Auto Scaling Group %s still exists", rs.Primary.ID) + } - tags = { - Name = %[1]q - } + return nil } -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func testAccCheckGroupHealthyInstanceCount(v *autoscaling.Group, expected int) resource.TestCheckFunc { + return func(s *terraform.State) error { + count := 0 - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + for _, v := range v.Instances { + if aws.StringValue(v.HealthStatus) == tfautoscaling.InstanceHealthStatusHealthy { + count++ + } + } -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" - enable_monitoring = false + if count < expected { + return fmt.Errorf("Expected at least %d healthy instances, got %d", expected, count) + } + + return nil + } } -resource "aws_autoscaling_group" "bar" { - vpc_zone_identifier = [ - aws_subnet.main.id, - aws_subnet.alt.id, - ] +func testAccCheckInstanceRefreshCount(v *autoscaling.Group, expected int) resource.TestCheckFunc { + return func(state *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).AutoScalingConn - max_size = 2 - min_size = 0 - health_check_grace_period = 300 - health_check_type = "ELB" - desired_capacity = 0 - force_delete = true - termination_policies = ["OldestInstance"] - launch_configuration = aws_launch_configuration.foobar.name -} + output, err := tfautoscaling.FindInstanceRefreshes(conn, &autoscaling.DescribeInstanceRefreshesInput{ + AutoScalingGroupName: v.AutoScalingGroupName, + }) -resource "aws_security_group" "tf_test_self" { - name = %[1]q - description = %[1]q - vpc_id = aws_vpc.default.id + if err != nil { + return err + } - ingress { - from_port = 80 - to_port = 80 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } + if got := len(output); got != expected { + return fmt.Errorf("Expected %d Instance Refreshes, got %d", expected, got) + } - tags = { - Name = %[1]q - } -} -`, rName)) + return nil + } } -func testAccGroupConfig_ALB_TargetGroup_post(rName string) string { - return acctest.ConfigCompose( - acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - fmt.Sprintf(` -resource "aws_vpc" "default" { - cidr_block = "10.0.0.0/16" +func testAccCheckInstanceRefreshStatus(v *autoscaling.Group, index int, expected ...string) resource.TestCheckFunc { + return func(state *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).AutoScalingConn - tags = { - Name = %[1]q - } -} + output, err := tfautoscaling.FindInstanceRefreshes(conn, &autoscaling.DescribeInstanceRefreshesInput{ + AutoScalingGroupName: v.AutoScalingGroupName, + }) -resource "aws_lb_target_group" "test" { - name = %[1]q - port = 80 - protocol = "HTTP" - vpc_id = aws_vpc.default.id -} + if err != nil { + return err + } -resource "aws_subnet" "main" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] + if got := len(output); got < index { + return fmt.Errorf("Expected at least %d Instance Refreshes, got %d", index+1, got) + } - tags = { - Name = %[1]q - } -} + status := aws.StringValue(output[index].Status) -resource "aws_subnet" "alt" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] + for _, v := range expected { + if status == v { + return nil + } + } - tags = { - Name = "%[1]s-2" - } + return fmt.Errorf("Expected Instance Refresh at index %d to be in %q, got %q", index, expected, status) + } } -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func testAccCheckLBTargetGroupExists(n string, v *elbv2.TargetGroup) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + if rs.Primary.ID == "" { + return errors.New("No ELBv2 Target Group ID is set") + } -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" - enable_monitoring = false -} + conn := acctest.Provider.Meta().(*conns.AWSClient).ELBV2Conn -resource "aws_autoscaling_group" "bar" { - vpc_zone_identifier = [ - aws_subnet.main.id, - aws_subnet.alt.id, - ] + output, err := tfelbv2.FindTargetGroupByARN(conn, rs.Primary.ID) - target_group_arns = [aws_lb_target_group.test.arn] + if err != nil { + return fmt.Errorf("error reading ELBv2 Target Group (%s): %w", rs.Primary.ID, err) + } - max_size = 2 - min_size = 0 - health_check_grace_period = 300 - health_check_type = "ELB" - desired_capacity = 0 - force_delete = true - termination_policies = ["OldestInstance"] - launch_configuration = aws_launch_configuration.foobar.name + if output == nil { + return fmt.Errorf("ELBv2 Target Group (%s) not found", rs.Primary.ID) + } + + *v = *output + + return nil + } } -resource "aws_security_group" "tf_test_self" { - name = %[1]q - description = %[1]q - vpc_id = aws_vpc.default.id +// testAccCheckALBTargetGroupHealthy checks an *elbv2.TargetGroup to make +// sure that all instances in it are healthy. +func testAccCheckALBTargetGroupHealthy(v *elbv2.TargetGroup) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).ELBV2Conn - ingress { - from_port = 80 - to_port = 80 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } + output, err := conn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{ + TargetGroupArn: v.TargetGroupArn, + }) - tags = { - Name = %[1]q - } -} -`, rName)) + if err != nil { + return err + } + + for _, v := range output.TargetHealthDescriptions { + if v.TargetHealth == nil || aws.StringValue(v.TargetHealth.State) != elbv2.TargetHealthStateEnumHealthy { + return errors.New("Not all instances in target group are healthy yet, but should be") + } + } + + return nil + } } -func testAccGroupConfig_ALB_TargetGroup_post_duo(rName string) string { +func testAccGroupLaunchConfigurationBaseConfig(rName, instanceType string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` -resource "aws_vpc" "default" { - cidr_block = "10.0.0.0/16" - - tags = { - Name = %[1]q - } +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = %[2]q +} +`, rName, instanceType)) } -resource "aws_lb_target_group" "test" { - name = %[1]q - port = 80 - protocol = "HTTP" - vpc_id = aws_vpc.default.id +func testAccGroupLaunchTemplateBaseConfig(rName, instanceType string) string { + // Include a Launch Configuration so that we can test swapping between Launch Template and Launch Configuration and vice-versa. + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, instanceType), fmt.Sprintf(` +resource "aws_launch_template" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = %[2]q +} +`, rName, instanceType)) } -resource "aws_lb_target_group" "test_more" { - name = format("%%s-%%s", substr(%[1]q, 0, 28), "2") - port = 80 - protocol = "HTTP" - vpc_id = aws_vpc.default.id +func testAccGroupConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name +} +`, rName)) } -resource "aws_subnet" "main" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] +func testAccGroupConfig_nameGenerated(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), ` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + launch_configuration = aws_launch_configuration.test.name +} +`) +} - tags = { - Name = %[1]q - } +func testAccGroupConfig_namePrefix(rName, namePrefix string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name_prefix = %[1]q + launch_configuration = aws_launch_configuration.test.name +} +`, namePrefix)) } -resource "aws_subnet" "alt" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] +func testAccGroupConfig_tags1(rName, tagKey1, tagValue1 string, tagPropagateAtLaunch1 bool) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name - tags = { - Name = "%[1]s-2" + tag { + key = %[2]q + value = %[3]q + propagate_at_launch = %[4]t } } +`, rName, tagKey1, tagValue1, tagPropagateAtLaunch1)) +} + +func testAccGroupConfig_tags2(rName, tagKey1, tagValue1 string, tagPropagateAtLaunch1 bool, tagKey2, tagValue2 string, tagPropagateAtLaunch2 bool) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + tag { + key = %[2]q + value = %[3]q + propagate_at_launch = %[4]t + } - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + tag { + key = %[5]q + value = %[6]q + propagate_at_launch = %[7]t } } - -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" - enable_monitoring = false +`, rName, tagKey1, tagValue1, tagPropagateAtLaunch1, tagKey2, tagValue2, tagPropagateAtLaunch2)) } -resource "aws_autoscaling_group" "bar" { - vpc_zone_identifier = [ - aws_subnet.main.id, - aws_subnet.alt.id, - ] - - target_group_arns = [ - aws_lb_target_group.test.arn, - aws_lb_target_group.test_more.arn, - ] +func testAccGroupConfig_deprecatedTags1(rName, tagKey1, tagValue1 string, tagPropagateAtLaunch1 bool) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name - max_size = 2 - min_size = 0 - health_check_grace_period = 300 - health_check_type = "ELB" - desired_capacity = 0 - force_delete = true - termination_policies = ["OldestInstance"] - launch_configuration = aws_launch_configuration.foobar.name + tags = [{ + "key" = %[2]q + "value" = %[3]q + "propagate_at_launch" = %[4]t + }] +} +`, rName, tagKey1, tagValue1, tagPropagateAtLaunch1)) } -resource "aws_security_group" "tf_test_self" { - name = %[1]q - description = %[1]q - vpc_id = aws_vpc.default.id - - ingress { - from_port = 80 - to_port = 80 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } +func testAccGroupConfig_simple(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 5 + min_size = 2 + health_check_type = "ELB" + desired_capacity = 4 + force_delete = true + termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] + launch_configuration = aws_launch_configuration.test.name - tags = { - Name = %[1]q + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } `, rName)) } -func testAccGroupConfig_TargetGroupARNs(rName string, tgCount int) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } +func testAccGroupConfig_simpleUpdated(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_launch_configuration" "test2" { + name = "%[1]s-2" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" } -resource "aws_launch_template" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.micro" - name = %[1]q -} +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 6 + min_size = 3 + health_check_grace_period = 400 + health_check_type = "ELB" + desired_capacity = 4 + force_delete = true + termination_policies = ["ClosestToNextInstanceHour"] + protect_from_scale_in = true -resource "aws_vpc" "test" { - cidr_block = "10.0.0.0/16" + launch_configuration = aws_launch_configuration.test2.name - tags = { - Name = %[1]q + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } - -resource "aws_subnet" "test" { - availability_zone = data.aws_availability_zones.available.names[0] - cidr_block = "10.0.0.0/24" - vpc_id = aws_vpc.test.id - - tags = { - Name = %[1]q - } +`, rName)) } -resource "aws_lb_target_group" "test" { - count = %[2]d - - port = 80 - protocol = "HTTP" - vpc_id = aws_vpc.test.id +func testAccGroupConfig_terminationPoliciesExplicitDefault(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name + termination_policies = ["Default"] +} +`, rName)) } +func testAccGroupConfig_terminationPoliciesUpdated(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - force_delete = true - max_size = 0 - min_size = 0 - target_group_arns = length(aws_lb_target_group.test) > 0 ? aws_lb_target_group.test[*].arn : [] - vpc_zone_identifier = [aws_subnet.test.id] - - launch_template { - id = aws_launch_template.test.id - } + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name + termination_policies = ["OldestInstance"] } -`, rName, tgCount) +`, rName)) } -func testAccGroupWithHookConfig(name string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + +func testAccGroupConfig_az(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + acctest.ConfigVPCWithSubnets(rName, 1), fmt.Sprintf(` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} - -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t2.micro" } -resource "aws_autoscaling_group" "bar" { +resource "aws_autoscaling_group" "test" { availability_zones = [data.aws_availability_zones.available.names[0]] - name = "%s" - max_size = 5 - min_size = 2 - health_check_type = "ELB" - desired_capacity = 4 - force_delete = true - termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name + + depends_on = [aws_subnet.test[0]] +} +`, rName)) +} - launch_configuration = aws_launch_configuration.foobar.name +func testAccGroupConfig_vpcZoneIdentifier(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + acctest.ConfigVPCWithSubnets(rName, 1), + fmt.Sprintf(` +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" +} - initial_lifecycle_hook { - name = "launching" - default_result = "CONTINUE" - heartbeat_timeout = 30 # minimum value - lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING" - } +resource "aws_autoscaling_group" "test" { + vpc_zone_identifier = aws_subnet.test[*].id + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name } -`, name) +`, rName)) } -func testAccGroupConfig_ALB_TargetGroup_ELBCapacity(rInt int) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + +func testAccGroupELBBaseConfig(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + acctest.ConfigVPCWithSubnets(rName, 1), fmt.Sprintf(` -resource "aws_vpc" "default" { - cidr_block = "10.0.0.0/16" - enable_dns_hostnames = "true" - enable_dns_support = "true" +resource "aws_internet_gateway" "test" { + vpc_id = aws_vpc.test.id tags = { - Name = "terraform-testacc-autoscaling-group-alb-target-group-elb-capacity" + Name = %[1]q } } -resource "aws_lb" "test_lb" { - subnets = [aws_subnet.main.id, aws_subnet.alt.id] +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id - tags = { - Name = "testAccGroupConfig_ALB_TargetGroup_ELBCapacity" + ingress { + protocol = "-1" + from_port = 0 + to_port = 0 + cidr_blocks = ["0.0.0.0/0"] } -} -resource "aws_lb_listener" "test_listener" { - load_balancer_arn = aws_lb.test_lb.arn - port = "80" + egress { + protocol = "-1" + from_port = 0 + to_port = 0 + cidr_blocks = ["0.0.0.0/0"] + } - default_action { - target_group_arn = aws_lb_target_group.test.arn - type = "forward" + tags = { + Name = %[1]q } } resource "aws_lb_target_group" "test" { - name = "tf-alb-test-%d" + name = %[1]q port = 80 protocol = "HTTP" - vpc_id = aws_vpc.default.id - - health_check { - path = "/" - healthy_threshold = "2" - timeout = "2" - interval = "5" - matcher = "200" - } - - tags = { - Name = "testAccGroupConfig_ALB_TargetGroup_ELBCapacity" - } + vpc_id = aws_vpc.test.id } -resource "aws_subnet" "main" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] +resource "aws_elb" "test" { + name = %[1]q + subnets = aws_subnet.test[*].id + security_groups = [aws_security_group.test.id] - tags = { - Name = "tf-acc-autoscaling-group-alb-target-group-elb-capacity-main" + listener { + instance_port = 80 + instance_protocol = "http" + lb_port = 80 + lb_protocol = "http" } -} -resource "aws_subnet" "alt" { - vpc_id = aws_vpc.default.id - cidr_block = "10.0.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] - - tags = { - Name = "tf-acc-autoscaling-group-alb-target-group-elb-capacity-alt" + health_check { + healthy_threshold = 2 + unhealthy_threshold = 2 + target = "HTTP:80/" + interval = 5 + timeout = 2 } -} -resource "aws_internet_gateway" "internet_gateway" { - vpc_id = aws_vpc.default.id + depends_on = [aws_internet_gateway.test] } -resource "aws_route_table" "route_table" { - vpc_id = aws_vpc.default.id -} +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + security_groups = [aws_security_group.test.id] -resource "aws_route_table_association" "route_table_association_main" { - subnet_id = aws_subnet.main.id - route_table_id = aws_route_table.route_table.id + # Need the instance to listen on port 80 at boot + user_data = < index.html +nohup python -m SimpleHTTPServer 80 & +EOF } - -resource "aws_route_table_association" "route_table_association_alt" { - subnet_id = aws_subnet.alt.id - route_table_id = aws_route_table.route_table.id +`, rName)) } -resource "aws_route" "public_default_route" { - route_table_id = aws_route_table.route_table.id - destination_cidr_block = "0.0.0.0/0" - gateway_id = aws_internet_gateway.internet_gateway.id -} +func testAccGroupConfig_loadBalancer(rName string) string { + return acctest.ConfigCompose(testAccGroupELBBaseConfig(rName), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + vpc_zone_identifier = aws_subnet.test[*].id + max_size = 2 + min_size = 2 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] + health_check_grace_period = 300 + health_check_type = "ELB" + wait_for_elb_capacity = 2 + force_delete = true + load_balancers = [aws_elb.test.name] - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } - -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" - associate_public_ip_address = "true" - - user_data = < /var/www/html/index.html -chkconfig httpd on -service httpd start -EOS +`, rName)) } -resource "aws_autoscaling_group" "bar" { - vpc_zone_identifier = [ - aws_subnet.main.id, - aws_subnet.alt.id, - ] - - target_group_arns = [aws_lb_target_group.test.arn] +func testAccGroupConfig_target2(rName string) string { + return acctest.ConfigCompose(testAccGroupELBBaseConfig(rName), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + vpc_zone_identifier = aws_subnet.test[*].id + max_size = 2 + min_size = 2 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name - max_size = 2 - min_size = 2 health_check_grace_period = 300 health_check_type = "ELB" - desired_capacity = 2 wait_for_elb_capacity = 2 force_delete = true - termination_policies = ["OldestInstance"] - launch_configuration = aws_launch_configuration.foobar.name + target_group_arns = [aws_lb_target_group.test.arn] + + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } } -`, rInt) +`, rName)) } -func testAccGroupWithSuspendedProcessesConfig(name string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func testAccGroupConfig_placement(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "c3.large"), fmt.Sprintf(` +resource "aws_placement_group" "test" { + name = %[1]q + strategy = "cluster" +} + +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 1 + min_size = 1 + health_check_grace_period = 300 + health_check_type = "ELB" + desired_capacity = 1 + force_delete = true + termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] + placement_group = aws_placement_group.test.name + launch_configuration = aws_launch_configuration.test.name - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } +`, rName)) +} -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" +func testAccGroupConfig_enabledMetrics(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name + + enabled_metrics = [ + "GroupTotalInstances", + "GroupPendingInstances", + "GroupTerminatingInstances", + "GroupDesiredCapacity", + "GroupMaxSize" + ] +} +`, rName)) +} + +func testAccGroupConfig_allMetricsEnabled(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name + + enabled_metrics = [ + "GroupTotalInstances", + "GroupPendingInstances", + "GroupTerminatingInstances", + "GroupDesiredCapacity", + "GroupInServiceInstances", + "GroupMinSize", + "GroupMaxSize", + "GroupPendingCapacity", + "GroupInServiceCapacity", + "GroupStandbyCapacity", + "GroupTotalCapacity", + "GroupTerminatingCapacity", + "GroupStandbyInstances" + ] + metrics_granularity = "1Minute" } - -resource "aws_placement_group" "test" { - name = "asg_pg_%s" - strategy = "cluster" +`, rName)) } -resource "aws_autoscaling_group" "bar" { +func testAccGroupConfig_suspendedProcesses(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { availability_zones = [data.aws_availability_zones.available.names[0]] - name = "%s" + name = %[1]q max_size = 5 min_size = 2 health_check_type = "ELB" desired_capacity = 4 force_delete = true termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - - launch_configuration = aws_launch_configuration.foobar.name + launch_configuration = aws_launch_configuration.test.name suspended_processes = ["AlarmNotification", "ScheduledActions"] tag { - key = "Foo" - value = "foo-bar" + key = "Name" + value = %[1]q propagate_at_launch = true } } -`, name, name) -} - -func testAccGroupWithSuspendedProcessesUpdatedConfig(name string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} - -resource "aws_launch_configuration" "foobar" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} - -resource "aws_placement_group" "test" { - name = "asg_pg_%s" - strategy = "cluster" +`, rName)) } -resource "aws_autoscaling_group" "bar" { +func testAccGroupConfig_suspendedProcessesUpdated(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { availability_zones = [data.aws_availability_zones.available.names[0]] - name = "%s" + name = %[1]q max_size = 5 min_size = 2 health_check_type = "ELB" desired_capacity = 4 force_delete = true termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - - launch_configuration = aws_launch_configuration.foobar.name + launch_configuration = aws_launch_configuration.test.name suspended_processes = ["AZRebalance", "ScheduledActions"] tag { - key = "Foo" - value = "foo-bar" + key = "Name" + value = %[1]q propagate_at_launch = true } } -`, name, name) +`, rName)) +} + +func testAccGroupConfig_serviceLinkedRoleARN(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +data "aws_iam_role" "test" { + name = "AWSServiceRoleForAutoScaling" } -func testAccGroupConfig_classicVPCZoneIdentifier() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` resource "aws_autoscaling_group" "test" { - min_size = 0 - max_size = 0 + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name + + service_linked_role_arn = data.aws_iam_role.test.arn +} +`, rName)) +} +func testAccGroupConfig_maxInstanceLifetime(rName string, maxInstanceLifetime int) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q launch_configuration = aws_launch_configuration.test.name + + max_instance_lifetime = %[2]d +} +`, rName, maxInstanceLifetime)) } -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func testAccGroupConfig_initialLifecycleHook(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 5 + min_size = 2 + health_check_type = "ELB" + desired_capacity = 4 + force_delete = true + termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] + launch_configuration = aws_launch_configuration.test.name - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + initial_lifecycle_hook { + name = "launching" + default_result = "CONTINUE" + heartbeat_timeout = 30 # minimum value + lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING" } -} -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test_ami.id - instance_type = "t1.micro" + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } } -`) +`, rName)) } -func testAccGroupConfig_withLaunchTemplate() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func testAccGroupConfig_launchTemplate(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + launch_template { + id = aws_launch_template.test.id + version = aws_launch_template.test.default_version } } - -resource "aws_launch_template" "foobar" { - name_prefix = "foobar" - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" +`, rName)) } -resource "aws_autoscaling_group" "bar" { +func testAccGroupConfig_launchTemplateName(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 max_size = 0 min_size = 0 + name = %[1]q + launch_template { - id = aws_launch_template.foobar.id - version = aws_launch_template.foobar.default_version + name = aws_launch_template.test.name } } -`) +`, rName)) } -func testAccGroupConfig_withLaunchTemplate_toLaunchConfig() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func testAccGroupConfig_launchTemplateLatestVersion(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t2.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + name = %[1]q - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + launch_template { + id = aws_launch_template.test.id + version = "$Latest" } } - -resource "aws_launch_template" "foobar" { - name_prefix = "foobar" - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} - -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" +`, rName)) } -resource "aws_autoscaling_group" "bar" { +func testAccGroupConfig_largeDesiredCapacity(rName string, n int) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 + name = %[1]q + max_size = %[2]d + min_size = %[2]d + desired_capacity = %[2]d launch_configuration = aws_launch_configuration.test.name + + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } } -`) +`, rName, n)) } -func testAccGroupConfig_withLaunchTemplate_toLaunchTemplateName() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func testAccGroupConfig_instanceRefreshBasic(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.nano"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 2 + min_size = 1 + desired_capacity = 1 + launch_configuration = aws_launch_configuration.test.name - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + instance_refresh { + strategy = "Rolling" } -} -resource "aws_launch_template" "foobar" { - name_prefix = "foobar" - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } } - -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" +`, rName)) } -resource "aws_launch_template" "foobar2" { - name = "foobar2" - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} +func testAccGroupConfig_instanceRefreshMinHealthyPercentage(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.nano"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 2 + min_size = 1 + desired_capacity = 1 + launch_configuration = aws_launch_configuration.test.name -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_template { - name = "foobar2" + instance_refresh { + strategy = "Rolling" + + preferences { + min_healthy_percentage = 0 + } + } + + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } -`) +`, rName)) } -func testAccGroupConfig_withLaunchTemplate_toLaunchTemplateVersion() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - ` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] +func testAccGroupConfig_instanceRefreshSkipMatching(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.nano"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 2 + min_size = 1 + desired_capacity = 1 + launch_configuration = aws_launch_configuration.test.name + + instance_refresh { + strategy = "Rolling" - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + preferences { + min_healthy_percentage = 0 + skip_matching = true + } } -} -resource "aws_launch_template" "foobar" { - name_prefix = "foobar" - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } } - -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" +`, rName)) } -resource "aws_launch_template" "foobar2" { - name = "foobar2" - image_id = data.aws_ami.test_ami.id - instance_type = "t2.micro" -} +func testAccGroupConfig_instanceRefreshFull(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.nano"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 2 + min_size = 1 + desired_capacity = 1 + launch_configuration = aws_launch_configuration.test.name -resource "aws_autoscaling_group" "bar" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_template { - id = aws_launch_template.foobar.id - version = "$Latest" + instance_refresh { + strategy = "Rolling" + + preferences { + instance_warmup = 10 + min_healthy_percentage = 50 + checkpoint_delay = 25 + checkpoint_percentages = [1, 20, 25, 50, 100] + } + } + + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } -`) +`, rName)) } -func testAccGroupConfig_LaunchTemplate_IAMInstanceProfile(rName string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] +func testAccGroupConfig_instanceRefreshDisabled(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.nano"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 2 + min_size = 1 + desired_capacity = 1 + launch_configuration = aws_launch_configuration.test.name - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } - -resource "aws_iam_role" "test" { - assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}" - name = %q +`, rName)) } -resource "aws_iam_instance_profile" "test" { - name = %q - role = aws_iam_role.test.name -} +func testAccGroupConfig_instanceRefreshStart(rName, launchConfigurationNamePrefix string) string { + return acctest.ConfigCompose( + acctest.ConfigAvailableAZsNoOptInDefaultExclude(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 2 + min_size = 1 + desired_capacity = 1 + launch_configuration = aws_launch_configuration.test.name -resource "aws_launch_template" "test" { - image_id = data.aws_ami.test.id - instance_type = "t2.micro" - name = %q + instance_refresh { + strategy = "Rolling" + } - iam_instance_profile { - name = aws_iam_instance_profile.test.id + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q +resource "aws_launch_configuration" "test" { + name_prefix = %[2]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t3.nano" - launch_template { - id = aws_launch_template.test.id + lifecycle { + create_before_destroy = true } } -`, rName, rName, rName, rName) +`, rName, launchConfigurationNamePrefix)) } -func testAccGroupConfig_LoadBalancers(rName string, elbCount int) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] +func testAccGroupConfig_instanceRefreshTriggers(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.nano"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 2 + min_size = 1 + desired_capacity = 1 + launch_configuration = aws_launch_configuration.test.name - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + instance_refresh { + strategy = "Rolling" + triggers = ["tags"] } -} - -resource "aws_launch_template" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.micro" - name = %[1]q -} -resource "aws_vpc" "test" { - cidr_block = "10.0.0.0/16" + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } - tags = { - Name = %[1]q + tag { + key = "Key" + value = "Value" + propagate_at_launch = true } } +`, rName)) +} -resource "aws_subnet" "test" { - availability_zone = data.aws_availability_zones.available.names[0] - cidr_block = "10.0.0.0/24" - vpc_id = aws_vpc.test.id +func testAccGroupConfig_loadBalancers(rName string, elbCount int) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + acctest.ConfigVPCWithSubnets(rName, 1), + fmt.Sprintf(` +resource "aws_internet_gateway" "test" { + vpc_id = aws_vpc.test.id tags = { Name = %[1]q } } -resource "aws_internet_gateway" "test" { - vpc_id = aws_vpc.test.id +resource "aws_launch_template" "test" { + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t3.micro" + name = %[1]q } resource "aws_elb" "test" { - count = %[2]d - depends_on = [aws_internet_gateway.test] + count = %[2]d - subnets = [aws_subnet.test.id] + # "name" cannot be longer than 32 characters. + name = format("%%s-%%s", substr(%[1]q, 0, 28), count.index) + subnets = aws_subnet.test[*].id listener { instance_port = 80 @@ -4028,412 +4092,312 @@ resource "aws_elb" "test" { lb_port = 80 lb_protocol = "http" } + + depends_on = [aws_internet_gateway.test] } resource "aws_autoscaling_group" "test" { + name = %[1]q force_delete = true max_size = 0 min_size = 0 load_balancers = length(aws_elb.test) > 0 ? aws_elb.test[*].name : [] - vpc_zone_identifier = [aws_subnet.test.id] + vpc_zone_identifier = aws_subnet.test[*].id launch_template { id = aws_launch_template.test.id } } -`, rName, elbCount) +`, rName, elbCount)) } -func testAccGroupConfig_MixedInstancesPolicy_Base(rName string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + +func testAccGroupConfig_target(rName string, targetGroupCount int) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" -resource "aws_launch_template" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.micro" - name = %q -} -`, rName) + enable_monitoring = false } -func testAccGroupConfig_MixedInstancesPolicy_Arm_Base(rName string) string { - return fmt.Sprintf(` -data "aws_ami" "testarm" { - most_recent = true - owners = ["amazon"] +resource "aws_lb_target_group" "test" { + count = %[2]d - filter { - name = "name" - values = ["amzn2-ami-hvm-*-arm64-gp2"] - } + name = format("%%s-%%s", substr(%[1]q, 0, 28), count.index) + port = 80 + protocol = "HTTP" + vpc_id = aws_vpc.test.id } -resource "aws_launch_template" "testarm" { - image_id = data.aws_ami.testarm.id - instance_type = "t4g.micro" - name = %q +resource "aws_autoscaling_group" "test" { + vpc_zone_identifier = aws_subnet.test[*].id + max_size = 0 + min_size = 0 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name + + target_group_arns = length(aws_lb_target_group.test) > 0 ? aws_lb_target_group.test[*].arn : [] } -`, rName) +`, rName, targetGroupCount)) } -func testAccGroupConfig_MixedInstancesPolicy(rName string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + +func testAccGroupConfig_targetELBCapacity(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q - - mixed_instances_policy { - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } +resource "aws_internet_gateway" "test" { + vpc_id = aws_vpc.test.id - override { - instance_type = "t2.micro" - weighted_capacity = "1" - } - override { - instance_type = "t3.small" - weighted_capacity = "2" - } - } + tags = { + Name = %[1]q } } -`, rName) + +resource "aws_lb" "test" { + name = %[1]q + subnets = aws_subnet.test[*].id + + tags = { + Name = %[1]q + } } -func testAccGroupConfig_MixedInstancesPolicy_CapacityRebalance(rName string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - capacity_rebalance = true - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q +resource "aws_lb_listener" "test" { + load_balancer_arn = aws_lb.test.arn + port = "80" - mixed_instances_policy { - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } + default_action { + target_group_arn = aws_lb_target_group.test.arn + type = "forward" + } - override { - instance_type = "t2.micro" - weighted_capacity = "1" - } - override { - instance_type = "t3.small" - weighted_capacity = "2" - } - } + tags = { + Name = %[1]q } } -`, rName) -} -func testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandAllocationStrategy(rName, onDemandAllocationStrategy string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q +resource "aws_lb_target_group" "test" { + name = %[1]q + port = 80 + protocol = "HTTP" + vpc_id = aws_vpc.test.id - mixed_instances_policy { - instances_distribution { - on_demand_allocation_strategy = %q - } + health_check { + path = "/" + healthy_threshold = "2" + timeout = "2" + interval = "5" + matcher = "200" + } - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } + tags = { + Name = %[1]q + } +} - override { - instance_type = "t2.micro" - } - override { - instance_type = "t3.small" - } - } +resource "aws_route_table" "test" { + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q } } -`, rName, onDemandAllocationStrategy) + +resource "aws_route_table_association" "test" { + count = length(aws_subnet.test[*]) + + subnet_id = aws_subnet.test[count.index].id + route_table_id = aws_route_table.test.id } -func testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandBaseCapacity(rName string, onDemandBaseCapacity int) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 2 - min_size = 0 - name = %q +resource "aws_route" "test" { + route_table_id = aws_route_table.test.id + destination_cidr_block = "0.0.0.0/0" + gateway_id = aws_internet_gateway.test.id +} - mixed_instances_policy { - instances_distribution { - on_demand_base_capacity = %d - } +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } + associate_public_ip_address = "true" - override { - instance_type = "t2.micro" - } - override { - instance_type = "t3.small" - } - } - } -} -`, rName, onDemandBaseCapacity) + # Need the instance to listen on port 80 at boot + user_data = < /var/www/html/index.html +chkconfig httpd on +service httpd start +EOF } -func testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandPercentageAboveBaseCapacity(rName string, onDemandPercentageAboveBaseCapacity int) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q + vpc_zone_identifier = aws_subnet.test[*].id - mixed_instances_policy { - instances_distribution { - on_demand_percentage_above_base_capacity = %d - } + target_group_arns = [aws_lb_target_group.test.arn] - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } + name = %[1]q + max_size = 2 + min_size = 2 + health_check_grace_period = 300 + health_check_type = "ELB" + desired_capacity = 2 + wait_for_elb_capacity = 2 + force_delete = true + termination_policies = ["OldestInstance"] + launch_configuration = aws_launch_configuration.test.name - override { - instance_type = "t2.micro" - } - override { - instance_type = "t3.small" - } - } + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } -`, rName, onDemandPercentageAboveBaseCapacity) +`, rName)) } -func testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotAllocationStrategy(rName, spotAllocationStrategy string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` +func testAccGroupConfig_warmPoolEmpty(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.nano"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q - - mixed_instances_policy { - instances_distribution { - spot_allocation_strategy = %q - } + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 5 + min_size = 1 + desired_capacity = 1 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } + warm_pool {} - override { - instance_type = "t2.micro" - } - override { - instance_type = "t3.small" - } - } + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } -`, rName, spotAllocationStrategy) +`, rName)) } -func testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotInstancePools(rName string, spotInstancePools int) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` +func testAccGroupConfig_warmPoolFull(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.nano"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q - - mixed_instances_policy { - instances_distribution { - spot_instance_pools = %d - } - - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 5 + min_size = 1 + desired_capacity = 1 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name - override { - instance_type = "t2.micro" - } - override { - instance_type = "t3.small" - } + warm_pool { + pool_state = "Stopped" + min_size = 0 + max_group_prepared_capacity = 2 + instance_reuse_policy { + reuse_on_scale_in = true } } + + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } } -`, rName, spotInstancePools) +`, rName)) } -func testAccGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotMaxPrice(rName, spotMaxPrice string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` +func testAccGroupConfig_warmPoolNone(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.nano"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q - - mixed_instances_policy { - instances_distribution { - spot_max_price = %q - } - - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 5 + min_size = 1 + desired_capacity = 1 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name - override { - instance_type = "t2.micro" - } - override { - instance_type = "t3.small" - } - } + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } -`, rName, spotMaxPrice) +`, rName)) } -func testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_LaunchTemplateSpecification_LaunchTemplateName(rName string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + +func testAccGroupConfig_partition(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigAvailableAZsNoOptInDefaultExclude(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q - - mixed_instances_policy { - launch_template { - launch_template_specification { - launch_template_name = aws_launch_template.test.name - } +resource "aws_launch_template" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "m5.large" - override { - instance_type = "t2.micro" - } - override { - instance_type = "t3.small" - } - } + placement { + tenancy = "default" + group_name = aws_placement_group.test.id } } -`, rName) + +resource "aws_placement_group" "test" { + name = %[1]q + strategy = "cluster" } -func testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_LaunchTemplateSpecification_Version(rName, version string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` resource "aws_autoscaling_group" "test" { availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 max_size = 0 min_size = 0 - name = %q - - mixed_instances_policy { - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - version = %q - } + name = %[1]q - override { - instance_type = "t2.micro" - } - override { - instance_type = "t3.small" - } - } + launch_template { + id = aws_launch_template.test.id + version = "$Latest" } } -`, rName, version) +`, rName)) } -func testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_InstanceType(rName, instanceType string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` +func testAccGroupConfig_destroyWhenProtectedFromScaleInBeforeDestroy(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchConfigurationBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name = %q - - mixed_instances_policy { - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } + availability_zones = [data.aws_availability_zones.available.names[0]] + name = %[1]q + max_size = 2 + min_size = 2 + desired_capacity = 2 + protect_from_scale_in = true + launch_configuration = aws_launch_configuration.test.name - override { - instance_type = "t2.micro" - } - override { - instance_type = %q - } - } + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true } } -`, rName, instanceType) +`, rName)) } -func testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_InstanceType_With_LaunchTemplateSpecification(rName, rName2 string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - testAccGroupConfig_MixedInstancesPolicy_Arm_Base(rName2) + - fmt.Sprintf(` +func testAccGroupConfig_destroyWhenProtectedFromScaleInAfterDestroy(rName string) string { + return testAccGroupLaunchConfigurationBaseConfig(rName, "t3.micro") +} +func testAccGroupConfig_mixedInstancesPolicy(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 - name = %q + name = %[1]q mixed_instances_policy { launch_template { @@ -4442,29 +4406,29 @@ resource "aws_autoscaling_group" "test" { } override { - instance_type = "t2.micro" + instance_type = "t2.micro" + weighted_capacity = "1" } + override { - instance_type = "t4g.micro" - launch_template_specification { - launch_template_id = aws_launch_template.testarm.id - } + instance_type = "t3.small" + weighted_capacity = "2" } } } } -`, rName) +`, rName)) } -func testAccGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_WeightedCapacity(rName string) string { - return testAccGroupConfig_MixedInstancesPolicy_Base(rName) + - fmt.Sprintf(` +func testAccGroupConfig_mixedInstancesPolicyCapacityRebalance(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { availability_zones = [data.aws_availability_zones.available.names[0]] - desired_capacity = 4 - max_size = 6 - min_size = 2 - name = %q + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q + capacity_rebalance = true mixed_instances_policy { launch_template { @@ -4474,130 +4438,9 @@ resource "aws_autoscaling_group" "test" { override { instance_type = "t2.micro" - weighted_capacity = "2" - } - override { - instance_type = "t3.small" - weighted_capacity = "4" + weighted_capacity = "1" } - } - } -} -`, rName) -} - -func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_WeightedCapacity_WithELB(rName string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -resource "aws_vpc" "foo" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = %[1]q - } -} - -resource "aws_internet_gateway" "gw" { - vpc_id = aws_vpc.foo.id - - tags = { - Name = %[1]q - } -} -resource "aws_subnet" "foo" { - availability_zone = data.aws_availability_zones.available.names[0] - cidr_block = "10.1.1.0/24" - vpc_id = aws_vpc.foo.id - - tags = { - Name = %[1]q - } -} - -resource "aws_security_group" "foo" { - vpc_id = aws_vpc.foo.id - - ingress { - protocol = "-1" - from_port = 0 - to_port = 0 - cidr_blocks = ["0.0.0.0/0"] - } - egress { - protocol = "-1" - from_port = 0 - to_port = 0 - cidr_blocks = ["0.0.0.0/0"] - } -} - -resource "aws_lb_target_group" "foo" { - port = 80 - protocol = "HTTP" - vpc_id = aws_vpc.foo.id -} - -resource "aws_elb" "bar" { - subnets = [aws_subnet.foo.id] - security_groups = [aws_security_group.foo.id] - listener { - instance_port = 80 - instance_protocol = "http" - lb_port = 80 - lb_protocol = "http" - } - health_check { - healthy_threshold = 2 - unhealthy_threshold = 2 - target = "HTTP:80/" - interval = 5 - timeout = 2 - } - depends_on = [aws_internet_gateway.gw] -} - -locals { - user_data = < index.html - nohup python -m SimpleHTTPServer 80 & - EOF -} - -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} -resource "aws_launch_template" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.micro" - name = %[1]q - user_data = base64encode(local.user_data) - vpc_security_group_ids = [aws_security_group.foo.id] -} - -resource "aws_autoscaling_group" "test" { - desired_capacity = 2 - wait_for_elb_capacity = 2 - max_size = 2 - min_size = 2 - name = %[1]q - load_balancers = [aws_elb.bar.name] - vpc_zone_identifier = aws_subnet.foo[*].id - mixed_instances_policy { - launch_template { - launch_template_specification { - launch_template_id = aws_launch_template.test.id - } - override { - instance_type = "t3.micro" - weighted_capacity = "2" - } override { instance_type = "t3.small" weighted_capacity = "2" @@ -4605,951 +4448,444 @@ resource "aws_autoscaling_group" "test" { } } } -`, rName) -} - -func testAccGroupPartitionConfig(rName string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } +`, rName)) } -resource "aws_launch_template" "this" { - name = %[1]q - image_id = data.aws_ami.test_ami.id - instance_type = "m5.large" +func testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandAllocationStrategy(rName, onDemandAllocationStrategy string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q - placement { - tenancy = "default" - group_name = aws_placement_group.test.id - } -} + mixed_instances_policy { + instances_distribution { + on_demand_allocation_strategy = %[2]q + } -resource "aws_placement_group" "test" { - name = %[1]q - strategy = "cluster" -} + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } -resource "aws_autoscaling_group" "test" { - name_prefix = "test" - availability_zones = [data.aws_availability_zones.available.names[0]] - min_size = 0 - max_size = 0 + override { + instance_type = "t2.micro" + } - launch_template { - id = aws_launch_template.this.id - version = "$Latest" + override { + instance_type = "t3.small" + } + } } } -`, rName) +`, rName, onDemandAllocationStrategy)) } -func testAccGroupConfig_InstanceRefresh_Basic() string { - return ` +func testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandBaseCapacity(rName string, onDemandBaseCapacity int) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 2 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name - - instance_refresh { - strategy = "Rolling" - } -} + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 2 + min_size = 0 + name = %[1]q -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] + mixed_instances_policy { + instances_distribution { + on_demand_base_capacity = %[2]d + } - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } -data "aws_availability_zones" "current" { - state = "available" + override { + instance_type = "t2.micro" + } - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] + override { + instance_type = "t3.small" + } + } } } - -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.nano" -} -` +`, rName, onDemandBaseCapacity)) } -func testAccGroupConfig_InstanceRefresh_MinHealthyPercentage() string { - return ` +func testAccGroupConfig_mixedInstancesPolicyInstancesDistributionOnDemandPercentageAboveBaseCapacity(rName string, onDemandPercentageAboveBaseCapacity int) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 2 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q - instance_refresh { - strategy = "Rolling" - preferences { - min_healthy_percentage = 0 + mixed_instances_policy { + instances_distribution { + on_demand_percentage_above_base_capacity = %[2]d } - } -} -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } -data "aws_availability_zones" "current" { - state = "available" + override { + instance_type = "t2.micro" + } - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] + override { + instance_type = "t3.small" + } + } } } - -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.nano" -} -` +`, rName, onDemandPercentageAboveBaseCapacity)) } -func testAccGroupConfig_InstanceRefresh_SkipMatching() string { - return ` +func testAccGroupConfig_mixedInstancesPolicyInstancesDistributionSpotAllocationStrategy(rName, spotAllocationStrategy string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 2 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q - instance_refresh { - strategy = "Rolling" - preferences { - min_healthy_percentage = 0 - skip_matching = true + mixed_instances_policy { + instances_distribution { + spot_allocation_strategy = %[2]q } - } -} - -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } -data "aws_availability_zones" "current" { - state = "available" + override { + instance_type = "t2.micro" + } - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] + override { + instance_type = "t3.small" + } + } } } - -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.nano" -} -` +`, rName, spotAllocationStrategy)) } -func testAccGroupConfig_InstanceRefresh_Full() string { - return ` +func testAccGroupConfig_mixedInstancesPolicyInstancesDistributionSpotInstancePools(rName string, spotInstancePools int) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 2 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q - instance_refresh { - strategy = "Rolling" - preferences { - instance_warmup = 10 - min_healthy_percentage = 50 - checkpoint_delay = 25 - checkpoint_percentages = [1, 20, 25, 50, 100] + mixed_instances_policy { + instances_distribution { + spot_instance_pools = %[2]d } - } -} -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } -data "aws_availability_zones" "current" { - state = "available" + override { + instance_type = "t2.micro" + } - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] + override { + instance_type = "t3.small" + } + } } } - -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.nano" -} -` +`, rName, spotInstancePools)) } -func testAccGroupConfig_InstanceRefresh_Disabled() string { - return ` +func testAccGroupConfig_mixedInstancesPolicyInstancesDistributionSpotMaxPrice(rName, spotMaxPrice string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 2 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name -} + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] + mixed_instances_policy { + instances_distribution { + spot_max_price = %[2]q + } - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } -data "aws_availability_zones" "current" { - state = "available" + override { + instance_type = "t2.micro" + } - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] + override { + instance_type = "t3.small" + } + } } } - -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.nano" -} -` +`, rName, spotMaxPrice)) } -func testAccGroupConfig_InstanceRefresh_Start(launchConfigurationName string) string { - return fmt.Sprintf(` +func testAccGroupConfig_mixedInstancesPolicyLaunchTemplateLaunchTemplateSpecificationLaunchTemplateName(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 2 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q - instance_refresh { - strategy = "Rolling" - } -} + mixed_instances_policy { + launch_template { + launch_template_specification { + launch_template_name = aws_launch_template.test.name + } -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] + override { + instance_type = "t2.micro" + } - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + override { + instance_type = "t3.small" + } + } } } +`, rName)) +} -data "aws_availability_zones" "current" { - state = "available" +func testAccGroupConfig_mixedInstancesPolicyLaunchTemplateLaunchTemplateSpecificationVersion(rName, version string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} + mixed_instances_policy { + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + version = %[2]q + } -resource "aws_launch_configuration" "test" { - name_prefix = %[1]q - image_id = data.aws_ami.test.id - instance_type = "t3.nano" + override { + instance_type = "t2.micro" + } - lifecycle { - create_before_destroy = true + override { + instance_type = "t3.small" + } + } } } -`, launchConfigurationName) +`, rName, version)) } -func testAccGroupConfig_InstanceRefresh_Triggers() string { - return ` +func testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceType(rName, instanceType string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 2 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name - - instance_refresh { - strategy = "Rolling" - triggers = ["tags"] - } + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q - tag { - key = "Key" - value = "Value" - propagate_at_launch = true - } -} + mixed_instances_policy { + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] + override { + instance_type = "t2.micro" + } - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + override { + instance_type = %[2]q + } + } } } - -data "aws_availability_zones" "current" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } +`, rName, instanceType)) } -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.nano" -} -` +func testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceTypeLaunchTemplateSpecification(rName string) string { + return acctest.ConfigCompose( + testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), + acctest.ConfigLatestAmazonLinux2HVMEBSARM64AMI(), + fmt.Sprintf(` +resource "aws_launch_template" "test-arm" { + image_id = data.aws_ami.amzn2-ami-minimal-hvm-ebs-arm64.id + instance_type = "t4g.micro" + name = "%[1]s-arm" } -func testAccGroupConfig_WarmPool_Base() string { - return ` -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} + mixed_instances_policy { + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } -data "aws_availability_zones" "current" { - state = "available" + override { + instance_type = "t2.micro" + } - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} + override { + instance_type = "t4g.small" -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.nano" + launch_template_specification { + launch_template_id = aws_launch_template.test-arm.id + } + } + } + } } -` +`, rName)) } -func testAccGroupConfig_WarmPool_Empty() string { - return testAccGroupConfig_WarmPool_Base() + ` +func testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideWeightedCapacity(rName string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 5 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 4 + max_size = 6 + min_size = 2 + name = %[1]q - warm_pool {} -} -` -} + mixed_instances_policy { + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } -func testAccGroupConfig_WarmPool_Full() string { - return testAccGroupConfig_WarmPool_Base() + ` -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 5 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name + override { + instance_type = "t2.micro" + weighted_capacity = "2" + } - warm_pool { - pool_state = "Stopped" - min_size = 0 - max_group_prepared_capacity = 2 - instance_reuse_policy { - reuse_on_scale_in = true + override { + instance_type = "t3.small" + weighted_capacity = "4" + } } } -} -` -} -func testAccGroupConfig_WarmPool_Remove() string { - return testAccGroupConfig_WarmPool_Base() + ` -resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.current.names[0]] - max_size = 5 - min_size = 1 - desired_capacity = 1 - launch_configuration = aws_launch_configuration.test.name + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } } -` +`, rName)) } -func testAccGroupConfig_DestroyWhenProtectedFromScaleIn_beforeDestroy(name string) string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - fmt.Sprintf(` -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } +func testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideWeightedCapacityELB(rName string) string { + return acctest.ConfigCompose(testAccGroupELBBaseConfig(rName), fmt.Sprintf(` +locals { + user_data = < index.html +nohup python -m SimpleHTTPServer 80 & +EOF } -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.micro" +resource "aws_launch_template" "test" { + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t3.micro" + name = %[1]q + user_data = base64encode(local.user_data) + vpc_security_group_ids = [aws_security_group.test.id] } resource "aws_autoscaling_group" "test" { - availability_zones = [data.aws_availability_zones.available.names[0]] - name = %[1]q + desired_capacity = 2 + wait_for_elb_capacity = 2 max_size = 2 min_size = 2 - desired_capacity = 2 - protect_from_scale_in = true - launch_configuration = aws_launch_configuration.test.name -} -`, name) -} - -func testAccGroupConfig_DestroyWhenProtectedFromScaleIn_afterDestroy() string { - return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + - ` -data "aws_ami" "test" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} - -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.test.id - instance_type = "t3.micro" -} -` -} - -func testAccCheckInstanceRefreshCount(group *autoscaling.Group, expected int) resource.TestCheckFunc { - return func(state *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).AutoScalingConn - - input := autoscaling.DescribeInstanceRefreshesInput{ - AutoScalingGroupName: group.AutoScalingGroupName, - } - resp, err := conn.DescribeInstanceRefreshes(&input) - if err != nil { - return fmt.Errorf("error describing Auto Scaling Group (%s) Instance Refreshes: %w", aws.StringValue(group.AutoScalingGroupName), err) - } - - if len(resp.InstanceRefreshes) != expected { - return fmt.Errorf("expected %d Instance Refreshes, got %d", expected, len(resp.InstanceRefreshes)) - } - return nil - } -} + name = %[1]q + load_balancers = [aws_elb.test.name] + vpc_zone_identifier = aws_subnet.test[*].id -func testAccCheckInstanceRefreshStatus(group *autoscaling.Group, offset int, expected ...string) resource.TestCheckFunc { - return func(state *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).AutoScalingConn + mixed_instances_policy { + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } - input := autoscaling.DescribeInstanceRefreshesInput{ - AutoScalingGroupName: group.AutoScalingGroupName, - } - resp, err := conn.DescribeInstanceRefreshes(&input) - if err != nil { - return fmt.Errorf("error describing Auto Scaling Group (%s) Instance Refreshes: %w", aws.StringValue(group.AutoScalingGroupName), err) - } + override { + instance_type = "t3.micro" + weighted_capacity = "2" + } - if len(resp.InstanceRefreshes) < offset { - return fmt.Errorf("expected at least %d Instance Refreshes, got %d", offset+1, len(resp.InstanceRefreshes)) - } + override { + instance_type = "t3.small" + weighted_capacity = "2" + } + } + } - actual := aws.StringValue(resp.InstanceRefreshes[offset].Status) - for _, s := range expected { - if actual == s { - return nil - } - } - return fmt.Errorf("expected Instance Refresh at index %d to be in %q, got %q", offset, expected, actual) - } + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } } - -func TestCreateAutoScalingGroupInstanceRefreshInput(t *testing.T) { - const asgName = "test-asg" - testCases := []struct { - name string - input []interface{} - expected *autoscaling.StartInstanceRefreshInput - }{ - { - name: "empty list", - input: []interface{}{}, - expected: nil, - }, - { - name: "nil", - input: []interface{}{nil}, - expected: nil, - }, - { - name: "defaults", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{}, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: nil, - }, - }, - { - name: "instance_warmup only", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "instance_warmup": "60", - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: nil, - CheckpointPercentages: nil, - InstanceWarmup: aws.Int64(60), - MinHealthyPercentage: nil, - }, - }, - }, - { - name: "instance_warmup zero", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "instance_warmup": "0", - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: nil, - CheckpointPercentages: nil, - InstanceWarmup: aws.Int64(0), - MinHealthyPercentage: nil, - }, - }, - }, - { - name: "instance_warmup empty string", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "instance_warmup": "", - "min_healthy_percentage": 80, - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: nil, - CheckpointPercentages: nil, - InstanceWarmup: nil, - MinHealthyPercentage: aws.Int64(80), - }, - }, - }, - { - name: "min_healthy_percentage only", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "min_healthy_percentage": 80, - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: nil, - CheckpointPercentages: nil, - InstanceWarmup: nil, - MinHealthyPercentage: aws.Int64(80), - }, - }, - }, - { - name: "preferences", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "instance_warmup": "60", - "min_healthy_percentage": 80, - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: nil, - CheckpointPercentages: nil, - InstanceWarmup: aws.Int64(60), - MinHealthyPercentage: aws.Int64(80), - }, - }, - }, - { - name: "checkpoint_delay", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "checkpoint_delay": "25", - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: aws.Int64(25), - CheckpointPercentages: nil, - InstanceWarmup: nil, - MinHealthyPercentage: nil, - }, - }, - }, - { - name: "checkpoint_delay zero", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "checkpoint_delay": "0", - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: aws.Int64(0), - CheckpointPercentages: nil, - InstanceWarmup: nil, - MinHealthyPercentage: nil, - }, - }, - }, - { - name: "checkpoint_delay empty string", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "checkpoint_delay": "", - "checkpoint_percentages": []interface{}{20, 100}, - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: nil, - CheckpointPercentages: []*int64{ - aws.Int64(20), - aws.Int64(100), - }, - InstanceWarmup: nil, - MinHealthyPercentage: nil, - }, - }, - }, - { - name: "checkpoint_percentages empty", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "checkpoint_percentages": []interface{}{}, - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: nil, - CheckpointPercentages: nil, - InstanceWarmup: nil, - MinHealthyPercentage: nil, - }, - }, - }, - { - name: "checkpoint_percentages", - input: []interface{}{map[string]interface{}{ - "strategy": "Rolling", - "preferences": []interface{}{ - map[string]interface{}{ - "checkpoint_percentages": []interface{}{1, 20, 25, 50, 100}, - }, - }, - }}, - expected: &autoscaling.StartInstanceRefreshInput{ - AutoScalingGroupName: aws.String(asgName), - Strategy: aws.String("Rolling"), - Preferences: &autoscaling.RefreshPreferences{ - CheckpointDelay: nil, - CheckpointPercentages: []*int64{ - aws.Int64(1), - aws.Int64(20), - aws.Int64(25), - aws.Int64(50), - aws.Int64(100), - }, - InstanceWarmup: nil, - MinHealthyPercentage: nil, - }, - }, - }, - } - - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - got := tfautoscaling.CreateGroupInstanceRefreshInput(asgName, testCase.input) - - if !reflect.DeepEqual(got, testCase.expected) { - t.Errorf("got %s, expected %s", got, testCase.expected) - } - }) - } +`, rName)) } -func TestPutWarmPoolInput(t *testing.T) { - const asgName = "test-asg" - testCases := []struct { - name string - input []interface{} - expected *autoscaling.PutWarmPoolInput - }{ - { - name: "empty interface", - input: []interface{}{}, - expected: nil, - }, - { - name: "nil", - input: nil, - expected: nil, - }, - { - name: "only pool state", - input: []interface{}{map[string]interface{}{ - "pool_state": "Stopped", - }}, - expected: &autoscaling.PutWarmPoolInput{ - AutoScalingGroupName: aws.String(asgName), - PoolState: aws.String("Stopped"), - }, - }, - { - name: "0 min size", - input: []interface{}{map[string]interface{}{ - "pool_state": "Stopped", - "min_size": 0, - "max_group_prepared_capacity": 5, - }}, - expected: &autoscaling.PutWarmPoolInput{ - AutoScalingGroupName: aws.String(asgName), - PoolState: aws.String("Stopped"), - MinSize: aws.Int64(0), - MaxGroupPreparedCapacity: aws.Int64(5), - }, - }, - { - name: "-1 max prepared size", - input: []interface{}{map[string]interface{}{ - "pool_state": "Stopped", - "max_group_prepared_capacity": -1, - }}, - expected: &autoscaling.PutWarmPoolInput{ - AutoScalingGroupName: aws.String(asgName), - PoolState: aws.String("Stopped"), - MaxGroupPreparedCapacity: aws.Int64(-1), - }, - }, - { - name: "all values", - input: []interface{}{map[string]interface{}{ - "pool_state": "Stopped", - "min_size": 3, - "max_group_prepared_capacity": 2, - }}, - expected: &autoscaling.PutWarmPoolInput{ - AutoScalingGroupName: aws.String(asgName), - PoolState: aws.String("Stopped"), - MinSize: aws.Int64(3), - MaxGroupPreparedCapacity: aws.Int64(2), - }, - }, - } - - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - got := tfautoscaling.CreatePutWarmPoolInput(asgName, testCase.input) - - if !reflect.DeepEqual(got, testCase.expected) { - t.Errorf("got %s, expected %s", got, testCase.expected) - } - }) - } -} +func testAccGroupConfig_mixedInstancesPolicyLaunchTemplateOverrideInstanceRequirements(rName string, instanceRequirements string) string { + return acctest.ConfigCompose(testAccGroupLaunchTemplateBaseConfig(rName, "t3.micro"), fmt.Sprintf(` +resource "aws_autoscaling_group" "test" { + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name = %[1]q -func TestFlattenWarmPoolConfiguration(t *testing.T) { - testCases := []struct { - name string - input *autoscaling.WarmPoolConfiguration - expected []interface{} - }{ - { - name: "empty interface", - input: nil, - expected: []interface{}{}, - }, - { - name: "only pool state", - input: &autoscaling.WarmPoolConfiguration{ - PoolState: aws.String("Stopped"), - }, - expected: []interface{}{map[string]interface{}{ - "pool_state": "Stopped", - "min_size": int64(0), - "max_group_prepared_capacity": int64(-1), - }}, - }, - { - name: "only max group prepared capacity", - input: &autoscaling.WarmPoolConfiguration{ - PoolState: aws.String("Stopped"), - MaxGroupPreparedCapacity: aws.Int64(2), - }, - expected: []interface{}{map[string]interface{}{ - "pool_state": "Stopped", - "min_size": int64(0), - "max_group_prepared_capacity": int64(2), - }}, - }, - { - name: "all values", - input: &autoscaling.WarmPoolConfiguration{ - PoolState: aws.String("Stopped"), - MinSize: aws.Int64(3), - MaxGroupPreparedCapacity: aws.Int64(5), - }, - expected: []interface{}{map[string]interface{}{ - "pool_state": "Stopped", - "min_size": int64(3), - "max_group_prepared_capacity": int64(5), - }}, - }, - } + mixed_instances_policy { + launch_template { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + } - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - got := tfautoscaling.FlattenWarmPoolConfiguration(testCase.input) + override { + instance_requirements { + %[2]s + } + } + } - if !reflect.DeepEqual(got, testCase.expected) { - t.Errorf("got %s, expected %s", got, testCase.expected) - } - }) - } + instances_distribution { + on_demand_percentage_above_base_capacity = 50 + spot_allocation_strategy = "capacity-optimized" + } + } } - -func testAccCheckLBTargetGroupExists(n string, res *elbv2.TargetGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - if rs.Primary.ID == "" { - return errors.New("No Target Group ID is set") - } - - conn := acctest.Provider.Meta().(*conns.AWSClient).ELBV2Conn - - targetGroup, err := tfelbv2.FindTargetGroupByARN(conn, rs.Primary.ID) - - if err != nil { - return fmt.Errorf("error reading ELBv2 Target Group (%s): %w", rs.Primary.ID, err) - } - - if targetGroup == nil { - return fmt.Errorf("Target Group (%s) not found", rs.Primary.ID) - } - - *res = *targetGroup - return nil - } +`, rName, instanceRequirements)) } diff --git a/internal/service/autoscaling/group_waiting.go b/internal/service/autoscaling/group_waiting.go index 75cece25059..510cc6c0ac2 100644 --- a/internal/service/autoscaling/group_waiting.go +++ b/internal/service/autoscaling/group_waiting.go @@ -1,6 +1,6 @@ package autoscaling -import ( +import ( // nosemgrep: aws-sdk-go-multiple-service-imports "fmt" "log" "strconv" @@ -9,6 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" + "github.com/aws/aws-sdk-go/service/elb" + "github.com/aws/aws-sdk-go/service/elbv2" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -201,3 +204,91 @@ func CapacitySatisfiedUpdate(d *schema.ResourceData, haveASG, haveELB int) (bool } return true, "" } + +// TODO: make this a finder +// TODO: this should return a NotFoundError if not found +func getGroup(asgName string, conn *autoscaling.AutoScaling) (*autoscaling.Group, error) { + describeOpts := autoscaling.DescribeAutoScalingGroupsInput{ + AutoScalingGroupNames: []*string{aws.String(asgName)}, + } + + log.Printf("[DEBUG] Auto Scaling Group describe configuration: %#v", describeOpts) + describeGroups, err := conn.DescribeAutoScalingGroups(&describeOpts) + if err != nil { + if tfawserr.ErrCodeEquals(err, "InvalidGroup.NotFound") { + return nil, nil + } + + return nil, fmt.Errorf("Error retrieving Auto Scaling Groups: %s", err) + } + + // Search for the Auto Scaling Group + for idx, asc := range describeGroups.AutoScalingGroups { + if asc == nil { + continue + } + + if aws.StringValue(asc.AutoScalingGroupName) == asgName { + return describeGroups.AutoScalingGroups[idx], nil + } + } + + return nil, nil +} + +// getELBInstanceStates returns a mapping of the instance states of all the ELBs attached to the +// provided ASG. +// +// Note that this is the instance state function for ELB Classic. +// +// Nested like: lbName -> instanceId -> instanceState +func getELBInstanceStates(g *autoscaling.Group, meta interface{}) (map[string]map[string]string, error) { + lbInstanceStates := make(map[string]map[string]string) + conn := meta.(*conns.AWSClient).ELBConn + + for _, lbName := range g.LoadBalancerNames { + lbInstanceStates[aws.StringValue(lbName)] = make(map[string]string) + opts := &elb.DescribeInstanceHealthInput{LoadBalancerName: lbName} + r, err := conn.DescribeInstanceHealth(opts) + if err != nil { + return nil, err + } + for _, is := range r.InstanceStates { + if is == nil || is.InstanceId == nil || is.State == nil { + continue + } + lbInstanceStates[aws.StringValue(lbName)][aws.StringValue(is.InstanceId)] = aws.StringValue(is.State) + } + } + + return lbInstanceStates, nil +} + +// getTargetGroupInstanceStates returns a mapping of the instance states of +// all the ALB target groups attached to the provided ASG. +// +// Note that this is the instance state function for Application Load +// Balancing (aka ELBv2). +// +// Nested like: targetGroupARN -> instanceId -> instanceState +func getTargetGroupInstanceStates(g *autoscaling.Group, meta interface{}) (map[string]map[string]string, error) { + targetInstanceStates := make(map[string]map[string]string) + conn := meta.(*conns.AWSClient).ELBV2Conn + + for _, targetGroupARN := range g.TargetGroupARNs { + targetInstanceStates[aws.StringValue(targetGroupARN)] = make(map[string]string) + opts := &elbv2.DescribeTargetHealthInput{TargetGroupArn: targetGroupARN} + r, err := conn.DescribeTargetHealth(opts) + if err != nil { + return nil, err + } + for _, desc := range r.TargetHealthDescriptions { + if desc == nil || desc.Target == nil || desc.Target.Id == nil || desc.TargetHealth == nil || desc.TargetHealth.State == nil { + continue + } + targetInstanceStates[aws.StringValue(targetGroupARN)][aws.StringValue(desc.Target.Id)] = aws.StringValue(desc.TargetHealth.State) + } + } + + return targetInstanceStates, nil +} diff --git a/internal/service/autoscaling/groups_data_source.go b/internal/service/autoscaling/groups_data_source.go index 9d62c0b1e68..91abe1f54fd 100644 --- a/internal/service/autoscaling/groups_data_source.go +++ b/internal/service/autoscaling/groups_data_source.go @@ -2,7 +2,6 @@ package autoscaling import ( "fmt" - "log" "sort" "github.com/aws/aws-sdk-go/aws" @@ -17,11 +16,6 @@ func DataSourceGroups() *schema.Resource { Read: dataSourceGroupsRead, Schema: map[string]*schema.Schema{ - "names": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, "arns": { Type: schema.TypeList, Computed: true, @@ -44,6 +38,12 @@ func DataSourceGroups() *schema.Resource { }, }, }, + "names": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, }, } } @@ -78,46 +78,35 @@ func buildFiltersDataSource(set *schema.Set) []*autoscaling.Filter { func dataSourceGroupsRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).AutoScalingConn - log.Printf("[DEBUG] Reading Autoscaling Groups.") + input := &autoscaling.DescribeAutoScalingGroupsInput{} - var rawName []string - var rawArn []string - var err error - - params := autoscaling.DescribeAutoScalingGroupsInput{} - - if v, ok := d.GetOk("filter"); ok { - params.Filters = buildFiltersDataSource(v.(*schema.Set)) + if v, ok := d.GetOk("names"); ok && len(v.([]interface{})) > 0 { + input.AutoScalingGroupNames = flex.ExpandStringList(v.([]interface{})) } - if v, ok := d.GetOk("names"); ok { - params.AutoScalingGroupNames = flex.ExpandStringList(v.([]interface{})) + if v, ok := d.GetOk("filter"); ok { + input.Filters = buildFiltersDataSource(v.(*schema.Set)) } - err = conn.DescribeAutoScalingGroupsPages(¶ms, func(resp *autoscaling.DescribeAutoScalingGroupsOutput, lastPage bool) bool { - for _, group := range resp.AutoScalingGroups { - rawName = append(rawName, aws.StringValue(group.AutoScalingGroupName)) - rawArn = append(rawArn, aws.StringValue(group.AutoScalingGroupARN)) - } - return !lastPage - }) + groups, err := findGroups(conn, input) if err != nil { - return fmt.Errorf("Error fetching Autoscaling Groups: %w", err) + return fmt.Errorf("reading Auto Scaling Groups: %w", err) } - d.SetId(meta.(*conns.AWSClient).Region) - - sort.Strings(rawName) - sort.Strings(rawArn) + var arns, names []string - if err := d.Set("names", rawName); err != nil { - return fmt.Errorf("[WARN] Error setting Autoscaling Group Names: %w", err) + for _, group := range groups { + arns = append(arns, aws.StringValue(group.AutoScalingGroupARN)) + names = append(names, aws.StringValue(group.AutoScalingGroupName)) } - if err := d.Set("arns", rawArn); err != nil { - return fmt.Errorf("[WARN] Error setting Autoscaling Group ARNs: %w", err) - } + sort.Strings(arns) + sort.Strings(names) + + d.SetId(meta.(*conns.AWSClient).Region) + d.Set("arns", arns) + d.Set("names", names) return nil } diff --git a/internal/service/autoscaling/groups_data_source_test.go b/internal/service/autoscaling/groups_data_source_test.go index c248d1872b8..774c1e6b339 100644 --- a/internal/service/autoscaling/groups_data_source_test.go +++ b/internal/service/autoscaling/groups_data_source_test.go @@ -13,7 +13,7 @@ import ( func TestAccAutoScalingGroupsDataSource_basic(t *testing.T) { datasource1Name := "data.aws_autoscaling_groups.group_list" datasource2Name := "data.aws_autoscaling_groups.group_list_tag_lookup" - datasource3Name := "data.aws_autoscaling_groups.group_list_multiple_filters" + datasource3Name := "data.aws_autoscaling_groups.group_list_by_name" datasource4Name := "data.aws_autoscaling_groups.group_list_multiple_values" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -24,7 +24,7 @@ func TestAccAutoScalingGroupsDataSource_basic(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccGroupsDataSourceConfig_basic(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(datasource1Name, "names.#", "3"), resource.TestCheckResourceAttr(datasource1Name, "arns.#", "3"), resource.TestCheckResourceAttr(datasource2Name, "names.#", "3"), @@ -41,7 +41,7 @@ func TestAccAutoScalingGroupsDataSource_basic(t *testing.T) { func testAccGroupsDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), fmt.Sprintf(` @@ -63,13 +63,14 @@ resource "aws_autoscaling_group" "test1" { launch_configuration = aws_launch_configuration.test.name tag { - key = "Foo" - value = "foo-bar" + key = "MetaGroup" + value = %[1]q propagate_at_launch = true } + tag { - key = "some-arbitrary-tag" - value = "some-arbitrary-value" + key = "Name" + value = "%[1]s-1" propagate_at_launch = true } } @@ -86,13 +87,14 @@ resource "aws_autoscaling_group" "test2" { launch_configuration = aws_launch_configuration.test.name tag { - key = "Foo" - value = "foo-bar" + key = "MetaGroup" + value = %[1]q propagate_at_launch = true } + tag { - key = "some-arbitrary-tag" - value = "some-other-arbitrary-value" + key = "Name" + value = "%[1]s-2" propagate_at_launch = true } } @@ -109,13 +111,14 @@ resource "aws_autoscaling_group" "test3" { launch_configuration = aws_launch_configuration.test.name tag { - key = "Foo" - value = "foo-bar" + key = "MetaGroup" + value = %[1]q propagate_at_launch = true } + tag { - key = "lorem" - value = "ipsum" + key = "Name" + value = "%[1]s-3" propagate_at_launch = true } } @@ -123,11 +126,12 @@ resource "aws_autoscaling_group" "test3" { data "aws_autoscaling_groups" "group_list" { filter { name = "key" - values = ["Foo"] + values = ["MetaGroup"] } + filter { name = "value" - values = ["foo-bar"] + values = [%[1]q] } depends_on = [aws_autoscaling_group.test1, aws_autoscaling_group.test2, aws_autoscaling_group.test3] @@ -135,30 +139,23 @@ data "aws_autoscaling_groups" "group_list" { data "aws_autoscaling_groups" "group_list_tag_lookup" { filter { - name = "tag:Foo" - values = ["foo-bar"] + name = "tag:MetaGroup" + values = [%[1]q] } depends_on = [aws_autoscaling_group.test1, aws_autoscaling_group.test2, aws_autoscaling_group.test3] } -data "aws_autoscaling_groups" "group_list_multiple_filters" { - filter { - name = "tag:Foo" - values = ["foo-bar"] - } - filter { - name = "key" - values = ["lorem"] - } +data "aws_autoscaling_groups" "group_list_by_name" { + names = [aws_autoscaling_group.test1.name] depends_on = [aws_autoscaling_group.test1, aws_autoscaling_group.test2, aws_autoscaling_group.test3] } data "aws_autoscaling_groups" "group_list_multiple_values" { filter { - name = "tag:some-arbitrary-tag" - values = ["some-arbitrary-value", "some-other-arbitrary-value"] + name = "tag:Name" + values = [aws_autoscaling_group.test2.name, aws_autoscaling_group.test3.name] } depends_on = [aws_autoscaling_group.test1, aws_autoscaling_group.test2, aws_autoscaling_group.test3] diff --git a/internal/service/autoscaling/launch_configuration.go b/internal/service/autoscaling/launch_configuration.go index f451393ad00..8ad64c669f9 100644 --- a/internal/service/autoscaling/launch_configuration.go +++ b/internal/service/autoscaling/launch_configuration.go @@ -5,7 +5,6 @@ import ( // nosemgrep: aws-sdk-go-multiple-service-imports "crypto/sha1" "encoding/base64" "encoding/hex" - "errors" "fmt" "log" @@ -19,6 +18,7 @@ import ( // nosemgrep: aws-sdk-go-multiple-service-imports "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" "github.com/hashicorp/terraform-provider-aws/internal/flex" + tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -41,8 +41,8 @@ func ResourceLaunchConfiguration() *schema.Resource { "associate_public_ip_address": { Type: schema.TypeBool, Optional: true, + Computed: true, ForceNew: true, - Default: false, }, "ebs_block_device": { Type: schema.TypeSet, @@ -315,7 +315,6 @@ func ResourceLaunchConfiguration() *schema.Resource { Optional: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, }, } @@ -326,212 +325,116 @@ func resourceLaunchConfigurationCreate(d *schema.ResourceData, meta interface{}) ec2conn := meta.(*conns.AWSClient).EC2Conn lcName := create.Name(d.Get("name").(string), d.Get("name_prefix").(string)) - - createLaunchConfigurationOpts := autoscaling.CreateLaunchConfigurationInput{ - LaunchConfigurationName: aws.String(lcName), + input := autoscaling.CreateLaunchConfigurationInput{ + EbsOptimized: aws.Bool(d.Get("ebs_optimized").(bool)), ImageId: aws.String(d.Get("image_id").(string)), InstanceType: aws.String(d.Get("instance_type").(string)), - EbsOptimized: aws.Bool(d.Get("ebs_optimized").(bool)), + LaunchConfigurationName: aws.String(lcName), } - if v, ok := d.GetOk("user_data"); ok { - userData := verify.Base64Encode([]byte(v.(string))) - createLaunchConfigurationOpts.UserData = aws.String(userData) - } else if v, ok := d.GetOk("user_data_base64"); ok { - createLaunchConfigurationOpts.UserData = aws.String(v.(string)) + associatePublicIPAddress := d.GetRawConfig().GetAttr("associate_public_ip_address") + if associatePublicIPAddress.IsKnown() && !associatePublicIPAddress.IsNull() { + input.AssociatePublicIpAddress = aws.Bool(associatePublicIPAddress.True()) } - createLaunchConfigurationOpts.InstanceMonitoring = &autoscaling.InstanceMonitoring{ - Enabled: aws.Bool(d.Get("enable_monitoring").(bool)), + if v, ok := d.GetOk("vpc_classic_link_id"); ok { + input.ClassicLinkVPCId = aws.String(v.(string)) } - if v, ok := d.GetOk("iam_instance_profile"); ok { - createLaunchConfigurationOpts.IamInstanceProfile = aws.String(v.(string)) + if v, ok := d.GetOk("vpc_classic_link_security_groups"); ok && v.(*schema.Set).Len() > 0 { + input.ClassicLinkVPCSecurityGroups = flex.ExpandStringSet(v.(*schema.Set)) } - if v, ok := d.GetOk("placement_tenancy"); ok { - createLaunchConfigurationOpts.PlacementTenancy = aws.String(v.(string)) + if v, ok := d.GetOk("iam_instance_profile"); ok { + input.IamInstanceProfile = aws.String(v.(string)) } - if v, ok := d.GetOk("associate_public_ip_address"); ok { - createLaunchConfigurationOpts.AssociatePublicIpAddress = aws.Bool(v.(bool)) + input.InstanceMonitoring = &autoscaling.InstanceMonitoring{ + Enabled: aws.Bool(d.Get("enable_monitoring").(bool)), } if v, ok := d.GetOk("key_name"); ok { - createLaunchConfigurationOpts.KeyName = aws.String(v.(string)) - } - if v, ok := d.GetOk("spot_price"); ok { - createLaunchConfigurationOpts.SpotPrice = aws.String(v.(string)) + input.KeyName = aws.String(v.(string)) } - if v, ok := d.GetOk("security_groups"); ok { - createLaunchConfigurationOpts.SecurityGroups = flex.ExpandStringSet(v.(*schema.Set)) + if v, ok := d.GetOk("metadata_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.MetadataOptions = expandInstanceMetadataOptions(v.([]interface{})[0].(map[string]interface{})) } - if v, ok := d.GetOk("vpc_classic_link_id"); ok { - createLaunchConfigurationOpts.ClassicLinkVPCId = aws.String(v.(string)) + if v, ok := d.GetOk("placement_tenancy"); ok { + input.PlacementTenancy = aws.String(v.(string)) } - if v, ok := d.GetOk("metadata_options"); ok { - createLaunchConfigurationOpts.MetadataOptions = expandLaunchConfigInstanceMetadataOptions(v.([]interface{})) + if v, ok := d.GetOk("security_groups"); ok && v.(*schema.Set).Len() > 0 { + input.SecurityGroups = flex.ExpandStringSet(v.(*schema.Set)) } - if v, ok := d.GetOk("vpc_classic_link_security_groups"); ok { - createLaunchConfigurationOpts.ClassicLinkVPCSecurityGroups = flex.ExpandStringSet(v.(*schema.Set)) + if v, ok := d.GetOk("spot_price"); ok { + input.SpotPrice = aws.String(v.(string)) } - var blockDevices []*autoscaling.BlockDeviceMapping + if v, ok := d.GetOk("user_data"); ok { + input.UserData = aws.String(verify.Base64Encode([]byte(v.(string)))) + } else if v, ok := d.GetOk("user_data_base64"); ok { + input.UserData = aws.String(v.(string)) + } // We'll use this to detect if we're declaring it incorrectly as an ebs_block_device. - rootDeviceName, err := fetchRootDeviceName(d.Get("image_id").(string), ec2conn) + rootDeviceName, err := findImageRootDeviceName(ec2conn, d.Get("image_id").(string)) + if err != nil { return 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 - } - - if v, ok := d.GetOk("ebs_block_device"); ok { - vL := v.(*schema.Set).List() - for _, v := range vL { - bd := v.(map[string]interface{}) - ebs := &autoscaling.Ebs{} - - var noDevice *bool - if v, ok := bd["no_device"].(bool); ok && v { - noDevice = aws.Bool(v) - } else { - ebs.DeleteOnTermination = aws.Bool(bd["delete_on_termination"].(bool)) - } - - if v, ok := bd["snapshot_id"].(string); ok && v != "" { - ebs.SnapshotId = aws.String(v) - } - - if v, ok := bd["encrypted"].(bool); ok && v { - ebs.Encrypted = aws.Bool(v) - } - if v, ok := bd["volume_size"].(int); ok && v != 0 { - ebs.VolumeSize = aws.Int64(int64(v)) - } - - if v, ok := bd["volume_type"].(string); ok && v != "" { - ebs.VolumeType = aws.String(v) - } - - if v, ok := bd["iops"].(int); ok && v > 0 { - ebs.Iops = aws.Int64(int64(v)) - } + var blockDeviceMappings []*autoscaling.BlockDeviceMapping - if v, ok := bd["throughput"].(int); ok && v > 0 { - ebs.Throughput = aws.Int64(int64(v)) - } + if v, ok := d.GetOk("ebs_block_device"); ok && v.(*schema.Set).Len() > 0 { + v := expandBlockDeviceMappings(v.(*schema.Set).List(), expandBlockDeviceMappingForEBSBlockDevice) - if bd["device_name"].(string) == aws.StringValue(rootDeviceName) { - return fmt.Errorf("Root device (%s) declared as an 'ebs_block_device'. Use 'root_block_device' keyword.", *rootDeviceName) + for _, v := range v { + if aws.StringValue(v.DeviceName) == rootDeviceName { + return fmt.Errorf("root device (%s) declared as an 'ebs_block_device'. Use 'root_block_device' argument.", rootDeviceName) } - - blockDevices = append(blockDevices, &autoscaling.BlockDeviceMapping{ - DeviceName: aws.String(bd["device_name"].(string)), - Ebs: ebs, - NoDevice: noDevice, - }) } - } - - if v, ok := d.GetOk("ephemeral_block_device"); ok { - vL := v.(*schema.Set).List() - for _, v := range vL { - bd := v.(map[string]interface{}) - bdm := &autoscaling.BlockDeviceMapping{ - DeviceName: aws.String(bd["device_name"].(string)), - } - - if v, ok := bd["no_device"].(bool); ok && v { - bdm.NoDevice = aws.Bool(true) - } - - if v, ok := bd["virtual_name"].(string); ok && v != "" { - bdm.VirtualName = aws.String(v) - } - blockDevices = append(blockDevices, bdm) - } + blockDeviceMappings = append(blockDeviceMappings, v...) } - if v, ok := d.GetOk("root_block_device"); ok { - vL := v.([]interface{}) - for _, v := range vL { - bd := v.(map[string]interface{}) - ebs := &autoscaling.Ebs{ - DeleteOnTermination: aws.Bool(bd["delete_on_termination"].(bool)), - } - - if v, ok := bd["encrypted"].(bool); ok && v { - ebs.Encrypted = aws.Bool(v) - } - - if v, ok := bd["volume_size"].(int); ok && v != 0 { - ebs.VolumeSize = aws.Int64(int64(v)) - } - - if v, ok := bd["volume_type"].(string); ok && v != "" { - ebs.VolumeType = aws.String(v) - } + if v, ok := d.GetOk("ephemeral_block_device"); ok && v.(*schema.Set).Len() > 0 { + v := expandBlockDeviceMappings(v.(*schema.Set).List(), expandBlockDeviceMappingForEphemeralBlockDevice) - if v, ok := bd["iops"].(int); ok && v > 0 { - ebs.Iops = aws.Int64(int64(v)) - } + blockDeviceMappings = append(blockDeviceMappings, v...) + } - if v, ok := bd["throughput"].(int); ok && v > 0 { - ebs.Throughput = aws.Int64(int64(v)) - } + if v, ok := d.GetOk("root_block_device"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + v := expandBlockDeviceMappingForRootBlockDevice(v.([]interface{})[0].(map[string]interface{})) + v.DeviceName = aws.String(rootDeviceName) - if dn, err := fetchRootDeviceName(d.Get("image_id").(string), ec2conn); err == nil { - if dn == nil { - return fmt.Errorf( - "Expected to find a Root Device name for AMI (%s), but got none", - d.Get("image_id").(string)) - } - blockDevices = append(blockDevices, &autoscaling.BlockDeviceMapping{ - DeviceName: dn, - Ebs: ebs, - }) - } else { - return err - } - } + blockDeviceMappings = append(blockDeviceMappings, v) } - if len(blockDevices) > 0 { - createLaunchConfigurationOpts.BlockDeviceMappings = blockDevices + if len(blockDeviceMappings) > 0 { + input.BlockDeviceMappings = blockDeviceMappings } - log.Printf("[DEBUG] autoscaling create launch configuration: %s", createLaunchConfigurationOpts) - + log.Printf("[DEBUG] Creating Auto Scaling Launch Configuration: %s", input) // IAM profiles can take ~10 seconds to propagate in AWS: // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console - err = resource.Retry(propagationTimeout, func() *resource.RetryError { - _, err := autoscalingconn.CreateLaunchConfiguration(&createLaunchConfigurationOpts) - if err != nil { - if tfawserr.ErrMessageContains(err, "ValidationError", "Invalid IamInstanceProfile") { - return resource.RetryableError(err) - } - if tfawserr.ErrMessageContains(err, "ValidationError", "You are not authorized to perform this operation") { - return resource.RetryableError(err) + _, err = tfresource.RetryWhen(propagationTimeout, + func() (interface{}, error) { + return autoscalingconn.CreateLaunchConfiguration(&input) + }, + func(err error) (bool, error) { + if tfawserr.ErrMessageContains(err, ErrCodeValidationError, "Invalid IamInstanceProfile") || + tfawserr.ErrMessageContains(err, ErrCodeValidationError, "You are not authorized to perform this operation") { + return true, err } - return resource.NonRetryableError(err) - } - return nil - }) - if tfresource.TimedOut(err) { - _, err = autoscalingconn.CreateLaunchConfiguration(&createLaunchConfigurationOpts) - } + + return false, err + }) + if err != nil { - return fmt.Errorf("Error creating launch configuration: %w", err) + return fmt.Errorf("creating Auto Scaling Launch Configuration (%s): %w", lcName, err) } d.SetId(lcName) @@ -546,50 +449,82 @@ func resourceLaunchConfigurationRead(d *schema.ResourceData, meta interface{}) e lc, err := FindLaunchConfigurationByName(autoscalingconn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] Autoscaling Launch Configuration %s not found, removing from state", d.Id()) + log.Printf("[WARN] Auto Scaling Launch Configuration %s not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("error reading Autoscaling Launch Configuration (%s): %w", d.Id(), err) + return fmt.Errorf("reading Auto Scaling Launch Configuration (%s): %w", d.Id(), err) } - d.Set("key_name", lc.KeyName) + d.Set("arn", lc.LaunchConfigurationARN) + d.Set("associate_public_ip_address", lc.AssociatePublicIpAddress) + d.Set("ebs_optimized", lc.EbsOptimized) + if lc.InstanceMonitoring != nil { + d.Set("enable_monitoring", lc.InstanceMonitoring.Enabled) + } else { + d.Set("enable_monitoring", false) + } + d.Set("iam_instance_profile", lc.IamInstanceProfile) d.Set("image_id", lc.ImageId) d.Set("instance_type", lc.InstanceType) + d.Set("key_name", lc.KeyName) + if lc.MetadataOptions != nil { + if err := d.Set("metadata_options", []interface{}{flattenInstanceMetadataOptions(lc.MetadataOptions)}); err != nil { + return fmt.Errorf("setting metadata_options: %w", err) + } + } else { + d.Set("metadata_options", nil) + } d.Set("name", lc.LaunchConfigurationName) d.Set("name_prefix", create.NamePrefixFromName(aws.StringValue(lc.LaunchConfigurationName))) - d.Set("arn", lc.LaunchConfigurationARN) - - d.Set("iam_instance_profile", lc.IamInstanceProfile) - d.Set("ebs_optimized", lc.EbsOptimized) + d.Set("placement_tenancy", lc.PlacementTenancy) + d.Set("security_groups", aws.StringValueSlice(lc.SecurityGroups)) d.Set("spot_price", lc.SpotPrice) - d.Set("enable_monitoring", lc.InstanceMonitoring.Enabled) - d.Set("associate_public_ip_address", lc.AssociatePublicIpAddress) - if err := d.Set("security_groups", flex.FlattenStringList(lc.SecurityGroups)); err != nil { - return fmt.Errorf("error setting security_groups: %w", err) - } if v := aws.StringValue(lc.UserData); v != "" { - _, b64 := d.GetOk("user_data_base64") - if b64 { + if _, ok := d.GetOk("user_data_base64"); ok { d.Set("user_data_base64", v) } else { d.Set("user_data", userDataHashSum(v)) } } - d.Set("vpc_classic_link_id", lc.ClassicLinkVPCId) - if err := d.Set("vpc_classic_link_security_groups", flex.FlattenStringList(lc.ClassicLinkVPCSecurityGroups)); err != nil { - return fmt.Errorf("error setting vpc_classic_link_security_groups: %w", err) + d.Set("vpc_classic_link_security_groups", aws.StringValueSlice(lc.ClassicLinkVPCSecurityGroups)) + + rootDeviceName, err := findImageRootDeviceName(ec2conn, d.Get("image_id").(string)) + + if tfresource.NotFound(err) { + // Don't block a refresh for a bad image. + rootDeviceName = "" + } else if err != nil { + return err } - if err := d.Set("metadata_options", flattenLaunchConfigInstanceMetadataOptions(lc.MetadataOptions)); err != nil { - return fmt.Errorf("error setting metadata_options: %w", err) + configuredEBSBlockDevices := make(map[string]map[string]interface{}) + + if v, ok := d.GetOk("ebs_block_device"); ok && v.(*schema.Set).Len() > 0 { + for _, v := range v.(*schema.Set).List() { + tfMap, ok := v.(map[string]interface{}) + + if !ok { + continue + } + + configuredEBSBlockDevices[tfMap["device_name"].(string)] = tfMap + } } - if err := readLCBlockDevices(d, lc, ec2conn); err != nil { - return err + tfListEBSBlockDevice, tfListEphemeralBlockDevice, tfListRootBlockDevice := flattenBlockDeviceMappings(lc.BlockDeviceMappings, rootDeviceName, configuredEBSBlockDevices) + + if err := d.Set("ebs_block_device", tfListEBSBlockDevice); err != nil { + return fmt.Errorf("setting ebs_block_device: %w", err) + } + if err := d.Set("ephemeral_block_device", tfListEphemeralBlockDevice); err != nil { + return fmt.Errorf("setting ephemeral_block_device: %w", err) + } + if err := d.Set("root_block_device", tfListRootBlockDevice); err != nil { + return fmt.Errorf("setting root_block_device: %w", err) } return nil @@ -618,216 +553,277 @@ func resourceLaunchConfigurationDelete(d *schema.ResourceData, meta interface{}) return nil } -func readLCBlockDevices(d *schema.ResourceData, lc *autoscaling.LaunchConfiguration, ec2conn *ec2.EC2) error { - ibds, err := readBlockDevicesFromLaunchConfiguration(d, lc, ec2conn) - if err != nil { - return err +func expandBlockDeviceMappingForEBSBlockDevice(tfMap map[string]interface{}) *autoscaling.BlockDeviceMapping { + if tfMap == nil { + return nil } - if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil { - return err + apiObject := &autoscaling.BlockDeviceMapping{ + Ebs: &autoscaling.Ebs{}, } - if err := d.Set("ephemeral_block_device", ibds["ephemeral"]); err != nil { - return err + + if v, ok := tfMap["device_name"].(string); ok && v != "" { + apiObject.DeviceName = aws.String(v) } - if ibds["root"] != nil { - if err := d.Set("root_block_device", []interface{}{ibds["root"]}); err != nil { - return err - } - } else { - d.Set("root_block_device", []interface{}{}) + + if v, ok := tfMap["no_device"].(bool); ok && v { + apiObject.NoDevice = aws.Bool(v) + } else if v, ok := tfMap["delete_on_termination"].(bool); ok { + apiObject.Ebs.DeleteOnTermination = aws.Bool(v) } - return nil + if v, ok := tfMap["encrypted"].(bool); ok && v { + apiObject.Ebs.Encrypted = aws.Bool(v) + } + + if v, ok := tfMap["iops"].(int); ok && v != 0 { + apiObject.Ebs.Iops = aws.Int64(int64(v)) + } + + if v, ok := tfMap["snapshot_id"].(string); ok && v != "" { + apiObject.Ebs.SnapshotId = aws.String(v) + } + + if v, ok := tfMap["throughput"].(int); ok && v != 0 { + apiObject.Ebs.Throughput = aws.Int64(int64(v)) + } + + if v, ok := tfMap["volume_size"].(int); ok && v != 0 { + apiObject.Ebs.VolumeSize = aws.Int64(int64(v)) + } + + if v, ok := tfMap["volume_type"].(string); ok && v != "" { + apiObject.Ebs.VolumeType = aws.String(v) + } + + return apiObject } -func expandLaunchConfigInstanceMetadataOptions(l []interface{}) *autoscaling.InstanceMetadataOptions { - if len(l) == 0 || l[0] == nil { +func expandBlockDeviceMappingForEphemeralBlockDevice(tfMap map[string]interface{}) *autoscaling.BlockDeviceMapping { + if tfMap == nil { return nil } - m := l[0].(map[string]interface{}) + apiObject := &autoscaling.BlockDeviceMapping{} - opts := &autoscaling.InstanceMetadataOptions{ - HttpEndpoint: aws.String(m["http_endpoint"].(string)), + if v, ok := tfMap["device_name"].(string); ok && v != "" { + apiObject.DeviceName = aws.String(v) } - if m["http_endpoint"].(string) == autoscaling.InstanceMetadataEndpointStateEnabled { - // These parameters are not allowed unless HttpEndpoint is enabled - - if v, ok := m["http_tokens"].(string); ok && v != "" { - opts.HttpTokens = aws.String(v) - } + if v, ok := tfMap["no_device"].(bool); ok && v { + apiObject.NoDevice = aws.Bool(v) + } - if v, ok := m["http_put_response_hop_limit"].(int); ok && v != 0 { - opts.HttpPutResponseHopLimit = aws.Int64(int64(v)) - } + if v, ok := tfMap["virtual_name"].(string); ok && v != "" { + apiObject.VirtualName = aws.String(v) } - return opts + return apiObject } -func flattenLaunchConfigInstanceMetadataOptions(opts *autoscaling.InstanceMetadataOptions) []interface{} { - if opts == nil { +func expandBlockDeviceMappingForRootBlockDevice(tfMap map[string]interface{}) *autoscaling.BlockDeviceMapping { + if tfMap == nil { return nil } - m := map[string]interface{}{ - "http_endpoint": aws.StringValue(opts.HttpEndpoint), - "http_put_response_hop_limit": aws.Int64Value(opts.HttpPutResponseHopLimit), - "http_tokens": aws.StringValue(opts.HttpTokens), + apiObject := &autoscaling.BlockDeviceMapping{ + Ebs: &autoscaling.Ebs{}, } - return []interface{}{m} -} + if v, ok := tfMap["delete_on_termination"].(bool); ok { + apiObject.Ebs.DeleteOnTermination = aws.Bool(v) + } -func readBlockDevicesFromLaunchConfiguration(d *schema.ResourceData, lc *autoscaling.LaunchConfiguration, ec2conn *ec2.EC2) ( - map[string]interface{}, error) { - blockDevices := make(map[string]interface{}) - blockDevices["ebs"] = make([]map[string]interface{}, 0) - blockDevices["ephemeral"] = make([]map[string]interface{}, 0) - blockDevices["root"] = nil - if len(lc.BlockDeviceMappings) == 0 { - return nil, nil + if v, ok := tfMap["encrypted"].(bool); ok && v { + apiObject.Ebs.Encrypted = aws.Bool(v) } - v, err := fetchRootDeviceName(d.Get("image_id").(string), ec2conn) - if err != nil { - return nil, err + + if v, ok := tfMap["iops"].(int); ok && v != 0 { + apiObject.Ebs.Iops = aws.Int64(int64(v)) + } + + if v, ok := tfMap["throughput"].(int); ok && v != 0 { + apiObject.Ebs.Throughput = aws.Int64(int64(v)) + } + + if v, ok := tfMap["volume_size"].(int); ok && v != 0 { + apiObject.Ebs.VolumeSize = aws.Int64(int64(v)) + } + + if v, ok := tfMap["volume_type"].(string); ok && v != "" { + apiObject.Ebs.VolumeType = aws.String(v) + } + + return apiObject +} + +func expandBlockDeviceMappings(tfList []interface{}, fn func(map[string]interface{}) *autoscaling.BlockDeviceMapping) []*autoscaling.BlockDeviceMapping { + if len(tfList) == 0 { + return nil } - rootDeviceName := aws.StringValue(v) - - // Collect existing configured devices, so we can check - // existing value of delete_on_termination below - existingEbsBlockDevices := make(map[string]map[string]interface{}) - if v, ok := d.GetOk("ebs_block_device"); ok { - ebsBlocks := v.(*schema.Set) - for _, ebd := range ebsBlocks.List() { - m := ebd.(map[string]interface{}) - deviceName := m["device_name"].(string) - existingEbsBlockDevices[deviceName] = m + + var apiObjects []*autoscaling.BlockDeviceMapping + + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]interface{}) + + if !ok { + continue } + + apiObject := fn(tfMap) + + if apiObject == nil { + continue + } + + apiObjects = append(apiObjects, apiObject) } - for _, bdm := range lc.BlockDeviceMappings { - bd := make(map[string]interface{}) + return apiObjects +} - if bdm.NoDevice != nil { - // Keep existing value in place to avoid spurious diff - deleteOnTermination := true - if device, ok := existingEbsBlockDevices[*bdm.DeviceName]; ok { - deleteOnTermination = device["delete_on_termination"].(bool) - } - bd["delete_on_termination"] = deleteOnTermination - } else if bdm.Ebs != nil && bdm.Ebs.DeleteOnTermination != nil { - bd["delete_on_termination"] = aws.BoolValue(bdm.Ebs.DeleteOnTermination) +func flattenBlockDeviceMappings(apiObjects []*autoscaling.BlockDeviceMapping, rootDeviceName string, configuredEBSBlockDevices map[string]map[string]interface{}) ([]interface{}, []interface{}, []interface{}) { + if len(apiObjects) == 0 { + return nil, nil, nil + } + + var tfListEBSBlockDevice, tfListEphemeralBlockDevice, tfListRootBlockDevice []interface{} + + for _, apiObject := range apiObjects { + if apiObject == nil { + continue } - if bdm.Ebs != nil && bdm.Ebs.VolumeSize != nil { - bd["volume_size"] = aws.Int64Value(bdm.Ebs.VolumeSize) + tfMap := map[string]interface{}{} + + if v := apiObject.NoDevice; v != nil { + if v, ok := configuredEBSBlockDevices[aws.StringValue(apiObject.DeviceName)]; ok { + tfMap["delete_on_termination"] = v["delete_on_termination"].(bool) + } else { + // Keep existing value in place to avoid spurious diff. + tfMap["delete_on_termination"] = true + } + } else if v := apiObject.Ebs; v != nil { + if v := v.DeleteOnTermination; v != nil { + tfMap["delete_on_termination"] = aws.BoolValue(v) + } } - if bdm.Ebs != nil && bdm.Ebs.VolumeType != nil { - bd["volume_type"] = aws.StringValue(bdm.Ebs.VolumeType) + + if v := apiObject.Ebs; v != nil { + if v := v.Encrypted; v != nil { + tfMap["encrypted"] = aws.BoolValue(v) + } + + if v := v.Iops; v != nil { + tfMap["iops"] = aws.Int64Value(v) + } + + if v := v.Throughput; v != nil { + tfMap["throughput"] = aws.Int64Value(v) + } + + if v := v.VolumeSize; v != nil { + tfMap["volume_size"] = aws.Int64Value(v) + } + + if v := v.VolumeType; v != nil { + tfMap["volume_type"] = aws.StringValue(v) + } } - if bdm.Ebs != nil && bdm.Ebs.Iops != nil { - bd["iops"] = aws.Int64Value(bdm.Ebs.Iops) + + if v := apiObject.DeviceName; aws.StringValue(v) == rootDeviceName { + tfListRootBlockDevice = append(tfListRootBlockDevice, tfMap) + + continue } - if bdm.Ebs != nil && bdm.Ebs.Throughput != nil { - bd["throughput"] = aws.Int64Value(bdm.Ebs.Throughput) + + if v := apiObject.DeviceName; v != nil { + tfMap["device_name"] = aws.StringValue(v) } - if bdm.Ebs != nil && bdm.Ebs.Encrypted != nil { - bd["encrypted"] = aws.BoolValue(bdm.Ebs.Encrypted) + + if v := apiObject.VirtualName; v != nil { + tfMap["virtual_name"] = aws.StringValue(v) + + tfListEphemeralBlockDevice = append(tfListEphemeralBlockDevice, tfMap) + + continue } - if bdm.DeviceName != nil && aws.StringValue(bdm.DeviceName) == rootDeviceName { - blockDevices["root"] = bd - } else { - if bdm.DeviceName != nil { - bd["device_name"] = aws.StringValue(bdm.DeviceName) - } + if v := apiObject.NoDevice; v != nil { + tfMap["no_device"] = aws.BoolValue(v) + } - if bdm.VirtualName != nil { - 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"] = aws.StringValue(bdm.Ebs.SnapshotId) - } - if bdm.NoDevice != nil { - bd["no_device"] = aws.BoolValue(bdm.NoDevice) - } - blockDevices["ebs"] = append(blockDevices["ebs"].([]map[string]interface{}), bd) + if v := apiObject.Ebs; v != nil { + if v := v.SnapshotId; v != nil { + tfMap["snapshot_id"] = aws.StringValue(v) } } - } - return blockDevices, nil -} -func userDataHashSum(user_data string) string { - // Check whether the user_data is not Base64 encoded. - // Always calculate hash of base64 decoded value since we - // check against double-encoding when setting it - v, base64DecodeError := base64.StdEncoding.DecodeString(user_data) - if base64DecodeError != nil { - v = []byte(user_data) + tfListEBSBlockDevice = append(tfListEBSBlockDevice, tfMap) } - hash := sha1.Sum(v) - return hex.EncodeToString(hash[:]) + return tfListEBSBlockDevice, tfListEphemeralBlockDevice, tfListRootBlockDevice } -func fetchRootDeviceName(ami string, conn *ec2.EC2) (*string, error) { - if ami == "" { - return nil, errors.New("Cannot fetch root device name for blank AMI ID.") +func expandInstanceMetadataOptions(tfMap map[string]interface{}) *autoscaling.InstanceMetadataOptions { + if tfMap == nil { + return nil } - log.Printf("[DEBUG] Describing AMI %q to get root block device name", ami) - res, err := conn.DescribeImages(&ec2.DescribeImagesInput{ - ImageIds: []*string{aws.String(ami)}, - }) - if err != nil { - return nil, err + apiObject := &autoscaling.InstanceMetadataOptions{} + + if v, ok := tfMap["http_endpoint"].(string); ok && v != "" { + apiObject.HttpEndpoint = aws.String(v) + + if v == autoscaling.InstanceMetadataEndpointStateEnabled { + if v, ok := tfMap["http_tokens"].(string); ok && v != "" { + apiObject.HttpTokens = aws.String(v) + } + + if v, ok := tfMap["http_put_response_hop_limit"].(int); ok && v != 0 { + apiObject.HttpPutResponseHopLimit = aws.Int64(int64(v)) + } + } } - // For a bad image, we just return nil so we don't block a refresh - if len(res.Images) == 0 { - return nil, nil + return apiObject +} + +func flattenInstanceMetadataOptions(apiObject *autoscaling.InstanceMetadataOptions) map[string]interface{} { + if apiObject == nil { + return nil } - image := res.Images[0] - rootDeviceName := image.RootDeviceName + tfMap := map[string]interface{}{} - // Instance store backed AMIs do not provide a root device name. - if aws.StringValue(image.RootDeviceType) == ec2.DeviceTypeInstanceStore { - return nil, nil + if v := apiObject.HttpEndpoint; v != nil { + tfMap["http_endpoint"] = aws.StringValue(v) } - // Some AMIs have a RootDeviceName like "/dev/sda1" that does not appear as a - // DeviceName in the BlockDeviceMapping list (which will instead have - // something like "/dev/sda") - // - // While this seems like it breaks an invariant of AMIs, it ends up working - // on the AWS side, and AMIs like this are common enough that we need to - // special case it so Terraform does the right thing. - // - // Our heuristic is: if the RootDeviceName does not appear in the - // BlockDeviceMapping, assume that the DeviceName of the first - // BlockDeviceMapping entry serves as the root device. - rootDeviceNameInMapping := false - for _, bdm := range image.BlockDeviceMappings { - if aws.StringValue(bdm.DeviceName) == aws.StringValue(image.RootDeviceName) { - rootDeviceNameInMapping = true - } + if v := apiObject.HttpPutResponseHopLimit; v != nil { + tfMap["http_put_response_hop_limit"] = aws.Int64Value(v) } - if !rootDeviceNameInMapping && len(image.BlockDeviceMappings) > 0 { - rootDeviceName = image.BlockDeviceMappings[0].DeviceName + if v := apiObject.HttpTokens; v != nil { + tfMap["http_tokens"] = aws.StringValue(v) } - if rootDeviceName == nil { - return nil, fmt.Errorf("Error finding Root Device Name for AMI (%s)", ami) + return tfMap +} + +func userDataHashSum(userData string) string { + // Check whether the user_data is not Base64 encoded. + // Always calculate hash of base64 decoded value since we + // check against double-encoding when setting it. + v, err := base64.StdEncoding.DecodeString(userData) + + if err != nil { + v = []byte(userData) } - return rootDeviceName, nil + hash := sha1.Sum(v) + return hex.EncodeToString(hash[:]) } func findLaunchConfiguration(conn *autoscaling.AutoScaling, input *autoscaling.DescribeLaunchConfigurationsInput) (*autoscaling.LaunchConfiguration, error) { @@ -894,3 +890,49 @@ func FindLaunchConfigurationByName(conn *autoscaling.AutoScaling, name string) ( return output, nil } + +func findImageRootDeviceName(conn *ec2.EC2, imageID string) (string, error) { + image, err := tfec2.FindImageByID(conn, imageID) + + if err != nil { + return "", err + } + + // Instance store backed AMIs do not provide a root device name. + if aws.StringValue(image.RootDeviceType) == ec2.DeviceTypeInstanceStore { + return "", nil + } + + rootDeviceName := aws.StringValue(image.RootDeviceName) + + // Some AMIs have a RootDeviceName like "/dev/sda1" that does not appear as a + // DeviceName in the BlockDeviceMapping list (which will instead have + // something like "/dev/sda") + // + // While this seems like it breaks an invariant of AMIs, it ends up working + // on the AWS side, and AMIs like this are common enough that we need to + // special case it so Terraform does the right thing. + // + // Our heuristic is: if the RootDeviceName does not appear in the + // BlockDeviceMapping, assume that the DeviceName of the first + // BlockDeviceMapping entry serves as the root device. + rootDeviceInBlockDeviceMappings := false + + for _, v := range image.BlockDeviceMappings { + if aws.StringValue(v.DeviceName) == rootDeviceName { + rootDeviceInBlockDeviceMappings = true + } + } + + if !rootDeviceInBlockDeviceMappings && len(image.BlockDeviceMappings) > 0 { + rootDeviceName = aws.StringValue(image.BlockDeviceMappings[0].DeviceName) + } + + if rootDeviceName == "" { + return "", &resource.NotFoundError{ + Message: fmt.Sprintf("finding root device name for EC2 AMI (%s)", imageID), + } + } + + return rootDeviceName, nil +} diff --git a/internal/service/autoscaling/launch_configuration_data_source.go b/internal/service/autoscaling/launch_configuration_data_source.go index 62a136355f1..322ccba5ea7 100644 --- a/internal/service/autoscaling/launch_configuration_data_source.go +++ b/internal/service/autoscaling/launch_configuration_data_source.go @@ -1,12 +1,9 @@ package autoscaling import ( - "errors" "fmt" - "log" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -14,83 +11,16 @@ import ( func DataSourceLaunchConfiguration() *schema.Resource { return &schema.Resource{ Read: dataSourceLaunchConfigurationRead, + Schema: map[string]*schema.Schema{ "arn": { Type: schema.TypeString, Computed: true, }, - "name": { - Type: schema.TypeString, - Required: true, - }, - - "image_id": { - Type: schema.TypeString, - Computed: true, - }, - - "instance_type": { - Type: schema.TypeString, - Computed: true, - }, - - "iam_instance_profile": { - Type: schema.TypeString, - Computed: true, - }, - - "key_name": { - Type: schema.TypeString, - Computed: true, - }, - - "user_data": { - Type: schema.TypeString, - Computed: true, - }, - - "security_groups": { - Type: schema.TypeSet, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - - "vpc_classic_link_id": { - Type: schema.TypeString, - Computed: true, - }, - - "vpc_classic_link_security_groups": { - Type: schema.TypeSet, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "associate_public_ip_address": { Type: schema.TypeBool, Computed: true, }, - - "spot_price": { - Type: schema.TypeString, - Computed: true, - }, - - "ebs_optimized": { - Type: schema.TypeBool, - Computed: true, - }, - - "placement_tenancy": { - Type: schema.TypeString, - Computed: true, - }, - - "enable_monitoring": { - Type: schema.TypeBool, - Computed: true, - }, - "ebs_block_device": { Type: schema.TypeSet, Computed: true, @@ -100,42 +30,34 @@ func DataSourceLaunchConfiguration() *schema.Resource { Type: schema.TypeBool, Computed: true, }, - "device_name": { Type: schema.TypeString, Computed: true, }, - "encrypted": { Type: schema.TypeBool, Computed: true, }, - "iops": { Type: schema.TypeInt, Computed: true, }, - "no_device": { Type: schema.TypeBool, Computed: true, }, - "snapshot_id": { Type: schema.TypeString, Computed: true, }, - "throughput": { - Type: schema.TypeBool, + Type: schema.TypeInt, Computed: true, }, - "volume_size": { Type: schema.TypeInt, Computed: true, }, - "volume_type": { Type: schema.TypeString, Computed: true, @@ -143,7 +65,14 @@ func DataSourceLaunchConfiguration() *schema.Resource { }, }, }, - + "ebs_optimized": { + Type: schema.TypeBool, + Computed: true, + }, + "enable_monitoring": { + Type: schema.TypeBool, + Computed: true, + }, "ephemeral_block_device": { Type: schema.TypeSet, Computed: true, @@ -153,7 +82,6 @@ func DataSourceLaunchConfiguration() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "virtual_name": { Type: schema.TypeString, Computed: true, @@ -161,7 +89,22 @@ func DataSourceLaunchConfiguration() *schema.Resource { }, }, }, - + "iam_instance_profile": { + Type: schema.TypeString, + Computed: true, + }, + "image_id": { + Type: schema.TypeString, + Computed: true, + }, + "instance_type": { + Type: schema.TypeString, + Computed: true, + }, + "key_name": { + Type: schema.TypeString, + Computed: true, + }, "metadata_options": { Type: schema.TypeList, Computed: true, @@ -171,18 +114,25 @@ func DataSourceLaunchConfiguration() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "http_tokens": { - Type: schema.TypeString, - Computed: true, - }, "http_put_response_hop_limit": { Type: schema.TypeInt, Computed: true, }, + "http_tokens": { + Type: schema.TypeString, + Computed: true, + }, }, }, }, - + "name": { + Type: schema.TypeString, + Required: true, + }, + "placement_tenancy": { + Type: schema.TypeString, + Computed: true, + }, "root_block_device": { Type: schema.TypeList, Computed: true, @@ -192,27 +142,22 @@ func DataSourceLaunchConfiguration() *schema.Resource { Type: schema.TypeBool, Computed: true, }, - "encrypted": { Type: schema.TypeBool, Computed: true, }, - "iops": { Type: schema.TypeInt, Computed: true, }, - "throughput": { - Type: schema.TypeBool, + Type: schema.TypeInt, Computed: true, }, - "volume_size": { Type: schema.TypeInt, Computed: true, }, - "volume_type": { Type: schema.TypeString, Computed: true, @@ -220,6 +165,28 @@ func DataSourceLaunchConfiguration() *schema.Resource { }, }, }, + "security_groups": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "spot_price": { + Type: schema.TypeString, + Computed: true, + }, + "user_data": { + Type: schema.TypeString, + Computed: true, + }, + "vpc_classic_link_id": { + Type: schema.TypeString, + Computed: true, + }, + "vpc_classic_link_security_groups": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, }, } } @@ -228,69 +195,58 @@ func dataSourceLaunchConfigurationRead(d *schema.ResourceData, meta interface{}) autoscalingconn := meta.(*conns.AWSClient).AutoScalingConn ec2conn := meta.(*conns.AWSClient).EC2Conn - if v, ok := d.GetOk("name"); ok { - d.SetId(v.(string)) - } - - describeOpts := autoscaling.DescribeLaunchConfigurationsInput{ - LaunchConfigurationNames: []*string{aws.String(d.Id())}, - } + name := d.Get("name").(string) + lc, err := FindLaunchConfigurationByName(autoscalingconn, name) - log.Printf("[DEBUG] launch configuration describe configuration: %s", describeOpts) - describConfs, err := autoscalingconn.DescribeLaunchConfigurations(&describeOpts) if err != nil { - return fmt.Errorf("Error retrieving launch configuration: %w", err) + return fmt.Errorf("reading Auto Scaling Launch Configuration (%s): %w", name, err) } - if describConfs == nil || len(describConfs.LaunchConfigurations) == 0 { - return errors.New("No matching Launch Configuration found") - } + d.SetId(name) - if len(describConfs.LaunchConfigurations) > 1 { - return errors.New("Multiple matching Launch Configurations found") + d.Set("arn", lc.LaunchConfigurationARN) + d.Set("associate_public_ip_address", lc.AssociatePublicIpAddress) + d.Set("ebs_optimized", lc.EbsOptimized) + if lc.InstanceMonitoring != nil { + d.Set("enable_monitoring", lc.InstanceMonitoring.Enabled) + } else { + d.Set("enable_monitoring", false) } - - lc := describConfs.LaunchConfigurations[0] - - d.Set("key_name", lc.KeyName) + d.Set("iam_instance_profile", lc.IamInstanceProfile) d.Set("image_id", lc.ImageId) d.Set("instance_type", lc.InstanceType) - d.Set("arn", lc.LaunchConfigurationARN) + d.Set("key_name", lc.KeyName) + if lc.MetadataOptions != nil { + if err := d.Set("metadata_options", []interface{}{flattenInstanceMetadataOptions(lc.MetadataOptions)}); err != nil { + return fmt.Errorf("setting metadata_options: %w", err) + } + } else { + d.Set("metadata_options", nil) + } d.Set("name", lc.LaunchConfigurationName) - d.Set("user_data", lc.UserData) - d.Set("iam_instance_profile", lc.IamInstanceProfile) - d.Set("ebs_optimized", lc.EbsOptimized) + d.Set("placement_tenancy", lc.PlacementTenancy) + d.Set("security_groups", aws.StringValueSlice(lc.SecurityGroups)) d.Set("spot_price", lc.SpotPrice) - d.Set("associate_public_ip_address", lc.AssociatePublicIpAddress) + d.Set("user_data", lc.UserData) d.Set("vpc_classic_link_id", lc.ClassicLinkVPCId) - d.Set("enable_monitoring", false) + d.Set("vpc_classic_link_security_groups", aws.StringValueSlice(lc.ClassicLinkVPCSecurityGroups)) - if lc.InstanceMonitoring != nil { - d.Set("enable_monitoring", lc.InstanceMonitoring.Enabled) - } + rootDeviceName, err := findImageRootDeviceName(ec2conn, d.Get("image_id").(string)) - vpcSGs := make([]string, 0, len(lc.SecurityGroups)) - for _, sg := range lc.SecurityGroups { - vpcSGs = append(vpcSGs, *sg) - } - if err := d.Set("security_groups", vpcSGs); err != nil { - return fmt.Errorf("error setting security_groups: %w", err) + if err != nil { + return err } - if err := d.Set("metadata_options", flattenLaunchConfigInstanceMetadataOptions(lc.MetadataOptions)); err != nil { - return fmt.Errorf("error setting metadata_options: %w", err) - } + tfListEBSBlockDevice, tfListEphemeralBlockDevice, tfListRootBlockDevice := flattenBlockDeviceMappings(lc.BlockDeviceMappings, rootDeviceName, map[string]map[string]interface{}{}) - classicSGs := make([]string, 0, len(lc.ClassicLinkVPCSecurityGroups)) - for _, sg := range lc.ClassicLinkVPCSecurityGroups { - classicSGs = append(classicSGs, *sg) + if err := d.Set("ebs_block_device", tfListEBSBlockDevice); err != nil { + return fmt.Errorf("setting ebs_block_device: %w", err) } - if err := d.Set("vpc_classic_link_security_groups", classicSGs); err != nil { - return fmt.Errorf("error setting vpc_classic_link_security_groups: %w", err) + if err := d.Set("ephemeral_block_device", tfListEphemeralBlockDevice); err != nil { + return fmt.Errorf("setting ephemeral_block_device: %w", err) } - - if err := readLCBlockDevices(d, lc, ec2conn); err != nil { - return err + if err := d.Set("root_block_device", tfListRootBlockDevice); err != nil { + return fmt.Errorf("setting root_block_device: %w", err) } return nil diff --git a/internal/service/autoscaling/launch_configuration_data_source_test.go b/internal/service/autoscaling/launch_configuration_data_source_test.go index eaa03e9c6c0..77649135e9c 100644 --- a/internal/service/autoscaling/launch_configuration_data_source_test.go +++ b/internal/service/autoscaling/launch_configuration_data_source_test.go @@ -2,7 +2,6 @@ package autoscaling_test import ( "fmt" - "regexp" "testing" "github.com/aws/aws-sdk-go/service/autoscaling" @@ -23,17 +22,26 @@ func TestAccAutoScalingLaunchConfigurationDataSource_basic(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccLaunchConfigurationDataSourceConfig_basic(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "associate_public_ip_address", resourceName, "associate_public_ip_address"), + resource.TestCheckResourceAttrPair(datasourceName, "ebs_block_device.#", resourceName, "ebs_block_device.#"), + resource.TestCheckResourceAttrPair(datasourceName, "ebs_optimized", resourceName, "ebs_optimized"), + resource.TestCheckResourceAttrPair(datasourceName, "enable_monitoring", resourceName, "enable_monitoring"), + resource.TestCheckResourceAttrPair(datasourceName, "ephemeral_block_device.#", resourceName, "ephemeral_block_device.#"), + resource.TestCheckResourceAttrPair(datasourceName, "iam_instance_profile", resourceName, "iam_instance_profile"), resource.TestCheckResourceAttrPair(datasourceName, "image_id", resourceName, "image_id"), resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), - resource.TestCheckResourceAttrPair(datasourceName, "associate_public_ip_address", resourceName, "associate_public_ip_address"), + resource.TestCheckResourceAttrPair(datasourceName, "metadata_options.#", resourceName, "metadata_options.#"), + resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(datasourceName, "placement_tenancy", resourceName, "placement_tenancy"), + resource.TestCheckResourceAttrPair(datasourceName, "root_block_device.#", resourceName, "root_block_device.#"), + resource.TestCheckResourceAttrPair(datasourceName, "security_groups.#", resourceName, "security_groups.#"), + resource.TestCheckResourceAttrPair(datasourceName, "spot_price", resourceName, "spot_price"), // Resource and data source user_data have differing representations in state. resource.TestCheckResourceAttrSet(datasourceName, "user_data"), - resource.TestCheckResourceAttrPair(datasourceName, "root_block_device.#", resourceName, "root_block_device.#"), - resource.TestCheckResourceAttrPair(datasourceName, "ebs_block_device.#", resourceName, "ebs_block_device.#"), - resource.TestCheckResourceAttrPair(datasourceName, "ephemeral_block_device.#", resourceName, "ephemeral_block_device.#"), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "autoscaling", regexp.MustCompile(`launchConfiguration:.+`)), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_classic_link_id", resourceName, "vpc_classic_link_id"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_classic_link_security_groups.#", resourceName, "vpc_classic_link_security_groups.#"), ), }, }, @@ -41,8 +49,8 @@ func TestAccAutoScalingLaunchConfigurationDataSource_basic(t *testing.T) { } func TestAccAutoScalingLaunchConfigurationDataSource_securityGroups(t *testing.T) { - rInt := sdkacctest.RandInt() - rName := "data.aws_launch_configuration.foo" + datasourceName := "data.aws_launch_configuration.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -50,9 +58,9 @@ func TestAccAutoScalingLaunchConfigurationDataSource_securityGroups(t *testing.T ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationDataSourceConfig_securityGroups(rInt), + Config: testAccLaunchConfigurationDataSourceConfig_securityGroups(rName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(rName, "security_groups.#", "1"), + resource.TestCheckResourceAttr(datasourceName, "security_groups.#", "1"), ), }, }, @@ -70,11 +78,8 @@ func TestAccAutoScalingLaunchConfigurationDataSource_ebsNoDevice(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationDataSourceConfigEbsNoDevice(rName), + Config: testAccLaunchConfigurationDataSourceConfig_ebsNoDevice(rName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), - resource.TestCheckResourceAttrPair(datasourceName, "image_id", resourceName, "image_id"), - resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), resource.TestCheckResourceAttrPair(datasourceName, "ebs_block_device.#", resourceName, "ebs_block_device.#"), ), }, @@ -94,12 +99,12 @@ func TestAccAutoScalingLaunchConfigurationDataSource_metadataOptions(t *testing. CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationDataSourceConfig_metadataOptions(rName), + Config: testAccLaunchConfigurationDataSourceConfig_metaOptions(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "metadata_options.#", resourceName, "metadata_options.#"), resource.TestCheckResourceAttrPair(dataSourceName, "metadata_options.0.http_endpoint", resourceName, "metadata_options.0.http_endpoint"), - resource.TestCheckResourceAttrPair(dataSourceName, "metadata_options.0.http_tokens", resourceName, "metadata_options.0.http_tokens"), resource.TestCheckResourceAttrPair(dataSourceName, "metadata_options.0.http_put_response_hop_limit", resourceName, "metadata_options.0.http_put_response_hop_limit"), + resource.TestCheckResourceAttrPair(dataSourceName, "metadata_options.0.http_tokens", resourceName, "metadata_options.0.http_tokens"), ), }, }, @@ -107,13 +112,13 @@ func TestAccAutoScalingLaunchConfigurationDataSource_metadataOptions(t *testing. } func testAccLaunchConfigurationDataSourceConfig_basic(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "m1.small" associate_public_ip_address = true - user_data = "foobar-user-data" + user_data = "test-user-data" root_block_device { volume_type = "gp2" @@ -128,8 +133,9 @@ resource "aws_launch_configuration" "test" { ebs_block_device { device_name = "/dev/sdc" volume_size = 10 - volume_type = "io1" - iops = 100 + volume_type = "gp3" + iops = 3000 + throughput = 125 } ephemeral_block_device { @@ -144,38 +150,45 @@ data "aws_launch_configuration" "test" { `, rName)) } -func testAccLaunchConfigurationDataSourceConfig_securityGroups(rInt int) string { - return acctest.ConfigLatestAmazonLinuxHvmEbsAmi() + fmt.Sprintf(` +func testAccLaunchConfigurationDataSourceConfig_securityGroups(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test" { - name = "terraform-test_%d" + name = %[1]q vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_launch_configuration" "test" { - name = "terraform-test-%d" + name = %[1]q image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "m1.small" security_groups = [aws_security_group.test.id] } -data "aws_launch_configuration" "foo" { +data "aws_launch_configuration" "test" { name = aws_launch_configuration.test.name } -`, rInt, rInt) +`, rName)) } -func testAccLaunchConfigurationDataSourceConfig_metadataOptions(rName string) string { - return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - fmt.Sprintf(` +func testAccLaunchConfigurationDataSourceConfig_metaOptions(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t3.nano" name = %[1]q + metadata_options { http_endpoint = "enabled" http_tokens = "required" @@ -189,10 +202,8 @@ data "aws_launch_configuration" "test" { `, rName)) } -func testAccLaunchConfigurationDataSourceConfigEbsNoDevice(rName string) string { - return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - fmt.Sprintf(` +func testAccLaunchConfigurationDataSourceConfig_ebsNoDevice(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id diff --git a/internal/service/autoscaling/launch_configuration_test.go b/internal/service/autoscaling/launch_configuration_test.go index 03a0b6376da..e6e85391e03 100644 --- a/internal/service/autoscaling/launch_configuration_test.go +++ b/internal/service/autoscaling/launch_configuration_test.go @@ -3,9 +3,9 @@ package autoscaling_test import ( "fmt" "regexp" - "strings" "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/ec2" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -31,17 +31,36 @@ func TestAccAutoScalingLaunchConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationConfig(rName), - Check: resource.ComposeTestCheckFunc( + Config: testAccLaunchConfigurationConfig_basic(rName), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "autoscaling", regexp.MustCompile(`launchConfiguration:.+`)), + resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), + resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "0"), + resource.TestCheckResourceAttr(resourceName, "ebs_optimized", "false"), + resource.TestCheckResourceAttr(resourceName, "enable_monitoring", "true"), + resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.#", "0"), + resource.TestCheckResourceAttr(resourceName, "iam_instance_profile", ""), + resource.TestCheckResourceAttrSet(resourceName, "image_id"), + resource.TestCheckResourceAttr(resourceName, "instance_type", "t2.micro"), + resource.TestCheckResourceAttr(resourceName, "key_name", ""), + resource.TestCheckResourceAttr(resourceName, "metadata_options.#", "0"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name_prefix", ""), + resource.TestCheckResourceAttr(resourceName, "placement_tenancy", ""), + resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "0"), + resource.TestCheckResourceAttr(resourceName, "security_groups.#", "0"), + resource.TestCheckResourceAttr(resourceName, "spot_price", ""), + resource.TestCheckNoResourceAttr(resourceName, "user_data"), + resource.TestCheckNoResourceAttr(resourceName, "user_data_base64"), + resource.TestCheckResourceAttr(resourceName, "vpc_classic_link_id", ""), + resource.TestCheckResourceAttr(resourceName, "vpc_classic_link_security_groups.#", "0"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -59,7 +78,7 @@ func TestAccAutoScalingLaunchConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationConfig(rName), + Config: testAccLaunchConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfautoscaling.ResourceLaunchConfiguration(), resourceName), @@ -81,7 +100,7 @@ func TestAccAutoScalingLaunchConfiguration_Name_generated(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationNameGeneratedConfig(), + Config: testAccLaunchConfigurationConfig_nameGenerated(), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -89,10 +108,9 @@ func TestAccAutoScalingLaunchConfiguration_Name_generated(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -109,7 +127,7 @@ func TestAccAutoScalingLaunchConfiguration_namePrefix(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationNamePrefixConfig("tf-acc-test-prefix-"), + Config: testAccLaunchConfigurationConfig_namePrefix("tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), @@ -117,10 +135,9 @@ func TestAccAutoScalingLaunchConfiguration_namePrefix(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -138,21 +155,36 @@ func TestAccAutoScalingLaunchConfiguration_withBlockDevices(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationConfig(rName), + Config: testAccLaunchConfigurationConfig_blockDevices(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), - testAccCheckLaunchConfigurationAttributes(&conf), - resource.TestMatchResourceAttr(resourceName, "image_id", regexp.MustCompile("^ami-[0-9a-z]+")), - resource.TestCheckResourceAttr(resourceName, "instance_type", "m1.small"), - resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), - resource.TestCheckResourceAttr(resourceName, "spot_price", ""), + resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "2"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "device_name": "/dev/sdb", + "volume_size": "9", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "device_name": "/dev/sdc", + "iops": "100", + "volume_size": "10", + "volume_type": "io1", + }), + resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ephemeral_block_device.*", map[string]string{ + "device_name": "/dev/sde", + "virtual_name": "ephemeral0", + }), + resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "root_block_device.*", map[string]string{ + "volume_size": "11", + "volume_type": "gp2", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -170,16 +202,15 @@ func TestAccAutoScalingLaunchConfiguration_withInstanceStoreAMI(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationWithInstanceStoreAMIConfig(rName), + Config: testAccLaunchConfigurationConfig_instanceStoreAMI(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -199,7 +230,7 @@ func TestAccAutoScalingLaunchConfiguration_RootBlockDevice_amiDisappears(t *test CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationWithRootBlockDeviceCopiedAMIConfig(rName), + Config: testAccLaunchConfigurationConfig_cofingRootBlockDeviceCopiedAMI(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), testAccCheckAMIExists(amiCopyResourceName, &ami), @@ -208,7 +239,7 @@ func TestAccAutoScalingLaunchConfiguration_RootBlockDevice_amiDisappears(t *test ExpectNonEmptyPlan: true, }, { - Config: testAccLaunchConfigurationWithRootBlockDeviceVolumeSizeConfig(rName, 10), + Config: testAccLaunchConfigurationConfig_rootBlockDeviceVolumeSize(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), ), @@ -229,22 +260,23 @@ func TestAccAutoScalingLaunchConfiguration_RootBlockDevice_volumeSize(t *testing CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationWithRootBlockDeviceVolumeSizeConfig(rName, 11), + Config: testAccLaunchConfigurationConfig_rootBlockDeviceVolumeSize(rName, 11), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", "11"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, { - Config: testAccLaunchConfigurationWithRootBlockDeviceVolumeSizeConfig(rName, 20), + Config: testAccLaunchConfigurationConfig_rootBlockDeviceVolumeSize(rName, 20), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", "20"), ), }, @@ -264,17 +296,21 @@ func TestAccAutoScalingLaunchConfiguration_encryptedRootBlockDevice(t *testing.T CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationWithEncryptedRootBlockDeviceConfig(rName), + Config: testAccLaunchConfigurationConfig_encryptedRootBlockDevice(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), - resource.TestCheckResourceAttr(resourceName, "root_block_device.0.encrypted", "true"), + resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "root_block_device.*", map[string]string{ + "encrypted": "true", + "volume_size": "11", + "volume_type": "gp2", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -292,17 +328,16 @@ func TestAccAutoScalingLaunchConfiguration_withSpotPrice(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationWithSpotPriceConfig(rName), + Config: testAccLaunchConfigurationConfig_spotPrice(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "spot_price", "0.05"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -314,6 +349,8 @@ func TestAccAutoScalingLaunchConfiguration_withVPCClassicLink(t *testing.T) { var conf autoscaling.LaunchConfiguration rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_launch_configuration.test" + vpcResourceName := "aws_vpc.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, @@ -322,11 +359,14 @@ func TestAccAutoScalingLaunchConfiguration_withVPCClassicLink(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationConfig_withVPCClassicLink(rName), + Config: testAccLaunchConfigurationConfig_vpcClassicLink(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), - acctest.CheckVPCExists("aws_vpc.test", &vpc), - testAccCheckSecurityGroupExists("aws_security_group.test", &group), + acctest.CheckVPCExists(vpcResourceName, &vpc), + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttrPair(resourceName, "vpc_classic_link_id", vpcResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "vpc_classic_link_security_groups.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "vpc_classic_link_security_groups.*", sgResourceName, "id"), ), }, { @@ -350,44 +390,16 @@ func TestAccAutoScalingLaunchConfiguration_withIAMProfile(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationConfig_withIAMProfile(rName), + Config: testAccLaunchConfigurationConfig_iamProfile(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), + resource.TestCheckResourceAttrSet(resourceName, "iam_instance_profile"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, - }, - }, - }) -} - -func TestAccAutoScalingLaunchConfiguration_withEncryption(t *testing.T) { - var conf autoscaling.LaunchConfiguration - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - resourceName := "aws_launch_configuration.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), - ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckLaunchConfigurationDestroy, - Steps: []resource.TestStep{ - { - Config: testAccLaunchConfigurationWithEncryption(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckLaunchConfigurationExists("aws_launch_configuration.test", &conf), - testAccCheckLaunchConfigurationWithEncryption(&conf), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -405,28 +417,34 @@ func TestAccAutoScalingLaunchConfiguration_withGP3(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationWithGP3(rName), + Config: testAccLaunchConfigurationConfig_gp3(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckLaunchConfigurationExists("aws_launch_configuration.test", &conf), + testAccCheckLaunchConfigurationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "device_name": "/dev/sdb", + "encrypted": "true", + "throughput": "150", + "volume_size": "9", "volume_type": "gp3", }), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ - "throughput": "150", + resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "root_block_device.*", map[string]string{ + "volume_size": "11", + "volume_type": "gp3", }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) } -func TestAccAutoScalingLaunchConfiguration_updateEBSBlockDevices(t *testing.T) { +func TestAccAutoScalingLaunchConfiguration_encryptedEBSBlockDevice(t *testing.T) { var conf autoscaling.LaunchConfiguration rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_launch_configuration.test" @@ -438,27 +456,42 @@ func TestAccAutoScalingLaunchConfiguration_updateEBSBlockDevices(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationWithEncryption(rName), + Config: testAccLaunchConfigurationConfig_encryptedEBSBlockDevice(rName, 9), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "device_name": "/dev/sdb", + "encrypted": "true", "volume_size": "9", }), + resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "root_block_device.*", map[string]string{ + "volume_size": "11", + "volume_type": "gp2", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, { - Config: testAccLaunchConfigurationWithEncryptionUpdated(rName), + Config: testAccLaunchConfigurationConfig_encryptedEBSBlockDevice(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "device_name": "/dev/sdb", + "encrypted": "true", "volume_size": "10", }), + resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "root_block_device.*", map[string]string{ + "volume_size": "11", + "volume_type": "gp2", + }), ), }, }, @@ -477,13 +510,13 @@ func TestAccAutoScalingLaunchConfiguration_metadataOptions(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationMetadataOptionsConfig(rName), + Config: testAccLaunchConfigurationConfig_metadataOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "metadata_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "metadata_options.0.http_endpoint", "enabled"), - resource.TestCheckResourceAttr(resourceName, "metadata_options.0.http_tokens", "required"), resource.TestCheckResourceAttr(resourceName, "metadata_options.0.http_put_response_hop_limit", "2"), + resource.TestCheckResourceAttr(resourceName, "metadata_options.0.http_tokens", "required"), ), }, { @@ -507,7 +540,7 @@ func TestAccAutoScalingLaunchConfiguration_EBS_noDevice(t *testing.T) { CheckDestroy: testAccCheckLaunchConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchConfigurationEBSNoDeviceConfig(rName), + Config: testAccLaunchConfigurationConfig_ebsNoDevice(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchConfigurationExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "1"), @@ -518,10 +551,9 @@ func TestAccAutoScalingLaunchConfiguration_EBS_noDevice(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -546,10 +578,9 @@ func TestAccAutoScalingLaunchConfiguration_userData(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"associate_public_ip_address"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, { Config: testAccLaunchConfigurationConfig_userDataBase64(rName), @@ -562,30 +593,190 @@ func TestAccAutoScalingLaunchConfiguration_userData(t *testing.T) { }) } -func testAccCheckLaunchConfigurationWithEncryption(conf *autoscaling.LaunchConfiguration) resource.TestCheckFunc { - return func(s *terraform.State) error { - // Map out the block devices by name, which should be unique. - blockDevices := make(map[string]*autoscaling.BlockDeviceMapping) - for _, blockDevice := range conf.BlockDeviceMappings { - blockDevices[*blockDevice.DeviceName] = blockDevice - } +func TestAccAutoScalingLaunchConfiguration_AssociatePublicIPAddress_subnetFalseConfigNull(t *testing.T) { + var conf autoscaling.LaunchConfiguration + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_launch_configuration.test" + groupResourceName := "aws_autoscaling_group.test" - // Check if the root block device exists. - if _, ok := blockDevices["/dev/xvda"]; !ok { - return fmt.Errorf("block device doesn't exist: /dev/xvda") - } else if blockDevices["/dev/xvda"].Ebs.Encrypted != nil { - return fmt.Errorf("root device should not include value for Encrypted") - } + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLaunchConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLaunchConfigurationConfig_associatePublicIPAddress(rName, false, ""), + Check: resource.ComposeTestCheckFunc( + testAccCheckLaunchConfigurationExists(resourceName, &conf), + testAccCheckGroupExists(groupResourceName, &group), + testAccCheckGroupHealthyInstanceCount(&group, 1), + testAccCheckInstanceHasPublicIPAddress(&group, 0, false), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} - // Check if the secondary block device exists. - if _, ok := blockDevices["/dev/sdb"]; !ok { - return fmt.Errorf("block device doesn't exist: /dev/sdb") - } else if !*blockDevices["/dev/sdb"].Ebs.Encrypted { - return fmt.Errorf("block device isn't encrypted as expected: /dev/sdb") - } +func TestAccAutoScalingLaunchConfiguration_AssociatePublicIPAddress_subnetFalseConfigFalse(t *testing.T) { + var conf autoscaling.LaunchConfiguration + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_launch_configuration.test" + groupResourceName := "aws_autoscaling_group.test" - return nil - } + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLaunchConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLaunchConfigurationConfig_associatePublicIPAddress(rName, false, "false"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLaunchConfigurationExists(resourceName, &conf), + testAccCheckGroupExists(groupResourceName, &group), + testAccCheckGroupHealthyInstanceCount(&group, 1), + testAccCheckInstanceHasPublicIPAddress(&group, 0, false), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAutoScalingLaunchConfiguration_AssociatePublicIPAddress_subnetFalseConfigTrue(t *testing.T) { + var conf autoscaling.LaunchConfiguration + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_launch_configuration.test" + groupResourceName := "aws_autoscaling_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLaunchConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLaunchConfigurationConfig_associatePublicIPAddress(rName, false, "true"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLaunchConfigurationExists(resourceName, &conf), + testAccCheckGroupExists(groupResourceName, &group), + testAccCheckGroupHealthyInstanceCount(&group, 1), + testAccCheckInstanceHasPublicIPAddress(&group, 0, true), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAutoScalingLaunchConfiguration_AssociatePublicIPAddress_subnetTrueConfigNull(t *testing.T) { + var conf autoscaling.LaunchConfiguration + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_launch_configuration.test" + groupResourceName := "aws_autoscaling_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLaunchConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLaunchConfigurationConfig_associatePublicIPAddress(rName, true, ""), + Check: resource.ComposeTestCheckFunc( + testAccCheckLaunchConfigurationExists(resourceName, &conf), + testAccCheckGroupExists(groupResourceName, &group), + testAccCheckGroupHealthyInstanceCount(&group, 1), + testAccCheckInstanceHasPublicIPAddress(&group, 0, true), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAutoScalingLaunchConfiguration_AssociatePublicIPAddress_subnetTrueConfigFalse(t *testing.T) { + var conf autoscaling.LaunchConfiguration + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_launch_configuration.test" + groupResourceName := "aws_autoscaling_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLaunchConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLaunchConfigurationConfig_associatePublicIPAddress(rName, true, "false"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLaunchConfigurationExists(resourceName, &conf), + testAccCheckGroupExists(groupResourceName, &group), + testAccCheckGroupHealthyInstanceCount(&group, 1), + testAccCheckInstanceHasPublicIPAddress(&group, 0, false), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAutoScalingLaunchConfiguration_AssociatePublicIPAddress_subnetTrueConfigTrue(t *testing.T) { + var conf autoscaling.LaunchConfiguration + var group autoscaling.Group + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_launch_configuration.test" + groupResourceName := "aws_autoscaling_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, autoscaling.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLaunchConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLaunchConfigurationConfig_associatePublicIPAddress(rName, true, "true"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLaunchConfigurationExists(resourceName, &conf), + testAccCheckGroupExists(groupResourceName, &group), + testAccCheckGroupHealthyInstanceCount(&group, 1), + testAccCheckInstanceHasPublicIPAddress(&group, 0, true), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) } func testAccCheckLaunchConfigurationDestroy(s *terraform.State) error { @@ -606,52 +797,12 @@ func testAccCheckLaunchConfigurationDestroy(s *terraform.State) error { return err } - return fmt.Errorf("Autoscaling Launch Configuration %s still exists", rs.Primary.ID) + return fmt.Errorf("Auto Scaling Launch Configuration %s still exists", rs.Primary.ID) } return nil } -func testAccCheckLaunchConfigurationAttributes(conf *autoscaling.LaunchConfiguration) resource.TestCheckFunc { - return func(s *terraform.State) error { - if !strings.HasPrefix(*conf.LaunchConfigurationName, "terraform-") && !strings.HasPrefix(*conf.LaunchConfigurationName, "tf-acc-test-") { - return fmt.Errorf("Bad name: %s", *conf.LaunchConfigurationName) - } - - if *conf.InstanceType != "m1.small" { - return fmt.Errorf("Bad instance_type: %s", *conf.InstanceType) - } - - // Map out the block devices by name, which should be unique. - blockDevices := make(map[string]*autoscaling.BlockDeviceMapping) - for _, blockDevice := range conf.BlockDeviceMappings { - blockDevices[*blockDevice.DeviceName] = blockDevice - } - - // Check if the root block device exists. - if _, ok := blockDevices["/dev/xvda"]; !ok { - return fmt.Errorf("block device doesn't exist: /dev/xvda") - } - - // Check if the secondary block device exists. - if _, ok := blockDevices["/dev/sdb"]; !ok { - return fmt.Errorf("block device doesn't exist: /dev/sdb") - } - - // Check if the third block device exists. - if _, ok := blockDevices["/dev/sdc"]; !ok { - return fmt.Errorf("block device doesn't exist: /dev/sdc") - } - - // Check if the fourth block device exists. - if _, ok := blockDevices["/dev/sde"]; !ok { - return fmt.Errorf("block device doesn't exist: /dev/sde") - } - - return nil - } -} - func testAccCheckLaunchConfigurationExists(n string, v *autoscaling.LaunchConfiguration) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -660,7 +811,7 @@ func testAccCheckLaunchConfigurationExists(n string, v *autoscaling.LaunchConfig } if rs.Primary.ID == "" { - return fmt.Errorf("No Autoscaling Launch Configuration ID is set") + return fmt.Errorf("No Auto Scaling Launch Configuration ID is set") } conn := acctest.Provider.Meta().(*conns.AWSClient).AutoScalingConn @@ -702,17 +853,38 @@ func testAccCheckAMIExists(n string, v *ec2.Image) resource.TestCheckFunc { } } -func testAccCheckSecurityGroupExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { +func testAccCheckInstanceHasPublicIPAddress(group *autoscaling.Group, idx int, expected bool) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No EC2 Security Group ID is set") - } - + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn + + instanceID := aws.StringValue(group.Instances[idx].InstanceId) + instance, err := tfec2.FindInstanceByID(conn, instanceID) + + if err != nil { + return err + } + + hasPublicIPAddress := aws.StringValue(instance.PublicIpAddress) != "" + + if hasPublicIPAddress != expected { + return fmt.Errorf("%s has public IP address; got %t, expected %t", instanceID, hasPublicIPAddress, expected) + } + + return nil + } +} + +func testAccCheckSecurityGroupExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No EC2 Security Group ID is set") + } + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn output, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) @@ -727,7 +899,68 @@ func testAccCheckSecurityGroupExists(n string, v *ec2.SecurityGroup) resource.Te } } -// configLatestAmazonLinuxPVInstanceStoreAmi returns the configuration for a data source that +func testAccLaunchConfigurationConfig_basic(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" +} +`, rName)) +} + +func testAccLaunchConfigurationConfig_nameGenerated() string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), ` +resource "aws_launch_configuration" "test" { + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" +} +`) +} + +func testAccLaunchConfigurationConfig_namePrefix(namePrefix string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` +resource "aws_launch_configuration" "test" { + name_prefix = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" +} +`, namePrefix)) +} + +func testAccLaunchConfigurationConfig_blockDevices(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "m1.small" + + root_block_device { + volume_type = "gp2" + volume_size = 11 + } + + ebs_block_device { + device_name = "/dev/sdb" + volume_size = 9 + } + + ebs_block_device { + device_name = "/dev/sdc" + volume_size = 10 + volume_type = "io1" + iops = 100 + } + + ephemeral_block_device { + device_name = "/dev/sde" + virtual_name = "ephemeral0" + } +} +`, rName)) +} + +// testAccLatestAmazonLinuxPVInstanceStoreAMIConfig returns the configuration for a data source that // describes the latest Amazon Linux AMI using PV virtualization and an instance store root device. // The data source is named 'amzn-ami-minimal-pv-ebs'. func testAccLatestAmazonLinuxPVInstanceStoreAMIConfig() string { @@ -749,7 +982,7 @@ data "aws_ami" "amzn-ami-minimal-pv-instance-store" { ` } -func testAccLaunchConfigurationWithInstanceStoreAMIConfig(rName string) string { +func testAccLaunchConfigurationConfig_instanceStoreAMI(rName string) string { return acctest.ConfigCompose(testAccLatestAmazonLinuxPVInstanceStoreAMIConfig(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q @@ -761,8 +994,8 @@ resource "aws_launch_configuration" "test" { `, rName)) } -func testAccLaunchConfigurationWithRootBlockDeviceCopiedAMIConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccLaunchConfigurationConfig_cofingRootBlockDeviceCopiedAMI(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` data "aws_region" "current" {} resource "aws_ami_copy" "test" { @@ -783,8 +1016,8 @@ resource "aws_launch_configuration" "test" { `, rName)) } -func testAccLaunchConfigurationWithRootBlockDeviceVolumeSizeConfig(rName string, volumeSize int) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccLaunchConfigurationConfig_rootBlockDeviceVolumeSize(rName string, volumeSize int) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -797,99 +1030,24 @@ resource "aws_launch_configuration" "test" { `, rName, volumeSize)) } -func testAccLaunchConfigurationWithEncryptedRootBlockDeviceConfig(rName string) string { - return acctest.ConfigCompose( - acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = %[1]q - } -} - -resource "aws_subnet" "test" { - cidr_block = "10.1.1.0/24" - vpc_id = aws_vpc.test.id - availability_zone = data.aws_availability_zones.available.names[0] - - tags = { - Name = %[1]q - } -} - -resource "aws_launch_configuration" "test" { - name_prefix = %[1]q - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t3.nano" - user_data = "testtest-user-data" - associate_public_ip_address = true - - root_block_device { - encrypted = true - volume_type = "gp2" - volume_size = 11 - } -} -`, rName)) -} - -func testAccLaunchConfigurationMetadataOptionsConfig(rName string) string { - return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - fmt.Sprintf(` +func testAccLaunchConfigurationConfig_encryptedRootBlockDevice(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { + name = %[1]q image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t3.nano" - name = %[1]q - - metadata_options { - http_endpoint = "enabled" - http_tokens = "required" - http_put_response_hop_limit = 2 - } -} -`, rName)) -} - -func testAccLaunchConfigurationConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` -resource "aws_launch_configuration" "test" { - name = %[1]q - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "m1.small" - user_data = "testtest-user-data" - associate_public_ip_address = true root_block_device { + encrypted = true volume_type = "gp2" volume_size = 11 } - - ebs_block_device { - device_name = "/dev/sdb" - volume_size = 9 - } - - ebs_block_device { - device_name = "/dev/sdc" - volume_size = 10 - volume_type = "io1" - iops = 100 - } - - ephemeral_block_device { - device_name = "/dev/sde" - virtual_name = "ephemeral0" - } } `, rName)) } -func testAccLaunchConfigurationWithSpotPriceConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccLaunchConfigurationConfig_spotPrice(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -899,95 +1057,8 @@ resource "aws_launch_configuration" "test" { `, rName)) } -func testAccLaunchConfigurationNameGeneratedConfig() string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), ` -resource "aws_launch_configuration" "test" { - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" -} -`) -} - -func testAccLaunchConfigurationNamePrefixConfig(namePrefix string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` -resource "aws_launch_configuration" "test" { - name_prefix = %[1]q - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" -} -`, namePrefix)) -} - -func testAccLaunchConfigurationWithEncryption(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` -resource "aws_launch_configuration" "test" { - name = %[1]q - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" - associate_public_ip_address = false - - root_block_device { - volume_type = "gp2" - volume_size = 11 - } - - ebs_block_device { - device_name = "/dev/sdb" - volume_size = 9 - encrypted = true - } -} -`, rName)) -} - -func testAccLaunchConfigurationWithGP3(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` -resource "aws_launch_configuration" "test" { - name = %[1]q - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" - associate_public_ip_address = false - - root_block_device { - volume_type = "gp3" - volume_size = 11 - } - - ebs_block_device { - volume_type = "gp3" - device_name = "/dev/sdb" - volume_size = 9 - encrypted = true - throughput = 150 - } -} -`, rName)) -} - -func testAccLaunchConfigurationWithEncryptionUpdated(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` -resource "aws_launch_configuration" "test" { - name = %[1]q - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" - associate_public_ip_address = false - - root_block_device { - volume_type = "gp2" - volume_size = 11 - } - - ebs_block_device { - device_name = "/dev/sdb" - volume_size = 10 - encrypted = true - } -} -`, rName)) -} - -func testAccLaunchConfigurationConfig_withVPCClassicLink(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccLaunchConfigurationConfig_vpcClassicLink(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" enable_classiclink = true @@ -1017,8 +1088,8 @@ resource "aws_launch_configuration" "test" { `, rName)) } -func testAccLaunchConfigurationConfig_withIAMProfile(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccLaunchConfigurationConfig_iamProfile(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -1053,10 +1124,70 @@ resource "aws_launch_configuration" "test" { `, rName)) } -func testAccLaunchConfigurationEBSNoDeviceConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccLaunchConfigurationConfig_gp3(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { - name_prefix = %[1]q + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + + root_block_device { + volume_type = "gp3" + volume_size = 11 + } + + ebs_block_device { + volume_type = "gp3" + device_name = "/dev/sdb" + volume_size = 9 + encrypted = true + throughput = 150 + } +} +`, rName)) +} + +func testAccLaunchConfigurationConfig_encryptedEBSBlockDevice(rName string, size int) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + + root_block_device { + volume_type = "gp2" + volume_size = 11 + } + + ebs_block_device { + device_name = "/dev/sdb" + volume_size = %[2]d + encrypted = true + } +} +`, rName, size)) +} + +func testAccLaunchConfigurationConfig_metadataOptions(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` +resource "aws_launch_configuration" "test" { + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t3.nano" + name = %[1]q + + metadata_options { + http_endpoint = "enabled" + http_tokens = "required" + http_put_response_hop_limit = 2 + } +} +`, rName)) +} + +func testAccLaunchConfigurationConfig_ebsNoDevice(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` +resource "aws_launch_configuration" "test" { + name = %[1]q image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "m1.small" @@ -1069,25 +1200,76 @@ resource "aws_launch_configuration" "test" { } func testAccLaunchConfigurationConfig_userData(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { - name_prefix = %[1]q - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" - user_data = "foo:-with-character's" - associate_public_ip_address = false + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + user_data = "foo:-with-character's" } `, rName)) } func testAccLaunchConfigurationConfig_userDataBase64(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { - name_prefix = %[1]q - image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.micro" - user_data_base64 = base64encode("hello world") - associate_public_ip_address = false + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + user_data_base64 = base64encode("hello world") } `, rName)) } + +func testAccLaunchConfigurationConfig_associatePublicIPAddress(rName string, subnetMapPublicIPOnLaunch bool, associatePublicIPAddress string) string { + if associatePublicIPAddress == "" { + associatePublicIPAddress = "null" + } + + return acctest.ConfigCompose( + acctest.ConfigAvailableAZsNoOptInDefaultExclude(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[1]", "t3.micro", "t2.micro"), + fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_subnet" "test" { + cidr_block = "10.1.1.0/24" + vpc_id = aws_vpc.test.id + availability_zone = data.aws_availability_zones.available.names[1] + map_public_ip_on_launch = %[2]t + + tags = { + Name = %[1]q + } +} + +resource "aws_launch_configuration" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = data.aws_ec2_instance_type_offering.available.instance_type + associate_public_ip_address = %[3]s +} + +resource "aws_autoscaling_group" "test" { + vpc_zone_identifier = [aws_subnet.test.id] + max_size = 1 + min_size = 1 + desired_capacity = 1 + name = %[1]q + launch_configuration = aws_launch_configuration.test.name + + tag { + key = "Name" + value = %[1]q + propagate_at_launch = true + } +} +`, rName, subnetMapPublicIPOnLaunch, associatePublicIPAddress)) +} diff --git a/internal/service/autoscaling/lifecycle_hook_test.go b/internal/service/autoscaling/lifecycle_hook_test.go index f4208db0ed8..5805d95a639 100644 --- a/internal/service/autoscaling/lifecycle_hook_test.go +++ b/internal/service/autoscaling/lifecycle_hook_test.go @@ -25,7 +25,7 @@ func TestAccAutoScalingLifecycleHook_basic(t *testing.T) { CheckDestroy: testAccCheckLifecycleHookDestroy, Steps: []resource.TestStep{ { - Config: testAccLifecycleHookConfig(rName), + Config: testAccLifecycleHookConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecycleHookExists(resourceName), resource.TestCheckResourceAttr(resourceName, "autoscaling_group_name", rName), @@ -55,7 +55,7 @@ func TestAccAutoScalingLifecycleHook_disappears(t *testing.T) { CheckDestroy: testAccCheckLifecycleHookDestroy, Steps: []resource.TestStep{ { - Config: testAccLifecycleHookConfig(rName), + Config: testAccLifecycleHookConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecycleHookExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfautoscaling.ResourceLifecycleHook(), resourceName), @@ -145,10 +145,10 @@ func testAccLifecycleHookImportStateIdFunc(resourceName string) resource.ImportS } } -func testAccLifecycleHookConfig(rName string) string { +func testAccLifecycleHookConfig_basic(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q @@ -229,7 +229,7 @@ EOF func testAccLifecycleHookConfig_omitDefaultResult(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q diff --git a/internal/service/autoscaling/list_pages_gen.go b/internal/service/autoscaling/list_pages_gen.go new file mode 100644 index 00000000000..4942eb9b565 --- /dev/null +++ b/internal/service/autoscaling/list_pages_gen.go @@ -0,0 +1,94 @@ +// Code generated by "internal/generate/listpages/main.go -ListOps=DescribeInstanceRefreshes,DescribeLoadBalancers,DescribeLoadBalancerTargetGroups,DescribeWarmPool"; DO NOT EDIT. + +package autoscaling + +import ( + "context" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/autoscaling" +) + +func describeInstanceRefreshesPages(conn *autoscaling.AutoScaling, input *autoscaling.DescribeInstanceRefreshesInput, fn func(*autoscaling.DescribeInstanceRefreshesOutput, bool) bool) error { + return describeInstanceRefreshesPagesWithContext(context.Background(), conn, input, fn) +} + +func describeInstanceRefreshesPagesWithContext(ctx context.Context, conn *autoscaling.AutoScaling, input *autoscaling.DescribeInstanceRefreshesInput, fn func(*autoscaling.DescribeInstanceRefreshesOutput, bool) bool) error { + for { + output, err := conn.DescribeInstanceRefreshesWithContext(ctx, input) + if err != nil { + return err + } + + lastPage := aws.StringValue(output.NextToken) == "" + if !fn(output, lastPage) || lastPage { + break + } + + input.NextToken = output.NextToken + } + return nil +} + +func describeLoadBalancerTargetGroupsPages(conn *autoscaling.AutoScaling, input *autoscaling.DescribeLoadBalancerTargetGroupsInput, fn func(*autoscaling.DescribeLoadBalancerTargetGroupsOutput, bool) bool) error { + return describeLoadBalancerTargetGroupsPagesWithContext(context.Background(), conn, input, fn) +} + +func describeLoadBalancerTargetGroupsPagesWithContext(ctx context.Context, conn *autoscaling.AutoScaling, input *autoscaling.DescribeLoadBalancerTargetGroupsInput, fn func(*autoscaling.DescribeLoadBalancerTargetGroupsOutput, bool) bool) error { + for { + output, err := conn.DescribeLoadBalancerTargetGroupsWithContext(ctx, input) + if err != nil { + return err + } + + lastPage := aws.StringValue(output.NextToken) == "" + if !fn(output, lastPage) || lastPage { + break + } + + input.NextToken = output.NextToken + } + return nil +} + +func describeLoadBalancersPages(conn *autoscaling.AutoScaling, input *autoscaling.DescribeLoadBalancersInput, fn func(*autoscaling.DescribeLoadBalancersOutput, bool) bool) error { + return describeLoadBalancersPagesWithContext(context.Background(), conn, input, fn) +} + +func describeLoadBalancersPagesWithContext(ctx context.Context, conn *autoscaling.AutoScaling, input *autoscaling.DescribeLoadBalancersInput, fn func(*autoscaling.DescribeLoadBalancersOutput, bool) bool) error { + for { + output, err := conn.DescribeLoadBalancersWithContext(ctx, input) + if err != nil { + return err + } + + lastPage := aws.StringValue(output.NextToken) == "" + if !fn(output, lastPage) || lastPage { + break + } + + input.NextToken = output.NextToken + } + return nil +} + +func describeWarmPoolPages(conn *autoscaling.AutoScaling, input *autoscaling.DescribeWarmPoolInput, fn func(*autoscaling.DescribeWarmPoolOutput, bool) bool) error { + return describeWarmPoolPagesWithContext(context.Background(), conn, input, fn) +} + +func describeWarmPoolPagesWithContext(ctx context.Context, conn *autoscaling.AutoScaling, input *autoscaling.DescribeWarmPoolInput, fn func(*autoscaling.DescribeWarmPoolOutput, bool) bool) error { + for { + output, err := conn.DescribeWarmPoolWithContext(ctx, input) + if err != nil { + return err + } + + lastPage := aws.StringValue(output.NextToken) == "" + if !fn(output, lastPage) || lastPage { + break + } + + input.NextToken = output.NextToken + } + return nil +} diff --git a/internal/service/autoscaling/notification_test.go b/internal/service/autoscaling/notification_test.go index 440547fe36e..03c192481a4 100644 --- a/internal/service/autoscaling/notification_test.go +++ b/internal/service/autoscaling/notification_test.go @@ -26,7 +26,7 @@ func TestAccAutoScalingNotification_ASG_basic(t *testing.T) { CheckDestroy: testAccCheckASGNDestroy, Steps: []resource.TestStep{ { - Config: testAccASGNotificationConfig_basic(rName), + Config: testAccNotificationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckASGNotificationExists("aws_autoscaling_notification.example", []string{"foobar1-terraform-test-" + rName}, &asgn), testAccCheckASGNotificationAttributes("aws_autoscaling_notification.example", &asgn), @@ -48,7 +48,7 @@ func TestAccAutoScalingNotification_ASG_update(t *testing.T) { CheckDestroy: testAccCheckASGNDestroy, Steps: []resource.TestStep{ { - Config: testAccASGNotificationConfig_basic(rName), + Config: testAccNotificationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckASGNotificationExists("aws_autoscaling_notification.example", []string{"foobar1-terraform-test-" + rName}, &asgn), testAccCheckASGNotificationAttributes("aws_autoscaling_notification.example", &asgn), @@ -56,7 +56,7 @@ func TestAccAutoScalingNotification_ASG_update(t *testing.T) { }, { - Config: testAccASGNotificationConfig_update(rName), + Config: testAccNotificationConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckASGNotificationExists("aws_autoscaling_notification.example", []string{"foobar1-terraform-test-" + rName, "barfoo-terraform-test-" + rName}, &asgn), testAccCheckASGNotificationAttributes("aws_autoscaling_notification.example", &asgn), @@ -78,7 +78,7 @@ func TestAccAutoScalingNotification_ASG_pagination(t *testing.T) { CheckDestroy: testAccCheckASGNDestroy, Steps: []resource.TestStep{ { - Config: testAccASGNotificationConfig_pagination(), + Config: testAccNotificationConfig_pagination(), Check: resource.ComposeTestCheckFunc( testAccCheckASGNotificationExists(resourceName, []string{ @@ -217,8 +217,8 @@ func testAccCheckASGNotificationAttributes(n string, asgn *autoscaling.DescribeN } } -func testAccASGNotificationConfig_basic(rName string) string { - return acctest.ConfigLatestAmazonLinuxHvmEbsAmi() + fmt.Sprintf(` +func testAccNotificationConfig_basic(rName string) string { + return acctest.ConfigLatestAmazonLinuxHVMEBSAMI() + fmt.Sprintf(` resource "aws_sns_topic" "topic_example" { name = "user-updates-topic-%s" } @@ -264,8 +264,8 @@ resource "aws_autoscaling_notification" "example" { `, rName, rName, rName) } -func testAccASGNotificationConfig_update(rName string) string { - return acctest.ConfigLatestAmazonLinuxHvmEbsAmi() + fmt.Sprintf(` +func testAccNotificationConfig_update(rName string) string { + return acctest.ConfigLatestAmazonLinuxHVMEBSAMI() + fmt.Sprintf(` resource "aws_sns_topic" "topic_example" { name = "user-updates-topic-%s" } @@ -328,8 +328,8 @@ resource "aws_autoscaling_notification" "example" { `, rName, rName, rName, rName) } -func testAccASGNotificationConfig_pagination() string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), ` +func testAccNotificationConfig_pagination() string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), ` resource "aws_sns_topic" "user_updates" { name = "user-updates-topic" } diff --git a/internal/service/autoscaling/policy_test.go b/internal/service/autoscaling/policy_test.go index eb4a7c082f5..c34cd1ae09a 100644 --- a/internal/service/autoscaling/policy_test.go +++ b/internal/service/autoscaling/policy_test.go @@ -28,7 +28,7 @@ func TestAccAutoScalingPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigBasic(rName), + Config: testAccPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceSimpleName, &v), resource.TestCheckResourceAttr(resourceSimpleName, "adjustment_type", "ChangeInCapacity"), @@ -123,7 +123,7 @@ func TestAccAutoScalingPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigBasic(rName), + Config: testAccPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfautoscaling.ResourcePolicy(), resourceName), @@ -146,7 +146,7 @@ func TestAccAutoScalingPolicy_predictiveScalingPredefined(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigPredictiveScalingPredefined(rName), + Config: testAccPolicyConfig_predictiveScalingPredefined(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceSimpleName, &v), resource.TestCheckResourceAttr(resourceSimpleName, "predictive_scaling_configuration.0.mode", "ForecastAndScale"), @@ -182,7 +182,7 @@ func TestAccAutoScalingPolicy_predictiveScalingCustom(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigPredictiveScalingCustom(rName), + Config: testAccPolicyConfig_predictiveScalingCustom(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "predictive_scaling_configuration.0.max_capacity_breach_behavior", "IncreaseMaxCapacity"), @@ -234,14 +234,14 @@ func TestAccAutoScalingPolicy_predictiveScalingRemoved(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigPredictiveScalingPredefined(rName), + Config: testAccPolicyConfig_predictiveScalingPredefined(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "predictive_scaling_configuration.#", "1"), ), }, { - Config: testAccPolicyConfigPredictiveScalingRemoved(rName), + Config: testAccPolicyConfig_predictiveScalingRemoved(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "predictive_scaling_configuration.#", "0"), @@ -269,7 +269,7 @@ func TestAccAutoScalingPolicy_predictiveScalingUpdated(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigPredictiveScalingPredefined(rName), + Config: testAccPolicyConfig_predictiveScalingPredefined(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "predictive_scaling_configuration.0.mode", "ForecastAndScale"), @@ -320,7 +320,7 @@ func TestAccAutoScalingPolicy_simpleScalingStepAdjustment(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigSimpleScalingStepAdjustment(rName), + Config: testAccPolicyConfig_simpleScalingStepAdjustment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "adjustment_type", "ExactCapacity"), @@ -349,7 +349,7 @@ func TestAccAutoScalingPolicy_TargetTrack_predefined(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigTargetTrackingPredefined(rName), + Config: testAccPolicyConfig_targetTrackingPredefined(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceName, &v), ), @@ -376,7 +376,7 @@ func TestAccAutoScalingPolicy_TargetTrack_custom(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigTargetTrackingCustom(rName), + Config: testAccPolicyConfig_targetTrackingCustom(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceName, &v), ), @@ -404,7 +404,7 @@ func TestAccAutoScalingPolicy_zeroValue(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfigZeroValue(rName), + Config: testAccPolicyConfig_zeroValue(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScalingPolicyExists(resourceSimpleName, &v1), testAccCheckScalingPolicyExists(resourceStepName, &v2), @@ -493,7 +493,7 @@ func testAccPolicyImportStateIdFunc(resourceName string) resource.ImportStateIdF func testAccPolicyConfigBase(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q @@ -512,7 +512,7 @@ resource "aws_autoscaling_group" "test" { `, rName)) } -func testAccPolicyConfigBasic(rName string) string { +func testAccPolicyConfig_basic(rName string) string { return acctest.ConfigCompose(testAccPolicyConfigBase(rName), fmt.Sprintf(` resource "aws_autoscaling_policy" "test_simple" { name = "%[1]s-simple" @@ -556,7 +556,7 @@ resource "aws_autoscaling_policy" "test_tracking" { `, rName)) } -func testAccPolicyConfigPredictiveScalingPredefined(rName string) string { +func testAccPolicyConfig_predictiveScalingPredefined(rName string) string { return acctest.ConfigCompose(testAccPolicyConfigBase(rName), fmt.Sprintf(` resource "aws_autoscaling_policy" "test" { name = "%[1]s-predictive" @@ -583,7 +583,7 @@ resource "aws_autoscaling_policy" "test" { `, rName)) } -func testAccPolicyConfigPredictiveScalingCustom(rName string) string { +func testAccPolicyConfig_predictiveScalingCustom(rName string) string { return acctest.ConfigCompose(testAccPolicyConfigBase(rName), fmt.Sprintf(` resource "aws_autoscaling_policy" "test" { name = "%[1]s-predictive" @@ -653,7 +653,7 @@ resource "aws_autoscaling_policy" "test" { `, rName)) } -func testAccPolicyConfigPredictiveScalingRemoved(rName string) string { +func testAccPolicyConfig_predictiveScalingRemoved(rName string) string { return acctest.ConfigCompose(testAccPolicyConfigBase(rName), fmt.Sprintf(` resource "aws_autoscaling_policy" "test" { name = "%[1]s-simple" @@ -742,7 +742,7 @@ resource "aws_autoscaling_policy" "test_tracking" { `, rName)) } -func testAccPolicyConfigSimpleScalingStepAdjustment(rName string) string { +func testAccPolicyConfig_simpleScalingStepAdjustment(rName string) string { return acctest.ConfigCompose(testAccPolicyConfigBase(rName), fmt.Sprintf(` resource "aws_autoscaling_policy" "test" { name = "%[1]s-simple" @@ -755,7 +755,7 @@ resource "aws_autoscaling_policy" "test" { `, rName)) } -func testAccPolicyConfigTargetTrackingPredefined(rName string) string { +func testAccPolicyConfig_targetTrackingPredefined(rName string) string { return acctest.ConfigCompose(testAccPolicyConfigBase(rName), fmt.Sprintf(` resource "aws_autoscaling_policy" "test" { name = "%[1]s-tracking" @@ -773,7 +773,7 @@ resource "aws_autoscaling_policy" "test" { `, rName)) } -func testAccPolicyConfigTargetTrackingCustom(rName string) string { +func testAccPolicyConfig_targetTrackingCustom(rName string) string { return acctest.ConfigCompose(testAccPolicyConfigBase(rName), fmt.Sprintf(` resource "aws_autoscaling_policy" "test" { name = "%[1]s-tracking" @@ -798,7 +798,7 @@ resource "aws_autoscaling_policy" "test" { `, rName)) } -func testAccPolicyConfigZeroValue(rName string) string { +func testAccPolicyConfig_zeroValue(rName string) string { return acctest.ConfigCompose(testAccPolicyConfigBase(rName), fmt.Sprintf(` resource "aws_autoscaling_policy" "test_simple" { name = "%[1]s-simple" diff --git a/internal/service/autoscaling/schedule_test.go b/internal/service/autoscaling/schedule_test.go index c1c1091fc81..8023e19c7ec 100644 --- a/internal/service/autoscaling/schedule_test.go +++ b/internal/service/autoscaling/schedule_test.go @@ -31,7 +31,7 @@ func TestAccAutoScalingSchedule_basic(t *testing.T) { CheckDestroy: testAccCheckScheduleDestroy, Steps: []resource.TestStep{ { - Config: testAccScheduleConfig(rName1, rName2, startTime, endTime), + Config: testAccScheduleConfig_basic(rName1, rName2, startTime, endTime), Check: resource.ComposeTestCheckFunc( testAccCheckScalingScheduleExists(resourceName, &v), ), @@ -61,7 +61,7 @@ func TestAccAutoScalingSchedule_disappears(t *testing.T) { CheckDestroy: testAccCheckScheduleDestroy, Steps: []resource.TestStep{ { - Config: testAccScheduleConfig(rName1, rName2, startTime, endTime), + Config: testAccScheduleConfig_basic(rName1, rName2, startTime, endTime), Check: resource.ComposeTestCheckFunc( testAccCheckScalingScheduleExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfautoscaling.ResourceSchedule(), resourceName), @@ -236,10 +236,10 @@ func testAccCheckScalingScheduleHasNoDesiredCapacity(v *autoscaling.ScheduledUpd } } -func testAccScheduleConfig(rName1, rName2, startTime, endTime string) string { +func testAccScheduleConfig_basic(rName1, rName2, startTime, endTime string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q @@ -274,7 +274,7 @@ resource "aws_autoscaling_schedule" "test" { func testAccScheduleConfig_recurrence(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q @@ -309,7 +309,7 @@ resource "aws_autoscaling_schedule" "test" { func testAccScheduleConfig_zeroValues(rName, startTime, endTime string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q @@ -344,7 +344,7 @@ resource "aws_autoscaling_schedule" "test" { func testAccScheduleConfig_negativeOne(rName, startTime, endTime string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_configuration" "test" { name = %[1]q diff --git a/internal/service/autoscaling/status.go b/internal/service/autoscaling/status.go deleted file mode 100644 index c2016c621c4..00000000000 --- a/internal/service/autoscaling/status.go +++ /dev/null @@ -1,28 +0,0 @@ -package autoscaling - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" -) - -func statusInstanceRefresh(conn *autoscaling.AutoScaling, asgName, instanceRefreshId string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - input := autoscaling.DescribeInstanceRefreshesInput{ - AutoScalingGroupName: aws.String(asgName), - InstanceRefreshIds: []*string{aws.String(instanceRefreshId)}, - } - output, err := conn.DescribeInstanceRefreshes(&input) - if err != nil { - return nil, "", err - } - - if output == nil || len(output.InstanceRefreshes) == 0 || output.InstanceRefreshes[0] == nil { - return nil, "", nil - } - - instanceRefresh := output.InstanceRefreshes[0] - - return instanceRefresh, aws.StringValue(instanceRefresh.Status), nil - } -} diff --git a/internal/service/autoscaling/wait.go b/internal/service/autoscaling/wait.go deleted file mode 100644 index 78c64717fca..00000000000 --- a/internal/service/autoscaling/wait.go +++ /dev/null @@ -1,44 +0,0 @@ -package autoscaling - -import ( - "time" - - "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" -) - -const ( - // Maximum amount of time to wait for an InstanceRefresh to be started - // Must be at least as long as instanceRefreshCancelledTimeout, since we try to cancel any - // existing Instance Refreshes when starting. - instanceRefreshStartedTimeout = instanceRefreshCancelledTimeout - - // Maximum amount of time to wait for an Instance Refresh to be Cancelled - instanceRefreshCancelledTimeout = 15 * time.Minute -) - -func waitInstanceRefreshCancelled(conn *autoscaling.AutoScaling, asgName, instanceRefreshId string) (*autoscaling.InstanceRefresh, error) { - stateConf := &resource.StateChangeConf{ - Pending: []string{ - autoscaling.InstanceRefreshStatusPending, - autoscaling.InstanceRefreshStatusInProgress, - autoscaling.InstanceRefreshStatusCancelling, - }, - Target: []string{ - autoscaling.InstanceRefreshStatusCancelled, - // Failed and Successful are also acceptable end-states - autoscaling.InstanceRefreshStatusFailed, - autoscaling.InstanceRefreshStatusSuccessful, - }, - Refresh: statusInstanceRefresh(conn, asgName, instanceRefreshId), - Timeout: instanceRefreshCancelledTimeout, - } - - outputRaw, err := stateConf.WaitForState() - - if v, ok := outputRaw.(*autoscaling.InstanceRefresh); ok { - return v, err - } - - return nil, err -} diff --git a/internal/service/autoscalingplans/scaling_plan_test.go b/internal/service/autoscalingplans/scaling_plan_test.go index 89eec073ef7..0c0ed79fcaa 100644 --- a/internal/service/autoscalingplans/scaling_plan_test.go +++ b/internal/service/autoscalingplans/scaling_plan_test.go @@ -437,7 +437,7 @@ func testAccCheckApplicationSourceTags(scalingPlan *autoscalingplans.ScalingPlan func testAccScalingPlanConfigBase(rName, tagName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptInDefaultExclude(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` diff --git a/internal/service/backup/consts.go b/internal/service/backup/consts.go index 2e17cff83c9..dc43465190f 100644 --- a/internal/service/backup/consts.go +++ b/internal/service/backup/consts.go @@ -28,7 +28,7 @@ func reportDeliveryChannelFormat_Values() []string { } const ( - reportSettingTemplateBackupJobReport = "BACKUP_JOB_REPORT" + reportSettingTemplateJobReport = "BACKUP_JOB_REPORT" reportSettingTemplateControlComplianceReport = "CONTROL_COMPLIANCE_REPORT" reportSettingTemplateCopyJobReport = "COPY_JOB_REPORT" reportSettingTemplateResourceComplianceReport = "RESOURCE_COMPLIANCE_REPORT" @@ -37,7 +37,7 @@ const ( func reportSettingTemplate_Values() []string { return []string{ - reportSettingTemplateBackupJobReport, + reportSettingTemplateJobReport, reportSettingTemplateControlComplianceReport, reportSettingTemplateCopyJobReport, reportSettingTemplateResourceComplianceReport, diff --git a/internal/service/backup/find.go b/internal/service/backup/find.go index ad671d616c2..65fe78ab8fa 100644 --- a/internal/service/backup/find.go +++ b/internal/service/backup/find.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func FindBackupVaultAccessPolicyByName(conn *backup.Backup, name string) (*backup.GetBackupVaultAccessPolicyOutput, error) { +func FindVaultAccessPolicyByName(conn *backup.Backup, name string) (*backup.GetBackupVaultAccessPolicyOutput, error) { input := &backup.GetBackupVaultAccessPolicyInput{ BackupVaultName: aws.String(name), } @@ -33,7 +33,7 @@ func FindBackupVaultAccessPolicyByName(conn *backup.Backup, name string) (*backu return output, nil } -func FindBackupVaultByName(conn *backup.Backup, name string) (*backup.DescribeBackupVaultOutput, error) { +func FindVaultByName(conn *backup.Backup, name string) (*backup.DescribeBackupVaultOutput, error) { input := &backup.DescribeBackupVaultInput{ BackupVaultName: aws.String(name), } diff --git a/internal/service/backup/framework_data_source_test.go b/internal/service/backup/framework_data_source_test.go index bce54cd69ae..601ecf97b30 100644 --- a/internal/service/backup/framework_data_source_test.go +++ b/internal/service/backup/framework_data_source_test.go @@ -11,7 +11,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" ) -func testAccBackupFrameworkDataSource_basic(t *testing.T) { +func testAccFrameworkDataSource_basic(t *testing.T) { datasourceName := "data.aws_backup_framework.test" resourceName := "aws_backup_framework.test" rName := fmt.Sprintf("tf_acc_test_%s", sdkacctest.RandString(7)) @@ -67,7 +67,7 @@ func testAccBackupFrameworkDataSource_basic(t *testing.T) { }) } -func testAccBackupFrameworkDataSource_controlScopeTag(t *testing.T) { +func testAccFrameworkDataSource_controlScopeTag(t *testing.T) { datasourceName := "data.aws_backup_framework.test" resourceName := "aws_backup_framework.test" rName := fmt.Sprintf("tf_acc_test_%s", sdkacctest.RandString(7)) diff --git a/internal/service/backup/framework_test.go b/internal/service/backup/framework_test.go index d24c3c81f73..d761597ddc0 100644 --- a/internal/service/backup/framework_test.go +++ b/internal/service/backup/framework_test.go @@ -17,16 +17,16 @@ import ( func TestAccBackupFramework_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Resource": { - "basic": testAccBackupFramework_basic, - "disappears": testAccBackupFramework_disappears, - "UpdateTags": testAccBackupFramework_updateTags, - "UpdateControlScope": testAccBackupFramework_updateControlScope, - "UpdateControlInputParameters": testAccBackupFramework_updateControlInputParameters, - "UpdateControls": testAccBackupFramework_updateControls, + "basic": testAccFramework_basic, + "disappears": testAccFramework_disappears, + "UpdateTags": testAccFramework_updateTags, + "UpdateControlScope": testAccFramework_updateControlScope, + "UpdateControlInputParameters": testAccFramework_updateControlInputParameters, + "UpdateControls": testAccFramework_updateControls, }, "DataSource": { - "basic": testAccBackupFrameworkDataSource_basic, - "ControlScopeTag": testAccBackupFrameworkDataSource_controlScopeTag, + "basic": testAccFrameworkDataSource_basic, + "ControlScopeTag": testAccFrameworkDataSource_controlScopeTag, }, } @@ -43,7 +43,7 @@ func TestAccBackupFramework_serial(t *testing.T) { } } -func testAccBackupFramework_basic(t *testing.T) { +func testAccFramework_basic(t *testing.T) { var framework backup.DescribeFrameworkOutput rName := fmt.Sprintf("tf_acc_test_%s", sdkacctest.RandString(7)) @@ -58,7 +58,7 @@ func testAccBackupFramework_basic(t *testing.T) { CheckDestroy: testAccCheckFrameworkDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupFrameworkConfig_basic(rName, originalDescription), + Config: testAccFrameworkConfig_basic(rName, originalDescription), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -82,7 +82,7 @@ func testAccBackupFramework_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupFrameworkConfig_basic(rName, updatedDescription), + Config: testAccFrameworkConfig_basic(rName, updatedDescription), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -104,7 +104,7 @@ func testAccBackupFramework_basic(t *testing.T) { }) } -func testAccBackupFramework_updateTags(t *testing.T) { +func testAccFramework_updateTags(t *testing.T) { var framework backup.DescribeFrameworkOutput rName := fmt.Sprintf("tf_acc_test_%s", sdkacctest.RandString(7)) @@ -118,7 +118,7 @@ func testAccBackupFramework_updateTags(t *testing.T) { CheckDestroy: testAccCheckFrameworkDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupFrameworkConfig_basic(rName, description), + Config: testAccFrameworkConfig_basic(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -142,7 +142,7 @@ func testAccBackupFramework_updateTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupFrameworkConfig_tags(rName, description), + Config: testAccFrameworkConfig_tags(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -167,7 +167,7 @@ func testAccBackupFramework_updateTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupFrameworkConfig_tagsUpdated(rName, description), + Config: testAccFrameworkConfig_tagsUpdated(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -191,7 +191,7 @@ func testAccBackupFramework_updateTags(t *testing.T) { }) } -func testAccBackupFramework_updateControlScope(t *testing.T) { +func testAccFramework_updateControlScope(t *testing.T) { var framework backup.DescribeFrameworkOutput rName := fmt.Sprintf("tf_acc_test_%s", sdkacctest.RandString(7)) @@ -207,7 +207,7 @@ func testAccBackupFramework_updateControlScope(t *testing.T) { CheckDestroy: testAccCheckFrameworkDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupFrameworkConfig_basic(rName, description), + Config: testAccFrameworkConfig_basic(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -231,7 +231,7 @@ func testAccBackupFramework_updateControlScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupFrameworkConfig_controlScopeComplianceResourceId(rName, description), + Config: testAccFrameworkConfig_controlScopeComplianceResourceID(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -257,7 +257,7 @@ func testAccBackupFramework_updateControlScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupFrameworkConfig_controlScopeTag(rName, description, originalControlScopeTagValue), + Config: testAccFrameworkConfig_controlScopeTag(rName, description, originalControlScopeTagValue), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -281,7 +281,7 @@ func testAccBackupFramework_updateControlScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupFrameworkConfig_controlScopeTag(rName, description, updatedControlScopeTagValue), + Config: testAccFrameworkConfig_controlScopeTag(rName, description, updatedControlScopeTagValue), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -303,7 +303,7 @@ func testAccBackupFramework_updateControlScope(t *testing.T) { }) } -func testAccBackupFramework_updateControlInputParameters(t *testing.T) { +func testAccFramework_updateControlInputParameters(t *testing.T) { var framework backup.DescribeFrameworkOutput rName := fmt.Sprintf("tf_acc_test_%s", sdkacctest.RandString(7)) @@ -319,7 +319,7 @@ func testAccBackupFramework_updateControlInputParameters(t *testing.T) { CheckDestroy: testAccCheckFrameworkDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupFrameworkConfig_controlInputParameter(rName, description, originalRequiredRetentionDays), + Config: testAccFrameworkConfig_controlInputParameter(rName, description, originalRequiredRetentionDays), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -353,7 +353,7 @@ func testAccBackupFramework_updateControlInputParameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupFrameworkConfig_controlInputParameter(rName, description, updatedRequiredRetentionDays), + Config: testAccFrameworkConfig_controlInputParameter(rName, description, updatedRequiredRetentionDays), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -385,7 +385,7 @@ func testAccBackupFramework_updateControlInputParameters(t *testing.T) { }) } -func testAccBackupFramework_updateControls(t *testing.T) { +func testAccFramework_updateControls(t *testing.T) { var framework backup.DescribeFrameworkOutput rName := fmt.Sprintf("tf_acc_test_%s", sdkacctest.RandString(7)) @@ -399,7 +399,7 @@ func testAccBackupFramework_updateControls(t *testing.T) { CheckDestroy: testAccCheckFrameworkDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupFrameworkConfig_basic(rName, description), + Config: testAccFrameworkConfig_basic(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -423,7 +423,7 @@ func testAccBackupFramework_updateControls(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupFrameworkConfig_controls(rName, description), + Config: testAccFrameworkConfig_controls(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -463,7 +463,7 @@ func testAccBackupFramework_updateControls(t *testing.T) { }) } -func testAccBackupFramework_disappears(t *testing.T) { +func testAccFramework_disappears(t *testing.T) { var framework backup.DescribeFrameworkOutput rName := fmt.Sprintf("tf_acc_test_%s", sdkacctest.RandString(7)) @@ -477,7 +477,7 @@ func testAccBackupFramework_disappears(t *testing.T) { CheckDestroy: testAccCheckFrameworkDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupFrameworkConfig_basic(rName, description), + Config: testAccFrameworkConfig_basic(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckFrameworkExists(resourceName, &framework), acctest.CheckResourceDisappears(acctest.Provider, tfbackup.ResourceFramework(), resourceName), @@ -549,7 +549,7 @@ func testAccCheckFrameworkExists(name string, framework *backup.DescribeFramewor } } -func testAccBackupFrameworkConfig_basic(rName, label string) string { +func testAccFrameworkConfig_basic(rName, label string) string { return fmt.Sprintf(` resource "aws_backup_framework" "test" { name = %[1]q @@ -572,7 +572,7 @@ resource "aws_backup_framework" "test" { `, rName, label) } -func testAccBackupFrameworkConfig_tags(rName, label string) string { +func testAccFrameworkConfig_tags(rName, label string) string { return fmt.Sprintf(` resource "aws_backup_framework" "test" { name = %[1]q @@ -596,7 +596,7 @@ resource "aws_backup_framework" "test" { `, rName, label) } -func testAccBackupFrameworkConfig_tagsUpdated(rName, label string) string { +func testAccFrameworkConfig_tagsUpdated(rName, label string) string { return fmt.Sprintf(` resource "aws_backup_framework" "test" { name = %[1]q @@ -621,7 +621,7 @@ resource "aws_backup_framework" "test" { `, rName, label) } -func testAccBackupFrameworkConfig_controlScopeComplianceResourceId(rName, label string) string { +func testAccFrameworkConfig_controlScopeComplianceResourceID(rName, label string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -663,7 +663,7 @@ resource "aws_backup_framework" "test" { `, rName, label) } -func testAccBackupFrameworkConfig_controlScopeTag(rName, label, controlScopeTagValue string) string { +func testAccFrameworkConfig_controlScopeTag(rName, label, controlScopeTagValue string) string { return fmt.Sprintf(` resource "aws_backup_framework" "test" { name = %[1]q @@ -686,7 +686,7 @@ resource "aws_backup_framework" "test" { `, rName, label, controlScopeTagValue) } -func testAccBackupFrameworkConfig_controlInputParameter(rName, label, requiredRetentionDaysValue string) string { +func testAccFrameworkConfig_controlInputParameter(rName, label, requiredRetentionDaysValue string) string { return fmt.Sprintf(` resource "aws_backup_framework" "test" { name = %[1]q @@ -718,7 +718,7 @@ resource "aws_backup_framework" "test" { `, rName, label, requiredRetentionDaysValue) } -func testAccBackupFrameworkConfig_controls(rName, label string) string { +func testAccFrameworkConfig_controls(rName, label string) string { return fmt.Sprintf(` resource "aws_backup_framework" "test" { name = %[1]q diff --git a/internal/service/backup/global_settings_test.go b/internal/service/backup/global_settings_test.go index a2c002b2d12..51cb48c725d 100644 --- a/internal/service/backup/global_settings_test.go +++ b/internal/service/backup/global_settings_test.go @@ -26,7 +26,7 @@ func TestAccBackupGlobalSettings_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccBackupGlobalSettingsConfig("true"), + Config: testAccGlobalSettingsConfig_basic("true"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalSettingsExists(&settings), resource.TestCheckResourceAttr(resourceName, "global_settings.%", "1"), @@ -39,7 +39,7 @@ func TestAccBackupGlobalSettings_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupGlobalSettingsConfig("false"), + Config: testAccGlobalSettingsConfig_basic("false"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalSettingsExists(&settings), resource.TestCheckResourceAttr(resourceName, "global_settings.%", "1"), @@ -47,7 +47,7 @@ func TestAccBackupGlobalSettings_basic(t *testing.T) { ), }, { - Config: testAccBackupGlobalSettingsConfig("true"), + Config: testAccGlobalSettingsConfig_basic("true"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalSettingsExists(&settings), resource.TestCheckResourceAttr(resourceName, "global_settings.%", "1"), @@ -73,7 +73,7 @@ func testAccCheckGlobalSettingsExists(settings *backup.DescribeGlobalSettingsOut } } -func testAccBackupGlobalSettingsConfig(setting string) string { +func testAccGlobalSettingsConfig_basic(setting string) string { return fmt.Sprintf(` resource "aws_backup_global_settings" "test" { global_settings = { diff --git a/internal/service/backup/plan.go b/internal/service/backup/plan.go index 299cce9d68a..f24e5021b74 100644 --- a/internal/service/backup/plan.go +++ b/internal/service/backup/plan.go @@ -127,7 +127,7 @@ func ResourcePlan() *schema.Resource { "recovery_point_tags": tftags.TagsSchema(), }, }, - Set: backupBackupPlanHash, + Set: planHash, }, "advanced_backup_setting": { Type: schema.TypeSet, @@ -173,8 +173,8 @@ func resourcePlanCreate(d *schema.ResourceData, meta interface{}) error { input := &backup.CreateBackupPlanInput{ BackupPlan: &backup.PlanInput{ BackupPlanName: aws.String(d.Get("name").(string)), - Rules: expandBackupPlanRules(d.Get("rule").(*schema.Set)), - AdvancedBackupSettings: expandBackupPlanAdvancedBackupSettings(d.Get("advanced_backup_setting").(*schema.Set)), + Rules: expandPlanRules(d.Get("rule").(*schema.Set)), + AdvancedBackupSettings: expandPlanAdvancedSettings(d.Get("advanced_backup_setting").(*schema.Set)), }, BackupPlanTags: Tags(tags.IgnoreAWS()), } @@ -211,13 +211,13 @@ func resourcePlanRead(d *schema.ResourceData, meta interface{}) error { d.Set("name", resp.BackupPlan.BackupPlanName) d.Set("version", resp.VersionId) - if err := d.Set("rule", flattenBackupPlanRules(resp.BackupPlan.Rules)); err != nil { + if err := d.Set("rule", flattenPlanRules(resp.BackupPlan.Rules)); err != nil { return fmt.Errorf("error setting rule: %w", err) } // AdvancedBackupSettings being read direct from resp and not from under // resp.BackupPlan is deliberate - the latter always contains null - if err := d.Set("advanced_backup_setting", flattenBackupPlanAdvancedBackupSettings(resp.AdvancedBackupSettings)); err != nil { + if err := d.Set("advanced_backup_setting", flattenPlanAdvancedSettings(resp.AdvancedBackupSettings)); err != nil { return fmt.Errorf("error setting advanced_backup_setting: %w", err) } @@ -247,8 +247,8 @@ func resourcePlanUpdate(d *schema.ResourceData, meta interface{}) error { BackupPlanId: aws.String(d.Id()), BackupPlan: &backup.PlanInput{ BackupPlanName: aws.String(d.Get("name").(string)), - Rules: expandBackupPlanRules(d.Get("rule").(*schema.Set)), - AdvancedBackupSettings: expandBackupPlanAdvancedBackupSettings(d.Get("advanced_backup_setting").(*schema.Set)), + Rules: expandPlanRules(d.Get("rule").(*schema.Set)), + AdvancedBackupSettings: expandPlanAdvancedSettings(d.Get("advanced_backup_setting").(*schema.Set)), }, } @@ -305,7 +305,7 @@ func resourcePlanDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func expandBackupPlanRules(vRules *schema.Set) []*backup.RuleInput { +func expandPlanRules(vRules *schema.Set) []*backup.RuleInput { rules := []*backup.RuleInput{} for _, vRule := range vRules.List() { @@ -339,10 +339,10 @@ func expandBackupPlanRules(vRules *schema.Set) []*backup.RuleInput { } if vLifecycle, ok := mRule["lifecycle"].([]interface{}); ok && len(vLifecycle) > 0 { - rule.Lifecycle = expandBackupPlanLifecycle(vLifecycle) + rule.Lifecycle = expandPlanLifecycle(vLifecycle) } - if vCopyActions := expandBackupPlanCopyActions(mRule["copy_action"].(*schema.Set).List()); len(vCopyActions) > 0 { + if vCopyActions := expandPlanCopyActions(mRule["copy_action"].(*schema.Set).List()); len(vCopyActions) > 0 { rule.CopyActions = vCopyActions } @@ -352,7 +352,7 @@ func expandBackupPlanRules(vRules *schema.Set) []*backup.RuleInput { return rules } -func expandBackupPlanAdvancedBackupSettings(vAdvancedBackupSettings *schema.Set) []*backup.AdvancedBackupSetting { +func expandPlanAdvancedSettings(vAdvancedBackupSettings *schema.Set) []*backup.AdvancedBackupSetting { advancedBackupSettings := []*backup.AdvancedBackupSetting{} for _, vAdvancedBackupSetting := range vAdvancedBackupSettings.List() { @@ -379,7 +379,7 @@ func expandBackupPlanAdvancedBackupSettings(vAdvancedBackupSettings *schema.Set) return advancedBackupSettings } -func expandBackupPlanCopyActions(actionList []interface{}) []*backup.CopyAction { +func expandPlanCopyActions(actionList []interface{}) []*backup.CopyAction { actions := []*backup.CopyAction{} for _, i := range actionList { @@ -389,7 +389,7 @@ func expandBackupPlanCopyActions(actionList []interface{}) []*backup.CopyAction action.DestinationBackupVaultArn = aws.String(item["destination_vault_arn"].(string)) if v, ok := item["lifecycle"].([]interface{}); ok && len(v) > 0 { - action.Lifecycle = expandBackupPlanLifecycle(v) + action.Lifecycle = expandPlanLifecycle(v) } actions = append(actions, action) @@ -398,7 +398,7 @@ func expandBackupPlanCopyActions(actionList []interface{}) []*backup.CopyAction return actions } -func expandBackupPlanLifecycle(l []interface{}) *backup.Lifecycle { +func expandPlanLifecycle(l []interface{}) *backup.Lifecycle { lifecycle := new(backup.Lifecycle) for _, i := range l { @@ -414,7 +414,7 @@ func expandBackupPlanLifecycle(l []interface{}) *backup.Lifecycle { return lifecycle } -func flattenBackupPlanRules(rules []*backup.Rule) *schema.Set { +func flattenPlanRules(rules []*backup.Rule) *schema.Set { vRules := []interface{}{} for _, rule := range rules { @@ -429,18 +429,18 @@ func flattenBackupPlanRules(rules []*backup.Rule) *schema.Set { } if lifecycle := rule.Lifecycle; lifecycle != nil { - mRule["lifecycle"] = flattenBackupPlanCopyActionLifecycle(lifecycle) + mRule["lifecycle"] = flattenPlanCopyActionLifecycle(lifecycle) } - mRule["copy_action"] = flattenBackupPlanCopyActions(rule.CopyActions) + mRule["copy_action"] = flattenPlanCopyActions(rule.CopyActions) vRules = append(vRules, mRule) } - return schema.NewSet(backupBackupPlanHash, vRules) + return schema.NewSet(planHash, vRules) } -func flattenBackupPlanAdvancedBackupSettings(advancedBackupSettings []*backup.AdvancedBackupSetting) *schema.Set { +func flattenPlanAdvancedSettings(advancedBackupSettings []*backup.AdvancedBackupSetting) *schema.Set { vAdvancedBackupSettings := []interface{}{} for _, advancedBackupSetting := range advancedBackupSettings { @@ -452,10 +452,10 @@ func flattenBackupPlanAdvancedBackupSettings(advancedBackupSettings []*backup.Ad vAdvancedBackupSettings = append(vAdvancedBackupSettings, mAdvancedBackupSetting) } - return schema.NewSet(backupBackupPlanHash, vAdvancedBackupSettings) + return schema.NewSet(planHash, vAdvancedBackupSettings) } -func flattenBackupPlanCopyActions(copyActions []*backup.CopyAction) []interface{} { +func flattenPlanCopyActions(copyActions []*backup.CopyAction) []interface{} { if len(copyActions) == 0 { return nil } @@ -472,7 +472,7 @@ func flattenBackupPlanCopyActions(copyActions []*backup.CopyAction) []interface{ } if copyAction.Lifecycle != nil { - tfMap["lifecycle"] = flattenBackupPlanCopyActionLifecycle(copyAction.Lifecycle) + tfMap["lifecycle"] = flattenPlanCopyActionLifecycle(copyAction.Lifecycle) } tfList = append(tfList, tfMap) @@ -481,7 +481,7 @@ func flattenBackupPlanCopyActions(copyActions []*backup.CopyAction) []interface{ return tfList } -func flattenBackupPlanCopyActionLifecycle(copyActionLifecycle *backup.Lifecycle) []interface{} { +func flattenPlanCopyActionLifecycle(copyActionLifecycle *backup.Lifecycle) []interface{} { if copyActionLifecycle == nil { return []interface{}{} } @@ -494,7 +494,7 @@ func flattenBackupPlanCopyActionLifecycle(copyActionLifecycle *backup.Lifecycle) return []interface{}{m} } -func backupBackupPlanHash(vRule interface{}) int { +func planHash(vRule interface{}) int { var buf bytes.Buffer mRule := vRule.(map[string]interface{}) diff --git a/internal/service/backup/plan_test.go b/internal/service/backup/plan_test.go index e0926cb0031..2ef28942fe6 100644 --- a/internal/service/backup/plan_test.go +++ b/internal/service/backup/plan_test.go @@ -349,7 +349,7 @@ func TestAccBackupPlan_RuleCopyAction_sameRegion(t *testing.T) { CheckDestroy: testAccCheckPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccPlanRuleCopyActionConfig(rName, 30, 180), + Config: testAccPlanConfig_ruleCopyAction(rName, 30, 180), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -369,7 +369,7 @@ func TestAccBackupPlan_RuleCopyAction_sameRegion(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPlanRuleCopyActionConfig(rName, 60, 365), + Config: testAccPlanConfig_ruleCopyAction(rName, 60, 365), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -412,7 +412,7 @@ func TestAccBackupPlan_RuleCopyAction_noLifecycle(t *testing.T) { CheckDestroy: testAccCheckPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccPlanRuleCopyActionNoLifecycleConfig(rName), + Config: testAccPlanConfig_ruleCopyActionNoLifecycle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -430,7 +430,7 @@ func TestAccBackupPlan_RuleCopyAction_noLifecycle(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPlanRuleCopyActionConfig(rName, 60, 365), + Config: testAccPlanConfig_ruleCopyAction(rName, 60, 365), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -445,7 +445,7 @@ func TestAccBackupPlan_RuleCopyAction_noLifecycle(t *testing.T) { ), }, { - Config: testAccPlanRuleCopyActionNoLifecycleConfig(rName), + Config: testAccPlanConfig_ruleCopyActionNoLifecycle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -473,7 +473,7 @@ func TestAccBackupPlan_RuleCopyAction_multiple(t *testing.T) { CheckDestroy: testAccCheckPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccPlanRuleCopyActionMultipleConfig(rName), + Config: testAccPlanConfig_ruleCopyActionMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -513,7 +513,7 @@ func TestAccBackupPlan_RuleCopyAction_crossRegion(t *testing.T) { CheckDestroy: testAccCheckPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccPlanRuleCopyActionCrossRegionConfig(rName), + Config: testAccPlanConfig_ruleCopyActionCrossRegion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -528,7 +528,7 @@ func TestAccBackupPlan_RuleCopyAction_crossRegion(t *testing.T) { ), }, { - Config: testAccPlanRuleCopyActionCrossRegionConfig(rName), + Config: testAccPlanConfig_ruleCopyActionCrossRegion(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -549,7 +549,7 @@ func TestAccBackupPlan_advancedBackupSetting(t *testing.T) { CheckDestroy: testAccCheckPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccPlanAdvancedBackupSettingConfig(rName), + Config: testAccPlanConfig_advancedSetting(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -567,7 +567,7 @@ func TestAccBackupPlan_advancedBackupSetting(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPlanAdvancedBackupSettingUpdatedConfig(rName), + Config: testAccPlanConfig_advancedSettingUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -595,7 +595,7 @@ func TestAccBackupPlan_enableContinuousBackup(t *testing.T) { CheckDestroy: testAccCheckPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccPlanEnableContinuousBackupConfig(rName), + Config: testAccPlanConfig_enableContinuous(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlanExists(resourceName, &plan), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "backup", regexp.MustCompile(`backup-plan:.+`)), @@ -925,7 +925,7 @@ resource "aws_backup_plan" "test" { `, rName) } -func testAccPlanRuleCopyActionConfig(rName string, coldStorageAfter, deleteAfter int) string { +func testAccPlanConfig_ruleCopyAction(rName string, coldStorageAfter, deleteAfter int) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = "%[1]s-1" @@ -961,7 +961,7 @@ resource "aws_backup_plan" "test" { `, rName, coldStorageAfter, deleteAfter) } -func testAccPlanRuleCopyActionMultipleConfig(rName string) string { +func testAccPlanConfig_ruleCopyActionMultiple(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = "%[1]s-1" @@ -1010,7 +1010,7 @@ resource "aws_backup_plan" "test" { `, rName) } -func testAccPlanRuleCopyActionCrossRegionConfig(rName string) string { +func testAccPlanConfig_ruleCopyActionCrossRegion(rName string) string { return acctest.ConfigAlternateRegionProvider() + fmt.Sprintf(` resource "aws_backup_vault" "test" { name = "%[1]s-1" @@ -1047,7 +1047,7 @@ resource "aws_backup_plan" "test" { `, rName) } -func testAccPlanRuleCopyActionNoLifecycleConfig(rName string) string { +func testAccPlanConfig_ruleCopyActionNoLifecycle(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = "%[1]s-1" @@ -1073,7 +1073,7 @@ resource "aws_backup_plan" "test" { `, rName) } -func testAccPlanAdvancedBackupSettingConfig(rName string) string { +func testAccPlanConfig_advancedSetting(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = %[1]q @@ -1104,7 +1104,7 @@ resource "aws_backup_plan" "test" { `, rName) } -func testAccPlanAdvancedBackupSettingUpdatedConfig(rName string) string { +func testAccPlanConfig_advancedSettingUpdated(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = %[1]q @@ -1135,7 +1135,7 @@ resource "aws_backup_plan" "test" { `, rName) } -func testAccPlanEnableContinuousBackupConfig(rName string) string { +func testAccPlanConfig_enableContinuous(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = %[1]q diff --git a/internal/service/backup/region_settings_test.go b/internal/service/backup/region_settings_test.go index abfb35be8c6..d1a584539d9 100644 --- a/internal/service/backup/region_settings_test.go +++ b/internal/service/backup/region_settings_test.go @@ -26,7 +26,7 @@ func TestAccBackupRegionSettings_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccRegionSettings1Config(), + Config: testAccRegionSettingsConfig_1(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRegionSettingsExists(&settings), resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.%", "12"), @@ -53,7 +53,7 @@ func TestAccBackupRegionSettings_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRegionSettings2Config(), + Config: testAccRegionSettingsConfig_2(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRegionSettingsExists(&settings), resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.%", "12"), @@ -75,7 +75,7 @@ func TestAccBackupRegionSettings_basic(t *testing.T) { ), }, { - Config: testAccRegionSettings3Config(), + Config: testAccRegionSettingsConfig_3(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRegionSettingsExists(&settings), resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.%", "12"), @@ -116,7 +116,7 @@ func testAccCheckRegionSettingsExists(v *backup.DescribeRegionSettingsOutput) re } } -func testAccRegionSettings1Config() string { +func testAccRegionSettingsConfig_1() string { return ` resource "aws_backup_region_settings" "test" { resource_type_opt_in_preference = { @@ -137,7 +137,7 @@ resource "aws_backup_region_settings" "test" { ` } -func testAccRegionSettings2Config() string { +func testAccRegionSettingsConfig_2() string { return ` resource "aws_backup_region_settings" "test" { resource_type_opt_in_preference = { @@ -163,7 +163,7 @@ resource "aws_backup_region_settings" "test" { ` } -func testAccRegionSettings3Config() string { +func testAccRegionSettingsConfig_3() string { return ` resource "aws_backup_region_settings" "test" { resource_type_opt_in_preference = { diff --git a/internal/service/backup/report_plan_data_source_test.go b/internal/service/backup/report_plan_data_source_test.go index 3cda02ce375..14749eabbf2 100644 --- a/internal/service/backup/report_plan_data_source_test.go +++ b/internal/service/backup/report_plan_data_source_test.go @@ -23,11 +23,11 @@ func TestAccBackupReportPlanDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccReportPlanDataSourceNonExistentConfig, + Config: testAccReportPlanDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`error reading Backup Report Plan`), }, { - Config: testAccReportPlanDataSourceConfig(rName, rName2), + Config: testAccReportPlanDataSourceConfig_basic(rName, rName2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "creation_time", resourceName, "creation_time"), @@ -48,13 +48,13 @@ func TestAccBackupReportPlanDataSource_basic(t *testing.T) { }) } -const testAccReportPlanDataSourceNonExistentConfig = ` +const testAccReportPlanDataSourceConfig_nonExistent = ` data "aws_backup_report_plan" "test" { name = "tf_acc_test_does_not_exist" } ` -func testAccReportPlanDataSourceConfig(rName, rName2 string) string { +func testAccReportPlanDataSourceConfig_basic(rName, rName2 string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/backup/report_plan_test.go b/internal/service/backup/report_plan_test.go index 326a6121d1c..bbac51d86a8 100644 --- a/internal/service/backup/report_plan_test.go +++ b/internal/service/backup/report_plan_test.go @@ -29,7 +29,7 @@ func TestAccBackupReportPlan_basic(t *testing.T) { CheckDestroy: testAccCheckReportPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccReportPlanConfig(rName, rName2, originalDescription), + Config: testAccReportPlanConfig_basic(rName, rName2, originalDescription), Check: resource.ComposeTestCheckFunc( testAccCheckReportPlanExists(resourceName, &reportPlan), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -52,7 +52,7 @@ func TestAccBackupReportPlan_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccReportPlanConfig(rName, rName2, updatedDescription), + Config: testAccReportPlanConfig_basic(rName, rName2, updatedDescription), Check: resource.ComposeTestCheckFunc( testAccCheckReportPlanExists(resourceName, &reportPlan), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -87,7 +87,7 @@ func TestAccBackupReportPlan_updateTags(t *testing.T) { CheckDestroy: testAccCheckReportPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccReportPlanConfig(rName, rName2, description), + Config: testAccReportPlanConfig_basic(rName, rName2, description), Check: resource.ComposeTestCheckFunc( testAccCheckReportPlanExists(resourceName, &reportPlan), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -110,7 +110,7 @@ func TestAccBackupReportPlan_updateTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccReportPlanConfigTags1(rName, rName2, description), + Config: testAccReportPlanConfig_tags1(rName, rName2, description), Check: resource.ComposeTestCheckFunc( testAccCheckReportPlanExists(resourceName, &reportPlan), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -134,7 +134,7 @@ func TestAccBackupReportPlan_updateTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccReportPlanConfigTags2(rName, rName2, description), + Config: testAccReportPlanConfig_tags2(rName, rName2, description), Check: resource.ComposeTestCheckFunc( testAccCheckReportPlanExists(resourceName, &reportPlan), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -171,7 +171,7 @@ func TestAccBackupReportPlan_updateReportDeliveryChannel(t *testing.T) { CheckDestroy: testAccCheckReportPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccReportPlanConfig(rName, rName2, description), + Config: testAccReportPlanConfig_basic(rName, rName2, description), Check: resource.ComposeTestCheckFunc( testAccCheckReportPlanExists(resourceName, &reportPlan), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -194,7 +194,7 @@ func TestAccBackupReportPlan_updateReportDeliveryChannel(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccReportPlanReportDeliveryChannelConfig(rName, rName2, description), + Config: testAccReportPlanConfig_deliveryChannel(rName, rName2, description), Check: resource.ComposeTestCheckFunc( testAccCheckReportPlanExists(resourceName, &reportPlan), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -230,7 +230,7 @@ func TestAccBackupReportPlan_disappears(t *testing.T) { CheckDestroy: testAccCheckReportPlanDestroy, Steps: []resource.TestStep{ { - Config: testAccReportPlanConfig(rName, rName2, description), + Config: testAccReportPlanConfig_basic(rName, rName2, description), Check: resource.ComposeTestCheckFunc( testAccCheckReportPlanExists(resourceName, &reportPlan), acctest.CheckResourceDisappears(acctest.Provider, tfbackup.ResourceReportPlan(), resourceName), @@ -320,7 +320,7 @@ resource "aws_s3_bucket_public_access_block" "test" { `, bucketName) } -func testAccReportPlanConfig(rName, rName2, label string) string { +func testAccReportPlanConfig_basic(rName, rName2, label string) string { return acctest.ConfigCompose(testAccReportPlanBaseConfig(rName), fmt.Sprintf(` resource "aws_backup_report_plan" "test" { name = %[1]q @@ -344,7 +344,7 @@ resource "aws_backup_report_plan" "test" { `, rName2, label)) } -func testAccReportPlanConfigTags1(rName, rName2, label string) string { +func testAccReportPlanConfig_tags1(rName, rName2, label string) string { return acctest.ConfigCompose(testAccReportPlanBaseConfig(rName), fmt.Sprintf(` resource "aws_backup_report_plan" "test" { name = %[1]q @@ -369,7 +369,7 @@ resource "aws_backup_report_plan" "test" { `, rName2, label)) } -func testAccReportPlanConfigTags2(rName, rName2, label string) string { +func testAccReportPlanConfig_tags2(rName, rName2, label string) string { return acctest.ConfigCompose(testAccReportPlanBaseConfig(rName), fmt.Sprintf(` resource "aws_backup_report_plan" "test" { name = %[1]q @@ -395,7 +395,7 @@ resource "aws_backup_report_plan" "test" { `, rName2, label)) } -func testAccReportPlanReportDeliveryChannelConfig(rName, rName2, label string) string { +func testAccReportPlanConfig_deliveryChannel(rName, rName2, label string) string { return acctest.ConfigCompose(testAccReportPlanBaseConfig(rName), fmt.Sprintf(` resource "aws_backup_report_plan" "test" { name = %[1]q diff --git a/internal/service/backup/selection.go b/internal/service/backup/selection.go index 0c804b70abf..c516c172713 100644 --- a/internal/service/backup/selection.go +++ b/internal/service/backup/selection.go @@ -184,9 +184,9 @@ func resourceSelectionCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).BackupConn selection := &backup.Selection{ - Conditions: expandBackupConditions(d.Get("condition").(*schema.Set).List()), + Conditions: expandConditions(d.Get("condition").(*schema.Set).List()), IamRoleArn: aws.String(d.Get("iam_role_arn").(string)), - ListOfTags: expandBackupConditionTags(d.Get("selection_tag").(*schema.Set).List()), + ListOfTags: expandConditionTags(d.Get("selection_tag").(*schema.Set).List()), NotResources: flex.ExpandStringSet(d.Get("not_resources").(*schema.Set)), Resources: flex.ExpandStringSet(d.Get("resources").(*schema.Set)), SelectionName: aws.String(d.Get("name").(string)), @@ -296,7 +296,7 @@ func resourceSelectionRead(d *schema.ResourceData, meta interface{}) error { d.Set("iam_role_arn", resp.BackupSelection.IamRoleArn) if conditions := resp.BackupSelection.Conditions; conditions != nil { - if err := d.Set("condition", flattenBackupConditions(conditions)); err != nil { + if err := d.Set("condition", flattenConditions(conditions)); err != nil { return fmt.Errorf("error setting conditions: %s", err) } } @@ -365,7 +365,7 @@ func resourceSelectionImportState(d *schema.ResourceData, meta interface{}) ([]* return []*schema.ResourceData{d}, nil } -func expandBackupConditionTags(tagList []interface{}) []*backup.Condition { +func expandConditionTags(tagList []interface{}) []*backup.Condition { conditions := []*backup.Condition{} for _, i := range tagList { @@ -382,22 +382,22 @@ func expandBackupConditionTags(tagList []interface{}) []*backup.Condition { return conditions } -func expandBackupConditions(conditionsList []interface{}) *backup.Conditions { +func expandConditions(conditionsList []interface{}) *backup.Conditions { conditions := &backup.Conditions{} for _, condition := range conditionsList { mCondition := condition.(map[string]interface{}) - if vStringEquals := expandBackupConditionParameters(mCondition["string_equals"].(*schema.Set).List()); len(vStringEquals) > 0 { + if vStringEquals := expandConditionParameters(mCondition["string_equals"].(*schema.Set).List()); len(vStringEquals) > 0 { conditions.StringEquals = vStringEquals } - if vStringNotEquals := expandBackupConditionParameters(mCondition["string_not_equals"].(*schema.Set).List()); len(vStringNotEquals) > 0 { + if vStringNotEquals := expandConditionParameters(mCondition["string_not_equals"].(*schema.Set).List()); len(vStringNotEquals) > 0 { conditions.StringNotEquals = vStringNotEquals } - if vStringLike := expandBackupConditionParameters(mCondition["string_like"].(*schema.Set).List()); len(vStringLike) > 0 { + if vStringLike := expandConditionParameters(mCondition["string_like"].(*schema.Set).List()); len(vStringLike) > 0 { conditions.StringLike = vStringLike } - if vStringNotLike := expandBackupConditionParameters(mCondition["string_not_like"].(*schema.Set).List()); len(vStringNotLike) > 0 { + if vStringNotLike := expandConditionParameters(mCondition["string_not_like"].(*schema.Set).List()); len(vStringNotLike) > 0 { conditions.StringNotLike = vStringNotLike } } @@ -405,7 +405,7 @@ func expandBackupConditions(conditionsList []interface{}) *backup.Conditions { return conditions } -func expandBackupConditionParameters(conditionParametersList []interface{}) []*backup.ConditionParameter { +func expandConditionParameters(conditionParametersList []interface{}) []*backup.ConditionParameter { conditionParameters := []*backup.ConditionParameter{} for _, i := range conditionParametersList { @@ -421,22 +421,22 @@ func expandBackupConditionParameters(conditionParametersList []interface{}) []*b return conditionParameters } -func flattenBackupConditions(conditions *backup.Conditions) *schema.Set { +func flattenConditions(conditions *backup.Conditions) *schema.Set { var vConditions []interface{} mCondition := map[string]interface{}{} - mCondition["string_equals"] = flattenBackupConditionParameters(conditions.StringEquals) - mCondition["string_not_equals"] = flattenBackupConditionParameters(conditions.StringNotEquals) - mCondition["string_like"] = flattenBackupConditionParameters(conditions.StringLike) - mCondition["string_not_like"] = flattenBackupConditionParameters(conditions.StringNotLike) + mCondition["string_equals"] = flattenConditionParameters(conditions.StringEquals) + mCondition["string_not_equals"] = flattenConditionParameters(conditions.StringNotEquals) + mCondition["string_like"] = flattenConditionParameters(conditions.StringLike) + mCondition["string_not_like"] = flattenConditionParameters(conditions.StringNotLike) vConditions = append(vConditions, mCondition) - return schema.NewSet(backupConditionsHash, vConditions) + return schema.NewSet(conditionsHash, vConditions) } -func backupConditionsHash(vCondition interface{}) int { +func conditionsHash(vCondition interface{}) int { var buf bytes.Buffer mCondition := vCondition.(map[string]interface{}) @@ -460,7 +460,7 @@ func backupConditionsHash(vCondition interface{}) int { return create.StringHashcode(buf.String()) } -func flattenBackupConditionParameters(conditionParameters []*backup.ConditionParameter) []interface{} { +func flattenConditionParameters(conditionParameters []*backup.ConditionParameter) []interface{} { if len(conditionParameters) == 0 { return nil } diff --git a/internal/service/backup/selection_test.go b/internal/service/backup/selection_test.go index e1806da31e1..4a06765642a 100644 --- a/internal/service/backup/selection_test.go +++ b/internal/service/backup/selection_test.go @@ -26,7 +26,7 @@ func TestAccBackupSelection_basic(t *testing.T) { CheckDestroy: testAccCheckSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigBasic(rName), + Config: testAccSelectionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSelectionExists(resourceName, &selection1), ), @@ -53,7 +53,7 @@ func TestAccBackupSelection_disappears(t *testing.T) { CheckDestroy: testAccCheckSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigBasic(rName), + Config: testAccSelectionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSelectionExists(resourceName, &selection1), acctest.CheckResourceDisappears(acctest.Provider, tfbackup.ResourceSelection(), resourceName), @@ -77,7 +77,7 @@ func TestAccBackupSelection_Disappears_backupPlan(t *testing.T) { CheckDestroy: testAccCheckSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigBasic(rName), + Config: testAccSelectionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSelectionExists(resourceName, &selection1), acctest.CheckResourceDisappears(acctest.Provider, tfbackup.ResourceSelection(), resourceName), @@ -101,7 +101,7 @@ func TestAccBackupSelection_withTags(t *testing.T) { CheckDestroy: testAccCheckSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigWithTags(rName), + Config: testAccSelectionConfig_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSelectionExists(resourceName, &selection1), resource.TestCheckResourceAttr(resourceName, "selection_tag.#", "2"), @@ -129,7 +129,7 @@ func TestAccBackupSelection_conditionsWithTags(t *testing.T) { CheckDestroy: testAccCheckSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigWithConditionsTags(rName), + Config: testAccSelectionConfig_conditionsTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSelectionExists(resourceName, &selection1), resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), @@ -161,7 +161,7 @@ func TestAccBackupSelection_withResources(t *testing.T) { CheckDestroy: testAccCheckSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigWithResources(rName), + Config: testAccSelectionConfig_resources(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSelectionExists(resourceName, &selection1), resource.TestCheckResourceAttr(resourceName, "resources.#", "2"), @@ -189,7 +189,7 @@ func TestAccBackupSelection_withNotResources(t *testing.T) { CheckDestroy: testAccCheckSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigWithNotResources(rName), + Config: testAccSelectionConfig_notResources(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSelectionExists(resourceName, &selection1), resource.TestCheckResourceAttr(resourceName, "not_resources.#", "1"), @@ -217,13 +217,13 @@ func TestAccBackupSelection_updateTag(t *testing.T) { CheckDestroy: testAccCheckSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigBasic(rName), + Config: testAccSelectionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSelectionExists(resourceName, &selection1), ), }, { - Config: testAccBackupSelectionConfigUpdateTag(rName), + Config: testAccSelectionConfig_updateTag(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSelectionExists(resourceName, &selection2), testAccCheckSelectionRecreated(t, &selection1, &selection2), @@ -314,7 +314,7 @@ func testAccSelectionImportStateIDFunc(resourceName string) resource.ImportState } } -func testAccBackupSelectionConfigBase(rName string) string { +func testAccSelectionConfig_base(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -338,9 +338,9 @@ resource "aws_backup_plan" "test" { `, rName) } -func testAccBackupSelectionConfigBasic(rName string) string { +func testAccSelectionConfig_basic(rName string) string { return acctest.ConfigCompose( - testAccBackupSelectionConfigBase(rName), + testAccSelectionConfig_base(rName), fmt.Sprintf(` resource "aws_backup_selection" "test" { plan_id = aws_backup_plan.test.id @@ -361,9 +361,9 @@ resource "aws_backup_selection" "test" { `, rName)) } -func testAccBackupSelectionConfigWithTags(rName string) string { +func testAccSelectionConfig_tags(rName string) string { return acctest.ConfigCompose( - testAccBackupSelectionConfigBase(rName), + testAccSelectionConfig_base(rName), fmt.Sprintf(` resource "aws_backup_selection" "test" { plan_id = aws_backup_plan.test.id @@ -390,9 +390,9 @@ resource "aws_backup_selection" "test" { `, rName)) } -func testAccBackupSelectionConfigWithConditionsTags(rName string) string { +func testAccSelectionConfig_conditionsTags(rName string) string { return acctest.ConfigCompose( - testAccBackupSelectionConfigBase(rName), + testAccSelectionConfig_base(rName), fmt.Sprintf(` resource "aws_backup_selection" "test" { plan_id = aws_backup_plan.test.id @@ -436,9 +436,9 @@ resource "aws_backup_selection" "test" { `, rName)) } -func testAccBackupSelectionConfigWithResources(rName string) string { +func testAccSelectionConfig_resources(rName string) string { return acctest.ConfigCompose( - testAccBackupSelectionConfigBase(rName), + testAccSelectionConfig_base(rName), fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -477,9 +477,9 @@ resource "aws_backup_selection" "test" { `, rName)) } -func testAccBackupSelectionConfigWithNotResources(rName string) string { +func testAccSelectionConfig_notResources(rName string) string { return acctest.ConfigCompose( - testAccBackupSelectionConfigBase(rName), + testAccSelectionConfig_base(rName), fmt.Sprintf(` resource "aws_backup_selection" "test" { plan_id = aws_backup_plan.test.id @@ -499,9 +499,9 @@ resource "aws_backup_selection" "test" { `, rName)) } -func testAccBackupSelectionConfigUpdateTag(rName string) string { +func testAccSelectionConfig_updateTag(rName string) string { return acctest.ConfigCompose( - testAccBackupSelectionConfigBase(rName), + testAccSelectionConfig_base(rName), fmt.Sprintf(` resource "aws_backup_selection" "test" { plan_id = aws_backup_plan.test.id diff --git a/internal/service/backup/sweep.go b/internal/service/backup/sweep.go index 537ce34531a..75ac33deec0 100644 --- a/internal/service/backup/sweep.go +++ b/internal/service/backup/sweep.go @@ -295,8 +295,14 @@ func sweepVaults(region string) error { for _, vault := range page.BackupVaultList { failedToDeleteRecoveryPoint := false name := aws.StringValue(vault.BackupVaultName) + + // Ignore Default and Automatic EFS Backup Vaults in region (cannot be deleted) + if name == "Default" || name == "aws/efs/automatic-backup-vault" { + log.Printf("[INFO] Skipping Backup Vault: %s", name) + continue + } input := &backup.ListRecoveryPointsByBackupVaultInput{ - BackupVaultName: aws.String(name), + BackupVaultName: vault.BackupVaultName, } err := conn.ListRecoveryPointsByBackupVaultPages(input, func(page *backup.ListRecoveryPointsByBackupVaultOutput, lastPage bool) bool { @@ -305,17 +311,15 @@ func sweepVaults(region string) error { } for _, recoveryPoint := range page.RecoveryPoints { - arn := aws.StringValue(recoveryPoint.RecoveryPointArn) - - log.Printf("[INFO] Deleting Recovery Point (%s) in Backup Vault (%s)", arn, name) _, err := conn.DeleteRecoveryPoint(&backup.DeleteRecoveryPointInput{ - BackupVaultName: aws.String(name), - RecoveryPointArn: aws.String(arn), + BackupVaultName: vault.BackupVaultName, + RecoveryPointArn: recoveryPoint.RecoveryPointArn, }) if err != nil { - log.Printf("[WARN] Failed to delete Recovery Point (%s) in Backup Vault (%s): %s", arn, name, err) + log.Printf("[WARN] Failed to delete Recovery Point (%s) in Backup Vault (%s): %s", aws.StringValue(recoveryPoint.RecoveryPointArn), name, err) failedToDeleteRecoveryPoint = true + return true } } @@ -326,12 +330,6 @@ func sweepVaults(region string) error { sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing Reovery Points in Backup Vault (%s) for %s: %w", name, region, err)) } - // Ignore Default and Automatic EFS Backup Vaults in region (cannot be deleted) - if name == "Default" || name == "aws/efs/automatic-backup-vault" { - log.Printf("[INFO] Skipping Backup Vault: %s", name) - continue - } - // Backup Vault deletion only supported when empty // Reference: https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteBackupVault.html if failedToDeleteRecoveryPoint { diff --git a/internal/service/backup/vault.go b/internal/service/backup/vault.go index 60233a7fc45..dd42d33c480 100644 --- a/internal/service/backup/vault.go +++ b/internal/service/backup/vault.go @@ -87,7 +87,7 @@ func resourceVaultRead(d *schema.ResourceData, meta interface{}) error { defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - output, err := FindBackupVaultByName(conn, d.Id()) + output, err := FindVaultByName(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Backup Vault (%s) not found, removing from state", d.Id()) diff --git a/internal/service/backup/vault_lock_configuration.go b/internal/service/backup/vault_lock_configuration.go index 9a52c84dcdc..d25aa3f1113 100644 --- a/internal/service/backup/vault_lock_configuration.go +++ b/internal/service/backup/vault_lock_configuration.go @@ -88,7 +88,7 @@ func resourceVaultLockConfigurationCreate(d *schema.ResourceData, meta interface func resourceVaultLockConfigurationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).BackupConn - output, err := FindBackupVaultByName(conn, d.Id()) + output, err := FindVaultByName(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Backup Vault Lock Configuration (%s) not found, removing from state", d.Id()) diff --git a/internal/service/backup/vault_lock_configuration_test.go b/internal/service/backup/vault_lock_configuration_test.go index aea9cdcd1d2..775823d3223 100644 --- a/internal/service/backup/vault_lock_configuration_test.go +++ b/internal/service/backup/vault_lock_configuration_test.go @@ -26,7 +26,7 @@ func TestAccBackupVaultLockConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckVaultLockConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultLockConfigurationConfigAll(rName), + Config: testAccVaultLockConfigurationConfig_all(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultLockConfigurationExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "changeable_for_days", "3"), @@ -57,7 +57,7 @@ func TestAccBackupVaultLockConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckVaultLockConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultLockConfigurationConfigAll(rName), + Config: testAccVaultLockConfigurationConfig_all(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultLockConfigurationExists(resourceName, &vault), acctest.CheckResourceDisappears(acctest.Provider, tfbackup.ResourceVaultLockConfiguration(), resourceName), @@ -75,7 +75,7 @@ func testAccCheckVaultLockConfigurationDestroy(s *terraform.State) error { continue } - _, err := tfbackup.FindBackupVaultByName(conn, rs.Primary.ID) + _, err := tfbackup.FindVaultByName(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -104,7 +104,7 @@ func testAccCheckVaultLockConfigurationExists(name string, vault *backup.Describ conn := acctest.Provider.Meta().(*conns.AWSClient).BackupConn - output, err := tfbackup.FindBackupVaultByName(conn, rs.Primary.ID) + output, err := tfbackup.FindVaultByName(conn, rs.Primary.ID) if err != nil { return err @@ -116,7 +116,7 @@ func testAccCheckVaultLockConfigurationExists(name string, vault *backup.Describ } } -func testAccBackupVaultLockConfigurationConfigAll(rName string) string { +func testAccVaultLockConfigurationConfig_all(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = %[1]q diff --git a/internal/service/backup/vault_notifications_test.go b/internal/service/backup/vault_notifications_test.go index ac219f24337..5919dd483f4 100644 --- a/internal/service/backup/vault_notifications_test.go +++ b/internal/service/backup/vault_notifications_test.go @@ -26,7 +26,7 @@ func TestAccBackupVaultNotification_basic(t *testing.T) { CheckDestroy: testAccCheckVaultNotificationDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultNotificationConfig(rName), + Config: testAccVaultNotificationsConfig_notification(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultNotificationExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "backup_vault_events.#", "2"), @@ -53,7 +53,7 @@ func TestAccBackupVaultNotification_disappears(t *testing.T) { CheckDestroy: testAccCheckVaultNotificationDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultNotificationConfig(rName), + Config: testAccVaultNotificationsConfig_notification(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultNotificationExists(resourceName, &vault), acctest.CheckResourceDisappears(acctest.Provider, tfbackup.ResourceVaultNotifications(), resourceName), @@ -109,7 +109,7 @@ func testAccCheckVaultNotificationExists(name string, vault *backup.GetBackupVau } } -func testAccBackupVaultNotificationConfig(rName string) string { +func testAccVaultNotificationsConfig_notification(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = %[1]q diff --git a/internal/service/backup/vault_policy.go b/internal/service/backup/vault_policy.go index f3bd33e0d14..3002118fde8 100644 --- a/internal/service/backup/vault_policy.go +++ b/internal/service/backup/vault_policy.go @@ -78,7 +78,7 @@ func resourceVaultPolicyPut(d *schema.ResourceData, meta interface{}) error { func resourceVaultPolicyRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).BackupConn - output, err := FindBackupVaultAccessPolicyByName(conn, d.Id()) + output, err := FindVaultAccessPolicyByName(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Backup Vault Policy (%s) not found, removing from state", d.Id()) diff --git a/internal/service/backup/vault_policy_test.go b/internal/service/backup/vault_policy_test.go index ab5666b862a..dc4214112db 100644 --- a/internal/service/backup/vault_policy_test.go +++ b/internal/service/backup/vault_policy_test.go @@ -27,7 +27,7 @@ func TestAccBackupVaultPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckVaultPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultPolicyConfig(rName), + Config: testAccVaultPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultPolicyExists(resourceName, &vault), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile("^{\"Id\":\"default\".+"))), @@ -38,7 +38,7 @@ func TestAccBackupVaultPolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupVaultPolicyConfigUpdated(rName), + Config: testAccVaultPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultPolicyExists(resourceName, &vault), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile("^{\"Id\":\"default\".+")), @@ -61,7 +61,7 @@ func TestAccBackupVaultPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckVaultPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultPolicyConfig(rName), + Config: testAccVaultPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultPolicyExists(resourceName, &vault), acctest.CheckResourceDisappears(acctest.Provider, tfbackup.ResourceVaultPolicy(), resourceName), @@ -85,7 +85,7 @@ func TestAccBackupVaultPolicy_Disappears_vault(t *testing.T) { CheckDestroy: testAccCheckVaultPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultPolicyConfig(rName), + Config: testAccVaultPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultPolicyExists(resourceName, &vault), acctest.CheckResourceDisappears(acctest.Provider, tfbackup.ResourceVault(), vaultResourceName), @@ -108,13 +108,13 @@ func TestAccBackupVaultPolicy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckVaultPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultPolicyConfig(rName), + Config: testAccVaultPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultPolicyExists(resourceName, &vault), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile("\"Version\":\"2012-10-17\""))), }, { - Config: testAccBackupVaultPolicyNewOrderConfig(rName), + Config: testAccVaultPolicyConfig_newOrder(rName), PlanOnly: true, }, }, @@ -129,7 +129,7 @@ func testAccCheckVaultPolicyDestroy(s *terraform.State) error { continue } - _, err := tfbackup.FindBackupVaultAccessPolicyByName(conn, rs.Primary.ID) + _, err := tfbackup.FindVaultAccessPolicyByName(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -158,7 +158,7 @@ func testAccCheckVaultPolicyExists(name string, vault *backup.GetBackupVaultAcce conn := acctest.Provider.Meta().(*conns.AWSClient).BackupConn - output, err := tfbackup.FindBackupVaultAccessPolicyByName(conn, rs.Primary.ID) + output, err := tfbackup.FindVaultAccessPolicyByName(conn, rs.Primary.ID) if err != nil { return err @@ -170,7 +170,7 @@ func testAccCheckVaultPolicyExists(name string, vault *backup.GetBackupVaultAcce } } -func testAccBackupVaultPolicyConfig(rName string) string { +func testAccVaultPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = %[1]q @@ -205,7 +205,7 @@ resource "aws_backup_vault_policy" "test" { `, rName) } -func testAccBackupVaultPolicyConfigUpdated(rName string) string { +func testAccVaultPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = %[1]q @@ -241,7 +241,7 @@ resource "aws_backup_vault_policy" "test" { `, rName) } -func testAccBackupVaultPolicyNewOrderConfig(rName string) string { +func testAccVaultPolicyConfig_newOrder(rName string) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = %[1]q diff --git a/internal/service/backup/vault_test.go b/internal/service/backup/vault_test.go index 68fdb509f45..56d2d498277 100644 --- a/internal/service/backup/vault_test.go +++ b/internal/service/backup/vault_test.go @@ -26,7 +26,7 @@ func TestAccBackupVault_basic(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultConfig(rInt), + Config: testAccVaultConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), ), @@ -52,7 +52,7 @@ func TestAccBackupVault_withKMSKey(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultWithKmsKey(rInt), + Config: testAccVaultConfig_kmsKey(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttrPair(resourceName, "kms_key_arn", "aws_kms_key.test", "arn"), @@ -79,7 +79,7 @@ func TestAccBackupVault_withTags(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultWithTags(rInt), + Config: testAccVaultConfig_tags(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -93,7 +93,7 @@ func TestAccBackupVault_withTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupVaultWithUpdateTags(rInt), + Config: testAccVaultConfig_updateTags(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "tags.%", "4"), @@ -104,7 +104,7 @@ func TestAccBackupVault_withTags(t *testing.T) { ), }, { - Config: testAccBackupVaultWithRemoveTags(rInt), + Config: testAccVaultConfig_removeTags(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -128,7 +128,7 @@ func TestAccBackupVault_disappears(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupVaultConfig(rInt), + Config: testAccVaultConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), acctest.CheckResourceDisappears(acctest.Provider, tfbackup.ResourceVault(), resourceName), @@ -146,7 +146,7 @@ func testAccCheckVaultDestroy(s *terraform.State) error { continue } - _, err := tfbackup.FindBackupVaultByName(conn, rs.Primary.ID) + _, err := tfbackup.FindVaultByName(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -175,7 +175,7 @@ func testAccCheckVaultExists(name string, vault *backup.DescribeBackupVaultOutpu conn := acctest.Provider.Meta().(*conns.AWSClient).BackupConn - output, err := tfbackup.FindBackupVaultByName(conn, rs.Primary.ID) + output, err := tfbackup.FindVaultByName(conn, rs.Primary.ID) if err != nil { return err @@ -203,7 +203,7 @@ func testAccPreCheck(t *testing.T) { } } -func testAccBackupVaultConfig(randInt int) string { +func testAccVaultConfig_basic(randInt int) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = "tf_acc_test_backup_vault_%d" @@ -211,7 +211,7 @@ resource "aws_backup_vault" "test" { `, randInt) } -func testAccBackupVaultWithKmsKey(randInt int) string { +func testAccVaultConfig_kmsKey(randInt int) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Test KMS Key for AWS Backup Vault" @@ -225,7 +225,7 @@ resource "aws_backup_vault" "test" { `, randInt) } -func testAccBackupVaultWithTags(randInt int) string { +func testAccVaultConfig_tags(randInt int) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = "tf_acc_test_backup_vault_%d" @@ -238,7 +238,7 @@ resource "aws_backup_vault" "test" { `, randInt) } -func testAccBackupVaultWithUpdateTags(randInt int) string { +func testAccVaultConfig_updateTags(randInt int) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = "tf_acc_test_backup_vault_%d" @@ -253,7 +253,7 @@ resource "aws_backup_vault" "test" { `, randInt) } -func testAccBackupVaultWithRemoveTags(randInt int) string { +func testAccVaultConfig_removeTags(randInt int) string { return fmt.Sprintf(` resource "aws_backup_vault" "test" { name = "tf_acc_test_backup_vault_%d" diff --git a/internal/service/batch/compute_environment.go b/internal/service/batch/compute_environment.go index 7960bb2a592..787562b387d 100644 --- a/internal/service/batch/compute_environment.go +++ b/internal/service/batch/compute_environment.go @@ -249,7 +249,7 @@ func resourceComputeEnvironmentCreate(d *schema.ResourceData, meta interface{}) } if v, ok := d.GetOk("compute_resources"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - input.ComputeResources = expandBatchComputeResource(v.([]interface{})[0].(map[string]interface{})) + input.ComputeResources = expandComputeResource(v.([]interface{})[0].(map[string]interface{})) } if v, ok := d.GetOk("state"); ok { @@ -306,7 +306,7 @@ func resourceComputeEnvironmentRead(d *schema.ResourceData, meta interface{}) er d.Set("type", computeEnvironmentType) if computeEnvironment.ComputeResources != nil { - if err := d.Set("compute_resources", []interface{}{flattenBatchComputeResource(computeEnvironment.ComputeResources)}); err != nil { + if err := d.Set("compute_resources", []interface{}{flattenComputeResource(computeEnvironment.ComputeResources)}); err != nil { return fmt.Errorf("error setting compute_resources: %w", err) } } else { @@ -459,7 +459,7 @@ func resourceComputeEnvironmentCustomizeDiff(_ context.Context, diff *schema.Res return nil } -func expandBatchComputeResource(tfMap map[string]interface{}) *batch.ComputeResource { +func expandComputeResource(tfMap map[string]interface{}) *batch.ComputeResource { if tfMap == nil { return nil } @@ -485,7 +485,7 @@ func expandBatchComputeResource(tfMap map[string]interface{}) *batch.ComputeReso } if v, ok := tfMap["ec2_configuration"].([]interface{}); ok && len(v) > 0 { - apiObject.Ec2Configuration = expandBatchEc2Configurations(v) + apiObject.Ec2Configuration = expandEC2Configurations(v) } if v, ok := tfMap["ec2_key_pair"].(string); ok && v != "" { @@ -505,7 +505,7 @@ func expandBatchComputeResource(tfMap map[string]interface{}) *batch.ComputeReso } if v, ok := tfMap["launch_template"].([]interface{}); ok && len(v) > 0 { - apiObject.LaunchTemplate = expandBatchLaunchTemplateSpecification(v[0].(map[string]interface{})) + apiObject.LaunchTemplate = expandLaunchTemplateSpecification(v[0].(map[string]interface{})) } if v, ok := tfMap["max_vcpus"].(int); ok && v != 0 { @@ -541,7 +541,7 @@ func expandBatchComputeResource(tfMap map[string]interface{}) *batch.ComputeReso return apiObject } -func expandBatchEc2Configuration(tfMap map[string]interface{}) *batch.Ec2Configuration { +func expandEC2Configuration(tfMap map[string]interface{}) *batch.Ec2Configuration { if tfMap == nil { return nil } @@ -559,7 +559,7 @@ func expandBatchEc2Configuration(tfMap map[string]interface{}) *batch.Ec2Configu return apiObject } -func expandBatchEc2Configurations(tfList []interface{}) []*batch.Ec2Configuration { +func expandEC2Configurations(tfList []interface{}) []*batch.Ec2Configuration { if len(tfList) == 0 { return nil } @@ -573,7 +573,7 @@ func expandBatchEc2Configurations(tfList []interface{}) []*batch.Ec2Configuratio continue } - apiObject := expandBatchEc2Configuration(tfMap) + apiObject := expandEC2Configuration(tfMap) if apiObject == nil { continue @@ -585,7 +585,7 @@ func expandBatchEc2Configurations(tfList []interface{}) []*batch.Ec2Configuratio return apiObjects } -func expandBatchLaunchTemplateSpecification(tfMap map[string]interface{}) *batch.LaunchTemplateSpecification { +func expandLaunchTemplateSpecification(tfMap map[string]interface{}) *batch.LaunchTemplateSpecification { if tfMap == nil { return nil } @@ -607,7 +607,7 @@ func expandBatchLaunchTemplateSpecification(tfMap map[string]interface{}) *batch return apiObject } -func flattenBatchComputeResource(apiObject *batch.ComputeResource) map[string]interface{} { +func flattenComputeResource(apiObject *batch.ComputeResource) map[string]interface{} { if apiObject == nil { return nil } @@ -627,7 +627,7 @@ func flattenBatchComputeResource(apiObject *batch.ComputeResource) map[string]in } if v := apiObject.Ec2Configuration; v != nil { - tfMap["ec2_configuration"] = flattenBatchEc2Configurations(v) + tfMap["ec2_configuration"] = flattenEC2Configurations(v) } if v := apiObject.Ec2KeyPair; v != nil { @@ -647,7 +647,7 @@ func flattenBatchComputeResource(apiObject *batch.ComputeResource) map[string]in } if v := apiObject.LaunchTemplate; v != nil { - tfMap["launch_template"] = []interface{}{flattenBatchLaunchTemplateSpecification(v)} + tfMap["launch_template"] = []interface{}{flattenLaunchTemplateSpecification(v)} } if v := apiObject.MaxvCpus; v != nil { @@ -681,7 +681,7 @@ func flattenBatchComputeResource(apiObject *batch.ComputeResource) map[string]in return tfMap } -func flattenBatchEc2Configuration(apiObject *batch.Ec2Configuration) map[string]interface{} { +func flattenEC2Configuration(apiObject *batch.Ec2Configuration) map[string]interface{} { if apiObject == nil { return nil } @@ -699,7 +699,7 @@ func flattenBatchEc2Configuration(apiObject *batch.Ec2Configuration) map[string] return tfMap } -func flattenBatchEc2Configurations(apiObjects []*batch.Ec2Configuration) []interface{} { +func flattenEC2Configurations(apiObjects []*batch.Ec2Configuration) []interface{} { if len(apiObjects) == 0 { return nil } @@ -711,13 +711,13 @@ func flattenBatchEc2Configurations(apiObjects []*batch.Ec2Configuration) []inter continue } - tfList = append(tfList, flattenBatchEc2Configuration(apiObject)) + tfList = append(tfList, flattenEC2Configuration(apiObject)) } return tfList } -func flattenBatchLaunchTemplateSpecification(apiObject *batch.LaunchTemplateSpecification) map[string]interface{} { +func flattenLaunchTemplateSpecification(apiObject *batch.LaunchTemplateSpecification) map[string]interface{} { if apiObject == nil { return nil } diff --git a/internal/service/batch/compute_environment_data_source_test.go b/internal/service/batch/compute_environment_data_source_test.go index 0ac9a4ff2a8..dc47059379b 100644 --- a/internal/service/batch/compute_environment_data_source_test.go +++ b/internal/service/batch/compute_environment_data_source_test.go @@ -21,7 +21,7 @@ func TestAccBatchComputeEnvironmentDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentDataSourceConfig(rName), + Config: testAccComputeEnvironmentDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "compute_environment_name", resourceName, "compute_environment_name"), @@ -36,7 +36,7 @@ func TestAccBatchComputeEnvironmentDataSource_basic(t *testing.T) { }) } -func testAccComputeEnvironmentDataSourceConfig(rName string) string { +func testAccComputeEnvironmentDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/batch/compute_environment_test.go b/internal/service/batch/compute_environment_test.go index 01cb1b4b48b..ba65c322c31 100644 --- a/internal/service/batch/compute_environment_test.go +++ b/internal/service/batch/compute_environment_test.go @@ -26,10 +26,10 @@ func TestAccBatchComputeEnvironment_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentBasicConfig(rName), + Config: testAccComputeEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -58,10 +58,10 @@ func TestAccBatchComputeEnvironment_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentBasicConfig(rName), + Config: testAccComputeEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceDisappears(acctest.Provider, tfbatch.ResourceComputeEnvironment(), resourceName), @@ -81,10 +81,10 @@ func TestAccBatchComputeEnvironment_nameGenerated(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentNameGeneratedConfig(rName), + Config: testAccComputeEnvironmentConfig_nameGenerated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), create.TestCheckResourceAttrNameGenerated(resourceName, "compute_environment_name"), @@ -109,10 +109,10 @@ func TestAccBatchComputeEnvironment_namePrefix(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentNamePrefixConfig(rName), + Config: testAccComputeEnvironmentConfig_namePrefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), create.TestCheckResourceAttrNameFromPrefix(resourceName, "compute_environment_name", rName), @@ -141,10 +141,10 @@ func TestAccBatchComputeEnvironment_createEC2(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentEC2Config(rName), + Config: testAccComputeEnvironmentConfig_ec2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -209,10 +209,10 @@ func TestAccBatchComputeEnvironment_CreateEC2DesiredVCPUsEC2KeyPairImageID_compu PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentEC2WithDesiredVcpusEC2KeyPairImageIdAndComputeResourcesTagsConfig(rName, publicKey), + Config: testAccComputeEnvironmentConfig_ec2DesiredVCPUsEC2KeyPairImageIDAndResourcesTags(rName, publicKey), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -270,10 +270,10 @@ func TestAccBatchComputeEnvironment_createSpot(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentSpotConfig(rName), + Config: testAccComputeEnvironmentConfig_spot(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -330,10 +330,10 @@ func TestAccBatchComputeEnvironment_CreateSpotAllocationStrategy_bidPercentage(t PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentSpotWithAllocationStrategyAndBidPercentageConfig(rName), + Config: testAccComputeEnvironmentConfig_spotAllocationStrategyAndBidPercentage(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -388,10 +388,10 @@ func TestAccBatchComputeEnvironment_createFargate(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentFargateConfig(rName), + Config: testAccComputeEnvironmentConfig_fargate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -445,10 +445,10 @@ func TestAccBatchComputeEnvironment_createFargateSpot(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentFargateSpotConfig(rName), + Config: testAccComputeEnvironmentConfig_fargateSpot(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -500,10 +500,10 @@ func TestAccBatchComputeEnvironment_updateState(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentStateConfig(rName, "ENABLED"), + Config: testAccComputeEnvironmentConfig_state(rName, "ENABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -520,7 +520,7 @@ func TestAccBatchComputeEnvironment_updateState(t *testing.T) { ), }, { - Config: testAccComputeEnvironmentStateConfig(rName, "disabled"), + Config: testAccComputeEnvironmentConfig_state(rName, "disabled"), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -558,10 +558,10 @@ func TestAccBatchComputeEnvironment_updateServiceRole(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentFargateConfig(rName), + Config: testAccComputeEnvironmentConfig_fargate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -595,7 +595,7 @@ func TestAccBatchComputeEnvironment_updateServiceRole(t *testing.T) { ), }, { - Config: testAccComputeEnvironmentFargateUpdatedServiceRoleConfig(rName), + Config: testAccComputeEnvironmentConfig_fargateUpdatedServiceRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -652,10 +652,10 @@ func TestAccBatchComputeEnvironment_defaultServiceRole(t *testing.T) { }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentFargateDefaultServiceRoleConfig(rName), + Config: testAccComputeEnvironmentConfig_fargateDefaultServiceRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -710,10 +710,10 @@ func TestAccBatchComputeEnvironment_ComputeResources_minVCPUs(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentComputeResourcesMaxVcpusMinVcpusConfig(rName, 4, 0), + Config: testAccComputeEnvironmentConfig_resourcesMaxVCPUsMinVCPUs(rName, 4, 0), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -748,7 +748,7 @@ func TestAccBatchComputeEnvironment_ComputeResources_minVCPUs(t *testing.T) { ), }, { - Config: testAccComputeEnvironmentComputeResourcesMaxVcpusMinVcpusConfig(rName, 4, 4), + Config: testAccComputeEnvironmentConfig_resourcesMaxVCPUsMinVCPUs(rName, 4, 4), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -783,7 +783,7 @@ func TestAccBatchComputeEnvironment_ComputeResources_minVCPUs(t *testing.T) { ), }, { - Config: testAccComputeEnvironmentComputeResourcesMaxVcpusMinVcpusConfig(rName, 4, 2), + Config: testAccComputeEnvironmentConfig_resourcesMaxVCPUsMinVCPUs(rName, 4, 2), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -839,10 +839,10 @@ func TestAccBatchComputeEnvironment_ComputeResources_maxVCPUs(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentComputeResourcesMaxVcpusMinVcpusConfig(rName, 4, 0), + Config: testAccComputeEnvironmentConfig_resourcesMaxVCPUsMinVCPUs(rName, 4, 0), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -877,7 +877,7 @@ func TestAccBatchComputeEnvironment_ComputeResources_maxVCPUs(t *testing.T) { ), }, { - Config: testAccComputeEnvironmentComputeResourcesMaxVcpusMinVcpusConfig(rName, 8, 0), + Config: testAccComputeEnvironmentConfig_resourcesMaxVCPUsMinVCPUs(rName, 8, 0), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -912,7 +912,7 @@ func TestAccBatchComputeEnvironment_ComputeResources_maxVCPUs(t *testing.T) { ), }, { - Config: testAccComputeEnvironmentComputeResourcesMaxVcpusMinVcpusConfig(rName, 2, 0), + Config: testAccComputeEnvironmentConfig_resourcesMaxVCPUsMinVCPUs(rName, 2, 0), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -969,10 +969,10 @@ func TestAccBatchComputeEnvironment_ec2Configuration(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentEC2Configuration(rName), + Config: testAccComputeEnvironmentConfig_ec2Configuration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -1032,10 +1032,10 @@ func TestAccBatchComputeEnvironment_launchTemplate(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentLaunchTemplateConfig(rName), + Config: testAccComputeEnvironmentConfig_launchTemplate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -1096,10 +1096,10 @@ func TestAccBatchComputeEnvironment_updateLaunchTemplate(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentUpdateLaunchTemplateInExistingComputeEnvironment(rName, "$Default"), + Config: testAccComputeEnvironmentConfig_updateLaunchTemplateInExisting(rName, "$Default"), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -1137,7 +1137,7 @@ func TestAccBatchComputeEnvironment_updateLaunchTemplate(t *testing.T) { ), }, { - Config: testAccComputeEnvironmentUpdateLaunchTemplateInExistingComputeEnvironment(rName, "$Latest"), + Config: testAccComputeEnvironmentConfig_updateLaunchTemplateInExisting(rName, "$Latest"), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -1198,10 +1198,10 @@ func TestAccBatchComputeEnvironment_UpdateSecurityGroupsAndSubnets_fargate(t *te PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentFargateConfig(rName), + Config: testAccComputeEnvironmentConfig_fargate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -1235,7 +1235,7 @@ func TestAccBatchComputeEnvironment_UpdateSecurityGroupsAndSubnets_fargate(t *te ), }, { - Config: testAccComputeEnvironmentFargateUpdatedSecurityGroupsAndSubnetsConfig(rName), + Config: testAccComputeEnvironmentConfig_fargateUpdatedSecurityGroupsAndSubnets(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("compute-environment/%s", rName)), @@ -1287,10 +1287,10 @@ func TestAccBatchComputeEnvironment_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentTags1Config(rName, "key1", "value1"), + Config: testAccComputeEnvironmentConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1303,7 +1303,7 @@ func TestAccBatchComputeEnvironment_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccComputeEnvironmentTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccComputeEnvironmentConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1312,7 +1312,7 @@ func TestAccBatchComputeEnvironment_tags(t *testing.T) { ), }, { - Config: testAccComputeEnvironmentTags1Config(rName, "key2", "value2"), + Config: testAccComputeEnvironmentConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckComputeEnvironmentExists(resourceName, &ce), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1330,10 +1330,10 @@ func TestAccBatchComputeEnvironment_createUnmanagedWithComputeResources(t *testi PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentUnmanagedWithComputeResourcesConfig(rName), + Config: testAccComputeEnvironmentConfig_unmanagedResources(rName), ExpectError: regexp.MustCompile("no `compute_resources` can be specified when `type` is \"UNMANAGED\""), }, }, @@ -1349,10 +1349,10 @@ func TestAccBatchComputeEnvironment_createEC2WithoutComputeResources(t *testing. PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentEC2WithoutComputeResourcesConfig(rName), + Config: testAccComputeEnvironmentConfig_ec2NoResources(rName), ExpectError: regexp.MustCompile(`computeResources must be provided for a MANAGED compute environment`), }, }, @@ -1366,17 +1366,17 @@ func TestAccBatchComputeEnvironment_createSpotWithoutIAMFleetRole(t *testing.T) PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + CheckDestroy: testAccCheckComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccComputeEnvironmentSpotWithoutIAMFleetRoleConfig(rName), + Config: testAccComputeEnvironmentConfig_spotNoIAMFleetRole(rName), ExpectError: regexp.MustCompile(`ComputeResources.spotIamFleetRole cannot not be null or empty`), }, }, }) } -func testAccCheckBatchComputeEnvironmentDestroy(s *terraform.State) error { +func testAccCheckComputeEnvironmentDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).BatchConn for _, rs := range s.RootModule().Resources { @@ -1543,7 +1543,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccComputeEnvironmentBasicConfig(rName string) string { +func testAccComputeEnvironmentConfig_basic(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1557,7 +1557,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentNameGeneratedConfig(rName string) string { +func testAccComputeEnvironmentConfig_nameGenerated(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), ` @@ -1569,7 +1569,7 @@ resource "aws_batch_compute_environment" "test" { `) } -func testAccComputeEnvironmentNamePrefixConfig(rName string) string { +func testAccComputeEnvironmentConfig_namePrefix(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1583,7 +1583,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentEC2Config(rName string) string { +func testAccComputeEnvironmentConfig_ec2(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1612,10 +1612,10 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentEC2WithDesiredVcpusEC2KeyPairImageIdAndComputeResourcesTagsConfig(rName, publicKey string) string { +func testAccComputeEnvironmentConfig_ec2DesiredVCPUsEC2KeyPairImageIDAndResourcesTags(rName, publicKey string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_batch_compute_environment" "test" { compute_environment_name = %[1]q @@ -1656,7 +1656,7 @@ resource "aws_key_pair" "test" { `, rName, publicKey)) } -func testAccComputeEnvironmentFargateConfig(rName string) string { +func testAccComputeEnvironmentConfig_fargate(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1681,7 +1681,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentFargateDefaultServiceRoleConfig(rName string) string { +func testAccComputeEnvironmentConfig_fargateDefaultServiceRole(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1704,7 +1704,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentFargateUpdatedServiceRoleConfig(rName string) string { +func testAccComputeEnvironmentConfig_fargateUpdatedServiceRole(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1751,7 +1751,7 @@ resource "aws_iam_role_policy_attachment" "batch_service_2" { `, rName)) } -func testAccComputeEnvironmentFargateSpotConfig(rName string) string { +func testAccComputeEnvironmentConfig_fargateSpot(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1776,7 +1776,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentSpotConfig(rName string) string { +func testAccComputeEnvironmentConfig_spot(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1807,7 +1807,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentSpotWithAllocationStrategyAndBidPercentageConfig(rName string) string { +func testAccComputeEnvironmentConfig_spotAllocationStrategyAndBidPercentage(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1840,7 +1840,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentStateConfig(rName string, state string) string { +func testAccComputeEnvironmentConfig_state(rName string, state string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1855,7 +1855,7 @@ resource "aws_batch_compute_environment" "test" { `, rName, state)) } -func testAccComputeEnvironmentComputeResourcesMaxVcpusMinVcpusConfig(rName string, maxVcpus int, minVcpus int) string { +func testAccComputeEnvironmentConfig_resourcesMaxVCPUsMinVCPUs(rName string, maxVcpus int, minVcpus int) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1883,7 +1883,7 @@ resource "aws_batch_compute_environment" "test" { `, rName, maxVcpus, minVcpus)) } -func testAccComputeEnvironmentFargateUpdatedSecurityGroupsAndSubnetsConfig(rName string) string { +func testAccComputeEnvironmentConfig_fargateUpdatedSecurityGroupsAndSubnets(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1936,7 +1936,7 @@ resource "aws_subnet" "test_2" { `, rName)) } -func testAccComputeEnvironmentEC2WithoutComputeResourcesConfig(rName string) string { +func testAccComputeEnvironmentConfig_ec2NoResources(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1950,7 +1950,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentUnmanagedWithComputeResourcesConfig(rName string) string { +func testAccComputeEnvironmentConfig_unmanagedResources(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -1980,7 +1980,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentSpotWithoutIAMFleetRoleConfig(rName string) string { +func testAccComputeEnvironmentConfig_spotNoIAMFleetRole(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -2010,7 +2010,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentLaunchTemplateConfig(rName string) string { +func testAccComputeEnvironmentConfig_launchTemplate(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -2050,7 +2050,7 @@ resource "aws_batch_compute_environment" "test" { `, rName)) } -func testAccComputeEnvironmentUpdateLaunchTemplateInExistingComputeEnvironment(rName string, version string) string { +func testAccComputeEnvironmentConfig_updateLaunchTemplateInExisting(rName string, version string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -2091,7 +2091,7 @@ resource "aws_batch_compute_environment" "test" { `, rName, version)) } -func testAccComputeEnvironmentTags1Config(rName string, tagKey1, tagValue1 string) string { +func testAccComputeEnvironmentConfig_tags1(rName string, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -2109,7 +2109,7 @@ resource "aws_batch_compute_environment" "test" { `, rName, tagKey1, tagValue1)) } -func testAccComputeEnvironmentTags2Config(rName string, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccComputeEnvironmentConfig_tags2(rName string, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), fmt.Sprintf(` @@ -2128,10 +2128,10 @@ resource "aws_batch_compute_environment" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccComputeEnvironmentEC2Configuration(rName string) string { +func testAccComputeEnvironmentConfig_ec2Configuration(rName string) string { return acctest.ConfigCompose( testAccComputeEnvironmentBaseConfig(rName), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_batch_compute_environment" "test" { compute_environment_name = %[1]q diff --git a/internal/service/batch/container_properties_test.go b/internal/service/batch/container_properties_test.go index 17201bda2ea..78ad840bb8a 100644 --- a/internal/service/batch/container_properties_test.go +++ b/internal/service/batch/container_properties_test.go @@ -6,7 +6,7 @@ import ( tfbatch "github.com/hashicorp/terraform-provider-aws/internal/service/batch" ) -func TestEquivalentBatchContainerPropertiesJSON(t *testing.T) { +func TestEquivalentContainerPropertiesJSON(t *testing.T) { testCases := []struct { Name string ApiJson string diff --git a/internal/service/batch/job_definition.go b/internal/service/batch/job_definition.go index 1de1714a9f9..3175235a0de 100644 --- a/internal/service/batch/job_definition.go +++ b/internal/service/batch/job_definition.go @@ -187,7 +187,7 @@ func resourceJobDefinitionCreate(d *schema.ResourceData, meta interface{}) error } if v, ok := d.GetOk("container_properties"); ok { - props, err := expandBatchJobContainerProperties(v.(string)) + props, err := expandJobContainerProperties(v.(string)) if err != nil { return err } @@ -204,7 +204,7 @@ func resourceJobDefinitionCreate(d *schema.ResourceData, meta interface{}) error } if v, ok := d.GetOk("retry_strategy"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - input.RetryStrategy = expandBatchRetryStrategy(v.([]interface{})[0].(map[string]interface{})) + input.RetryStrategy = expandRetryStrategy(v.([]interface{})[0].(map[string]interface{})) } if len(tags) > 0 { @@ -212,7 +212,7 @@ func resourceJobDefinitionCreate(d *schema.ResourceData, meta interface{}) error } if v, ok := d.GetOk("timeout"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - input.Timeout = expandBatchJobTimeout(v.([]interface{})[0].(map[string]interface{})) + input.Timeout = expandJobTimeout(v.([]interface{})[0].(map[string]interface{})) } output, err := conn.RegisterJobDefinition(input) @@ -245,7 +245,7 @@ func resourceJobDefinitionRead(d *schema.ResourceData, meta interface{}) error { d.Set("arn", jobDefinition.JobDefinitionArn) - containerProperties, err := flattenBatchContainerProperties(jobDefinition.ContainerProperties) + containerProperties, err := flattenContainerProperties(jobDefinition.ContainerProperties) if err != nil { return fmt.Errorf("error converting Batch Container Properties to JSON: %w", err) @@ -261,7 +261,7 @@ func resourceJobDefinitionRead(d *schema.ResourceData, meta interface{}) error { d.Set("propagate_tags", jobDefinition.PropagateTags) if jobDefinition.RetryStrategy != nil { - if err := d.Set("retry_strategy", []interface{}{flattenBatchRetryStrategy(jobDefinition.RetryStrategy)}); err != nil { + if err := d.Set("retry_strategy", []interface{}{flattenRetryStrategy(jobDefinition.RetryStrategy)}); err != nil { return fmt.Errorf("error setting retry_strategy: %w", err) } } else { @@ -280,7 +280,7 @@ func resourceJobDefinitionRead(d *schema.ResourceData, meta interface{}) error { } if jobDefinition.Timeout != nil { - if err := d.Set("timeout", []interface{}{flattenBatchJobTimeout(jobDefinition.Timeout)}); err != nil { + if err := d.Set("timeout", []interface{}{flattenJobTimeout(jobDefinition.Timeout)}); err != nil { return fmt.Errorf("error setting timeout: %w", err) } } else { @@ -323,14 +323,14 @@ func resourceJobDefinitionDelete(d *schema.ResourceData, meta interface{}) error func validJobContainerProperties(v interface{}, k string) (ws []string, errors []error) { value := v.(string) - _, err := expandBatchJobContainerProperties(value) + _, err := expandJobContainerProperties(value) if err != nil { errors = append(errors, fmt.Errorf("AWS Batch Job container_properties is invalid: %s", err)) } return } -func expandBatchJobContainerProperties(rawProps string) (*batch.ContainerProperties, error) { +func expandJobContainerProperties(rawProps string) (*batch.ContainerProperties, error) { var props *batch.ContainerProperties err := json.Unmarshal([]byte(rawProps), &props) @@ -342,7 +342,7 @@ func expandBatchJobContainerProperties(rawProps string) (*batch.ContainerPropert } // Convert batch.ContainerProperties object into its JSON representation -func flattenBatchContainerProperties(containerProperties *batch.ContainerProperties) (string, error) { +func flattenContainerProperties(containerProperties *batch.ContainerProperties) (string, error) { b, err := jsonutil.BuildJSON(containerProperties) if err != nil { @@ -361,7 +361,7 @@ func expandJobDefinitionParameters(params map[string]interface{}) map[string]*st return jobParams } -func expandBatchRetryStrategy(tfMap map[string]interface{}) *batch.RetryStrategy { +func expandRetryStrategy(tfMap map[string]interface{}) *batch.RetryStrategy { if tfMap == nil { return nil } @@ -373,13 +373,13 @@ func expandBatchRetryStrategy(tfMap map[string]interface{}) *batch.RetryStrategy } if v, ok := tfMap["evaluate_on_exit"].([]interface{}); ok && len(v) > 0 { - apiObject.EvaluateOnExit = expandBatchEvaluateOnExits(v) + apiObject.EvaluateOnExit = expandEvaluateOnExits(v) } return apiObject } -func expandBatchEvaluateOnExit(tfMap map[string]interface{}) *batch.EvaluateOnExit { +func expandEvaluateOnExit(tfMap map[string]interface{}) *batch.EvaluateOnExit { if tfMap == nil { return nil } @@ -405,7 +405,7 @@ func expandBatchEvaluateOnExit(tfMap map[string]interface{}) *batch.EvaluateOnEx return apiObject } -func expandBatchEvaluateOnExits(tfList []interface{}) []*batch.EvaluateOnExit { +func expandEvaluateOnExits(tfList []interface{}) []*batch.EvaluateOnExit { if len(tfList) == 0 { return nil } @@ -419,7 +419,7 @@ func expandBatchEvaluateOnExits(tfList []interface{}) []*batch.EvaluateOnExit { continue } - apiObject := expandBatchEvaluateOnExit(tfMap) + apiObject := expandEvaluateOnExit(tfMap) if apiObject == nil { continue @@ -431,7 +431,7 @@ func expandBatchEvaluateOnExits(tfList []interface{}) []*batch.EvaluateOnExit { return apiObjects } -func flattenBatchRetryStrategy(apiObject *batch.RetryStrategy) map[string]interface{} { +func flattenRetryStrategy(apiObject *batch.RetryStrategy) map[string]interface{} { if apiObject == nil { return nil } @@ -443,13 +443,13 @@ func flattenBatchRetryStrategy(apiObject *batch.RetryStrategy) map[string]interf } if v := apiObject.EvaluateOnExit; v != nil { - tfMap["evaluate_on_exit"] = flattenBatchEvaluateOnExits(v) + tfMap["evaluate_on_exit"] = flattenEvaluateOnExits(v) } return tfMap } -func flattenBatchEvaluateOnExit(apiObject *batch.EvaluateOnExit) map[string]interface{} { +func flattenEvaluateOnExit(apiObject *batch.EvaluateOnExit) map[string]interface{} { if apiObject == nil { return nil } @@ -475,7 +475,7 @@ func flattenBatchEvaluateOnExit(apiObject *batch.EvaluateOnExit) map[string]inte return tfMap } -func flattenBatchEvaluateOnExits(apiObjects []*batch.EvaluateOnExit) []interface{} { +func flattenEvaluateOnExits(apiObjects []*batch.EvaluateOnExit) []interface{} { if len(apiObjects) == 0 { return nil } @@ -487,13 +487,13 @@ func flattenBatchEvaluateOnExits(apiObjects []*batch.EvaluateOnExit) []interface continue } - tfList = append(tfList, flattenBatchEvaluateOnExit(apiObject)) + tfList = append(tfList, flattenEvaluateOnExit(apiObject)) } return tfList } -func expandBatchJobTimeout(tfMap map[string]interface{}) *batch.JobTimeout { +func expandJobTimeout(tfMap map[string]interface{}) *batch.JobTimeout { if tfMap == nil { return nil } @@ -507,7 +507,7 @@ func expandBatchJobTimeout(tfMap map[string]interface{}) *batch.JobTimeout { return apiObject } -func flattenBatchJobTimeout(apiObject *batch.JobTimeout) map[string]interface{} { +func flattenJobTimeout(apiObject *batch.JobTimeout) map[string]interface{} { if apiObject == nil { return nil } diff --git a/internal/service/batch/job_definition_test.go b/internal/service/batch/job_definition_test.go index afe78b30754..fe83ce66795 100644 --- a/internal/service/batch/job_definition_test.go +++ b/internal/service/batch/job_definition_test.go @@ -27,12 +27,12 @@ func TestAccBatchJobDefinition_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobDefinitionDestroy, + CheckDestroy: testAccCheckJobDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobDefinitionConfigName(rName), + Config: testAccJobDefinitionConfig_name(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionExists(resourceName, &jd), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "batch", regexp.MustCompile(fmt.Sprintf(`job-definition/%s:\d+`, rName))), resource.TestCheckResourceAttrSet(resourceName, "container_properties"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -64,12 +64,12 @@ func TestAccBatchJobDefinition_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobDefinitionDestroy, + CheckDestroy: testAccCheckJobDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobDefinitionConfigName(rName), + Config: testAccJobDefinitionConfig_name(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionExists(resourceName, &jd), acctest.CheckResourceDisappears(acctest.Provider, tfbatch.ResourceJobDefinition(), resourceName), ), ExpectNonEmptyPlan: true, @@ -87,12 +87,12 @@ func TestAccBatchJobDefinition_PlatformCapabilities_ec2(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobDefinitionDestroy, + CheckDestroy: testAccCheckJobDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobDefinitionConfigCapabilitiesEC2(rName), + Config: testAccJobDefinitionConfig_capabilitiesEC2(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionExists(resourceName, &jd), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "batch", regexp.MustCompile(fmt.Sprintf(`job-definition/%s:\d+`, rName))), resource.TestCheckResourceAttrSet(resourceName, "container_properties"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -125,12 +125,12 @@ func TestAccBatchJobDefinition_PlatformCapabilitiesFargate_containerPropertiesDe PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobDefinitionDestroy, + CheckDestroy: testAccCheckJobDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobDefinitionConfigCapabilitiesFargateContainerPropertiesDefaults(rName), + Config: testAccJobDefinitionConfig_capabilitiesFargateContainerPropertiesDefaults(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionExists(resourceName, &jd), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "batch", regexp.MustCompile(fmt.Sprintf(`job-definition/%s:\d+`, rName))), resource.TestCheckResourceAttrSet(resourceName, "container_properties"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -163,12 +163,12 @@ func TestAccBatchJobDefinition_PlatformCapabilities_fargate(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobDefinitionDestroy, + CheckDestroy: testAccCheckJobDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobDefinitionConfigCapabilitiesFargate(rName), + Config: testAccJobDefinitionConfig_capabilitiesFargate(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionExists(resourceName, &jd), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "batch", regexp.MustCompile(fmt.Sprintf(`job-definition/%s:\d+`, rName))), resource.TestCheckResourceAttrSet(resourceName, "container_properties"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -240,13 +240,13 @@ func TestAccBatchJobDefinition_ContainerProperties_advanced(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobDefinitionDestroy, + CheckDestroy: testAccCheckJobDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobDefinitionConfigContainerPropertiesAdvanced(rName), + Config: testAccJobDefinitionConfig_containerPropertiesAdvanced(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), - testAccCheckBatchJobDefinitionAttributes(&jd, &compare), + testAccCheckJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionAttributes(&jd, &compare), ), }, { @@ -267,19 +267,19 @@ func TestAccBatchJobDefinition_updateForcesNewResource(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobDefinitionDestroy, + CheckDestroy: testAccCheckJobDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobDefinitionConfigContainerPropertiesAdvanced(rName), + Config: testAccJobDefinitionConfig_containerPropertiesAdvanced(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &before), - testAccCheckBatchJobDefinitionAttributes(&before, nil), + testAccCheckJobDefinitionExists(resourceName, &before), + testAccCheckJobDefinitionAttributes(&before, nil), ), }, { - Config: testAccBatchJobDefinitionConfigContainerPropertiesAdvancedUpdate(rName), + Config: testAccJobDefinitionConfig_containerPropertiesAdvancedUpdate(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &after), + testAccCheckJobDefinitionExists(resourceName, &after), testAccCheckJobDefinitionRecreated(t, &before, &after), ), }, @@ -301,12 +301,12 @@ func TestAccBatchJobDefinition_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobDefinitionDestroy, + CheckDestroy: testAccCheckJobDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobDefinitionConfigTags1(rName, "key1", "value1"), + Config: testAccJobDefinitionConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionExists(resourceName, &jd), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), @@ -317,18 +317,18 @@ func TestAccBatchJobDefinition_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBatchJobDefinitionConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccJobDefinitionConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionExists(resourceName, &jd), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { - Config: testAccBatchJobDefinitionConfigTags1(rName, "key2", "value2"), + Config: testAccJobDefinitionConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionExists(resourceName, &jd), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), @@ -346,12 +346,12 @@ func TestAccBatchJobDefinition_propagateTags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobDefinitionDestroy, + CheckDestroy: testAccCheckJobDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobDefinitionPropagateTags(rName), + Config: testAccJobDefinitionConfig_propagateTags(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobDefinitionExists(resourceName, &jd), + testAccCheckJobDefinitionExists(resourceName, &jd), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "batch", regexp.MustCompile(fmt.Sprintf(`job-definition/%s:\d+`, rName))), resource.TestCheckResourceAttrSet(resourceName, "container_properties"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -369,7 +369,7 @@ func TestAccBatchJobDefinition_propagateTags(t *testing.T) { }) } -func testAccCheckBatchJobDefinitionExists(n string, jd *batch.JobDefinition) resource.TestCheckFunc { +func testAccCheckJobDefinitionExists(n string, jd *batch.JobDefinition) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -394,7 +394,7 @@ func testAccCheckBatchJobDefinitionExists(n string, jd *batch.JobDefinition) res } } -func testAccCheckBatchJobDefinitionAttributes(jd *batch.JobDefinition, compare *batch.JobDefinition) resource.TestCheckFunc { +func testAccCheckJobDefinitionAttributes(jd *batch.JobDefinition, compare *batch.JobDefinition) resource.TestCheckFunc { return func(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "aws_batch_job_definition" { @@ -431,7 +431,7 @@ func testAccCheckJobDefinitionRecreated(t *testing.T, before, after *batch.JobDe } } -func testAccCheckBatchJobDefinitionDestroy(s *terraform.State) error { +func testAccCheckJobDefinitionDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).BatchConn for _, rs := range s.RootModule().Resources { @@ -454,7 +454,7 @@ func testAccCheckBatchJobDefinitionDestroy(s *terraform.State) error { return nil } -func testAccBatchJobDefinitionConfigContainerPropertiesAdvanced(rName string) string { +func testAccJobDefinitionConfig_containerPropertiesAdvanced(rName string) string { return fmt.Sprintf(` resource "aws_batch_job_definition" "test" { name = %[1]q @@ -515,7 +515,7 @@ CONTAINER_PROPERTIES `, rName) } -func testAccBatchJobDefinitionConfigContainerPropertiesAdvancedUpdate(rName string) string { +func testAccJobDefinitionConfig_containerPropertiesAdvancedUpdate(rName string) string { return fmt.Sprintf(` resource "aws_batch_job_definition" "test" { name = %[1]q @@ -558,7 +558,7 @@ CONTAINER_PROPERTIES `, rName) } -func testAccBatchJobDefinitionConfigName(rName string) string { +func testAccJobDefinitionConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_batch_job_definition" "test" { container_properties = jsonencode({ @@ -573,7 +573,7 @@ resource "aws_batch_job_definition" "test" { `, rName) } -func testAccBatchJobDefinitionConfigCapabilitiesEC2(rName string) string { +func testAccJobDefinitionConfig_capabilitiesEC2(rName string) string { return fmt.Sprintf(` resource "aws_batch_job_definition" "test" { name = %[1]q @@ -593,7 +593,7 @@ resource "aws_batch_job_definition" "test" { `, rName) } -func testAccBatchJobDefinitionConfigCapabilitiesFargateContainerPropertiesDefaults(rName string) string { +func testAccJobDefinitionConfig_capabilitiesFargateContainerPropertiesDefaults(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -640,7 +640,7 @@ CONTAINER_PROPERTIES `, rName) } -func testAccBatchJobDefinitionConfigCapabilitiesFargate(rName string) string { +func testAccJobDefinitionConfig_capabilitiesFargate(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -694,7 +694,7 @@ CONTAINER_PROPERTIES `, rName) } -func testAccBatchJobDefinitionConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccJobDefinitionConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_batch_job_definition" "test" { container_properties = jsonencode({ @@ -713,7 +713,7 @@ resource "aws_batch_job_definition" "test" { `, rName, tagKey1, tagValue1) } -func testAccBatchJobDefinitionConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccJobDefinitionConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_batch_job_definition" "test" { container_properties = jsonencode({ @@ -733,7 +733,7 @@ resource "aws_batch_job_definition" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccBatchJobDefinitionPropagateTags(rName string) string { +func testAccJobDefinitionConfig_propagateTags(rName string) string { return fmt.Sprintf(` resource "aws_batch_job_definition" "test" { container_properties = jsonencode({ diff --git a/internal/service/batch/job_queue.go b/internal/service/batch/job_queue.go index 6f7db914baa..c7b937d8444 100644 --- a/internal/service/batch/job_queue.go +++ b/internal/service/batch/job_queue.go @@ -96,7 +96,7 @@ func resourceJobQueueCreate(d *schema.ResourceData, meta interface{}) error { stateConf := &resource.StateChangeConf{ Pending: []string{batch.JQStatusCreating, batch.JQStatusUpdating}, Target: []string{batch.JQStatusValid}, - Refresh: batchJobQueueRefreshStatusFunc(conn, name), + Refresh: jobQueueRefreshStatusFunc(conn, name), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -198,7 +198,7 @@ func resourceJobQueueUpdate(d *schema.ResourceData, meta interface{}) error { stateConf := &resource.StateChangeConf{ Pending: []string{batch.JQStatusUpdating}, Target: []string{batch.JQStatusValid}, - Refresh: batchJobQueueRefreshStatusFunc(conn, name), + Refresh: jobQueueRefreshStatusFunc(conn, name), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -261,7 +261,7 @@ func DeleteJobQueue(jobQueue string, conn *batch.Batch) error { stateChangeConf := &resource.StateChangeConf{ Pending: []string{batch.JQStateDisabled, batch.JQStatusDeleting}, Target: []string{batch.JQStatusDeleted}, - Refresh: batchJobQueueRefreshStatusFunc(conn, jobQueue), + Refresh: jobQueueRefreshStatusFunc(conn, jobQueue), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -283,7 +283,7 @@ func DisableJobQueue(jobQueue string, conn *batch.Batch) error { stateChangeConf := &resource.StateChangeConf{ Pending: []string{batch.JQStatusUpdating}, Target: []string{batch.JQStatusValid}, - Refresh: batchJobQueueRefreshStatusFunc(conn, jobQueue), + Refresh: jobQueueRefreshStatusFunc(conn, jobQueue), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -314,7 +314,7 @@ func GetJobQueue(conn *batch.Batch, sn string) (*batch.JobQueueDetail, error) { return nil, nil } -func batchJobQueueRefreshStatusFunc(conn *batch.Batch, sn string) resource.StateRefreshFunc { +func jobQueueRefreshStatusFunc(conn *batch.Batch, sn string) resource.StateRefreshFunc { return func() (interface{}, string, error) { ce, err := GetJobQueue(conn, sn) if err != nil { diff --git a/internal/service/batch/job_queue_data_source_test.go b/internal/service/batch/job_queue_data_source_test.go index 5bf0baa0442..a513ee85b78 100644 --- a/internal/service/batch/job_queue_data_source_test.go +++ b/internal/service/batch/job_queue_data_source_test.go @@ -21,7 +21,7 @@ func TestAccBatchJobQueueDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccJobQueueDataSourceConfigBasic(rName), + Config: testAccJobQueueDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "compute_environment_order.#", resourceName, "compute_environments.#"), @@ -47,7 +47,7 @@ func TestAccBatchJobQueueDataSource_schedulingPolicy(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccJobQueueDataSourceConfigSchedulingPolicy(rName), + Config: testAccJobQueueDataSourceConfig_schedulingPolicy(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "compute_environment_order.#", resourceName, "compute_environments.#"), @@ -163,7 +163,7 @@ resource "aws_batch_compute_environment" "sample" { `, rName) } -func testAccJobQueueDataSourceConfigBasic(rName string) string { +func testAccJobQueueDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( testAccJobQueueDataSourceConfigBase(rName), fmt.Sprintf(` @@ -187,7 +187,7 @@ data "aws_batch_job_queue" "by_name" { `, rName)) } -func testAccJobQueueDataSourceConfigSchedulingPolicy(rName string) string { +func testAccJobQueueDataSourceConfig_schedulingPolicy(rName string) string { return acctest.ConfigCompose( testAccJobQueueDataSourceConfigBase(rName), fmt.Sprintf(` diff --git a/internal/service/batch/job_queue_test.go b/internal/service/batch/job_queue_test.go index d7a2c7b9a20..a972bcca490 100644 --- a/internal/service/batch/job_queue_test.go +++ b/internal/service/batch/job_queue_test.go @@ -26,12 +26,12 @@ func TestAccBatchJobQueue_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobQueueDestroy, + CheckDestroy: testAccCheckJobQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobQueueConfigState(rName, batch.JQStateEnabled), + Config: testAccJobQueueConfig_state(rName, batch.JQStateEnabled), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue1), + testAccCheckJobQueueExists(resourceName, &jobQueue1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "batch", fmt.Sprintf("job-queue/%s", rName)), resource.TestCheckResourceAttr(resourceName, "compute_environments.#", "1"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -61,10 +61,10 @@ func TestAccBatchJobQueue_disappears(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobQueueConfigState(rName, batch.JQStateEnabled), + Config: testAccJobQueueConfig_state(rName, batch.JQStateEnabled), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue1), - testAccCheckBatchJobQueueDisappears(&jobQueue1), + testAccCheckJobQueueExists(resourceName, &jobQueue1), + testAccCheckJobQueueDisappears(&jobQueue1), ), ExpectNonEmptyPlan: true, }, @@ -82,13 +82,13 @@ func TestAccBatchJobQueue_ComputeEnvironments_externalOrderUpdate(t *testing.T) PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobQueueDestroy, + CheckDestroy: testAccCheckJobQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobQueueConfigState(rName, batch.JQStateEnabled), + Config: testAccJobQueueConfig_state(rName, batch.JQStateEnabled), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue1), - testAccCheckBatchJobQueueComputeEnvironmentOrderUpdate(&jobQueue1), + testAccCheckJobQueueExists(resourceName, &jobQueue1), + testAccCheckJobQueueComputeEnvironmentOrderUpdate(&jobQueue1), ), }, { @@ -109,19 +109,19 @@ func TestAccBatchJobQueue_priority(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobQueueDestroy, + CheckDestroy: testAccCheckJobQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobQueueConfigPriority(rName, 1), + Config: testAccJobQueueConfig_priority(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue1), + testAccCheckJobQueueExists(resourceName, &jobQueue1), resource.TestCheckResourceAttr(resourceName, "priority", "1"), ), }, { - Config: testAccBatchJobQueueConfigPriority(rName, 2), + Config: testAccJobQueueConfig_priority(rName, 2), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue2), + testAccCheckJobQueueExists(resourceName, &jobQueue2), resource.TestCheckResourceAttr(resourceName, "priority", "2"), ), }, @@ -145,13 +145,13 @@ func TestAccBatchJobQueue_schedulingPolicy(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobQueueDestroy, + CheckDestroy: testAccCheckJobQueueDestroy, Steps: []resource.TestStep{ { // last variable selects the scheduling policy's arn. In this case, the first scheduling policy's arn. - Config: testAccBatchJobQueueConfigSchedulingPolicy(rName, schedulingPolicyName1, schedulingPolicyName2, "first"), + Config: testAccJobQueueConfig_schedulingPolicy(rName, schedulingPolicyName1, schedulingPolicyName2, "first"), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue1), + testAccCheckJobQueueExists(resourceName, &jobQueue1), resource.TestCheckResourceAttrSet(resourceName, "scheduling_policy_arn"), ), }, @@ -162,9 +162,9 @@ func TestAccBatchJobQueue_schedulingPolicy(t *testing.T) { }, { // test switching the scheduling_policy_arn by changing the last variable to select the second scheduling policy's arn. - Config: testAccBatchJobQueueConfigSchedulingPolicy(rName, schedulingPolicyName1, schedulingPolicyName2, "second"), + Config: testAccJobQueueConfig_schedulingPolicy(rName, schedulingPolicyName1, schedulingPolicyName2, "second"), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue2), + testAccCheckJobQueueExists(resourceName, &jobQueue2), resource.TestCheckResourceAttrSet(resourceName, "scheduling_policy_arn"), ), }, @@ -181,19 +181,19 @@ func TestAccBatchJobQueue_state(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobQueueDestroy, + CheckDestroy: testAccCheckJobQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobQueueConfigState(rName, batch.JQStateDisabled), + Config: testAccJobQueueConfig_state(rName, batch.JQStateDisabled), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue1), + testAccCheckJobQueueExists(resourceName, &jobQueue1), resource.TestCheckResourceAttr(resourceName, "state", batch.JQStateDisabled), ), }, { - Config: testAccBatchJobQueueConfigState(rName, batch.JQStateEnabled), + Config: testAccJobQueueConfig_state(rName, batch.JQStateEnabled), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue2), + testAccCheckJobQueueExists(resourceName, &jobQueue2), resource.TestCheckResourceAttr(resourceName, "state", batch.JQStateEnabled), ), }, @@ -215,12 +215,12 @@ func TestAccBatchJobQueue_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchJobQueueDestroy, + CheckDestroy: testAccCheckJobQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchJobQueueConfigTags1(rName, "key1", "value1"), + Config: testAccJobQueueConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue), + testAccCheckJobQueueExists(resourceName, &jobQueue), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), @@ -231,18 +231,18 @@ func TestAccBatchJobQueue_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBatchJobQueueConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccJobQueueConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue), + testAccCheckJobQueueExists(resourceName, &jobQueue), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { - Config: testAccBatchJobQueueConfigTags1(rName, "key2", "value2"), + Config: testAccJobQueueConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchJobQueueExists(resourceName, &jobQueue), + testAccCheckJobQueueExists(resourceName, &jobQueue), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), @@ -251,7 +251,7 @@ func TestAccBatchJobQueue_tags(t *testing.T) { }) } -func testAccCheckBatchJobQueueExists(n string, jq *batch.JobQueueDetail) resource.TestCheckFunc { +func testAccCheckJobQueueExists(n string, jq *batch.JobQueueDetail) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] log.Printf("State: %#v", s.RootModule().Resources) @@ -278,7 +278,7 @@ func testAccCheckBatchJobQueueExists(n string, jq *batch.JobQueueDetail) resourc } } -func testAccCheckBatchJobQueueDestroy(s *terraform.State) error { +func testAccCheckJobQueueDestroy(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "aws_batch_job_queue" { continue @@ -295,7 +295,7 @@ func testAccCheckBatchJobQueueDestroy(s *terraform.State) error { return nil } -func testAccCheckBatchJobQueueDisappears(jobQueue *batch.JobQueueDetail) resource.TestCheckFunc { +func testAccCheckJobQueueDisappears(jobQueue *batch.JobQueueDetail) resource.TestCheckFunc { return func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).BatchConn name := aws.StringValue(jobQueue.JobQueueName) @@ -309,11 +309,11 @@ func testAccCheckBatchJobQueueDisappears(jobQueue *batch.JobQueueDetail) resourc } } -// testAccCheckBatchJobQueueComputeEnvironmentOrderUpdate simulates the change of a Compute Environment Order +// testAccCheckJobQueueComputeEnvironmentOrderUpdate simulates the change of a Compute Environment Order // An external update to the Batch Job Queue (e.g. console) may trigger changes to the value of the Order // parameter that do not affect the operation of the queue itself, but the resource logic needs to handle. // For example, Terraform may set a single Compute Environment with Order 0, but the console updates it to 1. -func testAccCheckBatchJobQueueComputeEnvironmentOrderUpdate(jobQueue *batch.JobQueueDetail) resource.TestCheckFunc { +func testAccCheckJobQueueComputeEnvironmentOrderUpdate(jobQueue *batch.JobQueueDetail) resource.TestCheckFunc { return func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).BatchConn @@ -343,7 +343,7 @@ func testAccCheckBatchJobQueueComputeEnvironmentOrderUpdate(jobQueue *batch.JobQ } } -func testAccBatchJobQueueConfigBase(rName string) string { +func testAccJobQueueConfigBase(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -441,9 +441,9 @@ resource "aws_batch_compute_environment" "test" { `, rName) } -func testAccBatchJobQueueConfigPriority(rName string, priority int) string { +func testAccJobQueueConfig_priority(rName string, priority int) string { return acctest.ConfigCompose( - testAccBatchJobQueueConfigBase(rName), + testAccJobQueueConfigBase(rName), fmt.Sprintf(` resource "aws_batch_job_queue" "test" { compute_environments = [aws_batch_compute_environment.test.arn] @@ -454,7 +454,7 @@ resource "aws_batch_job_queue" "test" { `, rName, priority)) } -func testAccBatchJobQueueSchedulingPolicy(rName string, rName2 string) string { +func testAccJobQueueSchedulingPolicy(rName string, rName2 string) string { return fmt.Sprintf(` resource "aws_batch_scheduling_policy" "test1" { name = %[1]q @@ -486,10 +486,10 @@ resource "aws_batch_scheduling_policy" "test2" { `, rName, rName2) } -func testAccBatchJobQueueConfigSchedulingPolicy(rName string, schedulingPolicyName1 string, schedulingPolicyName2 string, selectSchedulingPolicy string) string { +func testAccJobQueueConfig_schedulingPolicy(rName string, schedulingPolicyName1 string, schedulingPolicyName2 string, selectSchedulingPolicy string) string { return acctest.ConfigCompose( - testAccBatchJobQueueConfigBase(rName), - testAccBatchJobQueueSchedulingPolicy(schedulingPolicyName1, schedulingPolicyName2), + testAccJobQueueConfigBase(rName), + testAccJobQueueSchedulingPolicy(schedulingPolicyName1, schedulingPolicyName2), fmt.Sprintf(` locals { select_scheduling_policy = %[2]q @@ -505,9 +505,9 @@ resource "aws_batch_job_queue" "test" { `, rName, selectSchedulingPolicy)) } -func testAccBatchJobQueueConfigState(rName string, state string) string { +func testAccJobQueueConfig_state(rName string, state string) string { return acctest.ConfigCompose( - testAccBatchJobQueueConfigBase(rName), + testAccJobQueueConfigBase(rName), fmt.Sprintf(` resource "aws_batch_job_queue" "test" { compute_environments = [aws_batch_compute_environment.test.arn] @@ -518,9 +518,9 @@ resource "aws_batch_job_queue" "test" { `, rName, state)) } -func testAccBatchJobQueueConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccJobQueueConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccBatchJobQueueConfigBase(rName), + testAccJobQueueConfigBase(rName), fmt.Sprintf(` resource "aws_batch_job_queue" "test" { compute_environments = [aws_batch_compute_environment.test.arn] @@ -535,9 +535,9 @@ resource "aws_batch_job_queue" "test" { `, rName, tagKey1, tagValue1)) } -func testAccBatchJobQueueConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccJobQueueConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccBatchJobQueueConfigBase(rName), + testAccJobQueueConfigBase(rName), fmt.Sprintf(` resource "aws_batch_job_queue" "test" { compute_environments = [aws_batch_compute_environment.test.arn] diff --git a/internal/service/batch/scheduling_policy_data_source_test.go b/internal/service/batch/scheduling_policy_data_source_test.go index 0ef5d0fbdeb..0615bd6bb34 100644 --- a/internal/service/batch/scheduling_policy_data_source_test.go +++ b/internal/service/batch/scheduling_policy_data_source_test.go @@ -21,7 +21,7 @@ func TestAccBatchSchedulingPolicyDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccBatchSchedulingPolicyDataSourceConfig_Basic(rName), + Config: testAccSchedulingPolicyDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "fair_share_policy.#", resourceName, "fair_share_policy.#"), @@ -36,7 +36,7 @@ func TestAccBatchSchedulingPolicyDataSource_basic(t *testing.T) { }) } -func testAccBatchSchedulingPolicyDataSourceConfig(rName string) string { +func testAccSchedulingPolicyDataSourceConfig(rName string) string { return fmt.Sprintf(` resource "aws_batch_scheduling_policy" "test" { name = %[1]q @@ -63,8 +63,8 @@ resource "aws_batch_scheduling_policy" "test" { `, rName) } -func testAccBatchSchedulingPolicyDataSourceConfig_Basic(rName string) string { - return fmt.Sprintf(testAccBatchSchedulingPolicyDataSourceConfig(rName) + ` +func testAccSchedulingPolicyDataSourceConfig_basic(rName string) string { + return fmt.Sprintf(testAccSchedulingPolicyDataSourceConfig(rName) + ` data "aws_batch_scheduling_policy" "test" { arn = aws_batch_scheduling_policy.test.arn } diff --git a/internal/service/batch/scheduling_policy_test.go b/internal/service/batch/scheduling_policy_test.go index dfe07394887..e55e6ed57f4 100644 --- a/internal/service/batch/scheduling_policy_test.go +++ b/internal/service/batch/scheduling_policy_test.go @@ -24,12 +24,12 @@ func TestAccBatchSchedulingPolicy_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchSchedulingPolicyDestroy, + CheckDestroy: testAccCheckSchedulingPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchSchedulingPolicyConfigBasic(rName), + Config: testAccSchedulingPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchSchedulingPolicyExists(resourceName, &schedulingPolicy1), + testAccCheckSchedulingPolicyExists(resourceName, &schedulingPolicy1), resource.TestCheckResourceAttrSet(resourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "fair_share_policy.#", "1"), resource.TestCheckResourceAttr(resourceName, "fair_share_policy.0.compute_reservation", "1"), @@ -46,9 +46,9 @@ func TestAccBatchSchedulingPolicy_basic(t *testing.T) { }, { // add one more share_distribution block - Config: testAccBatchSchedulingPolicyConfigBasic2(rName), + Config: testAccSchedulingPolicyConfig_basic2(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchSchedulingPolicyExists(resourceName, &schedulingPolicy1), + testAccCheckSchedulingPolicyExists(resourceName, &schedulingPolicy1), resource.TestCheckResourceAttrSet(resourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "fair_share_policy.#", "1"), resource.TestCheckResourceAttr(resourceName, "fair_share_policy.0.compute_reservation", "1"), @@ -71,12 +71,12 @@ func TestAccBatchSchedulingPolicy_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, batch.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBatchSchedulingPolicyDestroy, + CheckDestroy: testAccCheckSchedulingPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBatchSchedulingPolicyConfigBasic(rName), + Config: testAccSchedulingPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBatchSchedulingPolicyExists(resourceName, &schedulingPolicy1), + testAccCheckSchedulingPolicyExists(resourceName, &schedulingPolicy1), acctest.CheckResourceDisappears(acctest.Provider, tfbatch.ResourceSchedulingPolicy(), resourceName), ), ExpectNonEmptyPlan: true, @@ -85,7 +85,7 @@ func TestAccBatchSchedulingPolicy_disappears(t *testing.T) { }) } -func testAccCheckBatchSchedulingPolicyExists(n string, sp *batch.SchedulingPolicyDetail) resource.TestCheckFunc { +func testAccCheckSchedulingPolicyExists(n string, sp *batch.SchedulingPolicyDetail) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] log.Printf("State: %#v", s.RootModule().Resources) @@ -111,7 +111,7 @@ func testAccCheckBatchSchedulingPolicyExists(n string, sp *batch.SchedulingPolic } } -func testAccCheckBatchSchedulingPolicyDestroy(s *terraform.State) error { +func testAccCheckSchedulingPolicyDestroy(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "aws_batch_scheduling_policy" { continue @@ -149,7 +149,7 @@ func GetSchedulingPolicyNoContext(conn *batch.Batch, arn string) (*batch.Schedul return nil, nil } -func testAccBatchSchedulingPolicyConfigBasic(rName string) string { +func testAccSchedulingPolicyConfig_basic(rName string) string { return acctest.ConfigCompose( fmt.Sprintf(` resource "aws_batch_scheduling_policy" "test" { @@ -172,7 +172,7 @@ resource "aws_batch_scheduling_policy" "test" { `, rName)) } -func testAccBatchSchedulingPolicyConfigBasic2(rName string) string { +func testAccSchedulingPolicyConfig_basic2(rName string) string { return acctest.ConfigCompose( fmt.Sprintf(` resource "aws_batch_scheduling_policy" "test" { diff --git a/internal/service/budgets/budget.go b/internal/service/budgets/budget.go index edcc540e56b..a67eab0b67a 100644 --- a/internal/service/budgets/budget.go +++ b/internal/service/budgets/budget.go @@ -228,7 +228,7 @@ func ResourceBudget() *schema.Resource { func resourceBudgetCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).BudgetsConn - budget, err := expandBudgetsBudgetUnmarshal(d) + budget, err := expandBudgetUnmarshal(d) if err != nil { return fmt.Errorf("failed unmarshalling budget: %v", err) } @@ -303,7 +303,7 @@ func resourceBudgetRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting cost_filters: %w", err) } - if err := d.Set("cost_types", flattenBudgetsCostTypes(budget.CostTypes)); err != nil { + if err := d.Set("cost_types", flattenCostTypes(budget.CostTypes)); err != nil { return fmt.Errorf("error setting cost_types: %w", err) } @@ -393,7 +393,7 @@ func resourceBudgetUpdate(d *schema.ResourceData, meta interface{}) error { return err } - budget, err := expandBudgetsBudgetUnmarshal(d) + budget, err := expandBudgetUnmarshal(d) if err != nil { return fmt.Errorf("could not create budget: %v", err) } @@ -505,7 +505,7 @@ func resourceBudgetNotificationsUpdate(d *schema.ResourceData, meta interface{}) return nil } -func flattenBudgetsCostTypes(costTypes *budgets.CostTypes) []map[string]interface{} { +func flattenCostTypes(costTypes *budgets.CostTypes) []map[string]interface{} { if costTypes == nil { return []map[string]interface{}{} } @@ -556,7 +556,7 @@ func convertCostFiltersToStringMap(costFilters map[string][]*string) map[string] return convertedCostFilters } -func expandBudgetsBudgetUnmarshal(d *schema.ResourceData) (*budgets.Budget, error) { +func expandBudgetUnmarshal(d *schema.ResourceData) (*budgets.Budget, error) { budgetName := d.Get("name").(string) budgetType := d.Get("budget_type").(string) budgetLimitAmount := d.Get("limit_amount").(string) @@ -607,13 +607,13 @@ func expandBudgetsBudgetUnmarshal(d *schema.ResourceData) (*budgets.Budget, erro } if v, ok := d.GetOk("cost_types"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - budget.CostTypes = expandBudgetsCostTypes(v.([]interface{})[0].(map[string]interface{})) + budget.CostTypes = expandCostTypes(v.([]interface{})[0].(map[string]interface{})) } return budget, nil } -func expandBudgetsCostTypes(tfMap map[string]interface{}) *budgets.CostTypes { +func expandCostTypes(tfMap map[string]interface{}) *budgets.CostTypes { if tfMap == nil { return nil } @@ -675,15 +675,15 @@ func expandBudgetNotificationsUnmarshal(notificationsRaw []interface{}) ([]*budg NotificationType: aws.String(notificationType), } - emailSubscribers := expandBudgetSubscribers(notificationRaw["subscriber_email_addresses"], budgets.SubscriptionTypeEmail) - snsSubscribers := expandBudgetSubscribers(notificationRaw["subscriber_sns_topic_arns"], budgets.SubscriptionTypeSns) + emailSubscribers := expandSubscribers(notificationRaw["subscriber_email_addresses"], budgets.SubscriptionTypeEmail) + snsSubscribers := expandSubscribers(notificationRaw["subscriber_sns_topic_arns"], budgets.SubscriptionTypeSns) subscribersForNotifications[i] = append(emailSubscribers, snsSubscribers...) } return notifications, subscribersForNotifications } -func expandBudgetSubscribers(rawList interface{}, subscriptionType string) []*budgets.Subscriber { +func expandSubscribers(rawList interface{}, subscriptionType string) []*budgets.Subscriber { result := make([]*budgets.Subscriber, 0) addrs := flex.ExpandStringSet(rawList.(*schema.Set)) for _, addr := range addrs { diff --git a/internal/service/budgets/budget_action_test.go b/internal/service/budgets/budget_action_test.go index 716b37dd272..9e3d130ad25 100644 --- a/internal/service/budgets/budget_action_test.go +++ b/internal/service/budgets/budget_action_test.go @@ -27,7 +27,7 @@ func TestAccBudgetsBudgetAction_basic(t *testing.T) { CheckDestroy: testAccBudgetActionDestroy, Steps: []resource.TestStep{ { - Config: testAccBudgetActionBasicConfig(rName), + Config: testAccBudgetActionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccBudgetActionExists(resourceName, &conf), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "budgets", regexp.MustCompile(fmt.Sprintf(`budget/%s/action/.+`, rName))), @@ -67,7 +67,7 @@ func TestAccBudgetsBudgetAction_disappears(t *testing.T) { CheckDestroy: testAccBudgetActionDestroy, Steps: []resource.TestStep{ { - Config: testAccBudgetActionBasicConfig(rName), + Config: testAccBudgetActionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccBudgetActionExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfbudgets.ResourceBudgetAction(), resourceName), @@ -139,7 +139,7 @@ func testAccBudgetActionDestroy(s *terraform.State) error { return nil } -func testAccBudgetActionBasicConfig(rName string) string { +func testAccBudgetActionConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_iam_policy" "test" { name = %[1]q diff --git a/internal/service/budgets/budget_test.go b/internal/service/budgets/budget_test.go index 418883bf05c..0eea9461735 100644 --- a/internal/service/budgets/budget_test.go +++ b/internal/service/budgets/budget_test.go @@ -29,7 +29,7 @@ func TestAccBudgetsBudget_basic(t *testing.T) { CheckDestroy: testAccBudgetDestroy, Steps: []resource.TestStep{ { - Config: testAccBudgetConfigDeprecated(rName), + Config: testAccBudgetConfig_deprecated(rName), Check: resource.ComposeTestCheckFunc( testAccBudgetExists(resourceName, &budget), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -72,7 +72,7 @@ func TestAccBudgetsBudget_Name_generated(t *testing.T) { CheckDestroy: testAccBudgetDestroy, Steps: []resource.TestStep{ { - Config: testAccBudgetNameGeneratedConfig(), + Config: testAccBudgetConfig_nameGenerated(), Check: resource.ComposeTestCheckFunc( testAccBudgetExists(resourceName, &budget), resource.TestCheckResourceAttr(resourceName, "budget_type", "RI_COVERAGE"), @@ -114,7 +114,7 @@ func TestAccBudgetsBudget_namePrefix(t *testing.T) { CheckDestroy: testAccBudgetDestroy, Steps: []resource.TestStep{ { - Config: testAccBudgetNamePrefixConfig("tf-acc-test-prefix-"), + Config: testAccBudgetConfig_namePrefix("tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccBudgetExists(resourceName, &budget), resource.TestCheckResourceAttr(resourceName, "budget_type", "SAVINGS_PLANS_UTILIZATION"), @@ -151,7 +151,7 @@ func TestAccBudgetsBudget_disappears(t *testing.T) { CheckDestroy: testAccBudgetDestroy, Steps: []resource.TestStep{ { - Config: testAccBudgetConfigDeprecated(rName), + Config: testAccBudgetConfig_deprecated(rName), Check: resource.ComposeTestCheckFunc( testAccBudgetExists(resourceName, &budget), acctest.CheckResourceDisappears(acctest.Provider, tfbudgets.ResourceBudget(), resourceName), @@ -184,7 +184,7 @@ func TestAccBudgetsBudget_costTypes(t *testing.T) { CheckDestroy: testAccBudgetDestroy, Steps: []resource.TestStep{ { - Config: testAccBudgetCostTypesConfig(rName, startDate1, endDate1), + Config: testAccBudgetConfig_costTypes(rName, startDate1, endDate1), Check: resource.ComposeTestCheckFunc( testAccBudgetExists(resourceName, &budget), resource.TestCheckResourceAttr(resourceName, "budget_type", "COST"), @@ -224,7 +224,7 @@ func TestAccBudgetsBudget_costTypes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBudgetCostTypesUpdatedConfig(rName, startDate2, endDate2), + Config: testAccBudgetConfig_costTypesUpdated(rName, startDate2, endDate2), Check: resource.ComposeTestCheckFunc( testAccBudgetExists(resourceName, &budget), resource.TestCheckResourceAttr(resourceName, "budget_type", "COST"), @@ -280,7 +280,7 @@ func TestAccBudgetsBudget_notifications(t *testing.T) { CheckDestroy: testAccBudgetDestroy, Steps: []resource.TestStep{ { - Config: testAccBudgetNotificationsConfig(rName, emailAddress1, emailAddress2), + Config: testAccBudgetConfig_notifications(rName, emailAddress1, emailAddress2), Check: resource.ComposeTestCheckFunc( testAccBudgetExists(resourceName, &budget), resource.TestCheckResourceAttr(resourceName, "budget_type", "USAGE"), @@ -318,7 +318,7 @@ func TestAccBudgetsBudget_notifications(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBudgetNotificationsUpdatedConfig(rName, emailAddress3), + Config: testAccBudgetConfig_notificationsUpdated(rName, emailAddress3), Check: resource.ComposeTestCheckFunc( testAccBudgetExists(resourceName, &budget), resource.TestCheckResourceAttr(resourceName, "budget_type", "USAGE"), @@ -405,7 +405,7 @@ func testAccBudgetDestroy(s *terraform.State) error { return nil } -func testAccBudgetConfigDeprecated(rName string) string { +func testAccBudgetConfig_deprecated(rName string) string { return fmt.Sprintf(` resource "aws_budgets_budget" "test" { name = %[1]q @@ -421,7 +421,7 @@ resource "aws_budgets_budget" "test" { `, rName) } -func testAccBudgetNameGeneratedConfig() string { +func testAccBudgetConfig_nameGenerated() string { return ` resource "aws_budgets_budget" "test" { budget_type = "RI_COVERAGE" @@ -437,7 +437,7 @@ resource "aws_budgets_budget" "test" { ` } -func testAccBudgetNamePrefixConfig(namePrefix string) string { +func testAccBudgetConfig_namePrefix(namePrefix string) string { return fmt.Sprintf(` resource "aws_budgets_budget" "test" { name_prefix = %[1]q @@ -449,7 +449,7 @@ resource "aws_budgets_budget" "test" { `, namePrefix) } -func testAccBudgetCostTypesConfig(rName, startDate, endDate string) string { +func testAccBudgetConfig_costTypes(rName, startDate, endDate string) string { return fmt.Sprintf(` resource "aws_budgets_budget" "test" { name = %[1]q @@ -476,7 +476,7 @@ resource "aws_budgets_budget" "test" { `, rName, startDate, endDate, acctest.Region(), acctest.AlternateRegion()) } -func testAccBudgetCostTypesUpdatedConfig(rName, startDate, endDate string) string { +func testAccBudgetConfig_costTypesUpdated(rName, startDate, endDate string) string { return fmt.Sprintf(` resource "aws_budgets_budget" "test" { name = %[1]q @@ -505,7 +505,7 @@ resource "aws_budgets_budget" "test" { `, rName, startDate, endDate, acctest.AlternateRegion(), acctest.ThirdRegion()) } -func testAccBudgetNotificationsConfig(rName, emailAddress1, emailAddress2 string) string { +func testAccBudgetConfig_notifications(rName, emailAddress1, emailAddress2 string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -537,7 +537,7 @@ resource "aws_budgets_budget" "test" { `, rName, emailAddress1, emailAddress2) } -func testAccBudgetNotificationsUpdatedConfig(rName, emailAddress1 string) string { +func testAccBudgetConfig_notificationsUpdated(rName, emailAddress1 string) string { return fmt.Sprintf(` resource "aws_budgets_budget" "test" { name = %[1]q diff --git a/internal/service/budgets/sweep.go b/internal/service/budgets/sweep.go index 1d95f2dae39..f91e00b8a00 100644 --- a/internal/service/budgets/sweep.go +++ b/internal/service/budgets/sweep.go @@ -19,7 +19,7 @@ import ( func init() { resource.AddTestSweepers("aws_budgets_budget_action", &resource.Sweeper{ Name: "aws_budgets_budget_action", - F: sweepBudgetActionss, + F: sweepBudgetActions, }) resource.AddTestSweepers("aws_budgets_budget", &resource.Sweeper{ @@ -28,7 +28,7 @@ func init() { }) } -func sweepBudgetActionss(region string) error { +func sweepBudgetActions(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { return fmt.Errorf("error getting client: %w", err) @@ -78,7 +78,7 @@ func sweepBudgetActionss(region string) error { return sweeperErrs.ErrorOrNil() } -func sweepBudgets(region string) error { +func sweepBudgets(region string) error { // nosemgrep:budgets-in-func-name client, err := sweep.SharedRegionalSweepClient(region) if err != nil { return fmt.Errorf("error getting client: %w", err) diff --git a/internal/service/ce/anomaly_monitor.go b/internal/service/ce/anomaly_monitor.go new file mode 100644 index 00000000000..c9c0bdccb58 --- /dev/null +++ b/internal/service/ce/anomaly_monitor.go @@ -0,0 +1,232 @@ +package ce + +import ( + "context" + "encoding/json" + "regexp" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/costexplorer" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func ResourceAnomalyMonitor() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceAnomalyMonitorCreate, + ReadContext: resourceAnomalyMonitorRead, + UpdateContext: resourceAnomalyMonitorUpdate, + DeleteContext: resourceAnomalyMonitorDelete, + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "monitor_dimension": { + Type: schema.TypeString, + Optional: true, + ConflictsWith: []string{"monitor_specification"}, + ValidateFunc: validation.StringInSlice(costexplorer.MonitorDimension_Values(), false), + }, + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 1024), + validation.StringMatch(regexp.MustCompile(`[\\S\\s]*`), "Must be a valid Anomaly Monitor Name matching expression: [\\S\\s]*")), + }, + "monitor_specification": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringIsJSON, + DiffSuppressFunc: verify.SuppressEquivalentJSONDiffs, + ConflictsWith: []string{"monitor_dimension"}, + }, + "monitor_type": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(costexplorer.MonitorType_Values(), false), + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourceAnomalyMonitorCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).CEConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + input := &costexplorer.CreateAnomalyMonitorInput{ + AnomalyMonitor: &costexplorer.AnomalyMonitor{ + MonitorName: aws.String(d.Get("name").(string)), + MonitorType: aws.String(d.Get("monitor_type").(string)), + }, + } + switch d.Get("monitor_type").(string) { + case costexplorer.MonitorTypeDimensional: + if v, ok := d.GetOk("monitor_dimension"); ok { + input.AnomalyMonitor.MonitorDimension = aws.String(v.(string)) + } else { + return diag.Errorf("If Monitor Type is %s, dimension attrribute is required", costexplorer.MonitorTypeDimensional) + } + case costexplorer.MonitorTypeCustom: + if v, ok := d.GetOk("monitor_specification"); ok { + expression := costexplorer.Expression{} + + if err := json.Unmarshal([]byte(v.(string)), &expression); err != nil { + return diag.Errorf("Error parsing specification: %s", err) + } + + input.AnomalyMonitor.MonitorSpecification = &expression + + } else { + return diag.Errorf("If Monitor Type is %s, dimension attrribute is required", costexplorer.MonitorTypeCustom) + } + } + + if len(tags) > 0 { + input.ResourceTags = Tags(tags.IgnoreAWS()) + } + + resp, err := conn.CreateAnomalyMonitorWithContext(ctx, input) + + if err != nil { + return diag.Errorf("Error creating Anomaly Monitor: %s", err) + } + + if resp == nil || resp.MonitorArn == nil { + return diag.Errorf("creating Cost Explorer Anomaly Monitor resource (%s): empty output", d.Get("name").(string)) + } + + d.SetId(aws.StringValue(resp.MonitorArn)) + + return resourceAnomalyMonitorRead(ctx, d, meta) +} + +func resourceAnomalyMonitorRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).CEConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + monitor, err := FindAnomalyMonitorByARN(ctx, conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + names.LogNotFoundRemoveState(names.CE, names.ErrActionReading, ResAnomalyMonitor, d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return names.DiagError(names.CE, names.ErrActionReading, ResAnomalyMonitor, d.Id(), err) + } + + if monitor.MonitorSpecification != nil { + specificationToJson, err := json.Marshal(monitor.MonitorSpecification) + if err != nil { + return diag.Errorf("Error parsing specification response: %s", err) + } + specificationToSet, err := structure.NormalizeJsonString(string(specificationToJson)) + + if err != nil { + return diag.Errorf("Specification (%s) is invalid JSON: %s", specificationToSet, err) + } + + d.Set("monitor_specification", specificationToSet) + } + + d.Set("arn", monitor.MonitorArn) + d.Set("monitor_dimension", monitor.MonitorDimension) + d.Set("name", monitor.MonitorName) + d.Set("monitor_type", monitor.MonitorType) + + tags, err := ListTags(conn, aws.StringValue(monitor.MonitorArn)) + tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + if err != nil { + return names.DiagError(names.CE, names.ErrActionReading, ResTags, d.Id(), err) + } + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return names.DiagError(names.CE, names.ErrActionReading, ResTags, d.Id(), err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return names.DiagError(names.CE, names.ErrActionReading, ResTags, d.Id(), err) + } + + return nil +} + +func resourceAnomalyMonitorUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).CEConn + requestUpdate := false + + input := &costexplorer.UpdateAnomalyMonitorInput{ + MonitorArn: aws.String(d.Id()), + } + + if d.HasChange("name") { + input.MonitorName = aws.String(d.Get("name").(string)) + requestUpdate = true + } + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + + if err := UpdateTags(conn, d.Id(), o, n); err != nil { + return names.DiagError(names.CE, names.ErrActionUpdating, ResTags, d.Id(), err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Id(), o, n); err != nil { + return names.DiagError(names.CE, names.ErrActionUpdating, ResTags, d.Id(), err) + } + } + + if requestUpdate { + _, err := conn.UpdateAnomalyMonitorWithContext(ctx, input) + + if err != nil { + return names.DiagError(names.CE, names.ErrActionUpdating, ResAnomalyMonitor, d.Id(), err) + } + } + + return resourceAnomalyMonitorRead(ctx, d, meta) +} + +func resourceAnomalyMonitorDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).CEConn + + _, err := conn.DeleteAnomalyMonitorWithContext(ctx, &costexplorer.DeleteAnomalyMonitorInput{MonitorArn: aws.String(d.Id())}) + + if err != nil && tfawserr.ErrCodeEquals(err, costexplorer.ErrCodeUnknownMonitorException) { + return nil + } + + if err != nil { + return names.DiagError(names.CE, names.ErrActionDeleting, ResAnomalyMonitor, d.Id(), err) + } + + return nil +} diff --git a/internal/service/ce/anomaly_monitor_test.go b/internal/service/ce/anomaly_monitor_test.go new file mode 100644 index 00000000000..fa756fa7746 --- /dev/null +++ b/internal/service/ce/anomaly_monitor_test.go @@ -0,0 +1,336 @@ +package ce_test + +import ( + "context" + "errors" + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/costexplorer" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfce "github.com/hashicorp/terraform-provider-aws/internal/service/ce" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func TestAccCEAnomalyMonitor_basic(t *testing.T) { + var monitor costexplorer.AnomalyMonitor + resourceName := "aws_ce_anomaly_monitor.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalyMonitorDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalyMonitorConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAnomalyMonitorExists(resourceName, &monitor), + resource.TestCheckResourceAttr(resourceName, "name", rName), + acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "ce", regexp.MustCompile(`anomalymonitor/.+`)), + resource.TestCheckResourceAttr(resourceName, "monitor_type", "CUSTOM"), + resource.TestCheckResourceAttrSet(resourceName, "monitor_specification"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccCEAnomalyMonitor_disappears(t *testing.T) { + var monitor costexplorer.AnomalyMonitor + resourceName := "aws_ce_anomaly_monitor.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalyMonitorDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalyMonitorConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAnomalyMonitorExists(resourceName, &monitor), + acctest.CheckResourceDisappears(acctest.Provider, tfce.ResourceAnomalyMonitor(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccCEAnomalyMonitor_update(t *testing.T) { + var monitor costexplorer.AnomalyMonitor + resourceName := "aws_ce_anomaly_monitor.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalyMonitorDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalyMonitorConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAnomalyMonitorExists(resourceName, &monitor), + resource.TestCheckResourceAttr(resourceName, "name", rName), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAnomalyMonitorConfig_basic(rName2), + Check: resource.ComposeTestCheckFunc( + testAccCheckAnomalyMonitorExists(resourceName, &monitor), + resource.TestCheckResourceAttr(resourceName, "name", rName2), + ), + }, + }, + }) +} + +func TestAccCEAnomalyMonitor_tags(t *testing.T) { + var monitor costexplorer.AnomalyMonitor + resourceName := "aws_ce_anomaly_monitor.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalyMonitorDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalyMonitorConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalyMonitorExists(resourceName, &monitor), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAnomalyMonitorConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalyMonitorExists(resourceName, &monitor), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccAnomalyMonitorConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAnomalyMonitorExists(resourceName, &monitor), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +// An AWS account can only have one anomaly monitor of type DIMENSIONAL. As +// such, if additional tests are added, they should be combined with the +// following test in a serial test +func TestAccCEAnomalyMonitor_Dimensional(t *testing.T) { + var monitor costexplorer.AnomalyMonitor + resourceName := "aws_ce_anomaly_monitor.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalyMonitorDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalyMonitorConfig_dimensional(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAnomalyMonitorExists(resourceName, &monitor), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "monitor_type", "DIMENSIONAL"), + resource.TestCheckResourceAttr(resourceName, "monitor_dimension", "SERVICE"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckAnomalyMonitorExists(n string, anomalyMonitor *costexplorer.AnomalyMonitor) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).CEConn + + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Cost Explorer Anomaly Monitor is set") + } + + resp, err := tfce.FindAnomalyMonitorByARN(context.Background(), conn, rs.Primary.ID) + + if err != nil { + return err + } + + if resp == nil { + return fmt.Errorf("Cost Explorer %q does not exist", rs.Primary.ID) + } + + *anomalyMonitor = *resp + + return nil + } +} + +func testAccCheckAnomalyMonitorDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).CEConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ce_anomaly_monitor" { + continue + } + + _, err := tfce.FindAnomalyMonitorByARN(context.Background(), conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return names.Error(names.CE, names.ErrActionCheckingDestroyed, tfce.ResAnomalyMonitor, rs.Primary.ID, errors.New("still exists")) + + } + + return nil + +} + +func testAccAnomalyMonitorConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_ce_anomaly_monitor" "test" { + name = %[1]q + monitor_type = "CUSTOM" + + monitor_specification = < 0 { + input.ResourceTags = Tags(tags.IgnoreAWS()) + } + + resp, err := conn.CreateAnomalySubscriptionWithContext(ctx, input) + + if err != nil { + return names.DiagError(names.CE, names.ErrActionCreating, ResAnomalySubscription, d.Id(), err) + } + + if resp == nil || resp.SubscriptionArn == nil { + return diag.Errorf("creating Cost Explorer Anomaly Subscription resource (%s): empty output", d.Get("name").(string)) + } + + d.SetId(aws.StringValue(resp.SubscriptionArn)) + + return resourceAnomalySubscriptionRead(ctx, d, meta) +} + +func resourceAnomalySubscriptionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).CEConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + subscription, err := FindAnomalySubscriptionByARN(ctx, conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + names.LogNotFoundRemoveState(names.CE, names.ErrActionReading, ResAnomalySubscription, d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return names.DiagError(names.CE, names.ErrActionReading, ResAnomalySubscription, d.Id(), err) + } + + d.Set("account_id", subscription.AccountId) + d.Set("arn", subscription.SubscriptionArn) + d.Set("frequency", subscription.Frequency) + d.Set("monitor_arn_list", subscription.MonitorArnList) + d.Set("subscriber", flattenAnomalySubscriptionSubscribers(subscription.Subscribers)) + d.Set("threshold", subscription.Threshold) + d.Set("name", subscription.SubscriptionName) + + tags, err := ListTags(conn, aws.StringValue(subscription.SubscriptionArn)) + tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + if err != nil { + return names.DiagError(names.CE, names.ErrActionReading, ResTags, d.Id(), err) + } + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return names.DiagError(names.CE, names.ErrActionUpdating, ResTags, d.Id(), err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return names.DiagError(names.CE, names.ErrActionUpdating, ResTags, d.Id(), err) + } + + return nil +} + +func resourceAnomalySubscriptionUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).CEConn + requestUpdate := false + + input := &costexplorer.UpdateAnomalySubscriptionInput{ + SubscriptionArn: aws.String(d.Id()), + } + + if d.HasChange("frequency") { + input.Frequency = aws.String(d.Get("frequency").(string)) + requestUpdate = true + } + + if d.HasChange("monitor_arn_list") { + input.MonitorArnList = aws.StringSlice(d.Get("monitor_arn_list").([]string)) + requestUpdate = true + } + + if d.HasChange("subscriber") { + input.Subscribers = expandAnomalySubscriptionSubscribers(d.Get("subscriber").(*schema.Set).List()) + requestUpdate = true + } + + if d.HasChange("threshold") { + input.Threshold = aws.Float64(d.Get("threshold").(float64)) + requestUpdate = true + } + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + + if err := UpdateTags(conn, d.Id(), o, n); err != nil { + return names.DiagError(names.CE, names.ErrActionUpdating, ResTags, d.Id(), err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Id(), o, n); err != nil { + return names.DiagError(names.CE, names.ErrActionUpdating, ResTags, d.Id(), err) + } + } + + if requestUpdate { + _, err := conn.UpdateAnomalySubscriptionWithContext(ctx, input) + + if err != nil { + return names.DiagError(names.CE, names.ErrActionUpdating, ResAnomalySubscription, d.Id(), err) + } + } + + return resourceAnomalySubscriptionRead(ctx, d, meta) +} + +func resourceAnomalySubscriptionDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).CEConn + + _, err := conn.DeleteAnomalySubscriptionWithContext(ctx, &costexplorer.DeleteAnomalySubscriptionInput{SubscriptionArn: aws.String(d.Id())}) + + if err != nil && tfawserr.ErrCodeEquals(err, costexplorer.ErrCodeResourceNotFoundException) { + return nil + } + + if err != nil { + return names.DiagError(names.CE, names.ErrActionDeleting, ResAnomalySubscription, d.Id(), err) + } + + return nil +} + +func expandAnomalySubscriptionMonitorARNList(rawMonitorArnList []interface{}) []string { + if len(rawMonitorArnList) == 0 { + return nil + } + + var monitorArns []string + + for _, arn := range rawMonitorArnList { + + monitorArns = append(monitorArns, arn.(string)) + } + + return monitorArns +} + +func expandAnomalySubscriptionSubscribers(rawSubscribers []interface{}) []*costexplorer.Subscriber { + if len(rawSubscribers) == 0 { + return nil + } + + var subscribers []*costexplorer.Subscriber + + for _, sub := range rawSubscribers { + rawSubMap := sub.(map[string]interface{}) + subscriber := &costexplorer.Subscriber{Address: aws.String(rawSubMap["address"].(string)), Type: aws.String(rawSubMap["type"].(string))} + subscribers = append(subscribers, subscriber) + } + + return subscribers +} + +func flattenAnomalySubscriptionSubscribers(subscribers []*costexplorer.Subscriber) []interface{} { + if subscribers == nil { + return []interface{}{} + } + + var rawSubscribers []interface{} + for _, subscriber := range subscribers { + rawSubscriber := map[string]interface{}{ + "address": aws.StringValue(subscriber.Address), + "type": aws.StringValue(subscriber.Type), + } + + rawSubscribers = append(rawSubscribers, rawSubscriber) + } + + return rawSubscribers +} diff --git a/internal/service/ce/anomaly_subscription_test.go b/internal/service/ce/anomaly_subscription_test.go new file mode 100644 index 00000000000..7fe5784eb31 --- /dev/null +++ b/internal/service/ce/anomaly_subscription_test.go @@ -0,0 +1,662 @@ +package ce_test + +import ( + "context" + "errors" + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/costexplorer" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfce "github.com/hashicorp/terraform-provider-aws/internal/service/ce" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func TestAccCEAnomalySubscription_basic(t *testing.T) { + var subscription costexplorer.AnomalySubscription + resourceName := "aws_ce_anomaly_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + domain := acctest.RandomDomainName() + address := acctest.RandomEmailAddress(domain) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalySubscriptionDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalySubscriptionConfig_basic(rName, address), + Check: resource.ComposeTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "name", rName), + acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "ce", regexp.MustCompile(`anomalysubscription/.+`)), + resource.TestCheckResourceAttrSet(resourceName, "account_id"), + resource.TestCheckResourceAttr(resourceName, "frequency", "DAILY"), + resource.TestCheckResourceAttrSet(resourceName, "monitor_arn_list.#"), + resource.TestCheckResourceAttr(resourceName, "subscriber.0.type", "EMAIL"), + resource.TestCheckResourceAttr(resourceName, "subscriber.0.address", address), + resource.TestCheckResourceAttr(resourceName, "threshold", "100"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccCEAnomalySubscription_disappears(t *testing.T) { + var subscription costexplorer.AnomalySubscription + resourceName := "aws_ce_anomaly_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + domain := acctest.RandomDomainName() + address := acctest.RandomEmailAddress(domain) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalySubscriptionDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalySubscriptionConfig_basic(rName, address), + Check: resource.ComposeTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + acctest.CheckResourceDisappears(acctest.Provider, tfce.ResourceAnomalySubscription(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccCEAnomalySubscription_Frequency(t *testing.T) { + var subscription costexplorer.AnomalySubscription + resourceName := "aws_ce_anomaly_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + domain := acctest.RandomDomainName() + address := acctest.RandomEmailAddress(domain) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalySubscriptionDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalySubscriptionConfig_frequency(rName, "DAILY", address), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "frequency", "DAILY"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAnomalySubscriptionConfig_frequency(rName, "WEEKLY", address), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "frequency", "WEEKLY"), + ), + }, + }, + }) +} + +func TestAccCEAnomalySubscription_MonitorARNList(t *testing.T) { + var subscription costexplorer.AnomalySubscription + resourceName := "aws_ce_anomaly_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName3 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + domain := acctest.RandomDomainName() + address := acctest.RandomEmailAddress(domain) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalySubscriptionDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalySubscriptionConfig_basic(rName, address), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttrPair(resourceName, "monitor_arn_list.0", "aws_ce_anomaly_monitor.test", "arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAnomalySubscriptionConfig_monitorARNList(rName2, rName3, address), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttrPair(resourceName, "monitor_arn_list.0", "aws_ce_anomaly_monitor.test", "arn"), + resource.TestCheckResourceAttrPair(resourceName, "monitor_arn_list.1", "aws_ce_anomaly_monitor.test2", "arn"), + ), + }, + }, + }) +} + +func TestAccCEAnomalySubscription_Subscriber(t *testing.T) { + var subscription costexplorer.AnomalySubscription + resourceName := "aws_ce_anomaly_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + domain := acctest.RandomDomainName() + address1 := acctest.RandomEmailAddress(domain) + address2 := acctest.RandomEmailAddress(domain) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalySubscriptionDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalySubscriptionConfig_basic(rName, address1), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "subscriber.0.type", "EMAIL"), + resource.TestCheckResourceAttr(resourceName, "subscriber.0.address", address1), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAnomalySubscriptionConfig_basic(rName, address2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "subscriber.0.type", "EMAIL"), + resource.TestCheckResourceAttr(resourceName, "subscriber.0.address", address2), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAnomalySubscriptionConfig_subscriber2(rName, address1, address2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttrSet(resourceName, "subscriber.0.type"), + resource.TestCheckResourceAttrSet(resourceName, "subscriber.0.address"), + resource.TestCheckResourceAttrSet(resourceName, "subscriber.1.type"), + resource.TestCheckResourceAttrSet(resourceName, "subscriber.1.address"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAnomalySubscriptionConfig_subscriberSNS(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "subscriber.0.type", "SNS"), + resource.TestCheckResourceAttrPair(resourceName, "subscriber.0.address", "aws_sns_topic.test", "arn"), + ), + }, + }, + }) +} + +func TestAccCEAnomalySubscription_Threshold(t *testing.T) { + var subscription costexplorer.AnomalySubscription + resourceName := "aws_ce_anomaly_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + domain := acctest.RandomDomainName() + address := acctest.RandomEmailAddress(domain) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalySubscriptionDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalySubscriptionConfig_threshold(rName, 100, address), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "threshold", "100"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAnomalySubscriptionConfig_threshold(rName, 200, address), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "threshold", "200"), + ), + }, + }, + }) +} + +func TestAccCEAnomalySubscription_Tags(t *testing.T) { + var subscription costexplorer.AnomalySubscription + resourceName := "aws_ce_anomaly_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + domain := acctest.RandomDomainName() + address := acctest.RandomEmailAddress(domain) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAnomalySubscriptionDestroy, + ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID), + Steps: []resource.TestStep{ + { + Config: testAccAnomalySubscriptionConfig_tags1(rName, "key1", "value1", address), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAnomalySubscriptionConfig_tags2(rName, "key1", "value1updated", "key2", "value2", address), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccAnomalySubscriptionConfig_tags1(rName, "key2", "value2", address), + Check: resource.ComposeTestCheckFunc( + testAccCheckAnomalySubscriptionExists(resourceName, &subscription), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func testAccCheckAnomalySubscriptionExists(n string, anomalySubscription *costexplorer.AnomalySubscription) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).CEConn + + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Cost Explorer Anomaly Subscription is set") + } + + resp, err := tfce.FindAnomalySubscriptionByARN(context.Background(), conn, rs.Primary.ID) + + if err != nil { + return err + } + + if resp == nil { + return fmt.Errorf("Cost Explorer %q does not exist", rs.Primary.ID) + } + + *anomalySubscription = *resp + + return nil + } +} + +func testAccCheckAnomalySubscriptionDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).CEConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ce_anomaly_subscription" { + continue + } + + _, err := tfce.FindAnomalySubscriptionByARN(context.Background(), conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return names.Error(names.CE, names.ErrActionCheckingDestroyed, tfce.ResAnomalySubscription, rs.Primary.ID, errors.New("still exists")) + + } + return nil +} + +func testAccAnomalySubscriptionConfigBase(rName string) string { + return fmt.Sprintf(` +resource "aws_ce_anomaly_monitor" "test" { + name = %[1]q + monitor_type = "CUSTOM" + + monitor_specification = < 0 { + input := &costexplorer.UntagResourceInput{ + ResourceArn: aws.String(identifier), + ResourceTagKeys: aws.StringSlice(removedTags.IgnoreAWS().Keys()), + } + + _, err := conn.UntagResource(input) + + if err != nil { + return fmt.Errorf("error untagging resource (%s): %w", identifier, err) + } + } + + if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 { + input := &costexplorer.TagResourceInput{ + ResourceArn: aws.String(identifier), + ResourceTags: Tags(updatedTags.IgnoreAWS()), + } + + _, err := conn.TagResource(input) + + if err != nil { + return fmt.Errorf("error tagging resource (%s): %w", identifier, err) + } + } + + return nil +} diff --git a/internal/service/chime/voice_connector_group_test.go b/internal/service/chime/voice_connector_group_test.go index d82f915358e..77a0007302b 100644 --- a/internal/service/chime/voice_connector_group_test.go +++ b/internal/service/chime/voice_connector_group_test.go @@ -27,7 +27,7 @@ func TestAccChimeVoiceConnectorGroup_basic(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorGroupConfig(vcgName), + Config: testAccVoiceConnectorGroupConfig_basic(vcgName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorGroupExists(resourceName, voiceConnectorGroup), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("vcg-%s", vcgName)), @@ -57,7 +57,7 @@ func TestAccChimeVoiceConnectorGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorGroupConfig(vcgName), + Config: testAccVoiceConnectorGroupConfig_basic(vcgName), Check: resource.ComposeTestCheckFunc( testAccCheckVoiceConnectorGroupExists(resourceName, voiceConnectorGroup), acctest.CheckResourceDisappears(acctest.Provider, tfchime.ResourceVoiceConnectorGroup(), resourceName), @@ -81,7 +81,7 @@ func TestAccChimeVoiceConnectorGroup_update(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorGroupConfig(vcgName), + Config: testAccVoiceConnectorGroupConfig_basic(vcgName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorGroupExists(resourceName, voiceConnectorGroup), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("vcg-%s", vcgName)), @@ -89,7 +89,7 @@ func TestAccChimeVoiceConnectorGroup_update(t *testing.T) { ), }, { - Config: testAccVoiceConnectorGroupUpdated(vcgName), + Config: testAccVoiceConnectorGroupConfig_updated(vcgName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("vcg-updated-%s", vcgName)), resource.TestCheckResourceAttr(resourceName, "connector.0.priority", "10"), @@ -104,7 +104,7 @@ func TestAccChimeVoiceConnectorGroup_update(t *testing.T) { }) } -func testAccVoiceConnectorGroupConfig(name string) string { +func testAccVoiceConnectorGroupConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "chime" { name = "vc-%[1]s" @@ -122,7 +122,7 @@ resource "aws_chime_voice_connector_group" "test" { `, name) } -func testAccVoiceConnectorGroupUpdated(name string) string { +func testAccVoiceConnectorGroupConfig_updated(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "chime" { name = "vc-%[1]s" diff --git a/internal/service/chime/voice_connector_logging_test.go b/internal/service/chime/voice_connector_logging_test.go index 4431f137860..13092b1d466 100644 --- a/internal/service/chime/voice_connector_logging_test.go +++ b/internal/service/chime/voice_connector_logging_test.go @@ -25,7 +25,7 @@ func TestAccChimeVoiceConnectorLogging_basic(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorLoggingConfig(name), + Config: testAccVoiceConnectorLoggingConfig_basic(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enable_sip_logs", "true"), @@ -51,7 +51,7 @@ func TestAccChimeVoiceConnectorLogging_disappears(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorLoggingConfig(name), + Config: testAccVoiceConnectorLoggingConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckVoiceConnectorLoggingExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfchime.ResourceVoiceConnectorLogging(), resourceName), @@ -73,13 +73,13 @@ func TestAccChimeVoiceConnectorLogging_update(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorLoggingConfig(name), + Config: testAccVoiceConnectorLoggingConfig_basic(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorLoggingExists(resourceName), ), }, { - Config: testAccVoiceConnectorLoggingUpdated(name), + Config: testAccVoiceConnectorLoggingConfig_updated(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enable_sip_logs", "false"), @@ -94,7 +94,7 @@ func TestAccChimeVoiceConnectorLogging_update(t *testing.T) { }) } -func testAccVoiceConnectorLoggingConfig(name string) string { +func testAccVoiceConnectorLoggingConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "chime" { name = "vc-%[1]s" @@ -108,7 +108,7 @@ resource "aws_chime_voice_connector_logging" "test" { `, name) } -func testAccVoiceConnectorLoggingUpdated(name string) string { +func testAccVoiceConnectorLoggingConfig_updated(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "chime" { name = "vc-%[1]s" diff --git a/internal/service/chime/voice_connector_origination_test.go b/internal/service/chime/voice_connector_origination_test.go index afd8fe2d26b..0e47ea1a9f3 100644 --- a/internal/service/chime/voice_connector_origination_test.go +++ b/internal/service/chime/voice_connector_origination_test.go @@ -26,7 +26,7 @@ func TestAccChimeVoiceConnectorOrigination_basic(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorOriginationDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorOriginationConfig(name), + Config: testAccVoiceConnectorOriginationConfig_basic(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorOriginationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "route.#", "1"), @@ -56,7 +56,7 @@ func TestAccChimeVoiceConnectorOrigination_disappears(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorOriginationDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorOriginationConfig(name), + Config: testAccVoiceConnectorOriginationConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckVoiceConnectorOriginationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfchime.ResourceVoiceConnectorOrigination(), resourceName), @@ -78,14 +78,14 @@ func TestAccChimeVoiceConnectorOrigination_update(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorOriginationDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorOriginationConfig(name), + Config: testAccVoiceConnectorOriginationConfig_basic(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorOriginationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "route.#", "1"), ), }, { - Config: testAccVoiceConnectorOriginationUpdated(name), + Config: testAccVoiceConnectorOriginationConfig_updated(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorOriginationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "route.#", "2"), @@ -166,7 +166,7 @@ func testAccCheckVoiceConnectorOriginationDestroy(s *terraform.State) error { return nil } -func testAccVoiceConnectorOriginationConfig(name string) string { +func testAccVoiceConnectorOriginationConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "test" { name = "vc-%[1]s" @@ -186,7 +186,7 @@ resource "aws_chime_voice_connector_origination" "test" { `, name) } -func testAccVoiceConnectorOriginationUpdated(name string) string { +func testAccVoiceConnectorOriginationConfig_updated(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "test" { name = "vc-%[1]s" diff --git a/internal/service/chime/voice_connector_streaming_test.go b/internal/service/chime/voice_connector_streaming_test.go index fab8195cd54..6b0cce6f4f3 100644 --- a/internal/service/chime/voice_connector_streaming_test.go +++ b/internal/service/chime/voice_connector_streaming_test.go @@ -26,7 +26,7 @@ func TestAccChimeVoiceConnectorStreaming_basic(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorStreamingDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorStreamingConfig(name), + Config: testAccVoiceConnectorStreamingConfig_basic(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorStreamingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "data_retention", "5"), @@ -54,7 +54,7 @@ func TestAccChimeVoiceConnectorStreaming_disappears(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorStreamingDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorStreamingConfig(name), + Config: testAccVoiceConnectorStreamingConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckVoiceConnectorStreamingExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfchime.ResourceVoiceConnectorStreaming(), resourceName), @@ -76,13 +76,13 @@ func TestAccChimeVoiceConnectorStreaming_update(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorStreamingDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorStreamingConfig(name), + Config: testAccVoiceConnectorStreamingConfig_basic(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorStreamingExists(resourceName), ), }, { - Config: testAccVoiceConnectorStreamingUpdated(name), + Config: testAccVoiceConnectorStreamingConfig_updated(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorStreamingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "data_retention", "2"), @@ -99,7 +99,7 @@ func TestAccChimeVoiceConnectorStreaming_update(t *testing.T) { }) } -func testAccVoiceConnectorStreamingConfig(name string) string { +func testAccVoiceConnectorStreamingConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "chime" { name = "vc-%[1]s" @@ -116,7 +116,7 @@ resource "aws_chime_voice_connector_streaming" "test" { `, name) } -func testAccVoiceConnectorStreamingUpdated(name string) string { +func testAccVoiceConnectorStreamingConfig_updated(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "chime" { name = "vc-%[1]s" diff --git a/internal/service/chime/voice_connector_termination_credentials_test.go b/internal/service/chime/voice_connector_termination_credentials_test.go index 90302f010f8..66ccdd8e69e 100644 --- a/internal/service/chime/voice_connector_termination_credentials_test.go +++ b/internal/service/chime/voice_connector_termination_credentials_test.go @@ -26,7 +26,7 @@ func TestAccChimeVoiceConnectorTerminationCredentials_basic(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorTerminationCredentialsDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorTerminationCredentialsConfig(rName), + Config: testAccVoiceConnectorTerminationCredentialsConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorTerminationCredentialsExists(resourceName), resource.TestCheckResourceAttr(resourceName, "credentials.#", "1"), @@ -53,7 +53,7 @@ func TestAccChimeVoiceConnectorTerminationCredentials_disappears(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorTerminationCredentialsDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorTerminationCredentialsConfig(rName), + Config: testAccVoiceConnectorTerminationCredentialsConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVoiceConnectorTerminationCredentialsExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfchime.ResourceVoiceConnectorTerminationCredentials(), resourceName), @@ -75,14 +75,14 @@ func TestAccChimeVoiceConnectorTerminationCredentials_update(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorTerminationCredentialsDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorTerminationCredentialsConfig(rName), + Config: testAccVoiceConnectorTerminationCredentialsConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorTerminationCredentialsExists(resourceName), resource.TestCheckResourceAttr(resourceName, "credentials.#", "1"), ), }, { - Config: testAccVoiceConnectorTerminationCredentialsUpdatedConfig(rName), + Config: testAccVoiceConnectorTerminationCredentialsConfig_updated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorTerminationCredentialsExists(resourceName), resource.TestCheckResourceAttr(resourceName, "credentials.#", "2"), @@ -164,7 +164,7 @@ resource "aws_chime_voice_connector_termination" "test" { `, rName) } -func testAccVoiceConnectorTerminationCredentialsConfig(rName string) string { +func testAccVoiceConnectorTerminationCredentialsConfig_basic(rName string) string { return acctest.ConfigCompose(testAccVoiceConnectorTerminationCredentialsBaseConfig(rName), ` resource "aws_chime_voice_connector_termination_credentials" "test" { voice_connector_id = aws_chime_voice_connector.chime.id @@ -179,7 +179,7 @@ resource "aws_chime_voice_connector_termination_credentials" "test" { `) } -func testAccVoiceConnectorTerminationCredentialsUpdatedConfig(rName string) string { +func testAccVoiceConnectorTerminationCredentialsConfig_updated(rName string) string { return acctest.ConfigCompose(testAccVoiceConnectorTerminationCredentialsBaseConfig(rName), ` resource "aws_chime_voice_connector_termination_credentials" "test" { voice_connector_id = aws_chime_voice_connector.chime.id diff --git a/internal/service/chime/voice_connector_termination_test.go b/internal/service/chime/voice_connector_termination_test.go index caee0a8c499..9ded32ddf9f 100644 --- a/internal/service/chime/voice_connector_termination_test.go +++ b/internal/service/chime/voice_connector_termination_test.go @@ -26,7 +26,7 @@ func TestAccChimeVoiceConnectorTermination_basic(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorTerminationDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorTerminationConfig(name), + Config: testAccVoiceConnectorTerminationConfig_basic(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorTerminationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cps_limit", "1"), @@ -55,7 +55,7 @@ func TestAccChimeVoiceConnectorTermination_disappears(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorTerminationDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorTerminationConfig(name), + Config: testAccVoiceConnectorTerminationConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckVoiceConnectorTerminationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfchime.ResourceVoiceConnectorTermination(), resourceName), @@ -77,13 +77,13 @@ func TestAccChimeVoiceConnectorTermination_update(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorTerminationDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorTerminationConfig(name), + Config: testAccVoiceConnectorTerminationConfig_basic(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorTerminationExists(resourceName), ), }, { - Config: testAccVoiceConnectorTerminationUpdated(name), + Config: testAccVoiceConnectorTerminationConfig_updated(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorTerminationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cps_limit", "1"), @@ -102,7 +102,7 @@ func TestAccChimeVoiceConnectorTermination_update(t *testing.T) { }) } -func testAccVoiceConnectorTerminationConfig(name string) string { +func testAccVoiceConnectorTerminationConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "chime" { name = "vc-%[1]s" @@ -118,7 +118,7 @@ resource "aws_chime_voice_connector_termination" "test" { `, name) } -func testAccVoiceConnectorTerminationUpdated(name string) string { +func testAccVoiceConnectorTerminationConfig_updated(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "chime" { name = "vc-%[1]s" diff --git a/internal/service/chime/voice_connector_test.go b/internal/service/chime/voice_connector_test.go index 72b62e27255..6adb1510b88 100644 --- a/internal/service/chime/voice_connector_test.go +++ b/internal/service/chime/voice_connector_test.go @@ -27,7 +27,7 @@ func TestAccChimeVoiceConnector_basic(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorConfig(vcName), + Config: testAccVoiceConnectorConfig_basic(vcName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorExists(resourceName, voiceConnector), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("vc-%s", vcName)), @@ -57,7 +57,7 @@ func TestAccChimeVoiceConnector_disappears(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorConfig(vcName), + Config: testAccVoiceConnectorConfig_basic(vcName), Check: resource.ComposeTestCheckFunc( testAccCheckVoiceConnectorExists(resourceName, voiceConnector), acctest.CheckResourceDisappears(acctest.Provider, tfchime.ResourceVoiceConnector(), resourceName), @@ -81,7 +81,7 @@ func TestAccChimeVoiceConnector_update(t *testing.T) { CheckDestroy: testAccCheckVoiceConnectorDestroy, Steps: []resource.TestStep{ { - Config: testAccVoiceConnectorConfig(vcName), + Config: testAccVoiceConnectorConfig_basic(vcName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVoiceConnectorExists(resourceName, voiceConnector), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("vc-%s", vcName)), @@ -90,7 +90,7 @@ func TestAccChimeVoiceConnector_update(t *testing.T) { ), }, { - Config: testAccVoiceConnectorUpdated(vcName), + Config: testAccVoiceConnectorConfig_updated(vcName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "require_encryption", "false"), ), @@ -104,7 +104,7 @@ func TestAccChimeVoiceConnector_update(t *testing.T) { }) } -func testAccVoiceConnectorConfig(name string) string { +func testAccVoiceConnectorConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "test" { name = "vc-%s" @@ -113,7 +113,7 @@ resource "aws_chime_voice_connector" "test" { `, name) } -func testAccVoiceConnectorUpdated(name string) string { +func testAccVoiceConnectorConfig_updated(name string) string { return fmt.Sprintf(` resource "aws_chime_voice_connector" "test" { name = "vc-%s" diff --git a/internal/service/cloud9/environment_ec2_test.go b/internal/service/cloud9/environment_ec2_test.go index 49b681f14c2..91b6998e73f 100644 --- a/internal/service/cloud9/environment_ec2_test.go +++ b/internal/service/cloud9/environment_ec2_test.go @@ -28,7 +28,7 @@ func TestAccCloud9EnvironmentEC2_basic(t *testing.T) { CheckDestroy: testAccCheckEnvironmentEC2Destroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentEC2Config(rName), + Config: testAccEnvironmentEC2Config_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentEC2Exists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "cloud9", regexp.MustCompile(`environment:.+$`)), @@ -66,7 +66,7 @@ func TestAccCloud9EnvironmentEC2_allFields(t *testing.T) { CheckDestroy: testAccCheckEnvironmentEC2Destroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentEC2AllFieldsConfig(rName, name1, description1), + Config: testAccEnvironmentEC2Config_allFields(rName, name1, description1), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentEC2Exists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "automatic_stop_time_minutes", "60"), @@ -87,7 +87,7 @@ func TestAccCloud9EnvironmentEC2_allFields(t *testing.T) { ImportStateVerifyIgnore: []string{"automatic_stop_time_minutes", "image_id", "instance_type", "subnet_id"}, }, { - Config: testAccEnvironmentEC2AllFieldsConfig(rName, name2, description2), + Config: testAccEnvironmentEC2Config_allFields(rName, name2, description2), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentEC2Exists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "description", description2), @@ -111,7 +111,7 @@ func TestAccCloud9EnvironmentEC2_tags(t *testing.T) { CheckDestroy: testAccCheckEnvironmentEC2Destroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentEC2Tags1Config(rName, "key1", "value1"), + Config: testAccEnvironmentEC2Config_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentEC2Exists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -125,7 +125,7 @@ func TestAccCloud9EnvironmentEC2_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"instance_type", "subnet_id"}, }, { - Config: testAccEnvironmentEC2Tags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccEnvironmentEC2Config_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentEC2Exists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -134,7 +134,7 @@ func TestAccCloud9EnvironmentEC2_tags(t *testing.T) { ), }, { - Config: testAccEnvironmentEC2Tags1Config(rName, "key2", "value2"), + Config: testAccEnvironmentEC2Config_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentEC2Exists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -158,7 +158,7 @@ func TestAccCloud9EnvironmentEC2_disappears(t *testing.T) { CheckDestroy: testAccCheckEnvironmentEC2Destroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentEC2Config(rName), + Config: testAccEnvironmentEC2Config_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentEC2Exists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfcloud9.ResourceEnvironmentEC2(), resourceName), @@ -254,7 +254,7 @@ resource "aws_route" "test" { `, rName)) } -func testAccEnvironmentEC2Config(rName string) string { +func testAccEnvironmentEC2Config_basic(rName string) string { return acctest.ConfigCompose(testAccEnvironmentEC2BaseConfig(rName), fmt.Sprintf(` resource "aws_cloud9_environment_ec2" "test" { instance_type = "t2.micro" @@ -264,7 +264,7 @@ resource "aws_cloud9_environment_ec2" "test" { `, rName)) } -func testAccEnvironmentEC2AllFieldsConfig(rName, name, description string) string { +func testAccEnvironmentEC2Config_allFields(rName, name, description string) string { return acctest.ConfigCompose(testAccEnvironmentEC2BaseConfig(rName), fmt.Sprintf(` resource "aws_cloud9_environment_ec2" "test" { automatic_stop_time_minutes = 60 @@ -283,7 +283,7 @@ resource "aws_iam_user" "test" { `, name, description, rName)) } -func testAccEnvironmentEC2Tags1Config(rName, tagKey1, tagValue1 string) string { +func testAccEnvironmentEC2Config_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccEnvironmentEC2BaseConfig(rName), fmt.Sprintf(` resource "aws_cloud9_environment_ec2" "test" { instance_type = "t2.micro" @@ -297,7 +297,7 @@ resource "aws_cloud9_environment_ec2" "test" { `, rName, tagKey1, tagValue1)) } -func testAccEnvironmentEC2Tags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccEnvironmentEC2Config_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccEnvironmentEC2BaseConfig(rName), fmt.Sprintf(` resource "aws_cloud9_environment_ec2" "test" { instance_type = "t2.micro" diff --git a/internal/service/cloud9/environment_membership_test.go b/internal/service/cloud9/environment_membership_test.go index df4c831a99c..cfd40cdb093 100644 --- a/internal/service/cloud9/environment_membership_test.go +++ b/internal/service/cloud9/environment_membership_test.go @@ -14,7 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func TestAccEnvironmentMembership_basic(t *testing.T) { +func TestAccCloud9EnvironmentMembership_basic(t *testing.T) { var conf cloud9.EnvironmentMember rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -27,7 +27,7 @@ func TestAccEnvironmentMembership_basic(t *testing.T) { CheckDestroy: testAccCheckEnvironmentMemberDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentMembershipConfig(rName, "read-only"), + Config: testAccEnvironmentMembershipConfig_basic(rName, "read-only"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentMemberExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "permissions", "read-only"), @@ -41,7 +41,7 @@ func TestAccEnvironmentMembership_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEnvironmentMembershipConfig(rName, "read-write"), + Config: testAccEnvironmentMembershipConfig_basic(rName, "read-write"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentMemberExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "permissions", "read-write"), @@ -53,7 +53,7 @@ func TestAccEnvironmentMembership_basic(t *testing.T) { }) } -func TestAccEnvironmentMembership_disappears(t *testing.T) { +func TestAccCloud9EnvironmentMembership_disappears(t *testing.T) { var conf cloud9.EnvironmentMember rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -66,7 +66,7 @@ func TestAccEnvironmentMembership_disappears(t *testing.T) { CheckDestroy: testAccCheckEnvironmentMemberDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentMembershipConfig(rName, "read-only"), + Config: testAccEnvironmentMembershipConfig_basic(rName, "read-only"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentMemberExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfcloud9.ResourceEnvironmentMembership(), resourceName), @@ -78,7 +78,7 @@ func TestAccEnvironmentMembership_disappears(t *testing.T) { }) } -func TestAccEnvironmentMembership_disappears_env(t *testing.T) { +func TestAccCloud9EnvironmentMembership_disappears_env(t *testing.T) { var conf cloud9.EnvironmentMember rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -91,7 +91,7 @@ func TestAccEnvironmentMembership_disappears_env(t *testing.T) { CheckDestroy: testAccCheckEnvironmentMemberDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentMembershipConfig(rName, "read-only"), + Config: testAccEnvironmentMembershipConfig_basic(rName, "read-only"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentMemberExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfcloud9.ResourceEnvironmentEC2(), "aws_cloud9_environment_ec2.test"), @@ -213,7 +213,7 @@ resource "aws_cloud9_environment_ec2" "test" { `, rName) } -func testAccEnvironmentMembershipConfig(rName, permissions string) string { +func testAccEnvironmentMembershipConfig_basic(rName, permissions string) string { return testAccEnvironmentMemberBaseConfig(rName) + fmt.Sprintf(` resource "aws_iam_user" "test" { name = %[1]q diff --git a/internal/service/cloudcontrol/resource_data_source_test.go b/internal/service/cloudcontrol/resource_data_source_test.go index dbe7eb61b24..e2108503062 100644 --- a/internal/service/cloudcontrol/resource_data_source_test.go +++ b/internal/service/cloudcontrol/resource_data_source_test.go @@ -22,7 +22,7 @@ func TestAccCloudControlResourceDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDataSourceConfig(rName), + Config: testAccResourceDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "properties", resourceName, "properties"), @@ -33,7 +33,7 @@ func TestAccCloudControlResourceDataSource_basic(t *testing.T) { }) } -func testAccResourceDataSourceConfig(rName string) string { +func testAccResourceDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::Logs::LogGroup" diff --git a/internal/service/cloudcontrol/resource_test.go b/internal/service/cloudcontrol/resource_test.go index a6962fac902..3b9cea13d5b 100644 --- a/internal/service/cloudcontrol/resource_test.go +++ b/internal/service/cloudcontrol/resource_test.go @@ -38,7 +38,7 @@ func TestAccCloudControlResource_basic(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceConfig(rName), + Config: testAccResourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`^\{.*\}$`)), resource.TestMatchResourceAttr(resourceName, "schema", regexp.MustCompile(`^\{.*`)), @@ -59,7 +59,7 @@ func TestAccCloudControlResource_disappears(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceConfig(rName), + Config: testAccResourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckResourceDisappears(acctest.Provider, tfcloudcontrol.ResourceResource(), resourceName), ), @@ -80,13 +80,13 @@ func TestAccCloudControlResource_DesiredState_booleanValueAdded(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateBooleanValueRemovedConfig(rName), + Config: testAccResourceConfig_desiredStateBooleanValueRemoved(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Enabled":false`)), ), }, { - Config: testAccResourceDesiredStateBooleanValueConfig(rName, true), + Config: testAccResourceConfig_desiredStateBooleanValue(rName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Enabled":true`)), ), @@ -106,13 +106,13 @@ func TestAccCloudControlResource_DesiredState_booleanValueRemoved(t *testing.T) CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateBooleanValueConfig(rName, true), + Config: testAccResourceConfig_desiredStateBooleanValue(rName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Enabled":true`)), ), }, { - Config: testAccResourceDesiredStateBooleanValueRemovedConfig(rName), + Config: testAccResourceConfig_desiredStateBooleanValueRemoved(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Enabled":false`)), ), @@ -132,13 +132,13 @@ func TestAccCloudControlResource_DesiredState_booleanValueUpdate(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateBooleanValueConfig(rName, true), + Config: testAccResourceConfig_desiredStateBooleanValue(rName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Enabled":true`)), ), }, { - Config: testAccResourceDesiredStateBooleanValueConfig(rName, false), + Config: testAccResourceConfig_desiredStateBooleanValue(rName, false), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Enabled":false`)), ), @@ -159,13 +159,13 @@ func TestAccCloudControlResource_DesiredState_createOnly(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateCreateOnlyConfig(rName1), + Config: testAccResourceConfig_desiredStateCreateOnly(rName1), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"LogGroupName":"`+rName1+`"`)), ), }, { - Config: testAccResourceDesiredStateCreateOnlyConfig(rName2), + Config: testAccResourceConfig_desiredStateCreateOnly(rName2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"LogGroupName":"`+rName2+`"`)), ), @@ -185,13 +185,13 @@ func TestAccCloudControlResource_DesiredState_integerValueAdded(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateIntegerValueRemovedConfig(rName), + Config: testAccResourceConfig_desiredStateIntegerValueRemoved(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"LogGroupName":`)), ), }, { - Config: testAccResourceDesiredStateIntegerValueConfig(rName, 14), + Config: testAccResourceConfig_desiredStateIntegerValue(rName, 14), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"RetentionInDays":14`)), ), @@ -211,13 +211,13 @@ func TestAccCloudControlResource_DesiredState_integerValueRemoved(t *testing.T) CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateIntegerValueConfig(rName, 14), + Config: testAccResourceConfig_desiredStateIntegerValue(rName, 14), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"RetentionInDays":14`)), ), }, { - Config: testAccResourceDesiredStateIntegerValueRemovedConfig(rName), + Config: testAccResourceConfig_desiredStateIntegerValueRemoved(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"LogGroupName":`)), ), @@ -237,13 +237,13 @@ func TestAccCloudControlResource_DesiredState_integerValueUpdate(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateIntegerValueConfig(rName, 7), + Config: testAccResourceConfig_desiredStateIntegerValue(rName, 7), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"RetentionInDays":7`)), ), }, { - Config: testAccResourceDesiredStateIntegerValueConfig(rName, 14), + Config: testAccResourceConfig_desiredStateIntegerValue(rName, 14), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"RetentionInDays":14`)), ), @@ -262,7 +262,7 @@ func TestAccCloudControlResource_DesiredState_invalidPropertyName(t *testing.T) CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateInvalidPropertyNameConfig(rName), + Config: testAccResourceConfig_desiredStateInvalidPropertyName(rName), ExpectError: regexp.MustCompile(`\(root\): Additional property InvalidName is not allowed`), }, }, @@ -279,7 +279,7 @@ func TestAccCloudControlResource_DesiredState_invalidPropertyValue(t *testing.T) CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateInvalidPropertyValueConfig(rName), + Config: testAccResourceConfig_desiredStateInvalidPropertyValue(rName), ExpectError: regexp.MustCompile(`Model validation failed`), }, }, @@ -297,13 +297,13 @@ func TestAccCloudControlResource_DesiredState_objectValueAdded(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateObjectValueRemovedConfig(rName), + Config: testAccResourceConfig_desiredStateObjectValueRemoved(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Name":`)), ), }, { - Config: testAccResourceDesiredStateObjectValue1Config(rName, "key1", "value1"), + Config: testAccResourceConfig_desiredStateObjectValue1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Value":"value1"`)), ), @@ -323,13 +323,13 @@ func TestAccCloudControlResource_DesiredState_objectValueRemoved(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateObjectValue1Config(rName, "key1", "value1"), + Config: testAccResourceConfig_desiredStateObjectValue1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Value":"value1"`)), ), }, { - Config: testAccResourceDesiredStateObjectValueRemovedConfig(rName), + Config: testAccResourceConfig_desiredStateObjectValueRemoved(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Name":`)), ), @@ -349,19 +349,19 @@ func TestAccCloudControlResource_DesiredState_objectValueUpdate(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateObjectValue1Config(rName, "key1", "value1"), + Config: testAccResourceConfig_desiredStateObjectValue1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Value":"value1"`)), ), }, { - Config: testAccResourceDesiredStateObjectValue1Config(rName, "key1", "value1updated"), + Config: testAccResourceConfig_desiredStateObjectValue1(rName, "key1", "value1updated"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Value":"value1updated"`)), ), }, { - Config: testAccResourceDesiredStateObjectValue1Config(rName, "key2", "value2"), + Config: testAccResourceConfig_desiredStateObjectValue1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Value":"value2"`)), ), @@ -381,13 +381,13 @@ func TestAccCloudControlResource_DesiredState_stringValueAdded(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateStringValueRemovedConfig(rName), + Config: testAccResourceConfig_desiredStateStringValueRemoved(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Name":`)), ), }, { - Config: testAccResourceDesiredStateStringValueConfig(rName, "description1"), + Config: testAccResourceConfig_desiredStateStringValue(rName, "description1"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Description":"description1"`)), ), @@ -407,13 +407,13 @@ func TestAccCloudControlResource_DesiredState_stringValueRemoved(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateStringValueConfig(rName, "description1"), + Config: testAccResourceConfig_desiredStateStringValue(rName, "description1"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Description":"description1"`)), ), }, { - Config: testAccResourceDesiredStateStringValueRemovedConfig(rName), + Config: testAccResourceConfig_desiredStateStringValueRemoved(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Name":`)), ), @@ -433,13 +433,13 @@ func TestAccCloudControlResource_DesiredState_stringValueUpdate(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceDesiredStateStringValueConfig(rName, "description1"), + Config: testAccResourceConfig_desiredStateStringValue(rName, "description1"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Description":"description1"`)), ), }, { - Config: testAccResourceDesiredStateStringValueConfig(rName, "description2"), + Config: testAccResourceConfig_desiredStateStringValue(rName, "description2"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(resourceName, "properties", regexp.MustCompile(`"Description":"description2"`)), ), @@ -459,7 +459,7 @@ func TestAccCloudControlResource_resourceSchema(t *testing.T) { CheckDestroy: testAccCheckResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceResourceSchemaConfig(rName), + Config: testAccResourceConfig_schema(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "schema", "data.aws_cloudformation_type.test", "schema"), ), @@ -492,7 +492,7 @@ func testAccCheckResourceDestroy(s *terraform.State) error { return nil } -func testAccResourceConfig(rName string) string { +func testAccResourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::Logs::LogGroup" @@ -504,7 +504,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName) } -func testAccResourceDesiredStateBooleanValueConfig(rName string, booleanValue bool) string { +func testAccResourceConfig_desiredStateBooleanValue(rName string, booleanValue bool) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::ApiGateway::ApiKey" @@ -518,7 +518,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName, booleanValue) } -func testAccResourceDesiredStateBooleanValueRemovedConfig(rName string) string { +func testAccResourceConfig_desiredStateBooleanValueRemoved(rName string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::ApiGateway::ApiKey" @@ -531,7 +531,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName) } -func testAccResourceDesiredStateCreateOnlyConfig(rName string) string { +func testAccResourceConfig_desiredStateCreateOnly(rName string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::Logs::LogGroup" @@ -543,7 +543,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName) } -func testAccResourceDesiredStateIntegerValueConfig(rName string, integerValue int) string { +func testAccResourceConfig_desiredStateIntegerValue(rName string, integerValue int) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::Logs::LogGroup" @@ -556,7 +556,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName, integerValue) } -func testAccResourceDesiredStateIntegerValueRemovedConfig(rName string) string { +func testAccResourceConfig_desiredStateIntegerValueRemoved(rName string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::Logs::LogGroup" @@ -568,7 +568,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName) } -func testAccResourceDesiredStateInvalidPropertyNameConfig(rName string) string { +func testAccResourceConfig_desiredStateInvalidPropertyName(rName string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::Logs::LogGroup" @@ -580,7 +580,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName) } -func testAccResourceDesiredStateInvalidPropertyValueConfig(rName string) string { +func testAccResourceConfig_desiredStateInvalidPropertyValue(rName string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::Logs::LogGroup" @@ -592,7 +592,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName) } -func testAccResourceDesiredStateObjectValue1Config(rName string, key1 string, value1 string) string { +func testAccResourceConfig_desiredStateObjectValue1(rName string, key1 string, value1 string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::ECS::Cluster" @@ -610,7 +610,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName, key1, value1) } -func testAccResourceDesiredStateObjectValueRemovedConfig(rName string) string { +func testAccResourceConfig_desiredStateObjectValueRemoved(rName string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::ECS::Cluster" @@ -622,7 +622,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName) } -func testAccResourceDesiredStateStringValueConfig(rName string, stringValue string) string { +func testAccResourceConfig_desiredStateStringValue(rName string, stringValue string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::Athena::WorkGroup" @@ -635,7 +635,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName, stringValue) } -func testAccResourceDesiredStateStringValueRemovedConfig(rName string) string { +func testAccResourceConfig_desiredStateStringValueRemoved(rName string) string { return fmt.Sprintf(` resource "aws_cloudcontrolapi_resource" "test" { type_name = "AWS::Athena::WorkGroup" @@ -647,7 +647,7 @@ resource "aws_cloudcontrolapi_resource" "test" { `, rName) } -func testAccResourceResourceSchemaConfig(rName string) string { +func testAccResourceConfig_schema(rName string) string { return fmt.Sprintf(` data "aws_cloudformation_type" "test" { type = "RESOURCE" diff --git a/internal/service/cloudformation/export_data_source_test.go b/internal/service/cloudformation/export_data_source_test.go index d251e97d814..91e8a86e704 100644 --- a/internal/service/cloudformation/export_data_source_test.go +++ b/internal/service/cloudformation/export_data_source_test.go @@ -20,7 +20,7 @@ func TestAccCloudFormationExportDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckExportStaticValueConfig(rName), + Config: testAccExportDataSourceConfig_staticValue(rName), PreventPostDestroyRefresh: true, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "value", "waiter"), @@ -41,7 +41,7 @@ func TestAccCloudFormationExportDataSource_resourceReference(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckExportResourceReferenceConfig(rName), + Config: testAccExportDataSourceConfig_resourceReference(rName), PreventPostDestroyRefresh: true, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "exporting_stack_id", resourceName, "id"), @@ -52,7 +52,7 @@ func TestAccCloudFormationExportDataSource_resourceReference(t *testing.T) { }) } -func testAccCheckExportStaticValueConfig(rName string) string { +func testAccExportDataSourceConfig_staticValue(rName string) string { return fmt.Sprintf(` resource "aws_cloudformation_stack" "test" { name = %[1]q @@ -89,7 +89,7 @@ data "aws_cloudformation_export" "test" { `, rName) } -func testAccCheckExportResourceReferenceConfig(rName string) string { +func testAccExportDataSourceConfig_resourceReference(rName string) string { return fmt.Sprintf(` resource "aws_cloudformation_stack" "test" { name = %[1]q diff --git a/internal/service/cloudformation/stack_data_source_test.go b/internal/service/cloudformation/stack_data_source_test.go index 229b11b5274..2b9abed9810 100644 --- a/internal/service/cloudformation/stack_data_source_test.go +++ b/internal/service/cloudformation/stack_data_source_test.go @@ -21,7 +21,7 @@ func TestAccCloudFormationStackDataSource_DataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckStackDataSourceConfig_basic(stackName), + Config: testAccStackDataSourceConfig_basic(stackName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "outputs.%", "1"), resource.TestMatchResourceAttr(resourceName, "outputs.VPCId", regexp.MustCompile("^vpc-[a-z0-9]+")), @@ -40,7 +40,7 @@ func TestAccCloudFormationStackDataSource_DataSource_basic(t *testing.T) { }) } -func testAccCheckStackDataSourceConfig_basic(stackName string) string { +func testAccStackDataSourceConfig_basic(stackName string) string { return fmt.Sprintf(` resource "aws_cloudformation_stack" "cfs" { name = "%s" @@ -107,7 +107,7 @@ func TestAccCloudFormationStackDataSource_DataSource_yaml(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckStackDataSourceConfig_yaml(stackName), + Config: testAccStackDataSourceConfig_yaml(stackName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "outputs.%", "1"), resource.TestMatchResourceAttr(resourceName, "outputs.VPCId", regexp.MustCompile("^vpc-[a-z0-9]+")), @@ -126,7 +126,7 @@ func TestAccCloudFormationStackDataSource_DataSource_yaml(t *testing.T) { }) } -func testAccCheckStackDataSourceConfig_yaml(stackName string) string { +func testAccStackDataSourceConfig_yaml(stackName string) string { return fmt.Sprintf(` resource "aws_cloudformation_stack" "yaml" { name = "%s" diff --git a/internal/service/cloudformation/stack_set_instance_test.go b/internal/service/cloudformation/stack_set_instance_test.go index 3e35d4c670f..83ce61ac4a4 100644 --- a/internal/service/cloudformation/stack_set_instance_test.go +++ b/internal/service/cloudformation/stack_set_instance_test.go @@ -28,7 +28,7 @@ func TestAccCloudFormationStackSetInstance_basic(t *testing.T) { CheckDestroy: testAccCheckStackSetInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetInstanceConfig(rName), + Config: testAccStackSetInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance1), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -66,7 +66,7 @@ func TestAccCloudFormationStackSetInstance_disappears(t *testing.T) { CheckDestroy: testAccCheckStackSetInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetInstanceConfig(rName), + Config: testAccStackSetInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance1), acctest.CheckResourceDisappears(acctest.Provider, tfcloudformation.ResourceStackSetInstance(), resourceName), @@ -91,7 +91,7 @@ func TestAccCloudFormationStackSetInstance_Disappears_stackSet(t *testing.T) { CheckDestroy: testAccCheckStackSetInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetInstanceConfig(rName), + Config: testAccStackSetInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(stackSetResourceName, &stackSet1), testAccCheckStackSetInstanceExists(resourceName, &stackInstance1), @@ -116,7 +116,7 @@ func TestAccCloudFormationStackSetInstance_parameterOverrides(t *testing.T) { CheckDestroy: testAccCheckStackSetInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetInstanceParameterOverrides1Config(rName, "overridevalue1"), + Config: testAccStackSetInstanceConfig_parameterOverrides1(rName, "overridevalue1"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance1), resource.TestCheckResourceAttr(resourceName, "parameter_overrides.%", "1"), @@ -133,7 +133,7 @@ func TestAccCloudFormationStackSetInstance_parameterOverrides(t *testing.T) { }, }, { - Config: testAccStackSetInstanceParameterOverrides2Config(rName, "overridevalue1updated", "overridevalue2"), + Config: testAccStackSetInstanceConfig_parameterOverrides2(rName, "overridevalue1updated", "overridevalue2"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance2), testAccCheckStackSetInstanceNotRecreated(&stackInstance1, &stackInstance2), @@ -143,7 +143,7 @@ func TestAccCloudFormationStackSetInstance_parameterOverrides(t *testing.T) { ), }, { - Config: testAccStackSetInstanceParameterOverrides1Config(rName, "overridevalue1updated"), + Config: testAccStackSetInstanceConfig_parameterOverrides1(rName, "overridevalue1updated"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance3), testAccCheckStackSetInstanceNotRecreated(&stackInstance2, &stackInstance3), @@ -152,7 +152,7 @@ func TestAccCloudFormationStackSetInstance_parameterOverrides(t *testing.T) { ), }, { - Config: testAccStackSetInstanceConfig(rName), + Config: testAccStackSetInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance4), testAccCheckStackSetInstanceNotRecreated(&stackInstance3, &stackInstance4), @@ -181,7 +181,7 @@ func TestAccCloudFormationStackSetInstance_retainStack(t *testing.T) { CheckDestroy: testAccCheckStackSetInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetInstanceRetainStackConfig(rName, true), + Config: testAccStackSetInstanceConfig_retain(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance1), resource.TestCheckResourceAttr(resourceName, "retain_stack", "true"), @@ -197,7 +197,7 @@ func TestAccCloudFormationStackSetInstance_retainStack(t *testing.T) { }, }, { - Config: testAccStackSetInstanceRetainStackConfig(rName, false), + Config: testAccStackSetInstanceConfig_retain(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance2), testAccCheckStackSetInstanceNotRecreated(&stackInstance1, &stackInstance2), @@ -205,7 +205,7 @@ func TestAccCloudFormationStackSetInstance_retainStack(t *testing.T) { ), }, { - Config: testAccStackSetInstanceRetainStackConfig(rName, true), + Config: testAccStackSetInstanceConfig_retain(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance3), testAccCheckStackSetInstanceNotRecreated(&stackInstance2, &stackInstance3), @@ -213,7 +213,7 @@ func TestAccCloudFormationStackSetInstance_retainStack(t *testing.T) { ), }, { - Config: testAccStackSetInstanceRetainStackConfig(rName, true), + Config: testAccStackSetInstanceConfig_retain(rName, true), Destroy: true, Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceStackExists(&stackInstance3, &stack1), @@ -242,7 +242,7 @@ func TestAccCloudFormationStackSetInstance_deploymentTargets(t *testing.T) { CheckDestroy: testAccCheckStackSetInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetInstanceDeploymentTargetsConfig(rName), + Config: testAccStackSetInstanceConfig_deploymentTargets(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance), resource.TestCheckResourceAttr(resourceName, "deployment_targets.#", "1"), @@ -260,7 +260,7 @@ func TestAccCloudFormationStackSetInstance_deploymentTargets(t *testing.T) { }, }, { - Config: testAccStackSetInstanceConfig_ServiceManagedStackSet(rName), + Config: testAccStackSetInstanceConfig_serviceManaged(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance), ), @@ -287,7 +287,7 @@ func TestAccCloudFormationStackSetInstance_operationPreferences(t *testing.T) { CheckDestroy: testAccCheckStackSetInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetInstanceOperationPreferencesConfig(rName), + Config: testAccStackSetInstanceConfig_operationPreferences(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance), resource.TestCheckResourceAttr(resourceName, "operation_preferences.#", "1"), @@ -299,7 +299,7 @@ func TestAccCloudFormationStackSetInstance_operationPreferences(t *testing.T) { ), }, { - Config: testAccStackSetInstanceConfig_ServiceManagedStackSet(rName), + Config: testAccStackSetInstanceConfig_serviceManaged(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetInstanceExists(resourceName, &stackInstance), ), @@ -525,7 +525,7 @@ TEMPLATE `, rName) } -func testAccStackSetInstanceConfig(rName string) string { +func testAccStackSetInstanceConfig_basic(rName string) string { return acctest.ConfigCompose(testAccStackSetInstanceBaseConfig(rName), ` resource "aws_cloudformation_stack_set_instance" "test" { depends_on = [aws_iam_role_policy.Administration, aws_iam_role_policy.Execution] @@ -535,7 +535,7 @@ resource "aws_cloudformation_stack_set_instance" "test" { `) } -func testAccStackSetInstanceParameterOverrides1Config(rName, value1 string) string { +func testAccStackSetInstanceConfig_parameterOverrides1(rName, value1 string) string { return acctest.ConfigCompose(testAccStackSetInstanceBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudformation_stack_set_instance" "test" { depends_on = [aws_iam_role_policy.Administration, aws_iam_role_policy.Execution] @@ -549,7 +549,7 @@ resource "aws_cloudformation_stack_set_instance" "test" { `, value1)) } -func testAccStackSetInstanceParameterOverrides2Config(rName, value1, value2 string) string { +func testAccStackSetInstanceConfig_parameterOverrides2(rName, value1, value2 string) string { return acctest.ConfigCompose(testAccStackSetInstanceBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudformation_stack_set_instance" "test" { depends_on = [aws_iam_role_policy.Administration, aws_iam_role_policy.Execution] @@ -564,7 +564,7 @@ resource "aws_cloudformation_stack_set_instance" "test" { `, value1, value2)) } -func testAccStackSetInstanceRetainStackConfig(rName string, retainStack bool) string { +func testAccStackSetInstanceConfig_retain(rName string, retainStack bool) string { return acctest.ConfigCompose(testAccStackSetInstanceBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudformation_stack_set_instance" "test" { depends_on = [aws_iam_role_policy.Administration, aws_iam_role_policy.Execution] @@ -691,7 +691,7 @@ TEMPLATE `, rName, testAccStackSetTemplateBodyVPC(rName)) } -func testAccStackSetInstanceDeploymentTargetsConfig(rName string) string { +func testAccStackSetInstanceConfig_deploymentTargets(rName string) string { return acctest.ConfigCompose(testAccStackSetInstanceBaseConfig_ServiceManagedStackSet(rName), ` resource "aws_cloudformation_stack_set_instance" "test" { depends_on = [aws_iam_role_policy.Administration, aws_iam_role_policy.Execution] @@ -705,7 +705,7 @@ resource "aws_cloudformation_stack_set_instance" "test" { `) } -func testAccStackSetInstanceConfig_ServiceManagedStackSet(rName string) string { +func testAccStackSetInstanceConfig_serviceManaged(rName string) string { return acctest.ConfigCompose(testAccStackSetInstanceBaseConfig_ServiceManagedStackSet(rName), ` resource "aws_cloudformation_stack_set_instance" "test" { depends_on = [aws_iam_role_policy.Administration, aws_iam_role_policy.Execution] @@ -715,7 +715,7 @@ resource "aws_cloudformation_stack_set_instance" "test" { `) } -func testAccStackSetInstanceOperationPreferencesConfig(rName string) string { +func testAccStackSetInstanceConfig_operationPreferences(rName string) string { return acctest.ConfigCompose(testAccStackSetInstanceBaseConfig_ServiceManagedStackSet(rName), ` resource "aws_cloudformation_stack_set_instance" "test" { depends_on = [aws_iam_role_policy.Administration, aws_iam_role_policy.Execution] diff --git a/internal/service/cloudformation/stack_set_test.go b/internal/service/cloudformation/stack_set_test.go index e7208ace99e..cd68489f080 100644 --- a/internal/service/cloudformation/stack_set_test.go +++ b/internal/service/cloudformation/stack_set_test.go @@ -30,7 +30,7 @@ func TestAccCloudFormationStackSet_basic(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetNameConfig(rName), + Config: testAccStackSetConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttrPair(resourceName, "administration_role_arn", iamRoleResourceName, "arn"), @@ -74,7 +74,7 @@ func TestAccCloudFormationStackSet_disappears(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetNameConfig(rName), + Config: testAccStackSetConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), acctest.CheckResourceDisappears(acctest.Provider, tfcloudformation.ResourceStackSet(), resourceName), @@ -99,7 +99,7 @@ func TestAccCloudFormationStackSet_administrationRoleARN(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetAdministrationRoleARN1Config(rName), + Config: testAccStackSetConfig_administrationRoleARN1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttrPair(resourceName, "administration_role_arn", iamRoleResourceName1, "arn"), @@ -115,7 +115,7 @@ func TestAccCloudFormationStackSet_administrationRoleARN(t *testing.T) { }, }, { - Config: testAccStackSetAdministrationRoleARN2Config(rName), + Config: testAccStackSetConfig_administrationRoleARN2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetNotRecreated(&stackSet1, &stackSet2), @@ -138,7 +138,7 @@ func TestAccCloudFormationStackSet_description(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetDescriptionConfig(rName, "description1"), + Config: testAccStackSetConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -154,7 +154,7 @@ func TestAccCloudFormationStackSet_description(t *testing.T) { }, }, { - Config: testAccStackSetDescriptionConfig(rName, "description2"), + Config: testAccStackSetConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetNotRecreated(&stackSet1, &stackSet2), @@ -177,7 +177,7 @@ func TestAccCloudFormationStackSet_executionRoleName(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetExecutionRoleNameConfig(rName, "name1"), + Config: testAccStackSetConfig_executionRoleName(rName, "name1"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "execution_role_name", "name1"), @@ -193,7 +193,7 @@ func TestAccCloudFormationStackSet_executionRoleName(t *testing.T) { }, }, { - Config: testAccStackSetExecutionRoleNameConfig(rName, "name2"), + Config: testAccStackSetConfig_executionRoleName(rName, "name2"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetNotRecreated(&stackSet1, &stackSet2), @@ -217,23 +217,23 @@ func TestAccCloudFormationStackSet_name(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetNameConfig(""), + Config: testAccStackSetConfig_name(""), ExpectError: regexp.MustCompile(`expected length`), }, { - Config: testAccStackSetNameConfig(sdkacctest.RandStringFromCharSet(129, sdkacctest.CharSetAlpha)), + Config: testAccStackSetConfig_name(sdkacctest.RandStringFromCharSet(129, sdkacctest.CharSetAlpha)), ExpectError: regexp.MustCompile(`(cannot be longer|expected length)`), }, { - Config: testAccStackSetNameConfig("1"), + Config: testAccStackSetConfig_name("1"), ExpectError: regexp.MustCompile(`must begin with alphabetic character`), }, { - Config: testAccStackSetNameConfig("a_b"), + Config: testAccStackSetConfig_name("a_b"), ExpectError: regexp.MustCompile(`must contain only alphanumeric and hyphen characters`), }, { - Config: testAccStackSetNameConfig(rName1), + Config: testAccStackSetConfig_name(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "name", rName1), @@ -249,7 +249,7 @@ func TestAccCloudFormationStackSet_name(t *testing.T) { }, }, { - Config: testAccStackSetNameConfig(rName2), + Config: testAccStackSetConfig_name(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetRecreated(&stackSet1, &stackSet2), @@ -272,7 +272,7 @@ func TestAccCloudFormationStackSet_operationPreferences(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetOperationPreferencesConfig(rName, 1, 10), + Config: testAccStackSetConfig_operationPreferences(rName, 1, 10), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet), resource.TestCheckResourceAttr(resourceName, "operation_preferences.#", "1"), @@ -294,7 +294,7 @@ func TestAccCloudFormationStackSet_operationPreferences(t *testing.T) { }, }, { - Config: testAccStackSetOperationPreferencesConfig(rName, 3, 12), + Config: testAccStackSetConfig_operationPreferences(rName, 3, 12), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet), resource.TestCheckResourceAttr(resourceName, "operation_preferences.#", "1"), @@ -306,7 +306,7 @@ func TestAccCloudFormationStackSet_operationPreferences(t *testing.T) { ), }, { - Config: testAccStackSetOperationPreferencesUpdatedConfig(rName, 15, 75), + Config: testAccStackSetConfig_operationPreferencesUpdated(rName, 15, 75), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet), resource.TestCheckResourceAttr(resourceName, "operation_preferences.#", "1"), @@ -318,7 +318,7 @@ func TestAccCloudFormationStackSet_operationPreferences(t *testing.T) { ), }, { - Config: testAccStackSetOperationPreferencesConfig(rName, 2, 8), + Config: testAccStackSetConfig_operationPreferences(rName, 2, 8), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet), resource.TestCheckResourceAttr(resourceName, "operation_preferences.#", "1"), @@ -330,7 +330,7 @@ func TestAccCloudFormationStackSet_operationPreferences(t *testing.T) { ), }, { - Config: testAccStackSetOperationPreferencesConfig(rName, 0, 3), + Config: testAccStackSetConfig_operationPreferences(rName, 0, 3), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet), resource.TestCheckResourceAttr(resourceName, "operation_preferences.#", "1"), @@ -342,7 +342,7 @@ func TestAccCloudFormationStackSet_operationPreferences(t *testing.T) { ), }, { - Config: testAccStackSetOperationPreferencesUpdatedConfig(rName, 0, 95), + Config: testAccStackSetConfig_operationPreferencesUpdated(rName, 0, 95), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet), resource.TestCheckResourceAttr(resourceName, "operation_preferences.#", "1"), @@ -369,7 +369,7 @@ func TestAccCloudFormationStackSet_parameters(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetParameters1Config(rName, "value1"), + Config: testAccStackSetConfig_parameters1(rName, "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "parameters.%", "1"), @@ -386,7 +386,7 @@ func TestAccCloudFormationStackSet_parameters(t *testing.T) { }, }, { - Config: testAccStackSetParameters2Config(rName, "value1updated", "value2"), + Config: testAccStackSetConfig_parameters2(rName, "value1updated", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetNotRecreated(&stackSet1, &stackSet2), @@ -396,7 +396,7 @@ func TestAccCloudFormationStackSet_parameters(t *testing.T) { ), }, { - Config: testAccStackSetParameters1Config(rName, "value1updated"), + Config: testAccStackSetConfig_parameters1(rName, "value1updated"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "parameters.%", "1"), @@ -404,7 +404,7 @@ func TestAccCloudFormationStackSet_parameters(t *testing.T) { ), }, { - Config: testAccStackSetNameConfig(rName), + Config: testAccStackSetConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "parameters.%", "0"), @@ -430,7 +430,7 @@ func TestAccCloudFormationStackSet_Parameters_default(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetParametersDefault0Config(rName), + Config: testAccStackSetConfig_parametersDefault0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "parameters.%", "1"), @@ -447,7 +447,7 @@ func TestAccCloudFormationStackSet_Parameters_default(t *testing.T) { }, }, { - Config: testAccStackSetParametersDefault1Config(rName, "value1"), + Config: testAccStackSetConfig_parametersDefault1(rName, "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetNotRecreated(&stackSet1, &stackSet2), @@ -456,7 +456,7 @@ func TestAccCloudFormationStackSet_Parameters_default(t *testing.T) { ), }, { - Config: testAccStackSetParametersDefault0Config(rName), + Config: testAccStackSetConfig_parametersDefault0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "parameters.%", "1"), @@ -483,7 +483,7 @@ func TestAccCloudFormationStackSet_Parameters_noEcho(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetParametersNoEcho1Config(rName, "value1"), + Config: testAccStackSetConfig_parametersNoEcho1(rName, "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "parameters.%", "1"), @@ -500,7 +500,7 @@ func TestAccCloudFormationStackSet_Parameters_noEcho(t *testing.T) { }, }, { - Config: testAccStackSetParametersNoEcho1Config(rName, "value2"), + Config: testAccStackSetConfig_parametersNoEcho1(rName, "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetNotRecreated(&stackSet1, &stackSet2), @@ -530,7 +530,7 @@ func TestAccCloudFormationStackSet_PermissionModel_serviceManaged(t *testing.T) CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetPermissionModelConfig(rName), + Config: testAccStackSetConfig_permissionModel(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "cloudformation", regexp.MustCompile(`stackset/.+`)), @@ -566,7 +566,7 @@ func TestAccCloudFormationStackSet_tags(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetTags1Config(rName, "value1"), + Config: testAccStackSetConfig_tags1(rName, "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -583,7 +583,7 @@ func TestAccCloudFormationStackSet_tags(t *testing.T) { }, }, { - Config: testAccStackSetTags2Config(rName, "value1updated", "value2"), + Config: testAccStackSetConfig_tags2(rName, "value1updated", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetNotRecreated(&stackSet1, &stackSet2), @@ -593,7 +593,7 @@ func TestAccCloudFormationStackSet_tags(t *testing.T) { ), }, { - Config: testAccStackSetTags1Config(rName, "value1updated"), + Config: testAccStackSetConfig_tags1(rName, "value1updated"), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -601,7 +601,7 @@ func TestAccCloudFormationStackSet_tags(t *testing.T) { ), }, { - Config: testAccStackSetNameConfig(rName), + Config: testAccStackSetConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -623,7 +623,7 @@ func TestAccCloudFormationStackSet_templateBody(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetTemplateBodyConfig(rName, testAccStackSetTemplateBodyVPC(rName+"1")), + Config: testAccStackSetConfig_templateBody(rName, testAccStackSetTemplateBodyVPC(rName+"1")), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttr(resourceName, "template_body", testAccStackSetTemplateBodyVPC(rName+"1")+"\n"), @@ -639,7 +639,7 @@ func TestAccCloudFormationStackSet_templateBody(t *testing.T) { }, }, { - Config: testAccStackSetTemplateBodyConfig(rName, testAccStackSetTemplateBodyVPC(rName+"2")), + Config: testAccStackSetConfig_templateBody(rName, testAccStackSetTemplateBodyVPC(rName+"2")), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetNotRecreated(&stackSet1, &stackSet2), @@ -662,7 +662,7 @@ func TestAccCloudFormationStackSet_templateURL(t *testing.T) { CheckDestroy: testAccCheckStackSetDestroy, Steps: []resource.TestStep{ { - Config: testAccStackSetTemplateURL1Config(rName), + Config: testAccStackSetConfig_templateURL1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet1), resource.TestCheckResourceAttrSet(resourceName, "template_body"), @@ -679,7 +679,7 @@ func TestAccCloudFormationStackSet_templateURL(t *testing.T) { }, }, { - Config: testAccStackSetTemplateURL2Config(rName), + Config: testAccStackSetConfig_templateURL2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackSetExists(resourceName, &stackSet2), testAccCheckStackSetNotRecreated(&stackSet1, &stackSet2), @@ -891,7 +891,7 @@ Outputs: `, rName) } -func testAccStackSetAdministrationRoleARN1Config(rName string) string { +func testAccStackSetConfig_administrationRoleARN1(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test1" { assume_role_policy = < 0 && v.([]interface{})[0] != nil { - input.LoggingConfig = expandCloudformationLoggingConfig(v.([]interface{})[0].(map[string]interface{})) + input.LoggingConfig = expandLoggingConfig(v.([]interface{})[0].(map[string]interface{})) } if v, ok := d.GetOk("type"); ok { @@ -204,7 +204,7 @@ func resourceTypeRead(ctx context.Context, d *schema.ResourceData, meta interfac d.Set("execution_role_arn", output.ExecutionRoleArn) d.Set("is_default_version", output.IsDefaultVersion) if output.LoggingConfig != nil { - if err := d.Set("logging_config", []interface{}{flattenCloudformationLoggingConfig(output.LoggingConfig)}); err != nil { + if err := d.Set("logging_config", []interface{}{flattenLoggingConfig(output.LoggingConfig)}); err != nil { return diag.FromErr(fmt.Errorf("error setting logging_config: %w", err)) } } else { @@ -295,7 +295,7 @@ func resourceTypeDelete(ctx context.Context, d *schema.ResourceData, meta interf return nil } -func expandCloudformationLoggingConfig(tfMap map[string]interface{}) *cloudformation.LoggingConfig { +func expandLoggingConfig(tfMap map[string]interface{}) *cloudformation.LoggingConfig { if tfMap == nil { return nil } @@ -354,7 +354,7 @@ func expandOperationPreferences(tfMap map[string]interface{}) *cloudformation.St return apiObject } -func flattenCloudformationLoggingConfig(apiObject *cloudformation.LoggingConfig) map[string]interface{} { +func flattenLoggingConfig(apiObject *cloudformation.LoggingConfig) map[string]interface{} { if apiObject == nil { return nil } diff --git a/internal/service/cloudformation/type_data_source.go b/internal/service/cloudformation/type_data_source.go index 2ee01743020..67302fbe57c 100644 --- a/internal/service/cloudformation/type_data_source.go +++ b/internal/service/cloudformation/type_data_source.go @@ -147,7 +147,7 @@ func dataSourceTypeRead(ctx context.Context, d *schema.ResourceData, meta interf d.Set("execution_role_arn", output.ExecutionRoleArn) d.Set("is_default_version", output.IsDefaultVersion) if output.LoggingConfig != nil { - if err := d.Set("logging_config", []interface{}{flattenCloudformationLoggingConfig(output.LoggingConfig)}); err != nil { + if err := d.Set("logging_config", []interface{}{flattenLoggingConfig(output.LoggingConfig)}); err != nil { return diag.FromErr(fmt.Errorf("error setting logging_config: %w", err)) } } else { diff --git a/internal/service/cloudformation/type_data_source_test.go b/internal/service/cloudformation/type_data_source_test.go index 94d3dc8483c..083f61a3a65 100644 --- a/internal/service/cloudformation/type_data_source_test.go +++ b/internal/service/cloudformation/type_data_source_test.go @@ -25,7 +25,7 @@ func TestAccCloudFormationTypeDataSource_ARN_private(t *testing.T) { CheckDestroy: testAccCheckTypeDestroy, Steps: []resource.TestStep{ { - Config: testAccTypeARNPrivateDataSourceConfig(rName, zipPath, typeName), + Config: testAccTypeDataSourceConfig_arnPrivate(rName, zipPath, typeName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "deprecated_status", resourceName, "deprecated_status"), @@ -56,7 +56,7 @@ func TestAccCloudFormationTypeDataSource_ARN_public(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccTypeARNPublicDataSourceConfig(), + Config: testAccTypeDataSourceConfig_arnPublic(), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckResourceAttrRegionalARNNoAccount(dataSourceName, "arn", "cloudformation", "type/resource/AWS-Athena-WorkGroup"), resource.TestCheckResourceAttr(dataSourceName, "deprecated_status", cloudformation.DeprecatedStatusLive), @@ -90,7 +90,7 @@ func TestAccCloudFormationTypeDataSource_TypeName_private(t *testing.T) { CheckDestroy: testAccCheckTypeDestroy, Steps: []resource.TestStep{ { - Config: testAccTypeTypeNamePrivateDataSourceConfig(rName, zipPath, typeName), + Config: testAccTypeDataSourceConfig_namePrivate(rName, zipPath, typeName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "deprecated_status", resourceName, "deprecated_status"), @@ -121,7 +121,7 @@ func TestAccCloudFormationTypeDataSource_TypeName_public(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccTypeTypeNamePublicDataSourceConfig(), + Config: testAccTypeDataSourceConfig_namePublic(), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckResourceAttrRegionalARNNoAccount(dataSourceName, "arn", "cloudformation", "type/resource/AWS-Athena-WorkGroup"), resource.TestCheckResourceAttr(dataSourceName, "deprecated_status", cloudformation.DeprecatedStatusLive), @@ -141,7 +141,7 @@ func TestAccCloudFormationTypeDataSource_TypeName_public(t *testing.T) { }) } -func testAccCloudformationTypeConfigPrivateBase(rName string, zipPath string, typeName string) string { +func testAccTypeConfig_privateBase(rName string, zipPath string, typeName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -164,9 +164,9 @@ resource "aws_cloudformation_type" "test" { `, rName, zipPath, typeName) } -func testAccTypeARNPrivateDataSourceConfig(rName string, zipPath string, typeName string) string { +func testAccTypeDataSourceConfig_arnPrivate(rName string, zipPath string, typeName string) string { return acctest.ConfigCompose( - testAccCloudformationTypeConfigPrivateBase(rName, zipPath, typeName), + testAccTypeConfig_privateBase(rName, zipPath, typeName), ` data "aws_cloudformation_type" "test" { arn = aws_cloudformation_type.test.arn @@ -174,7 +174,7 @@ data "aws_cloudformation_type" "test" { `) } -func testAccTypeARNPublicDataSourceConfig() string { +func testAccTypeDataSourceConfig_arnPublic() string { return ` data "aws_partition" "current" {} @@ -186,9 +186,9 @@ data "aws_cloudformation_type" "test" { ` } -func testAccTypeTypeNamePrivateDataSourceConfig(rName string, zipPath string, typeName string) string { +func testAccTypeDataSourceConfig_namePrivate(rName string, zipPath string, typeName string) string { return acctest.ConfigCompose( - testAccCloudformationTypeConfigPrivateBase(rName, zipPath, typeName), + testAccTypeConfig_privateBase(rName, zipPath, typeName), ` data "aws_cloudformation_type" "test" { type = aws_cloudformation_type.test.type @@ -197,7 +197,7 @@ data "aws_cloudformation_type" "test" { `) } -func testAccTypeTypeNamePublicDataSourceConfig() string { +func testAccTypeDataSourceConfig_namePublic() string { return ` data "aws_cloudformation_type" "test" { type = "RESOURCE" diff --git a/internal/service/cloudformation/type_test.go b/internal/service/cloudformation/type_test.go index 89ea941f2da..82c76df4f85 100644 --- a/internal/service/cloudformation/type_test.go +++ b/internal/service/cloudformation/type_test.go @@ -36,7 +36,7 @@ func TestAccCloudFormationType_basic(t *testing.T) { CheckDestroy: testAccCheckTypeDestroy, Steps: []resource.TestStep{ { - Config: testAccCloudformationTypeConfigTypeName(rName, zipPath, typeName), + Config: testAccTypeConfig_name(rName, zipPath, typeName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTypeExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "cloudformation", regexp.MustCompile(fmt.Sprintf("type/resource/%s/.+", strings.ReplaceAll(typeName, "::", "-")))), @@ -74,7 +74,7 @@ func TestAccCloudFormationType_disappears(t *testing.T) { CheckDestroy: testAccCheckTypeDestroy, Steps: []resource.TestStep{ { - Config: testAccCloudformationTypeConfigTypeName(rName, zipPath, typeName), + Config: testAccTypeConfig_name(rName, zipPath, typeName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTypeExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudformation.ResourceType(), resourceName), @@ -101,7 +101,7 @@ func TestAccCloudFormationType_executionRoleARN(t *testing.T) { CheckDestroy: testAccCheckTypeDestroy, Steps: []resource.TestStep{ { - Config: testAccCloudformationTypeConfigExecutionRoleArn(rName, zipPath, typeName), + Config: testAccTypeConfig_executionRoleARN(rName, zipPath, typeName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTypeExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "execution_role_arn", iamRoleResourceName, "arn"), @@ -126,7 +126,7 @@ func TestAccCloudFormationType_logging(t *testing.T) { CheckDestroy: testAccCheckTypeDestroy, Steps: []resource.TestStep{ { - Config: testAccCloudformationTypeConfigLoggingConfig(rName, zipPath, typeName), + Config: testAccTypeConfig_logging(rName, zipPath, typeName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTypeExists(resourceName), resource.TestCheckResourceAttr(resourceName, "logging_config.#", "1"), @@ -368,7 +368,7 @@ func testAccTypeCopyFileWithTypeNameReplacement(sourceFilePath string, targetFil return nil } -func testAccCloudformationTypeConfigBase(rName string, zipPath string) string { +func testAccTypeConfig_base(rName string, zipPath string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -385,9 +385,9 @@ resource "aws_s3_object" "test" { `, rName, zipPath) } -func testAccCloudformationTypeConfigExecutionRoleArn(rName string, zipPath string, typeName string) string { +func testAccTypeConfig_executionRoleARN(rName string, zipPath string, typeName string) string { return acctest.ConfigCompose( - testAccCloudformationTypeConfigBase(rName, zipPath), + testAccTypeConfig_base(rName, zipPath), fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -413,9 +413,9 @@ resource "aws_cloudformation_type" "test" { `, rName, typeName)) } -func testAccCloudformationTypeConfigLoggingConfig(rName string, zipPath string, typeName string) string { +func testAccTypeConfig_logging(rName string, zipPath string, typeName string) string { return acctest.ConfigCompose( - testAccCloudformationTypeConfigBase(rName, zipPath), + testAccTypeConfig_base(rName, zipPath), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = %[1]q @@ -449,9 +449,9 @@ resource "aws_cloudformation_type" "test" { `, rName, typeName)) } -func testAccCloudformationTypeConfigTypeName(rName string, zipPath string, typeName string) string { +func testAccTypeConfig_name(rName string, zipPath string, typeName string) string { return acctest.ConfigCompose( - testAccCloudformationTypeConfigBase(rName, zipPath), + testAccTypeConfig_base(rName, zipPath), fmt.Sprintf(` resource "aws_cloudformation_type" "test" { schema_handler_package = "s3://${aws_s3_object.test.bucket}/${aws_s3_object.test.key}" diff --git a/internal/service/cloudfront/cache_policy_data_source_test.go b/internal/service/cloudfront/cache_policy_data_source_test.go index 4bef57cff01..1aa60b50119 100644 --- a/internal/service/cloudfront/cache_policy_data_source_test.go +++ b/internal/service/cloudfront/cache_policy_data_source_test.go @@ -23,7 +23,7 @@ func TestAccCloudFrontCachePolicyDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckPublicKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccCachePolicyDataSourceConfig(rName), + Config: testAccCachePolicyDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSource1Name, "comment", resourceName, "comment"), resource.TestCheckResourceAttrPair(dataSource1Name, "default_ttl", resourceName, "default_ttl"), @@ -64,7 +64,7 @@ func TestAccCloudFrontCachePolicyDataSource_basic(t *testing.T) { }) } -func testAccCachePolicyDataSourceConfig(rName string) string { +func testAccCachePolicyDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_cloudfront_cache_policy" "by_name" { name = aws_cloudfront_cache_policy.test.name diff --git a/internal/service/cloudfront/cache_policy_test.go b/internal/service/cloudfront/cache_policy_test.go index ad6b1d853a7..4bc07188ca3 100644 --- a/internal/service/cloudfront/cache_policy_test.go +++ b/internal/service/cloudfront/cache_policy_test.go @@ -25,7 +25,7 @@ func TestAccCloudFrontCachePolicy_basic(t *testing.T) { CheckDestroy: testAccCheckCachePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccCachePolicyConfig(rName), + Config: testAccCachePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachePolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", ""), @@ -68,7 +68,7 @@ func TestAccCloudFrontCachePolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckCachePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccCachePolicyConfig(rName), + Config: testAccCachePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachePolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceCachePolicy(), resourceName), @@ -90,7 +90,7 @@ func TestAccCloudFrontCachePolicy_Items(t *testing.T) { CheckDestroy: testAccCheckCachePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccCachePolicyItemsConfig(rName), + Config: testAccCachePolicyConfig_items(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachePolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", "test comment"), @@ -128,7 +128,7 @@ func TestAccCloudFrontCachePolicy_Items(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCachePolicyItemsUpdatedConfig(rName), + Config: testAccCachePolicyConfig_itemsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachePolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", "test comment updated"), @@ -171,7 +171,7 @@ func TestAccCloudFrontCachePolicy_ZeroTTLs(t *testing.T) { CheckDestroy: testAccCheckCachePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccCachePolicyZeroTTLsConfig(rName), + Config: testAccCachePolicyConfig_zeroTTLs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachePolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", ""), @@ -250,7 +250,7 @@ func testAccCheckCachePolicyExists(n string) resource.TestCheckFunc { } } -func testAccCachePolicyConfig(rName string) string { +func testAccCachePolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_cache_policy" "test" { name = %[1]q @@ -272,7 +272,7 @@ resource "aws_cloudfront_cache_policy" "test" { `, rName) } -func testAccCachePolicyItemsConfig(rName string) string { +func testAccCachePolicyConfig_items(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_cache_policy" "test" { name = %[1]q @@ -313,7 +313,7 @@ resource "aws_cloudfront_cache_policy" "test" { `, rName) } -func testAccCachePolicyItemsUpdatedConfig(rName string) string { +func testAccCachePolicyConfig_itemsUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_cache_policy" "test" { name = %[1]q @@ -350,7 +350,7 @@ resource "aws_cloudfront_cache_policy" "test" { `, rName) } -func testAccCachePolicyZeroTTLsConfig(rName string) string { +func testAccCachePolicyConfig_zeroTTLs(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_cache_policy" "test" { name = %[1]q diff --git a/internal/service/cloudfront/cloudfront_test.go b/internal/service/cloudfront/cloudfront_test.go index f3aca1a2c4e..45c31c33d98 100644 --- a/internal/service/cloudfront/cloudfront_test.go +++ b/internal/service/cloudfront/cloudfront_test.go @@ -5,11 +5,11 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" ) -// testAccCloudfrontRegionProviderConfig is the Terraform provider configuration for CloudFront region testing +// testAccRegionProviderConfig is the Terraform provider configuration for CloudFront region testing // // Testing CloudFront assumes no other provider configurations // are necessary and overwrites the "aws" provider configuration. -func testAccCloudfrontRegionProviderConfig() string { +func testAccRegionProviderConfig() string { switch acctest.Partition() { case endpoints.AwsPartitionID: return acctest.ConfigRegionalProvider(endpoints.UsEast1RegionID) diff --git a/internal/service/cloudfront/distribution.go b/internal/service/cloudfront/distribution.go index 899cae2e29b..3d34f2cf1c2 100644 --- a/internal/service/cloudfront/distribution.go +++ b/internal/service/cloudfront/distribution.go @@ -898,10 +898,10 @@ func resourceDistributionRead(d *schema.ResourceData, meta interface{}) error { } // Update other attributes outside of DistributionConfig - if err := d.Set("trusted_key_groups", flattenCloudfrontActiveTrustedKeyGroups(resp.Distribution.ActiveTrustedKeyGroups)); err != nil { + if err := d.Set("trusted_key_groups", flattenActiveTrustedKeyGroups(resp.Distribution.ActiveTrustedKeyGroups)); err != nil { return fmt.Errorf("error setting trusted_key_groups: %w", err) } - if err := d.Set("trusted_signers", flattenCloudfrontActiveTrustedSigners(resp.Distribution.ActiveTrustedSigners)); err != nil { + if err := d.Set("trusted_signers", flattenActiveTrustedSigners(resp.Distribution.ActiveTrustedSigners)); err != nil { return fmt.Errorf("error setting trusted_signers: %w", err) } d.Set("status", resp.Distribution.Status) @@ -914,9 +914,9 @@ func resourceDistributionRead(d *schema.ResourceData, meta interface{}) error { // override hosted_zone_id from flattenDistributionConfig region := meta.(*conns.AWSClient).Region if v, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), region); ok && v.ID() == endpoints.AwsCnPartitionID { - d.Set("hosted_zone_id", cloudFrontCNRoute53ZoneID) + d.Set("hosted_zone_id", cnRoute53ZoneID) } else { - d.Set("hosted_zone_id", cloudFrontRoute53ZoneID) + d.Set("hosted_zone_id", route53ZoneID) } tags, err := ListTags(conn, d.Get("arn").(string)) diff --git a/internal/service/cloudfront/distribution_configuration_structure.go b/internal/service/cloudfront/distribution_configuration_structure.go index b5b1e13b2c3..a65379742bf 100644 --- a/internal/service/cloudfront/distribution_configuration_structure.go +++ b/internal/service/cloudfront/distribution_configuration_structure.go @@ -20,14 +20,14 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/flex" ) -// cloudFrontRoute53ZoneID defines the route 53 zone ID for CloudFront. This +// route53ZoneID defines the route 53 zone ID for CloudFront. This // is used to set the zone_id attribute. -const cloudFrontRoute53ZoneID = "Z2FDTNDATAQYW2" +const route53ZoneID = "Z2FDTNDATAQYW2" -// cloudFrontCNRoute53ZoneID defines the route 53 zone ID for CloudFront in AWS CN. +// cnRoute53ZoneID defines the route 53 zone ID for CloudFront in AWS CN. // This is used to set the zone_id attribute. // ref: https://docs.amazonaws.cn/en_us/aws/latest/userguide/route53.html -const cloudFrontCNRoute53ZoneID = "Z3RFFRIM2A3IF5" +const cnRoute53ZoneID = "Z3RFFRIM2A3IF5" // Assemble the *cloudfront.DistributionConfig variable. Calls out to various // expander functions to convert attributes and sub-attributes to the various @@ -90,7 +90,7 @@ func flattenDistributionConfig(d *schema.ResourceData, distributionConfig *cloud d.Set("enabled", distributionConfig.Enabled) d.Set("is_ipv6_enabled", distributionConfig.IsIPV6Enabled) d.Set("price_class", distributionConfig.PriceClass) - d.Set("hosted_zone_id", cloudFrontRoute53ZoneID) + d.Set("hosted_zone_id", route53ZoneID) err = d.Set("default_cache_behavior", []interface{}{flattenDefaultCacheBehavior(distributionConfig.DefaultCacheBehavior)}) if err != nil { @@ -1302,20 +1302,20 @@ func flattenViewerCertificate(vc *cloudfront.ViewerCertificate) []interface{} { return []interface{}{m} } -func flattenCloudfrontActiveTrustedKeyGroups(atkg *cloudfront.ActiveTrustedKeyGroups) []interface{} { +func flattenActiveTrustedKeyGroups(atkg *cloudfront.ActiveTrustedKeyGroups) []interface{} { if atkg == nil { return []interface{}{} } m := map[string]interface{}{ "enabled": aws.BoolValue(atkg.Enabled), - "items": flattenCloudfrontKGKeyPairIds(atkg.Items), + "items": flattenKGKeyPairIds(atkg.Items), } return []interface{}{m} } -func flattenCloudfrontKGKeyPairIds(keyPairIds []*cloudfront.KGKeyPairIds) []interface{} { +func flattenKGKeyPairIds(keyPairIds []*cloudfront.KGKeyPairIds) []interface{} { result := make([]interface{}, 0, len(keyPairIds)) for _, keyPairId := range keyPairIds { @@ -1330,20 +1330,20 @@ func flattenCloudfrontKGKeyPairIds(keyPairIds []*cloudfront.KGKeyPairIds) []inte return result } -func flattenCloudfrontActiveTrustedSigners(ats *cloudfront.ActiveTrustedSigners) []interface{} { +func flattenActiveTrustedSigners(ats *cloudfront.ActiveTrustedSigners) []interface{} { if ats == nil { return []interface{}{} } m := map[string]interface{}{ "enabled": aws.BoolValue(ats.Enabled), - "items": flattenCloudfrontSigners(ats.Items), + "items": flattenSigners(ats.Items), } return []interface{}{m} } -func flattenCloudfrontSigners(signers []*cloudfront.Signer) []interface{} { +func flattenSigners(signers []*cloudfront.Signer) []interface{} { result := make([]interface{}, 0, len(signers)) for _, signer := range signers { diff --git a/internal/service/cloudfront/distribution_configuration_structure_test.go b/internal/service/cloudfront/distribution_configuration_structure_test.go index c97109f8fee..d4cf8ac6ceb 100644 --- a/internal/service/cloudfront/distribution_configuration_structure_test.go +++ b/internal/service/cloudfront/distribution_configuration_structure_test.go @@ -129,13 +129,13 @@ func customOriginConf() map[string]interface{} { "origin_protocol_policy": "http-only", "http_port": 80, "https_port": 443, - "origin_ssl_protocols": customOriginSslProtocolsConf(), + "origin_ssl_protocols": customOriginSSLProtocolsConf(), "origin_read_timeout": 30, "origin_keepalive_timeout": 5, } } -func customOriginSslProtocolsConf() *schema.Set { +func customOriginSSLProtocolsConf() *schema.Set { return schema.NewSet(schema.HashString, []interface{}{"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}) } @@ -295,7 +295,7 @@ func viewerCertificateConfSetACM() map[string]interface{} { } } -func TestCloudFrontStructure_expandCloudFrontDefaultCacheBehavior(t *testing.T) { +func TestStructure_expandDefaultCacheBehavior(t *testing.T) { data := defaultCacheBehaviorConf() dcb := tfcloudfront.ExpandDefaultCacheBehavior(data) if dcb == nil { @@ -342,7 +342,7 @@ func TestCloudFrontStructure_expandCloudFrontDefaultCacheBehavior(t *testing.T) } } -func TestCloudFrontStructure_expandTrustedSigners(t *testing.T) { +func TestStructure_expandTrustedSigners(t *testing.T) { data := trustedSignersConf() ts := tfcloudfront.ExpandTrustedSigners(data) if *ts.Quantity != 2 { @@ -356,7 +356,7 @@ func TestCloudFrontStructure_expandTrustedSigners(t *testing.T) { } } -func TestCloudFrontStructure_flattenTrustedSigners(t *testing.T) { +func TestStructure_flattenTrustedSigners(t *testing.T) { in := trustedSignersConf() ts := tfcloudfront.ExpandTrustedSigners(in) out := tfcloudfront.FlattenTrustedSigners(ts) @@ -366,7 +366,7 @@ func TestCloudFrontStructure_flattenTrustedSigners(t *testing.T) { } } -func TestCloudFrontStructure_expandTrustedSigners_empty(t *testing.T) { +func TestStructure_expandTrustedSigners_empty(t *testing.T) { data := []interface{}{} ts := tfcloudfront.ExpandTrustedSigners(data) if *ts.Quantity != 0 { @@ -380,7 +380,7 @@ func TestCloudFrontStructure_expandTrustedSigners_empty(t *testing.T) { } } -func TestCloudFrontStructure_expandLambdaFunctionAssociations(t *testing.T) { +func TestStructure_expandLambdaFunctionAssociations(t *testing.T) { data := lambdaFunctionAssociationsConf() lfa := tfcloudfront.ExpandLambdaFunctionAssociations(data.List()) if *lfa.Quantity != 2 { @@ -397,7 +397,7 @@ func TestCloudFrontStructure_expandLambdaFunctionAssociations(t *testing.T) { } } -func TestCloudFrontStructure_flattenlambdaFunctionAssociations(t *testing.T) { +func TestStructure_flattenlambdaFunctionAssociations(t *testing.T) { in := lambdaFunctionAssociationsConf() lfa := tfcloudfront.ExpandLambdaFunctionAssociations(in.List()) out := tfcloudfront.FlattenLambdaFunctionAssociations(lfa) @@ -407,7 +407,7 @@ func TestCloudFrontStructure_flattenlambdaFunctionAssociations(t *testing.T) { } } -func TestCloudFrontStructure_expandlambdaFunctionAssociations_empty(t *testing.T) { +func TestStructure_expandlambdaFunctionAssociations_empty(t *testing.T) { data := new(schema.Set) lfa := tfcloudfront.ExpandLambdaFunctionAssociations(data.List()) if *lfa.Quantity != 0 { @@ -421,7 +421,7 @@ func TestCloudFrontStructure_expandlambdaFunctionAssociations_empty(t *testing.T } } -func TestCloudFrontStructure_expandFunctionAssociations(t *testing.T) { +func TestStructure_expandFunctionAssociations(t *testing.T) { data := functionAssociationsConf() lfa := tfcloudfront.ExpandFunctionAssociations(data.List()) if *lfa.Quantity != 2 { @@ -438,7 +438,7 @@ func TestCloudFrontStructure_expandFunctionAssociations(t *testing.T) { } } -func TestCloudFrontStructure_flattenFunctionAssociations(t *testing.T) { +func TestStructure_flattenFunctionAssociations(t *testing.T) { in := functionAssociationsConf() lfa := tfcloudfront.ExpandFunctionAssociations(in.List()) out := tfcloudfront.FlattenFunctionAssociations(lfa) @@ -448,7 +448,7 @@ func TestCloudFrontStructure_flattenFunctionAssociations(t *testing.T) { } } -func TestCloudFrontStructure_expandFunctionAssociations_empty(t *testing.T) { +func TestStructure_expandFunctionAssociations_empty(t *testing.T) { data := new(schema.Set) lfa := tfcloudfront.ExpandFunctionAssociations(data.List()) if *lfa.Quantity != 0 { @@ -462,7 +462,7 @@ func TestCloudFrontStructure_expandFunctionAssociations_empty(t *testing.T) { } } -func TestCloudFrontStructure_expandForwardedValues(t *testing.T) { +func TestStructure_expandForwardedValues(t *testing.T) { data := forwardedValuesConf() fv := tfcloudfront.ExpandForwardedValues(data) if !*fv.QueryString { @@ -476,7 +476,7 @@ func TestCloudFrontStructure_expandForwardedValues(t *testing.T) { } } -func TestCloudFrontStructure_flattenForwardedValues(t *testing.T) { +func TestStructure_flattenForwardedValues(t *testing.T) { in := forwardedValuesConf() fv := tfcloudfront.ExpandForwardedValues(in) out := tfcloudfront.FlattenForwardedValues(fv) @@ -486,7 +486,7 @@ func TestCloudFrontStructure_flattenForwardedValues(t *testing.T) { } } -func TestCloudFrontStructure_expandHeaders(t *testing.T) { +func TestStructure_expandHeaders(t *testing.T) { data := headersConf() h := tfcloudfront.ExpandHeaders(data.List()) if *h.Quantity != 2 { @@ -497,7 +497,7 @@ func TestCloudFrontStructure_expandHeaders(t *testing.T) { } } -func TestCloudFrontStructure_flattenHeaders(t *testing.T) { +func TestStructure_flattenHeaders(t *testing.T) { in := headersConf() h := tfcloudfront.ExpandHeaders(in.List()) out := schema.NewSet(schema.HashString, tfcloudfront.FlattenHeaders(h)) @@ -507,7 +507,7 @@ func TestCloudFrontStructure_flattenHeaders(t *testing.T) { } } -func TestCloudFrontStructure_expandQueryStringCacheKeys(t *testing.T) { +func TestStructure_expandQueryStringCacheKeys(t *testing.T) { data := queryStringCacheKeysConf() k := tfcloudfront.ExpandQueryStringCacheKeys(data) if *k.Quantity != 2 { @@ -518,7 +518,7 @@ func TestCloudFrontStructure_expandQueryStringCacheKeys(t *testing.T) { } } -func TestCloudFrontStructure_flattenQueryStringCacheKeys(t *testing.T) { +func TestStructure_flattenQueryStringCacheKeys(t *testing.T) { in := queryStringCacheKeysConf() k := tfcloudfront.ExpandQueryStringCacheKeys(in) out := tfcloudfront.FlattenQueryStringCacheKeys(k) @@ -528,7 +528,7 @@ func TestCloudFrontStructure_flattenQueryStringCacheKeys(t *testing.T) { } } -func TestCloudFrontStructure_expandCookiePreference(t *testing.T) { +func TestStructure_expandCookiePreference(t *testing.T) { data := cookiePreferenceConf() cp := tfcloudfront.ExpandCookiePreference(data) if *cp.Forward != "whitelist" { @@ -539,7 +539,7 @@ func TestCloudFrontStructure_expandCookiePreference(t *testing.T) { } } -func TestCloudFrontStructure_flattenCookiePreference(t *testing.T) { +func TestStructure_flattenCookiePreference(t *testing.T) { in := cookiePreferenceConf() cp := tfcloudfront.ExpandCookiePreference(in) out := tfcloudfront.FlattenCookiePreference(cp) @@ -549,7 +549,7 @@ func TestCloudFrontStructure_flattenCookiePreference(t *testing.T) { } } -func TestCloudFrontStructure_expandCookieNames(t *testing.T) { +func TestStructure_expandCookieNames(t *testing.T) { data := cookieNamesConf() cn := tfcloudfront.ExpandCookieNames(data.List()) if *cn.Quantity != 2 { @@ -560,7 +560,7 @@ func TestCloudFrontStructure_expandCookieNames(t *testing.T) { } } -func TestCloudFrontStructure_flattenCookieNames(t *testing.T) { +func TestStructure_flattenCookieNames(t *testing.T) { in := cookieNamesConf() cn := tfcloudfront.ExpandCookieNames(in.List()) out := schema.NewSet(schema.HashString, tfcloudfront.FlattenCookieNames(cn)) @@ -570,7 +570,7 @@ func TestCloudFrontStructure_flattenCookieNames(t *testing.T) { } } -func TestCloudFrontStructure_expandAllowedMethods(t *testing.T) { +func TestStructure_expandAllowedMethods(t *testing.T) { data := allowedMethodsConf() am := tfcloudfront.ExpandAllowedMethods(data) if *am.Quantity != 7 { @@ -581,7 +581,7 @@ func TestCloudFrontStructure_expandAllowedMethods(t *testing.T) { } } -func TestCloudFrontStructure_flattenAllowedMethods(t *testing.T) { +func TestStructure_flattenAllowedMethods(t *testing.T) { in := allowedMethodsConf() am := tfcloudfront.ExpandAllowedMethods(in) out := tfcloudfront.FlattenAllowedMethods(am) @@ -591,7 +591,7 @@ func TestCloudFrontStructure_flattenAllowedMethods(t *testing.T) { } } -func TestCloudFrontStructure_expandCachedMethods(t *testing.T) { +func TestStructure_expandCachedMethods(t *testing.T) { data := cachedMethodsConf() cm := tfcloudfront.ExpandCachedMethods(data) if *cm.Quantity != 3 { @@ -602,7 +602,7 @@ func TestCloudFrontStructure_expandCachedMethods(t *testing.T) { } } -func TestCloudFrontStructure_flattenCachedMethods(t *testing.T) { +func TestStructure_flattenCachedMethods(t *testing.T) { in := cachedMethodsConf() cm := tfcloudfront.ExpandCachedMethods(in) out := tfcloudfront.FlattenCachedMethods(cm) @@ -612,7 +612,7 @@ func TestCloudFrontStructure_flattenCachedMethods(t *testing.T) { } } -func TestCloudFrontStructure_expandOrigins(t *testing.T) { +func TestStructure_expandOrigins(t *testing.T) { data := multiOriginConf() origins := tfcloudfront.ExpandOrigins(data) if *origins.Quantity != 2 { @@ -623,7 +623,7 @@ func TestCloudFrontStructure_expandOrigins(t *testing.T) { } } -func TestCloudFrontStructure_flattenOrigins(t *testing.T) { +func TestStructure_flattenOrigins(t *testing.T) { in := multiOriginConf() origins := tfcloudfront.ExpandOrigins(in) out := tfcloudfront.FlattenOrigins(origins) @@ -634,7 +634,7 @@ func TestCloudFrontStructure_flattenOrigins(t *testing.T) { } } -func TestCloudFrontStructure_expandOriginGroups(t *testing.T) { +func TestStructure_expandOriginGroups(t *testing.T) { in := originGroupsConf() groups := tfcloudfront.ExpandOriginGroups(in) @@ -670,7 +670,7 @@ func TestCloudFrontStructure_expandOriginGroups(t *testing.T) { } } -func TestCloudFrontStructure_flattenOriginGroups(t *testing.T) { +func TestStructure_flattenOriginGroups(t *testing.T) { in := originGroupsConf() groups := tfcloudfront.ExpandOriginGroups(in) out := tfcloudfront.FlattenOriginGroups(groups) @@ -681,7 +681,7 @@ func TestCloudFrontStructure_flattenOriginGroups(t *testing.T) { } } -func TestCloudFrontStructure_expandOrigin(t *testing.T) { +func TestStructure_expandOrigin(t *testing.T) { data := originWithCustomConf() or := tfcloudfront.ExpandOrigin(data) if *or.Id != "CustomOrigin" { @@ -701,7 +701,7 @@ func TestCloudFrontStructure_expandOrigin(t *testing.T) { } } -func TestCloudFrontStructure_flattenOrigin(t *testing.T) { +func TestStructure_flattenOrigin(t *testing.T) { in := originWithCustomConf() or := tfcloudfront.ExpandOrigin(in) out := tfcloudfront.FlattenOrigin(or) @@ -717,7 +717,7 @@ func TestCloudFrontStructure_flattenOrigin(t *testing.T) { } } -func TestCloudFrontStructure_expandCustomHeaders(t *testing.T) { +func TestStructure_expandCustomHeaders(t *testing.T) { in := originCustomHeadersConf() chs := tfcloudfront.ExpandCustomHeaders(in) if *chs.Quantity != 2 { @@ -728,7 +728,7 @@ func TestCloudFrontStructure_expandCustomHeaders(t *testing.T) { } } -func TestCloudFrontStructure_flattenCustomHeaders(t *testing.T) { +func TestStructure_flattenCustomHeaders(t *testing.T) { in := originCustomHeadersConf() chs := tfcloudfront.ExpandCustomHeaders(in) out := tfcloudfront.FlattenCustomHeaders(chs) @@ -739,7 +739,7 @@ func TestCloudFrontStructure_flattenCustomHeaders(t *testing.T) { } } -func TestCloudFrontStructure_flattenOriginCustomHeader(t *testing.T) { +func TestStructure_flattenOriginCustomHeader(t *testing.T) { in := originCustomHeaderConf1() och := tfcloudfront.ExpandOriginCustomHeader(in) out := tfcloudfront.FlattenOriginCustomHeader(och) @@ -752,7 +752,7 @@ func TestCloudFrontStructure_flattenOriginCustomHeader(t *testing.T) { } } -func TestCloudFrontStructure_expandOriginCustomHeader(t *testing.T) { +func TestStructure_expandOriginCustomHeader(t *testing.T) { in := originCustomHeaderConf1() och := tfcloudfront.ExpandOriginCustomHeader(in) @@ -764,7 +764,7 @@ func TestCloudFrontStructure_expandOriginCustomHeader(t *testing.T) { } } -func TestCloudFrontStructure_expandCustomOriginConfig(t *testing.T) { +func TestStructure_expandCustomOriginConfig(t *testing.T) { data := customOriginConf() co := tfcloudfront.ExpandCustomOriginConfig(data) if *co.OriginProtocolPolicy != "http-only" { @@ -784,7 +784,7 @@ func TestCloudFrontStructure_expandCustomOriginConfig(t *testing.T) { } } -func TestCloudFrontStructure_flattenCustomOriginConfig(t *testing.T) { +func TestStructure_flattenCustomOriginConfig(t *testing.T) { in := customOriginConf() co := tfcloudfront.ExpandCustomOriginConfig(in) out := tfcloudfront.FlattenCustomOriginConfig(co) @@ -809,16 +809,16 @@ func TestCloudFrontStructure_flattenCustomOriginConfig(t *testing.T) { } } -func TestCloudFrontStructure_expandCustomOriginConfigSSL(t *testing.T) { - in := customOriginSslProtocolsConf() +func TestStructure_expandCustomOriginConfigSSL(t *testing.T) { + in := customOriginSSLProtocolsConf() ocs := tfcloudfront.ExpandCustomOriginConfigSSL(in.List()) if *ocs.Quantity != 4 { t.Fatalf("Expected Quantity to be 4, got %v", *ocs.Quantity) } } -func TestCloudFrontStructure_flattenCustomOriginConfigSSL(t *testing.T) { - in := customOriginSslProtocolsConf() +func TestStructure_flattenCustomOriginConfigSSL(t *testing.T) { + in := customOriginSSLProtocolsConf() ocs := tfcloudfront.ExpandCustomOriginConfigSSL(in.List()) out := tfcloudfront.FlattenCustomOriginConfigSSL(ocs) @@ -827,7 +827,7 @@ func TestCloudFrontStructure_flattenCustomOriginConfigSSL(t *testing.T) { } } -func TestCloudFrontStructure_expandOriginShield(t *testing.T) { +func TestStructure_expandOriginShield(t *testing.T) { data := originShield() o := tfcloudfront.ExpandOriginShield(data) if *o.Enabled != true { @@ -838,7 +838,7 @@ func TestCloudFrontStructure_expandOriginShield(t *testing.T) { } } -func TestCloudFrontStructure_flattenOriginShield(t *testing.T) { +func TestStructure_flattenOriginShield(t *testing.T) { in := originShield() o := tfcloudfront.ExpandOriginShield(in) out := tfcloudfront.FlattenOriginShield(o) @@ -848,7 +848,7 @@ func TestCloudFrontStructure_flattenOriginShield(t *testing.T) { } } -func TestCloudFrontStructure_expandS3OriginConfig(t *testing.T) { +func TestStructure_expandS3OriginConfig(t *testing.T) { data := s3OriginConf() s3o := tfcloudfront.ExpandS3OriginConfig(data) if *s3o.OriginAccessIdentity != "origin-access-identity/cloudfront/E127EXAMPLE51Z" { @@ -856,7 +856,7 @@ func TestCloudFrontStructure_expandS3OriginConfig(t *testing.T) { } } -func TestCloudFrontStructure_flattenS3OriginConfig(t *testing.T) { +func TestStructure_flattenS3OriginConfig(t *testing.T) { in := s3OriginConf() s3o := tfcloudfront.ExpandS3OriginConfig(in) out := tfcloudfront.FlattenS3OriginConfig(s3o) @@ -866,7 +866,7 @@ func TestCloudFrontStructure_flattenS3OriginConfig(t *testing.T) { } } -func TestCloudFrontStructure_expandCustomErrorResponses(t *testing.T) { +func TestStructure_expandCustomErrorResponses(t *testing.T) { data := customErrorResponsesConfSet() ers := tfcloudfront.ExpandCustomErrorResponses(data) if *ers.Quantity != 2 { @@ -877,7 +877,7 @@ func TestCloudFrontStructure_expandCustomErrorResponses(t *testing.T) { } } -func TestCloudFrontStructure_flattenCustomErrorResponses(t *testing.T) { +func TestStructure_flattenCustomErrorResponses(t *testing.T) { in := customErrorResponsesConfSet() ers := tfcloudfront.ExpandCustomErrorResponses(in) out := tfcloudfront.FlattenCustomErrorResponses(ers) @@ -887,7 +887,7 @@ func TestCloudFrontStructure_flattenCustomErrorResponses(t *testing.T) { } } -func TestCloudFrontStructure_expandCustomErrorResponse(t *testing.T) { +func TestStructure_expandCustomErrorResponse(t *testing.T) { data := customErrorResponsesConfFirst() er := tfcloudfront.ExpandCustomErrorResponse(data) if *er.ErrorCode != 404 { @@ -904,7 +904,7 @@ func TestCloudFrontStructure_expandCustomErrorResponse(t *testing.T) { } } -func TestCloudFrontStructure_expandCustomErrorResponse_emptyResponseCode(t *testing.T) { +func TestStructure_expandCustomErrorResponse_emptyResponseCode(t *testing.T) { data := customErrorResponseConfNoResponseCode() er := tfcloudfront.ExpandCustomErrorResponse(data) if *er.ResponseCode != "" { @@ -915,7 +915,7 @@ func TestCloudFrontStructure_expandCustomErrorResponse_emptyResponseCode(t *test } } -func TestCloudFrontStructure_flattenCustomErrorResponse(t *testing.T) { +func TestStructure_flattenCustomErrorResponse(t *testing.T) { in := customErrorResponsesConfFirst() er := tfcloudfront.ExpandCustomErrorResponse(in) out := tfcloudfront.FlattenCustomErrorResponse(er) @@ -925,7 +925,7 @@ func TestCloudFrontStructure_flattenCustomErrorResponse(t *testing.T) { } } -func TestCloudFrontStructure_expandLoggingConfig(t *testing.T) { +func TestStructure_expandLoggingConfig(t *testing.T) { data := loggingConfigConf() lc := tfcloudfront.ExpandLoggingConfig(data) @@ -943,7 +943,7 @@ func TestCloudFrontStructure_expandLoggingConfig(t *testing.T) { } } -func TestCloudFrontStructure_expandLoggingConfig_nilValue(t *testing.T) { +func TestStructure_expandLoggingConfig_nilValue(t *testing.T) { lc := tfcloudfront.ExpandLoggingConfig(nil) if *lc.Enabled { t.Fatalf("Expected Enabled to be false, got %v", *lc.Enabled) @@ -959,7 +959,7 @@ func TestCloudFrontStructure_expandLoggingConfig_nilValue(t *testing.T) { } } -func TestCloudFrontStructure_expandAliases(t *testing.T) { +func TestStructure_expandAliases(t *testing.T) { data := aliasesConf() a := tfcloudfront.ExpandAliases(data) if *a.Quantity != 2 { @@ -970,7 +970,7 @@ func TestCloudFrontStructure_expandAliases(t *testing.T) { } } -func TestCloudFrontStructure_flattenAliases(t *testing.T) { +func TestStructure_flattenAliases(t *testing.T) { in := aliasesConf() a := tfcloudfront.ExpandAliases(in) out := tfcloudfront.FlattenAliases(a) @@ -981,7 +981,7 @@ func TestCloudFrontStructure_flattenAliases(t *testing.T) { } } -func TestCloudFrontStructure_expandRestrictions(t *testing.T) { +func TestStructure_expandRestrictions(t *testing.T) { data := geoRestrictionsConf() r := tfcloudfront.ExpandRestrictions(data) if *r.GeoRestriction.RestrictionType != "whitelist" { @@ -989,7 +989,7 @@ func TestCloudFrontStructure_expandRestrictions(t *testing.T) { } } -func TestCloudFrontStructure_expandGeoRestriction_whitelist(t *testing.T) { +func TestStructure_expandGeoRestriction_whitelist(t *testing.T) { data := geoRestrictionWhitelistConf() gr := tfcloudfront.ExpandGeoRestriction(data) if *gr.RestrictionType != "whitelist" { @@ -1003,7 +1003,7 @@ func TestCloudFrontStructure_expandGeoRestriction_whitelist(t *testing.T) { } } -func TestCloudFrontStructure_flattenGeoRestriction_whitelist(t *testing.T) { +func TestStructure_flattenGeoRestriction_whitelist(t *testing.T) { in := geoRestrictionWhitelistConf() gr := tfcloudfront.ExpandGeoRestriction(in) out := tfcloudfront.FlattenGeoRestriction(gr) @@ -1016,7 +1016,7 @@ func TestCloudFrontStructure_flattenGeoRestriction_whitelist(t *testing.T) { } } -func TestCloudFrontStructure_expandGeoRestriction_no_items(t *testing.T) { +func TestStructure_expandGeoRestriction_no_items(t *testing.T) { data := geoRestrictionConfNoItems() gr := tfcloudfront.ExpandGeoRestriction(data) if *gr.RestrictionType != "none" { @@ -1030,7 +1030,7 @@ func TestCloudFrontStructure_expandGeoRestriction_no_items(t *testing.T) { } } -func TestCloudFrontStructure_flattenGeoRestriction_no_items(t *testing.T) { +func TestStructure_flattenGeoRestriction_no_items(t *testing.T) { in := geoRestrictionConfNoItems() gr := tfcloudfront.ExpandGeoRestriction(in) out := tfcloudfront.FlattenGeoRestriction(gr) @@ -1043,7 +1043,7 @@ func TestCloudFrontStructure_flattenGeoRestriction_no_items(t *testing.T) { } } -func TestCloudFrontStructure_expandViewerCertificate_cloudfront_default_certificate(t *testing.T) { +func TestStructure_expandViewerCertificateDefaultCertificate(t *testing.T) { data := viewerCertificateConfSetDefault() vc := tfcloudfront.ExpandViewerCertificate(data) if vc.ACMCertificateArn != nil { @@ -1063,7 +1063,7 @@ func TestCloudFrontStructure_expandViewerCertificate_cloudfront_default_certific } } -func TestCloudFrontStructure_expandViewerCertificate_iam_certificate_id(t *testing.T) { +func TestStructure_expandViewerCertificate_iam_certificate_id(t *testing.T) { data := viewerCertificateConfSetIAM() vc := tfcloudfront.ExpandViewerCertificate(data) if vc.ACMCertificateArn != nil { @@ -1083,7 +1083,7 @@ func TestCloudFrontStructure_expandViewerCertificate_iam_certificate_id(t *testi } } -func TestCloudFrontStructure_expandViewerCertificate_acm_certificate_arn(t *testing.T) { +func TestStructure_expandViewerCertificate_acm_certificate_arn(t *testing.T) { data := viewerCertificateConfSetACM() vc := tfcloudfront.ExpandViewerCertificate(data) diff --git a/internal/service/cloudfront/distribution_data_source.go b/internal/service/cloudfront/distribution_data_source.go index b8565921995..87747e754d9 100644 --- a/internal/service/cloudfront/distribution_data_source.go +++ b/internal/service/cloudfront/distribution_data_source.go @@ -88,9 +88,9 @@ func dataSourceDistributionRead(d *schema.ResourceData, meta interface{}) error d.Set("status", distribution.Status) region := meta.(*conns.AWSClient).Region if v, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), region); ok && v.ID() == endpoints.AwsCnPartitionID { - d.Set("hosted_zone_id", cloudFrontCNRoute53ZoneID) + d.Set("hosted_zone_id", cnRoute53ZoneID) } else { - d.Set("hosted_zone_id", cloudFrontRoute53ZoneID) + d.Set("hosted_zone_id", route53ZoneID) } if distributionConfig := distribution.DistributionConfig; distributionConfig != nil { d.Set("enabled", distributionConfig.Enabled) diff --git a/internal/service/cloudfront/distribution_data_source_test.go b/internal/service/cloudfront/distribution_data_source_test.go index bcaf63250e0..d6e85e9a102 100644 --- a/internal/service/cloudfront/distribution_data_source_test.go +++ b/internal/service/cloudfront/distribution_data_source_test.go @@ -20,7 +20,7 @@ func TestAccCloudFrontDistributionDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDistributionDataConfig(rName), + Config: testAccDistributionDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "domain_name", resourceName, "domain_name"), @@ -36,9 +36,9 @@ func TestAccCloudFrontDistributionDataSource_basic(t *testing.T) { }) } -func testAccDistributionDataConfig(rName string) string { +func testAccDistributionDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( - testAccDistributionS3WithTagsConfig(rName), ` + testAccDistributionConfig_s3Tags(rName), ` data "aws_cloudfront_distribution" "test" { id = aws_cloudfront_distribution.s3_distribution.id } diff --git a/internal/service/cloudfront/distribution_test.go b/internal/service/cloudfront/distribution_test.go index a8c6b8c12b0..02b7d56f13d 100644 --- a/internal/service/cloudfront/distribution_test.go +++ b/internal/service/cloudfront/distribution_test.go @@ -30,7 +30,7 @@ func TestAccCloudFrontDistribution_disappears(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionEnabledConfig(false, false), + Config: testAccDistributionConfig_enabled(false, false), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), testAccCheckDistributionDisappears(&distribution), @@ -61,7 +61,7 @@ func TestAccCloudFrontDistribution_s3Origin(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionS3Config(rName), + Config: testAccDistributionConfig_s3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists("aws_cloudfront_distribution.s3_distribution", &distribution), resource.TestCheckResourceAttr("aws_cloudfront_distribution.s3_distribution", "hosted_zone_id", "Z2FDTNDATAQYW2"), @@ -95,7 +95,7 @@ func TestAccCloudFrontDistribution_s3OriginWithTags(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionS3WithTagsConfig(rName), + Config: testAccDistributionConfig_s3Tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists("aws_cloudfront_distribution.s3_distribution", &distribution), resource.TestCheckResourceAttr("aws_cloudfront_distribution.s3_distribution", "tags.%", "2"), @@ -113,7 +113,7 @@ func TestAccCloudFrontDistribution_s3OriginWithTags(t *testing.T) { }, }, { - Config: testAccDistributionS3WithTagsUpdatedConfig(rName), + Config: testAccDistributionConfig_s3TagsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists("aws_cloudfront_distribution.s3_distribution", &distribution), resource.TestCheckResourceAttr("aws_cloudfront_distribution.s3_distribution", "tags.%", "1"), @@ -143,7 +143,7 @@ func TestAccCloudFrontDistribution_customOrigin(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionCustomConfig(rName), + Config: testAccDistributionConfig_custom(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists("aws_cloudfront_distribution.custom_distribution", &distribution), ), @@ -175,7 +175,7 @@ func TestAccCloudFrontDistribution_originPolicyDefault(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOriginRequestPolicyDefaultConfig(rName), + Config: testAccDistributionConfig_originRequestPolicyDefault(rName), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr("aws_cloudfront_distribution.custom_distribution", "default_cache_behavior.0.origin_request_policy_id", regexp.MustCompile("[A-z0-9]+")), ), @@ -207,7 +207,7 @@ func TestAccCloudFrontDistribution_originPolicyOrdered(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOriginRequestPolicyOrderedConfig(rName), + Config: testAccDistributionConfig_originRequestPolicyOrdered(rName), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr("aws_cloudfront_distribution.custom_distribution", "ordered_cache_behavior.0.origin_request_policy_id", regexp.MustCompile("[A-z0-9]+")), ), @@ -246,7 +246,7 @@ func TestAccCloudFrontDistribution_multiOrigin(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionMultiOriginConfig(rName), + Config: testAccDistributionConfig_multiOrigin(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.#", "2"), @@ -288,7 +288,7 @@ func TestAccCloudFrontDistribution_orderedCacheBehavior(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOrderedCacheBehavior(), + Config: testAccDistributionConfig_orderedCacheBehavior(), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.#", "2"), @@ -327,7 +327,7 @@ func TestAccCloudFrontDistribution_orderedCacheBehaviorCachePolicy(t *testing.T) CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOrderedCacheBehaviorCachePolicy(rName), + Config: testAccDistributionConfig_orderedCacheBehaviorCachePolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.0.path_pattern", "images2/*.jpg"), @@ -363,7 +363,7 @@ func TestAccCloudFrontDistribution_orderedCacheBehaviorResponseHeadersPolicy(t * CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccOrderedCacheBehaviorResponseHeadersPolicy(rName), + Config: testAccDistributionConfig_orderedCacheBehaviorResponseHeadersPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.0.path_pattern", "images2/*.jpg"), @@ -399,13 +399,13 @@ func TestAccCloudFrontDistribution_forwardedValuesToCachePolicy(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOrderedCacheBehavior(), + Config: testAccDistributionConfig_orderedCacheBehavior(), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), ), }, { - Config: testAccDistributionOrderedCacheBehaviorCachePolicy(rName), + Config: testAccDistributionConfig_orderedCacheBehaviorCachePolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), ), @@ -422,7 +422,7 @@ func TestAccCloudFrontDistribution_Origin_emptyDomainName(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionConfig_Origin_EmptyDomainName(), + Config: testAccDistributionConfig_originEmptyDomainName(), ExpectError: regexp.MustCompile(`domain_name must not be empty`), }, }, @@ -437,7 +437,7 @@ func TestAccCloudFrontDistribution_Origin_emptyOriginID(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionConfig_Origin_EmptyOriginID(), + Config: testAccDistributionConfig_originEmptyOriginID(), ExpectError: regexp.MustCompile(`origin.0.origin_id must not be empty`), }, }, @@ -460,15 +460,15 @@ func TestAccCloudFrontDistribution_Origin_connectionAttempts(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOriginItem(rName, `connection_attempts = 0`), + Config: testAccDistributionConfig_originItem(rName, `connection_attempts = 0`), ExpectError: regexp.MustCompile(`expected origin.0.connection_attempts to be in the range`), }, { - Config: testAccDistributionOriginItem(rName, `connection_attempts = 4`), + Config: testAccDistributionConfig_originItem(rName, `connection_attempts = 4`), ExpectError: regexp.MustCompile(`expected origin.0.connection_attempts to be in the range`), }, { - Config: testAccDistributionOriginItem(rName, `connection_attempts = 2`), + Config: testAccDistributionConfig_originItem(rName, `connection_attempts = 2`), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "origin.#", "1"), @@ -495,15 +495,15 @@ func TestAccCloudFrontDistribution_Origin_connectionTimeout(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOriginItem(rName, `connection_timeout = 0`), + Config: testAccDistributionConfig_originItem(rName, `connection_timeout = 0`), ExpectError: regexp.MustCompile(`expected origin.0.connection_timeout to be in the range`), }, { - Config: testAccDistributionOriginItem(rName, `connection_timeout = 11`), + Config: testAccDistributionConfig_originItem(rName, `connection_timeout = 11`), ExpectError: regexp.MustCompile(`expected origin.0.connection_timeout to be in the range`), }, { - Config: testAccDistributionOriginItem(rName, `connection_timeout = 6`), + Config: testAccDistributionConfig_originItem(rName, `connection_timeout = 6`), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "origin.#", "1"), @@ -530,27 +530,27 @@ func TestAccCloudFrontDistribution_Origin_originShield(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOriginItem(rName, originShieldItem(`null`, `data.aws_region.current.name`)), + Config: testAccDistributionConfig_originItem(rName, originShieldItem(`null`, `data.aws_region.current.name`)), ExpectError: regexp.MustCompile(`Missing required argument`), }, { - Config: testAccDistributionOriginItem(rName, originShieldItem(`false`, `null`)), + Config: testAccDistributionConfig_originItem(rName, originShieldItem(`false`, `null`)), ExpectError: regexp.MustCompile(`Missing required argument`), }, { - Config: testAccDistributionOriginItem(rName, originShieldItem(`true`, `null`)), + Config: testAccDistributionConfig_originItem(rName, originShieldItem(`true`, `null`)), ExpectError: regexp.MustCompile(`Missing required argument`), }, { - Config: testAccDistributionOriginItem(rName, originShieldItem(`false`, `""`)), + Config: testAccDistributionConfig_originItem(rName, originShieldItem(`false`, `""`)), ExpectError: regexp.MustCompile(`.*must be a valid AWS Region Code.*`), }, { - Config: testAccDistributionOriginItem(rName, originShieldItem(`true`, `"US East (Ohio)"`)), + Config: testAccDistributionConfig_originItem(rName, originShieldItem(`true`, `"US East (Ohio)"`)), ExpectError: regexp.MustCompile(`.*must be a valid AWS Region Code.*`), }, { - Config: testAccDistributionOriginItem(rName, originShieldItem(`true`, `"us-east-1"`)), //lintignore:AWSAT003 + Config: testAccDistributionConfig_originItem(rName, originShieldItem(`true`, `"us-east-1"`)), //lintignore:AWSAT003 Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "origin.#", "1"), @@ -582,7 +582,7 @@ func TestAccCloudFrontDistribution_noOptionalItems(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionNoOptionalItemsConfig(), + Config: testAccDistributionConfig_noOptionalItems(), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "aliases.#", "0"), @@ -670,7 +670,7 @@ func TestAccCloudFrontDistribution_http11(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionHTTP11Config(), + Config: testAccDistributionConfig_http11(), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists("aws_cloudfront_distribution.http_1_1", &distribution), ), @@ -702,7 +702,7 @@ func TestAccCloudFrontDistribution_isIPV6Enabled(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionIsIPV6EnabledConfig(), + Config: testAccDistributionConfig_isIPV6Enabled(), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists("aws_cloudfront_distribution.is_ipv6_enabled", &distribution), resource.TestCheckResourceAttr( @@ -736,7 +736,7 @@ func TestAccCloudFrontDistribution_noCustomErrorResponse(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionNoCustomErroResponseInfo(), + Config: testAccDistributionConfig_noCustomErroResponseInfo(), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists("aws_cloudfront_distribution.no_custom_error_responses", &distribution), ), @@ -766,7 +766,7 @@ func TestAccCloudFrontDistribution_DefaultCacheBehaviorForwardedValuesCookies_wh CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered3Config(retainOnDelete), + Config: testAccDistributionConfig_defaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered3(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "default_cache_behavior.#", "1"), @@ -785,7 +785,7 @@ func TestAccCloudFrontDistribution_DefaultCacheBehaviorForwardedValuesCookies_wh }, }, { - Config: testAccDistributionDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered2Config(retainOnDelete), + Config: testAccDistributionConfig_defaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered2(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "default_cache_behavior.#", "1"), @@ -810,7 +810,7 @@ func TestAccCloudFrontDistribution_DefaultCacheBehaviorForwardedValues_headers(t CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionDefaultCacheBehaviorForwardedValuesHeadersUnordered3Config(retainOnDelete), + Config: testAccDistributionConfig_defaultCacheBehaviorForwardedValuesHeadersUnordered3(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "default_cache_behavior.#", "1"), @@ -828,7 +828,7 @@ func TestAccCloudFrontDistribution_DefaultCacheBehaviorForwardedValues_headers(t }, }, { - Config: testAccDistributionDefaultCacheBehaviorForwardedValuesHeadersUnordered2Config(retainOnDelete), + Config: testAccDistributionConfig_defaultCacheBehaviorForwardedValuesHeadersUnordered2(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "default_cache_behavior.#", "1"), @@ -854,7 +854,7 @@ func TestAccCloudFrontDistribution_DefaultCacheBehavior_trustedKeyGroups(t *test CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionDefaultCacheBehaviorTrustedKeyGroupsConfig(retainOnDelete, rName), + Config: testAccDistributionConfig_defaultCacheBehaviorTrustedKeyGroups(retainOnDelete, rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "trusted_key_groups.#", "1"), @@ -891,7 +891,7 @@ func TestAccCloudFrontDistribution_DefaultCacheBehavior_trustedSigners(t *testin CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionDefaultCacheBehaviorTrustedSignersSelfConfig(retainOnDelete), + Config: testAccDistributionConfig_defaultCacheBehaviorTrustedSignersSelf(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "trusted_signers.#", "1"), @@ -928,7 +928,7 @@ func TestAccCloudFrontDistribution_DefaultCacheBehavior_realtimeLogARN(t *testin CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionDefaultCacheBehaviorRealtimeLogARNConfig(rName, retainOnDelete), + Config: testAccDistributionConfig_defaultCacheBehaviorRealtimeLogARN(rName, retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "default_cache_behavior.#", "1"), @@ -962,7 +962,7 @@ func TestAccCloudFrontDistribution_OrderedCacheBehavior_realtimeLogARN(t *testin CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOrderedCacheBehaviorRealtimeLogARNConfig(rName, retainOnDelete), + Config: testAccDistributionConfig_orderedCacheBehaviorRealtimeLogARN(rName, retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.#", "1"), @@ -997,7 +997,7 @@ func TestAccCloudFrontDistribution_enabled(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionEnabledConfig(false, false), + Config: testAccDistributionConfig_enabled(false, false), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -1013,7 +1013,7 @@ func TestAccCloudFrontDistribution_enabled(t *testing.T) { }, }, { - Config: testAccDistributionEnabledConfig(true, false), + Config: testAccDistributionConfig_enabled(true, false), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), @@ -1043,13 +1043,13 @@ func TestAccCloudFrontDistribution_retainOnDelete(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionEnabledConfig(true, true), + Config: testAccDistributionConfig_enabled(true, true), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), ), }, { - Config: testAccDistributionEnabledConfig(true, true), + Config: testAccDistributionConfig_enabled(true, true), Destroy: true, Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExistsAPIOnly(&distribution), @@ -1078,7 +1078,7 @@ func TestAccCloudFrontDistribution_OrderedCacheBehaviorForwardedValuesCookies_wh CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOrderedCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered3Config(retainOnDelete), + Config: testAccDistributionConfig_orderedCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered3(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.#", "1"), @@ -1097,7 +1097,7 @@ func TestAccCloudFrontDistribution_OrderedCacheBehaviorForwardedValuesCookies_wh }, }, { - Config: testAccDistributionOrderedCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered2Config(retainOnDelete), + Config: testAccDistributionConfig_orderedCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered2(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.#", "1"), @@ -1126,7 +1126,7 @@ func TestAccCloudFrontDistribution_OrderedCacheBehaviorForwardedValues_headers(t CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOrderedCacheBehaviorForwardedValuesHeadersUnordered3Config(retainOnDelete), + Config: testAccDistributionConfig_orderedCacheBehaviorForwardedValuesHeadersUnordered3(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.#", "1"), @@ -1144,7 +1144,7 @@ func TestAccCloudFrontDistribution_OrderedCacheBehaviorForwardedValues_headers(t }, }, { - Config: testAccDistributionOrderedCacheBehaviorForwardedValuesHeadersUnordered2Config(retainOnDelete), + Config: testAccDistributionConfig_orderedCacheBehaviorForwardedValuesHeadersUnordered2(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.#", "1"), @@ -1168,13 +1168,13 @@ func TestAccCloudFrontDistribution_ViewerCertificate_acmCertificateARN(t *testin CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionViewerCertificateACMCertificateARNConfig(retainOnDelete), + Config: testAccDistributionConfig_viewerCertificateACMCertificateARN(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), ), }, { - Config: testAccDistributionViewerCertificateACMCertificateARNConfig(retainOnDelete), + Config: testAccDistributionConfig_viewerCertificateACMCertificateARN(retainOnDelete), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1200,13 +1200,13 @@ func TestAccCloudFrontDistribution_ViewerCertificateACMCertificateARN_conflictsW CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionViewerCertificateACMCertificateARNConflictsWithDefaultCertificateConfig(retainOnDelete), + Config: testAccDistributionConfig_viewerCertificateACMCertificateARNConflictsDefaultCertificate(retainOnDelete), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), ), }, { - Config: testAccDistributionViewerCertificateACMCertificateARNConflictsWithDefaultCertificateConfig(retainOnDelete), + Config: testAccDistributionConfig_viewerCertificateACMCertificateARNConflictsDefaultCertificate(retainOnDelete), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1234,7 +1234,7 @@ func TestAccCloudFrontDistribution_waitForDeployment(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionWaitForDeploymentConfig(false, false), + Config: testAccDistributionConfig_waitForDeployment(false, false), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), testAccCheckDistributionStatusInProgress(&distribution), @@ -1252,7 +1252,7 @@ func TestAccCloudFrontDistribution_waitForDeployment(t *testing.T) { }, }, { - Config: testAccDistributionWaitForDeploymentConfig(true, false), + Config: testAccDistributionConfig_waitForDeployment(true, false), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), testAccCheckDistributionStatusInProgress(&distribution), @@ -1260,7 +1260,7 @@ func TestAccCloudFrontDistribution_waitForDeployment(t *testing.T) { ), }, { - Config: testAccDistributionWaitForDeploymentConfig(false, true), + Config: testAccDistributionConfig_waitForDeployment(false, true), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), testAccCheckDistributionStatusDeployed(&distribution), @@ -1287,7 +1287,7 @@ func TestAccCloudFrontDistribution_preconditionFailed(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionETagInitialConfig(rName), + Config: testAccDistributionConfig_eTagInitial(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr("aws_cloudfront_response_headers_policy.example", "cors_config.#", "1"), @@ -1307,7 +1307,7 @@ func TestAccCloudFrontDistribution_preconditionFailed(t *testing.T) { }, }, { - Config: testAccDistributionETagUpdatedConfig(rName), + Config: testAccDistributionConfig_eTagUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr("aws_cloudfront_response_headers_policy.example", "cors_config.#", "1"), @@ -1328,7 +1328,7 @@ func TestAccCloudFrontDistribution_preconditionFailed(t *testing.T) { }, }, { - Config: testAccDistributionETagFinalConfig(rName), + Config: testAccDistributionConfig_eTagFinal(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr("aws_cloudfront_response_headers_policy.example", "cors_config.#", "1"), @@ -1554,7 +1554,7 @@ func TestAccCloudFrontDistribution_originGroups(t *testing.T) { CheckDestroy: testAccCheckDistributionDestroy, Steps: []resource.TestStep{ { - Config: testAccDistributionOriginGroupsConfig(rName), + Config: testAccDistributionConfig_originGroups(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDistributionExists(resourceName, &distribution), resource.TestCheckResourceAttr(resourceName, "origin_group.#", "1"), @@ -1616,7 +1616,7 @@ resource "aws_s3_bucket_acl" "s3_bucket_logs_acl" { `, rName) } -func testAccDistributionS3Config(rName string) string { +func testAccDistributionConfig_s3(rName string) string { return acctest.ConfigCompose( originBucket(rName), logBucket(rName), @@ -1673,7 +1673,7 @@ resource "aws_cloudfront_distribution" "s3_distribution" { `, testAccDistributionRetainConfig())) } -func testAccDistributionS3WithTagsConfig(rName string) string { +func testAccDistributionConfig_s3Tags(rName string) string { return acctest.ConfigCompose( originBucket(rName), logBucket(rName), @@ -1729,7 +1729,7 @@ resource "aws_cloudfront_distribution" "s3_distribution" { `, testAccDistributionRetainConfig())) } -func testAccDistributionS3WithTagsUpdatedConfig(rName string) string { +func testAccDistributionConfig_s3TagsUpdated(rName string) string { return acctest.ConfigCompose( originBucket(rName), logBucket(rName), @@ -1784,7 +1784,7 @@ resource "aws_cloudfront_distribution" "s3_distribution" { `, testAccDistributionRetainConfig())) } -func testAccDistributionCustomConfig(rName string) string { +func testAccDistributionConfig_custom(rName string) string { return acctest.ConfigCompose( logBucket(rName), fmt.Sprintf(` @@ -1851,7 +1851,7 @@ resource "aws_cloudfront_distribution" "custom_distribution" { `, testAccDistributionRetainConfig())) } -func testAccDistributionOriginRequestPolicyDefaultConfig(rName string) string { +func testAccDistributionConfig_originRequestPolicyDefault(rName string) string { return acctest.ConfigCompose( logBucket(rName), fmt.Sprintf(` @@ -1985,7 +1985,7 @@ resource "aws_cloudfront_distribution" "custom_distribution" { `, rName, testAccDistributionRetainConfig())) } -func testAccDistributionOriginRequestPolicyOrderedConfig(rName string) string { +func testAccDistributionConfig_originRequestPolicyOrdered(rName string) string { return acctest.ConfigCompose( logBucket(rName), fmt.Sprintf(` @@ -2133,7 +2133,7 @@ resource "aws_cloudfront_distribution" "custom_distribution" { `, rName, testAccDistributionRetainConfig())) } -func testAccDistributionMultiOriginConfig(rName string) string { +func testAccDistributionConfig_multiOrigin(rName string) string { return acctest.ConfigCompose( originBucket(rName), logBucket(rName), @@ -2251,7 +2251,7 @@ resource "aws_cloudfront_distribution" "multi_origin_distribution" { `, testAccDistributionRetainConfig())) } -func testAccDistributionNoCustomErroResponseInfo() string { +func testAccDistributionConfig_noCustomErroResponseInfo() string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "no_custom_error_responses" { origin { @@ -2310,7 +2310,7 @@ resource "aws_cloudfront_distribution" "no_custom_error_responses" { `, testAccDistributionRetainConfig()) } -func testAccDistributionNoOptionalItemsConfig() string { +func testAccDistributionConfig_noOptionalItems() string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "no_optional_items" { origin { @@ -2360,7 +2360,7 @@ resource "aws_cloudfront_distribution" "no_optional_items" { `, testAccDistributionRetainConfig()) } -func testAccDistributionConfig_Origin_EmptyDomainName() string { +func testAccDistributionConfig_originEmptyDomainName() string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "Origin_EmptyDomainName" { origin { @@ -2410,7 +2410,7 @@ resource "aws_cloudfront_distribution" "Origin_EmptyDomainName" { `, testAccDistributionRetainConfig()) } -func testAccDistributionConfig_Origin_EmptyOriginID() string { +func testAccDistributionConfig_originEmptyOriginID() string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "Origin_EmptyOriginID" { origin { @@ -2460,7 +2460,7 @@ resource "aws_cloudfront_distribution" "Origin_EmptyOriginID" { `, testAccDistributionRetainConfig()) } -func testAccDistributionHTTP11Config() string { +func testAccDistributionConfig_http11() string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "http_1_1" { origin { @@ -2516,7 +2516,7 @@ resource "aws_cloudfront_distribution" "http_1_1" { `, testAccDistributionRetainConfig()) } -func testAccDistributionIsIPV6EnabledConfig() string { +func testAccDistributionConfig_isIPV6Enabled() string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "is_ipv6_enabled" { origin { @@ -2573,7 +2573,7 @@ resource "aws_cloudfront_distribution" "is_ipv6_enabled" { `, testAccDistributionRetainConfig()) } -func testAccDistributionOrderedCacheBehavior() string { +func testAccDistributionConfig_orderedCacheBehavior() string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "main" { origin { @@ -2668,7 +2668,7 @@ resource "aws_cloudfront_distribution" "main" { `, testAccDistributionRetainConfig()) } -func testAccDistributionOrderedCacheBehaviorCachePolicy(rName string) string { +func testAccDistributionConfig_orderedCacheBehaviorCachePolicy(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "main" { origin { @@ -2749,7 +2749,7 @@ resource "aws_cloudfront_cache_policy" "cache_policy" { `, rName, testAccDistributionRetainConfig()) } -func testAccOrderedCacheBehaviorResponseHeadersPolicy(rName string) string { +func testAccDistributionConfig_orderedCacheBehaviorResponseHeadersPolicy(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "main" { origin { @@ -2854,7 +2854,7 @@ resource "aws_cloudfront_response_headers_policy" "response_headers_policy" { `, rName, testAccDistributionRetainConfig()) } -func testAccDistributionOriginGroupsConfig(rName string) string { +func testAccDistributionConfig_originGroups(rName string) string { return acctest.ConfigCompose( originBucket(rName), backupBucket(rName), @@ -2919,7 +2919,7 @@ resource "aws_cloudfront_distribution" "failover_distribution" { `, testAccDistributionRetainConfig())) } -func testAccDistributionDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered2Config(retainOnDelete bool) string { +func testAccDistributionConfig_defaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered2(retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -2968,7 +2968,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered3Config(retainOnDelete bool) string { +func testAccDistributionConfig_defaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered3(retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -3017,7 +3017,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionDefaultCacheBehaviorForwardedValuesHeadersUnordered2Config(retainOnDelete bool) string { +func testAccDistributionConfig_defaultCacheBehaviorForwardedValuesHeadersUnordered2(retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -3066,7 +3066,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionDefaultCacheBehaviorForwardedValuesHeadersUnordered3Config(retainOnDelete bool) string { +func testAccDistributionConfig_defaultCacheBehaviorForwardedValuesHeadersUnordered3(retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -3115,7 +3115,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionEnabledConfig(enabled, retainOnDelete bool) string { +func testAccDistributionConfig_enabled(enabled, retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { enabled = %[1]t @@ -3161,7 +3161,7 @@ resource "aws_cloudfront_distribution" "test" { `, enabled, retainOnDelete) } -func testAccDistributionOrderedCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered2Config(retainOnDelete bool) string { +func testAccDistributionConfig_orderedCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered2(retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -3226,7 +3226,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionOrderedCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered3Config(retainOnDelete bool) string { +func testAccDistributionConfig_orderedCacheBehaviorForwardedValuesCookiesWhitelistedNamesUnordered3(retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -3291,7 +3291,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionOrderedCacheBehaviorForwardedValuesHeadersUnordered2Config(retainOnDelete bool) string { +func testAccDistributionConfig_orderedCacheBehaviorForwardedValuesHeadersUnordered2(retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -3356,7 +3356,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionOrderedCacheBehaviorForwardedValuesHeadersUnordered3Config(retainOnDelete bool) string { +func testAccDistributionConfig_orderedCacheBehaviorForwardedValuesHeadersUnordered3(retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -3421,7 +3421,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionDefaultCacheBehaviorTrustedKeyGroupsConfig(retainOnDelete bool, rName string) string { +func testAccDistributionConfig_defaultCacheBehaviorTrustedKeyGroups(retainOnDelete bool, rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -3482,7 +3482,7 @@ resource "aws_cloudfront_key_group" "test" { `, retainOnDelete, rName) } -func testAccDistributionDefaultCacheBehaviorTrustedSignersSelfConfig(retainOnDelete bool) string { +func testAccDistributionConfig_defaultCacheBehaviorTrustedSignersSelf(retainOnDelete bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { # Faster acceptance testing @@ -3536,7 +3536,7 @@ func testAccDistributionViewerCertificateACMCertificateARNBaseConfig(commonName key := acctest.TLSRSAPrivateKeyPEM(2048) certificate := acctest.TLSRSAX509SelfSignedCertificatePEM(key, commonName) - return testAccCloudfrontRegionProviderConfig() + fmt.Sprintf(` + return testAccRegionProviderConfig() + fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[1]s" private_key = "%[2]s" @@ -3544,7 +3544,7 @@ resource "aws_acm_certificate" "test" { `, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key)) } -func testAccDistributionViewerCertificateACMCertificateARNConfig(retainOnDelete bool) string { +func testAccDistributionConfig_viewerCertificateACMCertificateARN(retainOnDelete bool) string { return testAccDistributionViewerCertificateACMCertificateARNBaseConfig("example.com") + fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { enabled = false @@ -3591,7 +3591,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionViewerCertificateACMCertificateARNConflictsWithDefaultCertificateConfig(retainOnDelete bool) string { +func testAccDistributionConfig_viewerCertificateACMCertificateARNConflictsDefaultCertificate(retainOnDelete bool) string { return testAccDistributionViewerCertificateACMCertificateARNBaseConfig("example.com") + fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { enabled = false @@ -3639,7 +3639,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete) } -func testAccDistributionWaitForDeploymentConfig(enabled, waitForDeployment bool) string { +func testAccDistributionConfig_waitForDeployment(enabled, waitForDeployment bool) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { enabled = %[1]t @@ -3749,7 +3749,7 @@ resource "aws_cloudfront_realtime_log_config" "test" { `, rName) } -func testAccDistributionDefaultCacheBehaviorRealtimeLogARNConfig(rName string, retainOnDelete bool) string { +func testAccDistributionConfig_defaultCacheBehaviorRealtimeLogARN(rName string, retainOnDelete bool) string { return acctest.ConfigCompose( testAccDistributionCacheBehaviorRealtimeLogBaseConfig(rName), fmt.Sprintf(` @@ -3800,7 +3800,7 @@ resource "aws_cloudfront_distribution" "test" { `, retainOnDelete)) } -func testAccDistributionOrderedCacheBehaviorRealtimeLogARNConfig(rName string, retainOnDelete bool) string { +func testAccDistributionConfig_orderedCacheBehaviorRealtimeLogARN(rName string, retainOnDelete bool) string { return acctest.ConfigCompose( testAccDistributionCacheBehaviorRealtimeLogBaseConfig(rName), fmt.Sprintf(` @@ -3876,7 +3876,7 @@ origin_shield { `, enabled, region) } -func testAccDistributionOriginItem(rName string, item string) string { +func testAccDistributionConfig_originItem(rName string, item string) string { return acctest.ConfigCompose( originBucket(rName), testAccDistributionCacheBehaviorRealtimeLogBaseConfig(rName), @@ -3919,7 +3919,7 @@ resource "aws_cloudfront_distribution" "test" { `, item)) } -func testAccDistributionETagInitialConfig(rName string) string { +func testAccDistributionConfig_eTagInitial(rName string) string { return acctest.ConfigCompose( logBucket(rName), fmt.Sprintf(` @@ -4053,7 +4053,7 @@ resource "aws_cloudfront_distribution" "main" { `, rName, testAccDistributionRetainConfig())) } -func testAccDistributionETagUpdatedConfig(rName string) string { +func testAccDistributionConfig_eTagUpdated(rName string) string { return acctest.ConfigCompose( logBucket(rName), fmt.Sprintf(` @@ -4187,7 +4187,7 @@ resource "aws_cloudfront_distribution" "main" { `, rName, testAccDistributionRetainConfig())) } -func testAccDistributionETagFinalConfig(rName string) string { +func testAccDistributionConfig_eTagFinal(rName string) string { return acctest.ConfigCompose( logBucket(rName), fmt.Sprintf(` diff --git a/internal/service/cloudfront/field_level_encryption_config_test.go b/internal/service/cloudfront/field_level_encryption_config_test.go index 91ce80bf7d0..d36a0295e7b 100644 --- a/internal/service/cloudfront/field_level_encryption_config_test.go +++ b/internal/service/cloudfront/field_level_encryption_config_test.go @@ -26,7 +26,7 @@ func TestAccCloudFrontFieldLevelEncryptionConfig_basic(t *testing.T) { CheckDestroy: testAccCheckFieldLevelEncryptionConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccFieldLevelEncryptionConfig_basic(rName), + Config: testAccFieldLevelEncryptionConfigConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFieldLevelEncryptionConfigExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "comment", "some comment"), @@ -50,7 +50,7 @@ func TestAccCloudFrontFieldLevelEncryptionConfig_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFieldLevelEncryptionConfig_updated(rName), + Config: testAccFieldLevelEncryptionConfigConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFieldLevelEncryptionConfigExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "comment", "some other comment"), @@ -90,7 +90,7 @@ func TestAccCloudFrontFieldLevelEncryptionConfig_disappears(t *testing.T) { CheckDestroy: testAccCheckFieldLevelEncryptionConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccFieldLevelEncryptionConfig_basic(rName), + Config: testAccFieldLevelEncryptionConfigConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFieldLevelEncryptionConfigExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceFieldLevelEncryptionConfig(), resourceName), @@ -177,7 +177,7 @@ resource "aws_cloudfront_field_level_encryption_profile" "test" { `, rName) } -func testAccFieldLevelEncryptionConfig_basic(rName string) string { +func testAccFieldLevelEncryptionConfigConfig_basic(rName string) string { return acctest.ConfigCompose(testAccFieldLevelEncryptionConfig_base(rName), ` resource "aws_cloudfront_field_level_encryption_config" "test" { comment = "some comment" @@ -201,7 +201,7 @@ resource "aws_cloudfront_field_level_encryption_config" "test" { `) } -func testAccFieldLevelEncryptionConfig_updated(rName string) string { +func testAccFieldLevelEncryptionConfigConfig_updated(rName string) string { return acctest.ConfigCompose(testAccFieldLevelEncryptionConfig_base(rName), ` resource "aws_cloudfront_field_level_encryption_config" "test" { comment = "some other comment" diff --git a/internal/service/cloudfront/field_level_encryption_profile_test.go b/internal/service/cloudfront/field_level_encryption_profile_test.go index ac6ac44017a..6e316101467 100644 --- a/internal/service/cloudfront/field_level_encryption_profile_test.go +++ b/internal/service/cloudfront/field_level_encryption_profile_test.go @@ -26,7 +26,7 @@ func TestAccCloudFrontFieldLevelEncryptionProfile_basic(t *testing.T) { CheckDestroy: testAccCheckFieldLevelEncryptionProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccFieldLevelEncryptionProfileConfig(rName), + Config: testAccFieldLevelEncryptionProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFieldLevelEncryptionProfileExists(resourceName, &profile), resource.TestCheckResourceAttr(resourceName, "comment", "some comment"), @@ -48,7 +48,7 @@ func TestAccCloudFrontFieldLevelEncryptionProfile_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFieldLevelEncryptionProfileExtendedConfig(rName), + Config: testAccFieldLevelEncryptionProfileConfig_extended(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFieldLevelEncryptionProfileExists(resourceName, &profile), resource.TestCheckResourceAttr(resourceName, "comment", "some other comment"), @@ -81,7 +81,7 @@ func TestAccCloudFrontFieldLevelEncryptionProfile_disappears(t *testing.T) { CheckDestroy: testAccCheckFieldLevelEncryptionProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccFieldLevelEncryptionProfileConfig(rName), + Config: testAccFieldLevelEncryptionProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFieldLevelEncryptionProfileExists(resourceName, &profile), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceFieldLevelEncryptionProfile(), resourceName), @@ -142,7 +142,7 @@ func testAccCheckFieldLevelEncryptionProfileExists(r string, v *cloudfront.GetFi } } -func testAccFieldLevelEncryptionProfileConfig(rName string) string { +func testAccFieldLevelEncryptionProfileConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_public_key" "test" { comment = "test key" @@ -168,7 +168,7 @@ resource "aws_cloudfront_field_level_encryption_profile" "test" { `, rName) } -func testAccFieldLevelEncryptionProfileExtendedConfig(rName string) string { +func testAccFieldLevelEncryptionProfileConfig_extended(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_public_key" "test" { comment = "test key" diff --git a/internal/service/cloudfront/function.go b/internal/service/cloudfront/function.go index 1c410a7f9aa..911bdde8810 100644 --- a/internal/service/cloudfront/function.go +++ b/internal/service/cloudfront/function.go @@ -167,7 +167,7 @@ func resourceFunctionUpdate(d *schema.ResourceData, meta interface{}) error { IfMatch: aws.String(etag), } - log.Printf("[INFO] Updating Cloudfront Function: %s", d.Id()) + log.Printf("[INFO] Updating CloudFront Function: %s", d.Id()) output, err := conn.UpdateFunction(input) if err != nil { diff --git a/internal/service/cloudfront/function_data_source_test.go b/internal/service/cloudfront/function_data_source_test.go index 0894c7f4cbd..d5c63d990c2 100644 --- a/internal/service/cloudfront/function_data_source_test.go +++ b/internal/service/cloudfront/function_data_source_test.go @@ -21,7 +21,7 @@ func TestAccCloudFrontFunctionDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccFunctionBasicDataSourceConfig(rName), + Config: testAccFunctionDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "code", resourceName, "code"), @@ -37,7 +37,7 @@ func TestAccCloudFrontFunctionDataSource_basic(t *testing.T) { }) } -func testAccFunctionBasicDataSourceConfig(rName string) string { +func testAccFunctionDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_function" "test" { name = %[1]q diff --git a/internal/service/cloudfront/function_test.go b/internal/service/cloudfront/function_test.go index c7aaa836b29..63a1ddde8c4 100644 --- a/internal/service/cloudfront/function_test.go +++ b/internal/service/cloudfront/function_test.go @@ -16,7 +16,6 @@ import ( func init() { acctest.RegisterServiceErrorCheckFunc(cloudfront.EndpointsID, testAccErrorCheckSkipFunction) - } func testAccErrorCheckSkipFunction(t *testing.T) resource.ErrorCheckFunc { @@ -34,10 +33,10 @@ func TestAccCloudFrontFunction_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudfront.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckCloudfrontFunctionDestroy, + CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccBasicConfig(rName), + Config: testAccFunctionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), acctest.CheckResourceAttrGlobalARN(resourceName, "arn", "cloudfront", fmt.Sprintf("function/%s", rName)), @@ -70,10 +69,10 @@ func TestAccCloudFrontFunction_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudfront.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckCloudfrontFunctionDestroy, + CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccBasicConfig(rName), + Config: testAccFunctionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceFunction(), resourceName), @@ -93,10 +92,10 @@ func TestAccCloudFrontFunction_publish(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudfront.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckCloudfrontFunctionDestroy, + CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccPublishConfig(rName, false), + Config: testAccFunctionConfig_publish(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "etag", "ETVPDKIKX0DER"), @@ -112,7 +111,7 @@ func TestAccCloudFrontFunction_publish(t *testing.T) { ImportStateVerifyIgnore: []string{"publish"}, }, { - Config: testAccPublishConfig(rName, true), + Config: testAccFunctionConfig_publish(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "etag", "ETVPDKIKX0DER"), @@ -136,10 +135,10 @@ func TestAccCloudFrontFunction_associated(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudfront.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckCloudfrontFunctionDestroy, + CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociatedConfig(rName), + Config: testAccFunctionConfig_associated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), // After creation the function will be in UNASSOCIATED status. @@ -148,7 +147,7 @@ func TestAccCloudFrontFunction_associated(t *testing.T) { ), }, { - Config: testAccAssociatedConfig(rName), + Config: testAccFunctionConfig_associated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "status", "DEPLOYED"), @@ -161,7 +160,7 @@ func TestAccCloudFrontFunction_associated(t *testing.T) { ImportStateVerifyIgnore: []string{"publish"}, }, { - Config: testAccUnassociatedConfig(rName), + Config: testAccFunctionConfig_unassociated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), ), @@ -179,17 +178,17 @@ func TestAccCloudFrontFunction_Update_code(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudfront.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckCloudfrontFunctionDestroy, + CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccBasicConfig(rName), + Config: testAccFunctionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "etag", "ETVPDKIKX0DER"), ), }, { - Config: testAccCodeUpdateConfig(rName), + Config: testAccFunctionConfig_codeUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "etag", "E3UN6WX5RRO2AG"), @@ -214,10 +213,10 @@ func TestAccCloudFrontFunction_UpdateCodeAndPublish(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudfront.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckCloudfrontFunctionDestroy, + CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccPublishConfig(rName, false), + Config: testAccFunctionConfig_publish(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "etag", "ETVPDKIKX0DER"), @@ -226,7 +225,7 @@ func TestAccCloudFrontFunction_UpdateCodeAndPublish(t *testing.T) { ), }, { - Config: testAccCodeUpdateConfig(rName), + Config: testAccFunctionConfig_codeUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "etag", "E3UN6WX5RRO2AG"), @@ -253,17 +252,17 @@ func TestAccCloudFrontFunction_Update_comment(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudfront.EndpointsID, t) }, ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckCloudfrontFunctionDestroy, + CheckDestroy: testAccCheckFunctionDestroy, Steps: []resource.TestStep{ { - Config: testAccCommentConfig(rName, "test 1"), + Config: testAccFunctionConfig_comment(rName, "test 1"), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "comment", "test 1"), ), }, { - Config: testAccCommentConfig(rName, "test 2"), + Config: testAccFunctionConfig_comment(rName, "test 2"), Check: resource.ComposeTestCheckFunc( testAccCheckFunctionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "comment", "test 2"), @@ -279,7 +278,7 @@ func TestAccCloudFrontFunction_Update_comment(t *testing.T) { }) } -func testAccCheckCloudfrontFunctionDestroy(s *terraform.State) error { +func testAccCheckFunctionDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).CloudFrontConn for _, rs := range s.RootModule().Resources { @@ -308,11 +307,11 @@ func testAccCheckFunctionExists(n string, v *cloudfront.DescribeFunctionOutput) return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Cloudfront Function not found: %s", n) + return fmt.Errorf("CloudFront Function not found: %s", n) } if rs.Primary.ID == "" { - return fmt.Errorf("Cloudfront Function ID not set") + return fmt.Errorf("CloudFront Function ID not set") } conn := acctest.Provider.Meta().(*conns.AWSClient).CloudFrontConn @@ -329,7 +328,7 @@ func testAccCheckFunctionExists(n string, v *cloudfront.DescribeFunctionOutput) } } -func testAccBasicConfig(rName string) string { +func testAccFunctionConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_function" "test" { name = %[1]q @@ -351,7 +350,7 @@ EOT `, rName) } -func testAccPublishConfig(rName string, publish bool) string { +func testAccFunctionConfig_publish(rName string, publish bool) string { return fmt.Sprintf(` resource "aws_cloudfront_function" "test" { name = %[1]q @@ -375,7 +374,7 @@ EOT `, rName, publish) } -func testAccAssociatedConfig(rName string) string { +func testAccFunctionConfig_associated(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { origin { @@ -450,7 +449,7 @@ EOT `, rName, testAccDistributionRetainConfig()) } -func testAccUnassociatedConfig(rName string) string { +func testAccFunctionConfig_unassociated(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_distribution" "test" { origin { @@ -520,7 +519,7 @@ EOT `, rName, testAccDistributionRetainConfig()) } -func testAccCodeUpdateConfig(rName string) string { +func testAccFunctionConfig_codeUpdate(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_function" "test" { name = %[1]q @@ -543,7 +542,7 @@ EOT `, rName) } -func testAccCommentConfig(rName, comment string) string { +func testAccFunctionConfig_comment(rName, comment string) string { return fmt.Sprintf(` resource "aws_cloudfront_function" "test" { name = %[1]q diff --git a/internal/service/cloudfront/key_group_test.go b/internal/service/cloudfront/key_group_test.go index 6187b364c9a..e633592ffac 100644 --- a/internal/service/cloudfront/key_group_test.go +++ b/internal/service/cloudfront/key_group_test.go @@ -26,7 +26,7 @@ func TestAccCloudFrontKeyGroup_basic(t *testing.T) { CheckDestroy: testAccCheckKeyGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyGroupConfig(rName), + Config: testAccKeyGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyGroupExistence(resourceName), resource.TestCheckResourceAttr("aws_cloudfront_key_group.test", "comment", "test key group"), @@ -56,7 +56,7 @@ func TestAccCloudFrontKeyGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckKeyGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyGroupConfig(rName), + Config: testAccKeyGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyGroupExistence(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceKeyGroup(), resourceName), @@ -81,7 +81,7 @@ func TestAccCloudFrontKeyGroup_comment(t *testing.T) { CheckDestroy: testAccCheckKeyGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyGroupCommentConfig(rName, firstComment), + Config: testAccKeyGroupConfig_comment(rName, firstComment), Check: resource.ComposeTestCheckFunc( testAccCheckKeyGroupExistence(resourceName), resource.TestCheckResourceAttr("aws_cloudfront_key_group.test", "comment", firstComment), @@ -93,7 +93,7 @@ func TestAccCloudFrontKeyGroup_comment(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccKeyGroupCommentConfig(rName, secondComment), + Config: testAccKeyGroupConfig_comment(rName, secondComment), Check: resource.ComposeTestCheckFunc( testAccCheckKeyGroupExistence(resourceName), resource.TestCheckResourceAttr("aws_cloudfront_key_group.test", "comment", secondComment), @@ -114,7 +114,7 @@ func TestAccCloudFrontKeyGroup_items(t *testing.T) { CheckDestroy: testAccCheckKeyGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyGroupConfig(rName), + Config: testAccKeyGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyGroupExistence(resourceName), resource.TestCheckResourceAttr("aws_cloudfront_key_group.test", "items.#", "1"), @@ -126,7 +126,7 @@ func TestAccCloudFrontKeyGroup_items(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccKeyGroupItemsConfig(rName), + Config: testAccKeyGroupConfig_items(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyGroupExistence(resourceName), resource.TestCheckResourceAttr("aws_cloudfront_key_group.test", "items.#", "2"), @@ -195,7 +195,7 @@ resource "aws_cloudfront_public_key" "test" { `, rName) } -func testAccKeyGroupConfig(rName string) string { +func testAccKeyGroupConfig_basic(rName string) string { return testAccKeyGroupBaseConfig(rName) + fmt.Sprintf(` resource "aws_cloudfront_key_group" "test" { comment = "test key group" @@ -205,7 +205,7 @@ resource "aws_cloudfront_key_group" "test" { `, rName) } -func testAccKeyGroupCommentConfig(rName string, comment string) string { +func testAccKeyGroupConfig_comment(rName string, comment string) string { return testAccKeyGroupBaseConfig(rName) + fmt.Sprintf(` resource "aws_cloudfront_key_group" "test" { comment = %q @@ -215,7 +215,7 @@ resource "aws_cloudfront_key_group" "test" { `, comment, rName) } -func testAccKeyGroupItemsConfig(rName string) string { +func testAccKeyGroupConfig_items(rName string) string { return testAccKeyGroupBaseConfig(rName) + fmt.Sprintf(` resource "aws_cloudfront_public_key" "test2" { comment = "second test key" diff --git a/internal/service/cloudfront/list.go b/internal/service/cloudfront/list.go index a2a42f903cc..effbd1fdfa8 100644 --- a/internal/service/cloudfront/list.go +++ b/internal/service/cloudfront/list.go @@ -5,7 +5,7 @@ import ( "github.com/aws/aws-sdk-go/service/cloudfront" ) -// Custom Cloudfront listing functions using similar formatting as other service generated code. +// Custom CloudFront listing functions using similar formatting as other service generated code. func ListCachePoliciesPages(conn *cloudfront.CloudFront, input *cloudfront.ListCachePoliciesInput, fn func(*cloudfront.ListCachePoliciesOutput, bool) bool) error { for { diff --git a/internal/service/cloudfront/log_delivery_canonical_user_id_data_source.go b/internal/service/cloudfront/log_delivery_canonical_user_id_data_source.go index ca69e2eb9a9..2b10917dbc9 100644 --- a/internal/service/cloudfront/log_delivery_canonical_user_id_data_source.go +++ b/internal/service/cloudfront/log_delivery_canonical_user_id_data_source.go @@ -8,10 +8,10 @@ import ( const ( // See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html#AccessLogsBucketAndFileOwnership. - defaultCloudFrontLogDeliveryCanonicalUserId = "c4c1ede66af53448b93c283ce9448c4ba468c9432aa01d700d3878632f77d2d0" + defaultLogDeliveryCanonicalUserID = "c4c1ede66af53448b93c283ce9448c4ba468c9432aa01d700d3878632f77d2d0" // See https://docs.amazonaws.cn/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html#AccessLogsBucketAndFileOwnership. - cnCloudFrontLogDeliveryCanonicalUserId = "a52cb28745c0c06e84ec548334e44bfa7fc2a85c54af20cd59e4969344b7af56" + cnLogDeliveryCanonicalUserID = "a52cb28745c0c06e84ec548334e44bfa7fc2a85c54af20cd59e4969344b7af56" ) func DataSourceLogDeliveryCanonicalUserID() *schema.Resource { @@ -28,7 +28,7 @@ func DataSourceLogDeliveryCanonicalUserID() *schema.Resource { } func dataSourceLogDeliveryCanonicalUserIDRead(d *schema.ResourceData, meta interface{}) error { - canonicalId := defaultCloudFrontLogDeliveryCanonicalUserId + canonicalId := defaultLogDeliveryCanonicalUserID region := meta.(*conns.AWSClient).Region if v, ok := d.GetOk("region"); ok { @@ -36,7 +36,7 @@ func dataSourceLogDeliveryCanonicalUserIDRead(d *schema.ResourceData, meta inter } if v, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), region); ok && v.ID() == endpoints.AwsCnPartitionID { - canonicalId = cnCloudFrontLogDeliveryCanonicalUserId + canonicalId = cnLogDeliveryCanonicalUserID } d.SetId(canonicalId) diff --git a/internal/service/cloudfront/log_delivery_canonical_user_id_data_source_test.go b/internal/service/cloudfront/log_delivery_canonical_user_id_data_source_test.go index dac2170aa44..698c1f044db 100644 --- a/internal/service/cloudfront/log_delivery_canonical_user_id_data_source_test.go +++ b/internal/service/cloudfront/log_delivery_canonical_user_id_data_source_test.go @@ -19,7 +19,7 @@ func TestAccCloudFrontLogDeliveryCanonicalUserIDDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLogDeliveryCanonicalUserIdDataSourceConfig(""), + Config: testAccLogDeliveryCanonicalUserIdDataSourceConfig_basic(""), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", "c4c1ede66af53448b93c283ce9448c4ba468c9432aa01d700d3878632f77d2d0"), ), @@ -37,7 +37,7 @@ func TestAccCloudFrontLogDeliveryCanonicalUserIDDataSource_default(t *testing.T) ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLogDeliveryCanonicalUserIdDataSourceConfig(endpoints.UsWest2RegionID), + Config: testAccLogDeliveryCanonicalUserIdDataSourceConfig_basic(endpoints.UsWest2RegionID), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", "c4c1ede66af53448b93c283ce9448c4ba468c9432aa01d700d3878632f77d2d0"), ), @@ -55,7 +55,7 @@ func TestAccCloudFrontLogDeliveryCanonicalUserIDDataSource_cn(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLogDeliveryCanonicalUserIdDataSourceConfig(endpoints.CnNorthwest1RegionID), + Config: testAccLogDeliveryCanonicalUserIdDataSourceConfig_basic(endpoints.CnNorthwest1RegionID), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", "a52cb28745c0c06e84ec548334e44bfa7fc2a85c54af20cd59e4969344b7af56"), ), @@ -64,7 +64,7 @@ func TestAccCloudFrontLogDeliveryCanonicalUserIDDataSource_cn(t *testing.T) { }) } -func testAccLogDeliveryCanonicalUserIdDataSourceConfig(region string) string { +func testAccLogDeliveryCanonicalUserIdDataSourceConfig_basic(region string) string { if region == "" { region = "null" } diff --git a/internal/service/cloudfront/monitoring_subscription_test.go b/internal/service/cloudfront/monitoring_subscription_test.go index fdea0fd3848..7f9f4122466 100644 --- a/internal/service/cloudfront/monitoring_subscription_test.go +++ b/internal/service/cloudfront/monitoring_subscription_test.go @@ -24,7 +24,7 @@ func TestAccCloudFrontMonitoringSubscription_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccMonitoringSubscriptionConfig("Enabled"), + Config: testAccMonitoringSubscriptionConfig_basic("Enabled"), Check: resource.ComposeTestCheckFunc( testAccCheckMonitoringSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "distribution_id"), @@ -53,7 +53,7 @@ func TestAccCloudFrontMonitoringSubscription_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccMonitoringSubscriptionConfig("Enabled"), + Config: testAccMonitoringSubscriptionConfig_basic("Enabled"), Check: resource.ComposeTestCheckFunc( testAccCheckMonitoringSubscriptionExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceMonitoringSubscription(), resourceName), @@ -75,7 +75,7 @@ func TestAccCloudFrontMonitoringSubscription_update(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccMonitoringSubscriptionConfig("Enabled"), + Config: testAccMonitoringSubscriptionConfig_basic("Enabled"), Check: resource.ComposeTestCheckFunc( testAccCheckMonitoringSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "distribution_id"), @@ -90,7 +90,7 @@ func TestAccCloudFrontMonitoringSubscription_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMonitoringSubscriptionConfig("Disabled"), + Config: testAccMonitoringSubscriptionConfig_basic("Disabled"), Check: resource.ComposeTestCheckFunc( testAccCheckMonitoringSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "distribution_id"), @@ -198,7 +198,7 @@ resource "aws_cloudfront_distribution" "test" { ` } -func testAccMonitoringSubscriptionConfig(status string) string { +func testAccMonitoringSubscriptionConfig_basic(status string) string { return acctest.ConfigCompose( testAccMonitoringSubscriptionBaseConfig(), fmt.Sprintf(` diff --git a/internal/service/cloudfront/origin_access_identities_data_source_test.go b/internal/service/cloudfront/origin_access_identities_data_source_test.go index eed4effe65c..28c011a400f 100644 --- a/internal/service/cloudfront/origin_access_identities_data_source_test.go +++ b/internal/service/cloudfront/origin_access_identities_data_source_test.go @@ -22,7 +22,7 @@ func TestAccCloudFrontOriginAccessIdentitiesDataSource_comments(t *testing.T) { CheckDestroy: testAccCheckOriginAccessIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginAccessIdentitiesDataSourceCommentsConfig(rName), + Config: testAccOriginAccessIdentitiesDataSourceConfig_comments(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "iam_arns.#", "1"), resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), @@ -47,7 +47,7 @@ func TestAccCloudFrontOriginAccessIdentitiesDataSource_all(t *testing.T) { CheckDestroy: testAccCheckOriginAccessIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginAccessIdentitiesDataSourceNoCommentsConfig(rName), + Config: testAccOriginAccessIdentitiesDataSourceConfig_noComments(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "iam_arns.#", "1"), acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "ids.#", "1"), @@ -58,7 +58,7 @@ func TestAccCloudFrontOriginAccessIdentitiesDataSource_all(t *testing.T) { }) } -func testAccOriginAccessIdentitiesDataSourceCommentsConfig(rName string) string { +func testAccOriginAccessIdentitiesDataSourceConfig_comments(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_origin_access_identity" "test1" { comment = "%[1]s-1-comment" @@ -76,7 +76,7 @@ data "aws_cloudfront_origin_access_identities" "test" { `, rName) } -func testAccOriginAccessIdentitiesDataSourceNoCommentsConfig(rName string) string { +func testAccOriginAccessIdentitiesDataSourceConfig_noComments(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_origin_access_identity" "test1" { comment = "%[1]s-1-comment" diff --git a/internal/service/cloudfront/origin_access_identity_data_source_test.go b/internal/service/cloudfront/origin_access_identity_data_source_test.go index b2d23c62f6d..e87c91b6c1e 100644 --- a/internal/service/cloudfront/origin_access_identity_data_source_test.go +++ b/internal/service/cloudfront/origin_access_identity_data_source_test.go @@ -20,7 +20,7 @@ func TestAccCloudFrontOriginAccessIdentityDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckOriginAccessIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginAccessIdentityDataSourceConfig, + Config: testAccOriginAccessIdentityDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckOriginAccessIdentityExistence(resourceName, &origin), resource.TestCheckResourceAttrPair(dataSourceName, "iam_arn", resourceName, "iam_arn"), @@ -35,7 +35,7 @@ func TestAccCloudFrontOriginAccessIdentityDataSource_basic(t *testing.T) { }) } -const testAccOriginAccessIdentityDataSourceConfig = ` +const testAccOriginAccessIdentityDataSourceConfig_basic = ` resource "aws_cloudfront_origin_access_identity" "test" { comment = "some comment" } diff --git a/internal/service/cloudfront/origin_access_identity_test.go b/internal/service/cloudfront/origin_access_identity_test.go index 163431c3b32..b594c1a12b0 100644 --- a/internal/service/cloudfront/origin_access_identity_test.go +++ b/internal/service/cloudfront/origin_access_identity_test.go @@ -25,7 +25,7 @@ func TestAccCloudFrontOriginAccessIdentity_basic(t *testing.T) { CheckDestroy: testAccCheckOriginAccessIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginAccessIdentityConfig, + Config: testAccOriginAccessIdentityConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckOriginAccessIdentityExistence(resourceName, &origin), resource.TestCheckResourceAttr(resourceName, "comment", "some comment"), @@ -56,7 +56,7 @@ func TestAccCloudFrontOriginAccessIdentity_noComment(t *testing.T) { CheckDestroy: testAccCheckOriginAccessIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginAccessIdentityNoCommentConfig, + Config: testAccOriginAccessIdentityConfig_noComment, Check: resource.ComposeTestCheckFunc( testAccCheckOriginAccessIdentityExistence(resourceName, &origin), resource.TestMatchResourceAttr(resourceName, "caller_reference", regexp.MustCompile(fmt.Sprintf("^%s", resource.UniqueIdPrefix))), @@ -86,7 +86,7 @@ func TestAccCloudFrontOriginAccessIdentity_disappears(t *testing.T) { CheckDestroy: testAccCheckOriginAccessIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginAccessIdentityConfig, + Config: testAccOriginAccessIdentityConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckOriginAccessIdentityExistence(resourceName, &origin), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceOriginAccessIdentity(), resourceName), @@ -145,13 +145,13 @@ func testAccCheckOriginAccessIdentityExistence(r string, origin *cloudfront.GetC } } -const testAccOriginAccessIdentityConfig = ` +const testAccOriginAccessIdentityConfig_basic = ` resource "aws_cloudfront_origin_access_identity" "test" { comment = "some comment" } ` -const testAccOriginAccessIdentityNoCommentConfig = ` +const testAccOriginAccessIdentityConfig_noComment = ` resource "aws_cloudfront_origin_access_identity" "test" { } ` diff --git a/internal/service/cloudfront/origin_request_policy_data_source_test.go b/internal/service/cloudfront/origin_request_policy_data_source_test.go index d80d37c7472..2147f23f5c5 100644 --- a/internal/service/cloudfront/origin_request_policy_data_source_test.go +++ b/internal/service/cloudfront/origin_request_policy_data_source_test.go @@ -23,7 +23,7 @@ func TestAccCloudFrontOriginRequestPolicyDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckPublicKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginRequestPolicyDataSourceConfig(rName), + Config: testAccOriginRequestPolicyDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSource1Name, "comment", resourceName, "comment"), resource.TestCheckResourceAttrPair(dataSource1Name, "cookies_config.#", resourceName, "cookies_config.#"), @@ -52,7 +52,7 @@ func TestAccCloudFrontOriginRequestPolicyDataSource_basic(t *testing.T) { }) } -func testAccOriginRequestPolicyDataSourceConfig(rName string) string { +func testAccOriginRequestPolicyDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_cloudfront_origin_request_policy" "by_name" { name = aws_cloudfront_origin_request_policy.test.name diff --git a/internal/service/cloudfront/origin_request_policy_test.go b/internal/service/cloudfront/origin_request_policy_test.go index e3864187b30..1c59a413c09 100644 --- a/internal/service/cloudfront/origin_request_policy_test.go +++ b/internal/service/cloudfront/origin_request_policy_test.go @@ -25,7 +25,7 @@ func TestAccCloudFrontOriginRequestPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckOriginRequestPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginRequestPolicyConfig(rName), + Config: testAccOriginRequestPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOriginRequestPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", ""), @@ -62,7 +62,7 @@ func TestAccCloudFrontOriginRequestPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckOriginRequestPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginRequestPolicyConfig(rName), + Config: testAccOriginRequestPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOriginRequestPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceOriginRequestPolicy(), resourceName), @@ -85,7 +85,7 @@ func TestAccCloudFrontOriginRequestPolicy_Items(t *testing.T) { CheckDestroy: testAccCheckOriginRequestPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccOriginRequestPolicyItemsConfig(rName), + Config: testAccOriginRequestPolicyConfig_items(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOriginRequestPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", "test comment"), @@ -114,7 +114,7 @@ func TestAccCloudFrontOriginRequestPolicy_Items(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOriginRequestPolicyItemsUpdatedConfig(rName), + Config: testAccOriginRequestPolicyConfig_itemsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOriginRequestPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", "test comment updated"), @@ -184,7 +184,7 @@ func testAccCheckOriginRequestPolicyExists(n string) resource.TestCheckFunc { } } -func testAccOriginRequestPolicyConfig(rName string) string { +func testAccOriginRequestPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_origin_request_policy" "test" { name = %[1]q @@ -204,7 +204,7 @@ resource "aws_cloudfront_origin_request_policy" "test" { `, rName) } -func testAccOriginRequestPolicyItemsConfig(rName string) string { +func testAccOriginRequestPolicyConfig_items(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_origin_request_policy" "test" { name = %[1]q @@ -237,7 +237,7 @@ resource "aws_cloudfront_origin_request_policy" "test" { `, rName) } -func testAccOriginRequestPolicyItemsUpdatedConfig(rName string) string { +func testAccOriginRequestPolicyConfig_itemsUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_origin_request_policy" "test" { name = %[1]q diff --git a/internal/service/cloudfront/public_key_test.go b/internal/service/cloudfront/public_key_test.go index 23fda99ec83..5204ae58ac3 100644 --- a/internal/service/cloudfront/public_key_test.go +++ b/internal/service/cloudfront/public_key_test.go @@ -27,7 +27,7 @@ func TestAccCloudFrontPublicKey_basic(t *testing.T) { CheckDestroy: testAccCheckPublicKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccPublicKeyConfig(rInt), + Config: testAccPublicKeyConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckPublicKeyExistence(resourceName), resource.TestCheckResourceAttr("aws_cloudfront_public_key.example", "comment", "test key"), @@ -55,7 +55,7 @@ func TestAccCloudFrontPublicKey_disappears(t *testing.T) { CheckDestroy: testAccCheckPublicKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccPublicKeyConfig(rInt), + Config: testAccPublicKeyConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckPublicKeyExistence(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourcePublicKey(), resourceName), @@ -106,7 +106,7 @@ func TestAccCloudFrontPublicKey_update(t *testing.T) { CheckDestroy: testAccCheckPublicKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccPublicKeyConfig(rInt), + Config: testAccPublicKeyConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckPublicKeyExistence(resourceName), resource.TestCheckResourceAttr("aws_cloudfront_public_key.example", "comment", "test key"), @@ -118,7 +118,7 @@ func TestAccCloudFrontPublicKey_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPublicKeyUpdateConfig(rInt), + Config: testAccPublicKeyConfig_update(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckPublicKeyExistence(resourceName), resource.TestCheckResourceAttr("aws_cloudfront_public_key.example", "comment", "test key1"), @@ -177,7 +177,7 @@ func testAccCheckPublicKeyDestroy(s *terraform.State) error { return nil } -func testAccPublicKeyConfig(rInt int) string { +func testAccPublicKeyConfig_basic(rInt int) string { return fmt.Sprintf(` resource "aws_cloudfront_public_key" "example" { comment = "test key" @@ -197,7 +197,7 @@ resource "aws_cloudfront_public_key" "example" { ` } -func testAccPublicKeyUpdateConfig(rInt int) string { +func testAccPublicKeyConfig_update(rInt int) string { return fmt.Sprintf(` resource "aws_cloudfront_public_key" "example" { comment = "test key1" diff --git a/internal/service/cloudfront/realtime_log_config.go b/internal/service/cloudfront/realtime_log_config.go index 6b98ba46583..aa4c7843e4c 100644 --- a/internal/service/cloudfront/realtime_log_config.go +++ b/internal/service/cloudfront/realtime_log_config.go @@ -188,7 +188,7 @@ func resourceRealtimeLogConfigDelete(d *schema.ResourceData, meta interface{}) e } if err != nil { - return fmt.Errorf("error deleting Cloudfront Real-time Log Config (%s): %w", d.Id(), err) + return fmt.Errorf("error deleting CloudFront Real-time Log Config (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/cloudfront/realtime_log_config_data_source_test.go b/internal/service/cloudfront/realtime_log_config_data_source_test.go index 6cca368d47c..57c5b31d83f 100644 --- a/internal/service/cloudfront/realtime_log_config_data_source_test.go +++ b/internal/service/cloudfront/realtime_log_config_data_source_test.go @@ -23,7 +23,7 @@ func TestAccCloudFrontRealtimeLogConfigDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckRealtimeLogConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccRealtimeLogConfigDataSource(rName, samplingRate), + Config: testAccRealtimeLogConfigDataSourceConfig_basic(rName, samplingRate), Check: resource.ComposeTestCheckFunc( testAccCheckRealtimeLogConfigExists(resourceName, &v), resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), @@ -39,9 +39,9 @@ func TestAccCloudFrontRealtimeLogConfigDataSource_basic(t *testing.T) { }) } -func testAccRealtimeLogConfigDataSource(rName string, samplingRate int) string { +func testAccRealtimeLogConfigDataSourceConfig_basic(rName string, samplingRate int) string { return acctest.ConfigCompose( - testAccRealtimeLogConfig(rName, samplingRate), ` + testAccRealtimeLogConfigConfig_basic(rName, samplingRate), ` data "aws_cloudfront_realtime_log_config" "test" { name = aws_cloudfront_realtime_log_config.test.name } diff --git a/internal/service/cloudfront/realtime_log_config_test.go b/internal/service/cloudfront/realtime_log_config_test.go index 76e32ffbc7c..9921b0e928e 100644 --- a/internal/service/cloudfront/realtime_log_config_test.go +++ b/internal/service/cloudfront/realtime_log_config_test.go @@ -30,7 +30,7 @@ func TestAccCloudFrontRealtimeLogConfig_basic(t *testing.T) { CheckDestroy: testAccCheckRealtimeLogConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccRealtimeLogConfig(rName, samplingRate), + Config: testAccRealtimeLogConfigConfig_basic(rName, samplingRate), Check: resource.ComposeTestCheckFunc( testAccCheckRealtimeLogConfigExists(resourceName, &v), acctest.CheckResourceAttrGlobalARN(resourceName, "arn", "cloudfront", fmt.Sprintf("realtime-log-config/%s", rName)), @@ -68,7 +68,7 @@ func TestAccCloudFrontRealtimeLogConfig_disappears(t *testing.T) { CheckDestroy: testAccCheckRealtimeLogConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccRealtimeLogConfig(rName, samplingRate), + Config: testAccRealtimeLogConfigConfig_basic(rName, samplingRate), Check: resource.ComposeTestCheckFunc( testAccCheckRealtimeLogConfigExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceRealtimeLogConfig(), resourceName), @@ -97,7 +97,7 @@ func TestAccCloudFrontRealtimeLogConfig_updates(t *testing.T) { CheckDestroy: testAccCheckRealtimeLogConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccRealtimeLogConfig(rName, samplingRate1), + Config: testAccRealtimeLogConfigConfig_basic(rName, samplingRate1), Check: resource.ComposeTestCheckFunc( testAccCheckRealtimeLogConfigExists(resourceName, &v), acctest.CheckResourceAttrGlobalARN(resourceName, "arn", "cloudfront", fmt.Sprintf("realtime-log-config/%s", rName)), @@ -114,7 +114,7 @@ func TestAccCloudFrontRealtimeLogConfig_updates(t *testing.T) { ), }, { - Config: testAccRealtimeLogUpdatedConfig(rName, samplingRate2), + Config: testAccRealtimeLogConfigConfig_updated(rName, samplingRate2), Check: resource.ComposeTestCheckFunc( testAccCheckRealtimeLogConfigExists(resourceName, &v), acctest.CheckResourceAttrGlobalARN(resourceName, "arn", "cloudfront", fmt.Sprintf("realtime-log-config/%s", rName)), @@ -242,7 +242,7 @@ EOF `, rName, count) } -func testAccRealtimeLogConfig(rName string, samplingRate int) string { +func testAccRealtimeLogConfigConfig_basic(rName string, samplingRate int) string { return acctest.ConfigCompose( testAccRealtimeLogBaseConfig(rName, 1), fmt.Sprintf(` @@ -265,7 +265,7 @@ resource "aws_cloudfront_realtime_log_config" "test" { `, rName, samplingRate)) } -func testAccRealtimeLogUpdatedConfig(rName string, samplingRate int) string { +func testAccRealtimeLogConfigConfig_updated(rName string, samplingRate int) string { return acctest.ConfigCompose( testAccRealtimeLogBaseConfig(rName, 2), fmt.Sprintf(` diff --git a/internal/service/cloudfront/response_headers_policy.go b/internal/service/cloudfront/response_headers_policy.go index 6d8aff33db6..1ee5db9c03c 100644 --- a/internal/service/cloudfront/response_headers_policy.go +++ b/internal/service/cloudfront/response_headers_policy.go @@ -104,7 +104,7 @@ func ResourceResponseHeadersPolicy() *schema.Resource { }, }, }, - AtLeastOneOf: []string{"cors_config", "custom_headers_config", "security_headers_config"}, + AtLeastOneOf: []string{"cors_config", "custom_headers_config", "security_headers_config", "server_timing_headers_config"}, }, "custom_headers_config": { Type: schema.TypeList, @@ -134,7 +134,7 @@ func ResourceResponseHeadersPolicy() *schema.Resource { }, }, }, - AtLeastOneOf: []string{"cors_config", "custom_headers_config", "security_headers_config"}, + AtLeastOneOf: []string{"cors_config", "custom_headers_config", "security_headers_config", "server_timing_headers_config"}, }, "etag": { Type: schema.TypeString, @@ -269,7 +269,26 @@ func ResourceResponseHeadersPolicy() *schema.Resource { }, }, }, - AtLeastOneOf: []string{"cors_config", "custom_headers_config", "security_headers_config"}, + AtLeastOneOf: []string{"cors_config", "custom_headers_config", "security_headers_config", "server_timing_headers_config"}, + }, + "server_timing_headers_config": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Required: true, + }, + "sampling_rate": { + Type: schema.TypeFloat, + Required: true, + ValidateFunc: validation.FloatBetween(0.0, 100.0), + }, + }, + }, + AtLeastOneOf: []string{"cors_config", "custom_headers_config", "security_headers_config", "server_timing_headers_config"}, }, }, } @@ -299,6 +318,10 @@ func resourceResponseHeadersPolicyCreate(d *schema.ResourceData, meta interface{ apiObject.SecurityHeadersConfig = expandResponseHeadersPolicySecurityHeadersConfig(v.([]interface{})[0].(map[string]interface{})) } + if v, ok := d.GetOk("server_timing_headers_config"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + apiObject.ServerTimingHeadersConfig = expandResponseHeadersPolicyServerTimingHeadersConfig(v.([]interface{})[0].(map[string]interface{})) + } + input := &cloudfront.CreateResponseHeadersPolicyInput{ ResponseHeadersPolicyConfig: apiObject, } @@ -356,6 +379,14 @@ func resourceResponseHeadersPolicyRead(d *schema.ResourceData, meta interface{}) d.Set("security_headers_config", nil) } + if apiObject.ServerTimingHeadersConfig != nil { + if err := d.Set("server_timing_headers_config", []interface{}{flattenResponseHeadersPolicyServerTimingHeadersConfig(apiObject.ServerTimingHeadersConfig)}); err != nil { + return fmt.Errorf("error setting server_timing_headers_config: %w", err) + } + } else { + d.Set("server_timing_headers_config", nil) + } + return nil } @@ -386,6 +417,10 @@ func resourceResponseHeadersPolicyUpdate(d *schema.ResourceData, meta interface{ apiObject.SecurityHeadersConfig = expandResponseHeadersPolicySecurityHeadersConfig(v.([]interface{})[0].(map[string]interface{})) } + if v, ok := d.GetOk("server_timing_headers_config"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + apiObject.ServerTimingHeadersConfig = expandResponseHeadersPolicyServerTimingHeadersConfig(v.([]interface{})[0].(map[string]interface{})) + } + input := &cloudfront.UpdateResponseHeadersPolicyInput{ Id: aws.String(d.Id()), IfMatch: aws.String(d.Get("etag").(string)), @@ -1057,3 +1092,43 @@ func flattenResponseHeadersPolicyXSSProtection(apiObject *cloudfront.ResponseHea return tfMap } + +// +// server_timing_headers_config: +// + +func expandResponseHeadersPolicyServerTimingHeadersConfig(tfMap map[string]interface{}) *cloudfront.ResponseHeadersPolicyServerTimingHeadersConfig { + if tfMap == nil { + return nil + } + + apiObject := &cloudfront.ResponseHeadersPolicyServerTimingHeadersConfig{} + + if v, ok := tfMap["enabled"].(bool); ok { + apiObject.Enabled = aws.Bool(v) + } + + if v, ok := tfMap["sampling_rate"].(float64); ok && v != 0 { + apiObject.SamplingRate = aws.Float64(v) + } + + return apiObject +} + +func flattenResponseHeadersPolicyServerTimingHeadersConfig(apiObject *cloudfront.ResponseHeadersPolicyServerTimingHeadersConfig) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.Enabled; v != nil { + tfMap["enabled"] = aws.BoolValue(v) + } + + if v := apiObject.SamplingRate; v != nil { + tfMap["sampling_rate"] = aws.Float64Value(v) + } + + return tfMap +} diff --git a/internal/service/cloudfront/response_headers_policy_data_source.go b/internal/service/cloudfront/response_headers_policy_data_source.go index 6567d924c10..12d32adfad8 100644 --- a/internal/service/cloudfront/response_headers_policy_data_source.go +++ b/internal/service/cloudfront/response_headers_policy_data_source.go @@ -250,6 +250,21 @@ func DataSourceResponseHeadersPolicy() *schema.Resource { }, }, }, + "server_timing_headers_config": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "sampling_rate": { + Type: schema.TypeFloat, + Computed: true, + }, + }}, + }, }, } } @@ -324,5 +339,13 @@ func dataSourceResponseHeadersPolicyRead(d *schema.ResourceData, meta interface{ d.Set("security_headers_config", nil) } + if apiObject.ServerTimingHeadersConfig != nil { + if err := d.Set("server_timing_headers_config", []interface{}{flattenResponseHeadersPolicyServerTimingHeadersConfig(apiObject.ServerTimingHeadersConfig)}); err != nil { + return fmt.Errorf("error setting server_timing_headers_config: %w", err) + } + } else { + d.Set("server_timing_headers_config", nil) + } + return nil } diff --git a/internal/service/cloudfront/response_headers_policy_data_source_test.go b/internal/service/cloudfront/response_headers_policy_data_source_test.go index 2ba7a767b31..d1ba2679adc 100644 --- a/internal/service/cloudfront/response_headers_policy_data_source_test.go +++ b/internal/service/cloudfront/response_headers_policy_data_source_test.go @@ -23,7 +23,7 @@ func TestAccCloudFrontResponseHeadersPolicyDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckPublicKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccResponseHeadersPolicyDataSourceConfig(rName), + Config: testAccResponseHeadersPolicyDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSource1Name, "comment", resourceName, "comment"), resource.TestCheckResourceAttrPair(dataSource1Name, "cors_config.#", resourceName, "cors_config.#"), @@ -49,6 +49,9 @@ func TestAccCloudFrontResponseHeadersPolicyDataSource_basic(t *testing.T) { resource.TestCheckResourceAttrPair(dataSource1Name, "security_headers_config.0.referrer_policy.#", resourceName, "security_headers_config.0.referrer_policy.#"), resource.TestCheckResourceAttrPair(dataSource1Name, "security_headers_config.0.strict_transport_security.#", resourceName, "security_headers_config.0.strict_transport_security.#"), resource.TestCheckResourceAttrPair(dataSource1Name, "security_headers_config.0.xss_protection.#", resourceName, "security_headers_config.0.xss_protection.#"), + resource.TestCheckResourceAttrPair(dataSource1Name, "server_timing_headers_config.#", resourceName, "server_timing_headers_config.#"), + resource.TestCheckResourceAttrPair(dataSource1Name, "server_timing_headers_config.0.enabled", resourceName, "server_timing_headers_config.0.enabled"), + resource.TestCheckResourceAttrPair(dataSource1Name, "server_timing_headers_config.0.sampling_rate", resourceName, "server_timing_headers_config.0.sampling_rate"), resource.TestCheckResourceAttrPair(dataSource2Name, "comment", resourceName, "comment"), resource.TestCheckResourceAttrPair(dataSource2Name, "cors_config.#", resourceName, "cors_config.#"), @@ -74,13 +77,16 @@ func TestAccCloudFrontResponseHeadersPolicyDataSource_basic(t *testing.T) { resource.TestCheckResourceAttrPair(dataSource2Name, "security_headers_config.0.referrer_policy.#", resourceName, "security_headers_config.0.referrer_policy.#"), resource.TestCheckResourceAttrPair(dataSource2Name, "security_headers_config.0.strict_transport_security.#", resourceName, "security_headers_config.0.strict_transport_security.#"), resource.TestCheckResourceAttrPair(dataSource2Name, "security_headers_config.0.xss_protection.#", resourceName, "security_headers_config.0.xss_protection.#"), + resource.TestCheckResourceAttrPair(dataSource2Name, "server_timing_headers_config.#", resourceName, "server_timing_headers_config.#"), + resource.TestCheckResourceAttrPair(dataSource2Name, "server_timing_headers_config.0.enabled", resourceName, "server_timing_headers_config.0.enabled"), + resource.TestCheckResourceAttrPair(dataSource2Name, "server_timing_headers_config.0.sampling_rate", resourceName, "server_timing_headers_config.0.sampling_rate"), ), }, }, }) } -func testAccResponseHeadersPolicyDataSourceConfig(rName string) string { +func testAccResponseHeadersPolicyDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_cloudfront_response_headers_policy" "by_name" { name = aws_cloudfront_response_headers_policy.test.name @@ -143,6 +149,11 @@ resource "aws_cloudfront_response_headers_policy" "test" { preload = true } } + + server_timing_headers_config { + enabled = true + sampling_rate = 10 + } } `, rName) } diff --git a/internal/service/cloudfront/response_headers_policy_test.go b/internal/service/cloudfront/response_headers_policy_test.go index 2af64eedf7e..78ab54d76b2 100644 --- a/internal/service/cloudfront/response_headers_policy_test.go +++ b/internal/service/cloudfront/response_headers_policy_test.go @@ -26,7 +26,7 @@ func TestAccCloudFrontResponseHeadersPolicy_CorsConfig(t *testing.T) { CheckDestroy: testAccCheckResponseHeadersPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResponseHeadersPolicyCorsConfigConfig(rName1), + Config: testAccResponseHeadersPolicyConfig_cors(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckResponseHeadersPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", "test comment"), @@ -50,6 +50,7 @@ func TestAccCloudFrontResponseHeadersPolicy_CorsConfig(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "etag"), resource.TestCheckResourceAttr(resourceName, "name", rName1), resource.TestCheckResourceAttr(resourceName, "security_headers_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.#", "0"), ), }, { @@ -59,7 +60,7 @@ func TestAccCloudFrontResponseHeadersPolicy_CorsConfig(t *testing.T) { ImportStateVerifyIgnore: []string{}, }, { - Config: testAccResponseHeadersPolicyCorsConfigUpdatedConfig(rName2), + Config: testAccResponseHeadersPolicyConfig_corsUpdated(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckResponseHeadersPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", "test comment updated"), @@ -84,6 +85,7 @@ func TestAccCloudFrontResponseHeadersPolicy_CorsConfig(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "etag"), resource.TestCheckResourceAttr(resourceName, "name", rName2), resource.TestCheckResourceAttr(resourceName, "security_headers_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.#", "0"), ), }, }, @@ -101,7 +103,7 @@ func TestAccCloudFrontResponseHeadersPolicy_CustomHeadersConfig(t *testing.T) { CheckDestroy: testAccCheckResponseHeadersPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResponseHeadersPolicyCustomHeadersConfigConfig(rName), + Config: testAccResponseHeadersPolicyConfig_custom(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResponseHeadersPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", ""), @@ -121,6 +123,7 @@ func TestAccCloudFrontResponseHeadersPolicy_CustomHeadersConfig(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "etag"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "security_headers_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.#", "0"), ), }, { @@ -144,7 +147,7 @@ func TestAccCloudFrontResponseHeadersPolicy_SecurityHeadersConfig(t *testing.T) CheckDestroy: testAccCheckResponseHeadersPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResponseHeadersPolicySecurityHeadersConfigConfig(rName), + Config: testAccResponseHeadersPolicyConfig_security(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResponseHeadersPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", ""), @@ -173,6 +176,7 @@ func TestAccCloudFrontResponseHeadersPolicy_SecurityHeadersConfig(t *testing.T) resource.TestCheckResourceAttr(resourceName, "security_headers_config.0.strict_transport_security.0.override", "true"), resource.TestCheckResourceAttr(resourceName, "security_headers_config.0.strict_transport_security.0.preload", "true"), resource.TestCheckResourceAttr(resourceName, "security_headers_config.0.xss_protection.#", "0"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.#", "0"), ), }, { @@ -182,7 +186,7 @@ func TestAccCloudFrontResponseHeadersPolicy_SecurityHeadersConfig(t *testing.T) ImportStateVerifyIgnore: []string{}, }, { - Config: testAccResponseHeadersPolicySecurityHeadersConfigUpdatedConfig(rName), + Config: testAccResponseHeadersPolicyConfig_securityUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResponseHeadersPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "comment", ""), @@ -204,6 +208,72 @@ func TestAccCloudFrontResponseHeadersPolicy_SecurityHeadersConfig(t *testing.T) resource.TestCheckResourceAttr(resourceName, "security_headers_config.0.xss_protection.0.override", "true"), resource.TestCheckResourceAttr(resourceName, "security_headers_config.0.xss_protection.0.protection", "true"), resource.TestCheckResourceAttr(resourceName, "security_headers_config.0.xss_protection.0.report_uri", "https://example.com/"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.#", "0"), + ), + }, + }, + }) +} + +func TestAccCloudFrontResponseHeadersPolicy_ServerTimingHeadersConfig(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_cloudfront_response_headers_policy.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudfront.EndpointsID, t) }, + ErrorCheck: acctest.ErrorCheck(t, cloudfront.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckResponseHeadersPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccResponseHeadersPolicyConfig_serverTiming(rName, true, 10), + Check: resource.ComposeTestCheckFunc( + testAccCheckResponseHeadersPolicyExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "comment", ""), + resource.TestCheckResourceAttr(resourceName, "cors_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "custom_headers_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "security_headers_config.#", "0"), + resource.TestCheckResourceAttrSet(resourceName, "etag"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.0.sampling_rate", "10"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + { + Config: testAccResponseHeadersPolicyConfig_serverTiming(rName, true, 90), + Check: resource.ComposeTestCheckFunc( + testAccCheckResponseHeadersPolicyExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "comment", ""), + resource.TestCheckResourceAttr(resourceName, "cors_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "custom_headers_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "security_headers_config.#", "0"), + resource.TestCheckResourceAttrSet(resourceName, "etag"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.0.sampling_rate", "90"), + ), + }, + { + Config: testAccResponseHeadersPolicyConfig_serverTiming(rName, false, 0), + Check: resource.ComposeTestCheckFunc( + testAccCheckResponseHeadersPolicyExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "comment", ""), + resource.TestCheckResourceAttr(resourceName, "cors_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "custom_headers_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "security_headers_config.#", "0"), + resource.TestCheckResourceAttrSet(resourceName, "etag"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.0.enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "server_timing_headers_config.0.sampling_rate", "0"), ), }, }, @@ -221,7 +291,7 @@ func TestAccCloudFrontResponseHeadersPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckResponseHeadersPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResponseHeadersPolicyCorsConfigConfig(rName), + Config: testAccResponseHeadersPolicyConfig_cors(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResponseHeadersPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudfront.ResourceResponseHeadersPolicy(), resourceName), @@ -279,7 +349,7 @@ func testAccCheckResponseHeadersPolicyExists(n string) resource.TestCheckFunc { } } -func testAccResponseHeadersPolicyCorsConfigConfig(rName string) string { +func testAccResponseHeadersPolicyConfig_cors(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_response_headers_policy" "test" { name = %[1]q @@ -306,7 +376,7 @@ resource "aws_cloudfront_response_headers_policy" "test" { `, rName) } -func testAccResponseHeadersPolicyCorsConfigUpdatedConfig(rName string) string { +func testAccResponseHeadersPolicyConfig_corsUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_response_headers_policy" "test" { name = %[1]q @@ -339,7 +409,7 @@ resource "aws_cloudfront_response_headers_policy" "test" { `, rName) } -func testAccResponseHeadersPolicyCustomHeadersConfigConfig(rName string) string { +func testAccResponseHeadersPolicyConfig_custom(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_response_headers_policy" "test" { name = %[1]q @@ -361,7 +431,7 @@ resource "aws_cloudfront_response_headers_policy" "test" { `, rName) } -func testAccResponseHeadersPolicySecurityHeadersConfigConfig(rName string) string { +func testAccResponseHeadersPolicyConfig_security(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_response_headers_policy" "test" { name = %[1]q @@ -395,7 +465,7 @@ resource "aws_cloudfront_response_headers_policy" "test" { `, rName) } -func testAccResponseHeadersPolicySecurityHeadersConfigUpdatedConfig(rName string) string { +func testAccResponseHeadersPolicyConfig_securityUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudfront_response_headers_policy" "test" { name = %[1]q @@ -419,3 +489,16 @@ resource "aws_cloudfront_response_headers_policy" "test" { } `, rName) } + +func testAccResponseHeadersPolicyConfig_serverTiming(rName string, enabled bool, rate float64) string { + return fmt.Sprintf(` +resource "aws_cloudfront_response_headers_policy" "test" { + name = %[1]q + + server_timing_headers_config { + enabled = %[2]t + sampling_rate = %[3]f + } +} +`, rName, enabled, rate) +} diff --git a/internal/service/cloudfront/sweep.go b/internal/service/cloudfront/sweep.go index f82c76ccbaa..911b061bd0f 100644 --- a/internal/service/cloudfront/sweep.go +++ b/internal/service/cloudfront/sweep.go @@ -282,13 +282,23 @@ func sweepKeyGroup(region string) error { } for _, item := range output.KeyGroupList.Items { - strId := aws.StringValue(item.KeyGroup.Id) - log.Printf("[INFO] CloudFront key group %s", strId) - _, err := conn.DeleteKeyGroup(&cloudfront.DeleteKeyGroupInput{ - Id: item.KeyGroup.Id, + id := item.KeyGroup.Id + out, err := conn.GetKeyGroup(&cloudfront.GetKeyGroupInput{ + Id: id, }) if err != nil { - sweeperErr := fmt.Errorf("error deleting CloudFront key group %s: %w", strId, err) + sweeperErr := fmt.Errorf("error reading CloudFront key group %s: %w", aws.StringValue(id), err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + + _, err = conn.DeleteKeyGroup(&cloudfront.DeleteKeyGroupInput{ + Id: id, + IfMatch: out.ETag, + }) + if err != nil { + sweeperErr := fmt.Errorf("error sweeping CloudFront key group %s: %w", aws.StringValue(id), err) log.Printf("[ERROR] %s", sweeperErr) sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) continue diff --git a/internal/service/cloudhsmv2/cluster_data_source_test.go b/internal/service/cloudhsmv2/cluster_data_source_test.go index 92af939cba0..f1efa887593 100644 --- a/internal/service/cloudhsmv2/cluster_data_source_test.go +++ b/internal/service/cloudhsmv2/cluster_data_source_test.go @@ -20,7 +20,7 @@ func testAccDataSourceCluster_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckCloudHsmV2ClusterDataSourceConfig, + Config: testAccClusterDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "cluster_state", "UNINITIALIZED"), resource.TestCheckResourceAttrPair(dataSourceName, "cluster_id", resourceName, "cluster_id"), @@ -34,7 +34,7 @@ func testAccDataSourceCluster_basic(t *testing.T) { }) } -var testAccCheckCloudHsmV2ClusterDataSourceConfig = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` +var testAccClusterDataSourceConfig_basic = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` variable "subnets" { default = ["10.0.1.0/24", "10.0.2.0/24"] type = list(string) diff --git a/internal/service/cloudhsmv2/cluster_test.go b/internal/service/cloudhsmv2/cluster_test.go index 9235d014ed5..df79ba23949 100644 --- a/internal/service/cloudhsmv2/cluster_test.go +++ b/internal/service/cloudhsmv2/cluster_test.go @@ -24,7 +24,7 @@ func testAccCluster_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(), + Config: testAccClusterConfig_basic(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestMatchResourceAttr(resourceName, "cluster_id", regexp.MustCompile(`^cluster-.+`)), @@ -59,7 +59,7 @@ func testAccCluster_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(), + Config: testAccClusterConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudhsmv2.ResourceCluster(), resourceName), @@ -82,7 +82,7 @@ func testAccCluster_Tags(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterTags2Config("key1", "value1", "key2", "value2"), + Config: testAccClusterConfig_tags2("key1", "value1", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -97,7 +97,7 @@ func testAccCluster_Tags(t *testing.T) { ImportStateVerifyIgnore: []string{"cluster_certificates"}, }, { - Config: testAccClusterTags1Config("key1", "value1updated"), + Config: testAccClusterConfig_tags1("key1", "value1updated"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -105,7 +105,7 @@ func testAccCluster_Tags(t *testing.T) { ), }, { - Config: testAccClusterTags2Config("key1", "value1updated", "key3", "value3"), + Config: testAccClusterConfig_tags2("key1", "value1updated", "key3", "value3"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -142,7 +142,7 @@ resource "aws_subnet" "test" { ` } -func testAccClusterConfig() string { +func testAccClusterConfig_basic() string { return acctest.ConfigCompose(testAccClusterBaseConfig(), ` resource "aws_cloudhsm_v2_cluster" "test" { hsm_type = "hsm1.medium" @@ -151,7 +151,7 @@ resource "aws_cloudhsm_v2_cluster" "test" { `) } -func testAccClusterTags1Config(tagKey1, tagValue1 string) string { +func testAccClusterConfig_tags1(tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_cloudhsm_v2_cluster" "test" { hsm_type = "hsm1.medium" @@ -164,7 +164,7 @@ resource "aws_cloudhsm_v2_cluster" "test" { `, tagKey1, tagValue1)) } -func testAccClusterTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccClusterConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_cloudhsm_v2_cluster" "test" { hsm_type = "hsm1.medium" diff --git a/internal/service/cloudhsmv2/hsm_test.go b/internal/service/cloudhsmv2/hsm_test.go index 7bf3a173288..dda14ace210 100644 --- a/internal/service/cloudhsmv2/hsm_test.go +++ b/internal/service/cloudhsmv2/hsm_test.go @@ -24,7 +24,7 @@ func testAccHSM_basic(t *testing.T) { CheckDestroy: testAccCheckHSMDestroy, Steps: []resource.TestStep{ { - Config: testAccHSMSubnetIDConfig(), + Config: testAccHSMConfig_subnetID(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckHSMExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "availability_zone", "aws_subnet.test.0", "availability_zone"), @@ -55,7 +55,7 @@ func testAccHSM_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccHSMSubnetIDConfig(), + Config: testAccHSMConfig_subnetID(), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudhsmv2.ResourceHSM(), resourceName), @@ -79,7 +79,7 @@ func testAccHSM_disappears_Cluster(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccHSMSubnetIDConfig(), + Config: testAccHSMConfig_subnetID(), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudhsmv2.ResourceHSM(), resourceName), @@ -101,7 +101,7 @@ func testAccHSM_AvailabilityZone(t *testing.T) { CheckDestroy: testAccCheckHSMDestroy, Steps: []resource.TestStep{ { - Config: testAccHSMAvailabilityZoneConfig(), + Config: testAccHSMConfig_availabilityZone(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckHSMExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "availability_zone", "aws_subnet.test.0", "availability_zone"), @@ -126,7 +126,7 @@ func testAccHSM_IPAddress(t *testing.T) { CheckDestroy: testAccCheckHSMDestroy, Steps: []resource.TestStep{ { - Config: testAccHSMIPAddressConfig(), + Config: testAccHSMConfig_ipAddress(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckHSMExists(resourceName), resource.TestCheckResourceAttr(resourceName, "ip_address", "10.0.0.5"), @@ -171,7 +171,7 @@ resource "aws_cloudhsm_v2_cluster" "test" { ` } -func testAccHSMAvailabilityZoneConfig() string { +func testAccHSMConfig_availabilityZone() string { return acctest.ConfigCompose( testAccHSMBaseConfig(), ` @@ -182,7 +182,7 @@ resource "aws_cloudhsm_v2_hsm" "test" { `) } -func testAccHSMIPAddressConfig() string { +func testAccHSMConfig_ipAddress() string { return acctest.ConfigCompose( testAccHSMBaseConfig(), ` @@ -194,7 +194,7 @@ resource "aws_cloudhsm_v2_hsm" "test" { `) } -func testAccHSMSubnetIDConfig() string { +func testAccHSMConfig_subnetID() string { return acctest.ConfigCompose( testAccHSMBaseConfig(), ` diff --git a/internal/service/cloudhsmv2/sweep.go b/internal/service/cloudhsmv2/sweep.go index c2a8a95e8fc..2b7f2935e49 100644 --- a/internal/service/cloudhsmv2/sweep.go +++ b/internal/service/cloudhsmv2/sweep.go @@ -17,17 +17,17 @@ import ( func init() { resource.AddTestSweepers("aws_cloudhsm_v2_cluster", &resource.Sweeper{ Name: "aws_cloudhsm_v2_cluster", - F: sweepCloudhsmv2Clusters, + F: sweepClusters, Dependencies: []string{"aws_cloudhsm_v2_hsm"}, }) resource.AddTestSweepers("aws_cloudhsm_v2_hsm", &resource.Sweeper{ Name: "aws_cloudhsm_v2_hsm", - F: sweepCloudhsmv2HSMs, + F: sweepHSMs, }) } -func sweepCloudhsmv2Clusters(region string) error { +func sweepClusters(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { return fmt.Errorf("error getting client: %s", err) @@ -73,7 +73,7 @@ func sweepCloudhsmv2Clusters(region string) error { return nil } -func sweepCloudhsmv2HSMs(region string) error { +func sweepHSMs(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { return fmt.Errorf("error getting client: %s", err) diff --git a/internal/service/cloudsearch/domain.go b/internal/service/cloudsearch/domain.go index 154a36e05a3..7fa5e4b88a6 100644 --- a/internal/service/cloudsearch/domain.go +++ b/internal/service/cloudsearch/domain.go @@ -111,6 +111,11 @@ func ResourceDomain() *schema.Resource { Optional: true, Default: false, }, + "source_fields": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringDoesNotMatch(regexp.MustCompile(`score`), "Cannot be set to reserved field score"), + }, "type": { Type: schema.TypeString, Required: true, @@ -230,6 +235,7 @@ func resourceDomainCreate(d *schema.ResourceData, meta interface{}) error { return err } + log.Printf("[DEBUG] Indexing CloudSearch Domain documents: %s", d.Id()) _, err = conn.IndexDocuments(&cloudsearch.IndexDocumentsInput{ DomainName: aws.String(d.Id()), }) @@ -411,10 +417,13 @@ func resourceDomainUpdate(d *schema.ResourceData, meta interface{}) error { continue } - _, err := conn.DeleteIndexField(&cloudsearch.DeleteIndexFieldInput{ + input := &cloudsearch.DeleteIndexFieldInput{ DomainName: aws.String(d.Id()), IndexFieldName: aws.String(fieldName), - }) + } + + log.Printf("[DEBUG] Deleting CloudSearch Domain index field: %s", input) + _, err := conn.DeleteIndexField(input) if err != nil { return fmt.Errorf("error deleting CloudSearch Domain (%s) index field (%s): %w", d.Id(), fieldName, err) @@ -433,6 +442,7 @@ func resourceDomainUpdate(d *schema.ResourceData, meta interface{}) error { } if requiresIndexDocuments { + log.Printf("[DEBUG] Indexing CloudSearch Domain documents: %s", d.Id()) _, err := conn.IndexDocuments(&cloudsearch.IndexDocumentsInput{ DomainName: aws.String(d.Id()), }) @@ -455,7 +465,6 @@ func resourceDomainDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).CloudSearchConn log.Printf("[DEBUG] Deleting CloudSearch Domain: %s", d.Id()) - _, err := conn.DeleteDomain(&cloudsearch.DeleteDomainInput{ DomainName: aws.String(d.Id()), }) @@ -489,30 +498,44 @@ func validateIndexName(v interface{}, k string) (ws []string, es []error) { } func defineIndexFields(conn *cloudsearch.CloudSearch, domainName string, tfList []interface{}) error { - for _, tfMapRaw := range tfList { - tfMap, ok := tfMapRaw.(map[string]interface{}) + // Define index fields with source fields after those without. + for _, defineWhenSourceFieldsConfigured := range []bool{false, true} { + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]interface{}) - if !ok { - continue - } + if !ok { + continue + } - apiObject, err := expandIndexField(tfMap) + apiObject, sourceFieldsConfigured, err := expandIndexField(tfMap) - if err != nil { - return err - } + if err != nil { + return err + } - if apiObject == nil { - continue - } + if apiObject == nil { + continue + } - _, err = conn.DefineIndexField(&cloudsearch.DefineIndexFieldInput{ - DomainName: aws.String(domainName), - IndexField: apiObject, - }) + if sourceFieldsConfigured && !defineWhenSourceFieldsConfigured { + continue + } - if err != nil { - return fmt.Errorf("error defining CloudSearch Domain (%s) index field (%s): %w", domainName, aws.StringValue(apiObject.IndexFieldName), err) + if !sourceFieldsConfigured && defineWhenSourceFieldsConfigured { + continue + } + + input := &cloudsearch.DefineIndexFieldInput{ + DomainName: aws.String(domainName), + IndexField: apiObject, + } + + log.Printf("[DEBUG] Defining CloudSearch Domain index field: %s", input) + _, err = conn.DefineIndexField(input) + + if err != nil { + return fmt.Errorf("error defining CloudSearch Domain (%s) index field (%s): %w", domainName, aws.StringValue(apiObject.IndexFieldName), err) + } } } @@ -746,9 +769,9 @@ func flattenDomainEndpointOptions(apiObject *cloudsearch.DomainEndpointOptions) return tfMap } -func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, error) { +func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, bool, error) { if tfMap == nil { - return nil, nil + return nil, false, nil } apiObject := &cloudsearch.IndexField{} @@ -768,6 +791,7 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er returnEnabled, _ := tfMap["return"].(bool) searchEnabled, _ := tfMap["search"].(bool) sortEnabled, _ := tfMap["sort"].(bool) + var sourceFieldsConfigured bool switch fieldType { case cloudsearch.IndexFieldTypeDate: @@ -782,6 +806,11 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er options.DefaultValue = aws.String(v) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceField = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.DateOptions = options case cloudsearch.IndexFieldTypeDateArray: @@ -795,6 +824,11 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er options.DefaultValue = aws.String(v) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceFields = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.DateArrayOptions = options case cloudsearch.IndexFieldTypeDouble: @@ -809,12 +843,17 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er v, err := strconv.ParseFloat(v, 64) if err != nil { - return nil, err + return nil, false, err } options.DefaultValue = aws.Float64(v) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceField = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.DoubleOptions = options case cloudsearch.IndexFieldTypeDoubleArray: @@ -828,12 +867,17 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er v, err := strconv.ParseFloat(v, 64) if err != nil { - return nil, err + return nil, false, err } options.DefaultValue = aws.Float64(v) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceFields = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.DoubleArrayOptions = options case cloudsearch.IndexFieldTypeInt: @@ -848,12 +892,17 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er v, err := strconv.Atoi(v) if err != nil { - return nil, err + return nil, false, err } options.DefaultValue = aws.Int64(int64(v)) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceField = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.IntOptions = options case cloudsearch.IndexFieldTypeIntArray: @@ -867,12 +916,17 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er v, err := strconv.Atoi(v) if err != nil { - return nil, err + return nil, false, err } options.DefaultValue = aws.Int64(int64(v)) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceFields = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.IntArrayOptions = options case cloudsearch.IndexFieldTypeLatlon: @@ -887,6 +941,11 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er options.DefaultValue = aws.String(v) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceField = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.LatLonOptions = options case cloudsearch.IndexFieldTypeLiteral: @@ -901,6 +960,11 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er options.DefaultValue = aws.String(v) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceField = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.LiteralOptions = options case cloudsearch.IndexFieldTypeLiteralArray: @@ -914,6 +978,11 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er options.DefaultValue = aws.String(v) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceFields = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.LiteralArrayOptions = options case cloudsearch.IndexFieldTypeText: @@ -931,6 +1000,11 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er options.DefaultValue = aws.String(v) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceField = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.TextOptions = options case cloudsearch.IndexFieldTypeTextArray: @@ -947,13 +1021,18 @@ func expandIndexField(tfMap map[string]interface{}) (*cloudsearch.IndexField, er options.DefaultValue = aws.String(v) } + if v, ok := tfMap["source_fields"].(string); ok && v != "" { + options.SourceFields = aws.String(v) + sourceFieldsConfigured = true + } + apiObject.TextArrayOptions = options default: - return nil, fmt.Errorf("unsupported index_field type: %s", fieldType) + return nil, false, fmt.Errorf("unsupported index_field type: %s", fieldType) } - return apiObject, nil + return apiObject, sourceFieldsConfigured, nil } func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[string]interface{}, error) { @@ -1002,6 +1081,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["sort"] = aws.BoolValue(v) } + if v := options.SourceField; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["analysis_scheme"] = "" tfMap["highlight"] = false @@ -1025,6 +1108,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["search"] = aws.BoolValue(v) } + if v := options.SourceFields; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["analysis_scheme"] = "" tfMap["highlight"] = false @@ -1053,6 +1140,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["sort"] = aws.BoolValue(v) } + if v := options.SourceField; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["analysis_scheme"] = "" tfMap["highlight"] = false @@ -1076,6 +1167,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["search"] = aws.BoolValue(v) } + if v := options.SourceFields; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["analysis_scheme"] = "" tfMap["highlight"] = false @@ -1104,6 +1199,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["sort"] = aws.BoolValue(v) } + if v := options.SourceField; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["analysis_scheme"] = "" tfMap["highlight"] = false @@ -1127,6 +1226,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["search"] = aws.BoolValue(v) } + if v := options.SourceFields; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["analysis_scheme"] = "" tfMap["highlight"] = false @@ -1155,6 +1258,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["sort"] = aws.BoolValue(v) } + if v := options.SourceField; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["analysis_scheme"] = "" tfMap["highlight"] = false @@ -1182,6 +1289,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["sort"] = aws.BoolValue(v) } + if v := options.SourceField; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["analysis_scheme"] = "" tfMap["highlight"] = false @@ -1205,6 +1316,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["search"] = aws.BoolValue(v) } + if v := options.SourceFields; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["analysis_scheme"] = "" tfMap["highlight"] = false @@ -1233,6 +1348,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["sort"] = aws.BoolValue(v) } + if v := options.SourceField; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["facet"] = false tfMap["search"] = true @@ -1256,6 +1375,10 @@ func flattenIndexFieldStatus(apiObject *cloudsearch.IndexFieldStatus) (map[strin tfMap["return"] = aws.BoolValue(v) } + if v := options.SourceFields; v != nil { + tfMap["source_fields"] = aws.StringValue(v) + } + // Defaults not returned via the API. tfMap["facet"] = false tfMap["search"] = true diff --git a/internal/service/cloudsearch/domain_service_access_policy_test.go b/internal/service/cloudsearch/domain_service_access_policy_test.go index b1b409d8fa5..b2dc72de03d 100644 --- a/internal/service/cloudsearch/domain_service_access_policy_test.go +++ b/internal/service/cloudsearch/domain_service_access_policy_test.go @@ -25,7 +25,7 @@ func TestAccCloudSearchDomainServiceAccessPolicy_basic(t *testing.T) { CheckDestroy: testAccDomainServiceAccessPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainServiceAccessPolicyConfig(rName), + Config: testAccDomainServiceAccessPolicyConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccDomainServiceAccessPolicyExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "access_policy"), @@ -51,7 +51,7 @@ func TestAccCloudSearchDomainServiceAccessPolicy_update(t *testing.T) { CheckDestroy: testAccDomainServiceAccessPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainServiceAccessPolicyConfig(rName), + Config: testAccDomainServiceAccessPolicyConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccDomainServiceAccessPolicyExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "access_policy"), @@ -63,7 +63,7 @@ func TestAccCloudSearchDomainServiceAccessPolicy_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainServiceAccessPolicyConfigUpdated(rName), + Config: testAccDomainServiceAccessPolicyConfig_updated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccDomainServiceAccessPolicyExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "access_policy"), @@ -120,7 +120,7 @@ func testAccDomainServiceAccessPolicyDestroy(s *terraform.State) error { return nil } -func testAccDomainServiceAccessPolicyConfig(rName string) string { +func testAccDomainServiceAccessPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudsearch_domain" "test" { name = %[1]q @@ -148,7 +148,7 @@ POLICY `, rName) } -func testAccDomainServiceAccessPolicyConfigUpdated(rName string) string { +func testAccDomainServiceAccessPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_cloudsearch_domain" "test" { name = %[1]q diff --git a/internal/service/cloudsearch/domain_test.go b/internal/service/cloudsearch/domain_test.go index 5a25c96e3fc..b945210c6d4 100644 --- a/internal/service/cloudsearch/domain_test.go +++ b/internal/service/cloudsearch/domain_test.go @@ -17,7 +17,7 @@ import ( func TestAccCloudSearchDomain_basic(t *testing.T) { var v cloudsearch.DomainStatus resourceName := "aws_cloudsearch_domain.test" - rName := acctest.ResourcePrefix + "-" + sdkacctest.RandString(28-(len(acctest.ResourcePrefix)+1)) + rName := testAccDomainName() resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudsearch.EndpointsID, t) }, @@ -26,7 +26,7 @@ func TestAccCloudSearchDomain_basic(t *testing.T) { CheckDestroy: testAccDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccDomainExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "cloudsearch", fmt.Sprintf("domain/%s", rName)), @@ -55,7 +55,7 @@ func TestAccCloudSearchDomain_basic(t *testing.T) { func TestAccCloudSearchDomain_disappears(t *testing.T) { var v cloudsearch.DomainStatus resourceName := "aws_cloudsearch_domain.test" - rName := acctest.ResourcePrefix + "-" + sdkacctest.RandString(28-(len(acctest.ResourcePrefix)+1)) + rName := testAccDomainName() resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudsearch.EndpointsID, t) }, @@ -64,7 +64,7 @@ func TestAccCloudSearchDomain_disappears(t *testing.T) { CheckDestroy: testAccDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccDomainExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfcloudsearch.ResourceDomain(), resourceName), @@ -78,7 +78,7 @@ func TestAccCloudSearchDomain_disappears(t *testing.T) { func TestAccCloudSearchDomain_indexFields(t *testing.T) { var v cloudsearch.DomainStatus resourceName := "aws_cloudsearch_domain.test" - rName := acctest.ResourcePrefix + "-" + sdkacctest.RandString(28-(len(acctest.ResourcePrefix)+1)) + rName := testAccDomainName() resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudsearch.EndpointsID, t) }, @@ -87,7 +87,7 @@ func TestAccCloudSearchDomain_indexFields(t *testing.T) { CheckDestroy: testAccDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainIndexFieldsConfig(rName), + Config: testAccDomainConfig_indexFields(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccDomainExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "index_field.#", "2"), @@ -110,7 +110,7 @@ func TestAccCloudSearchDomain_indexFields(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainIndexFieldsUpdatedConfig(rName), + Config: testAccDomainConfig_indexFieldsUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccDomainExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "index_field.#", "3"), @@ -139,10 +139,84 @@ func TestAccCloudSearchDomain_indexFields(t *testing.T) { }) } +func TestAccCloudSearchDomain_sourceFields(t *testing.T) { + var v cloudsearch.DomainStatus + resourceName := "aws_cloudsearch_domain.test" + rName := testAccDomainName() + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudsearch.EndpointsID, t) }, + ErrorCheck: acctest.ErrorCheck(t, cloudsearch.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccDomainDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDomainConfig_sourceFields(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccDomainExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "index_field.#", "3"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "index_field.*", map[string]string{ + "name": "int_test", + "type": "int", + "default_value": "2", + "source_fields": "", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "index_field.*", map[string]string{ + "name": "int_test_2", + "type": "int", + "default_value": "4", + "source_fields": "", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "index_field.*", map[string]string{ + "name": "int_test_source", + "type": "int-array", + "source_fields": "int_test,int_test_2", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccDomainConfig_sourceFieldsUpdated(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccDomainExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "index_field.#", "4"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "index_field.*", map[string]string{ + "name": "int_test", + "type": "int", + "default_value": "2", + "source_fields": "", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "index_field.*", map[string]string{ + "name": "int_test_2", + "type": "int", + "default_value": "4", + "source_fields": "", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "index_field.*", map[string]string{ + "name": "int_test_3", + "type": "int", + "default_value": "8", + "source_fields": "", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "index_field.*", map[string]string{ + "name": "int_test_source", + "type": "int-array", + "source_fields": "int_test_3", + }), + ), + }, + }, + }) +} + func TestAccCloudSearchDomain_update(t *testing.T) { var v cloudsearch.DomainStatus resourceName := "aws_cloudsearch_domain.test" - rName := acctest.ResourcePrefix + "-" + sdkacctest.RandString(28-(len(acctest.ResourcePrefix)+1)) + rName := testAccDomainName() resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(cloudsearch.EndpointsID, t) }, @@ -151,7 +225,7 @@ func TestAccCloudSearchDomain_update(t *testing.T) { CheckDestroy: testAccDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainAllOptionsConfig(rName), + Config: testAccDomainConfig_allOptions(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccDomainExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "cloudsearch", fmt.Sprintf("domain/%s", rName)), @@ -178,7 +252,7 @@ func TestAccCloudSearchDomain_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainAllOptionsUpdatedConfig(rName), + Config: testAccDomainConfig_allOptionsUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccDomainExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "cloudsearch", fmt.Sprintf("domain/%s", rName)), @@ -205,6 +279,10 @@ func TestAccCloudSearchDomain_update(t *testing.T) { }) } +func testAccDomainName() string { + return acctest.ResourcePrefix + "-" + sdkacctest.RandString(28-(len(acctest.ResourcePrefix)+1)) +} + func testAccDomainExists(n string, v *cloudsearch.DomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -254,7 +332,7 @@ func testAccDomainDestroy(s *terraform.State) error { return nil } -func testAccDomainConfig(rName string) string { +func testAccDomainConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudsearch_domain" "test" { name = %[1]q @@ -262,7 +340,7 @@ resource "aws_cloudsearch_domain" "test" { `, rName) } -func testAccDomainIndexFieldsConfig(rName string) string { +func testAccDomainConfig_indexFields(rName string) string { return fmt.Sprintf(` resource "aws_cloudsearch_domain" "test" { name = %[1]q @@ -285,7 +363,7 @@ resource "aws_cloudsearch_domain" "test" { `, rName) } -func testAccDomainIndexFieldsUpdatedConfig(rName string) string { +func testAccDomainConfig_indexFieldsUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudsearch_domain" "test" { name = %[1]q @@ -320,7 +398,7 @@ resource "aws_cloudsearch_domain" "test" { `, rName) } -func testAccDomainAllOptionsConfig(rName string) string { +func testAccDomainConfig_allOptions(rName string) string { return fmt.Sprintf(` resource "aws_cloudsearch_domain" "test" { name = %[1]q @@ -346,7 +424,67 @@ resource "aws_cloudsearch_domain" "test" { `, rName) } -func testAccDomainAllOptionsUpdatedConfig(rName string) string { +func testAccDomainConfig_sourceFields(rName string) string { + return fmt.Sprintf(` +resource "aws_cloudsearch_domain" "test" { + name = %[1]q + + index_field { + name = "int_test" + type = "int" + default_value = "2" + } + + index_field { + name = "int_test_2" + type = "int" + default_value = "4" + } + + index_field { + name = "int_test_source" + type = "int-array" + + source_fields = "int_test,int_test_2" + } +} +`, rName) +} + +func testAccDomainConfig_sourceFieldsUpdated(rName string) string { + return fmt.Sprintf(` +resource "aws_cloudsearch_domain" "test" { + name = %[1]q + + index_field { + name = "int_test" + type = "int" + default_value = "2" + } + + index_field { + name = "int_test_2" + type = "int" + default_value = "4" + } + + index_field { + name = "int_test_3" + type = "int" + default_value = "8" + } + + index_field { + name = "int_test_source" + type = "int-array" + + source_fields = "int_test_3" + } +} +`, rName) +} + +func testAccDomainConfig_allOptionsUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudsearch_domain" "test" { name = %[1]q diff --git a/internal/service/cloudtrail/cloudtrail.go b/internal/service/cloudtrail/cloudtrail.go index afb4d897cf8..c9b5b7947eb 100644 --- a/internal/service/cloudtrail/cloudtrail.go +++ b/internal/service/cloudtrail/cloudtrail.go @@ -19,7 +19,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -func ResourceCloudTrail() *schema.Resource { +func ResourceCloudTrail() *schema.Resource { // nosemgrep:cloudtrail-in-func-name return &schema.Resource{ Create: resourceCloudTrailCreate, Read: resourceCloudTrailRead, @@ -246,7 +246,7 @@ func ResourceCloudTrail() *schema.Resource { } } -func resourceCloudTrailCreate(d *schema.ResourceData, meta interface{}) error { +func resourceCloudTrailCreate(d *schema.ResourceData, meta interface{}) error { // nosemgrep:cloudtrail-in-func-name conn := meta.(*conns.AWSClient).CloudTrailConn defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) @@ -316,7 +316,7 @@ func resourceCloudTrailCreate(d *schema.ResourceData, meta interface{}) error { // AWS CloudTrail sets newly-created trails to false. if v, ok := d.GetOk("enable_logging"); ok && v.(bool) { - err := cloudTrailSetLogging(conn, v.(bool), d.Id()) + err := setLogging(conn, v.(bool), d.Id()) if err != nil { return err } @@ -324,19 +324,19 @@ func resourceCloudTrailCreate(d *schema.ResourceData, meta interface{}) error { // Event Selectors if _, ok := d.GetOk("event_selector"); ok { - if err := cloudTrailSetEventSelectors(conn, d); err != nil { + if err := setEventSelectors(conn, d); err != nil { return err } } if _, ok := d.GetOk("advanced_event_selector"); ok { - if err := cloudTrailSetAdvancedEventSelectors(conn, d); err != nil { + if err := setAdvancedEventSelectors(conn, d); err != nil { return err } } if _, ok := d.GetOk("insight_selector"); ok { - if err := cloudTrailSetInsightSelectors(conn, d); err != nil { + if err := setInsightSelectors(conn, d); err != nil { return err } } @@ -344,7 +344,7 @@ func resourceCloudTrailCreate(d *schema.ResourceData, meta interface{}) error { return resourceCloudTrailRead(d, meta) } -func resourceCloudTrailRead(d *schema.ResourceData, meta interface{}) error { +func resourceCloudTrailRead(d *schema.ResourceData, meta interface{}) error { // nosemgrep:cloudtrail-in-func-name conn := meta.(*conns.AWSClient).CloudTrailConn defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig @@ -369,13 +369,13 @@ func resourceCloudTrailRead(d *schema.ResourceData, meta interface{}) error { } if !d.IsNewResource() && trail == nil { - names.LogNotFoundRemoveState(names.CloudTrail, names.ErrActionReading, ResCloudTrail, d.Id()) + names.LogNotFoundRemoveState(names.CloudTrail, names.ErrActionReading, resTrail, d.Id()) d.SetId("") return nil } if d.IsNewResource() && trail == nil { - return names.Error(names.CloudTrail, names.ErrActionReading, ResCloudTrail, d.Id(), errors.New("not found after creation")) + return names.Error(names.CloudTrail, names.ErrActionReading, resTrail, d.Id(), errors.New("not found after creation")) } log.Printf("[DEBUG] CloudTrail received: %s", trail) @@ -417,7 +417,7 @@ func resourceCloudTrailRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting tags_all: %w", err) } - logstatus, err := cloudTrailGetLoggingStatus(conn, trail.Name) + logstatus, err := getLoggingStatus(conn, trail.Name) if err != nil { return err } @@ -461,7 +461,7 @@ func resourceCloudTrailRead(d *schema.ResourceData, meta interface{}) error { return nil } -func resourceCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error { +func resourceCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error { // nosemgrep:cloudtrail-in-func-name conn := meta.(*conns.AWSClient).CloudTrailConn if d.HasChangesExcept("tags", "tags_all", "insight_selector", "advanced_event_selector", "event_selector", "enable_logging") { @@ -533,7 +533,7 @@ func resourceCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("enable_logging") { log.Printf("[DEBUG] Updating logging on CloudTrail: %s", d.Id()) - err := cloudTrailSetLogging(conn, d.Get("enable_logging").(bool), d.Id()) + err := setLogging(conn, d.Get("enable_logging").(bool), d.Id()) if err != nil { return err } @@ -541,21 +541,21 @@ func resourceCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error { if !d.IsNewResource() && d.HasChange("event_selector") { log.Printf("[DEBUG] Updating event selector on CloudTrail: %s", d.Id()) - if err := cloudTrailSetEventSelectors(conn, d); err != nil { + if err := setEventSelectors(conn, d); err != nil { return err } } if !d.IsNewResource() && d.HasChange("advanced_event_selector") { log.Printf("[DEBUG] Updating advanced event selector on CloudTrail: %s", d.Id()) - if err := cloudTrailSetAdvancedEventSelectors(conn, d); err != nil { + if err := setAdvancedEventSelectors(conn, d); err != nil { return err } } if !d.IsNewResource() && d.HasChange("insight_selector") { log.Printf("[DEBUG] Updating insight selector on CloudTrail: %s", d.Id()) - if err := cloudTrailSetInsightSelectors(conn, d); err != nil { + if err := setInsightSelectors(conn, d); err != nil { return err } } @@ -563,7 +563,7 @@ func resourceCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error { return resourceCloudTrailRead(d, meta) } -func resourceCloudTrailDelete(d *schema.ResourceData, meta interface{}) error { +func resourceCloudTrailDelete(d *schema.ResourceData, meta interface{}) error { // nosemgrep:cloudtrail-in-func-name conn := meta.(*conns.AWSClient).CloudTrailConn log.Printf("[DEBUG] Deleting CloudTrail: %q", d.Id()) @@ -582,7 +582,7 @@ func resourceCloudTrailDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func cloudTrailGetLoggingStatus(conn *cloudtrail.CloudTrail, id *string) (bool, error) { +func getLoggingStatus(conn *cloudtrail.CloudTrail, id *string) (bool, error) { GetTrailStatusOpts := &cloudtrail.GetTrailStatusInput{ Name: id, } @@ -594,7 +594,7 @@ func cloudTrailGetLoggingStatus(conn *cloudtrail.CloudTrail, id *string) (bool, return aws.BoolValue(resp.IsLogging), err } -func cloudTrailSetLogging(conn *cloudtrail.CloudTrail, enabled bool, id string) error { +func setLogging(conn *cloudtrail.CloudTrail, enabled bool, id string) error { if enabled { log.Printf("[DEBUG] Starting logging on CloudTrail (%s)", id) StartLoggingOpts := &cloudtrail.StartLoggingInput{ @@ -616,7 +616,7 @@ func cloudTrailSetLogging(conn *cloudtrail.CloudTrail, enabled bool, id string) return nil } -func cloudTrailSetEventSelectors(conn *cloudtrail.CloudTrail, d *schema.ResourceData) error { +func setEventSelectors(conn *cloudtrail.CloudTrail, d *schema.ResourceData) error { input := &cloudtrail.PutEventSelectorsInput{ TrailName: aws.String(d.Id()), } @@ -720,7 +720,7 @@ func flattenEventSelectorDataResource(configured []*cloudtrail.DataResource) []m return dataResources } -func cloudTrailSetAdvancedEventSelectors(conn *cloudtrail.CloudTrail, d *schema.ResourceData) error { +func setAdvancedEventSelectors(conn *cloudtrail.CloudTrail, d *schema.ResourceData) error { input := &cloudtrail.PutEventSelectorsInput{ TrailName: aws.String(d.Id()), } @@ -843,7 +843,7 @@ func flattenAdvancedEventSelectorFieldSelector(configured []*cloudtrail.Advanced return fieldSelectors } -func cloudTrailSetInsightSelectors(conn *cloudtrail.CloudTrail, d *schema.ResourceData) error { +func setInsightSelectors(conn *cloudtrail.CloudTrail, d *schema.ResourceData) error { input := &cloudtrail.PutInsightSelectorsInput{ TrailName: aws.String(d.Id()), } diff --git a/internal/service/cloudtrail/cloudtrail_test.go b/internal/service/cloudtrail/cloudtrail_test.go index 34be270fdd3..649f27bfdd8 100644 --- a/internal/service/cloudtrail/cloudtrail_test.go +++ b/internal/service/cloudtrail/cloudtrail_test.go @@ -62,13 +62,13 @@ func testAcc_basic(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig(rName), + Config: testAccCloudTrailConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "cloudtrail", fmt.Sprintf("trail/%s", rName)), resource.TestCheckResourceAttr(resourceName, "include_global_service_events", "true"), resource.TestCheckResourceAttr(resourceName, "is_organization_trail", "false"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -78,12 +78,12 @@ func testAcc_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccModifiedConfig(rName), + Config: testAccCloudTrailConfig_modified(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "s3_key_prefix", "prefix"), resource.TestCheckResourceAttr(resourceName, "include_global_service_events", "false"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -108,9 +108,9 @@ func testAcc_cloudWatch(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccCloudWatchConfig(rName), + Config: testAccCloudTrailConfig_cloudWatch(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttrSet(resourceName, "cloud_watch_logs_group_arn"), resource.TestCheckResourceAttrSet(resourceName, "cloud_watch_logs_role_arn"), ), @@ -121,9 +121,9 @@ func testAcc_cloudWatch(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCloudWatchModifiedConfig(rName), + Config: testAccCloudTrailConfig_cloudWatchModified(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttrSet(resourceName, "cloud_watch_logs_group_arn"), resource.TestCheckResourceAttrSet(resourceName, "cloud_watch_logs_role_arn"), ), @@ -149,13 +149,13 @@ func testAcc_enableLogging(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccEnableLoggingConfig(rName, true), + Config: testAccCloudTrailConfig_enableLogging(rName, true), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), // AWS will create the trail with logging turned off. // Test that "enable_logging" default works. - testAccCheckCloudTrailLoggingEnabled(resourceName, true), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLoggingEnabled(resourceName, true), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -165,11 +165,11 @@ func testAcc_enableLogging(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEnableLoggingConfig(rName, false), + Config: testAccCloudTrailConfig_enableLogging(rName, false), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), - testAccCheckCloudTrailLoggingEnabled(resourceName, false), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckExists(resourceName, &trail), + testAccCheckLoggingEnabled(resourceName, false), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -179,11 +179,11 @@ func testAcc_enableLogging(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfig(rName), + Config: testAccCloudTrailConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), - testAccCheckCloudTrailLoggingEnabled(resourceName, true), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckExists(resourceName, &trail), + testAccCheckLoggingEnabled(resourceName, true), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -203,20 +203,20 @@ func testAcc_multiRegion(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig(rName), + Config: testAccCloudTrailConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "is_multi_region_trail", "false"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, { - Config: testAccMultiRegionConfig(rName), + Config: testAccCloudTrailConfig_multiRegion(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "is_multi_region_trail", "true"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -226,11 +226,11 @@ func testAcc_multiRegion(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfig(rName), + Config: testAccCloudTrailConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "is_multi_region_trail", "false"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -250,11 +250,11 @@ func testAcc_organization(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConfig(rName), + Config: testAccCloudTrailConfig_organization(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "is_organization_trail", "true"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -264,11 +264,11 @@ func testAcc_organization(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfig(rName), + Config: testAccCloudTrailConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "is_organization_trail", "false"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -288,12 +288,12 @@ func testAcc_logValidation(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccLogValidationConfig(rName), + Config: testAccCloudTrailConfig_logValidation(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "s3_key_prefix", ""), resource.TestCheckResourceAttr(resourceName, "include_global_service_events", "true"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, true, &trail), + testAccCheckLogValidationEnabled(resourceName, true, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -303,12 +303,12 @@ func testAcc_logValidation(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLogValidationModifiedConfig(rName), + Config: testAccCloudTrailConfig_logValidationModified(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "s3_key_prefix", ""), resource.TestCheckResourceAttr(resourceName, "include_global_service_events", "true"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -330,12 +330,12 @@ func testAcc_kmsKey(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccKMSKeyConfig(rName), + Config: testAccCloudTrailConfig_kmsKey(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "s3_key_prefix", ""), resource.TestCheckResourceAttr(resourceName, "include_global_service_events", "true"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsResourceName, "arn"), ), }, @@ -362,14 +362,14 @@ func testAcc_tags(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccTagsConfig(rName), + Config: testAccCloudTrailConfig_tags(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - testAccCheckCloudTrailLoadTags(&trail, &trailTags), + testAccCheckLoadTags(&trail, &trailTags), resource.TestCheckResourceAttr(resourceName, "tags.Yak", "milk"), resource.TestCheckResourceAttr(resourceName, "tags.Fox", "tail"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -379,25 +379,25 @@ func testAcc_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTagsModifiedConfig(rName), + Config: testAccCloudTrailConfig_tagsModified(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), - testAccCheckCloudTrailLoadTags(&trail, &trailTagsModified), + testAccCheckLoadTags(&trail, &trailTagsModified), resource.TestCheckResourceAttr(resourceName, "tags.Yak", "milk"), resource.TestCheckResourceAttr(resourceName, "tags.Emu", "toes"), resource.TestCheckResourceAttr(resourceName, "tags.Fox", "tail"), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, { - Config: testAccTagsModifiedAgainConfig(rName), + Config: testAccCloudTrailConfig_tagsModifiedAgain(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - testAccCheckCloudTrailLoadTags(&trail, &trailTagsModified), - testAccCheckCloudTrailLogValidationEnabled(resourceName, false, &trail), + testAccCheckLoadTags(&trail, &trailTagsModified), + testAccCheckLogValidationEnabled(resourceName, false, &trail), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), ), }, @@ -417,9 +417,9 @@ func testAcc_globalServiceEvents(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalServiceEventsConfig(rName), + Config: testAccCloudTrailConfig_globalServiceEvents(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), resource.TestCheckResourceAttr(resourceName, "include_global_service_events", "false"), ), }, @@ -443,7 +443,7 @@ func testAcc_eventSelector(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSelectorConfig(rName), + Config: testAccCloudTrailConfig_eventSelector(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_selector.#", "1"), resource.TestCheckResourceAttr(resourceName, "event_selector.0.data_resource.#", "1"), @@ -462,7 +462,7 @@ func testAcc_eventSelector(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEventSelectorReadWriteTypeConfig(rName), + Config: testAccCloudTrailConfig_eventSelectorReadWriteType(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_selector.#", "1"), resource.TestCheckResourceAttr(resourceName, "event_selector.0.include_management_events", "true"), @@ -470,7 +470,7 @@ func testAcc_eventSelector(t *testing.T) { ), }, { - Config: testAccEventSelectorModifiedConfig(rName), + Config: testAccCloudTrailConfig_eventSelectorModified(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_selector.#", "2"), resource.TestCheckResourceAttr(resourceName, "event_selector.0.data_resource.#", "1"), @@ -494,7 +494,7 @@ func testAcc_eventSelector(t *testing.T) { ), }, { - Config: testAccEventSelectorNoneConfig(rName), + Config: testAccCloudTrailConfig_eventSelectorNone(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_selector.#", "0"), ), @@ -514,7 +514,7 @@ func testAcc_eventSelectorDynamoDB(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSelectorDynamoDBConfig(rName), + Config: testAccCloudTrailConfig_eventSelectorDynamoDB(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_selector.#", "1"), resource.TestCheckResourceAttr(resourceName, "event_selector.0.data_resource.#", "1"), @@ -540,7 +540,7 @@ func testAcc_eventSelectorExclude(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSelectorExcludeKMSConfig(rName), + Config: testAccCloudTrailConfig_eventSelectorExcludeKMS(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_selector.#", "1"), resource.TestCheckResourceAttr(resourceName, "event_selector.0.include_management_events", "true"), @@ -554,7 +554,7 @@ func testAcc_eventSelectorExclude(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEventSelectorExcludeKMSAndRDSDataConfig(rName), + Config: testAccCloudTrailConfig_eventSelectorExcludeKMSAndRDSData(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_selector.#", "1"), resource.TestCheckResourceAttr(resourceName, "event_selector.0.include_management_events", "true"), @@ -569,7 +569,7 @@ func testAcc_eventSelectorExclude(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEventSelectorNoneConfig(rName), + Config: testAccCloudTrailConfig_eventSelectorNone(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_selector.#", "0"), ), @@ -589,7 +589,7 @@ func testAcc_insightSelector(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightSelectorConfig(rName), + Config: testAccCloudTrailConfig_insightSelector(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "insight_selector.#", "1"), resource.TestCheckResourceAttr(resourceName, "insight_selector.0.insight_type", "ApiCallRateInsight"), @@ -601,7 +601,7 @@ func testAcc_insightSelector(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccInsightSelectorMultiConfig(rName), + Config: testAccCloudTrailConfig_insightSelectorMulti(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "insight_selector.#", "2"), resource.TestCheckResourceAttr(resourceName, "insight_selector.0.insight_type", "ApiCallRateInsight"), @@ -609,14 +609,14 @@ func testAcc_insightSelector(t *testing.T) { ), }, { - Config: testAccInsightSelectorConfig(rName), + Config: testAccCloudTrailConfig_insightSelector(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "insight_selector.#", "1"), resource.TestCheckResourceAttr(resourceName, "insight_selector.0.insight_type", "ApiCallRateInsight"), ), }, { - Config: testAccConfig(rName), + Config: testAccCloudTrailConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "insight_selector.#", "0"), ), @@ -636,7 +636,7 @@ func testAcc_advanced_event_selector(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig_advancedEventSelector(rName), + Config: testAccCloudTrailConfig_advancedEventSelector(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "advanced_event_selector.#", "5"), resource.TestCheckResourceAttr(resourceName, "advanced_event_selector.0.name", "s3Custom"), @@ -735,9 +735,9 @@ func testAcc_disappears(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig(rName), + Config: testAccCloudTrailConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckCloudTrailExists(resourceName, &trail), + testAccCheckExists(resourceName, &trail), acctest.CheckResourceDisappears(acctest.Provider, tfcloudtrail.ResourceCloudTrail(), resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudtrail.ResourceCloudTrail(), resourceName), ), @@ -747,7 +747,7 @@ func testAcc_disappears(t *testing.T) { }) } -func testAccCheckCloudTrailExists(n string, trail *cloudtrail.Trail) resource.TestCheckFunc { +func testAccCheckExists(n string, trail *cloudtrail.Trail) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -771,7 +771,7 @@ func testAccCheckCloudTrailExists(n string, trail *cloudtrail.Trail) resource.Te } } -func testAccCheckCloudTrailLoggingEnabled(n string, desired bool) resource.TestCheckFunc { +func testAccCheckLoggingEnabled(n string, desired bool) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -797,7 +797,7 @@ func testAccCheckCloudTrailLoggingEnabled(n string, desired bool) resource.TestC } } -func testAccCheckCloudTrailLogValidationEnabled(n string, desired bool, trail *cloudtrail.Trail) resource.TestCheckFunc { +func testAccCheckLogValidationEnabled(n string, desired bool, trail *cloudtrail.Trail) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -853,7 +853,7 @@ func testAccCheckDestroy(s *terraform.State) error { return nil } -func testAccCheckCloudTrailLoadTags(trail *cloudtrail.Trail, tags *[]*cloudtrail.Tag) resource.TestCheckFunc { +func testAccCheckLoadTags(trail *cloudtrail.Trail, tags *[]*cloudtrail.Tag) resource.TestCheckFunc { return func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).CloudTrailConn input := cloudtrail.ListTagsInput{ @@ -911,7 +911,7 @@ resource "aws_s3_bucket_policy" "test" { `, rName) } -func testAccConfig(rName string) string { +func testAccCloudTrailConfig_basic(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -923,7 +923,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccModifiedConfig(rName string) string { +func testAccCloudTrailConfig_modified(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -937,7 +937,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccEnableLoggingConfig(rName string, enableLogging bool) string { +func testAccCloudTrailConfig_enableLogging(rName string, enableLogging bool) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -952,7 +952,7 @@ resource "aws_cloudtrail" "test" { `, rName, enableLogging)) } -func testAccCloudWatchConfig(rName string) string { +func testAccCloudTrailConfig_cloudWatch(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1009,7 +1009,7 @@ resource "aws_iam_role_policy" "test" { `, rName)) } -func testAccCloudWatchModifiedConfig(rName string) string { +func testAccCloudTrailConfig_cloudWatchModified(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1070,7 +1070,7 @@ resource "aws_iam_role_policy" "test" { `, rName)) } -func testAccMultiRegionConfig(rName string) string { +func testAccCloudTrailConfig_multiRegion(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1083,7 +1083,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccOrganizationConfig(rName string) string { +func testAccCloudTrailConfig_organization(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_organizations_organization" "test" { aws_service_access_principals = ["cloudtrail.${data.aws_partition.current.dns_suffix}"] @@ -1100,7 +1100,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccLogValidationConfig(rName string) string { +func testAccCloudTrailConfig_logValidation(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1115,7 +1115,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccLogValidationModifiedConfig(rName string) string { +func testAccCloudTrailConfig_logValidationModified(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1128,7 +1128,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccKMSKeyConfig(rName string) string { +func testAccCloudTrailConfig_kmsKey(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -1162,7 +1162,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccGlobalServiceEventsConfig(rName string) string { +func testAccCloudTrailConfig_globalServiceEvents(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1175,7 +1175,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccTagsConfig(rName string) string { +func testAccCloudTrailConfig_tags(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1192,7 +1192,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccTagsModifiedConfig(rName string) string { +func testAccCloudTrailConfig_tagsModified(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1210,7 +1210,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccTagsModifiedAgainConfig(rName string) string { +func testAccCloudTrailConfig_tagsModifiedAgain(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1222,7 +1222,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccEventSelectorConfig(rName string) string { +func testAccCloudTrailConfig_eventSelector(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1253,7 +1253,7 @@ resource "aws_s3_bucket" "test2" { `, rName)) } -func testAccEventSelectorReadWriteTypeConfig(rName string) string { +func testAccCloudTrailConfig_eventSelectorReadWriteType(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1270,7 +1270,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccEventSelectorModifiedConfig(rName string) string { +func testAccCloudTrailConfig_eventSelectorModified(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1349,7 +1349,7 @@ resource "aws_lambda_function" "test" { `, rName)) } -func testAccEventSelectorNoneConfig(rName string) string { +func testAccCloudTrailConfig_eventSelectorNone(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1361,7 +1361,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccEventSelectorDynamoDBConfig(rName string) string { +func testAccCloudTrailConfig_eventSelectorDynamoDB(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1398,7 +1398,7 @@ resource "aws_dynamodb_table" "test" { `, rName)) } -func testAccEventSelectorExcludeKMSConfig(rName string) string { +func testAccCloudTrailConfig_eventSelectorExcludeKMS(rName string) string { return acctest.ConfigCompose( testAccBaseConfig(rName), fmt.Sprintf(` @@ -1416,7 +1416,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccEventSelectorExcludeKMSAndRDSDataConfig(rName string) string { +func testAccCloudTrailConfig_eventSelectorExcludeKMSAndRDSData(rName string) string { return acctest.ConfigCompose( testAccBaseConfig(rName), fmt.Sprintf(` @@ -1437,7 +1437,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccInsightSelectorConfig(rName string) string { +func testAccCloudTrailConfig_insightSelector(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1454,7 +1454,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccInsightSelectorMultiConfig(rName string) string { +func testAccCloudTrailConfig_insightSelectorMulti(rName string) string { return acctest.ConfigCompose(testAccBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first @@ -1475,7 +1475,7 @@ resource "aws_cloudtrail" "test" { `, rName)) } -func testAccConfig_advancedEventSelector(rName string) string { +func testAccCloudTrailConfig_advancedEventSelector(rName string) string { return fmt.Sprintf(` resource "aws_cloudtrail" "test" { # Must have bucket policy attached first diff --git a/internal/service/cloudtrail/consts.go b/internal/service/cloudtrail/consts.go index e85e3292601..e1b1c236af8 100644 --- a/internal/service/cloudtrail/consts.go +++ b/internal/service/cloudtrail/consts.go @@ -3,7 +3,7 @@ package cloudtrail import "time" const ( - ResCloudTrail = "Trail" + resTrail = "Trail" resourceTypeDynamoDBTable = "AWS::DynamoDB::Table" resourceTypeLambdaFunction = "AWS::Lambda::Function" diff --git a/internal/service/cloudtrail/event_data_store_test.go b/internal/service/cloudtrail/event_data_store_test.go index 311e42f455b..a40f94d025d 100644 --- a/internal/service/cloudtrail/event_data_store_test.go +++ b/internal/service/cloudtrail/event_data_store_test.go @@ -16,7 +16,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func TestAccEventDataStore_basic(t *testing.T) { +func TestAccCloudTrailEventDataStore_basic(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_cloudtrail_event_data_store.test" @@ -27,7 +27,7 @@ func TestAccEventDataStore_basic(t *testing.T) { CheckDestroy: testAccCheckEventDataStoreDestroy, Steps: []resource.TestStep{ { - Config: testAccEventDataStoreConfig(rName), + Config: testAccEventDataStoreConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckEventDataStoreExists(resourceName), resource.TestCheckResourceAttr(resourceName, "advanced_event_selector.#", "1"), @@ -56,7 +56,7 @@ func TestAccEventDataStore_basic(t *testing.T) { }) } -func TestAccEventDataStore_disappears(t *testing.T) { +func TestAccCloudTrailEventDataStore_disappears(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_cloudtrail_event_data_store.test" @@ -67,7 +67,7 @@ func TestAccEventDataStore_disappears(t *testing.T) { CheckDestroy: testAccCheckEventDataStoreDestroy, Steps: []resource.TestStep{ { - Config: testAccEventDataStoreConfig(rName), + Config: testAccEventDataStoreConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventDataStoreExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcloudtrail.ResourceEventDataStore(), resourceName), @@ -78,7 +78,7 @@ func TestAccEventDataStore_disappears(t *testing.T) { }) } -func TestAccEventDataStore_tags(t *testing.T) { +func TestAccCloudTrailEventDataStore_tags(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_cloudtrail_event_data_store.test" @@ -89,7 +89,7 @@ func TestAccEventDataStore_tags(t *testing.T) { CheckDestroy: testAccCheckEventDataStoreDestroy, Steps: []resource.TestStep{ { - Config: testAccEventDataStoreTagsConfig1(rName, "key1", "value1"), + Config: testAccEventDataStoreConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckEventDataStoreExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -102,7 +102,7 @@ func TestAccEventDataStore_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEventDataStoreTagsConfig2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccEventDataStoreConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckEventDataStoreExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -111,7 +111,7 @@ func TestAccEventDataStore_tags(t *testing.T) { ), }, { - Config: testAccEventDataStoreTagsConfig1(rName, "key2", "value2"), + Config: testAccEventDataStoreConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckEventDataStoreExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -122,7 +122,7 @@ func TestAccEventDataStore_tags(t *testing.T) { }) } -func TestAccEventDataStore_options(t *testing.T) { +func TestAccCloudTrailEventDataStore_options(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_cloudtrail_event_data_store.test" @@ -133,7 +133,7 @@ func TestAccEventDataStore_options(t *testing.T) { CheckDestroy: testAccCheckEventDataStoreDestroy, Steps: []resource.TestStep{ { - Config: testAccEventDataStoreOptionsConfig(rName), + Config: testAccEventDataStoreConfig_options(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventDataStoreExists(resourceName), resource.TestCheckResourceAttr(resourceName, "multi_region_enabled", "false"), @@ -148,7 +148,7 @@ func TestAccEventDataStore_options(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEventDataStoreOptionsUpdatedConfig(rName), + Config: testAccEventDataStoreConfig_optionsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventDataStoreExists(resourceName), resource.TestCheckResourceAttr(resourceName, "multi_region_enabled", "true"), @@ -161,7 +161,7 @@ func TestAccEventDataStore_options(t *testing.T) { }) } -func TestAccEventDataStore_advancedEventSelector(t *testing.T) { +func TestAccCloudTrailEventDataStore_advancedEventSelector(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_cloudtrail_event_data_store.test" @@ -172,7 +172,7 @@ func TestAccEventDataStore_advancedEventSelector(t *testing.T) { CheckDestroy: testAccCheckEventDataStoreDestroy, Steps: []resource.TestStep{ { - Config: testAccEventDataStoreConfig_advancedEventSelector(rName), + Config: testAccEventDataStoreConfig_advancedSelector(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "advanced_event_selector.#", "5"), resource.TestCheckResourceAttr(resourceName, "advanced_event_selector.0.name", "s3Custom"), @@ -298,7 +298,7 @@ func testAccCheckEventDataStoreDestroy(s *terraform.State) error { return nil } -func testAccEventDataStoreConfig(rName string) string { +func testAccEventDataStoreConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudtrail_event_data_store" "test" { name = %[1]q @@ -308,7 +308,7 @@ resource "aws_cloudtrail_event_data_store" "test" { `, rName) } -func testAccEventDataStoreTagsConfig1(rName, tagKey1, tagValue1 string) string { +func testAccEventDataStoreConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_cloudtrail_event_data_store" "test" { name = %[1]q @@ -322,7 +322,7 @@ resource "aws_cloudtrail_event_data_store" "test" { `, rName, tagKey1, tagValue1) } -func testAccEventDataStoreTagsConfig2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccEventDataStoreConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_cloudtrail_event_data_store" "test" { name = %[1]q @@ -337,7 +337,7 @@ resource "aws_cloudtrail_event_data_store" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccEventDataStoreOptionsConfig(rName string) string { +func testAccEventDataStoreConfig_options(rName string) string { return fmt.Sprintf(` resource "aws_cloudtrail_event_data_store" "test" { name = %[1]q @@ -350,7 +350,7 @@ resource "aws_cloudtrail_event_data_store" "test" { `, rName) } -func testAccEventDataStoreOptionsUpdatedConfig(rName string) string { +func testAccEventDataStoreConfig_optionsUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudtrail_event_data_store" "test" { name = %[1]q @@ -363,7 +363,7 @@ resource "aws_cloudtrail_event_data_store" "test" { `, rName) } -func testAccEventDataStoreConfig_advancedEventSelector(rName string) string { +func testAccEventDataStoreConfig_advancedSelector(rName string) string { return fmt.Sprintf(` resource "aws_cloudtrail_event_data_store" "test" { name = %[1]q diff --git a/internal/service/cloudtrail/service_account_data_source_test.go b/internal/service/cloudtrail/service_account_data_source_test.go index fdd521a87ad..2552f502cd3 100644 --- a/internal/service/cloudtrail/service_account_data_source_test.go +++ b/internal/service/cloudtrail/service_account_data_source_test.go @@ -19,7 +19,7 @@ func TestAccCloudTrailServiceAccountDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAWSCloudTrailServiceAccountConfig, + Config: testAccServiceAccountDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", expectedAccountID), acctest.CheckResourceAttrGlobalARNAccountID(dataSourceName, "arn", expectedAccountID, "iam", "root"), @@ -40,7 +40,7 @@ func TestAccCloudTrailServiceAccountDataSource_region(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAWSCloudTrailServiceAccountConfigRegion, + Config: testAccServiceAccountDataSourceConfig_region, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", expectedAccountID), acctest.CheckResourceAttrGlobalARNAccountID(dataSourceName, "arn", expectedAccountID, "iam", "root"), @@ -50,11 +50,11 @@ func TestAccCloudTrailServiceAccountDataSource_region(t *testing.T) { }) } -const testAccCheckAWSCloudTrailServiceAccountConfig = ` +const testAccServiceAccountDataSourceConfig_basic = ` data "aws_cloudtrail_service_account" "main" {} ` -const testAccCheckAWSCloudTrailServiceAccountConfigRegion = ` +const testAccServiceAccountDataSourceConfig_region = ` data "aws_region" "current" {} data "aws_cloudtrail_service_account" "regional" { diff --git a/internal/service/cloudwatch/composite_alarm.go b/internal/service/cloudwatch/composite_alarm.go index baab91e6066..0670f7fa606 100644 --- a/internal/service/cloudwatch/composite_alarm.go +++ b/internal/service/cloudwatch/composite_alarm.go @@ -102,7 +102,7 @@ func resourceCompositeAlarmCreate(ctx context.Context, d *schema.ResourceData, m _, err := conn.PutCompositeAlarmWithContext(ctx, &input) // Some partitions (i.e., ISO) may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating CloudWatch Composite Alarm (%s) with tags: %s. Trying create without tags.", name, err) input.Tags = nil @@ -129,7 +129,7 @@ func resourceCompositeAlarmCreate(ctx context.Context, d *schema.ResourceData, m err = UpdateTags(conn, aws.StringValue(alarm.AlarmArn), nil, tags) // If default tags only, log and continue. Otherwise, error. - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed adding tags after create for CloudWatch Composite Alarm (%s): %s", d.Id(), err) return resourceCompositeAlarmRead(ctx, d, meta) } @@ -191,7 +191,7 @@ func resourceCompositeAlarmRead(ctx context.Context, d *schema.ResourceData, met tags, err := ListTags(conn, aws.StringValue(alarm.AlarmArn)) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed listing tags for CloudWatch Composite Alarm (%s): %s", d.Id(), err) return nil } @@ -232,7 +232,7 @@ func resourceCompositeAlarmUpdate(ctx context.Context, d *schema.ResourceData, m err := UpdateTags(conn, arn, o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed updating tags for CloudWatch Composite Alarm (%s): %s", d.Id(), err) return resourceCompositeAlarmRead(ctx, d, meta) } diff --git a/internal/service/cloudwatch/composite_alarm_test.go b/internal/service/cloudwatch/composite_alarm_test.go index 2ae68e71bf2..1061eb037a9 100644 --- a/internal/service/cloudwatch/composite_alarm_test.go +++ b/internal/service/cloudwatch/composite_alarm_test.go @@ -121,7 +121,7 @@ func TestAccCloudWatchCompositeAlarm_alarmActions(t *testing.T) { CheckDestroy: testAccCheckCompositeAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccCompositeAlarmConfig_alarmActions(suffix), + Config: testAccCompositeAlarmConfig_actions(suffix), Check: resource.ComposeTestCheckFunc( testAccCheckCompositeAlarmExists(resourceName), resource.TestCheckResourceAttr(resourceName, "alarm_actions.#", "2"), @@ -133,7 +133,7 @@ func TestAccCloudWatchCompositeAlarm_alarmActions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCompositeAlarmConfig_updateAlarmActions(suffix), + Config: testAccCompositeAlarmConfig_updateActions(suffix), Check: resource.ComposeTestCheckFunc( testAccCheckCompositeAlarmExists(resourceName), resource.TestCheckResourceAttr(resourceName, "alarm_actions.#", "1"), @@ -362,7 +362,7 @@ func TestAccCloudWatchCompositeAlarm_updateAlarmRule(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCompositeAlarmConfig_updateAlarmRule(suffix), + Config: testAccCompositeAlarmConfig_updateRule(suffix), Check: resource.ComposeTestCheckFunc( testAccCheckCompositeAlarmExists(resourceName), resource.TestCheckResourceAttr(resourceName, "alarm_rule", fmt.Sprintf("ALARM(tf-test-metric-0-%[1]s)", suffix)), @@ -485,7 +485,7 @@ resource "aws_cloudwatch_composite_alarm" "test" { `, description, suffix)) } -func testAccCompositeAlarmConfig_alarmActions(suffix string) string { +func testAccCompositeAlarmConfig_actions(suffix string) string { return acctest.ConfigCompose( testAccCompositeAlarmBaseConfig(suffix), fmt.Sprintf(` @@ -502,7 +502,7 @@ resource "aws_cloudwatch_composite_alarm" "test" { `, suffix)) } -func testAccCompositeAlarmConfig_updateAlarmActions(suffix string) string { +func testAccCompositeAlarmConfig_updateActions(suffix string) string { return acctest.ConfigCompose( testAccCompositeAlarmBaseConfig(suffix), fmt.Sprintf(` @@ -519,7 +519,7 @@ resource "aws_cloudwatch_composite_alarm" "test" { `, suffix)) } -func testAccCompositeAlarmConfig_updateAlarmRule(suffix string) string { +func testAccCompositeAlarmConfig_updateRule(suffix string) string { return acctest.ConfigCompose( testAccCompositeAlarmBaseConfig(suffix), fmt.Sprintf(` diff --git a/internal/service/cloudwatch/dashboard_test.go b/internal/service/cloudwatch/dashboard_test.go index 0cbafbc40c7..a8f37fe2c7b 100644 --- a/internal/service/cloudwatch/dashboard_test.go +++ b/internal/service/cloudwatch/dashboard_test.go @@ -29,7 +29,7 @@ func TestAccCloudWatchDashboard_basic(t *testing.T) { CheckDestroy: testAccCheckDashboardDestroy, Steps: []resource.TestStep{ { - Config: testAccDashboardConfig(rInt), + Config: testAccDashboardConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckDashboardExists(resourceName, &dashboard), resource.TestCheckResourceAttr(resourceName, "dashboard_name", testAccDashboardName(rInt)), @@ -56,7 +56,7 @@ func TestAccCloudWatchDashboard_update(t *testing.T) { CheckDestroy: testAccCheckDashboardDestroy, Steps: []resource.TestStep{ { - Config: testAccDashboardConfig(rInt), + Config: testAccDashboardConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckDashboardExists(resourceName, &dashboard), testAccCheckDashboardBodyIsExpected(resourceName, basicWidget), @@ -92,7 +92,7 @@ func TestAccCloudWatchDashboard_updateName(t *testing.T) { CheckDestroy: testAccCheckDashboardDestroy, Steps: []resource.TestStep{ { - Config: testAccDashboardConfig(rInt), + Config: testAccDashboardConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckDashboardExists(resourceName, &dashboard), testAccCheckDashboardBodyIsExpected(resourceName, basicWidget), @@ -100,7 +100,7 @@ func TestAccCloudWatchDashboard_updateName(t *testing.T) { ), }, { - Config: testAccDashboardConfig(rInt2), + Config: testAccDashboardConfig_basic(rInt2), Check: resource.ComposeTestCheckFunc( testAccCheckDashboardExists(resourceName, &dashboard), testAccCheckDashboardBodyIsExpected(resourceName, basicWidget), @@ -217,7 +217,7 @@ func testAccDashboardName(rInt int) string { return fmt.Sprintf("terraform-test-dashboard-%d", rInt) } -func testAccDashboardConfig(rInt int) string { +func testAccDashboardConfig_basic(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_dashboard" "test" { dashboard_name = "terraform-test-dashboard-%d" diff --git a/internal/service/cloudwatch/metric_alarm.go b/internal/service/cloudwatch/metric_alarm.go index 815e9d5f89f..6949b9dc148 100644 --- a/internal/service/cloudwatch/metric_alarm.go +++ b/internal/service/cloudwatch/metric_alarm.go @@ -307,7 +307,7 @@ func resourceMetricAlarmCreate(d *schema.ResourceData, meta interface{}) error { _, err = conn.PutMetricAlarm(¶ms) // Some partitions (i.e., ISO) may not support tag-on-create - if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating CloudWatch Metric Alarm (%s) with tags: %s. Trying create without tags.", d.Get("alarm_name").(string), err) params.Tags = nil @@ -335,7 +335,7 @@ func resourceMetricAlarmCreate(d *schema.ResourceData, meta interface{}) error { err = UpdateTags(conn, aws.StringValue(resp.AlarmArn), nil, tags) // If default tags only, log and continue. Otherwise, error. - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed adding tags after create for CloudWatch Metric Alarm (%s): %s", d.Id(), err) return resourceMetricAlarmRead(d, meta) } @@ -430,7 +430,7 @@ func resourceMetricAlarmRead(d *schema.ResourceData, meta interface{}) error { tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed listing tags for CloudWatch Metric Alarm (%s): %s", d.Id(), err) return nil } @@ -465,7 +465,7 @@ func resourceMetricAlarmUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, arn, o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed updating tags for CloudWatch Metric Alarm (%s): %s", d.Id(), err) return resourceMetricAlarmRead(d, meta) } diff --git a/internal/service/cloudwatch/metric_alarm_test.go b/internal/service/cloudwatch/metric_alarm_test.go index 9fbfa7049d8..f92005007e6 100755 --- a/internal/service/cloudwatch/metric_alarm_test.go +++ b/internal/service/cloudwatch/metric_alarm_test.go @@ -27,7 +27,7 @@ func TestAccCloudWatchMetricAlarm_basic(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmConfig(rName), + Config: testAccMetricAlarmConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "metric_name", "CPUUtilization"), @@ -68,7 +68,7 @@ func TestAccCloudWatchMetricAlarm_AlarmActions_ec2Automate(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmAlarmActionsEC2AutomateConfig(rName, "reboot"), + Config: testAccMetricAlarmConfig_actionsEC2Automate(rName, "reboot"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "alarm_actions.#", "1"), @@ -80,21 +80,21 @@ func TestAccCloudWatchMetricAlarm_AlarmActions_ec2Automate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMetricAlarmAlarmActionsEC2AutomateConfig(rName, "recover"), + Config: testAccMetricAlarmConfig_actionsEC2Automate(rName, "recover"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "alarm_actions.#", "1"), ), }, { - Config: testAccMetricAlarmAlarmActionsEC2AutomateConfig(rName, "stop"), + Config: testAccMetricAlarmConfig_actionsEC2Automate(rName, "stop"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "alarm_actions.#", "1"), ), }, { - Config: testAccMetricAlarmAlarmActionsEC2AutomateConfig(rName, "terminate"), + Config: testAccMetricAlarmConfig_actionsEC2Automate(rName, "terminate"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "alarm_actions.#", "1"), @@ -116,7 +116,7 @@ func TestAccCloudWatchMetricAlarm_AlarmActions_snsTopic(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmAlarmActionsSNSTopicConfig(rName), + Config: testAccMetricAlarmConfig_actionsSNSTopic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "alarm_actions.#", "1"), @@ -143,7 +143,7 @@ func TestAccCloudWatchMetricAlarm_AlarmActions_swfAction(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmAlarmActionsSWFActionConfig(rName), + Config: testAccMetricAlarmConfig_actionsSWFAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "alarm_actions.#", "1"), @@ -170,7 +170,7 @@ func TestAccCloudWatchMetricAlarm_dataPointsToAlarm(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmDatapointsToAlarmConfig(rName), + Config: testAccMetricAlarmConfig_datapointsTo(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "datapoints_to_alarm", "2"), @@ -192,21 +192,21 @@ func TestAccCloudWatchMetricAlarm_treatMissingData(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmTreatMissingDataConfig(rName), + Config: testAccMetricAlarmConfig_treatMissingData(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "treat_missing_data", "missing"), ), }, { - Config: testAccMetricAlarmTreatMissingDataUpdateConfig(rName), + Config: testAccMetricAlarmConfig_treatMissingDataUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "treat_missing_data", "breaching"), ), }, { - Config: testAccMetricAlarmTreatMissingDataConfigNoAttr(rName), + Config: testAccMetricAlarmConfig_treatMissingDataNoAttr(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "treat_missing_data", "missing"), @@ -233,14 +233,14 @@ func TestAccCloudWatchMetricAlarm_evaluateLowSampleCountPercentiles(t *testing.T CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmTreatEvaluateLowSampleCountPercentilesConfig(rName), + Config: testAccMetricAlarmConfig_treatEvaluateLowSampleCountPercentiles(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "evaluate_low_sample_count_percentiles", "evaluate"), ), }, { - Config: testAccMetricAlarmTreatEvaluateLowSampleCountPercentilesUpdatedConfig(rName), + Config: testAccMetricAlarmConfig_treatEvaluateLowSampleCountPercentilesUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "evaluate_low_sample_count_percentiles", "ignore"), @@ -262,137 +262,137 @@ func TestAccCloudWatchMetricAlarm_extendedStatistic(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "IQM(1:2)"), // IQM accepts no args + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "IQM(1:2)"), // IQM accepts no args ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "iqm10"), // IQM accepts no args + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "iqm10"), // IQM accepts no args ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), }, // { TODO: more complex regex to reject this - // Config: testAccMetricAlarmExtendedStatisticConfig(rName, "PR(5%:10%)"), // PR args must be absolute + // Config: testAccMetricAlarmConfig_extendedStatistic(rName, "PR(5%:10%)"), // PR args must be absolute // ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), // }, // { TODO: more complex regex to reject this - // Config: testAccMetricAlarmExtendedStatisticConfig(rName, "TC(:)"), // at least one arg must be provided + // Config: testAccMetricAlarmConfig_extendedStatistic(rName, "TC(:)"), // at least one arg must be provided // ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), // }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "WM"), // missing syntax + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "WM"), // missing syntax ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "p"), // missing arg + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "p"), // missing arg ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "AB(1:2)"), // unknown stat 'AB' + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "AB(1:2)"), // unknown stat 'AB' ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "cd42"), // unknown stat 'cd' + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "cd42"), // unknown stat 'cd' ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "p88.0"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "p88.0"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "p88.0"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "p0.0"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "p0.0"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "p0.0"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "p100"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "p100"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "p100"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "p95"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "p95"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "p95"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "tm90"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "tm90"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "tm90"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "TM(2%:98%)"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "TM(2%:98%)"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "TM(2%:98%)"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "TM(150:1000)"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "TM(150:1000)"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "TM(150:1000)"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "IQM"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "IQM"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "IQM"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "wm98"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "wm98"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "wm98"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "PR(:300)"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "PR(:300)"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "PR(:300)"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "PR(100:2000)"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "PR(100:2000)"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "PR(100:2000)"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "tc90"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "tc90"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "tc90"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "TC(0.005:0.030)"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "TC(0.005:0.030)"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "TC(0.005:0.030)"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "TS(80%:)"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "TS(80%:)"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "TS(80%:)"), ), }, { - Config: testAccMetricAlarmExtendedStatisticConfig(rName, "TC(:0.5)"), + Config: testAccMetricAlarmConfig_extendedStatistic(rName, "TC(:0.5)"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "extended_statistic", "TC(:0.5)"), @@ -414,46 +414,46 @@ func TestAccCloudWatchMetricAlarm_expression(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmWithBadExpressionConfig(rName), + Config: testAccMetricAlarmConfig_badExpression(rName), ExpectError: regexp.MustCompile("No metric_query may have both `expression` and a `metric` specified"), }, { - Config: testAccMetricAlarmWithExpressionConfig(rName), + Config: testAccMetricAlarmConfig_expression(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "metric_query.#", "2"), ), }, { - Config: testAccMetricAlarmWithCrossAccountMetricConfig(rName), + Config: testAccMetricAlarmConfig_crossAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttrPair(resourceName, "metric_query.0.account_id", "data.aws_caller_identity.current", "account_id"), ), }, { - Config: testAccMetricAlarmWithExpressionUpdatedConfig(rName), + Config: testAccMetricAlarmConfig_expressionUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "metric_query.#", "3"), ), }, { - Config: testAccMetricAlarmWithExpressionConfig(rName), + Config: testAccMetricAlarmConfig_expression(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "metric_query.#", "2"), ), }, { - Config: testAccMetricAlarmWithAnomalyDetectionExpressionConfig(rName), + Config: testAccMetricAlarmConfig_anomalyDetectionExpression(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "metric_query.#", "2"), ), }, { - Config: testAccMetricAlarmWithExpressionWithQueryUpdatedConfig(rName), + Config: testAccMetricAlarmConfig_expressionQueryUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "metric_query.#", "2"), @@ -477,7 +477,7 @@ func TestAccCloudWatchMetricAlarm_missingStatistic(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmMissingStatisticConfig(rName), + Config: testAccMetricAlarmConfig_missingStatistic(rName), ExpectError: regexp.MustCompile("One of `statistic` or `extended_statistic` must be set for a cloudwatch metric alarm"), }, }, @@ -496,7 +496,7 @@ func TestAccCloudWatchMetricAlarm_tags(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmTags1Config(rName, "key1", "value1"), + Config: testAccMetricAlarmConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -509,7 +509,7 @@ func TestAccCloudWatchMetricAlarm_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMetricAlarmTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccMetricAlarmConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -518,7 +518,7 @@ func TestAccCloudWatchMetricAlarm_tags(t *testing.T) { ), }, { - Config: testAccMetricAlarmTags1Config(rName, "key2", "value2"), + Config: testAccMetricAlarmConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -541,7 +541,7 @@ func TestAccCloudWatchMetricAlarm_disappears(t *testing.T) { CheckDestroy: testAccCheckMetricAlarmDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricAlarmConfig(rName), + Config: testAccMetricAlarmConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricAlarmExists(resourceName, &alarm), acctest.CheckResourceDisappears(acctest.Provider, tfcloudwatch.ResourceMetricAlarm(), resourceName), @@ -592,7 +592,7 @@ func testAccCheckMetricAlarmDestroy(s *terraform.State) error { return nil } -func testAccMetricAlarmConfig(rName string) string { +func testAccMetricAlarmConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -613,7 +613,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmDatapointsToAlarmConfig(rName string) string { +func testAccMetricAlarmConfig_datapointsTo(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -635,7 +635,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmTreatMissingDataConfig(rName string) string { +func testAccMetricAlarmConfig_treatMissingData(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -657,7 +657,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmTreatMissingDataUpdateConfig(rName string) string { +func testAccMetricAlarmConfig_treatMissingDataUpdate(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -679,7 +679,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmTreatMissingDataConfigNoAttr(rName string) string { +func testAccMetricAlarmConfig_treatMissingDataNoAttr(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -700,7 +700,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmTreatEvaluateLowSampleCountPercentilesConfig(rName string) string { +func testAccMetricAlarmConfig_treatEvaluateLowSampleCountPercentiles(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -722,7 +722,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmTreatEvaluateLowSampleCountPercentilesUpdatedConfig(rName string) string { +func testAccMetricAlarmConfig_treatEvaluateLowSampleCountPercentilesUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -744,7 +744,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmExtendedStatisticConfig(rName string, stat string) string { +func testAccMetricAlarmConfig_extendedStatistic(rName string, stat string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -765,7 +765,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName, stat) } -func testAccMetricAlarmMissingStatisticConfig(rName string) string { +func testAccMetricAlarmConfig_missingStatistic(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -785,7 +785,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmWithExpressionConfig(rName string) string { +func testAccMetricAlarmConfig_expression(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -821,7 +821,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmWithCrossAccountMetricConfig(rName string) string { +func testAccMetricAlarmConfig_crossAccount(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -854,7 +854,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmWithAnomalyDetectionExpressionConfig(rName string) string { +func testAccMetricAlarmConfig_anomalyDetectionExpression(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -891,7 +891,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmWithExpressionUpdatedConfig(rName string) string { +func testAccMetricAlarmConfig_expressionUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -933,7 +933,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmWithExpressionWithQueryUpdatedConfig(rName string) string { +func testAccMetricAlarmConfig_expressionQueryUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -969,7 +969,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmWithBadExpressionConfig(rName string) string { +func testAccMetricAlarmConfig_badExpression(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = "%s" @@ -1002,9 +1002,9 @@ resource "aws_cloudwatch_metric_alarm" "test" { // EC2 Automate requires a valid EC2 instance // ValidationError: Invalid use of EC2 'Recover' action. i-abc123 is not a valid EC2 instance. -func testAccMetricAlarmAlarmActionsEC2AutomateConfig(rName, action string) string { +func testAccMetricAlarmConfig_actionsEC2Automate(rName, action string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("aws_subnet.test.availability_zone", "t3.micro", "t2.micro"), fmt.Sprintf(` data "aws_partition" "current" {} @@ -1058,7 +1058,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName, action)) } -func testAccMetricAlarmAlarmActionsSNSTopicConfig(rName string) string { +func testAccMetricAlarmConfig_actionsSNSTopic(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %q @@ -1084,7 +1084,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName, rName) } -func testAccMetricAlarmAlarmActionsSWFActionConfig(rName string) string { +func testAccMetricAlarmConfig_actionsSWFAction(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" { } @@ -1115,7 +1115,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName) } -func testAccMetricAlarmTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccMetricAlarmConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = %[1]q @@ -1140,7 +1140,7 @@ resource "aws_cloudwatch_metric_alarm" "test" { `, rName, tagKey1, tagValue1) } -func testAccMetricAlarmTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccMetricAlarmConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = %[1]q diff --git a/internal/service/cloudwatch/metric_stream.go b/internal/service/cloudwatch/metric_stream.go index dd1f6530fd4..3fc721bbfb0 100644 --- a/internal/service/cloudwatch/metric_stream.go +++ b/internal/service/cloudwatch/metric_stream.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -113,6 +114,55 @@ func ResourceMetricStream() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "statistics_configuration": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "additional_statistics": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.All( + validation.Any( + validation.StringMatch( + regexp.MustCompile(`(^IQM$)|(^(p|tc|tm|ts|wm)(100|\d{1,2})(\.\d{0,10})?$)|(^[ou]\d+(\.\d*)?$)`), + "invalid statistic, see: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Statistics-definitions.html", + ), + validation.StringMatch( + regexp.MustCompile(`^(TM|TC|TS|WM)\(((((\d{1,2})(\.\d{0,10})?|100(\.0{0,10})?)%)?:((\d{1,2})(\.\d{0,10})?|100(\.0{0,10})?)%|((\d{1,2})(\.\d{0,10})?|100(\.0{0,10})?)%:(((\d{1,2})(\.\d{0,10})?|100(\.0{0,10})?)%)?)\)|(TM|TC|TS|WM|PR)\(((\d+(\.\d{0,10})?|(\d+(\.\d{0,10})?[Ee][+-]?\d+)):((\d+(\.\d{0,10})?|(\d+(\.\d{0,10})?[Ee][+-]?\d+)))?|((\d+(\.\d{0,10})?|(\d+(\.\d{0,10})?[Ee][+-]?\d+)))?:(\d+(\.\d{0,10})?|(\d+(\.\d{0,10})?[Ee][+-]?\d+)))\)$`), + "invalid statistic, see: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Statistics-definitions.html", + ), + ), + validation.StringDoesNotMatch( + regexp.MustCompile(`^p0(\.0{0,10})?|p100(\.\d{0,10})?$`), + "invalid statistic, see: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Statistics-definitions.html", + ), + ), + }, + }, + "include_metric": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "metric_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 255), + }, + "namespace": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 255), + }, + }, + }, + }, + }, + }, + }, "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), }, @@ -145,11 +195,15 @@ func resourceMetricStreamCreate(ctx context.Context, d *schema.ResourceData, met params.ExcludeFilters = expandMetricStreamFilters(v.(*schema.Set)) } + if v, ok := d.GetOk("statistics_configuration"); ok && v.(*schema.Set).Len() > 0 { + params.StatisticsConfigurations = expandMetricStreamStatisticsConfigurations(v.(*schema.Set)) + } + log.Printf("[DEBUG] Putting CloudWatch Metric Stream: %#v", params) output, err := conn.PutMetricStreamWithContext(ctx, ¶ms) // Some partitions (i.e., ISO) may not support tag-on-create - if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating CloudWatch Metric Stream (%s) with tags: %s. Trying create without tags.", name, err) params.Tags = nil @@ -168,7 +222,7 @@ func resourceMetricStreamCreate(ctx context.Context, d *schema.ResourceData, met err := UpdateTags(conn, aws.StringValue(output.Arn), nil, tags) // If default tags only, log and continue. Otherwise, error. - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed adding tags after create for CloudWatch Metric Stream (%s): %s", d.Id(), err) return resourceMetricStreamRead(ctx, d, meta) } @@ -224,10 +278,16 @@ func resourceMetricStreamRead(ctx context.Context, d *schema.ResourceData, meta } } + if output.StatisticsConfigurations != nil { + if err := d.Set("statistics_configuration", flattenMetricStreamStatisticsConfigurations(output.StatisticsConfigurations)); err != nil { + return diag.FromErr(fmt.Errorf("error setting statistics_configuration error: %w", err)) + } + } + tags, err := ListTags(conn, aws.StringValue(output.Arn)) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed listing tags for CloudWatch Metric Stream (%s): %s", d.Id(), err) return nil } @@ -312,3 +372,88 @@ func flattenMetricStreamFilters(s []*cloudwatch.MetricStreamFilter) []map[string return nil } + +func expandMetricStreamStatisticsConfigurations(s *schema.Set) []*cloudwatch.MetricStreamStatisticsConfiguration { + var configurations []*cloudwatch.MetricStreamStatisticsConfiguration + + for _, configurationRaw := range s.List() { + configuration := &cloudwatch.MetricStreamStatisticsConfiguration{} + mConfiguration := configurationRaw.(map[string]interface{}) + + if v, ok := mConfiguration["additional_statistics"].(*schema.Set); ok && v.Len() > 0 { + log.Printf("[DEBUG] CloudWatch Metric Stream StatisticsConfigurations additional_statistics: %#v", v) + configuration.AdditionalStatistics = flex.ExpandStringSet(v) + } + + if v, ok := mConfiguration["include_metric"].(*schema.Set); ok && v.Len() > 0 { + log.Printf("[DEBUG] CloudWatch Metric Stream StatisticsConfigurations include_metrics: %#v", v) + configuration.IncludeMetrics = expandMetricStreamStatisticsConfigurationsIncludeMetrics(v) + } + + configurations = append(configurations, configuration) + + } + + log.Printf("[DEBUG] statistics_configurations: %#v", configurations) + + if len(configurations) > 0 { + return configurations + } + + return nil +} + +func expandMetricStreamStatisticsConfigurationsIncludeMetrics(metrics *schema.Set) []*cloudwatch.MetricStreamStatisticsMetric { + var includeMetrics []*cloudwatch.MetricStreamStatisticsMetric + + for _, metricRaw := range metrics.List() { + metric := &cloudwatch.MetricStreamStatisticsMetric{} + mMetric := metricRaw.(map[string]interface{}) + + if v, ok := mMetric["metric_name"].(string); ok && v != "" { + metric.MetricName = aws.String(v) + } + + if v, ok := mMetric["namespace"].(string); ok && v != "" { + metric.Namespace = aws.String(v) + } + + includeMetrics = append(includeMetrics, metric) + } + + if len(includeMetrics) > 0 { + return includeMetrics + } + + return nil +} + +func flattenMetricStreamStatisticsConfigurations(configurations []*cloudwatch.MetricStreamStatisticsConfiguration) []map[string]interface{} { + flatConfigurations := make([]map[string]interface{}, len(configurations)) + + for i, configuration := range configurations { + flatConfiguration := map[string]interface{}{ + "additional_statistics": flex.FlattenStringSet(configuration.AdditionalStatistics), + "include_metric": flattenMetricStreamStatisticsConfigurationsIncludeMetrics(configuration.IncludeMetrics), + } + + flatConfigurations[i] = flatConfiguration + } + + return flatConfigurations +} + +func flattenMetricStreamStatisticsConfigurationsIncludeMetrics(metrics []*cloudwatch.MetricStreamStatisticsMetric) []map[string]interface{} { + flatMetrics := make([]map[string]interface{}, len(metrics)) + + for i, metric := range metrics { + flatMetric := map[string]interface{}{ + "metric_name": aws.StringValue(metric.MetricName), + "namespace": aws.StringValue(metric.Namespace), + } + + flatMetrics[i] = flatMetric + } + + return flatMetrics +} diff --git a/internal/service/cloudwatch/metric_stream_test.go b/internal/service/cloudwatch/metric_stream_test.go index 1a3fa5d56da..245c27829bf 100644 --- a/internal/service/cloudwatch/metric_stream_test.go +++ b/internal/service/cloudwatch/metric_stream_test.go @@ -2,6 +2,7 @@ package cloudwatch_test import ( "fmt" + "regexp" "strings" "testing" @@ -17,10 +18,10 @@ import ( ) func init() { - acctest.RegisterServiceErrorCheckFunc(cloudwatch.EndpointsID, testAccErrorCheckSkipCloudwatch) + acctest.RegisterServiceErrorCheckFunc(cloudwatch.EndpointsID, testAccErrorCheckSkip) } -func testAccErrorCheckSkipCloudwatch(t *testing.T) resource.ErrorCheckFunc { +func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { return acctest.ErrorCheckSkipMessagesContaining(t, "context deadline exceeded", // tests never fail in GovCloud, they just timeout ) @@ -37,7 +38,7 @@ func TestAccCloudWatchMetricStream_basic(t *testing.T) { CheckDestroy: testAccCheckMetricStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricStreamConfig(rName), + Config: testAccMetricStreamConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -68,7 +69,7 @@ func TestAccCloudWatchMetricStream_noName(t *testing.T) { CheckDestroy: testAccCheckMetricStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricStreamNoNameConfig(), + Config: testAccMetricStreamConfig_noName(), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), ), @@ -93,7 +94,7 @@ func TestAccCloudWatchMetricStream_namePrefix(t *testing.T) { CheckDestroy: testAccCheckMetricStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricStreamNamePrefixConfig(rName), + Config: testAccMetricStreamConfig_namePrefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), testAccCheckMetricStreamGeneratedNamePrefix(resourceName, acctest.ResourcePrefix), @@ -119,7 +120,7 @@ func TestAccCloudWatchMetricStream_includeFilters(t *testing.T) { CheckDestroy: testAccCheckMetricStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricStreamIncludeFiltersConfig(rName), + Config: testAccMetricStreamConfig_includeFilters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -147,7 +148,7 @@ func TestAccCloudWatchMetricStream_excludeFilters(t *testing.T) { CheckDestroy: testAccCheckMetricStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricStreamExcludeFiltersConfig(rName), + Config: testAccMetricStreamConfig_excludeFilters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -175,7 +176,7 @@ func TestAccCloudWatchMetricStream_update(t *testing.T) { CheckDestroy: testAccCheckMetricStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricStreamUpdateARNConfig(rName), + Config: testAccMetricStreamConfig_updateARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -188,7 +189,7 @@ func TestAccCloudWatchMetricStream_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMetricStreamConfig(rName), + Config: testAccMetricStreamConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -211,14 +212,14 @@ func TestAccCloudWatchMetricStream_updateName(t *testing.T) { CheckDestroy: testAccCheckMetricStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricStreamConfig(rName), + Config: testAccMetricStreamConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), ), }, { - Config: testAccMetricStreamConfig(rName2), + Config: testAccMetricStreamConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName2), @@ -240,7 +241,7 @@ func TestAccCloudWatchMetricStream_tags(t *testing.T) { CheckDestroy: testAccCheckMetricStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricStreamTagsConfig(rName), + Config: testAccMetricStreamConfig_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMetricStreamExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -255,6 +256,77 @@ func TestAccCloudWatchMetricStream_tags(t *testing.T) { }) } +func TestAccCloudWatchMetricStream_additional_statistics(t *testing.T) { + resourceName := "aws_cloudwatch_metric_stream.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, cloudwatch.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckMetricStreamDestroy, + Steps: []resource.TestStep{ + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "p0"), + ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), + }, + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "p100"), + ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), + }, + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "p"), + ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), + }, + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "tm"), + ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), + }, + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "tc()"), + ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), + }, + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "p99.12345678901"), + ExpectError: regexp.MustCompile(`invalid statistic, see: https:\/\/docs\.aws\.amazon\.com\/.*`), + }, + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "IQM"), + Check: resource.ComposeTestCheckFunc( + testAccCheckMetricStreamExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "statistics_configuration.#", "2"), + ), + }, + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "PR(:50)"), + Check: resource.ComposeTestCheckFunc( + testAccCheckMetricStreamExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "statistics_configuration.#", "2"), + ), + }, + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "TS(50.5:)"), + Check: resource.ComposeTestCheckFunc( + testAccCheckMetricStreamExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "statistics_configuration.#", "2"), + ), + }, + { + Config: testAccMetricStreamConfig_additionalStatistics(rName, "TC(1:100)"), + Check: resource.ComposeTestCheckFunc( + testAccCheckMetricStreamExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "statistics_configuration.#", "2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func testAccCheckMetricStreamGeneratedNamePrefix(resource, prefix string) resource.TestCheckFunc { return func(s *terraform.State) error { r, ok := s.RootModule().Resources[resource] @@ -340,7 +412,7 @@ func testAccCheckMetricStreamDestroyPrevious(name string) resource.TestCheckFunc } } -func testAccMetricStreamConfig(rName string) string { +func testAccMetricStreamConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -459,7 +531,7 @@ resource "aws_kinesis_firehose_delivery_stream" "s3_stream" { `, rName) } -func testAccMetricStreamUpdateARNConfig(rName string) string { +func testAccMetricStreamConfig_updateARN(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} data "aws_region" "current" {} @@ -474,7 +546,7 @@ resource "aws_cloudwatch_metric_stream" "test" { `, rName) } -func testAccMetricStreamIncludeFiltersConfig(rName string) string { +func testAccMetricStreamConfig_includeFilters(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} data "aws_region" "current" {} @@ -497,7 +569,7 @@ resource "aws_cloudwatch_metric_stream" "test" { `, rName) } -func testAccMetricStreamNoNameConfig() string { +func testAccMetricStreamConfig_noName() string { return ` data "aws_partition" "current" {} data "aws_region" "current" {} @@ -511,7 +583,7 @@ resource "aws_cloudwatch_metric_stream" "test" { ` } -func testAccMetricStreamNamePrefixConfig(rName string) string { +func testAccMetricStreamConfig_namePrefix(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} data "aws_region" "current" {} @@ -526,7 +598,7 @@ resource "aws_cloudwatch_metric_stream" "test" { `, rName) } -func testAccMetricStreamExcludeFiltersConfig(rName string) string { +func testAccMetricStreamConfig_excludeFilters(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} data "aws_region" "current" {} @@ -549,7 +621,7 @@ resource "aws_cloudwatch_metric_stream" "test" { `, rName) } -func testAccMetricStreamTagsConfig(rName string) string { +func testAccMetricStreamConfig_tags(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} data "aws_region" "current" {} @@ -568,3 +640,40 @@ resource "aws_cloudwatch_metric_stream" "test" { } `, rName) } + +func testAccMetricStreamConfig_additionalStatistics(rName string, stat string) string { + return fmt.Sprintf(` +data "aws_partition" "current" {} +data "aws_region" "current" {} +data "aws_caller_identity" "current" {} + +resource "aws_cloudwatch_metric_stream" "test" { + name = %[1]q + role_arn = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:role/MyRole" + firehose_arn = "arn:${data.aws_partition.current.partition}:firehose:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:deliverystream/MyFirehose" + output_format = "json" + + statistics_configuration { + additional_statistics = [ + "p1", "tm99" + ] + + include_metric { + metric_name = "CPUUtilization" + namespace = "AWS/EC2" + } + } + + statistics_configuration { + additional_statistics = [ + %[2]q + ] + + include_metric { + metric_name = "CPUUtilization" + namespace = "AWS/EC2" + } + } +} +`, rName, stat) +} diff --git a/internal/service/codeartifact/authorization_token_data_source_test.go b/internal/service/codeartifact/authorization_token_data_source_test.go index e8ebe1f4ccd..71197e67bc4 100644 --- a/internal/service/codeartifact/authorization_token_data_source_test.go +++ b/internal/service/codeartifact/authorization_token_data_source_test.go @@ -20,7 +20,7 @@ func testAccAuthorizationTokenDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAuthorizationTokenBasicConfig(rName), + Config: testAccAuthorizationTokenDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "authorization_token"), resource.TestCheckResourceAttrSet(dataSourceName, "expiration"), @@ -41,7 +41,7 @@ func testAccAuthorizationTokenDataSource_owner(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAuthorizationTokenOwnerConfig(rName), + Config: testAccAuthorizationTokenDataSourceConfig_owner(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "authorization_token"), resource.TestCheckResourceAttrSet(dataSourceName, "expiration"), @@ -62,7 +62,7 @@ func testAccAuthorizationTokenDataSource_duration(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAuthorizationTokenDurationConfig(rName), + Config: testAccAuthorizationTokenDataSourceConfig_duration(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "authorization_token"), resource.TestCheckResourceAttrSet(dataSourceName, "expiration"), @@ -88,7 +88,7 @@ resource "aws_codeartifact_domain" "test" { `, rName) } -func testAccCheckAuthorizationTokenBasicConfig(rName string) string { +func testAccAuthorizationTokenDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( testAccCheckAuthorizationTokenBaseConfig(rName), ` @@ -98,7 +98,7 @@ data "aws_codeartifact_authorization_token" "test" { `) } -func testAccCheckAuthorizationTokenOwnerConfig(rName string) string { +func testAccAuthorizationTokenDataSourceConfig_owner(rName string) string { return acctest.ConfigCompose( testAccCheckAuthorizationTokenBaseConfig(rName), ` @@ -109,7 +109,7 @@ data "aws_codeartifact_authorization_token" "test" { `) } -func testAccCheckAuthorizationTokenDurationConfig(rName string) string { +func testAccAuthorizationTokenDataSourceConfig_duration(rName string) string { return acctest.ConfigCompose( testAccCheckAuthorizationTokenBaseConfig(rName), ` diff --git a/internal/service/codeartifact/domain_permissions_policy_test.go b/internal/service/codeartifact/domain_permissions_policy_test.go index ac179005279..a66afd95676 100644 --- a/internal/service/codeartifact/domain_permissions_policy_test.go +++ b/internal/service/codeartifact/domain_permissions_policy_test.go @@ -27,7 +27,7 @@ func testAccDomainPermissionsPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckDomainPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainPermissionsPolicyBasicConfig(rName), + Config: testAccDomainPermissionsPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainPermissionsExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_codeartifact_domain.test", "arn"), @@ -42,7 +42,7 @@ func testAccDomainPermissionsPolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainPermissionsPolicyUpdatedConfig(rName), + Config: testAccDomainPermissionsPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainPermissionsExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_codeartifact_domain.test", "arn"), @@ -67,7 +67,7 @@ func testAccDomainPermissionsPolicy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckDomainPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainPermissionsPolicyOrderConfig(rName), + Config: testAccDomainPermissionsPolicyConfig_order(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainPermissionsExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_codeartifact_domain.test", "arn"), @@ -78,7 +78,7 @@ func testAccDomainPermissionsPolicy_ignoreEquivalent(t *testing.T) { ), }, { - Config: testAccDomainPermissionsPolicyNewOrderConfig(rName), + Config: testAccDomainPermissionsPolicyConfig_newOrder(rName), PlanOnly: true, }, }, @@ -96,7 +96,7 @@ func testAccDomainPermissionsPolicy_owner(t *testing.T) { CheckDestroy: testAccCheckDomainPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainPermissionsPolicyOwnerConfig(rName), + Config: testAccDomainPermissionsPolicyConfig_owner(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainPermissionsExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_codeartifact_domain.test", "arn"), @@ -125,7 +125,7 @@ func testAccDomainPermissionsPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckDomainPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainPermissionsPolicyBasicConfig(rName), + Config: testAccDomainPermissionsPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainPermissionsExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcodeartifact.ResourceDomainPermissionsPolicy(), resourceName), @@ -147,7 +147,7 @@ func testAccDomainPermissionsPolicy_Disappears_domain(t *testing.T) { CheckDestroy: testAccCheckDomainPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainPermissionsPolicyBasicConfig(rName), + Config: testAccDomainPermissionsPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainPermissionsExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcodeartifact.ResourceDomain(), resourceName), @@ -219,7 +219,7 @@ func testAccCheckDomainPermissionsDestroy(s *terraform.State) error { return nil } -func testAccDomainPermissionsPolicyBasicConfig(rName string) string { +func testAccDomainPermissionsPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -250,7 +250,7 @@ EOF `, rName) } -func testAccDomainPermissionsPolicyOwnerConfig(rName string) string { +func testAccDomainPermissionsPolicyConfig_owner(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -282,7 +282,7 @@ EOF `, rName) } -func testAccDomainPermissionsPolicyUpdatedConfig(rName string) string { +func testAccDomainPermissionsPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -316,7 +316,7 @@ EOF `, rName) } -func testAccDomainPermissionsPolicyOrderConfig(rName string) string { +func testAccDomainPermissionsPolicyConfig_order(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -346,7 +346,7 @@ resource "aws_codeartifact_domain_permissions_policy" "test" { `, rName) } -func testAccDomainPermissionsPolicyNewOrderConfig(rName string) string { +func testAccDomainPermissionsPolicyConfig_newOrder(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q diff --git a/internal/service/codeartifact/domain_test.go b/internal/service/codeartifact/domain_test.go index 6c5701a1309..d4be5675337 100644 --- a/internal/service/codeartifact/domain_test.go +++ b/internal/service/codeartifact/domain_test.go @@ -27,7 +27,7 @@ func testAccDomain_basic(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainBasicConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "codeartifact", fmt.Sprintf("domain/%s", rName)), @@ -60,7 +60,7 @@ func testAccDomain_defaultEncryptionKey(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainDefaultEncryptionKeyConfig(rName), + Config: testAccDomainConfig_defaultEncryptionKey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "codeartifact", fmt.Sprintf("domain/%s", rName)), @@ -92,7 +92,7 @@ func testAccDomain_tags(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainTags1Config(rName, "key1", "value1"), + Config: testAccDomainConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -105,7 +105,7 @@ func testAccDomain_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDomainConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -114,7 +114,7 @@ func testAccDomain_tags(t *testing.T) { ), }, { - Config: testAccDomainTags1Config(rName, "key2", "value2"), + Config: testAccDomainConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -135,7 +135,7 @@ func testAccDomain_disappears(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainDefaultEncryptionKeyConfig(rName), + Config: testAccDomainConfig_defaultEncryptionKey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcodeartifact.ResourceDomain(), resourceName), @@ -207,7 +207,7 @@ func testAccCheckDomainDestroy(s *terraform.State) error { return nil } -func testAccDomainBasicConfig(rName string) string { +func testAccDomainConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -221,7 +221,7 @@ resource "aws_codeartifact_domain" "test" { `, rName) } -func testAccDomainTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccDomainConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_codeartifact_domain" "test" { domain = %[1]q @@ -233,7 +233,7 @@ resource "aws_codeartifact_domain" "test" { `, rName, tagKey1, tagValue1) } -func testAccDomainTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDomainConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_codeartifact_domain" "test" { domain = %[1]q @@ -246,7 +246,7 @@ resource "aws_codeartifact_domain" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccDomainDefaultEncryptionKeyConfig(rName string) string { +func testAccDomainConfig_defaultEncryptionKey(rName string) string { return fmt.Sprintf(` resource "aws_codeartifact_domain" "test" { domain = %[1]q diff --git a/internal/service/codeartifact/repository_endpoint_data_source_test.go b/internal/service/codeartifact/repository_endpoint_data_source_test.go index 5a5b6470e37..2a0ffae55d1 100644 --- a/internal/service/codeartifact/repository_endpoint_data_source_test.go +++ b/internal/service/codeartifact/repository_endpoint_data_source_test.go @@ -20,28 +20,28 @@ func testAccRepositoryEndpointDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckRepositoryEndpointBasicConfig(rName, "npm"), + Config: testAccRepositoryEndpointDataSourceConfig_basic(rName, "npm"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "repository_endpoint"), acctest.CheckResourceAttrAccountID(dataSourceName, "domain_owner"), ), }, { - Config: testAccCheckRepositoryEndpointBasicConfig(rName, "pypi"), + Config: testAccRepositoryEndpointDataSourceConfig_basic(rName, "pypi"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "repository_endpoint"), acctest.CheckResourceAttrAccountID(dataSourceName, "domain_owner"), ), }, { - Config: testAccCheckRepositoryEndpointBasicConfig(rName, "maven"), + Config: testAccRepositoryEndpointDataSourceConfig_basic(rName, "maven"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "repository_endpoint"), acctest.CheckResourceAttrAccountID(dataSourceName, "domain_owner"), ), }, { - Config: testAccCheckRepositoryEndpointBasicConfig(rName, "nuget"), + Config: testAccRepositoryEndpointDataSourceConfig_basic(rName, "nuget"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "repository_endpoint"), acctest.CheckResourceAttrAccountID(dataSourceName, "domain_owner"), @@ -61,7 +61,7 @@ func testAccRepositoryEndpointDataSource_owner(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckRepositoryEndpointOwnerConfig(rName), + Config: testAccRepositoryEndpointDataSourceConfig_owner(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "repository_endpoint"), acctest.CheckResourceAttrAccountID(dataSourceName, "domain_owner"), @@ -90,7 +90,7 @@ resource "aws_codeartifact_repository" "test" { `, rName) } -func testAccCheckRepositoryEndpointBasicConfig(rName, format string) string { +func testAccRepositoryEndpointDataSourceConfig_basic(rName, format string) string { return acctest.ConfigCompose( testAccCheckRepositoryEndpointBaseConfig(rName), fmt.Sprintf(` @@ -102,7 +102,7 @@ data "aws_codeartifact_repository_endpoint" "test" { `, format)) } -func testAccCheckRepositoryEndpointOwnerConfig(rName string) string { +func testAccRepositoryEndpointDataSourceConfig_owner(rName string) string { return acctest.ConfigCompose( testAccCheckRepositoryEndpointBaseConfig(rName), ` diff --git a/internal/service/codeartifact/repository_permissions_policy_test.go b/internal/service/codeartifact/repository_permissions_policy_test.go index bb876475b6f..193384e1eab 100644 --- a/internal/service/codeartifact/repository_permissions_policy_test.go +++ b/internal/service/codeartifact/repository_permissions_policy_test.go @@ -27,7 +27,7 @@ func testAccRepositoryPermissionsPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckRepositoryPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPermissionsPolicyBasicConfig(rName), + Config: testAccRepositoryPermissionsPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPermissionsExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_codeartifact_repository.test", "arn"), @@ -42,7 +42,7 @@ func testAccRepositoryPermissionsPolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryPermissionsPolicyUpdatedConfig(rName), + Config: testAccRepositoryPermissionsPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPermissionsExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_codeartifact_repository.test", "arn"), @@ -67,7 +67,7 @@ func testAccRepositoryPermissionsPolicy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckRepositoryPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPermissionsPolicyOrderConfig(rName), + Config: testAccRepositoryPermissionsPolicyConfig_order(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPermissionsExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_codeartifact_repository.test", "arn"), @@ -77,7 +77,7 @@ func testAccRepositoryPermissionsPolicy_ignoreEquivalent(t *testing.T) { ), }, { - Config: testAccRepositoryPermissionsPolicyNewOrderConfig(rName), + Config: testAccRepositoryPermissionsPolicyConfig_newOrder(rName), PlanOnly: true, }, }, @@ -95,7 +95,7 @@ func testAccRepositoryPermissionsPolicy_owner(t *testing.T) { CheckDestroy: testAccCheckRepositoryPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPermissionsPolicyOwnerConfig(rName), + Config: testAccRepositoryPermissionsPolicyConfig_owner(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPermissionsExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_codeartifact_repository.test", "arn"), @@ -124,7 +124,7 @@ func testAccRepositoryPermissionsPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckRepositoryPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPermissionsPolicyBasicConfig(rName), + Config: testAccRepositoryPermissionsPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPermissionsExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcodeartifact.ResourceRepositoryPermissionsPolicy(), resourceName), @@ -146,7 +146,7 @@ func testAccRepositoryPermissionsPolicy_Disappears_domain(t *testing.T) { CheckDestroy: testAccCheckRepositoryPermissionsDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPermissionsPolicyBasicConfig(rName), + Config: testAccRepositoryPermissionsPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPermissionsExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcodeartifact.ResourceRepositoryPermissionsPolicy(), resourceName), @@ -220,7 +220,7 @@ func testAccCheckRepositoryPermissionsDestroy(s *terraform.State) error { return nil } -func testAccRepositoryPermissionsPolicyBasicConfig(rName string) string { +func testAccRepositoryPermissionsPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -257,7 +257,7 @@ EOF `, rName) } -func testAccRepositoryPermissionsPolicyOwnerConfig(rName string) string { +func testAccRepositoryPermissionsPolicyConfig_owner(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -295,7 +295,7 @@ EOF `, rName) } -func testAccRepositoryPermissionsPolicyUpdatedConfig(rName string) string { +func testAccRepositoryPermissionsPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -335,7 +335,7 @@ EOF `, rName) } -func testAccRepositoryPermissionsPolicyOrderConfig(rName string) string { +func testAccRepositoryPermissionsPolicyConfig_order(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -371,7 +371,7 @@ resource "aws_codeartifact_repository_permissions_policy" "test" { `, rName) } -func testAccRepositoryPermissionsPolicyNewOrderConfig(rName string) string { +func testAccRepositoryPermissionsPolicyConfig_newOrder(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q diff --git a/internal/service/codeartifact/repository_test.go b/internal/service/codeartifact/repository_test.go index ab4611621ef..67bc4cc3a5a 100644 --- a/internal/service/codeartifact/repository_test.go +++ b/internal/service/codeartifact/repository_test.go @@ -26,7 +26,7 @@ func testAccRepository_basic(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryBasicConfig(rName), + Config: testAccRepositoryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "codeartifact", fmt.Sprintf("repository/%s/%s", rName, rName)), @@ -104,7 +104,7 @@ func testAccRepository_owner(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryOwnerConfig(rName), + Config: testAccRepositoryConfig_owner(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "codeartifact", fmt.Sprintf("repository/%s/%s", rName, rName)), @@ -137,7 +137,7 @@ func testAccRepository_description(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryDescConfig(rName, "desc"), + Config: testAccRepositoryConfig_desc(rName, "desc"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "desc"), @@ -149,7 +149,7 @@ func testAccRepository_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryDescConfig(rName, "desc2"), + Config: testAccRepositoryConfig_desc(rName, "desc2"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "desc2"), @@ -170,7 +170,7 @@ func testAccRepository_upstreams(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryUpstreams1Config(rName), + Config: testAccRepositoryConfig_upstreams1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "upstream.#", "1"), @@ -183,7 +183,7 @@ func testAccRepository_upstreams(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryUpstreams2Config(rName), + Config: testAccRepositoryConfig_upstreams2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "upstream.#", "2"), @@ -192,7 +192,7 @@ func testAccRepository_upstreams(t *testing.T) { ), }, { - Config: testAccRepositoryUpstreams1Config(rName), + Config: testAccRepositoryConfig_upstreams1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "upstream.#", "1"), @@ -214,7 +214,7 @@ func testAccRepository_externalConnection(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryExternalConnectionConfig(rName), + Config: testAccRepositoryConfig_externalConnection(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "external_connections.#", "1"), @@ -229,14 +229,14 @@ func testAccRepository_externalConnection(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryBasicConfig(rName), + Config: testAccRepositoryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "external_connections.#", "0"), ), }, { - Config: testAccRepositoryExternalConnectionConfig(rName), + Config: testAccRepositoryConfig_externalConnection(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "external_connections.#", "1"), @@ -260,7 +260,7 @@ func testAccRepository_disappears(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryBasicConfig(rName), + Config: testAccRepositoryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcodeartifact.ResourceRepository(), resourceName), @@ -346,7 +346,7 @@ resource "aws_codeartifact_domain" "test" { `, rName) } -func testAccRepositoryBasicConfig(rName string) string { +func testAccRepositoryConfig_basic(rName string) string { return testAccRepositoryBaseConfig(rName) + fmt.Sprintf(` resource "aws_codeartifact_repository" "test" { repository = %[1]q @@ -355,7 +355,7 @@ resource "aws_codeartifact_repository" "test" { `, rName) } -func testAccRepositoryOwnerConfig(rName string) string { +func testAccRepositoryConfig_owner(rName string) string { return testAccRepositoryBaseConfig(rName) + fmt.Sprintf(` resource "aws_codeartifact_repository" "test" { repository = %[1]q @@ -365,7 +365,7 @@ resource "aws_codeartifact_repository" "test" { `, rName) } -func testAccRepositoryDescConfig(rName, desc string) string { +func testAccRepositoryConfig_desc(rName, desc string) string { return testAccRepositoryBaseConfig(rName) + fmt.Sprintf(` resource "aws_codeartifact_repository" "test" { repository = %[1]q @@ -375,7 +375,7 @@ resource "aws_codeartifact_repository" "test" { `, rName, desc) } -func testAccRepositoryUpstreams1Config(rName string) string { +func testAccRepositoryConfig_upstreams1(rName string) string { return testAccRepositoryBaseConfig(rName) + fmt.Sprintf(` resource "aws_codeartifact_repository" "upstream1" { repository = "%[1]s-upstream1" @@ -393,7 +393,7 @@ resource "aws_codeartifact_repository" "test" { `, rName) } -func testAccRepositoryUpstreams2Config(rName string) string { +func testAccRepositoryConfig_upstreams2(rName string) string { return testAccRepositoryBaseConfig(rName) + fmt.Sprintf(` resource "aws_codeartifact_repository" "upstream1" { repository = "%[1]s-upstream1" @@ -420,7 +420,7 @@ resource "aws_codeartifact_repository" "test" { `, rName) } -func testAccRepositoryExternalConnectionConfig(rName string) string { +func testAccRepositoryConfig_externalConnection(rName string) string { return testAccRepositoryBaseConfig(rName) + fmt.Sprintf(` resource "aws_codeartifact_repository" "test" { repository = %[1]q diff --git a/internal/service/codebuild/project.go b/internal/service/codebuild/project.go index 2778cce2d06..dc306a899b2 100644 --- a/internal/service/codebuild/project.go +++ b/internal/service/codebuild/project.go @@ -742,7 +742,7 @@ func resourceProjectCreate(d *schema.ResourceData, meta interface{}) error { projectSecondaryArtifacts := expandProjectSecondaryArtifacts(d) projectSecondarySources := expandProjectSecondarySources(d) projectLogsConfig := expandProjectLogsConfig(d) - projectBatchConfig := expandCodeBuildBuildBatchConfig(d) + projectBatchConfig := expandBuildBatchConfig(d) projectFileSystemLocations := expandProjectFileSystemLocations(d) if aws.StringValue(projectSource.Type) == codebuild.SourceTypeNoSource { @@ -801,7 +801,7 @@ func resourceProjectCreate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("vpc_config"); ok { - params.VpcConfig = expandCodeBuildVpcConfig(v.([]interface{})) + params.VpcConfig = expandVPCConfig(v.([]interface{})) } if v, ok := d.GetOk("badge_enabled"); ok { @@ -1106,11 +1106,11 @@ func expandProjectLogsConfig(d *schema.ResourceData) *codebuild.LogsConfig { data := configList[0].(map[string]interface{}) if v, ok := data["cloudwatch_logs"]; ok { - logsConfig.CloudWatchLogs = expandCodeBuildCloudWatchLogsConfig(v.([]interface{})) + logsConfig.CloudWatchLogs = expandCloudWatchLogsConfig(v.([]interface{})) } if v, ok := data["s3_logs"]; ok { - logsConfig.S3Logs = expandCodeBuildS3LogsConfig(v.([]interface{})) + logsConfig.S3Logs = expandS3LogsConfig(v.([]interface{})) } } @@ -1129,7 +1129,7 @@ func expandProjectLogsConfig(d *schema.ResourceData) *codebuild.LogsConfig { return logsConfig } -func expandCodeBuildBuildBatchConfig(d *schema.ResourceData) *codebuild.ProjectBuildBatchConfig { +func expandBuildBatchConfig(d *schema.ResourceData) *codebuild.ProjectBuildBatchConfig { configs, ok := d.Get("build_batch_config").([]interface{}) if !ok || len(configs) == 0 || configs[0] == nil { return nil @@ -1138,7 +1138,7 @@ func expandCodeBuildBuildBatchConfig(d *schema.ResourceData) *codebuild.ProjectB data := configs[0].(map[string]interface{}) projectBuildBatchConfig := &codebuild.ProjectBuildBatchConfig{ - Restrictions: expandCodeBuildBatchRestrictions(data), + Restrictions: expandBatchRestrictions(data), ServiceRole: aws.String(data["service_role"].(string)), } @@ -1153,7 +1153,7 @@ func expandCodeBuildBuildBatchConfig(d *schema.ResourceData) *codebuild.ProjectB return projectBuildBatchConfig } -func expandCodeBuildBatchRestrictions(data map[string]interface{}) *codebuild.BatchRestrictions { +func expandBatchRestrictions(data map[string]interface{}) *codebuild.BatchRestrictions { if v, ok := data["restrictions"]; !ok || len(v.([]interface{})) == 0 || v.([]interface{})[0] == nil { return nil } @@ -1172,7 +1172,7 @@ func expandCodeBuildBatchRestrictions(data map[string]interface{}) *codebuild.Ba return restrictions } -func expandCodeBuildCloudWatchLogsConfig(configList []interface{}) *codebuild.CloudWatchLogsConfig { +func expandCloudWatchLogsConfig(configList []interface{}) *codebuild.CloudWatchLogsConfig { if len(configList) == 0 || configList[0] == nil { return nil } @@ -1202,7 +1202,7 @@ func expandCodeBuildCloudWatchLogsConfig(configList []interface{}) *codebuild.Cl return cloudWatchLogsConfig } -func expandCodeBuildS3LogsConfig(configList []interface{}) *codebuild.S3LogsConfig { +func expandS3LogsConfig(configList []interface{}) *codebuild.S3LogsConfig { if len(configList) == 0 || configList[0] == nil { return nil } @@ -1228,7 +1228,7 @@ func expandCodeBuildS3LogsConfig(configList []interface{}) *codebuild.S3LogsConf return s3LogsConfig } -func expandCodeBuildVpcConfig(rawVpcConfig []interface{}) *codebuild.VpcConfig { +func expandVPCConfig(rawVpcConfig []interface{}) *codebuild.VpcConfig { vpcConfig := codebuild.VpcConfig{} if len(rawVpcConfig) == 0 || rawVpcConfig[0] == nil { return &vpcConfig @@ -1382,7 +1382,7 @@ func resourceProjectRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting secondary_sources: %w", err) } - if err := d.Set("secondary_source_version", flattenAwsCodeBuildProjectSecondarySourceVersions(project.SecondarySourceVersions)); err != nil { + if err := d.Set("secondary_source_version", flattenProjectSecondarySourceVersions(project.SecondarySourceVersions)); err != nil { return fmt.Errorf("error setting secondary_source_version: %w", err) } @@ -1515,7 +1515,7 @@ func resourceProjectUpdate(d *schema.ResourceData, meta interface{}) error { } if d.HasChange("vpc_config") { - params.VpcConfig = expandCodeBuildVpcConfig(d.Get("vpc_config").([]interface{})) + params.VpcConfig = expandVPCConfig(d.Get("vpc_config").([]interface{})) } if d.HasChange("logs_config") { @@ -1524,7 +1524,7 @@ func resourceProjectUpdate(d *schema.ResourceData, meta interface{}) error { } if d.HasChange("build_batch_config") { - params.BuildBatchConfig = expandCodeBuildBuildBatchConfig(d) + params.BuildBatchConfig = expandBuildBatchConfig(d) } if d.HasChange("cache") { @@ -1850,16 +1850,16 @@ func flattenProjectSourceData(source *codebuild.ProjectSource) interface{} { return m } -func flattenAwsCodeBuildProjectSecondarySourceVersions(sourceVersions []*codebuild.ProjectSourceVersion) []interface{} { +func flattenProjectSecondarySourceVersions(sourceVersions []*codebuild.ProjectSourceVersion) []interface{} { l := make([]interface{}, 0) for _, sourceVersion := range sourceVersions { - l = append(l, flattenAwsCodeBuildProjectsourceVersionsData(sourceVersion)) + l = append(l, flattenProjectSourceVersionsData(sourceVersion)) } return l } -func flattenAwsCodeBuildProjectsourceVersionsData(sourceVersion *codebuild.ProjectSourceVersion) map[string]interface{} { +func flattenProjectSourceVersionsData(sourceVersion *codebuild.ProjectSourceVersion) map[string]interface{} { values := map[string]interface{}{} if sourceVersion.SourceIdentifier != nil { diff --git a/internal/service/codebuild/project_test.go b/internal/service/codebuild/project_test.go index ea3ba84c772..2a21489ee45 100644 --- a/internal/service/codebuild/project_test.go +++ b/internal/service/codebuild/project_test.go @@ -18,10 +18,10 @@ import ( ) func init() { - acctest.RegisterServiceErrorCheckFunc(codebuild.EndpointsID, testAccErrorCheckSkipCodebuild) + acctest.RegisterServiceErrorCheckFunc(codebuild.EndpointsID, testAccErrorCheckSkip) } -func testAccErrorCheckSkipCodebuild(t *testing.T) resource.ErrorCheckFunc { +func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { return acctest.ErrorCheckSkipMessagesContaining(t, "InvalidInputException: Region", ) @@ -126,7 +126,7 @@ func TestAccCodeBuildProject_publicVisibility(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_projectVisibility(rName, "PUBLIC_READ"), + Config: testAccProjectConfig_visibility(rName, "PUBLIC_READ"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "project_visibility", "PUBLIC_READ"), @@ -139,14 +139,14 @@ func TestAccCodeBuildProject_publicVisibility(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_projectVisibility(rName, "PRIVATE"), + Config: testAccProjectConfig_visibility(rName, "PRIVATE"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "project_visibility", "PRIVATE"), ), }, { - Config: testAccProjectConfig_projectVisibility_resourceRole(rName, "PRIVATE"), + Config: testAccProjectConfig_visibilityResourceRole(rName, "PRIVATE"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "project_visibility", "PRIVATE"), @@ -169,7 +169,7 @@ func TestAccCodeBuildProject_badgeEnabled(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_BadgeEnabled(rName, true), + Config: testAccProjectConfig_badgeEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "badge_enabled", "true"), @@ -197,7 +197,7 @@ func TestAccCodeBuildProject_buildTimeout(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_BuildTimeout(rName, 120), + Config: testAccProjectConfig_buildTimeout(rName, 120), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "build_timeout", "120"), @@ -209,7 +209,7 @@ func TestAccCodeBuildProject_buildTimeout(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_BuildTimeout(rName, 240), + Config: testAccProjectConfig_buildTimeout(rName, 240), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "build_timeout", "240"), @@ -231,7 +231,7 @@ func TestAccCodeBuildProject_queuedTimeout(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_QueuedTimeout(rName, 120), + Config: testAccProjectConfig_queuedTimeout(rName, 120), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "queued_timeout", "120"), @@ -243,7 +243,7 @@ func TestAccCodeBuildProject_queuedTimeout(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_QueuedTimeout(rName, 240), + Config: testAccProjectConfig_queuedTimeout(rName, 240), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "queued_timeout", "240"), @@ -267,11 +267,11 @@ func TestAccCodeBuildProject_cache(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Cache(rName, "", "S3"), + Config: testAccProjectConfig_cache(rName, "", "S3"), ExpectError: regexp.MustCompile(`cache location is required when cache type is "S3"`), }, { - Config: testAccProjectConfig_Cache(rName, "", codebuild.CacheTypeNoCache), + Config: testAccProjectConfig_cache(rName, "", codebuild.CacheTypeNoCache), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "cache.#", "1"), @@ -292,7 +292,7 @@ func TestAccCodeBuildProject_cache(t *testing.T) { ), }, { - Config: testAccProjectConfig_Cache(rName, s3Location1, "S3"), + Config: testAccProjectConfig_cache(rName, s3Location1, "S3"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "cache.#", "1"), @@ -301,7 +301,7 @@ func TestAccCodeBuildProject_cache(t *testing.T) { ), }, { - Config: testAccProjectConfig_Cache(rName, s3Location2, "S3"), + Config: testAccProjectConfig_cache(rName, s3Location2, "S3"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "cache.#", "1"), @@ -318,7 +318,7 @@ func TestAccCodeBuildProject_cache(t *testing.T) { ), }, { - Config: testAccProjectConfig_LocalCache(rName, "LOCAL_DOCKER_LAYER_CACHE"), + Config: testAccProjectConfig_localCache(rName, "LOCAL_DOCKER_LAYER_CACHE"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "cache.#", "1"), @@ -327,7 +327,7 @@ func TestAccCodeBuildProject_cache(t *testing.T) { ), }, { - Config: testAccProjectConfig_S3_ComputedLocation(rName), + Config: testAccProjectConfig_s3ComputedLocation(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "cache.#", "1"), @@ -350,7 +350,7 @@ func TestAccCodeBuildProject_description(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Description(rName, "description1"), + Config: testAccProjectConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -362,7 +362,7 @@ func TestAccCodeBuildProject_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Description(rName, "description2"), + Config: testAccProjectConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -384,7 +384,7 @@ func TestAccCodeBuildProject_fileSystemLocations(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_FileSystemLocations(rName, "/mount1"), + Config: testAccProjectConfig_fileSystemLocations(rName, "/mount1"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "environment.#", "1"), @@ -407,7 +407,7 @@ func TestAccCodeBuildProject_fileSystemLocations(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_FileSystemLocations(rName, "/mount2"), + Config: testAccProjectConfig_fileSystemLocations(rName, "/mount2"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "file_system_locations.#", "1"), @@ -434,7 +434,7 @@ func TestAccCodeBuildProject_sourceVersion(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SourceVersion(rName, "master"), + Config: testAccProjectConfig_sourceVersion(rName, "master"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source_version", "master"), @@ -456,7 +456,7 @@ func TestAccCodeBuildProject_encryptionKey(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_EncryptionKey(rName), + Config: testAccProjectConfig_encryptionKey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttrPair(resourceName, "encryption_key", "aws_kms_key.test", "arn"), @@ -483,7 +483,7 @@ func TestAccCodeBuildProject_Environment_environmentVariable(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Environment_EnvironmentVariable_One(rName, "KEY1", "VALUE1"), + Config: testAccProjectConfig_environmentVariableOne(rName, "KEY1", "VALUE1"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project1), ), @@ -494,7 +494,7 @@ func TestAccCodeBuildProject_Environment_environmentVariable(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Environment_EnvironmentVariable_Two(rName, "KEY1", "VALUE1UPDATED", "KEY2", "VALUE2"), + Config: testAccProjectConfig_environmentVariableTwo(rName, "KEY1", "VALUE1UPDATED", "KEY2", "VALUE2"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project2), ), @@ -505,7 +505,7 @@ func TestAccCodeBuildProject_Environment_environmentVariable(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Environment_EnvironmentVariable_Zero(rName), + Config: testAccProjectConfig_environmentVariableZero(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project3), resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.#", "0"), @@ -532,7 +532,7 @@ func TestAccCodeBuildProject_EnvironmentEnvironmentVariable_type(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Environment_EnvironmentVariable_Type(rName, codebuild.EnvironmentVariableTypePlaintext), + Config: testAccProjectConfig_environmentVariableType(rName, codebuild.EnvironmentVariableTypePlaintext), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.0.type", codebuild.EnvironmentVariableTypePlaintext), @@ -545,7 +545,7 @@ func TestAccCodeBuildProject_EnvironmentEnvironmentVariable_type(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Environment_EnvironmentVariable_Type(rName, codebuild.EnvironmentVariableTypeParameterStore), + Config: testAccProjectConfig_environmentVariableType(rName, codebuild.EnvironmentVariableTypeParameterStore), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.0.type", codebuild.EnvironmentVariableTypePlaintext), @@ -553,7 +553,7 @@ func TestAccCodeBuildProject_EnvironmentEnvironmentVariable_type(t *testing.T) { ), }, { - Config: testAccProjectConfig_Environment_EnvironmentVariable_Type(rName, codebuild.EnvironmentVariableTypeSecretsManager), + Config: testAccProjectConfig_environmentVariableType(rName, codebuild.EnvironmentVariableTypeSecretsManager), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.0.type", codebuild.EnvironmentVariableTypePlaintext), @@ -576,7 +576,7 @@ func TestAccCodeBuildProject_EnvironmentEnvironmentVariable_value(t *testing.T) CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Environment_EnvironmentVariable_One(rName, "KEY1", ""), + Config: testAccProjectConfig_environmentVariableOne(rName, "KEY1", ""), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project1), ), @@ -587,7 +587,7 @@ func TestAccCodeBuildProject_EnvironmentEnvironmentVariable_value(t *testing.T) ImportStateVerify: true, }, { - Config: testAccProjectConfig_Environment_EnvironmentVariable_One(rName, "KEY1", "VALUE1"), + Config: testAccProjectConfig_environmentVariableOne(rName, "KEY1", "VALUE1"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project2), ), @@ -598,7 +598,7 @@ func TestAccCodeBuildProject_EnvironmentEnvironmentVariable_value(t *testing.T) ImportStateVerify: true, }, { - Config: testAccProjectConfig_Environment_EnvironmentVariable_One(rName, "KEY1", ""), + Config: testAccProjectConfig_environmentVariableOne(rName, "KEY1", ""), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project3), ), @@ -625,7 +625,7 @@ func TestAccCodeBuildProject_Environment_certificate(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Environment_Certificate(rName, oName), + Config: testAccProjectConfig_environmentCertificate(rName, oName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), testAccCheckProjectCertificate(&project, fmt.Sprintf("%s/%s", rName, oName)), @@ -652,7 +652,7 @@ func TestAccCodeBuildProject_Logs_cloudWatchLogs(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_LogsConfig_CloudWatchLogs(rName, codebuild.LogsConfigStatusTypeEnabled, "group-name", ""), + Config: testAccProjectConfig_cloudWatchLogs(rName, codebuild.LogsConfigStatusTypeEnabled, "group-name", ""), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", codebuild.LogsConfigStatusTypeEnabled), @@ -661,7 +661,7 @@ func TestAccCodeBuildProject_Logs_cloudWatchLogs(t *testing.T) { ), }, { - Config: testAccProjectConfig_LogsConfig_CloudWatchLogs(rName, codebuild.LogsConfigStatusTypeEnabled, "group-name", "stream-name"), + Config: testAccProjectConfig_cloudWatchLogs(rName, codebuild.LogsConfigStatusTypeEnabled, "group-name", "stream-name"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", codebuild.LogsConfigStatusTypeEnabled), @@ -670,7 +670,7 @@ func TestAccCodeBuildProject_Logs_cloudWatchLogs(t *testing.T) { ), }, { - Config: testAccProjectConfig_LogsConfig_CloudWatchLogs(rName, codebuild.LogsConfigStatusTypeDisabled, "", ""), + Config: testAccProjectConfig_cloudWatchLogs(rName, codebuild.LogsConfigStatusTypeDisabled, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", codebuild.LogsConfigStatusTypeDisabled), @@ -697,7 +697,7 @@ func TestAccCodeBuildProject_Logs_s3Logs(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_LogsConfig_S3Logs(rName, codebuild.LogsConfigStatusTypeEnabled, rName+"/build-log", false), + Config: testAccProjectConfig_s3Logs(rName, codebuild.LogsConfigStatusTypeEnabled, rName+"/build-log", false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", codebuild.LogsConfigStatusTypeEnabled), @@ -706,7 +706,7 @@ func TestAccCodeBuildProject_Logs_s3Logs(t *testing.T) { ), }, { - Config: testAccProjectConfig_LogsConfig_S3Logs(rName, codebuild.LogsConfigStatusTypeEnabled, rName+"/build-log", true), + Config: testAccProjectConfig_s3Logs(rName, codebuild.LogsConfigStatusTypeEnabled, rName+"/build-log", true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", codebuild.LogsConfigStatusTypeEnabled), @@ -715,7 +715,7 @@ func TestAccCodeBuildProject_Logs_s3Logs(t *testing.T) { ), }, { - Config: testAccProjectConfig_LogsConfig_S3Logs(rName, codebuild.LogsConfigStatusTypeDisabled, "", false), + Config: testAccProjectConfig_s3Logs(rName, codebuild.LogsConfigStatusTypeDisabled, "", false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", codebuild.LogsConfigStatusTypeDisabled), @@ -746,7 +746,7 @@ func TestAccCodeBuildProject_buildBatch(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_BuildBatchConfig(rName, true, "BUILD_GENERAL1_SMALL", 10, 5), + Config: testAccProjectConfig_buildBatch(rName, true, "BUILD_GENERAL1_SMALL", 10, 5), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "build_batch_config.0.combine_artifacts", "true"), @@ -763,7 +763,7 @@ func TestAccCodeBuildProject_buildBatch(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_BuildBatchConfig(rName, false, "BUILD_GENERAL1_MEDIUM", 20, 10), + Config: testAccProjectConfig_buildBatch(rName, false, "BUILD_GENERAL1_MEDIUM", 20, 10), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "build_batch_config.0.combine_artifacts", "false"), @@ -790,7 +790,7 @@ func TestAccCodeBuildProject_Source_gitCloneDepth(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_GitCloneDepth(rName, 1), + Config: testAccProjectConfig_sourceGitCloneDepth(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.git_clone_depth", "1"), @@ -802,7 +802,7 @@ func TestAccCodeBuildProject_Source_gitCloneDepth(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Source_GitCloneDepth(rName, 2), + Config: testAccProjectConfig_sourceGitCloneDepth(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.git_clone_depth", "2"), @@ -824,7 +824,7 @@ func TestAccCodeBuildProject_SourceGitSubmodules_codeCommit(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_GitSubmodulesConfig_CodeCommit(rName, true), + Config: testAccProjectConfig_sourceGitSubmodulesCodeCommit(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.git_submodules_config.#", "1"), @@ -837,7 +837,7 @@ func TestAccCodeBuildProject_SourceGitSubmodules_codeCommit(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Source_GitSubmodulesConfig_CodeCommit(rName, false), + Config: testAccProjectConfig_sourceGitSubmodulesCodeCommit(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.git_submodules_config.#", "1"), @@ -860,7 +860,7 @@ func TestAccCodeBuildProject_SourceGitSubmodules_gitHub(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_GitSubmodulesConfig_GitHub(rName, true), + Config: testAccProjectConfig_sourceGitSubmodulesGitHub(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -871,7 +871,7 @@ func TestAccCodeBuildProject_SourceGitSubmodules_gitHub(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Source_GitSubmodulesConfig_GitHub(rName, false), + Config: testAccProjectConfig_sourceGitSubmodulesGitHub(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -892,7 +892,7 @@ func TestAccCodeBuildProject_SourceGitSubmodules_gitHubEnterprise(t *testing.T) CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_GitSubmodulesConfig_GitHubEnterprise(rName, true), + Config: testAccProjectConfig_sourceGitSubmodulesGitHubEnterprise(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -903,7 +903,7 @@ func TestAccCodeBuildProject_SourceGitSubmodules_gitHubEnterprise(t *testing.T) ImportStateVerify: true, }, { - Config: testAccProjectConfig_Source_GitSubmodulesConfig_GitHubEnterprise(rName, false), + Config: testAccProjectConfig_sourceGitSubmodulesGitHubEnterprise(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -924,7 +924,7 @@ func TestAccCodeBuildProject_SecondarySourcesGitSubmodules_codeCommit(t *testing CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondarySources_GitSubmodulesConfig_CodeCommit(rName, true), + Config: testAccProjectConfig_secondarySourcesGitSubmodulesCodeCommit(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_sources.#", "2"), @@ -946,7 +946,7 @@ func TestAccCodeBuildProject_SecondarySourcesGitSubmodules_codeCommit(t *testing ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondarySources_GitSubmodulesConfig_CodeCommit(rName, false), + Config: testAccProjectConfig_secondarySourcesGitSubmodulesCodeCommit(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_sources.#", "2"), @@ -963,7 +963,7 @@ func TestAccCodeBuildProject_SecondarySourcesGitSubmodules_codeCommit(t *testing ), }, { - Config: testAccProjectConfig_SecondarySources_none(rName, false), + Config: testAccProjectConfig_secondarySourcesNone(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_sources.#", "0"), @@ -985,7 +985,7 @@ func TestAccCodeBuildProject_SecondarySourcesGitSubmodules_gitHub(t *testing.T) CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondarySources_GitSubmodulesConfig_GitHub(rName, true), + Config: testAccProjectConfig_secondarySourcesGitSubmodulesGitHub(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -996,7 +996,7 @@ func TestAccCodeBuildProject_SecondarySourcesGitSubmodules_gitHub(t *testing.T) ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondarySources_GitSubmodulesConfig_GitHub(rName, false), + Config: testAccProjectConfig_secondarySourcesGitSubmodulesGitHub(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -1017,7 +1017,7 @@ func TestAccCodeBuildProject_SecondarySourcesGitSubmodules_gitHubEnterprise(t *t CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondarySources_GitSubmodulesConfig_GitHubEnterprise(rName, true), + Config: testAccProjectConfig_secondarySourcesGitSubmodulesGitHubEnterprise(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -1028,7 +1028,7 @@ func TestAccCodeBuildProject_SecondarySourcesGitSubmodules_gitHubEnterprise(t *t ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondarySources_GitSubmodulesConfig_GitHubEnterprise(rName, false), + Config: testAccProjectConfig_secondarySourcesGitSubmodulesGitHubEnterprise(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -1049,7 +1049,7 @@ func TestAccCodeBuildProject_SecondarySourcesVersions(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondarySourceVersions_CodeCommit(rName), + Config: testAccProjectConfig_secondarySourceVersionsCodeCommit(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_sources.#", "2"), @@ -1072,7 +1072,7 @@ func TestAccCodeBuildProject_SecondarySourcesVersions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondarySourceVersions_CodeCommitUpdated(rName), + Config: testAccProjectConfig_secondarySourceVersionsCodeCommitUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_sources.#", "2"), @@ -1094,7 +1094,7 @@ func TestAccCodeBuildProject_SecondarySourcesVersions(t *testing.T) { ), }, { - Config: testAccProjectConfig_SecondarySourceVersions_CodeCommit(rName), + Config: testAccProjectConfig_secondarySourceVersionsCodeCommit(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_sources.#", "2"), @@ -1112,7 +1112,7 @@ func TestAccCodeBuildProject_SecondarySourcesVersions(t *testing.T) { ), }, { - Config: testAccProjectConfig_SecondarySources_GitSubmodulesConfig_CodeCommit(rName, false), + Config: testAccProjectConfig_secondarySourcesGitSubmodulesCodeCommit(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_sources.#", "2"), @@ -1145,7 +1145,7 @@ func TestAccCodeBuildProject_SourceBuildStatus_gitHubEnterprise(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_BuildStatusConfig_GitHubEnterprise(rName), + Config: testAccProjectConfig_sourceBuildStatusGitHubEnterprise(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -1171,7 +1171,7 @@ func TestAccCodeBuildProject_Source_insecureSSL(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_InsecureSSL(rName, true), + Config: testAccProjectConfig_sourceInsecureSSL(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.insecure_ssl", "true"), @@ -1183,7 +1183,7 @@ func TestAccCodeBuildProject_Source_insecureSSL(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Source_InsecureSSL(rName, false), + Config: testAccProjectConfig_sourceInsecureSSL(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.insecure_ssl", "false"), @@ -1207,7 +1207,7 @@ func TestAccCodeBuildProject_SourceReportBuildStatus_bitbucket(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_ReportBuildStatus_Bitbucket(rName, sourceLocation, true), + Config: testAccProjectConfig_sourceReportBuildStatusBitbucket(rName, sourceLocation, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "true"), @@ -1219,7 +1219,7 @@ func TestAccCodeBuildProject_SourceReportBuildStatus_bitbucket(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Source_ReportBuildStatus_Bitbucket(rName, sourceLocation, false), + Config: testAccProjectConfig_sourceReportBuildStatusBitbucket(rName, sourceLocation, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "false"), @@ -1241,7 +1241,7 @@ func TestAccCodeBuildProject_SourceReportBuildStatus_gitHub(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_ReportBuildStatus_GitHub(rName, true), + Config: testAccProjectConfig_sourceReportBuildStatusGitHub(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "true"), @@ -1253,7 +1253,7 @@ func TestAccCodeBuildProject_SourceReportBuildStatus_gitHub(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Source_ReportBuildStatus_GitHub(rName, false), + Config: testAccProjectConfig_sourceReportBuildStatusGitHub(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "false"), @@ -1275,7 +1275,7 @@ func TestAccCodeBuildProject_SourceReportBuildStatus_gitHubEnterprise(t *testing CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_ReportBuildStatus_GitHubEnterprise(rName, true), + Config: testAccProjectConfig_sourceReportBuildStatusGitHubEnterprise(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "true"), @@ -1287,7 +1287,7 @@ func TestAccCodeBuildProject_SourceReportBuildStatus_gitHubEnterprise(t *testing ImportStateVerify: true, }, { - Config: testAccProjectConfig_Source_ReportBuildStatus_GitHubEnterprise(rName, false), + Config: testAccProjectConfig_sourceReportBuildStatusGitHubEnterprise(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "false"), @@ -1311,7 +1311,7 @@ func TestAccCodeBuildProject_SourceType_bitbucket(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_Type_Bitbucket(rName, sourceLocation), + Config: testAccProjectConfig_sourceTypeBitbucket(rName, sourceLocation), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.type", "BITBUCKET"), @@ -1339,7 +1339,7 @@ func TestAccCodeBuildProject_SourceType_codeCommit(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_Type_CodeCommit(rName), + Config: testAccProjectConfig_sourceTypeCodeCommit(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.type", "CODECOMMIT"), @@ -1366,7 +1366,7 @@ func TestAccCodeBuildProject_SourceType_codePipeline(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_Type_CodePipeline(rName), + Config: testAccProjectConfig_sourceTypeCodePipeline(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.type", "CODEPIPELINE"), @@ -1393,7 +1393,7 @@ func TestAccCodeBuildProject_SourceType_gitHubEnterprise(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_Type_GitHubEnterprise(rName), + Config: testAccProjectConfig_sourceTypeGitHubEnterprise(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.type", "GITHUB_ENTERPRISE"), @@ -1420,7 +1420,7 @@ func TestAccCodeBuildProject_SourceType_s3(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_Type_S3(rName), + Config: testAccProjectConfig_sourceTypeS3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -1453,7 +1453,7 @@ phases: CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_Type_NoSource(rName, "", rBuildspec), + Config: testAccProjectConfig_sourceTypeNoSource(rName, "", rBuildspec), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.type", "NO_SOURCE"), @@ -1485,11 +1485,11 @@ phases: CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Source_Type_NoSource(rName, "", ""), + Config: testAccProjectConfig_sourceTypeNoSource(rName, "", ""), ExpectError: regexp.MustCompile("`buildspec` must be set when source's `type` is `NO_SOURCE`"), }, { - Config: testAccProjectConfig_Source_Type_NoSource(rName, "location", rBuildspec), + Config: testAccProjectConfig_sourceTypeNoSource(rName, "location", rBuildspec), ExpectError: regexp.MustCompile("`location` must be empty when source's `type` is `NO_SOURCE`"), }, }, @@ -1508,7 +1508,7 @@ func TestAccCodeBuildProject_tags(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Tags(rName, "tag2", "tag2value"), + Config: testAccProjectConfig_tags(rName, "tag2", "tag2value"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1522,7 +1522,7 @@ func TestAccCodeBuildProject_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Tags(rName, "tag2", "tag2value-updated"), + Config: testAccProjectConfig_tags(rName, "tag2", "tag2value-updated"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1546,7 +1546,7 @@ func TestAccCodeBuildProject_vpc(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_VPCConfig2(rName), + Config: testAccProjectConfig_vpc2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), @@ -1561,7 +1561,7 @@ func TestAccCodeBuildProject_vpc(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_VPCConfig1(rName), + Config: testAccProjectConfig_vpc1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), @@ -1593,7 +1593,7 @@ func TestAccCodeBuildProject_windowsServer2019Container(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_WindowsServer2019Container(rName), + Config: testAccProjectConfig_windowsServer2019Container(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "environment.#", "1"), @@ -1626,7 +1626,7 @@ func TestAccCodeBuildProject_armContainer(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_ARMContainer(rName), + Config: testAccProjectConfig_armContainer(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -1655,7 +1655,7 @@ func TestAccCodeBuildProject_Artifacts_artifactIdentifier(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_ArtifactIdentifier(rName, artifactIdentifier1), + Config: testAccProjectConfig_artifactsArtifactIdentifier(rName, artifactIdentifier1), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1668,7 +1668,7 @@ func TestAccCodeBuildProject_Artifacts_artifactIdentifier(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_ArtifactIdentifier(rName, artifactIdentifier2), + Config: testAccProjectConfig_artifactsArtifactIdentifier(rName, artifactIdentifier2), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1691,7 +1691,7 @@ func TestAccCodeBuildProject_Artifacts_encryptionDisabled(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_EncryptionDisabled(rName, true), + Config: testAccProjectConfig_artifactsEncryptionDisabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1704,7 +1704,7 @@ func TestAccCodeBuildProject_Artifacts_encryptionDisabled(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_EncryptionDisabled(rName, false), + Config: testAccProjectConfig_artifactsEncryptionDisabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1728,7 +1728,7 @@ func TestAccCodeBuildProject_Artifacts_location(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_Location(rName1, rName1), + Config: testAccProjectConfig_artifactsLocation(rName1, rName1), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1741,7 +1741,7 @@ func TestAccCodeBuildProject_Artifacts_location(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_Location(rName1, rName2), + Config: testAccProjectConfig_artifactsLocation(rName1, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1767,7 +1767,7 @@ func TestAccCodeBuildProject_Artifacts_name(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_Name(rName, name1), + Config: testAccProjectConfig_artifactsName(rName, name1), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1780,7 +1780,7 @@ func TestAccCodeBuildProject_Artifacts_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_Name(rName, name2), + Config: testAccProjectConfig_artifactsName(rName, name2), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1803,7 +1803,7 @@ func TestAccCodeBuildProject_Artifacts_namespaceType(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_NamespaceType(rName, codebuild.ArtifactNamespaceBuildId), + Config: testAccProjectConfig_artifactsNamespaceType(rName, codebuild.ArtifactNamespaceBuildId), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1816,7 +1816,7 @@ func TestAccCodeBuildProject_Artifacts_namespaceType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_NamespaceType(rName, codebuild.ArtifactNamespaceNone), + Config: testAccProjectConfig_artifactsNamespaceType(rName, codebuild.ArtifactNamespaceNone), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1839,7 +1839,7 @@ func TestAccCodeBuildProject_Artifacts_overrideArtifactName(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_OverrideArtifactName(rName, true), + Config: testAccProjectConfig_artifactsOverrideArtifactName(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1852,7 +1852,7 @@ func TestAccCodeBuildProject_Artifacts_overrideArtifactName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_OverrideArtifactName(rName, false), + Config: testAccProjectConfig_artifactsOverrideArtifactName(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1875,7 +1875,7 @@ func TestAccCodeBuildProject_Artifacts_packaging(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_Packaging(rName, codebuild.ArtifactPackagingZip), + Config: testAccProjectConfig_artifactsPackaging(rName, codebuild.ArtifactPackagingZip), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1888,7 +1888,7 @@ func TestAccCodeBuildProject_Artifacts_packaging(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_Packaging(rName, codebuild.ArtifactPackagingNone), + Config: testAccProjectConfig_artifactsPackaging(rName, codebuild.ArtifactPackagingNone), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1911,7 +1911,7 @@ func TestAccCodeBuildProject_Artifacts_path(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_Path(rName, "path1"), + Config: testAccProjectConfig_artifactsPath(rName, "path1"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1924,7 +1924,7 @@ func TestAccCodeBuildProject_Artifacts_path(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_Path(rName, "path2"), + Config: testAccProjectConfig_artifactsPath(rName, "path2"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1950,7 +1950,7 @@ func TestAccCodeBuildProject_Artifacts_type(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_Type(rName, type1), + Config: testAccProjectConfig_artifactsType(rName, type1), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1963,7 +1963,7 @@ func TestAccCodeBuildProject_Artifacts_type(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_Type(rName, type2), + Config: testAccProjectConfig_artifactsType(rName, type2), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1986,7 +1986,7 @@ func TestAccCodeBuildProject_Artifacts_bucketOwnerAccess(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Artifacts_BucketOwnerAccess(rName, "FULL"), + Config: testAccProjectConfig_artifactsBucketOwnerAccess(rName, "FULL"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -1999,7 +1999,7 @@ func TestAccCodeBuildProject_Artifacts_bucketOwnerAccess(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Artifacts_BucketOwnerAccess(rName, "READ_ONLY"), + Config: testAccProjectConfig_artifactsBucketOwnerAccess(rName, "READ_ONLY"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "artifacts.#", "1"), @@ -2022,7 +2022,7 @@ func TestAccCodeBuildProject_secondaryArtifacts(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts(rName), + Config: testAccProjectConfig_secondaryArtifacts(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "2"), @@ -2034,7 +2034,7 @@ func TestAccCodeBuildProject_secondaryArtifacts(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondaryArtifacts_none(rName), + Config: testAccProjectConfig_secondaryArtifactsNone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "0"), @@ -2059,7 +2059,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_artifactIdentifier(t *testing.T) CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts_ArtifactIdentifier(rName, artifactIdentifier1), + Config: testAccProjectConfig_secondaryArtifactsArtifactIdentifier(rName, artifactIdentifier1), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2074,7 +2074,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_artifactIdentifier(t *testing.T) ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondaryArtifacts_ArtifactIdentifier(rName, artifactIdentifier2), + Config: testAccProjectConfig_secondaryArtifactsArtifactIdentifier(rName, artifactIdentifier2), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2099,7 +2099,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_overrideArtifactName(t *testing. CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts_OverrideArtifactName(rName, true), + Config: testAccProjectConfig_secondaryArtifactsOverrideArtifactName(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2114,7 +2114,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_overrideArtifactName(t *testing. ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondaryArtifacts_OverrideArtifactName(rName, false), + Config: testAccProjectConfig_secondaryArtifactsOverrideArtifactName(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2139,7 +2139,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_encryptionDisabled(t *testing.T) CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts_EncryptionDisabled(rName, true), + Config: testAccProjectConfig_secondaryArtifactsEncryptionDisabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2154,7 +2154,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_encryptionDisabled(t *testing.T) ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondaryArtifacts_EncryptionDisabled(rName, false), + Config: testAccProjectConfig_secondaryArtifactsEncryptionDisabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2180,7 +2180,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_location(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts_Location(rName1, rName1), + Config: testAccProjectConfig_secondaryArtifactsLocation(rName1, rName1), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2195,7 +2195,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_location(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondaryArtifacts_Location(rName1, rName2), + Config: testAccProjectConfig_secondaryArtifactsLocation(rName1, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2225,7 +2225,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_name(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts_Name(rName, name1), + Config: testAccProjectConfig_secondaryArtifactsName(rName, name1), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2240,7 +2240,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondaryArtifacts_Name(rName, name2), + Config: testAccProjectConfig_secondaryArtifactsName(rName, name2), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2265,7 +2265,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_namespaceType(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts_NamespaceType(rName, codebuild.ArtifactNamespaceBuildId), + Config: testAccProjectConfig_secondaryArtifactsNamespaceType(rName, codebuild.ArtifactNamespaceBuildId), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2280,7 +2280,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_namespaceType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondaryArtifacts_NamespaceType(rName, codebuild.ArtifactNamespaceNone), + Config: testAccProjectConfig_secondaryArtifactsNamespaceType(rName, codebuild.ArtifactNamespaceNone), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2305,7 +2305,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_packaging(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts_Packaging(rName, codebuild.ArtifactPackagingZip), + Config: testAccProjectConfig_secondaryArtifactsPackaging(rName, codebuild.ArtifactPackagingZip), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2320,7 +2320,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_packaging(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondaryArtifacts_Packaging(rName, codebuild.ArtifactPackagingNone), + Config: testAccProjectConfig_secondaryArtifactsPackaging(rName, codebuild.ArtifactPackagingNone), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2348,7 +2348,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_path(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts_Path(rName, path1), + Config: testAccProjectConfig_secondaryArtifactsPath(rName, path1), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2363,7 +2363,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_path(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_SecondaryArtifacts_Path(rName, path2), + Config: testAccProjectConfig_secondaryArtifactsPath(rName, path2), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2388,7 +2388,7 @@ func TestAccCodeBuildProject_SecondaryArtifacts_type(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondaryArtifacts_Type(rName, codebuild.ArtifactsTypeS3), + Config: testAccProjectConfig_secondaryArtifactsType(rName, codebuild.ArtifactsTypeS3), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), @@ -2418,7 +2418,7 @@ func TestAccCodeBuildProject_SecondarySources_codeCommit(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_SecondarySources_CodeCommit(rName), + Config: testAccProjectConfig_secondarySourcesCodeCommit(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "source.0.type", "CODECOMMIT"), @@ -2472,7 +2472,7 @@ func TestAccCodeBuildProject_concurrentBuildLimit(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_ConcurrentBuildLimit(rName, 4), + Config: testAccProjectConfig_concurrentBuildLimit(rName, 4), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "concurrent_build_limit", "4"), @@ -2484,7 +2484,7 @@ func TestAccCodeBuildProject_concurrentBuildLimit(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_ConcurrentBuildLimit(rName, 12), + Config: testAccProjectConfig_concurrentBuildLimit(rName, 12), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "concurrent_build_limit", "12"), @@ -2506,7 +2506,7 @@ func TestAccCodeBuildProject_Environment_registryCredential(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectConfig_Environment_RegistryCredential1(rName), + Config: testAccProjectConfig_environmentRegistryCredential1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -2517,7 +2517,7 @@ func TestAccCodeBuildProject_Environment_registryCredential(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectConfig_Environment_RegistryCredential2(rName), + Config: testAccProjectConfig_environmentRegistryCredential2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &project), ), @@ -2730,7 +2730,7 @@ resource "aws_codebuild_project" "test" { `, rName, testAccGitHubSourceLocationFromEnv())) } -func testAccProjectConfig_projectVisibility(rName, visibility string) string { +func testAccProjectConfig_visibility(rName, visibility string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -2755,7 +2755,7 @@ resource "aws_codebuild_project" "test" { `, rName, testAccGitHubSourceLocationFromEnv(), visibility)) } -func testAccProjectConfig_projectVisibility_resourceRole(rName, visibility string) string { +func testAccProjectConfig_visibilityResourceRole(rName, visibility string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -2781,7 +2781,7 @@ resource "aws_codebuild_project" "test" { `, rName, testAccGitHubSourceLocationFromEnv(), visibility)) } -func testAccProjectConfig_BadgeEnabled(rName string, badgeEnabled bool) string { +func testAccProjectConfig_badgeEnabled(rName string, badgeEnabled bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { badge_enabled = %[1]t @@ -2806,7 +2806,7 @@ resource "aws_codebuild_project" "test" { `, badgeEnabled, rName)) } -func testAccProjectConfig_BuildTimeout(rName string, buildTimeout int) string { +func testAccProjectConfig_buildTimeout(rName string, buildTimeout int) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { build_timeout = %[1]d @@ -2831,7 +2831,7 @@ resource "aws_codebuild_project" "test" { `, buildTimeout, rName)) } -func testAccProjectConfig_QueuedTimeout(rName string, queuedTimeout int) string { +func testAccProjectConfig_queuedTimeout(rName string, queuedTimeout int) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { queued_timeout = %[1]d @@ -2856,7 +2856,7 @@ resource "aws_codebuild_project" "test" { `, queuedTimeout, rName)) } -func testAccProjectConfig_S3_ComputedLocation(rName string) string { +func testAccProjectConfig_s3ComputedLocation(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket_prefix = "cache" @@ -2889,7 +2889,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_Cache(rName, cacheLocation, cacheType string) string { +func testAccProjectConfig_cache(rName, cacheLocation, cacheType string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_s3_bucket" "test1" { bucket = "%[1]s-1" @@ -2930,7 +2930,7 @@ resource "aws_codebuild_project" "test" { `, rName, cacheLocation, cacheType)) } -func testAccProjectConfig_LocalCache(rName, modeType string) string { +func testAccProjectConfig_localCache(rName, modeType string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -2959,7 +2959,7 @@ resource "aws_codebuild_project" "test" { `, rName, modeType)) } -func testAccProjectConfig_Description(rName, description string) string { +func testAccProjectConfig_description(rName, description string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { description = %[1]q @@ -2984,7 +2984,7 @@ resource "aws_codebuild_project" "test" { `, description, rName)) } -func testAccProjectConfig_SourceVersion(rName, sourceVersion string) string { +func testAccProjectConfig_sourceVersion(rName, sourceVersion string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3010,7 +3010,7 @@ resource "aws_codebuild_project" "test" { `, rName, sourceVersion)) } -func testAccProjectConfig_EncryptionKey(rName string) string { +func testAccProjectConfig_encryptionKey(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -3040,7 +3040,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_Environment_EnvironmentVariable_One(rName, key1, value1 string) string { +func testAccProjectConfig_environmentVariableOne(rName, key1, value1 string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3069,7 +3069,7 @@ resource "aws_codebuild_project" "test" { `, rName, key1, value1)) } -func testAccProjectConfig_Environment_EnvironmentVariable_Two(rName, key1, value1, key2, value2 string) string { +func testAccProjectConfig_environmentVariableTwo(rName, key1, value1, key2, value2 string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3103,7 +3103,7 @@ resource "aws_codebuild_project" "test" { `, rName, key1, value1, key2, value2)) } -func testAccProjectConfig_Environment_EnvironmentVariable_Zero(rName string) string { +func testAccProjectConfig_environmentVariableZero(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3127,7 +3127,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_Environment_EnvironmentVariable_Type(rName, environmentVariableType string) string { +func testAccProjectConfig_environmentVariableType(rName, environmentVariableType string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3162,7 +3162,7 @@ resource "aws_codebuild_project" "test" { `, rName, environmentVariableType)) } -func testAccProjectConfig_Environment_Certificate(rName string, oName string) string { +func testAccProjectConfig_environmentCertificate(rName string, oName string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -3200,7 +3200,7 @@ resource "aws_codebuild_project" "test" { `, oName, rName)) } -func testAccProjectConfig_Environment_RegistryCredential1(rName string) string { +func testAccProjectConfig_environmentRegistryCredential1(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3240,7 +3240,7 @@ resource "aws_secretsmanager_secret_version" "test" { `, rName)) } -func testAccProjectConfig_Environment_RegistryCredential2(rName string) string { +func testAccProjectConfig_environmentRegistryCredential2(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3280,7 +3280,7 @@ resource "aws_secretsmanager_secret_version" "test" { `, rName)) } -func testAccProjectConfig_LogsConfig_CloudWatchLogs(rName, status, gName, sName string) string { +func testAccProjectConfig_cloudWatchLogs(rName, status, gName, sName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3312,7 +3312,7 @@ resource "aws_codebuild_project" "test" { `, rName, status, gName, sName)) } -func testAccProjectConfig_BuildBatchConfig(rName string, combineArtifacts bool, computeTypesAllowed string, maximumBuildsAllowed, timeoutInMins int) string { +func testAccProjectConfig_buildBatch(rName string, combineArtifacts bool, computeTypesAllowed string, maximumBuildsAllowed, timeoutInMins int) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3348,7 +3348,7 @@ resource "aws_codebuild_project" "test" { `, rName, combineArtifacts, computeTypesAllowed, maximumBuildsAllowed, timeoutInMins)) } -func testAccProjectConfig_LogsConfig_S3Logs(rName, status, location string, encryptionDisabled bool) string { +func testAccProjectConfig_s3Logs(rName, status, location string, encryptionDisabled bool) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -3387,7 +3387,7 @@ resource "aws_codebuild_project" "test" { `, rName, status, location, encryptionDisabled)) } -func testAccProjectConfig_Source_GitCloneDepth(rName string, gitCloneDepth int) string { +func testAccProjectConfig_sourceGitCloneDepth(rName string, gitCloneDepth int) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3412,7 +3412,7 @@ resource "aws_codebuild_project" "test" { `, rName, gitCloneDepth)) } -func testAccProjectConfig_Source_GitSubmodulesConfig_CodeCommit(rName string, fetchSubmodules bool) string { +func testAccProjectConfig_sourceGitSubmodulesCodeCommit(rName string, fetchSubmodules bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3440,7 +3440,7 @@ resource "aws_codebuild_project" "test" { `, rName, fetchSubmodules)) } -func testAccProjectConfig_Source_GitSubmodulesConfig_GitHub(rName string, fetchSubmodules bool) string { +func testAccProjectConfig_sourceGitSubmodulesGitHub(rName string, fetchSubmodules bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3468,7 +3468,7 @@ resource "aws_codebuild_project" "test" { `, rName, fetchSubmodules)) } -func testAccProjectConfig_Source_GitSubmodulesConfig_GitHubEnterprise(rName string, fetchSubmodules bool) string { +func testAccProjectConfig_sourceGitSubmodulesGitHubEnterprise(rName string, fetchSubmodules bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3496,7 +3496,7 @@ resource "aws_codebuild_project" "test" { `, rName, fetchSubmodules)) } -func testAccProjectConfig_SecondarySources_GitSubmodulesConfig_CodeCommit(rName string, fetchSubmodules bool) string { +func testAccProjectConfig_secondarySourcesGitSubmodulesCodeCommit(rName string, fetchSubmodules bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3544,7 +3544,7 @@ resource "aws_codebuild_project" "test" { `, rName, fetchSubmodules)) } -func testAccProjectConfig_SecondarySources_none(rName string, fetchSubmodules bool) string { +func testAccProjectConfig_secondarySourcesNone(rName string, fetchSubmodules bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3572,7 +3572,7 @@ resource "aws_codebuild_project" "test" { `, rName, fetchSubmodules)) } -func testAccProjectConfig_SecondarySources_GitSubmodulesConfig_GitHub(rName string, fetchSubmodules bool) string { +func testAccProjectConfig_secondarySourcesGitSubmodulesGitHub(rName string, fetchSubmodules bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3620,7 +3620,7 @@ resource "aws_codebuild_project" "test" { `, rName, fetchSubmodules)) } -func testAccProjectConfig_SecondarySources_GitSubmodulesConfig_GitHubEnterprise(rName string, fetchSubmodules bool) string { +func testAccProjectConfig_secondarySourcesGitSubmodulesGitHubEnterprise(rName string, fetchSubmodules bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3668,7 +3668,7 @@ resource "aws_codebuild_project" "test" { `, rName, fetchSubmodules)) } -func testAccProjectConfig_SecondarySourceVersions_CodeCommit(rName string) string { +func testAccProjectConfig_secondarySourceVersionsCodeCommit(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3709,7 +3709,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_SecondarySourceVersions_CodeCommitUpdated(rName string) string { +func testAccProjectConfig_secondarySourceVersionsCodeCommitUpdated(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3755,7 +3755,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_Source_InsecureSSL(rName string, insecureSSL bool) string { +func testAccProjectConfig_sourceInsecureSSL(rName string, insecureSSL bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3780,7 +3780,7 @@ resource "aws_codebuild_project" "test" { `, rName, insecureSSL)) } -func testAccProjectConfig_Source_ReportBuildStatus_Bitbucket(rName, sourceLocation string, reportBuildStatus bool) string { +func testAccProjectConfig_sourceReportBuildStatusBitbucket(rName, sourceLocation string, reportBuildStatus bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3805,7 +3805,7 @@ resource "aws_codebuild_project" "test" { `, rName, sourceLocation, reportBuildStatus)) } -func testAccProjectConfig_Source_ReportBuildStatus_GitHub(rName string, reportBuildStatus bool) string { +func testAccProjectConfig_sourceReportBuildStatusGitHub(rName string, reportBuildStatus bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3830,7 +3830,7 @@ resource "aws_codebuild_project" "test" { `, rName, reportBuildStatus)) } -func testAccProjectConfig_Source_ReportBuildStatus_GitHubEnterprise(rName string, reportBuildStatus bool) string { +func testAccProjectConfig_sourceReportBuildStatusGitHubEnterprise(rName string, reportBuildStatus bool) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3855,7 +3855,7 @@ resource "aws_codebuild_project" "test" { `, rName, reportBuildStatus)) } -func testAccProjectConfig_Source_Type_Bitbucket(rName, sourceLocation string) string { +func testAccProjectConfig_sourceTypeBitbucket(rName, sourceLocation string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3879,7 +3879,7 @@ resource "aws_codebuild_project" "test" { `, rName, sourceLocation)) } -func testAccProjectConfig_Source_Type_CodeCommit(rName string) string { +func testAccProjectConfig_sourceTypeCodeCommit(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3903,7 +3903,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_Source_Type_CodePipeline(rName string) string { +func testAccProjectConfig_sourceTypeCodePipeline(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3926,7 +3926,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_Source_Type_GitHubEnterprise(rName string) string { +func testAccProjectConfig_sourceTypeGitHubEnterprise(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -3950,7 +3950,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_Source_Type_S3(rName string) string { +func testAccProjectConfig_sourceTypeS3(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -3984,7 +3984,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_Source_Type_NoSource(rName string, rLocation string, rBuildspec string) string { +func testAccProjectConfig_sourceTypeNoSource(rName string, rLocation string, rBuildspec string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -4009,7 +4009,7 @@ resource "aws_codebuild_project" "test" { `, rName, rLocation, rBuildspec)) } -func testAccProjectConfig_Tags(rName, tagKey, tagValue string) string { +func testAccProjectConfig_tags(rName, tagKey, tagValue string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -4039,7 +4039,7 @@ resource "aws_codebuild_project" "test" { `, rName, tagKey, tagValue)) } -func testAccProjectConfig_VPCConfig1(rName string) string { +func testAccProjectConfig_vpc1(rName string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), acctest.ConfigAvailableAZsNoOptIn(), @@ -4097,7 +4097,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_VPCConfig2(rName string) string { +func testAccProjectConfig_vpc2(rName string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), acctest.ConfigAvailableAZsNoOptIn(), @@ -4155,7 +4155,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_WindowsServer2019Container(rName string) string { +func testAccProjectConfig_windowsServer2019Container(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -4179,7 +4179,7 @@ resource "aws_codebuild_project" "test" { `, rName, testAccGitHubSourceLocationFromEnv())) } -func testAccProjectConfig_ARMContainer(rName string) string { +func testAccProjectConfig_armContainer(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -4203,7 +4203,7 @@ resource "aws_codebuild_project" "test" { `, rName, testAccGitHubSourceLocationFromEnv())) } -func testAccProjectConfig_Artifacts_ArtifactIdentifier(rName string, artifactIdentifier string) string { +func testAccProjectConfig_artifactsArtifactIdentifier(rName string, artifactIdentifier string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4236,7 +4236,7 @@ resource "aws_codebuild_project" "test" { `, rName, artifactIdentifier)) } -func testAccProjectConfig_Artifacts_EncryptionDisabled(rName string, encryptionDisabled bool) string { +func testAccProjectConfig_artifactsEncryptionDisabled(rName string, encryptionDisabled bool) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4269,7 +4269,7 @@ resource "aws_codebuild_project" "test" { `, rName, encryptionDisabled)) } -func testAccProjectConfig_Artifacts_Location(rName, bucketName string) string { +func testAccProjectConfig_artifactsLocation(rName, bucketName string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4301,7 +4301,7 @@ resource "aws_codebuild_project" "test" { `, rName, bucketName)) } -func testAccProjectConfig_Artifacts_Name(rName string, name string) string { +func testAccProjectConfig_artifactsName(rName string, name string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4334,7 +4334,7 @@ resource "aws_codebuild_project" "test" { `, rName, name)) } -func testAccProjectConfig_Artifacts_NamespaceType(rName, namespaceType string) string { +func testAccProjectConfig_artifactsNamespaceType(rName, namespaceType string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4367,7 +4367,7 @@ resource "aws_codebuild_project" "test" { `, rName, namespaceType)) } -func testAccProjectConfig_Artifacts_OverrideArtifactName(rName string, overrideArtifactName bool) string { +func testAccProjectConfig_artifactsOverrideArtifactName(rName string, overrideArtifactName bool) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4400,7 +4400,7 @@ resource "aws_codebuild_project" "test" { `, rName, overrideArtifactName)) } -func testAccProjectConfig_Artifacts_Packaging(rName, packaging string) string { +func testAccProjectConfig_artifactsPackaging(rName, packaging string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4433,7 +4433,7 @@ resource "aws_codebuild_project" "test" { `, rName, packaging)) } -func testAccProjectConfig_Artifacts_Path(rName, path string) string { +func testAccProjectConfig_artifactsPath(rName, path string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4466,7 +4466,7 @@ resource "aws_codebuild_project" "test" { `, rName, path)) } -func testAccProjectConfig_Artifacts_Type(rName string, artifactType string) string { +func testAccProjectConfig_artifactsType(rName string, artifactType string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4498,7 +4498,7 @@ resource "aws_codebuild_project" "test" { `, rName, artifactType)) } -func testAccProjectConfig_Artifacts_BucketOwnerAccess(rName string, typ string) string { +func testAccProjectConfig_artifactsBucketOwnerAccess(rName string, typ string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4531,7 +4531,7 @@ resource "aws_codebuild_project" "test" { `, rName, typ)) } -func testAccProjectConfig_SecondaryArtifacts(rName string) string { +func testAccProjectConfig_secondaryArtifacts(rName string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4575,7 +4575,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_SecondaryArtifacts_none(rName string) string { +func testAccProjectConfig_secondaryArtifactsNone(rName string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4607,7 +4607,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_SecondaryArtifacts_ArtifactIdentifier(rName string, artifactIdentifier string) string { +func testAccProjectConfig_secondaryArtifactsArtifactIdentifier(rName string, artifactIdentifier string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4645,7 +4645,7 @@ resource "aws_codebuild_project" "test" { `, rName, artifactIdentifier)) } -func testAccProjectConfig_SecondaryArtifacts_EncryptionDisabled(rName string, encryptionDisabled bool) string { +func testAccProjectConfig_secondaryArtifactsEncryptionDisabled(rName string, encryptionDisabled bool) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4684,7 +4684,7 @@ resource "aws_codebuild_project" "test" { `, rName, encryptionDisabled)) } -func testAccProjectConfig_SecondaryArtifacts_Location(rName, bucketName string) string { +func testAccProjectConfig_secondaryArtifactsLocation(rName, bucketName string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4722,7 +4722,7 @@ resource "aws_codebuild_project" "test" { `, rName, bucketName)) } -func testAccProjectConfig_SecondaryArtifacts_Name(rName string, name string) string { +func testAccProjectConfig_secondaryArtifactsName(rName string, name string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4761,7 +4761,7 @@ resource "aws_codebuild_project" "test" { `, rName, name)) } -func testAccProjectConfig_SecondaryArtifacts_NamespaceType(rName, namespaceType string) string { +func testAccProjectConfig_secondaryArtifactsNamespaceType(rName, namespaceType string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4800,7 +4800,7 @@ resource "aws_codebuild_project" "test" { `, rName, namespaceType)) } -func testAccProjectConfig_SecondaryArtifacts_OverrideArtifactName(rName string, overrideArtifactName bool) string { +func testAccProjectConfig_secondaryArtifactsOverrideArtifactName(rName string, overrideArtifactName bool) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4839,7 +4839,7 @@ resource "aws_codebuild_project" "test" { `, rName, overrideArtifactName)) } -func testAccProjectConfig_SecondaryArtifacts_Packaging(rName, packaging string) string { +func testAccProjectConfig_secondaryArtifactsPackaging(rName, packaging string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4878,7 +4878,7 @@ resource "aws_codebuild_project" "test" { `, rName, packaging)) } -func testAccProjectConfig_SecondaryArtifacts_Path(rName, path string) string { +func testAccProjectConfig_secondaryArtifactsPath(rName, path string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4917,7 +4917,7 @@ resource "aws_codebuild_project" "test" { `, rName, path)) } -func testAccProjectConfig_SecondaryArtifacts_Type(rName string, artifactType string) string { +func testAccProjectConfig_secondaryArtifactsType(rName string, artifactType string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` @@ -4955,7 +4955,7 @@ resource "aws_codebuild_project" "test" { `, rName, artifactType)) } -func testAccProjectConfig_SecondarySources_CodeCommit(rName string) string { +func testAccProjectConfig_secondarySourcesCodeCommit(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -4991,7 +4991,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_Source_BuildStatusConfig_GitHubEnterprise(rName string) string { +func testAccProjectConfig_sourceBuildStatusGitHubEnterprise(rName string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -5020,7 +5020,7 @@ resource "aws_codebuild_project" "test" { `, rName)) } -func testAccProjectConfig_ConcurrentBuildLimit(rName string, concurrentBuildLimit int) string { +func testAccProjectConfig_concurrentBuildLimit(rName string, concurrentBuildLimit int) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { concurrent_build_limit = %[1]d @@ -5045,7 +5045,7 @@ resource "aws_codebuild_project" "test" { `, concurrentBuildLimit, rName)) } -func testAccProjectConfig_FileSystemLocations(rName, mountPoint string) string { +func testAccProjectConfig_fileSystemLocations(rName, mountPoint string) string { return acctest.ConfigCompose( testAccProjectConfig_Base_ServiceRole(rName), acctest.ConfigAvailableAZsNoOptIn(), diff --git a/internal/service/codebuild/report_group_test.go b/internal/service/codebuild/report_group_test.go index f4daaf2f3ff..c6ea577ea14 100644 --- a/internal/service/codebuild/report_group_test.go +++ b/internal/service/codebuild/report_group_test.go @@ -25,7 +25,7 @@ func TestAccCodeBuildReportGroup_basic(t *testing.T) { CheckDestroy: testAccCheckReportGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReportGroupBasicConfig(rName), + Config: testAccReportGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReportGroupExists(resourceName, &reportGroup), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -57,7 +57,7 @@ func TestAccCodeBuildReportGroup_Export_s3(t *testing.T) { CheckDestroy: testAccCheckReportGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReportGroupS3ExportConfig(rName), + Config: testAccReportGroupConfig_s3Export(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReportGroupExists(resourceName, &reportGroup), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -78,7 +78,7 @@ func TestAccCodeBuildReportGroup_Export_s3(t *testing.T) { ImportStateVerifyIgnore: []string{"delete_reports"}, }, { - Config: testAccReportGroupS3ExportUpdatedConfig(rName), + Config: testAccReportGroupConfig_s3ExportUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReportGroupExists(resourceName, &reportGroup), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -107,7 +107,7 @@ func TestAccCodeBuildReportGroup_tags(t *testing.T) { CheckDestroy: testAccCheckReportGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReportGroupTags1Config(rName, "key1", "value1"), + Config: testAccReportGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckReportGroupExists(resourceName, &reportGroup), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -121,7 +121,7 @@ func TestAccCodeBuildReportGroup_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"delete_reports"}, }, { - Config: testAccReportGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccReportGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckReportGroupExists(resourceName, &reportGroup), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -130,7 +130,7 @@ func TestAccCodeBuildReportGroup_tags(t *testing.T) { ), }, { - Config: testAccReportGroupTags1Config(rName, "key2", "value2"), + Config: testAccReportGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckReportGroupExists(resourceName, &reportGroup), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -153,7 +153,7 @@ func TestAccCodeBuildReportGroup_deleteReports(t *testing.T) { CheckDestroy: testAccCheckReportGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReportGroupDeleteReportsConfig(rName), + Config: testAccReportGroupConfig_delete(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReportGroupExists(resourceName, &reportGroup), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -181,7 +181,7 @@ func TestAccCodeBuildReportGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckReportGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReportGroupBasicConfig(rName), + Config: testAccReportGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReportGroupExists(resourceName, &reportGroup), acctest.CheckResourceDisappears(acctest.Provider, tfcodebuild.ResourceReportGroup(), resourceName), @@ -253,7 +253,7 @@ func testAccCheckReportGroupExists(name string, reportGroup *codebuild.ReportGro } } -func testAccReportGroupBasicConfig(rName string) string { +func testAccReportGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_codebuild_report_group" "test" { name = %[1]q @@ -297,7 +297,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccReportGroupS3ExportConfig(rName string) string { +func testAccReportGroupConfig_s3Export(rName string) string { return testAccReportGroupBasicS3ExportBaseConfig(rName) + fmt.Sprintf(` resource "aws_codebuild_report_group" "test" { @@ -319,7 +319,7 @@ resource "aws_codebuild_report_group" "test" { `, rName) } -func testAccReportGroupS3ExportUpdatedConfig(rName string) string { +func testAccReportGroupConfig_s3ExportUpdated(rName string) string { return testAccReportGroupBasicS3ExportBaseConfig(rName) + fmt.Sprintf(` resource "aws_codebuild_report_group" "test" { @@ -341,7 +341,7 @@ resource "aws_codebuild_report_group" "test" { `, rName) } -func testAccReportGroupTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccReportGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_codebuild_report_group" "test" { name = %[1]q @@ -358,7 +358,7 @@ resource "aws_codebuild_report_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccReportGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccReportGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_codebuild_report_group" "test" { name = %[1]q @@ -376,7 +376,7 @@ resource "aws_codebuild_report_group" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccReportGroupDeleteReportsConfig(rName string) string { +func testAccReportGroupConfig_delete(rName string) string { return fmt.Sprintf(` resource "aws_codebuild_report_group" "test" { name = %[1]q diff --git a/internal/service/codebuild/resource_policy_test.go b/internal/service/codebuild/resource_policy_test.go index 87d1a80dcae..e668d708abe 100644 --- a/internal/service/codebuild/resource_policy_test.go +++ b/internal/service/codebuild/resource_policy_test.go @@ -26,7 +26,7 @@ func TestAccCodeBuildResourcePolicy_basic(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyBasicConfig(rName), + Config: testAccResourcePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName, &reportGroup), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_codebuild_report_group.test", "arn"), @@ -54,7 +54,7 @@ func TestAccCodeBuildResourcePolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyBasicConfig(rName), + Config: testAccResourcePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName, &reportGroup), acctest.CheckResourceDisappears(acctest.Provider, tfcodebuild.ResourceResourcePolicy(), resourceName), @@ -78,7 +78,7 @@ func TestAccCodeBuildResourcePolicy_disappears_resource(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyBasicConfig(rName), + Config: testAccResourcePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName, &reportGroup), acctest.CheckResourceDisappears(acctest.Provider, tfcodebuild.ResourceReportGroup(), resourceName), @@ -139,7 +139,7 @@ func testAccCheckResourcePolicyExists(name string, policy *codebuild.GetResource } } -func testAccResourcePolicyBasicConfig(rName string) string { +func testAccResourcePolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_codebuild_report_group" "test" { name = %[1]q diff --git a/internal/service/codebuild/source_credential_test.go b/internal/service/codebuild/source_credential_test.go index 93bd8fee4b8..6a8481a65bb 100644 --- a/internal/service/codebuild/source_credential_test.go +++ b/internal/service/codebuild/source_credential_test.go @@ -27,7 +27,7 @@ func TestAccCodeBuildSourceCredential_basic(t *testing.T) { CheckDestroy: testAccCheckSourceCredentialDestroy, Steps: []resource.TestStep{ { - Config: testAccSourceCredential_Basic("PERSONAL_ACCESS_TOKEN", "GITHUB", token), + Config: testAccSourceCredentialConfig_basic("PERSONAL_ACCESS_TOKEN", "GITHUB", token), Check: resource.ComposeTestCheckFunc( testAccCheckSourceCredentialExists(resourceName, &sourceCredentialsInfo), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "codebuild", regexp.MustCompile(`token/github`)), @@ -36,7 +36,7 @@ func TestAccCodeBuildSourceCredential_basic(t *testing.T) { ), }, { - Config: testAccSourceCredential_Basic("PERSONAL_ACCESS_TOKEN", "GITHUB_ENTERPRISE", token), + Config: testAccSourceCredentialConfig_basic("PERSONAL_ACCESS_TOKEN", "GITHUB_ENTERPRISE", token), Check: resource.ComposeTestCheckFunc( testAccCheckSourceCredentialExists(resourceName, &sourceCredentialsInfo), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "codebuild", regexp.MustCompile(`token/github_enterprise`)), @@ -66,7 +66,7 @@ func TestAccCodeBuildSourceCredential_basicAuth(t *testing.T) { CheckDestroy: testAccCheckSourceCredentialDestroy, Steps: []resource.TestStep{ { - Config: testAccSourceCredential_BasicAuth(token, "user1"), + Config: testAccSourceCredentialConfig_basicAuth(token, "user1"), Check: resource.ComposeTestCheckFunc( testAccCheckSourceCredentialExists(resourceName, &sourceCredentialsInfo), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "codebuild", regexp.MustCompile(`token/bitbucket`)), @@ -76,7 +76,7 @@ func TestAccCodeBuildSourceCredential_basicAuth(t *testing.T) { ), }, { - Config: testAccSourceCredential_BasicAuth(token, "user2"), + Config: testAccSourceCredentialConfig_basicAuth(token, "user2"), Check: resource.ComposeTestCheckFunc( testAccCheckSourceCredentialExists(resourceName, &sourceCredentialsInfo), resource.TestCheckResourceAttr(resourceName, "user_name", "user2"), @@ -104,7 +104,7 @@ func TestAccCodeBuildSourceCredential_disappears(t *testing.T) { CheckDestroy: testAccCheckSourceCredentialDestroy, Steps: []resource.TestStep{ { - Config: testAccSourceCredential_Basic("PERSONAL_ACCESS_TOKEN", "GITHUB_ENTERPRISE", token), + Config: testAccSourceCredentialConfig_basic("PERSONAL_ACCESS_TOKEN", "GITHUB_ENTERPRISE", token), Check: resource.ComposeTestCheckFunc( testAccCheckSourceCredentialExists(resourceName, &sourceCredentialsInfo), acctest.CheckResourceDisappears(acctest.Provider, tfcodebuild.ResourceSourceCredential(), resourceName), @@ -163,7 +163,7 @@ func testAccCheckSourceCredentialExists(name string, sourceCredential *codebuild } } -func testAccSourceCredential_Basic(authType, serverType, token string) string { +func testAccSourceCredentialConfig_basic(authType, serverType, token string) string { return fmt.Sprintf(` resource "aws_codebuild_source_credential" "test" { auth_type = "%s" @@ -173,7 +173,7 @@ resource "aws_codebuild_source_credential" "test" { `, authType, serverType, token) } -func testAccSourceCredential_BasicAuth(token, userName string) string { +func testAccSourceCredentialConfig_basicAuth(token, userName string) string { return fmt.Sprintf(` resource "aws_codebuild_source_credential" "test" { auth_type = "BASIC_AUTH" diff --git a/internal/service/codebuild/webhook_test.go b/internal/service/codebuild/webhook_test.go index 7dd7196105f..15fc25a007d 100644 --- a/internal/service/codebuild/webhook_test.go +++ b/internal/service/codebuild/webhook_test.go @@ -29,7 +29,7 @@ func TestAccCodeBuildWebhook_bitbucket(t *testing.T) { CheckDestroy: testAccCheckWebhookDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookConfig_Bitbucket(rName, sourceLocation), + Config: testAccWebhookConfig_bitbucket(rName, sourceLocation), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "branch_filter", ""), @@ -61,7 +61,7 @@ func TestAccCodeBuildWebhook_gitHub(t *testing.T) { CheckDestroy: testAccCheckWebhookDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookConfig_GitHub(rName), + Config: testAccWebhookConfig_gitHub(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "branch_filter", ""), @@ -93,7 +93,7 @@ func TestAccCodeBuildWebhook_gitHubEnterprise(t *testing.T) { CheckDestroy: testAccCheckWebhookDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookConfig_GitHubEnterprise(rName, "dev"), + Config: testAccWebhookConfig_gitHubEnterprise(rName, "dev"), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "branch_filter", "dev"), @@ -110,7 +110,7 @@ func TestAccCodeBuildWebhook_gitHubEnterprise(t *testing.T) { ImportStateVerifyIgnore: []string{"secret"}, }, { - Config: testAccWebhookConfig_GitHubEnterprise(rName, "master"), + Config: testAccWebhookConfig_gitHubEnterprise(rName, "master"), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "branch_filter", "master"), @@ -142,21 +142,21 @@ func TestAccCodeBuildWebhook_buildType(t *testing.T) { CheckDestroy: testAccCheckWebhookDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookConfig_BuildType(rName, "BUILD"), + Config: testAccWebhookConfig_buildType(rName, "BUILD"), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "build_type", "BUILD"), ), }, { - Config: testAccWebhookConfig_GitHub(rName), + Config: testAccWebhookConfig_gitHub(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), ), ExpectNonEmptyPlan: true, }, { - Config: testAccWebhookConfig_BuildType(rName, "BUILD_BATCH"), + Config: testAccWebhookConfig_buildType(rName, "BUILD_BATCH"), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "build_type", "BUILD_BATCH"), @@ -184,14 +184,14 @@ func TestAccCodeBuildWebhook_branchFilter(t *testing.T) { CheckDestroy: testAccCheckWebhookDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookConfig_BranchFilter(rName, "master"), + Config: testAccWebhookConfig_branchFilter(rName, "master"), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "branch_filter", "master"), ), }, { - Config: testAccWebhookConfig_BranchFilter(rName, "dev"), + Config: testAccWebhookConfig_branchFilter(rName, "dev"), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), resource.TestCheckResourceAttr(resourceName, "branch_filter", "dev"), @@ -219,7 +219,7 @@ func TestAccCodeBuildWebhook_filterGroup(t *testing.T) { CheckDestroy: testAccCheckWebhookDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookConfig_FilterGroup(rName), + Config: testAccWebhookConfig_filterGroup(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &webhook), testAccCheckWebhookFilter(&webhook, [][]*codebuild.WebhookFilter{ @@ -333,9 +333,9 @@ func testAccCheckWebhookExists(name string, webhook *codebuild.Webhook) resource } } -func testAccWebhookConfig_Bitbucket(rName, sourceLocation string) string { +func testAccWebhookConfig_bitbucket(rName, sourceLocation string) string { return acctest.ConfigCompose( - testAccProjectConfig_Source_Type_Bitbucket(rName, sourceLocation), + testAccProjectConfig_sourceTypeBitbucket(rName, sourceLocation), ` resource "aws_codebuild_webhook" "test" { project_name = aws_codebuild_project.test.name @@ -343,7 +343,7 @@ resource "aws_codebuild_webhook" "test" { `) } -func testAccWebhookConfig_GitHub(rName string) string { +func testAccWebhookConfig_gitHub(rName string) string { return acctest.ConfigCompose( testAccProjectConfig_basic(rName), ` @@ -353,7 +353,7 @@ resource "aws_codebuild_webhook" "test" { `) } -func testAccWebhookConfig_GitHubEnterprise(rName string, branchFilter string) string { +func testAccWebhookConfig_gitHubEnterprise(rName string, branchFilter string) string { return acctest.ConfigCompose(testAccProjectConfig_Base_ServiceRole(rName), fmt.Sprintf(` resource "aws_codebuild_project" "test" { name = %[1]q @@ -382,7 +382,7 @@ resource "aws_codebuild_webhook" "test" { `, rName, branchFilter)) } -func testAccWebhookConfig_BuildType(rName, branchFilter string) string { +func testAccWebhookConfig_buildType(rName, branchFilter string) string { return acctest.ConfigCompose(testAccProjectConfig_basic(rName), fmt.Sprintf(` resource "aws_codebuild_webhook" "test" { build_type = %[1]q @@ -391,7 +391,7 @@ resource "aws_codebuild_webhook" "test" { `, branchFilter)) } -func testAccWebhookConfig_BranchFilter(rName, branchFilter string) string { +func testAccWebhookConfig_branchFilter(rName, branchFilter string) string { return acctest.ConfigCompose(testAccProjectConfig_basic(rName), fmt.Sprintf(` resource "aws_codebuild_webhook" "test" { branch_filter = %[1]q @@ -400,7 +400,7 @@ resource "aws_codebuild_webhook" "test" { `, branchFilter)) } -func testAccWebhookConfig_FilterGroup(rName string) string { +func testAccWebhookConfig_filterGroup(rName string) string { return acctest.ConfigCompose( testAccProjectConfig_basic(rName), ` diff --git a/internal/service/codecommit/approval_rule_template_data_source_test.go b/internal/service/codecommit/approval_rule_template_data_source_test.go index 4f68156858a..a36de4b3d46 100644 --- a/internal/service/codecommit/approval_rule_template_data_source_test.go +++ b/internal/service/codecommit/approval_rule_template_data_source_test.go @@ -21,7 +21,7 @@ func TestAccCodeCommitApprovalRuleTemplateDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckApprovalRuleTemplateDataSourceConfig(rName), + Config: testAccApprovalRuleTemplateDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), @@ -36,7 +36,7 @@ func TestAccCodeCommitApprovalRuleTemplateDataSource_basic(t *testing.T) { }) } -func testAccCheckApprovalRuleTemplateDataSourceConfig(rName string) string { +func testAccApprovalRuleTemplateDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/codecommit/repository_data_source_test.go b/internal/service/codecommit/repository_data_source_test.go index 8aaee3d9f81..db46bbec178 100644 --- a/internal/service/codecommit/repository_data_source_test.go +++ b/internal/service/codecommit/repository_data_source_test.go @@ -21,7 +21,7 @@ func TestAccCodeCommitRepositoryDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckRepositoryDataSourceConfig(rName), + Config: testAccRepositoryDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "clone_url_http", resourceName, "clone_url_http"), @@ -33,7 +33,7 @@ func TestAccCodeCommitRepositoryDataSource_basic(t *testing.T) { }) } -func testAccCheckRepositoryDataSourceConfig(rName string) string { +func testAccRepositoryDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_codecommit_repository" "default" { repository_name = "%s" diff --git a/internal/service/codepipeline/codepipeline.go b/internal/service/codepipeline/codepipeline.go index 7336c7122af..26ed90822c7 100644 --- a/internal/service/codepipeline/codepipeline.go +++ b/internal/service/codepipeline/codepipeline.go @@ -25,12 +25,12 @@ import ( ) const ( - CodePipelineProviderGitHub = "GitHub" + providerGitHub = "GitHub" - CodePipelineGitHubActionConfigurationOAuthToken = "OAuthToken" + gitHubActionConfigurationOAuthToken = "OAuthToken" ) -func ResourceCodePipeline() *schema.Resource { +func ResourceCodePipeline() *schema.Resource { // nosemgrep:codepipeline-in-func-name return &schema.Resource{ Create: resourceCreate, Read: resourceRead, @@ -446,11 +446,11 @@ func flattenStageActions(si int, actions []*codepipeline.ActionDeclaration, d *s config := aws.StringValueMap(action.Configuration) actionProvider := aws.StringValue(action.ActionTypeId.Provider) - if actionProvider == CodePipelineProviderGitHub { - if _, ok := config[CodePipelineGitHubActionConfigurationOAuthToken]; ok { + if actionProvider == providerGitHub { + if _, ok := config[gitHubActionConfigurationOAuthToken]; ok { // The AWS API returns "****" for the OAuthToken value. Pull the value from the configuration. addr := fmt.Sprintf("stage.%d.action.%d.configuration.OAuthToken", si, ai) - config[CodePipelineGitHubActionConfigurationOAuthToken] = d.Get(addr).(string) + config[gitHubActionConfigurationOAuthToken] = d.Get(addr).(string) } } @@ -538,13 +538,13 @@ func resourceRead(d *schema.ResourceData, meta interface{}) error { }) if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, codepipeline.ErrCodePipelineNotFoundException) { - names.LogNotFoundRemoveState(names.CodePipeline, names.ErrActionReading, ResCodePipeline, d.Id()) + names.LogNotFoundRemoveState(names.CodePipeline, names.ErrActionReading, resPipeline, d.Id()) d.SetId("") return nil } if err != nil { - return names.Error(names.CodePipeline, names.ErrActionReading, ResCodePipeline, d.Id(), err) + return names.Error(names.CodePipeline, names.ErrActionReading, resPipeline, d.Id(), err) } metadata := resp.Metadata @@ -643,7 +643,7 @@ func resourceValidateActionProvider(i interface{}, path cty.Path) diag.Diagnosti return diag.Errorf("expected type to be string") } - if v == CodePipelineProviderGitHub { + if v == providerGitHub { return diag.Diagnostics{ diag.Diagnostic{ Severity: diag.Warning, @@ -662,7 +662,7 @@ func suppressStageActionConfiguration(k, old, new string, d *schema.ResourceData providerAddr := strings.Join(append(parts, "provider"), ".") provider := d.Get(providerAddr).(string) - if provider == CodePipelineProviderGitHub && strings.HasSuffix(k, CodePipelineGitHubActionConfigurationOAuthToken) { + if provider == providerGitHub && strings.HasSuffix(k, gitHubActionConfigurationOAuthToken) { hash := hashGitHubToken(new) return old == hash } @@ -670,15 +670,15 @@ func suppressStageActionConfiguration(k, old, new string, d *schema.ResourceData return false } -const codePipelineGitHubTokenHashPrefix = "hash-" +const gitHubTokenHashPrefix = "hash-" func hashGitHubToken(token string) string { // Without this check, the value was getting encoded twice - if strings.HasPrefix(token, codePipelineGitHubTokenHashPrefix) { + if strings.HasPrefix(token, gitHubTokenHashPrefix) { return token } sum := sha256.Sum256([]byte(token)) - return codePipelineGitHubTokenHashPrefix + hex.EncodeToString(sum[:]) + return gitHubTokenHashPrefix + hex.EncodeToString(sum[:]) } // https://github.com/hashicorp/terraform-plugin-sdk/issues/780. diff --git a/internal/service/codepipeline/codepipeline_test.go b/internal/service/codepipeline/codepipeline_test.go index 0747f28d0e3..50eaf469c0a 100644 --- a/internal/service/codepipeline/codepipeline_test.go +++ b/internal/service/codepipeline/codepipeline_test.go @@ -36,7 +36,7 @@ func TestAccCodePipeline_basic(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig_basic(name), + Config: testAccCodePipelineConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p1), resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.codepipeline_role", "arn"), @@ -86,7 +86,7 @@ func TestAccCodePipeline_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfig_basicUpdated(name), + Config: testAccCodePipelineConfig_basicUpdated(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p2), @@ -141,7 +141,7 @@ func TestAccCodePipeline_disappears(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig_basic(name), + Config: testAccCodePipelineConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p), acctest.CheckResourceDisappears(acctest.Provider, tfcodepipeline.ResourceCodePipeline(), resourceName), @@ -168,7 +168,7 @@ func TestAccCodePipeline_emptyStageArtifacts(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig_emptyStageArtifacts(name), + Config: testAccCodePipelineConfig_emptyStageArtifacts(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "codepipeline", regexp.MustCompile(fmt.Sprintf("test-pipeline-%s$", name))), @@ -210,7 +210,7 @@ func TestAccCodePipeline_deployWithServiceRole(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig_deployWithServiceRole(name), + Config: testAccCodePipelineConfig_deployServiceRole(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p), resource.TestCheckResourceAttr(resourceName, "stage.2.name", "Deploy"), @@ -243,7 +243,7 @@ func TestAccCodePipeline_tags(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccWithTagsConfig(name, "tag1value", "tag2value"), + Config: testAccCodePipelineConfig_tags(name, "tag1value", "tag2value"), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p1), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -258,7 +258,7 @@ func TestAccCodePipeline_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccWithTagsConfig(name, "tag1valueUpdate", "tag2valueUpdate"), + Config: testAccCodePipelineConfig_tags(name, "tag1valueUpdate", "tag2valueUpdate"), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p2), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -273,7 +273,7 @@ func TestAccCodePipeline_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfig_basic(name), + Config: testAccCodePipelineConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p3), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -302,7 +302,7 @@ func TestAccCodePipeline_MultiRegion_basic(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig_multiregion(name), + Config: testAccCodePipelineConfig_multiregion(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p), resource.TestCheckResourceAttr(resourceName, "artifact_store.#", "2"), @@ -316,7 +316,7 @@ func TestAccCodePipeline_MultiRegion_basic(t *testing.T) { ), }, { - Config: testAccConfig_multiregion(name), + Config: testAccCodePipelineConfig_multiregion(name), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -344,7 +344,7 @@ func TestAccCodePipeline_MultiRegion_update(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig_multiregion(name), + Config: testAccCodePipelineConfig_multiregion(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p1), resource.TestCheckResourceAttr(resourceName, "artifact_store.#", "2"), @@ -358,7 +358,7 @@ func TestAccCodePipeline_MultiRegion_update(t *testing.T) { ), }, { - Config: testAccConfig_multiregionUpdated(name), + Config: testAccCodePipelineConfig_multiregionUpdated(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p2), resource.TestCheckResourceAttr(resourceName, "artifact_store.#", "2"), @@ -372,7 +372,7 @@ func TestAccCodePipeline_MultiRegion_update(t *testing.T) { ), }, { - Config: testAccConfig_multiregionUpdated(name), + Config: testAccCodePipelineConfig_multiregionUpdated(name), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -400,7 +400,7 @@ func TestAccCodePipeline_MultiRegion_convertSingleRegion(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig_basic(name), + Config: testAccCodePipelineConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p1), resource.TestCheckResourceAttr(resourceName, "artifact_store.#", "1"), @@ -412,7 +412,7 @@ func TestAccCodePipeline_MultiRegion_convertSingleRegion(t *testing.T) { ), }, { - Config: testAccConfig_multiregion(name), + Config: testAccCodePipelineConfig_multiregion(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p2), resource.TestCheckResourceAttr(resourceName, "artifact_store.#", "2"), @@ -426,7 +426,7 @@ func TestAccCodePipeline_MultiRegion_convertSingleRegion(t *testing.T) { ), }, { - Config: testAccConfig_backToBasic(name), + Config: testAccCodePipelineConfig_backToBasic(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p1), resource.TestCheckResourceAttr(resourceName, "artifact_store.#", "1"), @@ -438,7 +438,7 @@ func TestAccCodePipeline_MultiRegion_convertSingleRegion(t *testing.T) { ), }, { - Config: testAccConfig_backToBasic(name), + Config: testAccCodePipelineConfig_backToBasic(name), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -463,7 +463,7 @@ func TestAccCodePipeline_withNamespace(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccWithNamespaceConfig(name), + Config: testAccCodePipelineConfig_namespace(name), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &p1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "codepipeline", regexp.MustCompile(fmt.Sprintf("test-pipeline-%s", name))), @@ -496,7 +496,7 @@ func TestAccCodePipeline_withGitHubV1SourceAction(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccConfig_WithGitHubv1SourceAction(name, githubToken), + Config: testAccCodePipelineConfig_gitHubv1SourceAction(name, githubToken), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &v), @@ -524,7 +524,7 @@ func TestAccCodePipeline_withGitHubV1SourceAction(t *testing.T) { }, }, { - Config: testAccConfig_WithGitHubv1SourceAction_Updated(name, githubToken), + Config: testAccCodePipelineConfig_gitHubv1SourceActionUpdated(name, githubToken), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &v), @@ -749,7 +749,7 @@ EOF `, rName) } -func testAccConfig_basic(rName string) string { +func testAccCodePipelineConfig_basic(rName string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( testAccS3DefaultBucket(rName), testAccServiceIAMRole(rName), @@ -812,7 +812,7 @@ resource "aws_codestarconnections_connection" "test" { `, rName)) } -func testAccConfig_basicUpdated(rName string) string { +func testAccCodePipelineConfig_basicUpdated(rName string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( testAccS3DefaultBucket(rName), testAccS3Bucket("updated", rName), @@ -876,7 +876,7 @@ resource "aws_codestarconnections_connection" "test" { `, rName)) } -func testAccConfig_emptyStageArtifacts(rName string) string { +func testAccCodePipelineConfig_emptyStageArtifacts(rName string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( testAccS3DefaultBucket(rName), testAccServiceIAMRole(rName), @@ -986,7 +986,7 @@ EOF `, rName) } -func testAccConfig_deployWithServiceRole(rName string) string { +func testAccCodePipelineConfig_deployServiceRole(rName string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( testAccS3DefaultBucket(rName), testAccServiceIAMRoleWithAssumeRole(rName), @@ -1072,7 +1072,7 @@ resource "aws_codestarconnections_connection" "test" { `, rName)) } -func testAccWithTagsConfig(rName, tag1, tag2 string) string { +func testAccCodePipelineConfig_tags(rName, tag1, tag2 string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( testAccS3DefaultBucket(rName), testAccServiceIAMRole(rName), @@ -1141,7 +1141,7 @@ resource "aws_codestarconnections_connection" "test" { `, rName, tag1, tag2)) } -func testAccConfig_multiregion(rName string) string { +func testAccCodePipelineConfig_multiregion(rName string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( acctest.ConfigAlternateRegionProvider(), testAccS3DefaultBucket(rName), @@ -1235,7 +1235,7 @@ resource "aws_codestarconnections_connection" "test" { `, rName, acctest.Region(), acctest.AlternateRegion())) } -func testAccConfig_multiregionUpdated(rName string) string { +func testAccCodePipelineConfig_multiregionUpdated(rName string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( acctest.ConfigAlternateRegionProvider(), testAccS3DefaultBucket(rName), @@ -1329,10 +1329,10 @@ resource "aws_codestarconnections_connection" "test" { `, rName, acctest.Region(), acctest.AlternateRegion())) } -func testAccConfig_backToBasic(rName string) string { +func testAccCodePipelineConfig_backToBasic(rName string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( acctest.ConfigAlternateRegionProvider(), - testAccConfig_basic(rName), + testAccCodePipelineConfig_basic(rName), ) } @@ -1368,7 +1368,7 @@ resource "aws_s3_bucket_acl" "%[1]s" { `, bucket, rName, provider) } -func testAccWithNamespaceConfig(rName string) string { +func testAccCodePipelineConfig_namespace(rName string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( testAccS3DefaultBucket(rName), testAccServiceIAMRole(rName), @@ -1441,7 +1441,7 @@ resource "aws_s3_bucket_acl" "foo_acl" { `, rName)) } -func testAccConfig_WithGitHubv1SourceAction(rName, githubToken string) string { +func testAccCodePipelineConfig_gitHubv1SourceAction(rName, githubToken string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( testAccS3DefaultBucket(rName), testAccServiceIAMRole(rName), @@ -1500,7 +1500,7 @@ resource "aws_codepipeline" "test" { `, rName, githubToken)) } -func testAccConfig_WithGitHubv1SourceAction_Updated(rName, githubToken string) string { +func testAccCodePipelineConfig_gitHubv1SourceActionUpdated(rName, githubToken string) string { // nosemgrep:codepipeline-in-func-name return acctest.ConfigCompose( testAccS3DefaultBucket(rName), testAccServiceIAMRole(rName), diff --git a/internal/service/codepipeline/consts.go b/internal/service/codepipeline/consts.go index 4f66cbf2fd1..7293798b709 100644 --- a/internal/service/codepipeline/consts.go +++ b/internal/service/codepipeline/consts.go @@ -3,8 +3,8 @@ package codepipeline import "time" const ( - ResWebhook = "Webhook" - ResCodePipeline = "Pipeline" + ResWebhook = "Webhook" + resPipeline = "Pipeline" ) const ( diff --git a/internal/service/codepipeline/webhook_test.go b/internal/service/codepipeline/webhook_test.go index 2c09f85f991..f723f2a1008 100644 --- a/internal/service/codepipeline/webhook_test.go +++ b/internal/service/codepipeline/webhook_test.go @@ -15,10 +15,10 @@ import ( tfcodepipeline "github.com/hashicorp/terraform-provider-aws/internal/service/codepipeline" ) -const envVarGithubTokenUsageCodePipelineWebhook = "token with GitHub permissions to repository for CodePipeline webhook creation" +const envVarGithubTokenUsageWebhook = "token with GitHub permissions to repository for CodePipeline webhook creation" func TestAccCodePipelineWebhook_basic(t *testing.T) { - githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageCodePipelineWebhook) + githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageWebhook) var v codepipeline.ListWebhookItem rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -88,7 +88,7 @@ func TestAccCodePipelineWebhook_basic(t *testing.T) { } func TestAccCodePipelineWebhook_ipAuth(t *testing.T) { - githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageCodePipelineWebhook) + githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageWebhook) var v codepipeline.ListWebhookItem rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -123,7 +123,7 @@ func TestAccCodePipelineWebhook_ipAuth(t *testing.T) { } func TestAccCodePipelineWebhook_unauthenticated(t *testing.T) { - githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageCodePipelineWebhook) + githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageWebhook) var v codepipeline.ListWebhookItem rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -156,7 +156,7 @@ func TestAccCodePipelineWebhook_unauthenticated(t *testing.T) { } func TestAccCodePipelineWebhook_tags(t *testing.T) { - githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageCodePipelineWebhook) + githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageWebhook) var v1, v2, v3 codepipeline.ListWebhookItem rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -172,7 +172,7 @@ func TestAccCodePipelineWebhook_tags(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccWebhookWithTagsConfig(rName, "tag1value", "tag2value", githubToken), + Config: testAccWebhookConfig_tags(rName, "tag1value", "tag2value", githubToken), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -182,7 +182,7 @@ func TestAccCodePipelineWebhook_tags(t *testing.T) { ), }, { - Config: testAccWebhookWithTagsConfig(rName, "tag1valueUpdate", "tag2valueUpdate", githubToken), + Config: testAccWebhookConfig_tags(rName, "tag1valueUpdate", "tag2valueUpdate", githubToken), Check: resource.ComposeTestCheckFunc( testAccCheckWebhookExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -220,7 +220,7 @@ func TestAccCodePipelineWebhook_tags(t *testing.T) { } func TestAccCodePipelineWebhook_disappears(t *testing.T) { - githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageCodePipelineWebhook) + githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageWebhook) var v codepipeline.ListWebhookItem rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -249,7 +249,7 @@ func TestAccCodePipelineWebhook_disappears(t *testing.T) { } func TestAccCodePipelineWebhook_UpdateAuthentication_secretToken(t *testing.T) { - githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageCodePipelineWebhook) + githubToken := conns.SkipIfEnvVarEmpty(t, conns.EnvVarGithubToken, envVarGithubTokenUsageWebhook) var v1, v2 codepipeline.ListWebhookItem rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -400,7 +400,7 @@ resource "aws_codepipeline_webhook" "test" { `, rName) } -func testAccWebhookWithTagsConfig(rName, tag1, tag2, githubToken string) string { +func testAccWebhookConfig_tags(rName, tag1, tag2, githubToken string) string { return testAccWebhookConfig_base(rName, githubToken) + fmt.Sprintf(` resource "aws_codepipeline_webhook" "test" { name = %[1]q diff --git a/internal/service/codestarconnections/connection_data_source_test.go b/internal/service/codestarconnections/connection_data_source_test.go index 0269fb2dbc4..86566b37b7c 100644 --- a/internal/service/codestarconnections/connection_data_source_test.go +++ b/internal/service/codestarconnections/connection_data_source_test.go @@ -22,7 +22,7 @@ func TestAccCodeStarConnectionsConnectionDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectionBasicDataSourceConfig(rName), + Config: testAccConnectionDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "id"), resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), @@ -53,7 +53,7 @@ func TestAccCodeStarConnectionsConnectionDataSource_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectionTagsDataSourceConfig(rName), + Config: testAccConnectionDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "tags.%", dataSourceName, "tags.%"), ), @@ -62,7 +62,7 @@ func TestAccCodeStarConnectionsConnectionDataSource_tags(t *testing.T) { }) } -func testAccConnectionBasicDataSourceConfig(rName string) string { +func testAccConnectionDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_codestarconnections_connection" "test" { name = %[1]q @@ -79,7 +79,7 @@ data "aws_codestarconnections_connection" "test_name" { `, rName) } -func testAccConnectionTagsDataSourceConfig(rName string) string { +func testAccConnectionDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` resource "aws_codestarconnections_connection" "test" { name = %[1]q diff --git a/internal/service/codestarconnections/connection_test.go b/internal/service/codestarconnections/connection_test.go index 3d1c7078884..779f3df66a1 100644 --- a/internal/service/codestarconnections/connection_test.go +++ b/internal/service/codestarconnections/connection_test.go @@ -28,7 +28,7 @@ func TestAccCodeStarConnectionsConnection_basic(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionBasicConfig(rName), + Config: testAccConnectionConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "id", "codestar-connections", regexp.MustCompile("connection/.+")), @@ -59,7 +59,7 @@ func TestAccCodeStarConnectionsConnection_hostARN(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionHostARNConfig(rName), + Config: testAccConnectionConfig_hostARN(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "id", "codestar-connections", regexp.MustCompile("connection/.+")), @@ -91,7 +91,7 @@ func TestAccCodeStarConnectionsConnection_disappears(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionBasicConfig(rName), + Config: testAccConnectionConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfcodestarconnections.ResourceConnection(), resourceName), @@ -114,7 +114,7 @@ func TestAccCodeStarConnectionsConnection_tags(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionTags1Config(rName, "key1", "value1"), + Config: testAccConnectionConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -127,7 +127,7 @@ func TestAccCodeStarConnectionsConnection_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConnectionTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccConnectionConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -136,7 +136,7 @@ func TestAccCodeStarConnectionsConnection_tags(t *testing.T) { ), }, { - Config: testAccConnectionTags1Config(rName, "key2", "value2"), + Config: testAccConnectionConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -196,7 +196,7 @@ func testAccCheckConnectionDestroy(s *terraform.State) error { return nil } -func testAccConnectionBasicConfig(rName string) string { +func testAccConnectionConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_codestarconnections_connection" "test" { name = %[1]q @@ -205,7 +205,7 @@ resource "aws_codestarconnections_connection" "test" { `, rName) } -func testAccConnectionHostARNConfig(rName string) string { +func testAccConnectionConfig_hostARN(rName string) string { return fmt.Sprintf(` resource "aws_codestarconnections_host" "test" { name = %[1]q @@ -220,7 +220,7 @@ resource "aws_codestarconnections_connection" "test" { `, rName) } -func testAccConnectionTags1Config(rName string, tagKey1 string, tagValue1 string) string { +func testAccConnectionConfig_tags1(rName string, tagKey1 string, tagValue1 string) string { return fmt.Sprintf(` resource "aws_codestarconnections_connection" "test" { name = %[1]q @@ -233,7 +233,7 @@ resource "aws_codestarconnections_connection" "test" { `, rName, tagKey1, tagValue1) } -func testAccConnectionTags2Config(rName string, tagKey1 string, tagValue1 string, tagKey2 string, tagValue2 string) string { +func testAccConnectionConfig_tags2(rName string, tagKey1 string, tagValue1 string, tagKey2 string, tagValue2 string) string { return fmt.Sprintf(` resource "aws_codestarconnections_connection" "test" { name = %[1]q diff --git a/internal/service/codestarconnections/host_test.go b/internal/service/codestarconnections/host_test.go index f27ffabeb4e..f4a9ae897ad 100644 --- a/internal/service/codestarconnections/host_test.go +++ b/internal/service/codestarconnections/host_test.go @@ -28,7 +28,7 @@ func TestAccCodeStarConnectionsHost_basic(t *testing.T) { CheckDestroy: testAccCheckHostDestroy, Steps: []resource.TestStep{ { - Config: testAccHostBasicConfig(rName), + Config: testAccHostConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckHostExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "id", "codestar-connections", regexp.MustCompile("host/.+")), @@ -59,7 +59,7 @@ func TestAccCodeStarConnectionsHost_disappears(t *testing.T) { CheckDestroy: testAccCheckHostDestroy, Steps: []resource.TestStep{ { - Config: testAccHostBasicConfig(rName), + Config: testAccHostConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckHostExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfcodestarconnections.ResourceHost(), resourceName), @@ -82,7 +82,7 @@ func TestAccCodeStarConnectionsHost_vpc(t *testing.T) { CheckDestroy: testAccCheckHostDestroy, Steps: []resource.TestStep{ { - Config: testAccHostVPCConfig(rName), + Config: testAccHostConfig_vpc(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckHostExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "id", "codestar-connections", regexp.MustCompile("host/.+")), @@ -205,7 +205,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccHostBasicConfig(rName string) string { +func testAccHostConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_codestarconnections_host" "test" { name = %[1]q @@ -215,7 +215,7 @@ resource "aws_codestarconnections_host" "test" { `, rName) } -func testAccHostVPCConfig(rName string) string { +func testAccHostConfig_vpc(rName string) string { return acctest.ConfigCompose( testAccHostVPCBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/codestarnotifications/notification_rule.go b/internal/service/codestarnotifications/notification_rule.go index e01ddcba224..b5a5cc9a5a8 100644 --- a/internal/service/codestarnotifications/notification_rule.go +++ b/internal/service/codestarnotifications/notification_rule.go @@ -21,7 +21,7 @@ import ( const ( // Maximum amount of time to wait for target subscriptions to propagate - codestarNotificationsTargetSubscriptionTimeout = 30 * time.Second + targetSubscriptionTimeout = 30 * time.Second ) func ResourceNotificationRule() *schema.Resource { @@ -212,7 +212,7 @@ func resourceNotificationRuleRead(d *schema.ResourceData, meta interface{}) erro return nil } -const awsCodeStartNotificationsNotificationRuleErrorSubscribed = "The target cannot be deleted because it is subscribed to one or more notification rules." +const notificationRuleErrorSubscribed = "The target cannot be deleted because it is subscribed to one or more notification rules." // cleanupNotificationRuleTargets tries to remove unused notification targets. AWS API does not // provide expicit way for creating targets, they are created on first subscription. Here we are trying to remove all @@ -235,10 +235,10 @@ func cleanupNotificationRuleTargets(conn *codestarnotifications.CodeStarNotifica TargetAddress: aws.String(target["address"].(string)), } - err := resource.Retry(codestarNotificationsTargetSubscriptionTimeout, func() *resource.RetryError { + err := resource.Retry(targetSubscriptionTimeout, func() *resource.RetryError { _, err := conn.DeleteTarget(input) - if tfawserr.ErrMessageContains(err, codestarnotifications.ErrCodeValidationException, awsCodeStartNotificationsNotificationRuleErrorSubscribed) { + if tfawserr.ErrMessageContains(err, codestarnotifications.ErrCodeValidationException, notificationRuleErrorSubscribed) { return resource.RetryableError(err) } @@ -254,7 +254,7 @@ func cleanupNotificationRuleTargets(conn *codestarnotifications.CodeStarNotifica } // Treat target deletion as best effort - if tfawserr.ErrMessageContains(err, codestarnotifications.ErrCodeValidationException, awsCodeStartNotificationsNotificationRuleErrorSubscribed) { + if tfawserr.ErrMessageContains(err, codestarnotifications.ErrCodeValidationException, notificationRuleErrorSubscribed) { continue } diff --git a/internal/service/codestarnotifications/notification_rule_test.go b/internal/service/codestarnotifications/notification_rule_test.go index 9eecb0bf81f..232e3c07cb8 100644 --- a/internal/service/codestarnotifications/notification_rule_test.go +++ b/internal/service/codestarnotifications/notification_rule_test.go @@ -30,7 +30,7 @@ func TestAccCodeStarNotificationsNotificationRule_basic(t *testing.T) { CheckDestroy: testAccCheckNotificationRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNotificationRuleBasicConfig(rName), + Config: testAccNotificationRuleConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "codestar-notifications", regexp.MustCompile("notificationrule/.+")), resource.TestCheckResourceAttr(resourceName, "detail_type", codestarnotifications.DetailTypeBasic), @@ -61,7 +61,7 @@ func TestAccCodeStarNotificationsNotificationRule_status(t *testing.T) { CheckDestroy: testAccCheckNotificationRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNotificationRuleStatusConfig(rName, codestarnotifications.NotificationRuleStatusDisabled), + Config: testAccNotificationRuleConfig_status(rName, codestarnotifications.NotificationRuleStatusDisabled), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "status", codestarnotifications.NotificationRuleStatusDisabled), ), @@ -72,13 +72,13 @@ func TestAccCodeStarNotificationsNotificationRule_status(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotificationRuleStatusConfig(rName, codestarnotifications.NotificationRuleStatusEnabled), + Config: testAccNotificationRuleConfig_status(rName, codestarnotifications.NotificationRuleStatusEnabled), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "status", codestarnotifications.NotificationRuleStatusEnabled), ), }, { - Config: testAccNotificationRuleStatusConfig(rName, codestarnotifications.NotificationRuleStatusDisabled), + Config: testAccNotificationRuleConfig_status(rName, codestarnotifications.NotificationRuleStatusDisabled), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "status", codestarnotifications.NotificationRuleStatusDisabled), ), @@ -98,7 +98,7 @@ func TestAccCodeStarNotificationsNotificationRule_targets(t *testing.T) { CheckDestroy: testAccCheckNotificationRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNotificationRuleTargets1Config(rName), + Config: testAccNotificationRuleConfig_targets1(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "target.#", "1"), ), @@ -109,13 +109,13 @@ func TestAccCodeStarNotificationsNotificationRule_targets(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotificationRuleTargets2Config(rName), + Config: testAccNotificationRuleConfig_targets2(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "target.#", "2"), ), }, { - Config: testAccNotificationRuleTargets1Config(rName), + Config: testAccNotificationRuleConfig_targets1(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "target.#", "1"), ), @@ -135,7 +135,7 @@ func TestAccCodeStarNotificationsNotificationRule_tags(t *testing.T) { CheckDestroy: testAccCheckNotificationRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNotificationRuleTags1Config(rName), + Config: testAccNotificationRuleConfig_tags1(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.TestTag1", "123456"), @@ -148,7 +148,7 @@ func TestAccCodeStarNotificationsNotificationRule_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotificationRuleTags2Config(rName), + Config: testAccNotificationRuleConfig_tags2(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.TestTag2", "654321"), @@ -156,7 +156,7 @@ func TestAccCodeStarNotificationsNotificationRule_tags(t *testing.T) { ), }, { - Config: testAccNotificationRuleTags1Config(rName), + Config: testAccNotificationRuleConfig_tags1(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.TestTag1", "123456"), @@ -178,7 +178,7 @@ func TestAccCodeStarNotificationsNotificationRule_eventTypeIDs(t *testing.T) { CheckDestroy: testAccCheckNotificationRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNotificationRuleEventTypeIds1Config(rName), + Config: testAccNotificationRuleConfig_eventTypeIDs1(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_type_ids.#", "1"), ), @@ -189,13 +189,13 @@ func TestAccCodeStarNotificationsNotificationRule_eventTypeIDs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotificationRuleEventTypeIds2Config(rName), + Config: testAccNotificationRuleConfig_eventTypeIDs2(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_type_ids.#", "2"), ), }, { - Config: testAccNotificationRuleEventTypeIds3Config(rName), + Config: testAccNotificationRuleConfig_eventTypeIDs3(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "event_type_ids.#", "1"), ), @@ -273,7 +273,7 @@ resource "aws_sns_topic" "test" { `, rName) } -func testAccNotificationRuleBasicConfig(rName string) string { +func testAccNotificationRuleConfig_basic(rName string) string { return testAccNotificationRuleBaseConfig(rName) + fmt.Sprintf(` resource "aws_codestarnotifications_notification_rule" "test" { detail_type = "BASIC" @@ -293,7 +293,7 @@ resource "aws_codestarnotifications_notification_rule" "test" { `, rName) } -func testAccNotificationRuleStatusConfig(rName, status string) string { +func testAccNotificationRuleConfig_status(rName, status string) string { return testAccNotificationRuleBaseConfig(rName) + fmt.Sprintf(` resource "aws_codestarnotifications_notification_rule" "test" { detail_type = "BASIC" @@ -309,7 +309,7 @@ resource "aws_codestarnotifications_notification_rule" "test" { `, rName, status) } -func testAccNotificationRuleTargets1Config(rName string) string { +func testAccNotificationRuleConfig_targets1(rName string) string { return testAccNotificationRuleBaseConfig(rName) + fmt.Sprintf(` resource "aws_codestarnotifications_notification_rule" "test" { detail_type = "BASIC" @@ -324,7 +324,7 @@ resource "aws_codestarnotifications_notification_rule" "test" { `, rName) } -func testAccNotificationRuleTargets2Config(rName string) string { +func testAccNotificationRuleConfig_targets2(rName string) string { return testAccNotificationRuleBaseConfig(rName) + fmt.Sprintf(` resource "aws_sns_topic" "test2" { name = "%[1]s2" @@ -347,7 +347,7 @@ resource "aws_codestarnotifications_notification_rule" "test" { `, rName) } -func testAccNotificationRuleTags1Config(rName string) string { +func testAccNotificationRuleConfig_tags1(rName string) string { return testAccNotificationRuleBaseConfig(rName) + fmt.Sprintf(` resource "aws_codestarnotifications_notification_rule" "test" { detail_type = "BASIC" @@ -368,7 +368,7 @@ resource "aws_codestarnotifications_notification_rule" "test" { `, rName) } -func testAccNotificationRuleTags2Config(rName string) string { +func testAccNotificationRuleConfig_tags2(rName string) string { return testAccNotificationRuleBaseConfig(rName) + fmt.Sprintf(` resource "aws_codestarnotifications_notification_rule" "test" { detail_type = "BASIC" @@ -389,7 +389,7 @@ resource "aws_codestarnotifications_notification_rule" "test" { `, rName) } -func testAccNotificationRuleEventTypeIds1Config(rName string) string { +func testAccNotificationRuleConfig_eventTypeIDs1(rName string) string { return testAccNotificationRuleBaseConfig(rName) + fmt.Sprintf(` resource "aws_codestarnotifications_notification_rule" "test" { detail_type = "BASIC" @@ -407,7 +407,7 @@ resource "aws_codestarnotifications_notification_rule" "test" { `, rName) } -func testAccNotificationRuleEventTypeIds2Config(rName string) string { +func testAccNotificationRuleConfig_eventTypeIDs2(rName string) string { return testAccNotificationRuleBaseConfig(rName) + fmt.Sprintf(` resource "aws_codestarnotifications_notification_rule" "test" { detail_type = "BASIC" @@ -426,7 +426,7 @@ resource "aws_codestarnotifications_notification_rule" "test" { `, rName) } -func testAccNotificationRuleEventTypeIds3Config(rName string) string { +func testAccNotificationRuleConfig_eventTypeIDs3(rName string) string { return testAccNotificationRuleBaseConfig(rName) + fmt.Sprintf(` resource "aws_codestarnotifications_notification_rule" "test" { detail_type = "BASIC" diff --git a/internal/service/cognitoidentity/pool_test.go b/internal/service/cognitoidentity/pool_test.go index d7c82bb112a..f3fd1acfdfb 100644 --- a/internal/service/cognitoidentity/pool_test.go +++ b/internal/service/cognitoidentity/pool_test.go @@ -69,7 +69,7 @@ func TestAccCognitoIdentityPool_DeveloperProviderName(t *testing.T) { CheckDestroy: testAccCheckPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccPoolConfig_DeveloperProviderName(name, developerProviderName), + Config: testAccPoolConfig_developerProviderName(name, developerProviderName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckPoolExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "identity_pool_name", fmt.Sprintf("identity pool %s", name)), @@ -82,7 +82,7 @@ func TestAccCognitoIdentityPool_DeveloperProviderName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPoolConfig_DeveloperProviderName(name, developerProviderNameUpdated), + Config: testAccPoolConfig_developerProviderName(name, developerProviderNameUpdated), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckPoolExists(resourceName, &v2), testAccCheckPoolRecreated(&v1, &v2), @@ -251,7 +251,7 @@ func TestAccCognitoIdentityPool_cognitoIdentityProviders(t *testing.T) { CheckDestroy: testAccCheckPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccPoolConfig_cognitoIdentityProviders(name), + Config: testAccPoolConfig_identityProviders(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckPoolExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "identity_pool_name", fmt.Sprintf("identity pool %s", name)), @@ -274,7 +274,7 @@ func TestAccCognitoIdentityPool_cognitoIdentityProviders(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPoolConfig_cognitoIdentityProvidersModified(name), + Config: testAccPoolConfig_identityProvidersModified(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckPoolExists(resourceName, &v2), testAccCheckPoolNotRecreated(&v1, &v2), @@ -312,7 +312,7 @@ func TestAccCognitoIdentityPool_addingNewProviderKeepsOldProvider(t *testing.T) CheckDestroy: testAccCheckPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccPoolConfig_cognitoIdentityProviders(name), + Config: testAccPoolConfig_identityProviders(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckPoolExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "identity_pool_name", fmt.Sprintf("identity pool %s", name)), @@ -325,7 +325,7 @@ func TestAccCognitoIdentityPool_addingNewProviderKeepsOldProvider(t *testing.T) ImportStateVerify: true, }, { - Config: testAccPoolConfig_cognitoIdentityProvidersAndOpenidConnectProviderARNs(name), + Config: testAccPoolConfig_identityProvidersAndOpenIDConnectProviderARNs(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckPoolExists(resourceName, &v2), testAccCheckPoolNotRecreated(&v1, &v2), @@ -360,7 +360,7 @@ func TestAccCognitoIdentityPool_tags(t *testing.T) { CheckDestroy: testAccCheckPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccPoolConfig_Tags1(name, "key1", "value1"), + Config: testAccPoolConfig_tags1(name, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckPoolExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -373,7 +373,7 @@ func TestAccCognitoIdentityPool_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPoolConfig_Tags2(name, "key1", "value1updated", "key2", "value2"), + Config: testAccPoolConfig_tags2(name, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckPoolExists(resourceName, &v2), testAccCheckPoolNotRecreated(&v1, &v2), @@ -383,7 +383,7 @@ func TestAccCognitoIdentityPool_tags(t *testing.T) { ), }, { - Config: testAccPoolConfig_Tags1(name, "key2", "value2"), + Config: testAccPoolConfig_tags1(name, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckPoolExists(resourceName, &v3), testAccCheckPoolNotRecreated(&v2, &v3), @@ -502,7 +502,7 @@ resource "aws_cognito_identity_pool" "main" { `, name) } -func testAccPoolConfig_DeveloperProviderName(name, developerProviderName string) string { +func testAccPoolConfig_developerProviderName(name, developerProviderName string) string { return fmt.Sprintf(` resource "aws_cognito_identity_pool" "main" { identity_pool_name = "identity pool %[1]s" @@ -602,7 +602,7 @@ resource "aws_cognito_identity_pool" "main" { `, name, idpEntityId, secondaryIdpEntityId) } -func testAccPoolConfig_cognitoIdentityProviders(name string) string { +func testAccPoolConfig_identityProviders(name string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -627,7 +627,7 @@ resource "aws_cognito_identity_pool" "main" { `, name) } -func testAccPoolConfig_cognitoIdentityProvidersModified(name string) string { +func testAccPoolConfig_identityProvidersModified(name string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -646,7 +646,7 @@ resource "aws_cognito_identity_pool" "main" { `, name) } -func testAccPoolConfig_cognitoIdentityProvidersAndOpenidConnectProviderARNs(name string) string { +func testAccPoolConfig_identityProvidersAndOpenIDConnectProviderARNs(name string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -673,7 +673,7 @@ resource "aws_cognito_identity_pool" "main" { `, name) } -func testAccPoolConfig_Tags1(name, tagKey1, tagValue1 string) string { +func testAccPoolConfig_tags1(name, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_cognito_identity_pool" "main" { identity_pool_name = %q @@ -686,7 +686,7 @@ resource "aws_cognito_identity_pool" "main" { `, name, tagKey1, tagValue1) } -func testAccPoolConfig_Tags2(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccPoolConfig_tags2(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_cognito_identity_pool" "main" { identity_pool_name = %q diff --git a/internal/service/cognitoidp/consts.go b/internal/service/cognitoidp/consts.go index ab95f2a57c5..0292cd38217 100644 --- a/internal/service/cognitoidp/consts.go +++ b/internal/service/cognitoidp/consts.go @@ -3,13 +3,14 @@ package cognitoidp import "time" const ( - ResIdentityProvider = "Identity Provider" - ResResourceServer = "Resource Server" - ResUserGroup = "User Group" - ResUserPoolClient = "User Pool Client" - ResUserPoolDomain = "User Pool Domain" - ResUserPool = "User Pool" - ResUser = "User" + ResIdentityProvider = "Identity Provider" + ResResourceServer = "Resource Server" + ResRiskConfiguration = "Risk Configuration" + ResUserGroup = "User Group" + ResUserPoolClient = "User Pool Client" + ResUserPoolDomain = "User Pool Domain" + ResUserPool = "User Pool" + ResUser = "User" ) const ( diff --git a/internal/service/cognitoidp/find.go b/internal/service/cognitoidp/find.go index 1d5f833b872..b1f8672ed6e 100644 --- a/internal/service/cognitoidp/find.go +++ b/internal/service/cognitoidp/find.go @@ -6,6 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) // FindCognitoUserPoolUICustomization returns the UI Customization corresponding to the UserPoolId and ClientId. @@ -73,3 +76,63 @@ func FindCognitoUserInGroup(conn *cognitoidentityprovider.CognitoIdentityProvide return found, nil } + +func FindCognitoUserPoolClient(conn *cognitoidentityprovider.CognitoIdentityProvider, userPoolId, clientId string) (*cognitoidentityprovider.UserPoolClientType, error) { + input := &cognitoidentityprovider.DescribeUserPoolClientInput{ + ClientId: aws.String(clientId), + UserPoolId: aws.String(userPoolId), + } + + output, err := conn.DescribeUserPoolClient(input) + + if tfawserr.ErrCodeEquals(err, cognitoidentityprovider.ErrCodeResourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || output.UserPoolClient == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.UserPoolClient, nil +} + +func FindRiskConfigurationById(conn *cognitoidentityprovider.CognitoIdentityProvider, id string) (*cognitoidentityprovider.RiskConfigurationType, error) { + userPoolId, clientId, err := RiskConfigurationParseID(id) + if err != nil { + return nil, err + } + + input := &cognitoidentityprovider.DescribeRiskConfigurationInput{ + UserPoolId: aws.String(userPoolId), + } + + if clientId != "" { + input.ClientId = aws.String(clientId) + } + + output, err := conn.DescribeRiskConfiguration(input) + + if tfawserr.ErrCodeEquals(err, cognitoidentityprovider.ErrCodeResourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || output.RiskConfiguration == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.RiskConfiguration, nil +} diff --git a/internal/service/cognitoidp/identity_provider_test.go b/internal/service/cognitoidp/identity_provider_test.go index 178441033c9..aeef0140393 100644 --- a/internal/service/cognitoidp/identity_provider_test.go +++ b/internal/service/cognitoidp/identity_provider_test.go @@ -88,7 +88,7 @@ func TestAccCognitoIDPIdentityProvider_idpIdentifiers(t *testing.T) { CheckDestroy: testAccCheckIdentityProviderDestroy, Steps: []resource.TestStep{ { - Config: testAccIdentityProviderIDPIdentifierConfig(userPoolName, "test"), + Config: testAccIdentityProviderConfig_identifier(userPoolName, "test"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckIdentityProviderExists(resourceName, &identityProvider), resource.TestCheckResourceAttr(resourceName, "idp_identifiers.#", "1"), @@ -101,7 +101,7 @@ func TestAccCognitoIDPIdentityProvider_idpIdentifiers(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccIdentityProviderIDPIdentifierConfig(userPoolName, "test2"), + Config: testAccIdentityProviderConfig_identifier(userPoolName, "test2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckIdentityProviderExists(resourceName, &identityProvider), resource.TestCheckResourceAttr(resourceName, "idp_identifiers.#", "1"), @@ -281,7 +281,7 @@ resource "aws_cognito_identity_provider" "test" { `, userPoolName) } -func testAccIdentityProviderIDPIdentifierConfig(userPoolName, attribute string) string { +func testAccIdentityProviderConfig_identifier(userPoolName, attribute string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q diff --git a/internal/service/cognitoidp/resource_server_test.go b/internal/service/cognitoidp/resource_server_test.go index 220ab8a01cf..f0c65d54634 100644 --- a/internal/service/cognitoidp/resource_server_test.go +++ b/internal/service/cognitoidp/resource_server_test.go @@ -81,7 +81,7 @@ func TestAccCognitoIDPResourceServer_scope(t *testing.T) { ), }, { - Config: testAccResourceServerConfig_scope_update(identifier, name, poolName), + Config: testAccResourceServerConfig_scopeUpdate(identifier, name, poolName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckResourceServerExists(resourceName, &resourceServer), resource.TestCheckResourceAttr(resourceName, "scope.#", "1"), @@ -211,7 +211,7 @@ resource "aws_cognito_user_pool" "main" { `, identifier, name, poolName) } -func testAccResourceServerConfig_scope_update(identifier string, name string, poolName string) string { +func testAccResourceServerConfig_scopeUpdate(identifier string, name string, poolName string) string { return fmt.Sprintf(` resource "aws_cognito_resource_server" "main" { identifier = "%s" diff --git a/internal/service/cognitoidp/risk_configuration.go b/internal/service/cognitoidp/risk_configuration.go new file mode 100644 index 00000000000..37dd28adda0 --- /dev/null +++ b/internal/service/cognitoidp/risk_configuration.go @@ -0,0 +1,698 @@ +package cognitoidp + +import ( + "fmt" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" + "github.com/hashicorp/terraform-provider-aws/internal/verify" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func ResourceRiskConfiguration() *schema.Resource { + return &schema.Resource{ + Create: resourceRiskConfigurationPut, + Read: resourceRiskConfigurationRead, + Delete: resourceRiskConfigurationDelete, + Update: resourceRiskConfigurationPut, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "user_pool_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validUserPoolID, + }, + "client_id": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "account_takeover_risk_configuration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "actions": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "high_action": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "event_action": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(cognitoidentityprovider.AccountTakeoverEventActionType_Values(), false), + }, + "notify": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + }, + "low_action": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "event_action": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(cognitoidentityprovider.AccountTakeoverEventActionType_Values(), false), + }, + "notify": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + }, + "medium_action": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "event_action": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(cognitoidentityprovider.AccountTakeoverEventActionType_Values(), false), + }, + "notify": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + }, + }, + }, + }, + "notify_configuration": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "block_email": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "html_body": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(6, 2000), + }, + "subject": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 140), + }, + "text_body": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(6, 2000), + }, + }, + }, + }, + "from": { + Type: schema.TypeString, + Optional: true, + }, + "mfa_email": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "html_body": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(6, 2000), + }, + "subject": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 140), + }, + "text_body": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(6, 2000), + }, + }, + }, + }, + "no_action_email": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "html_body": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(6, 2000), + }, + "subject": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 140), + }, + "text_body": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(6, 2000), + }, + }, + }, + }, + "reply_to": { + Type: schema.TypeString, + Optional: true, + }, + "source_arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidARN, + }, + }, + }, + }, + }, + }, + }, + "compromised_credentials_risk_configuration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "event_filter": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(cognitoidentityprovider.EventFilterType_Values(), false), + }, + }, + "actions": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "event_action": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(cognitoidentityprovider.CompromisedCredentialsEventActionType_Values(), false), + }, + }, + }, + }, + }, + }, + }, + "risk_exception_configuration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "blocked_ip_range_list": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.All( + validation.StringLenBetween(0, 200), + validation.IsCIDR, + ), + }, + }, + "skipped_ip_range_list": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.All( + validation.StringLenBetween(0, 200), + validation.IsCIDR, + )}, + }, + }, + }, + }, + }, + } +} + +func resourceRiskConfigurationPut(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).CognitoIDPConn + + userPoolId := d.Get("user_pool_id").(string) + id := userPoolId + input := &cognitoidentityprovider.SetRiskConfigurationInput{ + UserPoolId: aws.String(userPoolId), + } + + if v, ok := d.GetOk("client_id"); ok { + input.ClientId = aws.String(v.(string)) + id = fmt.Sprintf("%s:%s", userPoolId, v.(string)) + } + + if v, ok := d.GetOk("risk_exception_configuration"); ok && len(v.([]interface{})) > 0 { + input.RiskExceptionConfiguration = expandRiskExceptionConfiguration(v.([]interface{})) + } + + if v, ok := d.GetOk("compromised_credentials_risk_configuration"); ok && len(v.([]interface{})) > 0 { + input.CompromisedCredentialsRiskConfiguration = expandCompromisedCredentialsRiskConfiguration(v.([]interface{})) + } + + if v, ok := d.GetOk("account_takeover_risk_configuration"); ok && len(v.([]interface{})) > 0 { + input.AccountTakeoverRiskConfiguration = expandAccountTakeoverRiskConfiguration(v.([]interface{})) + } + + _, err := conn.SetRiskConfiguration(input) + + if err != nil { + return fmt.Errorf("error setting risk configuration: %w", err) + } + + d.SetId(id) + + return resourceRiskConfigurationRead(d, meta) +} + +func resourceRiskConfigurationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).CognitoIDPConn + + riskConfig, err := FindRiskConfigurationById(conn, d.Id()) + + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, cognitoidentityprovider.ErrCodeResourceNotFoundException) { + names.LogNotFoundRemoveState(names.CognitoIDP, names.ErrActionReading, ResRiskConfiguration, d.Id()) + d.SetId("") + return nil + } + + userPoolId, clientId, err := RiskConfigurationParseID(d.Id()) + if err != nil { + return err + } + + d.Set("user_pool_id", userPoolId) + + if clientId != "" { + d.Set("client_id", clientId) + } + + if riskConfig.RiskExceptionConfiguration != nil { + if err := d.Set("risk_exception_configuration", flattenRiskExceptionConfiguration(riskConfig.RiskExceptionConfiguration)); err != nil { + return fmt.Errorf("error setting risk_exception_configuration: %w", err) + } + } + + if err := d.Set("compromised_credentials_risk_configuration", flattenCompromisedCredentialsRiskConfiguration(riskConfig.CompromisedCredentialsRiskConfiguration)); err != nil { + return fmt.Errorf("error setting compromised_credentials_risk_configuration: %w", err) + } + + if err := d.Set("account_takeover_risk_configuration", flattenAccountTakeoverRiskConfiguration(riskConfig.AccountTakeoverRiskConfiguration)); err != nil { + return fmt.Errorf("error setting account_takeover_risk_configuration: %w", err) + } + + return nil +} + +func resourceRiskConfigurationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).CognitoIDPConn + + userPoolId, clientId, err := RiskConfigurationParseID(d.Id()) + if err != nil { + return err + } + + input := &cognitoidentityprovider.SetRiskConfigurationInput{ + UserPoolId: aws.String(userPoolId), + } + + if clientId != "" { + input.ClientId = aws.String(clientId) + } + + _, err = conn.SetRiskConfiguration(input) + + if err != nil { + return fmt.Errorf("error removing risk configuration: %w", err) + } + + return nil +} + +func expandRiskExceptionConfiguration(riskConfig []interface{}) *cognitoidentityprovider.RiskExceptionConfigurationType { + config := riskConfig[0].(map[string]interface{}) + + riskExceptionConfigurationType := &cognitoidentityprovider.RiskExceptionConfigurationType{} + + if v, ok := config["blocked_ip_range_list"].(*schema.Set); ok && v.Len() > 0 { + riskExceptionConfigurationType.BlockedIPRangeList = flex.ExpandStringSet(v) + } + + if v, ok := config["skipped_ip_range_list"].(*schema.Set); ok && v.Len() > 0 { + riskExceptionConfigurationType.SkippedIPRangeList = flex.ExpandStringSet(v) + } + + return riskExceptionConfigurationType +} + +func flattenRiskExceptionConfiguration(apiObject *cognitoidentityprovider.RiskExceptionConfigurationType) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.BlockedIPRangeList; v != nil { + tfMap["blocked_ip_range_list"] = flex.FlattenStringSet(v) + } + + if v := apiObject.SkippedIPRangeList; v != nil { + tfMap["skipped_ip_range_list"] = flex.FlattenStringSet(v) + } + + return []interface{}{tfMap} +} + +func expandCompromisedCredentialsRiskConfiguration(riskConfig []interface{}) *cognitoidentityprovider.CompromisedCredentialsRiskConfigurationType { + config := riskConfig[0].(map[string]interface{}) + + riskExceptionConfigurationType := &cognitoidentityprovider.CompromisedCredentialsRiskConfigurationType{} + + if v, ok := config["event_filter"].(*schema.Set); ok && v.Len() > 0 { + riskExceptionConfigurationType.EventFilter = flex.ExpandStringSet(v) + } + + if v, ok := config["actions"].([]interface{}); ok && len(v) > 0 { + riskExceptionConfigurationType.Actions = expandCompromisedCredentialsActions(v) + } + + return riskExceptionConfigurationType +} + +func flattenCompromisedCredentialsRiskConfiguration(apiObject *cognitoidentityprovider.CompromisedCredentialsRiskConfigurationType) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.EventFilter; v != nil { + tfMap["event_filter"] = flex.FlattenStringSet(v) + } + + if v := apiObject.Actions; v != nil { + tfMap["actions"] = flattenCompromisedCredentialsActions(v) + } + + return []interface{}{tfMap} +} + +func expandCompromisedCredentialsActions(riskConfig []interface{}) *cognitoidentityprovider.CompromisedCredentialsActionsType { + config := riskConfig[0].(map[string]interface{}) + + compromisedCredentialsAction := &cognitoidentityprovider.CompromisedCredentialsActionsType{} + + if v, ok := config["event_action"].(string); ok && v != "" { + compromisedCredentialsAction.EventAction = aws.String(v) + } + + return compromisedCredentialsAction +} + +func flattenCompromisedCredentialsActions(apiObject *cognitoidentityprovider.CompromisedCredentialsActionsType) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.EventAction; v != nil { + tfMap["event_action"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +func expandAccountTakeoverRiskConfiguration(riskConfig []interface{}) *cognitoidentityprovider.AccountTakeoverRiskConfigurationType { + config := riskConfig[0].(map[string]interface{}) + + accountTakeoverRiskConfiguration := &cognitoidentityprovider.AccountTakeoverRiskConfigurationType{} + + if v, ok := config["notify_configuration"].([]interface{}); ok && len(v) > 0 { + accountTakeoverRiskConfiguration.NotifyConfiguration = expandNotifyConfiguration(v) + } + + if v, ok := config["actions"].([]interface{}); ok && len(v) > 0 { + accountTakeoverRiskConfiguration.Actions = expandAccountTakeoverActions(v) + } + + return accountTakeoverRiskConfiguration +} + +func flattenAccountTakeoverRiskConfiguration(apiObject *cognitoidentityprovider.AccountTakeoverRiskConfigurationType) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.Actions; v != nil { + tfMap["actions"] = flattenAccountTakeoverActions(v) + } + + if v := apiObject.NotifyConfiguration; v != nil { + tfMap["notify_configuration"] = flattenNotifyConfiguration(v) + } + + return []interface{}{tfMap} +} + +func expandAccountTakeoverActions(riskConfig []interface{}) *cognitoidentityprovider.AccountTakeoverActionsType { + config := riskConfig[0].(map[string]interface{}) + + actions := &cognitoidentityprovider.AccountTakeoverActionsType{} + + if v, ok := config["high_action"].([]interface{}); ok && len(v) > 0 { + actions.HighAction = expandAccountTakeoverAction(v) + } + + if v, ok := config["low_action"].([]interface{}); ok && len(v) > 0 { + actions.LowAction = expandAccountTakeoverAction(v) + } + + if v, ok := config["medium_action"].([]interface{}); ok && len(v) > 0 { + actions.MediumAction = expandAccountTakeoverAction(v) + } + + return actions +} + +func flattenAccountTakeoverActions(apiObject *cognitoidentityprovider.AccountTakeoverActionsType) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.HighAction; v != nil { + tfMap["high_action"] = flattenAccountTakeoverAction(v) + } + + if v := apiObject.LowAction; v != nil { + tfMap["low_action"] = flattenAccountTakeoverAction(v) + } + + if v := apiObject.MediumAction; v != nil { + tfMap["medium_action"] = flattenAccountTakeoverAction(v) + } + + return []interface{}{tfMap} +} + +func expandAccountTakeoverAction(riskConfig []interface{}) *cognitoidentityprovider.AccountTakeoverActionType { + config := riskConfig[0].(map[string]interface{}) + + action := &cognitoidentityprovider.AccountTakeoverActionType{} + + if v, ok := config["event_action"].(string); ok && v != "" { + action.EventAction = aws.String(v) + } + + if v, ok := config["notify"].(bool); ok { + action.Notify = aws.Bool(v) + } + + return action +} + +func flattenAccountTakeoverAction(apiObject *cognitoidentityprovider.AccountTakeoverActionType) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.EventAction; v != nil { + tfMap["event_action"] = aws.StringValue(v) + } + + if v := apiObject.Notify; v != nil { + tfMap["notify"] = aws.BoolValue(v) + } + + return []interface{}{tfMap} +} + +func expandNotifyConfiguration(riskConfig []interface{}) *cognitoidentityprovider.NotifyConfigurationType { + config := riskConfig[0].(map[string]interface{}) + + notifConfig := &cognitoidentityprovider.NotifyConfigurationType{} + + if v, ok := config["from"].(string); ok && v != "" { + notifConfig.From = aws.String(v) + } + + if v, ok := config["reply_to"].(string); ok && v != "" { + notifConfig.ReplyTo = aws.String(v) + } + + if v, ok := config["source_arn"].(string); ok && v != "" { + notifConfig.SourceArn = aws.String(v) + } + + if v, ok := config["block_email"].([]interface{}); ok && len(v) > 0 { + notifConfig.BlockEmail = expandNotifyEmail(v) + } + + if v, ok := config["mfa_email"].([]interface{}); ok && len(v) > 0 { + notifConfig.MfaEmail = expandNotifyEmail(v) + } + + if v, ok := config["no_action_email"].([]interface{}); ok && len(v) > 0 { + notifConfig.NoActionEmail = expandNotifyEmail(v) + } + + return notifConfig +} + +func flattenNotifyConfiguration(apiObject *cognitoidentityprovider.NotifyConfigurationType) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.From; v != nil { + tfMap["from"] = aws.StringValue(v) + } + + if v := apiObject.ReplyTo; v != nil { + tfMap["reply_to"] = aws.StringValue(v) + } + + if v := apiObject.SourceArn; v != nil { + tfMap["source_arn"] = aws.StringValue(v) + } + + if v := apiObject.BlockEmail; v != nil { + tfMap["block_email"] = flattenNotifyEmail(v) + } + + if v := apiObject.MfaEmail; v != nil { + tfMap["mfa_email"] = flattenNotifyEmail(v) + } + + if v := apiObject.NoActionEmail; v != nil { + tfMap["no_action_email"] = flattenNotifyEmail(v) + } + + return []interface{}{tfMap} +} + +func expandNotifyEmail(riskConfig []interface{}) *cognitoidentityprovider.NotifyEmailType { + config := riskConfig[0].(map[string]interface{}) + + notifyEmail := &cognitoidentityprovider.NotifyEmailType{} + + if v, ok := config["html_body"].(string); ok && v != "" { + notifyEmail.HtmlBody = aws.String(v) + } + + if v, ok := config["subject"].(string); ok && v != "" { + notifyEmail.Subject = aws.String(v) + } + + if v, ok := config["text_body"].(string); ok && v != "" { + notifyEmail.TextBody = aws.String(v) + } + + return notifyEmail +} + +func flattenNotifyEmail(apiObject *cognitoidentityprovider.NotifyEmailType) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.HtmlBody; v != nil { + tfMap["html_body"] = aws.StringValue(v) + } + + if v := apiObject.Subject; v != nil { + tfMap["subject"] = aws.StringValue(v) + } + + if v := apiObject.TextBody; v != nil { + tfMap["text_body"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +func RiskConfigurationParseID(id string) (string, string, error) { + parts := strings.Split(id, ":") + + if len(parts) > 2 || len(parts) < 1 { + return "", "", fmt.Errorf("Wrong format of resource: %s. Please follow 'userpool-id/client-id' or 'userpool-id'", id) + } + + if len(parts) == 2 { + return parts[0], parts[1], nil + } else { + return parts[0], "", nil + + } +} diff --git a/internal/service/cognitoidp/risk_configuration_test.go b/internal/service/cognitoidp/risk_configuration_test.go new file mode 100644 index 00000000000..66b8cee18b5 --- /dev/null +++ b/internal/service/cognitoidp/risk_configuration_test.go @@ -0,0 +1,271 @@ +package cognitoidp_test + +import ( + "errors" + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfcognitoidp "github.com/hashicorp/terraform-provider-aws/internal/service/cognitoidp" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccCognitoIDPRiskConfiguration_exception(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_cognito_risk_configuration.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIdentityProvider(t) }, + ErrorCheck: acctest.ErrorCheck(t, cognitoidentityprovider.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckRiskConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRiskConfigurationConfig_riskException(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckRiskConfigurationExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "user_pool_id", "aws_cognito_user_pool.test", "id"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.0.blocked_ip_range_list.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "risk_exception_configuration.0.blocked_ip_range_list.*", "10.10.10.10/32"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.0.skipped_ip_range_list.#", "0"), + resource.TestCheckResourceAttr(resourceName, "compromised_credentials_risk_configuration.#", "0"), + resource.TestCheckResourceAttr(resourceName, "account_takeover_risk_configuration.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccRiskConfigurationConfig_riskExceptionUpdated(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckRiskConfigurationExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "user_pool_id", "aws_cognito_user_pool.test", "id"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.0.blocked_ip_range_list.#", "2"), + resource.TestCheckTypeSetElemAttr(resourceName, "risk_exception_configuration.0.blocked_ip_range_list.*", "10.10.10.10/32"), + resource.TestCheckTypeSetElemAttr(resourceName, "risk_exception_configuration.0.blocked_ip_range_list.*", "10.10.10.11/32"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.0.skipped_ip_range_list.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "risk_exception_configuration.0.skipped_ip_range_list.*", "10.10.10.12/32"), + resource.TestCheckResourceAttr(resourceName, "compromised_credentials_risk_configuration.#", "0"), + resource.TestCheckResourceAttr(resourceName, "account_takeover_risk_configuration.#", "0"), + ), + }, + }, + }) +} + +func TestAccCognitoIDPRiskConfiguration_client(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_cognito_risk_configuration.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIdentityProvider(t) }, + ErrorCheck: acctest.ErrorCheck(t, cognitoidentityprovider.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckRiskConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRiskConfigurationConfig_riskExceptionClient(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckRiskConfigurationExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "user_pool_id", "aws_cognito_user_pool.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "client_id", "aws_cognito_user_pool_client.test", "id"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.0.blocked_ip_range_list.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "risk_exception_configuration.0.blocked_ip_range_list.*", "10.10.10.10/32"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.0.skipped_ip_range_list.#", "0"), + resource.TestCheckResourceAttr(resourceName, "compromised_credentials_risk_configuration.#", "0"), + resource.TestCheckResourceAttr(resourceName, "account_takeover_risk_configuration.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccCognitoIDPRiskConfiguration_compromised(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_cognito_risk_configuration.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIdentityProvider(t) }, + ErrorCheck: acctest.ErrorCheck(t, cognitoidentityprovider.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckRiskConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRiskConfigurationConfig_compromised(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckRiskConfigurationExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "user_pool_id", "aws_cognito_user_pool.test", "id"), + resource.TestCheckResourceAttr(resourceName, "risk_exception_configuration.#", "0"), + resource.TestCheckResourceAttr(resourceName, "compromised_credentials_risk_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "compromised_credentials_risk_configuration.0.event_filter.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "compromised_credentials_risk_configuration.0.event_filter.*", "SIGN_IN"), + resource.TestCheckResourceAttr(resourceName, "compromised_credentials_risk_configuration.0.actions.#", "1"), + resource.TestCheckResourceAttr(resourceName, "compromised_credentials_risk_configuration.0.actions.0.event_action", "BLOCK"), + resource.TestCheckResourceAttr(resourceName, "account_takeover_risk_configuration.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccCognitoIDPRiskConfiguration_disappears_userPool(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_cognito_risk_configuration.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIdentityProvider(t) }, + ErrorCheck: acctest.ErrorCheck(t, cognitoidentityprovider.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckRiskConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRiskConfigurationConfig_riskException(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckRiskConfigurationExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfcognitoidp.ResourceUserPool(), "aws_cognito_user_pool.test"), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckRiskConfigurationDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).CognitoIDPConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_cognito_risk_configuration" { + continue + } + + _, err := tfcognitoidp.FindRiskConfigurationById(conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + } + + return nil +} + +func testAccCheckRiskConfigurationExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + if rs.Primary.ID == "" { + return errors.New("No Cognito Risk Configuration ID set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).CognitoIDPConn + + _, err := tfcognitoidp.FindRiskConfigurationById(conn, rs.Primary.ID) + + if err != nil { + return err + } + + return nil + } +} + +func testAccRiskConfigurationConfig_riskException(rName string) string { + return fmt.Sprintf(` +resource "aws_cognito_user_pool" "test" { + name = %[1]q +} + +resource "aws_cognito_risk_configuration" "test" { + user_pool_id = aws_cognito_user_pool.test.id + + risk_exception_configuration { + blocked_ip_range_list = ["10.10.10.10/32"] + } +} +`, rName) +} + +func testAccRiskConfigurationConfig_riskExceptionUpdated(rName string) string { + return fmt.Sprintf(` +resource "aws_cognito_user_pool" "test" { + name = %[1]q +} + +resource "aws_cognito_risk_configuration" "test" { + user_pool_id = aws_cognito_user_pool.test.id + + risk_exception_configuration { + blocked_ip_range_list = ["10.10.10.10/32", "10.10.10.11/32"] + skipped_ip_range_list = ["10.10.10.12/32"] + } +} +`, rName) +} + +func testAccRiskConfigurationConfig_compromised(rName string) string { + return fmt.Sprintf(` +resource "aws_cognito_user_pool" "test" { + name = %[1]q +} + +resource "aws_cognito_risk_configuration" "test" { + user_pool_id = aws_cognito_user_pool.test.id + + compromised_credentials_risk_configuration { + event_filter = ["SIGN_IN"] + actions { + event_action = "BLOCK" + } + } +} +`, rName) +} + +func testAccRiskConfigurationConfig_riskExceptionClient(rName string) string { + return fmt.Sprintf(` +resource "aws_cognito_user_pool" "test" { + name = %[1]q +} + +resource "aws_cognito_user_pool_client" "test" { + name = %[1]q + user_pool_id = aws_cognito_user_pool.test.id + explicit_auth_flows = ["ADMIN_NO_SRP_AUTH"] +} + +resource "aws_cognito_risk_configuration" "test" { + user_pool_id = aws_cognito_user_pool.test.id + client_id = aws_cognito_user_pool_client.test.id + + risk_exception_configuration { + blocked_ip_range_list = ["10.10.10.10/32"] + } +} +`, rName) +} diff --git a/internal/service/cognitoidp/user_group_test.go b/internal/service/cognitoidp/user_group_test.go index 55a93779870..f74cb33c964 100644 --- a/internal/service/cognitoidp/user_group_test.go +++ b/internal/service/cognitoidp/user_group_test.go @@ -102,7 +102,7 @@ func TestAccCognitoIDPUserGroup_roleARN(t *testing.T) { CheckDestroy: testAccCheckUserGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccUserGroupConfig_RoleARN(rName), + Config: testAccUserGroupConfig_roleARN(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserGroupExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "role_arn"), @@ -114,7 +114,7 @@ func TestAccCognitoIDPUserGroup_roleARN(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserGroupConfig_RoleARN_Updated(rName), + Config: testAccUserGroupConfig_roleARNUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserGroupExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "role_arn"), @@ -245,7 +245,7 @@ resource "aws_cognito_user_group" "main" { `, poolName, groupName, groupDescription, precedence) } -func testAccUserGroupConfig_RoleARN(rName string) string { +func testAccUserGroupConfig_roleARN(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "main" { name = "%[1]s" @@ -279,7 +279,7 @@ resource "aws_cognito_user_group" "main" { `, rName) } -func testAccUserGroupConfig_RoleARN_Updated(rName string) string { +func testAccUserGroupConfig_roleARNUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "main" { name = "%[1]s" diff --git a/internal/service/cognitoidp/user_in_group_test.go b/internal/service/cognitoidp/user_in_group_test.go index 9edba45ae90..77caf9a4938 100644 --- a/internal/service/cognitoidp/user_in_group_test.go +++ b/internal/service/cognitoidp/user_in_group_test.go @@ -15,7 +15,7 @@ import ( tfcognitoidp "github.com/hashicorp/terraform-provider-aws/internal/service/cognitoidp" ) -func TestAccCognitoUserInGroup_basic(t *testing.T) { +func TestAccCognitoIDPUserInGroup_basic(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_cognito_user_in_group.test" userPoolResourceName := "aws_cognito_user_pool.test" @@ -29,7 +29,7 @@ func TestAccCognitoUserInGroup_basic(t *testing.T) { CheckDestroy: testAccCheckUserInGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigUserInGroup_basic(rName), + Config: testAccUserInGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserInGroupExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "user_pool_id", userPoolResourceName, "id"), @@ -41,7 +41,7 @@ func TestAccCognitoUserInGroup_basic(t *testing.T) { }) } -func TestAccCognitoUserInGroup_disappears(t *testing.T) { +func TestAccCognitoIDPUserInGroup_disappears(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_cognito_user_in_group.test" @@ -52,7 +52,7 @@ func TestAccCognitoUserInGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckUserInGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigUserInGroup_basic(rName), + Config: testAccUserInGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserInGroupExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcognitoidp.ResourceUserInGroup(), resourceName), @@ -63,7 +63,7 @@ func TestAccCognitoUserInGroup_disappears(t *testing.T) { }) } -func testAccConfigUserInGroup_basic(rName string) string { +func testAccUserInGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q diff --git a/internal/service/cognitoidp/user_pool.go b/internal/service/cognitoidp/user_pool.go index 903bc528841..3fe0c45e8dc 100644 --- a/internal/service/cognitoidp/user_pool.go +++ b/internal/service/cognitoidp/user_pool.go @@ -600,10 +600,7 @@ func resourceUserPoolCreate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("account_recovery_setting"); ok { - configs := v.([]interface{}) - config, ok := configs[0].(map[string]interface{}) - - if ok && config != nil { + if config, ok := v.([]interface{})[0].(map[string]interface{}); ok { params.AccountRecoverySetting = expandUserPoolAccountRecoverySettingConfig(config) } } @@ -1043,10 +1040,7 @@ func resourceUserPoolUpdate(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("account_recovery_setting"); ok { - configs := v.([]interface{}) - config, ok := configs[0].(map[string]interface{}) - - if ok && config != nil { + if config, ok := v.([]interface{})[0].(map[string]interface{}); ok { params.AccountRecoverySetting = expandUserPoolAccountRecoverySettingConfig(config) } } @@ -1287,6 +1281,10 @@ func flattenSoftwareTokenMFAConfiguration(apiObject *cognitoidentityprovider.Sof } func expandUserPoolAccountRecoverySettingConfig(config map[string]interface{}) *cognitoidentityprovider.AccountRecoverySettingType { + if len(config) == 0 { + return nil + } + configs := &cognitoidentityprovider.AccountRecoverySettingType{} mechs := make([]*cognitoidentityprovider.RecoveryOptionType, 0) @@ -1316,7 +1314,7 @@ func expandUserPoolAccountRecoverySettingConfig(config map[string]interface{}) * } func flattenUserPoolAccountRecoverySettingConfig(config *cognitoidentityprovider.AccountRecoverySettingType) []interface{} { - if config == nil { + if config == nil || len(config.RecoveryMechanisms) == 0 { return nil } diff --git a/internal/service/cognitoidp/user_pool_client.go b/internal/service/cognitoidp/user_pool_client.go index e7f687ebd1b..97ae30bdfbc 100644 --- a/internal/service/cognitoidp/user_pool_client.go +++ b/internal/service/cognitoidp/user_pool_client.go @@ -133,6 +133,10 @@ func ResourceUserPoolClient() *schema.Resource { Optional: true, Computed: true, }, + "enable_propagate_additional_user_context_data": { + Type: schema.TypeBool, + Optional: true, + }, "explicit_auth_flows": { Type: schema.TypeSet, Optional: true, @@ -328,6 +332,10 @@ func resourceUserPoolClientCreate(d *schema.ResourceData, meta interface{}) erro params.EnableTokenRevocation = aws.Bool(v.(bool)) } + if v, ok := d.GetOk("enable_propagate_additional_user_context_data"); ok { + params.EnablePropagateAdditionalUserContextData = aws.Bool(v.(bool)) + } + log.Printf("[DEBUG] Creating Cognito User Pool Client: %s", params) resp, err := conn.CreateUserPoolClient(params) @@ -344,16 +352,9 @@ func resourceUserPoolClientCreate(d *schema.ResourceData, meta interface{}) erro func resourceUserPoolClientRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).CognitoIDPConn - params := &cognitoidentityprovider.DescribeUserPoolClientInput{ - ClientId: aws.String(d.Id()), - UserPoolId: aws.String(d.Get("user_pool_id").(string)), - } - - log.Printf("[DEBUG] Reading Cognito User Pool Client: %s", params) + userPoolClient, err := FindCognitoUserPoolClient(conn, d.Get("user_pool_id").(string), d.Id()) - resp, err := conn.DescribeUserPoolClient(params) - - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, cognitoidentityprovider.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && tfresource.NotFound(err) { names.LogNotFoundRemoveState(names.CognitoIDP, names.ErrActionReading, ResUserPoolClient, d.Id()) d.SetId("") return nil @@ -363,7 +364,6 @@ func resourceUserPoolClientRead(d *schema.ResourceData, meta interface{}) error return names.Error(names.CognitoIDP, names.ErrActionReading, ResUserPoolClient, d.Id(), err) } - userPoolClient := resp.UserPoolClient d.Set("user_pool_id", userPoolClient.UserPoolId) d.Set("name", userPoolClient.ClientName) d.Set("explicit_auth_flows", flex.FlattenStringSet(userPoolClient.ExplicitAuthFlows)) @@ -382,6 +382,7 @@ func resourceUserPoolClientRead(d *schema.ResourceData, meta interface{}) error d.Set("prevent_user_existence_errors", userPoolClient.PreventUserExistenceErrors) d.Set("supported_identity_providers", flex.FlattenStringSet(userPoolClient.SupportedIdentityProviders)) d.Set("enable_token_revocation", userPoolClient.EnableTokenRevocation) + d.Set("enable_propagate_additional_user_context_data", userPoolClient.EnablePropagateAdditionalUserContextData) if err := d.Set("analytics_configuration", flattenUserPoolClientAnalyticsConfig(userPoolClient.AnalyticsConfiguration)); err != nil { return fmt.Errorf("error setting analytics_configuration: %w", err) @@ -471,6 +472,10 @@ func resourceUserPoolClientUpdate(d *schema.ResourceData, meta interface{}) erro params.TokenValidityUnits = expandUserPoolClientTokenValidityUnitsType(v.([]interface{})) } + if v, ok := d.GetOk("enable_propagate_additional_user_context_data"); ok { + params.EnablePropagateAdditionalUserContextData = aws.Bool(v.(bool)) + } + log.Printf("[DEBUG] Updating Cognito User Pool Client: %s", params) _, err := tfresource.RetryWhenAWSErrCodeEquals(2*time.Minute, func() (interface{}, error) { diff --git a/internal/service/cognitoidp/user_pool_client_data_source.go b/internal/service/cognitoidp/user_pool_client_data_source.go index 065bef78806..2639fbc5ab7 100644 --- a/internal/service/cognitoidp/user_pool_client_data_source.go +++ b/internal/service/cognitoidp/user_pool_client_data_source.go @@ -2,10 +2,7 @@ package cognitoidp import ( "fmt" - "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/flex" @@ -90,6 +87,10 @@ func DataSourceUserPoolClient() *schema.Resource { Type: schema.TypeBool, Computed: true, }, + "enable_propagate_additional_user_context_data": { + Type: schema.TypeBool, + Computed: true, + }, "explicit_auth_flows": { Type: schema.TypeSet, Computed: true, @@ -179,20 +180,12 @@ func dataSourceUserPoolClientRead(d *schema.ResourceData, meta interface{}) erro clientId := d.Get("client_id").(string) d.SetId(clientId) - params := &cognitoidentityprovider.DescribeUserPoolClientInput{ - ClientId: aws.String(clientId), - UserPoolId: aws.String(d.Get("user_pool_id").(string)), - } - - log.Printf("[DEBUG] Reading Cognito User Pool Client: %s", params) - - resp, err := conn.DescribeUserPoolClient(params) + userPoolClient, err := FindCognitoUserPoolClient(conn, d.Get("user_pool_id").(string), d.Id()) if err != nil { return fmt.Errorf("error reading Cognito User Pool Client (%s): %w", clientId, err) } - userPoolClient := resp.UserPoolClient d.Set("user_pool_id", userPoolClient.UserPoolId) d.Set("name", userPoolClient.ClientName) d.Set("explicit_auth_flows", flex.FlattenStringSet(userPoolClient.ExplicitAuthFlows)) @@ -211,6 +204,7 @@ func dataSourceUserPoolClientRead(d *schema.ResourceData, meta interface{}) erro d.Set("prevent_user_existence_errors", userPoolClient.PreventUserExistenceErrors) d.Set("supported_identity_providers", flex.FlattenStringSet(userPoolClient.SupportedIdentityProviders)) d.Set("enable_token_revocation", userPoolClient.EnableTokenRevocation) + d.Set("enable_propagate_additional_user_context_data", userPoolClient.EnablePropagateAdditionalUserContextData) if err := d.Set("analytics_configuration", flattenUserPoolClientAnalyticsConfig(userPoolClient.AnalyticsConfiguration)); err != nil { return fmt.Errorf("error setting analytics_configuration: %w", err) diff --git a/internal/service/cognitoidp/user_pool_client_data_source_test.go b/internal/service/cognitoidp/user_pool_client_data_source_test.go index fc6788756e6..cd955665754 100644 --- a/internal/service/cognitoidp/user_pool_client_data_source_test.go +++ b/internal/service/cognitoidp/user_pool_client_data_source_test.go @@ -21,7 +21,7 @@ func TestAccCognitoIDPUserPoolClientDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientConfigDataSource_basic(rName), + Config: testAccUserPoolClientDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -35,7 +35,7 @@ func TestAccCognitoIDPUserPoolClientDataSource_basic(t *testing.T) { }) } -func testAccUserPoolClientConfigDataSource_basic(rName string) string { +func testAccUserPoolClientDataSourceConfig_basic(rName string) string { return testAccUserPoolClientConfig_basic(rName) + ` data "aws_cognito_user_pool_client" "test" { user_pool_id = aws_cognito_user_pool.test.id diff --git a/internal/service/cognitoidp/user_pool_client_test.go b/internal/service/cognitoidp/user_pool_client_test.go index b9641607a17..2804a1dce09 100644 --- a/internal/service/cognitoidp/user_pool_client_test.go +++ b/internal/service/cognitoidp/user_pool_client_test.go @@ -5,16 +5,15 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfcognitoidp "github.com/hashicorp/terraform-provider-aws/internal/service/cognitoidp" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func TestAccCognitoIDPUserPoolClient_basic(t *testing.T) { @@ -62,7 +61,7 @@ func TestAccCognitoIDPUserPoolClient_enableRevocation(t *testing.T) { CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientRevocationConfig(rName, true), + Config: testAccUserPoolClientConfig_revocation(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -76,7 +75,7 @@ func TestAccCognitoIDPUserPoolClient_enableRevocation(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolClientRevocationConfig(rName, false), + Config: testAccUserPoolClientConfig_revocation(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -84,7 +83,7 @@ func TestAccCognitoIDPUserPoolClient_enableRevocation(t *testing.T) { ), }, { - Config: testAccUserPoolClientRevocationConfig(rName, true), + Config: testAccUserPoolClientConfig_revocation(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -107,7 +106,7 @@ func TestAccCognitoIDPUserPoolClient_refreshTokenValidity(t *testing.T) { CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientConfig_RefreshTokenValidity(rName, 60), + Config: testAccUserPoolClientConfig_refreshTokenValidity(rName, 60), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "refresh_token_validity", "60"), @@ -120,7 +119,7 @@ func TestAccCognitoIDPUserPoolClient_refreshTokenValidity(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolClientConfig_RefreshTokenValidity(rName, 120), + Config: testAccUserPoolClientConfig_refreshTokenValidity(rName, 120), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "refresh_token_validity", "120"), @@ -142,7 +141,7 @@ func TestAccCognitoIDPUserPoolClient_accessTokenValidity(t *testing.T) { CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientAccessTokenValidityConfig(rName, 5), + Config: testAccUserPoolClientConfig_accessTokenValidity(rName, 5), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "access_token_validity", "5"), @@ -155,7 +154,7 @@ func TestAccCognitoIDPUserPoolClient_accessTokenValidity(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolClientAccessTokenValidityConfig(rName, 1), + Config: testAccUserPoolClientConfig_accessTokenValidity(rName, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "access_token_validity", "1"), @@ -177,7 +176,7 @@ func TestAccCognitoIDPUserPoolClient_idTokenValidity(t *testing.T) { CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientIDTokenValidityConfig(rName, 5), + Config: testAccUserPoolClientConfig_idTokenValidity(rName, 5), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "id_token_validity", "5"), @@ -190,7 +189,7 @@ func TestAccCognitoIDPUserPoolClient_idTokenValidity(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolClientIDTokenValidityConfig(rName, 1), + Config: testAccUserPoolClientConfig_idTokenValidity(rName, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "id_token_validity", "1"), @@ -212,7 +211,7 @@ func TestAccCognitoIDPUserPoolClient_tokenValidityUnits(t *testing.T) { CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientTokenValidityUnitsConfig(rName, "days"), + Config: testAccUserPoolClientConfig_tokenValidityUnits(rName, "days"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "token_validity_units.#", "1"), @@ -228,7 +227,7 @@ func TestAccCognitoIDPUserPoolClient_tokenValidityUnits(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolClientTokenValidityUnitsConfig(rName, "hours"), + Config: testAccUserPoolClientConfig_tokenValidityUnits(rName, "hours"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "token_validity_units.#", "1"), @@ -253,7 +252,7 @@ func TestAccCognitoIDPUserPoolClient_tokenValidityUnitsWTokenValidity(t *testing CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientTokenValidityUnitsWithTokenValidityConfig(rName, "days"), + Config: testAccUserPoolClientConfig_tokenValidityUnitsTokenValidity(rName, "days"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "token_validity_units.#", "1"), @@ -270,7 +269,7 @@ func TestAccCognitoIDPUserPoolClient_tokenValidityUnitsWTokenValidity(t *testing ImportStateVerify: true, }, { - Config: testAccUserPoolClientTokenValidityUnitsWithTokenValidityConfig(rName, "hours"), + Config: testAccUserPoolClientConfig_tokenValidityUnitsTokenValidity(rName, "hours"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "token_validity_units.#", "1"), @@ -296,7 +295,7 @@ func TestAccCognitoIDPUserPoolClient_name(t *testing.T) { CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientConfig_Name(rName, "name1"), + Config: testAccUserPoolClientConfig_name(rName, "name1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "name", "name1"), @@ -309,7 +308,7 @@ func TestAccCognitoIDPUserPoolClient_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolClientConfig_Name(rName, "name2"), + Config: testAccUserPoolClientConfig_name(rName, "name2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "name", "name2"), @@ -451,7 +450,7 @@ func TestAccCognitoIDPUserPoolClient_analytics(t *testing.T) { CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientAnalyticsConfig(rName), + Config: testAccUserPoolClientConfig_analytics(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "analytics_configuration.#", "1"), @@ -474,7 +473,7 @@ func TestAccCognitoIDPUserPoolClient_analytics(t *testing.T) { ), }, { - Config: testAccUserPoolClientAnalyticsShareUserDataConfig(rName), + Config: testAccUserPoolClientConfig_analyticsShareData(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "analytics_configuration.#", "1"), @@ -503,7 +502,7 @@ func TestAccCognitoIDPUserPoolClient_analyticsWithARN(t *testing.T) { CheckDestroy: testAccCheckUserPoolClientDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientAnalyticsWithARNConfig(rName), + Config: testAccUserPoolClientConfig_analyticsARN(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolClientExists(resourceName, &client), resource.TestCheckResourceAttr(resourceName, "analytics_configuration.#", "1"), @@ -583,12 +582,7 @@ func testAccUserPoolClientImportStateIDFunc(resourceName string) resource.Import userPoolId := rs.Primary.Attributes["user_pool_id"] clientId := rs.Primary.ID - params := &cognitoidentityprovider.DescribeUserPoolClientInput{ - UserPoolId: aws.String(userPoolId), - ClientId: aws.String(clientId), - } - - _, err := conn.DescribeUserPoolClient(params) + _, err := tfcognitoidp.FindCognitoUserPoolClient(conn, userPoolId, clientId) if err != nil { return "", err @@ -606,17 +600,12 @@ func testAccCheckUserPoolClientDestroy(s *terraform.State) error { continue } - params := &cognitoidentityprovider.DescribeUserPoolClientInput{ - ClientId: aws.String(rs.Primary.ID), - UserPoolId: aws.String(rs.Primary.Attributes["user_pool_id"]), + _, err := tfcognitoidp.FindCognitoUserPoolClient(conn, rs.Primary.Attributes["user_pool_id"], rs.Primary.ID) + if tfresource.NotFound(err) { + continue } - _, err := conn.DescribeUserPoolClient(params) - if err != nil { - if tfawserr.ErrCodeEquals(err, cognitoidentityprovider.ErrCodeResourceNotFoundException) { - return nil - } return err } } @@ -637,17 +626,12 @@ func testAccCheckUserPoolClientExists(name string, client *cognitoidentityprovid conn := acctest.Provider.Meta().(*conns.AWSClient).CognitoIDPConn - params := &cognitoidentityprovider.DescribeUserPoolClientInput{ - ClientId: aws.String(rs.Primary.ID), - UserPoolId: aws.String(rs.Primary.Attributes["user_pool_id"]), - } - - resp, err := conn.DescribeUserPoolClient(params) + resp, err := tfcognitoidp.FindCognitoUserPoolClient(conn, rs.Primary.Attributes["user_pool_id"], rs.Primary.ID) if err != nil { return err } - *client = *resp.UserPoolClient + *client = *resp return nil } @@ -671,7 +655,7 @@ resource "aws_cognito_user_pool_client" "test" { `, rName) } -func testAccUserPoolClientRevocationConfig(rName string, revoke bool) string { +func testAccUserPoolClientConfig_revocation(rName string, revoke bool) string { return testAccUserPoolClientBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q @@ -682,7 +666,7 @@ resource "aws_cognito_user_pool_client" "test" { `, rName, revoke) } -func testAccUserPoolClientConfig_RefreshTokenValidity(rName string, refreshTokenValidity int) string { +func testAccUserPoolClientConfig_refreshTokenValidity(rName string, refreshTokenValidity int) string { return testAccUserPoolClientBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q @@ -692,7 +676,7 @@ resource "aws_cognito_user_pool_client" "test" { `, rName, refreshTokenValidity) } -func testAccUserPoolClientAccessTokenValidityConfig(rName string, validity int) string { +func testAccUserPoolClientConfig_accessTokenValidity(rName string, validity int) string { return testAccUserPoolClientBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q @@ -702,7 +686,7 @@ resource "aws_cognito_user_pool_client" "test" { `, rName, validity) } -func testAccUserPoolClientIDTokenValidityConfig(rName string, validity int) string { +func testAccUserPoolClientConfig_idTokenValidity(rName string, validity int) string { return testAccUserPoolClientBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q @@ -712,7 +696,7 @@ resource "aws_cognito_user_pool_client" "test" { `, rName, validity) } -func testAccUserPoolClientTokenValidityUnitsConfig(rName, units string) string { +func testAccUserPoolClientConfig_tokenValidityUnits(rName, units string) string { return testAccUserPoolClientBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q @@ -727,7 +711,7 @@ resource "aws_cognito_user_pool_client" "test" { `, rName, units) } -func testAccUserPoolClientTokenValidityUnitsWithTokenValidityConfig(rName, units string) string { +func testAccUserPoolClientConfig_tokenValidityUnitsTokenValidity(rName, units string) string { return testAccUserPoolClientBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q @@ -743,7 +727,7 @@ resource "aws_cognito_user_pool_client" "test" { `, rName, units) } -func testAccUserPoolClientConfig_Name(rName, name string) string { +func testAccUserPoolClientConfig_name(rName, name string) string { return testAccUserPoolClientBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q @@ -832,7 +816,7 @@ EOF `, rName) } -func testAccUserPoolClientAnalyticsConfig(rName string) string { +func testAccUserPoolClientConfig_analytics(rName string) string { return testAccUserPoolClientAnalyticsBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q @@ -847,7 +831,7 @@ resource "aws_cognito_user_pool_client" "test" { `, rName) } -func testAccUserPoolClientAnalyticsShareUserDataConfig(rName string) string { +func testAccUserPoolClientConfig_analyticsShareData(rName string) string { return testAccUserPoolClientAnalyticsBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q @@ -863,7 +847,7 @@ resource "aws_cognito_user_pool_client" "test" { `, rName) } -func testAccUserPoolClientAnalyticsWithARNConfig(rName string) string { +func testAccUserPoolClientConfig_analyticsARN(rName string) string { return testAccUserPoolClientAnalyticsBaseConfig(rName) + fmt.Sprintf(` resource "aws_cognito_user_pool_client" "test" { name = %[1]q diff --git a/internal/service/cognitoidp/user_pool_clients_data_source_test.go b/internal/service/cognitoidp/user_pool_clients_data_source_test.go index 67253295d73..07103ef4896 100644 --- a/internal/service/cognitoidp/user_pool_clients_data_source_test.go +++ b/internal/service/cognitoidp/user_pool_clients_data_source_test.go @@ -20,7 +20,7 @@ func TestAccCognitoIDPUserPoolClientsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccUserPoolClientsDataSource_basic(rName), + Config: testAccUserPoolClientsDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "client_ids.#", "3"), resource.TestCheckResourceAttr(datasourceName, "client_names.#", "3"), @@ -30,7 +30,7 @@ func TestAccCognitoIDPUserPoolClientsDataSource_basic(t *testing.T) { }) } -func testAccUserPoolClientsDataSource_basic(rName string) string { +func testAccUserPoolClientsDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q diff --git a/internal/service/cognitoidp/user_pool_test.go b/internal/service/cognitoidp/user_pool_test.go index ca7a32b6905..1ac12d90251 100644 --- a/internal/service/cognitoidp/user_pool_test.go +++ b/internal/service/cognitoidp/user_pool_test.go @@ -41,7 +41,7 @@ func TestAccCognitoIDPUserPool_basic(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_Name(rName), + Config: testAccUserPoolConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "cognito-idp", regexp.MustCompile(`userpool/.+`)), @@ -91,7 +91,7 @@ func TestAccCognitoIDPUserPool_recovery(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolAccountRecoverySingleConfig(rName), + Config: testAccUserPoolConfig_accountRecoverySingle(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -105,7 +105,7 @@ func TestAccCognitoIDPUserPool_recovery(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolAccountRecoveryMultiConfig(rName), + Config: testAccUserPoolConfig_accountRecoveryMulti(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -114,7 +114,7 @@ func TestAccCognitoIDPUserPool_recovery(t *testing.T) { ), }, { - Config: testAccUserPoolAccountRecoveryUpdateConfig(rName), + Config: testAccUserPoolConfig_accountRecoveryUpdate(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -137,7 +137,7 @@ func TestAccCognitoIDPUserPool_withAdminCreateUser(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withAdminCreateUserConfiguration(rName), + Config: testAccUserPoolConfig_adminCreateConfiguration(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "admin_create_user_config.0.allow_admin_create_user_only", "true"), @@ -152,7 +152,7 @@ func TestAccCognitoIDPUserPool_withAdminCreateUser(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_withAdminCreateUserConfigurationUpdated(rName), + Config: testAccUserPoolConfig_adminCreateConfigurationUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "admin_create_user_config.0.allow_admin_create_user_only", "false"), resource.TestCheckResourceAttr(resourceName, "admin_create_user_config.0.invite_message_template.0.email_message", "Your username is {username} and constant password is {####}. "), @@ -176,7 +176,7 @@ func TestAccCognitoIDPUserPool_withAdminCreateUserAndPasswordPolicy(t *testing.T CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withAdminCreateUserConfigAndPasswordPolicy(rName), + Config: testAccUserPoolConfig_adminCreateAndPasswordPolicy(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "admin_create_user_config.0.allow_admin_create_user_only", "true"), @@ -203,7 +203,7 @@ func TestAccCognitoIDPUserPool_withAdvancedSecurityMode(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_AdvancedSecurityMode(rName, "OFF"), + Config: testAccUserPoolConfig_advancedSecurityMode(rName, "OFF"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "user_pool_add_ons.0.advanced_security_mode", "OFF"), @@ -215,13 +215,13 @@ func TestAccCognitoIDPUserPool_withAdvancedSecurityMode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_AdvancedSecurityMode(rName, "ENFORCED"), + Config: testAccUserPoolConfig_advancedSecurityMode(rName, "ENFORCED"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "user_pool_add_ons.0.advanced_security_mode", "ENFORCED"), ), }, { - Config: testAccUserPoolConfig_Name(rName), + Config: testAccUserPoolConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "user_pool_add_ons.#", "0"), ), @@ -241,7 +241,7 @@ func TestAccCognitoIDPUserPool_withDevice(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withDeviceConfiguration(rName), + Config: testAccUserPoolConfig_deviceConfiguration(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "device_configuration.0.challenge_required_on_new_device", "true"), @@ -254,7 +254,7 @@ func TestAccCognitoIDPUserPool_withDevice(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_withDeviceConfigurationUpdated(rName), + Config: testAccUserPoolConfig_deviceConfigurationUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "device_configuration.0.challenge_required_on_new_device", "false"), resource.TestCheckResourceAttr(resourceName, "device_configuration.0.device_only_remembered_on_user_prompt", "true"), @@ -279,7 +279,7 @@ func TestAccCognitoIDPUserPool_withEmailVerificationMessage(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withEmailVerificationMessage(rName, subject, message), + Config: testAccUserPoolConfig_emailVerificationMessage(rName, subject, message), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "email_verification_subject", subject), @@ -292,7 +292,7 @@ func TestAccCognitoIDPUserPool_withEmailVerificationMessage(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_withEmailVerificationMessage(rName, updatedSubject, upatedMessage), + Config: testAccUserPoolConfig_emailVerificationMessage(rName, updatedSubject, upatedMessage), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "email_verification_subject", updatedSubject), resource.TestCheckResourceAttr(resourceName, "email_verification_message", upatedMessage), @@ -314,7 +314,7 @@ func TestAccCognitoIDPUserPool_MFA_sms(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_MFAConfiguration_SMSConfiguration(rName), + Config: testAccUserPoolConfig_mfaConfigurationSMSConfiguration(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -329,7 +329,7 @@ func TestAccCognitoIDPUserPool_MFA_sms(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_MFAConfiguration(rName, cognitoidentityprovider.UserPoolMfaTypeOff), + Config: testAccUserPoolConfig_mfaConfiguration(rName, cognitoidentityprovider.UserPoolMfaTypeOff), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -337,7 +337,7 @@ func TestAccCognitoIDPUserPool_MFA_sms(t *testing.T) { ), }, { - Config: testAccUserPoolConfig_MFAConfiguration_SMSConfiguration(rName), + Config: testAccUserPoolConfig_mfaConfigurationSMSConfiguration(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -362,7 +362,7 @@ func TestAccCognitoIDPUserPool_MFA_smsAndSoftwareTokenMFA(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_MFAConfiguration_SMSConfigurationAndSoftwareTokenMfaConfigurationEnabled(rName, false), + Config: testAccUserPoolConfig_mfaConfigurationSMSConfigurationAndSoftwareTokenMFAConfigurationEnabled(rName, false), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -378,7 +378,7 @@ func TestAccCognitoIDPUserPool_MFA_smsAndSoftwareTokenMFA(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_MFAConfiguration_SMSConfigurationAndSoftwareTokenMfaConfigurationEnabled(rName, true), + Config: testAccUserPoolConfig_mfaConfigurationSMSConfigurationAndSoftwareTokenMFAConfigurationEnabled(rName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -389,7 +389,7 @@ func TestAccCognitoIDPUserPool_MFA_smsAndSoftwareTokenMFA(t *testing.T) { ), }, { - Config: testAccUserPoolConfig_MFAConfiguration(rName, cognitoidentityprovider.UserPoolMfaTypeOff), + Config: testAccUserPoolConfig_mfaConfiguration(rName, cognitoidentityprovider.UserPoolMfaTypeOff), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -412,7 +412,7 @@ func TestAccCognitoIDPUserPool_MFA_smsToSoftwareTokenMFA(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_MFAConfiguration_SMSConfiguration(rName), + Config: testAccUserPoolConfig_mfaConfigurationSMSConfiguration(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -427,7 +427,7 @@ func TestAccCognitoIDPUserPool_MFA_smsToSoftwareTokenMFA(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_MFAConfiguration_SoftwareTokenMfaConfigurationEnabled(rName, true), + Config: testAccUserPoolConfig_mfaConfigurationSoftwareTokenMFAConfigurationEnabled(rName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -450,7 +450,7 @@ func TestAccCognitoIDPUserPool_MFA_softwareTokenMFA(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_MFAConfiguration_SoftwareTokenMfaConfigurationEnabled(rName, true), + Config: testAccUserPoolConfig_mfaConfigurationSoftwareTokenMFAConfigurationEnabled(rName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "0"), @@ -464,7 +464,7 @@ func TestAccCognitoIDPUserPool_MFA_softwareTokenMFA(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_MFAConfiguration(rName, cognitoidentityprovider.UserPoolMfaTypeOff), + Config: testAccUserPoolConfig_mfaConfiguration(rName, cognitoidentityprovider.UserPoolMfaTypeOff), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "0"), @@ -472,7 +472,7 @@ func TestAccCognitoIDPUserPool_MFA_softwareTokenMFA(t *testing.T) { ), }, { - Config: testAccUserPoolConfig_MFAConfiguration_SoftwareTokenMfaConfigurationEnabled(rName, true), + Config: testAccUserPoolConfig_mfaConfigurationSoftwareTokenMFAConfigurationEnabled(rName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "0"), @@ -496,7 +496,7 @@ func TestAccCognitoIDPUserPool_MFA_softwareTokenMFAToSMS(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_MFAConfiguration_SoftwareTokenMfaConfigurationEnabled(rName, true), + Config: testAccUserPoolConfig_mfaConfigurationSoftwareTokenMFAConfigurationEnabled(rName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "0"), @@ -510,7 +510,7 @@ func TestAccCognitoIDPUserPool_MFA_softwareTokenMFAToSMS(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_MFAConfiguration_SMSConfiguration(rName), + Config: testAccUserPoolConfig_mfaConfigurationSMSConfiguration(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "ON"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -536,7 +536,7 @@ func TestAccCognitoIDPUserPool_smsAuthenticationMessage(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_SMSAuthenticationMessage(rName, smsAuthenticationMessage1), + Config: testAccUserPoolConfig_smsAuthenticationMessage(rName, smsAuthenticationMessage1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "sms_authentication_message", smsAuthenticationMessage1), @@ -548,7 +548,7 @@ func TestAccCognitoIDPUserPool_smsAuthenticationMessage(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_SMSAuthenticationMessage(rName, smsAuthenticationMessage2), + Config: testAccUserPoolConfig_smsAuthenticationMessage(rName, smsAuthenticationMessage2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "sms_authentication_message", smsAuthenticationMessage2), @@ -570,7 +570,7 @@ func TestAccCognitoIDPUserPool_sms(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_SMSConfiguration_ExternalID(rName, "test"), + Config: testAccUserPoolConfig_smsConfigurationExternalID(rName, "test"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -584,14 +584,14 @@ func TestAccCognitoIDPUserPool_sms(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_Name(rName), + Config: testAccUserPoolConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), ), }, { - Config: testAccUserPoolConfig_SMSConfiguration_ExternalID(rName, "test"), + Config: testAccUserPoolConfig_smsConfigurationExternalID(rName, "test"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -615,7 +615,7 @@ func TestAccCognitoIDPUserPool_SMS_externalID(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_SMSConfiguration_ExternalID(rName, "test"), + Config: testAccUserPoolConfig_smsConfigurationExternalID(rName, "test"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -629,7 +629,7 @@ func TestAccCognitoIDPUserPool_SMS_externalID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_SMSConfiguration_ExternalID(rName, "test2"), + Config: testAccUserPoolConfig_smsConfigurationExternalID(rName, "test2"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -653,7 +653,7 @@ func TestAccCognitoIDPUserPool_SMS_snsCallerARN(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_SMSConfiguration_ExternalID(rName, "test"), + Config: testAccUserPoolConfig_smsConfigurationExternalID(rName, "test"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -667,7 +667,7 @@ func TestAccCognitoIDPUserPool_SMS_snsCallerARN(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_SMSConfiguration_SNSCallerARN2(rName), + Config: testAccUserPoolConfig_smsConfigurationSNSCallerARN2(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "mfa_configuration", "OFF"), resource.TestCheckResourceAttr(resourceName, "sms_configuration.#", "1"), @@ -692,7 +692,7 @@ func TestAccCognitoIDPUserPool_smsVerificationMessage(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_SMSVerificationMessage(rName, smsVerificationMessage1), + Config: testAccUserPoolConfig_smsVerificationMessage(rName, smsVerificationMessage1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "sms_verification_message", smsVerificationMessage1), @@ -704,7 +704,7 @@ func TestAccCognitoIDPUserPool_smsVerificationMessage(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_SMSVerificationMessage(rName, smsVerificationMessage2), + Config: testAccUserPoolConfig_smsVerificationMessage(rName, smsVerificationMessage2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "sms_verification_message", smsVerificationMessage2), @@ -725,7 +725,7 @@ func TestAccCognitoIDPUserPool_withEmail(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withEmailConfiguration(rName), + Config: testAccUserPoolConfig_emailConfiguration(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "email_configuration.#", "1"), resource.TestCheckResourceAttr(resourceName, "email_configuration.0.reply_to_email_address", ""), @@ -761,7 +761,7 @@ func TestAccCognitoIDPUserPool_withEmailSource(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withEmailConfigurationSource(rName, replyTo, sourceARN, emailTo, "DEVELOPER"), + Config: testAccUserPoolConfig_emailConfigurationSource(rName, replyTo, sourceARN, emailTo, "DEVELOPER"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "email_configuration.#", "1"), resource.TestCheckResourceAttr(resourceName, "email_configuration.0.reply_to_email_address", replyTo), @@ -786,7 +786,7 @@ func TestAccCognitoIDPUserPool_withTags(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_Tags1(rName, "key1", "value1"), + Config: testAccUserPoolConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -799,7 +799,7 @@ func TestAccCognitoIDPUserPool_withTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_Tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccUserPoolConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), @@ -807,7 +807,7 @@ func TestAccCognitoIDPUserPool_withTags(t *testing.T) { ), }, { - Config: testAccUserPoolConfig_Tags1(rName, "key2", "value2"), + Config: testAccUserPoolConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -829,7 +829,7 @@ func TestAccCognitoIDPUserPool_withAliasAttributes(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withAliasAttributes(rName), + Config: testAccUserPoolConfig_aliasAttributes(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "alias_attributes.#", "1"), @@ -843,7 +843,7 @@ func TestAccCognitoIDPUserPool_withAliasAttributes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_withAliasAttributesUpdated(rName), + Config: testAccUserPoolConfig_aliasAttributesUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "alias_attributes.#", "2"), resource.TestCheckTypeSetElemAttr(resourceName, "alias_attributes.*", "email"), @@ -867,7 +867,7 @@ func TestAccCognitoIDPUserPool_withUsernameAttributes(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withUsernameAttributes(rName), + Config: testAccUserPoolConfig_nameAttributes(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "username_attributes.#", "1"), @@ -881,7 +881,7 @@ func TestAccCognitoIDPUserPool_withUsernameAttributes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_withUsernameAttributesUpdated(rName), + Config: testAccUserPoolConfig_nameAttributesUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "username_attributes.#", "2"), resource.TestCheckTypeSetElemAttr(resourceName, "username_attributes.*", "email"), @@ -905,7 +905,7 @@ func TestAccCognitoIDPUserPool_withPasswordPolicy(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withPasswordPolicy(rName), + Config: testAccUserPoolConfig_passwordPolicy(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "password_policy.#", "1"), @@ -923,7 +923,7 @@ func TestAccCognitoIDPUserPool_withPasswordPolicy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_withPasswordPolicyUpdated(rName), + Config: testAccUserPoolConfig_passwordPolicyUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "password_policy.#", "1"), resource.TestCheckResourceAttr(resourceName, "password_policy.0.minimum_length", "9"), @@ -949,7 +949,7 @@ func TestAccCognitoIDPUserPool_withUsername(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withUsernameConfiguration(rName), + Config: testAccUserPoolConfig_nameConfiguration(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "username_configuration.#", "1"), @@ -962,7 +962,7 @@ func TestAccCognitoIDPUserPool_withUsername(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_withUsernameConfigurationUpdated(rName), + Config: testAccUserPoolConfig_nameConfigurationUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "username_configuration.#", "1"), @@ -986,7 +986,7 @@ func TestAccCognitoIDPUserPool_withLambda(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withLambdaConfig(rName), + Config: testAccUserPoolConfig_lambda(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "lambda_config.#", "1"), @@ -1008,7 +1008,7 @@ func TestAccCognitoIDPUserPool_withLambda(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_withLambdaConfigUpdated(rName), + Config: testAccUserPoolConfig_lambdaUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "lambda_config.#", "1"), resource.TestCheckResourceAttrPair(resourceName, "lambda_config.0.create_auth_challenge", lambdaUpdatedResourceName, "arn"), @@ -1024,7 +1024,7 @@ func TestAccCognitoIDPUserPool_withLambda(t *testing.T) { ), }, { - Config: testAccUserPoolConfig_Name(rName), + Config: testAccUserPoolConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "lambda_config.#", "0"), @@ -1056,7 +1056,7 @@ func TestAccCognitoIDPUserPool_WithLambda_email(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolLambdaEmailSenderConfig(rName), + Config: testAccUserPoolConfig_lambdaEmailSender(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "lambda_config.#", "1"), @@ -1071,7 +1071,7 @@ func TestAccCognitoIDPUserPool_WithLambda_email(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolLambdaEmailSenderUpdatedConfig(rName), + Config: testAccUserPoolConfig_lambdaEmailSenderUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "lambda_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "lambda_config.0.custom_email_sender.#", "1"), @@ -1096,7 +1096,7 @@ func TestAccCognitoIDPUserPool_WithLambda_sms(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolLambdaSMSSenderConfig(rName), + Config: testAccUserPoolConfig_lambdaSMSSender(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "lambda_config.#", "1"), @@ -1111,7 +1111,7 @@ func TestAccCognitoIDPUserPool_WithLambda_sms(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolLambdaSMSSenderUpdatedConfig(rName), + Config: testAccUserPoolConfig_lambdaSMSSenderUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "lambda_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "lambda_config.0.custom_sms_sender.#", "1"), @@ -1135,7 +1135,7 @@ func TestAccCognitoIDPUserPool_schemaAttributes(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withSchemaAttributes(rName), + Config: testAccUserPoolConfig_schemaAttributes(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, &pool1), resource.TestCheckResourceAttr(resourceName, "schema.#", "2"), @@ -1162,7 +1162,7 @@ func TestAccCognitoIDPUserPool_schemaAttributes(t *testing.T) { ), }, { - Config: testAccUserPoolConfig_withSchemaAttributesUpdated(rName, "mybool"), + Config: testAccUserPoolConfig_schemaAttributesUpdated(rName, "mybool"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, &pool2), testAccCheckUserPoolNotRecreated(&pool1, &pool2), @@ -1219,10 +1219,10 @@ func TestAccCognitoIDPUserPool_schemaAttributesRemoved(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withSchemaAttributesUpdated(rName, "mybool"), + Config: testAccUserPoolConfig_schemaAttributesUpdated(rName, "mybool"), }, { - Config: testAccUserPoolConfig_withSchemaAttributes(rName), + Config: testAccUserPoolConfig_schemaAttributes(rName), ExpectError: regexp.MustCompile("cannot modify or remove schema items"), }, }, @@ -1239,10 +1239,10 @@ func TestAccCognitoIDPUserPool_schemaAttributesModified(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withSchemaAttributesUpdated(rName, "mybool"), + Config: testAccUserPoolConfig_schemaAttributesUpdated(rName, "mybool"), }, { - Config: testAccUserPoolConfig_withSchemaAttributesUpdated(rName, "mybool2"), + Config: testAccUserPoolConfig_schemaAttributesUpdated(rName, "mybool2"), ExpectError: regexp.MustCompile("cannot modify or remove schema items"), }, }, @@ -1260,7 +1260,7 @@ func TestAccCognitoIDPUserPool_withVerificationMessageTemplate(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_withVerificationMessageTemplate(rName), + Config: testAccUserPoolConfig_verificationMessageTemplate(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), resource.TestCheckResourceAttr(resourceName, "verification_message_template.0.default_email_option", "CONFIRM_WITH_LINK"), @@ -1284,7 +1284,7 @@ func TestAccCognitoIDPUserPool_withVerificationMessageTemplate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolConfig_withVerificationMessageTemplate_DefaultEmailOption(rName), + Config: testAccUserPoolConfig_verificationMessageTemplateDefaultEmailOption(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "verification_message_template.0.default_email_option", "CONFIRM_WITH_CODE"), resource.TestCheckResourceAttr(resourceName, "email_verification_message", "{####} Baz"), @@ -1403,7 +1403,7 @@ func TestAccCognitoIDPUserPool_disappears(t *testing.T) { CheckDestroy: testAccCheckUserPoolDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolConfig_Name(rName), + Config: testAccUserPoolConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolExists(resourceName, nil), acctest.CheckResourceDisappears(acctest.Provider, tfcognitoidp.ResourceUserPool(), resourceName), @@ -1527,7 +1527,7 @@ resource "aws_iam_role_policy" "test" { `, rName, externalID) } -func testAccUserPoolConfig_Name(rName string) string { +func testAccUserPoolConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1535,7 +1535,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolAccountRecoverySingleConfig(rName string) string { +func testAccUserPoolConfig_accountRecoverySingle(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1550,7 +1550,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolAccountRecoveryMultiConfig(rName string) string { +func testAccUserPoolConfig_accountRecoveryMulti(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1570,7 +1570,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolAccountRecoveryUpdateConfig(rName string) string { +func testAccUserPoolConfig_accountRecoveryUpdate(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1585,7 +1585,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withAdminCreateUserConfiguration(rName string) string { +func testAccUserPoolConfig_adminCreateConfiguration(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1603,7 +1603,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withAdminCreateUserConfigurationUpdated(rName string) string { +func testAccUserPoolConfig_adminCreateConfigurationUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1621,7 +1621,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_AdvancedSecurityMode(rName string, advancedSecurityMode string) string { +func testAccUserPoolConfig_advancedSecurityMode(rName string, advancedSecurityMode string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1633,7 +1633,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, advancedSecurityMode) } -func testAccUserPoolConfig_withDeviceConfiguration(rName string) string { +func testAccUserPoolConfig_deviceConfiguration(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1646,7 +1646,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withDeviceConfigurationUpdated(rName string) string { +func testAccUserPoolConfig_deviceConfigurationUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1659,7 +1659,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withEmailVerificationMessage(rName, subject, message string) string { +func testAccUserPoolConfig_emailVerificationMessage(rName, subject, message string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1673,7 +1673,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, subject, message) } -func testAccUserPoolConfig_MFAConfiguration(rName string, mfaConfiguration string) string { +func testAccUserPoolConfig_mfaConfiguration(rName string, mfaConfiguration string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { mfa_configuration = %[2]q @@ -1682,7 +1682,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, mfaConfiguration) } -func testAccUserPoolConfig_MFAConfiguration_SMSConfiguration(rName string) string { +func testAccUserPoolConfig_mfaConfigurationSMSConfiguration(rName string) string { return testAccUserPoolSMSConfigurationBaseConfig(rName, "test") + fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { mfa_configuration = "ON" @@ -1696,7 +1696,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_MFAConfiguration_SMSConfigurationAndSoftwareTokenMfaConfigurationEnabled(rName string, enabled bool) string { +func testAccUserPoolConfig_mfaConfigurationSMSConfigurationAndSoftwareTokenMFAConfigurationEnabled(rName string, enabled bool) string { return testAccUserPoolSMSConfigurationBaseConfig(rName, "test") + fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { mfa_configuration = "ON" @@ -1714,7 +1714,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, enabled) } -func testAccUserPoolConfig_MFAConfiguration_SoftwareTokenMfaConfigurationEnabled(rName string, enabled bool) string { +func testAccUserPoolConfig_mfaConfigurationSoftwareTokenMFAConfigurationEnabled(rName string, enabled bool) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { mfa_configuration = "ON" @@ -1727,7 +1727,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, enabled) } -func testAccUserPoolConfig_SMSAuthenticationMessage(rName, smsAuthenticationMessage string) string { +func testAccUserPoolConfig_smsAuthenticationMessage(rName, smsAuthenticationMessage string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1736,7 +1736,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, smsAuthenticationMessage) } -func testAccUserPoolConfig_SMSConfiguration_ExternalID(rName string, externalID string) string { +func testAccUserPoolConfig_smsConfigurationExternalID(rName string, externalID string) string { return testAccUserPoolSMSConfigurationBaseConfig(rName, externalID) + fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1749,7 +1749,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, externalID) } -func testAccUserPoolConfig_SMSConfiguration_SNSCallerARN2(rName string) string { +func testAccUserPoolConfig_smsConfigurationSNSCallerARN2(rName string) string { return testAccUserPoolSMSConfigurationBaseConfig(rName+"-2", "test") + fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1762,7 +1762,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_SMSVerificationMessage(rName, smsVerificationMessage string) string { +func testAccUserPoolConfig_smsVerificationMessage(rName, smsVerificationMessage string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1771,7 +1771,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, smsVerificationMessage) } -func testAccUserPoolConfig_Tags1(rName, tagKey1, tagValue1 string) string { +func testAccUserPoolConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1783,7 +1783,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, tagKey1, tagValue1) } -func testAccUserPoolConfig_Tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccUserPoolConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1796,7 +1796,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccUserPoolConfig_withEmailConfiguration(rName string) string { +func testAccUserPoolConfig_emailConfiguration(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1808,7 +1808,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withEmailConfigurationSource(rName, email, arn, from, account string) string { +func testAccUserPoolConfig_emailConfigurationSource(rName, email, arn, from, account string) string { return fmt.Sprintf(` resource "aws_ses_configuration_set" "test" { name = %[1]q @@ -1832,7 +1832,7 @@ resource "aws_cognito_user_pool" "test" { `, rName, email, arn, from, account) } -func testAccUserPoolConfig_withAliasAttributes(rName string) string { +func testAccUserPoolConfig_aliasAttributes(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1842,7 +1842,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withAliasAttributesUpdated(rName string) string { +func testAccUserPoolConfig_aliasAttributesUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1853,7 +1853,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withUsernameAttributes(rName string) string { +func testAccUserPoolConfig_nameAttributes(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1863,7 +1863,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withUsernameAttributesUpdated(rName string) string { +func testAccUserPoolConfig_nameAttributesUpdated(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1874,7 +1874,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withAdminCreateUserConfigAndPasswordPolicy(rName string) string { +func testAccUserPoolConfig_adminCreateAndPasswordPolicy(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1895,7 +1895,7 @@ resource "aws_cognito_user_pool" "test" { `, rName) } -func testAccUserPoolConfig_withPasswordPolicy(name string) string { +func testAccUserPoolConfig_passwordPolicy(name string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1912,7 +1912,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolConfig_withPasswordPolicyUpdated(name string) string { +func testAccUserPoolConfig_passwordPolicyUpdated(name string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1929,7 +1929,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolConfig_withUsernameConfiguration(name string) string { +func testAccUserPoolConfig_nameConfiguration(name string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -1941,7 +1941,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolConfig_withUsernameConfigurationUpdated(name string) string { +func testAccUserPoolConfig_nameConfigurationUpdated(name string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -2008,7 +2008,7 @@ POLICY `, name) } -func testAccUserPoolConfig_withLambdaConfig(name string) string { +func testAccUserPoolConfig_lambda(name string) string { return testAccUserPoolLambdaBaseConfig(name) + fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -2029,7 +2029,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolConfig_withLambdaConfigUpdated(name string) string { +func testAccUserPoolConfig_lambdaUpdated(name string) string { return testAccUserPoolLambdaBaseConfig(name) + fmt.Sprintf(` resource "aws_lambda_function" "second" { filename = "test-fixtures/lambdatest.zip" @@ -2058,7 +2058,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolLambdaEmailSenderConfig(name string) string { +func testAccUserPoolConfig_lambdaEmailSender(name string) string { return testAccUserPoolLambdaBaseConfig(name) + fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -2075,7 +2075,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolLambdaEmailSenderUpdatedConfig(name string) string { +func testAccUserPoolConfig_lambdaEmailSenderUpdated(name string) string { return testAccUserPoolLambdaBaseConfig(name) + fmt.Sprintf(` resource "aws_lambda_function" "second" { filename = "test-fixtures/lambdatest.zip" @@ -2100,7 +2100,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolLambdaSMSSenderConfig(name string) string { +func testAccUserPoolConfig_lambdaSMSSender(name string) string { return testAccUserPoolLambdaBaseConfig(name) + fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -2117,7 +2117,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolLambdaSMSSenderUpdatedConfig(name string) string { +func testAccUserPoolConfig_lambdaSMSSenderUpdated(name string) string { return testAccUserPoolLambdaBaseConfig(name) + fmt.Sprintf(` resource "aws_lambda_function" "second" { filename = "test-fixtures/lambdatest.zip" @@ -2142,7 +2142,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolConfig_withSchemaAttributes(name string) string { +func testAccUserPoolConfig_schemaAttributes(name string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = "%[1]s" @@ -2171,7 +2171,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolConfig_withSchemaAttributesUpdated(name string, boolname string) string { +func testAccUserPoolConfig_schemaAttributesUpdated(name string, boolname string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = "%[1]s" @@ -2213,7 +2213,7 @@ resource "aws_cognito_user_pool" "test" { `, name, boolname) } -func testAccUserPoolConfig_withVerificationMessageTemplate(name string) string { +func testAccUserPoolConfig_verificationMessageTemplate(name string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -2234,7 +2234,7 @@ resource "aws_cognito_user_pool" "test" { `, name) } -func testAccUserPoolConfig_withVerificationMessageTemplate_DefaultEmailOption(name string) string { +func testAccUserPoolConfig_verificationMessageTemplateDefaultEmailOption(name string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q diff --git a/internal/service/cognitoidp/user_pool_ui_customization_test.go b/internal/service/cognitoidp/user_pool_ui_customization_test.go index 98db72d6b01..fe5299a12f0 100644 --- a/internal/service/cognitoidp/user_pool_ui_customization_test.go +++ b/internal/service/cognitoidp/user_pool_ui_customization_test.go @@ -30,7 +30,7 @@ func TestAccCognitoIDPUserPoolUICustomization_AllClients_CSS(t *testing.T) { CheckDestroy: testAccCheckUserPoolUICustomizationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolUICustomizationConfig_AllClients_CSS(rName, css), + Config: testAccUserPoolUICustomizationConfig_allClientsCSS(rName, css), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "css", css), @@ -47,7 +47,7 @@ func TestAccCognitoIDPUserPoolUICustomization_AllClients_CSS(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolUICustomizationConfig_AllClients_CSS(rName, cssUpdated), + Config: testAccUserPoolUICustomizationConfig_allClientsCSS(rName, cssUpdated), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "css", cssUpdated), @@ -80,7 +80,7 @@ func TestAccCognitoIDPUserPoolUICustomization_AllClients_disappears(t *testing.T CheckDestroy: testAccCheckUserPoolUICustomizationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolUICustomizationConfig_AllClients_CSS(rName, css), + Config: testAccUserPoolUICustomizationConfig_allClientsCSS(rName, css), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcognitoidp.ResourceUserPoolUICustomization(), resourceName), @@ -106,7 +106,7 @@ func TestAccCognitoIDPUserPoolUICustomization_AllClients_imageFile(t *testing.T) CheckDestroy: testAccCheckUserPoolUICustomizationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolUICustomizationConfig_AllClients_Image(rName, filename), + Config: testAccUserPoolUICustomizationConfig_allClientsImage(rName, filename), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "creation_date"), @@ -123,7 +123,7 @@ func TestAccCognitoIDPUserPoolUICustomization_AllClients_imageFile(t *testing.T) ImportStateVerifyIgnore: []string{"image_file"}, }, { - Config: testAccUserPoolUICustomizationConfig_AllClients_Image(rName, updatedFilename), + Config: testAccUserPoolUICustomizationConfig_allClientsImage(rName, updatedFilename), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "creation_date"), @@ -159,7 +159,7 @@ func TestAccCognitoIDPUserPoolUICustomization_AllClients_CSSAndImageFile(t *test CheckDestroy: testAccCheckUserPoolUICustomizationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolUICustomizationConfig_AllClients_CSSAndImage(rName, css, filename), + Config: testAccUserPoolUICustomizationConfig_allClientsCSSAndImage(rName, css, filename), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "creation_date"), @@ -178,7 +178,7 @@ func TestAccCognitoIDPUserPoolUICustomization_AllClients_CSSAndImageFile(t *test ImportStateVerifyIgnore: []string{"image_file"}, }, { - Config: testAccUserPoolUICustomizationConfig_AllClients_CSS(rName, css), + Config: testAccUserPoolUICustomizationConfig_allClientsCSS(rName, css), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "css", css), @@ -190,7 +190,7 @@ func TestAccCognitoIDPUserPoolUICustomization_AllClients_CSSAndImageFile(t *test ), }, { - Config: testAccUserPoolUICustomizationConfig_AllClients_Image(rName, updatedFilename), + Config: testAccUserPoolUICustomizationConfig_allClientsImage(rName, updatedFilename), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "creation_date"), @@ -226,7 +226,7 @@ func TestAccCognitoIDPUserPoolUICustomization_Client_CSS(t *testing.T) { CheckDestroy: testAccCheckUserPoolUICustomizationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolUICustomizationConfig_Client_CSS(rName, css), + Config: testAccUserPoolUICustomizationConfig_clientCSS(rName, css), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "css", css), @@ -243,7 +243,7 @@ func TestAccCognitoIDPUserPoolUICustomization_Client_CSS(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserPoolUICustomizationConfig_Client_CSS(rName, cssUpdated), + Config: testAccUserPoolUICustomizationConfig_clientCSS(rName, cssUpdated), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "css", cssUpdated), @@ -276,7 +276,7 @@ func TestAccCognitoIDPUserPoolUICustomization_Client_disappears(t *testing.T) { CheckDestroy: testAccCheckUserPoolUICustomizationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolUICustomizationConfig_Client_CSS(rName, css), + Config: testAccUserPoolUICustomizationConfig_clientCSS(rName, css), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfcognitoidp.ResourceUserPoolUICustomization(), resourceName), @@ -303,7 +303,7 @@ func TestAccCognitoIDPUserPoolUICustomization_Client_image(t *testing.T) { CheckDestroy: testAccCheckUserPoolUICustomizationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolUICustomizationConfig_Client_Image(rName, filename), + Config: testAccUserPoolUICustomizationConfig_clientImage(rName, filename), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "creation_date"), @@ -320,7 +320,7 @@ func TestAccCognitoIDPUserPoolUICustomization_Client_image(t *testing.T) { ImportStateVerifyIgnore: []string{"image_file"}, }, { - Config: testAccUserPoolUICustomizationConfig_Client_Image(rName, updatedFilename), + Config: testAccUserPoolUICustomizationConfig_clientImage(rName, updatedFilename), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "creation_date"), @@ -359,7 +359,7 @@ func TestAccCognitoIDPUserPoolUICustomization_ClientAndAll_cSS(t *testing.T) { Steps: []resource.TestStep{ { // Test UI Customization settings shared by ALL and a specific client - Config: testAccUserPoolUICustomizationConfig_ClientAndAllCustomizations_CSS(rName, allCSS, allCSS), + Config: testAccUserPoolUICustomizationConfig_clientAndAllCSS(rName, allCSS, allCSS), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), testAccCheckUserPoolUICustomizationExists(clientUIResourceName), @@ -386,7 +386,7 @@ func TestAccCognitoIDPUserPoolUICustomization_ClientAndAll_cSS(t *testing.T) { }, { // Test UI Customization settings overridden for the client - Config: testAccUserPoolUICustomizationConfig_ClientAndAllCustomizations_CSS(rName, allCSS, clientCSS), + Config: testAccUserPoolUICustomizationConfig_clientAndAllCSS(rName, allCSS, clientCSS), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), testAccCheckUserPoolUICustomizationExists(clientUIResourceName), @@ -430,7 +430,7 @@ func TestAccCognitoIDPUserPoolUICustomization_UpdateClientToAll_cSS(t *testing.T CheckDestroy: testAccCheckUserPoolUICustomizationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolUICustomizationConfig_Client_CSS(rName, css), + Config: testAccUserPoolUICustomizationConfig_clientCSS(rName, css), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "css", css), @@ -438,7 +438,7 @@ func TestAccCognitoIDPUserPoolUICustomization_UpdateClientToAll_cSS(t *testing.T ), }, { - Config: testAccUserPoolUICustomizationConfig_AllClients_CSS(rName, cssUpdated), + Config: testAccUserPoolUICustomizationConfig_allClientsCSS(rName, cssUpdated), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "css", cssUpdated), @@ -469,7 +469,7 @@ func TestAccCognitoIDPUserPoolUICustomization_UpdateAllToClient_cSS(t *testing.T CheckDestroy: testAccCheckUserPoolUICustomizationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserPoolUICustomizationConfig_AllClients_CSS(rName, css), + Config: testAccUserPoolUICustomizationConfig_allClientsCSS(rName, css), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "css", css), @@ -477,7 +477,7 @@ func TestAccCognitoIDPUserPoolUICustomization_UpdateAllToClient_cSS(t *testing.T ), }, { - Config: testAccUserPoolUICustomizationConfig_Client_CSS(rName, cssUpdated), + Config: testAccUserPoolUICustomizationConfig_clientCSS(rName, cssUpdated), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserPoolUICustomizationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "css", cssUpdated), @@ -564,7 +564,7 @@ func testAccCheckUserPoolUICustomizationExists(name string) resource.TestCheckFu } } -func testAccUserPoolUICustomizationConfig_AllClients_CSS(rName, css string) string { +func testAccUserPoolUICustomizationConfig_allClientsCSS(rName, css string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -585,7 +585,7 @@ resource "aws_cognito_user_pool_ui_customization" "test" { `, rName, css) } -func testAccUserPoolUICustomizationConfig_AllClients_Image(rName, filename string) string { +func testAccUserPoolUICustomizationConfig_allClientsImage(rName, filename string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -606,7 +606,7 @@ resource "aws_cognito_user_pool_ui_customization" "test" { `, rName, filename) } -func testAccUserPoolUICustomizationConfig_AllClients_CSSAndImage(rName, css, filename string) string { +func testAccUserPoolUICustomizationConfig_allClientsCSSAndImage(rName, css, filename string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -628,7 +628,7 @@ resource "aws_cognito_user_pool_ui_customization" "test" { `, rName, css, filename) } -func testAccUserPoolUICustomizationConfig_Client_CSS(rName, css string) string { +func testAccUserPoolUICustomizationConfig_clientCSS(rName, css string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -655,7 +655,7 @@ resource "aws_cognito_user_pool_ui_customization" "test" { `, rName, css) } -func testAccUserPoolUICustomizationConfig_Client_Image(rName, filename string) string { +func testAccUserPoolUICustomizationConfig_clientImage(rName, filename string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -682,7 +682,7 @@ resource "aws_cognito_user_pool_ui_customization" "test" { `, rName, filename) } -func testAccUserPoolUICustomizationConfig_ClientAndAllCustomizations_CSS(rName, allCSS, clientCSS string) string { +func testAccUserPoolUICustomizationConfig_clientAndAllCSS(rName, allCSS, clientCSS string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q diff --git a/internal/service/cognitoidp/user_pools_data_source_test.go b/internal/service/cognitoidp/user_pools_data_source_test.go index e76505240d8..bc6745c6d4b 100644 --- a/internal/service/cognitoidp/user_pools_data_source_test.go +++ b/internal/service/cognitoidp/user_pools_data_source_test.go @@ -19,7 +19,7 @@ func TestAccCognitoIDPUserPoolsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccUserPoolsDataSourceConfig(rName), + Config: testAccUserPoolsDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_cognito_user_pools.test", "arns.#", "2"), resource.TestCheckResourceAttr("data.aws_cognito_user_pools.test", "ids.#", "2"), @@ -31,7 +31,7 @@ func TestAccCognitoIDPUserPoolsDataSource_basic(t *testing.T) { }) } -func testAccUserPoolsDataSourceConfig(rName string) string { +func testAccUserPoolsDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { count = 2 diff --git a/internal/service/cognitoidp/user_test.go b/internal/service/cognitoidp/user_test.go index 559cf558279..04967020bc9 100644 --- a/internal/service/cognitoidp/user_test.go +++ b/internal/service/cognitoidp/user_test.go @@ -28,7 +28,7 @@ func TestAccCognitoIDPUser_basic(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfigBasic(rUserPoolName, rUserName), + Config: testAccUserConfig_basic(rUserPoolName, rUserName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "creation_date"), @@ -69,7 +69,7 @@ func TestAccCognitoIDPUser_disappears(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfigBasic(rUserPoolName, rUserName), + Config: testAccUserConfig_basic(rUserPoolName, rUserName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, cognitoidp.ResourceUser(), resourceName), @@ -96,7 +96,7 @@ func TestAccCognitoIDPUser_temporaryPassword(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfigTemporaryPassword(rUserPoolName, rClientName, rUserName, rUserPassword), + Config: testAccUserConfig_temporaryPassword(rUserPoolName, rClientName, rUserName, rUserPassword), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(userResourceName), testAccUserTemporaryPassword(userResourceName, clientResourceName), @@ -117,7 +117,7 @@ func TestAccCognitoIDPUser_temporaryPassword(t *testing.T) { }, }, { - Config: testAccUserConfigTemporaryPassword(rUserPoolName, rClientName, rUserName, rUserPasswordUpdated), + Config: testAccUserConfig_temporaryPassword(rUserPoolName, rClientName, rUserName, rUserPasswordUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(userResourceName), testAccUserTemporaryPassword(userResourceName, clientResourceName), @@ -125,7 +125,7 @@ func TestAccCognitoIDPUser_temporaryPassword(t *testing.T) { ), }, { - Config: testAccUserConfigNoPassword(rUserPoolName, rClientName, rUserName), + Config: testAccUserConfig_noPassword(rUserPoolName, rClientName, rUserName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(userResourceName), resource.TestCheckResourceAttr(userResourceName, "temporary_password", ""), @@ -152,7 +152,7 @@ func TestAccCognitoIDPUser_password(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfigPassword(rUserPoolName, rClientName, rUserName, rUserPassword), + Config: testAccUserConfig_password(rUserPoolName, rClientName, rUserName, rUserPassword), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(userResourceName), testAccUserPassword(userResourceName, clientResourceName), @@ -173,7 +173,7 @@ func TestAccCognitoIDPUser_password(t *testing.T) { }, }, { - Config: testAccUserConfigPassword(rUserPoolName, rClientName, rUserName, rUserPasswordUpdated), + Config: testAccUserConfig_password(rUserPoolName, rClientName, rUserName, rUserPasswordUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(userResourceName), testAccUserPassword(userResourceName, clientResourceName), @@ -181,7 +181,7 @@ func TestAccCognitoIDPUser_password(t *testing.T) { ), }, { - Config: testAccUserConfigNoPassword(rUserPoolName, rClientName, rUserName), + Config: testAccUserConfig_noPassword(rUserPoolName, rClientName, rUserName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(userResourceName), resource.TestCheckResourceAttr(userResourceName, "password", ""), @@ -204,7 +204,7 @@ func TestAccCognitoIDPUser_attributes(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfigAttributes(rUserPoolName, rUserName), + Config: testAccUserConfig_attributes(rUserPoolName, rUserName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "attributes.%", "4"), @@ -227,7 +227,7 @@ func TestAccCognitoIDPUser_attributes(t *testing.T) { }, }, { - Config: testAccUserConfigAttributesUpdated(rUserPoolName, rUserName), + Config: testAccUserConfig_attributesUpdated(rUserPoolName, rUserName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "attributes.%", "4"), @@ -252,7 +252,7 @@ func TestAccCognitoIDPUser_enabled(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfigEnable(rUserPoolName, rUserName, false), + Config: testAccUserConfig_enable(rUserPoolName, rUserName, false), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -272,7 +272,7 @@ func TestAccCognitoIDPUser_enabled(t *testing.T) { }, }, { - Config: testAccUserConfigEnable(rUserPoolName, rUserName, true), + Config: testAccUserConfig_enable(rUserPoolName, rUserName, true), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), @@ -423,7 +423,7 @@ func testAccUserPassword(userResName string, clientResName string) resource.Test } } -func testAccUserConfigBasic(userPoolName string, userName string) string { +func testAccUserConfig_basic(userPoolName string, userName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -436,7 +436,7 @@ resource "aws_cognito_user" "test" { `, userPoolName, userName) } -func testAccUserConfigTemporaryPassword(userPoolName string, clientName string, userName string, password string) string { +func testAccUserConfig_temporaryPassword(userPoolName string, clientName string, userName string, password string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -463,7 +463,7 @@ resource "aws_cognito_user" "test" { `, userPoolName, clientName, userName, password) } -func testAccUserConfigPassword(userPoolName string, clientName string, userName string, password string) string { +func testAccUserConfig_password(userPoolName string, clientName string, userName string, password string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -490,7 +490,7 @@ resource "aws_cognito_user" "test" { `, userPoolName, clientName, userName, password) } -func testAccUserConfigNoPassword(userPoolName string, clientName string, userName string) string { +func testAccUserConfig_noPassword(userPoolName string, clientName string, userName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -516,7 +516,7 @@ resource "aws_cognito_user" "test" { `, userPoolName, clientName, userName) } -func testAccUserConfigAttributes(userPoolName string, userName string) string { +func testAccUserConfig_attributes(userPoolName string, userName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -568,7 +568,7 @@ resource "aws_cognito_user" "test" { `, userPoolName, userName) } -func testAccUserConfigAttributesUpdated(userPoolName string, userName string) string { +func testAccUserConfig_attributesUpdated(userPoolName string, userName string) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q @@ -620,7 +620,7 @@ resource "aws_cognito_user" "test" { `, userPoolName, userName) } -func testAccUserConfigEnable(userPoolName string, userName string, enabled bool) string { +func testAccUserConfig_enable(userPoolName string, userName string, enabled bool) string { return fmt.Sprintf(` resource "aws_cognito_user_pool" "test" { name = %[1]q diff --git a/internal/service/configservice/config_rule_test.go b/internal/service/configservice/config_rule_test.go index 8ae81757488..cd0b183d171 100644 --- a/internal/service/configservice/config_rule_test.go +++ b/internal/service/configservice/config_rule_test.go @@ -41,7 +41,7 @@ func testAccConfigRule_basic(t *testing.T) { }) } -func testAccConfigRule_ownerAws(t *testing.T) { +func testAccConfigRule_ownerAws(t *testing.T) { // nosemgrep:aws-in-func-name var cr configservice.ConfigRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_config_config_rule.test" @@ -177,7 +177,7 @@ func testAccConfigRule_Scope_TagKey(t *testing.T) { CheckDestroy: testAccCheckConfigRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigRuleConfig_Scope_TagKey(rName, "key1"), + Config: testAccConfigRuleConfig_scopeTagKey(rName, "key1"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigRuleExists(resourceName, &configRule), resource.TestCheckResourceAttr(resourceName, "scope.#", "1"), @@ -185,7 +185,7 @@ func testAccConfigRule_Scope_TagKey(t *testing.T) { ), }, { - Config: testAccConfigRuleConfig_Scope_TagKey(rName, "key2"), + Config: testAccConfigRuleConfig_scopeTagKey(rName, "key2"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigRuleExists(resourceName, &configRule), resource.TestCheckResourceAttr(resourceName, "scope.#", "1"), @@ -208,7 +208,7 @@ func testAccConfigRule_Scope_TagKey_Empty(t *testing.T) { CheckDestroy: testAccCheckConfigRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigRuleConfig_Scope_TagKey(rName, ""), + Config: testAccConfigRuleConfig_scopeTagKey(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckConfigRuleExists(resourceName, &configRule), ), @@ -229,7 +229,7 @@ func testAccConfigRule_Scope_TagValue(t *testing.T) { CheckDestroy: testAccCheckConfigRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigRuleConfig_Scope_TagValue(rName, "value1"), + Config: testAccConfigRuleConfig_scopeTagValue(rName, "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigRuleExists(resourceName, &configRule), resource.TestCheckResourceAttr(resourceName, "scope.#", "1"), @@ -237,7 +237,7 @@ func testAccConfigRule_Scope_TagValue(t *testing.T) { ), }, { - Config: testAccConfigRuleConfig_Scope_TagValue(rName, "value2"), + Config: testAccConfigRuleConfig_scopeTagValue(rName, "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigRuleExists(resourceName, &configRule), resource.TestCheckResourceAttr(resourceName, "scope.#", "1"), @@ -260,7 +260,7 @@ func testAccConfigRule_tags(t *testing.T) { CheckDestroy: testAccCheckConfigRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigRuleConfig_Tags(rName, "foo", "bar", "fizz", "buzz"), + Config: testAccConfigRuleConfig_tags(rName, "foo", "bar", "fizz", "buzz"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigRuleExists(resourceName, &cr), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -270,7 +270,7 @@ func testAccConfigRule_tags(t *testing.T) { ), }, { - Config: testAccConfigRuleConfig_Tags(rName, "foo", "bar2", "fizz2", "buzz2"), + Config: testAccConfigRuleConfig_tags(rName, "foo", "bar2", "fizz2", "buzz2"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigRuleExists(resourceName, &cr), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -429,7 +429,7 @@ resource "aws_config_config_rule" "test" { `, rName) } -func testAccConfigRuleConfig_ownerAws(rName string) string { +func testAccConfigRuleConfig_ownerAws(rName string) string { // nosemgrep:aws-in-func-name return testAccConfigRuleConfig_base(rName) + fmt.Sprintf(` resource "aws_config_config_rule" "test" { name = %q @@ -635,7 +635,7 @@ POLICY `, randInt, path) } -func testAccConfigRuleConfig_Scope_TagKey(rName, tagKey string) string { +func testAccConfigRuleConfig_scopeTagKey(rName, tagKey string) string { return testAccConfigRuleConfig_base(rName) + fmt.Sprintf(` resource "aws_config_config_rule" "test" { name = %q @@ -654,7 +654,7 @@ resource "aws_config_config_rule" "test" { `, rName, tagKey) } -func testAccConfigRuleConfig_Scope_TagValue(rName, tagValue string) string { +func testAccConfigRuleConfig_scopeTagValue(rName, tagValue string) string { return testAccConfigRuleConfig_base(rName) + fmt.Sprintf(` resource "aws_config_config_rule" "test" { name = %q @@ -674,7 +674,7 @@ resource "aws_config_config_rule" "test" { `, rName, tagValue) } -func testAccConfigRuleConfig_Tags(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccConfigRuleConfig_tags(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccConfigRuleConfig_base(rName) + fmt.Sprintf(` resource "aws_config_config_rule" "test" { name = %[1]q diff --git a/internal/service/configservice/config_test.go b/internal/service/configservice/config_test.go index 85e99bf7d79..826dcdce6d9 100644 --- a/internal/service/configservice/config_test.go +++ b/internal/service/configservice/config_test.go @@ -65,7 +65,7 @@ func TestAccConfigService_serial(t *testing.T) { "Description": testAccOrganizationCustomRule_Description, "ExcludedAccounts": testAccOrganizationCustomRule_ExcludedAccounts, "InputParameters": testAccOrganizationCustomRule_InputParameters, - "LambdaFunctionArn": testAccOrganizationCustomRule_LambdaFunctionArn, + "LambdaFunctionArn": testAccOrganizationCustomRule_lambdaFunctionARN, "MaximumExecutionFrequency": testAccOrganizationCustomRule_MaximumExecutionFrequency, "ResourceIdScope": testAccOrganizationCustomRule_ResourceIdScope, "ResourceTypesScope": testAccOrganizationCustomRule_ResourceTypesScope, diff --git a/internal/service/configservice/configuration_aggregator_test.go b/internal/service/configservice/configuration_aggregator_test.go index 963c396d2ca..f4c902f9168 100644 --- a/internal/service/configservice/configuration_aggregator_test.go +++ b/internal/service/configservice/configuration_aggregator_test.go @@ -122,7 +122,7 @@ func TestAccConfigServiceConfigurationAggregator_tags(t *testing.T) { CheckDestroy: testAccCheckConfigurationAggregatorDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationAggregatorTags1Config(rName, "key1", "value1"), + Config: testAccConfigurationAggregatorConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationAggregatorExists(resourceName, &ca), testAccCheckConfigurationAggregatorName(resourceName, rName, &ca), @@ -131,7 +131,7 @@ func TestAccConfigServiceConfigurationAggregator_tags(t *testing.T) { ), }, { - Config: testAccConfigurationAggregatorTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccConfigurationAggregatorConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationAggregatorExists(resourceName, &ca), testAccCheckConfigurationAggregatorName(resourceName, rName, &ca), @@ -146,7 +146,7 @@ func TestAccConfigServiceConfigurationAggregator_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationAggregatorTags1Config(rName, "key2", "value2"), + Config: testAccConfigurationAggregatorConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationAggregatorExists(resourceName, &ca), testAccCheckConfigurationAggregatorName(resourceName, rName, &ca), @@ -309,7 +309,7 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName) } -func testAccConfigurationAggregatorTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccConfigurationAggregatorConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -330,7 +330,7 @@ resource "aws_config_configuration_aggregator" "test" { `, rName, tagKey1, tagValue1) } -func testAccConfigurationAggregatorTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccConfigurationAggregatorConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/configservice/configuration_recorder_status_test.go b/internal/service/configservice/configuration_recorder_status_test.go index 94521adc948..e60fcf1dbdd 100644 --- a/internal/service/configservice/configuration_recorder_status_test.go +++ b/internal/service/configservice/configuration_recorder_status_test.go @@ -26,7 +26,7 @@ func testAccConfigurationRecorderStatus_basic(t *testing.T) { CheckDestroy: testAccCheckConfigurationRecorderStatusDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationRecorderStatusConfig(rInt, false), + Config: testAccConfigurationRecorderStatusConfig_basic(rInt, false), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr), testAccCheckConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs), @@ -52,7 +52,7 @@ func testAccConfigurationRecorderStatus_startEnabled(t *testing.T) { CheckDestroy: testAccCheckConfigurationRecorderStatusDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationRecorderStatusConfig(rInt, true), + Config: testAccConfigurationRecorderStatusConfig_basic(rInt, true), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr), testAccCheckConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs), @@ -62,7 +62,7 @@ func testAccConfigurationRecorderStatus_startEnabled(t *testing.T) { ), }, { - Config: testAccConfigurationRecorderStatusConfig(rInt, false), + Config: testAccConfigurationRecorderStatusConfig_basic(rInt, false), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr), testAccCheckConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs), @@ -72,7 +72,7 @@ func testAccConfigurationRecorderStatus_startEnabled(t *testing.T) { ), }, { - Config: testAccConfigurationRecorderStatusConfig(rInt, true), + Config: testAccConfigurationRecorderStatusConfig_basic(rInt, true), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr), testAccCheckConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs), @@ -96,7 +96,7 @@ func testAccConfigurationRecorderStatus_importBasic(t *testing.T) { CheckDestroy: testAccCheckConfigurationRecorderStatusDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationRecorderStatusConfig(rInt, true), + Config: testAccConfigurationRecorderStatusConfig_basic(rInt, true), }, { @@ -173,7 +173,7 @@ func testAccCheckConfigurationRecorderStatusDestroy(s *terraform.State) error { return nil } -func testAccConfigurationRecorderStatusConfig(randInt int, enabled bool) string { +func testAccConfigurationRecorderStatusConfig_basic(randInt int, enabled bool) string { return fmt.Sprintf(` resource "aws_config_configuration_recorder" "foo" { name = "tf-acc-test-%d" diff --git a/internal/service/configservice/conformance_pack_test.go b/internal/service/configservice/conformance_pack_test.go index 13c585bf25c..aa72f9cd002 100644 --- a/internal/service/configservice/conformance_pack_test.go +++ b/internal/service/configservice/conformance_pack_test.go @@ -28,7 +28,7 @@ func testAccConformancePack_basic(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackBasicConfig(rName), + Config: testAccConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("conformance-pack/%s/.+", rName))), @@ -63,13 +63,13 @@ func testAccConformancePack_forceNew(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackBasicConfig(rName), + Config: testAccConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &before), ), }, { - Config: testAccConformancePackBasicConfig(rNameUpdated), + Config: testAccConformancePackConfig_basic(rNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &after), testAccCheckConformancePackRecreated(&before, &after), @@ -104,7 +104,7 @@ func testAccConformancePack_disappears(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackBasicConfig(rName), + Config: testAccConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), acctest.CheckResourceDisappears(acctest.Provider, tfconfig.ResourceConformancePack(), resourceName), @@ -127,7 +127,7 @@ func testAccConformancePack_inputParameters(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackInputParameterConfig(rName, "TestKey", "TestValue"), + Config: testAccConformancePackConfig_inputParameter(rName, "TestKey", "TestValue"), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("conformance-pack/%s/.+", rName))), @@ -163,7 +163,7 @@ func testAccConformancePack_S3Delivery(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackS3DeliveryConfig(rName, rName), + Config: testAccConformancePackConfig_s3Delivery(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("conformance-pack/%s/.+", rName))), @@ -195,7 +195,7 @@ func testAccConformancePack_S3Template(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackS3TemplateConfig(rName, rName), + Config: testAccConformancePackConfig_s3Template(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("conformance-pack/%s/.+", rName))), @@ -227,13 +227,13 @@ func testAccConformancePack_updateInputParameters(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackInputParameterConfig(rName, "TestKey", "TestValue"), + Config: testAccConformancePackConfig_inputParameter(rName, "TestKey", "TestValue"), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), ), }, { - Config: testAccConformancePackUpdateInputParameterConfig(rName, "TestKey1", "TestKey2"), + Config: testAccConformancePackConfig_updateInputParameter(rName, "TestKey1", "TestKey2"), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "input_parameter.#", "2"), @@ -254,7 +254,7 @@ func testAccConformancePack_updateInputParameters(t *testing.T) { ImportStateVerifyIgnore: []string{"template_body"}, }, { - Config: testAccConformancePackBasicConfig(rName), + Config: testAccConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "input_parameter.#", "0"), @@ -277,13 +277,13 @@ func testAccConformancePack_updateS3Delivery(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackS3DeliveryConfig(rName, rName), + Config: testAccConformancePackConfig_s3Delivery(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), ), }, { - Config: testAccConformancePackS3DeliveryConfig(rName, bucketName), + Config: testAccConformancePackConfig_s3Delivery(rName, bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("conformance-pack/%s/.+", rName))), @@ -316,13 +316,13 @@ func testAccConformancePack_updateS3Template(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackS3TemplateConfig(rName, rName), + Config: testAccConformancePackConfig_s3Template(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), ), }, { - Config: testAccConformancePackS3TemplateConfig(rName, bucketName), + Config: testAccConformancePackConfig_s3Template(rName, bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("conformance-pack/%s/.+", rName))), @@ -354,13 +354,13 @@ func testAccConformancePack_updateTemplateBody(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackBasicConfig(rName), + Config: testAccConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), ), }, { - Config: testAccConformancePackUpdateConfig(rName), + Config: testAccConformancePackConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("conformance-pack/%s/.+", rName))), @@ -394,7 +394,7 @@ func testAccConformancePack_S3TemplateAndTemplateBody(t *testing.T) { CheckDestroy: testAccCheckConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccConformancePackS3TemplateAndTemplateBodyConfig(rName), + Config: testAccConformancePackConfig_s3TemplateAndTemplateBody(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("conformance-pack/%s/.+", rName))), @@ -514,7 +514,7 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName) } -func testAccConformancePackBasicConfig(rName string) string { +func testAccConformancePackConfig_basic(rName string) string { return acctest.ConfigCompose(testAccConformancePackConfigBase(rName), fmt.Sprintf(` resource "aws_config_conformance_pack" "test" { @@ -534,7 +534,7 @@ EOT `, rName)) } -func testAccConformancePackUpdateConfig(rName string) string { +func testAccConformancePackConfig_update(rName string) string { return acctest.ConfigCompose(testAccConformancePackConfigBase(rName), fmt.Sprintf(` resource "aws_config_conformance_pack" "test" { @@ -554,7 +554,7 @@ EOT `, rName)) } -func testAccConformancePackInputParameterConfig(rName, pName, pValue string) string { +func testAccConformancePackConfig_inputParameter(rName, pName, pValue string) string { return acctest.ConfigCompose(testAccConformancePackConfigBase(rName), fmt.Sprintf(` resource "aws_config_conformance_pack" "test" { @@ -583,7 +583,7 @@ EOT `, rName, pName, pValue)) } -func testAccConformancePackUpdateInputParameterConfig(rName, pName1, pName2 string) string { +func testAccConformancePackConfig_updateInputParameter(rName, pName1, pName2 string) string { return acctest.ConfigCompose(testAccConformancePackConfigBase(rName), fmt.Sprintf(` resource "aws_config_conformance_pack" "test" { @@ -620,7 +620,7 @@ EOT `, rName, pName1, pName2)) } -func testAccConformancePackS3DeliveryConfig(rName, bucketName string) string { +func testAccConformancePackConfig_s3Delivery(rName, bucketName string) string { return acctest.ConfigCompose(testAccConformancePackConfigBase(rName), fmt.Sprintf(` resource "aws_s3_bucket" "test" { @@ -652,7 +652,7 @@ EOT `, bucketName, rName)) } -func testAccConformancePackS3TemplateConfig(rName, bucketName string) string { +func testAccConformancePackConfig_s3Template(rName, bucketName string) string { return acctest.ConfigCompose(testAccConformancePackConfigBase(rName), fmt.Sprintf(` resource "aws_s3_bucket" "test" { @@ -688,7 +688,7 @@ resource "aws_config_conformance_pack" "test" { `, bucketName, rName)) } -func testAccConformancePackS3TemplateAndTemplateBodyConfig(rName string) string { +func testAccConformancePackConfig_s3TemplateAndTemplateBody(rName string) string { return acctest.ConfigCompose(testAccConformancePackConfigBase(rName), fmt.Sprintf(` resource "aws_s3_bucket" "test" { diff --git a/internal/service/configservice/organization_conformance_pack_test.go b/internal/service/configservice/organization_conformance_pack_test.go index 9f7594163b7..5a4596fecda 100644 --- a/internal/service/configservice/organization_conformance_pack_test.go +++ b/internal/service/configservice/organization_conformance_pack_test.go @@ -28,7 +28,7 @@ func testAccOrganizationConformancePack_basic(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackBasicConfig(rName), + Config: testAccOrganizationConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("organization-conformance-pack/%s-.+", rName))), @@ -61,7 +61,7 @@ func testAccOrganizationConformancePack_disappears(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackBasicConfig(rName), + Config: testAccOrganizationConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), acctest.CheckResourceDisappears(acctest.Provider, tfconfig.ResourceOrganizationConformancePack(), resourceName), @@ -84,7 +84,7 @@ func testAccOrganizationConformancePack_excludedAccounts(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackExcludedAccounts1Config(rName), + Config: testAccOrganizationConformancePackConfig_excludedAccounts1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "excluded_accounts.#", "1"), @@ -97,7 +97,7 @@ func testAccOrganizationConformancePack_excludedAccounts(t *testing.T) { ImportStateVerifyIgnore: []string{"template_body"}, }, { - Config: testAccOrganizationConformancePackExcludedAccounts2Config(rName), + Config: testAccOrganizationConformancePackConfig_excludedAccounts2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "excluded_accounts.#", "2"), @@ -110,7 +110,7 @@ func testAccOrganizationConformancePack_excludedAccounts(t *testing.T) { ImportStateVerifyIgnore: []string{"template_body"}, }, { - Config: testAccOrganizationConformancePackBasicConfig(rName), + Config: testAccOrganizationConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "excluded_accounts.#", "0"), @@ -133,13 +133,13 @@ func testAccOrganizationConformancePack_forceNew(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackBasicConfig(rName), + Config: testAccOrganizationConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &before), ), }, { - Config: testAccOrganizationConformancePackBasicConfig(rNameUpdated), + Config: testAccOrganizationConformancePackConfig_basic(rNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &after), testAccCheckOrganizationConformancePackRecreated(&before, &after), @@ -175,7 +175,7 @@ func testAccOrganizationConformancePack_inputParameters(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackInputParameterConfig(rName, pKey, pValue), + Config: testAccOrganizationConformancePackConfig_inputParameter(rName, pKey, pValue), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "input_parameter.#", "1"), @@ -208,7 +208,7 @@ func testAccOrganizationConformancePack_S3Delivery(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackS3DeliveryConfig(rName, bucketName), + Config: testAccOrganizationConformancePackConfig_s3Delivery(rName, bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "delivery_s3_bucket", bucketName), @@ -237,7 +237,7 @@ func testAccOrganizationConformancePack_S3Template(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackS3TemplateConfig(rName, rName), + Config: testAccOrganizationConformancePackConfig_s3Template(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("organization-conformance-pack/%s-.+", rName))), @@ -270,13 +270,13 @@ func testAccOrganizationConformancePack_updateInputParameters(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackInputParameterConfig(rName, "TestKey", "TestValue"), + Config: testAccOrganizationConformancePackConfig_inputParameter(rName, "TestKey", "TestValue"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), ), }, { - Config: testAccOrganizationConformancePackUpdateInputParameterConfig(rName, "TestKey1", "TestKey2"), + Config: testAccOrganizationConformancePackConfig_updateInputParameter(rName, "TestKey1", "TestKey2"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "input_parameter.#", "2"), @@ -297,7 +297,7 @@ func testAccOrganizationConformancePack_updateInputParameters(t *testing.T) { ImportStateVerifyIgnore: []string{"template_body"}, }, { - Config: testAccOrganizationConformancePackBasicConfig(rName), + Config: testAccOrganizationConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "input_parameter.#", "0"), @@ -321,7 +321,7 @@ func testAccOrganizationConformancePack_updateS3Delivery(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackS3DeliveryConfig(rName, bucketName), + Config: testAccOrganizationConformancePackConfig_s3Delivery(rName, bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "delivery_s3_bucket", bucketName), @@ -329,7 +329,7 @@ func testAccOrganizationConformancePack_updateS3Delivery(t *testing.T) { ), }, { - Config: testAccOrganizationConformancePackS3DeliveryConfig(rName, updatedBucketName), + Config: testAccOrganizationConformancePackConfig_s3Delivery(rName, updatedBucketName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), resource.TestCheckResourceAttr(resourceName, "delivery_s3_bucket", updatedBucketName), @@ -359,13 +359,13 @@ func testAccOrganizationConformancePack_updateS3Template(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackS3TemplateConfig(rName, rName), + Config: testAccOrganizationConformancePackConfig_s3Template(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), ), }, { - Config: testAccOrganizationConformancePackS3TemplateConfig(rName, bucketName), + Config: testAccOrganizationConformancePackConfig_s3Template(rName, bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), ), @@ -392,13 +392,13 @@ func testAccOrganizationConformancePack_updateTemplateBody(t *testing.T) { CheckDestroy: testAccCheckOrganizationConformancePackDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConformancePackBasicConfig(rName), + Config: testAccOrganizationConformancePackConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), ), }, { - Config: testAccOrganizationConformancePackUpdateConfig(rName), + Config: testAccOrganizationConformancePackConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationConformancePackExists(resourceName, &pack), ), @@ -520,7 +520,7 @@ resource "aws_organizations_organization" "test" { `, rName) } -func testAccOrganizationConformancePackBasicConfig(rName string) string { +func testAccOrganizationConformancePackConfig_basic(rName string) string { return acctest.ConfigCompose( testAccOrganizationConformancePackBase(rName), fmt.Sprintf(` @@ -541,7 +541,7 @@ EOT `, rName)) } -func testAccOrganizationConformancePackInputParameterConfig(rName, pKey, pValue string) string { +func testAccOrganizationConformancePackConfig_inputParameter(rName, pKey, pValue string) string { return acctest.ConfigCompose( testAccOrganizationConformancePackBase(rName), fmt.Sprintf(` @@ -571,7 +571,7 @@ EOT `, rName, pKey, pValue)) } -func testAccOrganizationConformancePackUpdateInputParameterConfig(rName, pName1, pName2 string) string { +func testAccOrganizationConformancePackConfig_updateInputParameter(rName, pName1, pName2 string) string { return acctest.ConfigCompose( testAccOrganizationConformancePackBase(rName), fmt.Sprintf(` @@ -608,7 +608,7 @@ EOT `, rName, pName1, pName2)) } -func testAccOrganizationConformancePackS3DeliveryConfig(rName, bName string) string { +func testAccOrganizationConformancePackConfig_s3Delivery(rName, bName string) string { return acctest.ConfigCompose( testAccOrganizationConformancePackBase(rName), fmt.Sprintf(` @@ -641,7 +641,7 @@ resource "aws_s3_bucket_acl" "test" { `, rName, bName)) } -func testAccOrganizationConformancePackS3TemplateConfig(rName, bName string) string { +func testAccOrganizationConformancePackConfig_s3Template(rName, bName string) string { return acctest.ConfigCompose( testAccOrganizationConformancePackBase(rName), fmt.Sprintf(` @@ -678,7 +678,7 @@ EOT `, rName, bName)) } -func testAccOrganizationConformancePackUpdateConfig(rName string) string { +func testAccOrganizationConformancePackConfig_update(rName string) string { return acctest.ConfigCompose( testAccOrganizationConformancePackBase(rName), fmt.Sprintf(` @@ -699,7 +699,7 @@ EOT `, rName)) } -func testAccOrganizationConformancePackExcludedAccounts1Config(rName string) string { +func testAccOrganizationConformancePackConfig_excludedAccounts1(rName string) string { return acctest.ConfigCompose( testAccOrganizationConformancePackBase(rName), fmt.Sprintf(` @@ -723,7 +723,7 @@ EOT `, rName)) } -func testAccOrganizationConformancePackExcludedAccounts2Config(rName string) string { +func testAccOrganizationConformancePackConfig_excludedAccounts2(rName string) string { return acctest.ConfigCompose( testAccOrganizationConformancePackBase(rName), fmt.Sprintf(` diff --git a/internal/service/configservice/organization_custom_rule_test.go b/internal/service/configservice/organization_custom_rule_test.go index f5a34cd1d43..a6f8941e17a 100644 --- a/internal/service/configservice/organization_custom_rule_test.go +++ b/internal/service/configservice/organization_custom_rule_test.go @@ -28,7 +28,7 @@ func testAccOrganizationCustomRule_basic(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigTriggerTypes1(rName, "ConfigurationItemChangeNotification"), + Config: testAccOrganizationCustomRuleConfig_triggerTypes1(rName, "ConfigurationItemChangeNotification"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("organization-config-rule/%s-.+", rName))), @@ -66,7 +66,7 @@ func testAccOrganizationCustomRule_disappears(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigTriggerTypes1(rName, "ConfigurationItemChangeNotification"), + Config: testAccOrganizationCustomRuleConfig_triggerTypes1(rName, "ConfigurationItemChangeNotification"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), acctest.CheckResourceDisappears(acctest.Provider, tfconfig.ResourceOrganizationCustomRule(), resourceName), @@ -87,7 +87,7 @@ func testAccOrganizationCustomRule_errorHandling(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigErrorHandling(rName), + Config: testAccOrganizationCustomRuleConfig_errorHandling(rName), ExpectError: regexp.MustCompile(`InsufficientPermission`), }, }, @@ -106,7 +106,7 @@ func testAccOrganizationCustomRule_Description(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigDescription(rName, "description1"), + Config: testAccOrganizationCustomRuleConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -118,7 +118,7 @@ func testAccOrganizationCustomRule_Description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigDescription(rName, "description2"), + Config: testAccOrganizationCustomRuleConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -140,7 +140,7 @@ func testAccOrganizationCustomRule_ExcludedAccounts(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigExcludedAccounts1(rName), + Config: testAccOrganizationCustomRuleConfig_excludedAccounts1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "excluded_accounts.#", "1"), @@ -152,7 +152,7 @@ func testAccOrganizationCustomRule_ExcludedAccounts(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigExcludedAccounts2(rName), + Config: testAccOrganizationCustomRuleConfig_excludedAccounts2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "excluded_accounts.#", "2"), @@ -177,7 +177,7 @@ func testAccOrganizationCustomRule_InputParameters(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigInputParameters(rName, inputParameters1), + Config: testAccOrganizationCustomRuleConfig_inputParameters(rName, inputParameters1), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestMatchResourceAttr(resourceName, "input_parameters", regexp.MustCompile(`CostCenter`)), @@ -189,7 +189,7 @@ func testAccOrganizationCustomRule_InputParameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigInputParameters(rName, inputParameters2), + Config: testAccOrganizationCustomRuleConfig_inputParameters(rName, inputParameters2), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestMatchResourceAttr(resourceName, "input_parameters", regexp.MustCompile(`Department`)), @@ -199,7 +199,7 @@ func testAccOrganizationCustomRule_InputParameters(t *testing.T) { }) } -func testAccOrganizationCustomRule_LambdaFunctionArn(t *testing.T) { +func testAccOrganizationCustomRule_lambdaFunctionARN(t *testing.T) { var rule configservice.OrganizationConfigRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) lambdaFunctionResourceName1 := "aws_lambda_function.test" @@ -213,7 +213,7 @@ func testAccOrganizationCustomRule_LambdaFunctionArn(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigLambdaFunctionArn1(rName), + Config: testAccOrganizationCustomRuleConfig_lambdaFunctionARN1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttrPair(resourceName, "lambda_function_arn", lambdaFunctionResourceName1, "arn"), @@ -225,7 +225,7 @@ func testAccOrganizationCustomRule_LambdaFunctionArn(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigLambdaFunctionArn2(rName), + Config: testAccOrganizationCustomRuleConfig_lambdaFunctionARN2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttrPair(resourceName, "lambda_function_arn", lambdaFunctionResourceName2, "arn"), @@ -247,7 +247,7 @@ func testAccOrganizationCustomRule_MaximumExecutionFrequency(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigMaximumExecutionFrequency(rName, "One_Hour"), + Config: testAccOrganizationCustomRuleConfig_maximumExecutionFrequency(rName, "One_Hour"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "maximum_execution_frequency", "One_Hour"), @@ -259,7 +259,7 @@ func testAccOrganizationCustomRule_MaximumExecutionFrequency(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigMaximumExecutionFrequency(rName, "Three_Hours"), + Config: testAccOrganizationCustomRuleConfig_maximumExecutionFrequency(rName, "Three_Hours"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "maximum_execution_frequency", "Three_Hours"), @@ -281,7 +281,7 @@ func testAccOrganizationCustomRule_ResourceIdScope(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigResourceIdScope(rName, "i-12345678"), + Config: testAccOrganizationCustomRuleConfig_resourceIdScope(rName, "i-12345678"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "resource_id_scope", "i-12345678"), @@ -293,7 +293,7 @@ func testAccOrganizationCustomRule_ResourceIdScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigResourceIdScope(rName, "i-87654321"), + Config: testAccOrganizationCustomRuleConfig_resourceIdScope(rName, "i-87654321"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "resource_id_scope", "i-87654321"), @@ -315,7 +315,7 @@ func testAccOrganizationCustomRule_ResourceTypesScope(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigResourceTypesScope1(rName), + Config: testAccOrganizationCustomRuleConfig_resourceTypesScope1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "resource_types_scope.#", "1"), @@ -327,7 +327,7 @@ func testAccOrganizationCustomRule_ResourceTypesScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigResourceTypesScope2(rName), + Config: testAccOrganizationCustomRuleConfig_resourceTypesScope2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "resource_types_scope.#", "2"), @@ -349,7 +349,7 @@ func testAccOrganizationCustomRule_TagKeyScope(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigTagKeyScope(rName, "key1"), + Config: testAccOrganizationCustomRuleConfig_tagKeyScope(rName, "key1"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "tag_key_scope", "key1"), @@ -361,7 +361,7 @@ func testAccOrganizationCustomRule_TagKeyScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigTagKeyScope(rName, "key2"), + Config: testAccOrganizationCustomRuleConfig_tagKeyScope(rName, "key2"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "tag_key_scope", "key2"), @@ -383,7 +383,7 @@ func testAccOrganizationCustomRule_TagValueScope(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigTagValueScope(rName, "value1"), + Config: testAccOrganizationCustomRuleConfig_tagValueScope(rName, "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "tag_value_scope", "value1"), @@ -395,7 +395,7 @@ func testAccOrganizationCustomRule_TagValueScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigTagValueScope(rName, "value2"), + Config: testAccOrganizationCustomRuleConfig_tagValueScope(rName, "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "tag_value_scope", "value2"), @@ -417,7 +417,7 @@ func testAccOrganizationCustomRule_TriggerTypes(t *testing.T) { CheckDestroy: testAccCheckOrganizationCustomRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationCustomRuleConfigTriggerTypes1(rName, "ScheduledNotification"), + Config: testAccOrganizationCustomRuleConfig_triggerTypes1(rName, "ScheduledNotification"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "trigger_types.#", "1"), @@ -429,7 +429,7 @@ func testAccOrganizationCustomRule_TriggerTypes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationCustomRuleConfigTriggerTypes2(rName, "ConfigurationItemChangeNotification", "OversizedConfigurationItemChangeNotification"), + Config: testAccOrganizationCustomRuleConfig_triggerTypes2(rName, "ConfigurationItemChangeNotification", "OversizedConfigurationItemChangeNotification"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationCustomRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "trigger_types.#", "2"), @@ -574,7 +574,7 @@ resource "aws_organizations_organization" "test" { `, rName) } -func testAccOrganizationCustomRuleConfigDescription(rName, description string) string { +func testAccOrganizationCustomRuleConfig_description(rName, description string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -587,7 +587,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName, description) } -func testAccOrganizationCustomRuleConfigErrorHandling(rName string) string { +func testAccOrganizationCustomRuleConfig_errorHandling(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" { } @@ -640,7 +640,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName) } -func testAccOrganizationCustomRuleConfigExcludedAccounts1(rName string) string { +func testAccOrganizationCustomRuleConfig_excludedAccounts1(rName string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -653,7 +653,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName) } -func testAccOrganizationCustomRuleConfigExcludedAccounts2(rName string) string { +func testAccOrganizationCustomRuleConfig_excludedAccounts2(rName string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -666,7 +666,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName) } -func testAccOrganizationCustomRuleConfigInputParameters(rName, inputParameters string) string { +func testAccOrganizationCustomRuleConfig_inputParameters(rName, inputParameters string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -682,7 +682,7 @@ PARAMS `, rName, inputParameters) } -func testAccOrganizationCustomRuleConfigLambdaFunctionArn1(rName string) string { +func testAccOrganizationCustomRuleConfig_lambdaFunctionARN1(rName string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -694,7 +694,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName) } -func testAccOrganizationCustomRuleConfigLambdaFunctionArn2(rName string) string { +func testAccOrganizationCustomRuleConfig_lambdaFunctionARN2(rName string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_lambda_function" "test2" { filename = "test-fixtures/lambdatest.zip" @@ -721,7 +721,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName) } -func testAccOrganizationCustomRuleConfigMaximumExecutionFrequency(rName, maximumExecutionFrequency string) string { +func testAccOrganizationCustomRuleConfig_maximumExecutionFrequency(rName, maximumExecutionFrequency string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -734,7 +734,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName, maximumExecutionFrequency) } -func testAccOrganizationCustomRuleConfigResourceIdScope(rName, resourceIdScope string) string { +func testAccOrganizationCustomRuleConfig_resourceIdScope(rName, resourceIdScope string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -748,7 +748,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName, resourceIdScope) } -func testAccOrganizationCustomRuleConfigResourceTypesScope1(rName string) string { +func testAccOrganizationCustomRuleConfig_resourceTypesScope1(rName string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -761,7 +761,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName) } -func testAccOrganizationCustomRuleConfigResourceTypesScope2(rName string) string { +func testAccOrganizationCustomRuleConfig_resourceTypesScope2(rName string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -774,7 +774,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName) } -func testAccOrganizationCustomRuleConfigTagKeyScope(rName, tagKeyScope string) string { +func testAccOrganizationCustomRuleConfig_tagKeyScope(rName, tagKeyScope string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -787,7 +787,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName, tagKeyScope) } -func testAccOrganizationCustomRuleConfigTagValueScope(rName, tagValueScope string) string { +func testAccOrganizationCustomRuleConfig_tagValueScope(rName, tagValueScope string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -801,7 +801,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName, tagValueScope) } -func testAccOrganizationCustomRuleConfigTriggerTypes1(rName, triggerType1 string) string { +func testAccOrganizationCustomRuleConfig_triggerTypes1(rName, triggerType1 string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] @@ -813,7 +813,7 @@ resource "aws_config_organization_custom_rule" "test" { `, rName, triggerType1) } -func testAccOrganizationCustomRuleConfigTriggerTypes2(rName, triggerType1, triggerType2 string) string { +func testAccOrganizationCustomRuleConfig_triggerTypes2(rName, triggerType1, triggerType2 string) string { return testAccOrganizationCustomRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_custom_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_lambda_permission.test, aws_organizations_organization.test] diff --git a/internal/service/configservice/organization_managed_rule_test.go b/internal/service/configservice/organization_managed_rule_test.go index 45caf6d4da0..b50eac82f90 100644 --- a/internal/service/configservice/organization_managed_rule_test.go +++ b/internal/service/configservice/organization_managed_rule_test.go @@ -27,7 +27,7 @@ func testAccOrganizationManagedRule_basic(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigRuleIdentifier(rName, "IAM_PASSWORD_POLICY"), + Config: testAccOrganizationManagedRuleConfig_identifier(rName, "IAM_PASSWORD_POLICY"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "config", regexp.MustCompile(fmt.Sprintf("organization-config-rule/%s-.+", rName))), @@ -64,7 +64,7 @@ func testAccOrganizationManagedRule_disappears(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigRuleIdentifier(rName, "IAM_PASSWORD_POLICY"), + Config: testAccOrganizationManagedRuleConfig_identifier(rName, "IAM_PASSWORD_POLICY"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), acctest.CheckResourceDisappears(acctest.Provider, tfconfig.ResourceOrganizationManagedRule(), resourceName), @@ -85,7 +85,7 @@ func testAccOrganizationManagedRule_errorHandling(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigErrorHandling(rName), + Config: testAccOrganizationManagedRuleConfig_errorHandling(rName), ExpectError: regexp.MustCompile(`NoAvailableConfigurationRecorder`), }, }, @@ -104,7 +104,7 @@ func testAccOrganizationManagedRule_Description(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigDescription(rName, "description1"), + Config: testAccOrganizationManagedRuleConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -116,7 +116,7 @@ func testAccOrganizationManagedRule_Description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationManagedRuleConfigDescription(rName, "description2"), + Config: testAccOrganizationManagedRuleConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -138,7 +138,7 @@ func testAccOrganizationManagedRule_ExcludedAccounts(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigExcludedAccounts1(rName), + Config: testAccOrganizationManagedRuleConfig_excludedAccounts1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "excluded_accounts.#", "1"), @@ -150,7 +150,7 @@ func testAccOrganizationManagedRule_ExcludedAccounts(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationManagedRuleConfigExcludedAccounts2(rName), + Config: testAccOrganizationManagedRuleConfig_excludedAccounts2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "excluded_accounts.#", "2"), @@ -175,7 +175,7 @@ func testAccOrganizationManagedRule_InputParameters(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigInputParameters(rName, inputParameters1), + Config: testAccOrganizationManagedRuleConfig_inputParameters(rName, inputParameters1), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestMatchResourceAttr(resourceName, "input_parameters", regexp.MustCompile(`CostCenter`)), @@ -187,7 +187,7 @@ func testAccOrganizationManagedRule_InputParameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationManagedRuleConfigInputParameters(rName, inputParameters2), + Config: testAccOrganizationManagedRuleConfig_inputParameters(rName, inputParameters2), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestMatchResourceAttr(resourceName, "input_parameters", regexp.MustCompile(`Department`)), @@ -209,7 +209,7 @@ func testAccOrganizationManagedRule_MaximumExecutionFrequency(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigMaximumExecutionFrequency(rName, "One_Hour"), + Config: testAccOrganizationManagedRuleConfig_maximumExecutionFrequency(rName, "One_Hour"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "maximum_execution_frequency", "One_Hour"), @@ -221,7 +221,7 @@ func testAccOrganizationManagedRule_MaximumExecutionFrequency(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationManagedRuleConfigMaximumExecutionFrequency(rName, "Three_Hours"), + Config: testAccOrganizationManagedRuleConfig_maximumExecutionFrequency(rName, "Three_Hours"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "maximum_execution_frequency", "Three_Hours"), @@ -243,7 +243,7 @@ func testAccOrganizationManagedRule_ResourceIdScope(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigResourceIdScope(rName, "i-12345678"), + Config: testAccOrganizationManagedRuleConfig_resourceIdScope(rName, "i-12345678"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "resource_id_scope", "i-12345678"), @@ -255,7 +255,7 @@ func testAccOrganizationManagedRule_ResourceIdScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationManagedRuleConfigResourceIdScope(rName, "i-87654321"), + Config: testAccOrganizationManagedRuleConfig_resourceIdScope(rName, "i-87654321"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "resource_id_scope", "i-87654321"), @@ -277,7 +277,7 @@ func testAccOrganizationManagedRule_ResourceTypesScope(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigResourceTypesScope1(rName), + Config: testAccOrganizationManagedRuleConfig_resourceTypesScope1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "resource_types_scope.#", "1"), @@ -289,7 +289,7 @@ func testAccOrganizationManagedRule_ResourceTypesScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationManagedRuleConfigResourceTypesScope2(rName), + Config: testAccOrganizationManagedRuleConfig_resourceTypesScope2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "resource_types_scope.#", "2"), @@ -311,7 +311,7 @@ func testAccOrganizationManagedRule_RuleIdentifier(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigRuleIdentifier(rName, "EC2_INSTANCE_DETAILED_MONITORING_ENABLED"), + Config: testAccOrganizationManagedRuleConfig_identifier(rName, "EC2_INSTANCE_DETAILED_MONITORING_ENABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "rule_identifier", "EC2_INSTANCE_DETAILED_MONITORING_ENABLED"), @@ -323,7 +323,7 @@ func testAccOrganizationManagedRule_RuleIdentifier(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationManagedRuleConfigRuleIdentifier(rName, "EC2_INSTANCE_NO_PUBLIC_IP"), + Config: testAccOrganizationManagedRuleConfig_identifier(rName, "EC2_INSTANCE_NO_PUBLIC_IP"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "rule_identifier", "EC2_INSTANCE_NO_PUBLIC_IP"), @@ -345,7 +345,7 @@ func testAccOrganizationManagedRule_TagKeyScope(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigTagKeyScope(rName, "key1"), + Config: testAccOrganizationManagedRuleConfig_tagKeyScope(rName, "key1"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "tag_key_scope", "key1"), @@ -357,7 +357,7 @@ func testAccOrganizationManagedRule_TagKeyScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationManagedRuleConfigTagKeyScope(rName, "key2"), + Config: testAccOrganizationManagedRuleConfig_tagKeyScope(rName, "key2"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "tag_key_scope", "key2"), @@ -379,7 +379,7 @@ func testAccOrganizationManagedRule_TagValueScope(t *testing.T) { CheckDestroy: testAccCheckOrganizationManagedRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationManagedRuleConfigTagValueScope(rName, "value1"), + Config: testAccOrganizationManagedRuleConfig_tagValueScope(rName, "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "tag_value_scope", "value1"), @@ -391,7 +391,7 @@ func testAccOrganizationManagedRule_TagValueScope(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationManagedRuleConfigTagValueScope(rName, "value2"), + Config: testAccOrganizationManagedRuleConfig_tagValueScope(rName, "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationManagedRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "tag_value_scope", "value2"), @@ -496,7 +496,7 @@ resource "aws_organizations_organization" "test" { `, rName) } -func testAccOrganizationManagedRuleConfigDescription(rName, description string) string { +func testAccOrganizationManagedRuleConfig_description(rName, description string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -508,7 +508,7 @@ resource "aws_config_organization_managed_rule" "test" { `, rName, description) } -func testAccOrganizationManagedRuleConfigErrorHandling(rName string) string { +func testAccOrganizationManagedRuleConfig_errorHandling(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" { aws_service_access_principals = ["config-multiaccountsetup.amazonaws.com"] @@ -524,7 +524,7 @@ resource "aws_config_organization_managed_rule" "test" { `, rName) } -func testAccOrganizationManagedRuleConfigExcludedAccounts1(rName string) string { +func testAccOrganizationManagedRuleConfig_excludedAccounts1(rName string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -536,7 +536,7 @@ resource "aws_config_organization_managed_rule" "test" { `, rName) } -func testAccOrganizationManagedRuleConfigExcludedAccounts2(rName string) string { +func testAccOrganizationManagedRuleConfig_excludedAccounts2(rName string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -548,7 +548,7 @@ resource "aws_config_organization_managed_rule" "test" { `, rName) } -func testAccOrganizationManagedRuleConfigInputParameters(rName, inputParameters string) string { +func testAccOrganizationManagedRuleConfig_inputParameters(rName, inputParameters string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -563,7 +563,7 @@ PARAMS `, rName, inputParameters) } -func testAccOrganizationManagedRuleConfigMaximumExecutionFrequency(rName, maximumExecutionFrequency string) string { +func testAccOrganizationManagedRuleConfig_maximumExecutionFrequency(rName, maximumExecutionFrequency string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -575,7 +575,7 @@ resource "aws_config_organization_managed_rule" "test" { `, rName, maximumExecutionFrequency) } -func testAccOrganizationManagedRuleConfigResourceIdScope(rName, resourceIdScope string) string { +func testAccOrganizationManagedRuleConfig_resourceIdScope(rName, resourceIdScope string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -588,7 +588,7 @@ resource "aws_config_organization_managed_rule" "test" { `, rName, resourceIdScope) } -func testAccOrganizationManagedRuleConfigResourceTypesScope1(rName string) string { +func testAccOrganizationManagedRuleConfig_resourceTypesScope1(rName string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -607,7 +607,7 @@ EOF `, rName) } -func testAccOrganizationManagedRuleConfigResourceTypesScope2(rName string) string { +func testAccOrganizationManagedRuleConfig_resourceTypesScope2(rName string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -626,7 +626,7 @@ EOF `, rName) } -func testAccOrganizationManagedRuleConfigRuleIdentifier(rName, ruleIdentifier string) string { +func testAccOrganizationManagedRuleConfig_identifier(rName, ruleIdentifier string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -637,7 +637,7 @@ resource "aws_config_organization_managed_rule" "test" { `, rName, ruleIdentifier) } -func testAccOrganizationManagedRuleConfigTagKeyScope(rName, tagKeyScope string) string { +func testAccOrganizationManagedRuleConfig_tagKeyScope(rName, tagKeyScope string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] @@ -649,7 +649,7 @@ resource "aws_config_organization_managed_rule" "test" { `, rName, tagKeyScope) } -func testAccOrganizationManagedRuleConfigTagValueScope(rName, tagValueScope string) string { +func testAccOrganizationManagedRuleConfig_tagValueScope(rName, tagValueScope string) string { return testAccOrganizationManagedRuleConfigBase(rName) + fmt.Sprintf(` resource "aws_config_organization_managed_rule" "test" { depends_on = [aws_config_configuration_recorder.test, aws_organizations_organization.test] diff --git a/internal/service/configservice/remediation_configuration.go b/internal/service/configservice/remediation_configuration.go index d3480be6436..0c2339772ed 100644 --- a/internal/service/configservice/remediation_configuration.go +++ b/internal/service/configservice/remediation_configuration.go @@ -162,7 +162,7 @@ func expandRemediationConfigurationExecutionControlsConfig(v map[string]interfac if w, ok := v["ssm_controls"]; ok { x := w.([]interface{}) if len(x) > 0 { - ssmControls, err := expandRemediationConfigurationSsmControlsConfig(x[0].(map[string]interface{})) + ssmControls, err := expandRemediationConfigurationSSMControlsConfig(x[0].(map[string]interface{})) if err != nil { return nil, err } @@ -175,7 +175,7 @@ func expandRemediationConfigurationExecutionControlsConfig(v map[string]interfac return nil, fmt.Errorf("expected 'ssm_controls' in execution controls configuration") } -func expandRemediationConfigurationSsmControlsConfig(v map[string]interface{}) (ret *configservice.SsmControls, err error) { +func expandRemediationConfigurationSSMControlsConfig(v map[string]interface{}) (ret *configservice.SsmControls, err error) { ret = &configservice.SsmControls{} p := false if concurrentExecutionRatePercentage, ok := v["concurrent_execution_rate_percentage"]; ok { @@ -216,11 +216,11 @@ func flattenRemediationConfigurationExecutionControlsConfig(controls *configserv return nil } return []interface{}{map[string]interface{}{ - "ssm_controls": flattenRemediationConfigurationSsmControlsConfig(controls.SsmControls), + "ssm_controls": flattenRemediationConfigurationSSMControlsConfig(controls.SsmControls), }} } -func flattenRemediationConfigurationSsmControlsConfig(controls *configservice.SsmControls) []interface{} { +func flattenRemediationConfigurationSSMControlsConfig(controls *configservice.SsmControls) []interface{} { if controls == nil { return nil } diff --git a/internal/service/configservice/remediation_configuration_test.go b/internal/service/configservice/remediation_configuration_test.go index 798928993c6..2fb61369827 100644 --- a/internal/service/configservice/remediation_configuration_test.go +++ b/internal/service/configservice/remediation_configuration_test.go @@ -35,7 +35,7 @@ func testAccRemediationConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckRemediationConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccRemediationConfigurationConfig(prefix, sseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), + Config: testAccRemediationConfigurationConfig_basic(prefix, sseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), Check: resource.ComposeTestCheckFunc( testAccCheckRemediationConfigurationExists(resourceName, &rc), resource.TestCheckResourceAttr(resourceName, "config_rule_name", expectedName), @@ -76,7 +76,7 @@ func testAccRemediationConfiguration_basicBackwardCompatible(t *testing.T) { CheckDestroy: testAccCheckRemediationConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccRemediationConfigurationOlderSchemaConfig(prefix, sseAlgorithm, rInt), + Config: testAccRemediationConfigurationConfig_olderSchema(prefix, sseAlgorithm, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckRemediationConfigurationExists(resourceName, &rc), resource.TestCheckResourceAttr(resourceName, "config_rule_name", expectedName), @@ -113,7 +113,7 @@ func testAccRemediationConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckRemediationConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccRemediationConfigurationConfig(prefix, sseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), + Config: testAccRemediationConfigurationConfig_basic(prefix, sseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), Check: resource.ComposeTestCheckFunc( testAccCheckRemediationConfigurationExists(resourceName, &rc), acctest.CheckResourceDisappears(acctest.Provider, tfconfig.ResourceRemediationConfiguration(), resourceName), @@ -146,14 +146,14 @@ func testAccRemediationConfiguration_recreates(t *testing.T) { CheckDestroy: testAccCheckRemediationConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccRemediationConfigurationConfig(originalName, sseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), + Config: testAccRemediationConfigurationConfig_basic(originalName, sseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), Check: resource.ComposeTestCheckFunc( testAccCheckRemediationConfigurationExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "config_rule_name", fmt.Sprintf("%s-tf-acc-test-%d", originalName, rInt)), ), }, { - Config: testAccRemediationConfigurationConfig(updatedName, sseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), + Config: testAccRemediationConfigurationConfig_basic(updatedName, sseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), Check: resource.ComposeTestCheckFunc( testAccCheckRemediationConfigurationExists(resourceName, &updated), testAccCheckRemediationConfigurationRecreated(t, &original, &updated), @@ -191,7 +191,7 @@ func testAccRemediationConfiguration_updates(t *testing.T) { CheckDestroy: testAccCheckRemediationConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccRemediationConfigurationConfig(name, originalSseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), + Config: testAccRemediationConfigurationConfig_basic(name, originalSseAlgorithm, rInt, rAttempts, rSeconds, rExecPct, rErrorPct, automatic), Check: resource.ComposeTestCheckFunc( testAccCheckRemediationConfigurationExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "parameter.2.static_value", originalSseAlgorithm), @@ -206,7 +206,7 @@ func testAccRemediationConfiguration_updates(t *testing.T) { ), }, { - Config: testAccRemediationConfigurationConfig(name, updatedSseAlgorithm, rInt, uAttempts, uSeconds, uExecPct, uErrorPct, uAutomatic), + Config: testAccRemediationConfigurationConfig_basic(name, updatedSseAlgorithm, rInt, uAttempts, uSeconds, uExecPct, uErrorPct, uAutomatic), Check: resource.ComposeTestCheckFunc( testAccCheckRemediationConfigurationExists(resourceName, &updated), testAccCheckRemediationConfigurationNotRecreated(t, &original, &updated), @@ -277,7 +277,7 @@ func testAccCheckRemediationConfigurationDestroy(s *terraform.State) error { return nil } -func testAccRemediationConfigurationOlderSchemaConfig(namePrefix, sseAlgorithm string, randInt int) string { +func testAccRemediationConfigurationConfig_olderSchema(namePrefix, sseAlgorithm string, randInt int) string { return fmt.Sprintf(` resource "aws_config_remediation_configuration" "test" { config_rule_name = aws_config_config_rule.test.name @@ -362,7 +362,7 @@ EOF `, namePrefix, sseAlgorithm, randInt) } -func testAccRemediationConfigurationConfig(namePrefix, sseAlgorithm string, randInt int, randAttempts int, randSeconds int, randExecPct int, randErrorPct int, automatic string) string { +func testAccRemediationConfigurationConfig_basic(namePrefix, sseAlgorithm string, randInt int, randAttempts int, randSeconds int, randExecPct int, randErrorPct int, automatic string) string { return fmt.Sprintf(` resource "aws_config_remediation_configuration" "test" { config_rule_name = aws_config_config_rule.test.name diff --git a/internal/service/connect/bot_association.go b/internal/service/connect/bot_association.go index b9a2b0be9e8..d10d4568ac0 100644 --- a/internal/service/connect/bot_association.go +++ b/internal/service/connect/bot_association.go @@ -98,7 +98,7 @@ func resourceBotAssociationCreate(ctx context.Context, d *schema.ResourceData, m */ _, err := tfresource.RetryWhen( - connectBotAssociationCreateTimeout, + botAssociationCreateTimeout, func() (interface{}, error) { return conn.AssociateBotWithContext(ctx, input) }, diff --git a/internal/service/connect/bot_association_data_source_test.go b/internal/service/connect/bot_association_data_source_test.go index ed190cb7ae5..2b921d013a9 100644 --- a/internal/service/connect/bot_association_data_source_test.go +++ b/internal/service/connect/bot_association_data_source_test.go @@ -22,7 +22,7 @@ func TestAccConnectBotAssociationDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccBotAssociationDataSource_ConfigBasic(rName, rName2), + Config: testAccBotAssociationDataSourceConfig_basic(rName, rName2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "instance_id", resourceName, "instance_id"), resource.TestCheckResourceAttrPair(datasourceName, "lex_bot", resourceName, "lex_bot"), @@ -87,7 +87,7 @@ resource "aws_connect_bot_association" "test" { `, rName, rName2) } -func testAccBotAssociationDataSource_ConfigBasic(rName string, rName2 string) string { +func testAccBotAssociationDataSourceConfig_basic(rName string, rName2 string) string { return fmt.Sprintf(testAccBotAssociationDataSource_BaseConfig(rName, rName2) + ` data "aws_connect_bot_association" "test" { instance_id = aws_connect_instance.test.id diff --git a/internal/service/connect/bot_association_test.go b/internal/service/connect/bot_association_test.go index dc833e6b861..b37d1ecdf0e 100644 --- a/internal/service/connect/bot_association_test.go +++ b/internal/service/connect/bot_association_test.go @@ -42,7 +42,7 @@ func testAccBotAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckBotAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccBotV1AssociationConfigBasic(rName, rName2), + Config: testAccBotAssociationConfig_v1Basic(rName, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckBotAssociationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "instance_id"), @@ -73,7 +73,7 @@ func testAccBotAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckBotAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccBotV1AssociationConfigBasic(rName, rName2), + Config: testAccBotAssociationConfig_v1Basic(rName, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckBotAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceBotAssociation(), instanceResourceName), @@ -195,7 +195,7 @@ resource "aws_connect_instance" "test" { `, rName, rName2) } -func testAccBotV1AssociationConfigBasic(rName, rName2 string) string { +func testAccBotAssociationConfig_v1Basic(rName, rName2 string) string { return acctest.ConfigCompose( testAccBotV1AssociationConfigBase(rName, rName2), ` diff --git a/internal/service/connect/contact_flow.go b/internal/service/connect/contact_flow.go index 2c0e8e09725..3e607421b62 100644 --- a/internal/service/connect/contact_flow.go +++ b/internal/service/connect/contact_flow.go @@ -20,7 +20,7 @@ import ( "github.com/mitchellh/go-homedir" ) -const awsMutexConnectContactFlowKey = `aws_connect_contact_flow` +const contactFlowMutexKey = `aws_connect_contact_flow` func ResourceContactFlow() *schema.Resource { return &schema.Resource{ @@ -32,8 +32,8 @@ func ResourceContactFlow() *schema.Resource { StateContext: schema.ImportStatePassthroughContext, }, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(connectContactFlowCreateTimeout), - Update: schema.DefaultTimeout(connectContactFlowUpdateTimeout), + Create: schema.DefaultTimeout(contactFlowCreateTimeout), + Update: schema.DefaultTimeout(contactFlowUpdateTimeout), }, CustomizeDiff: verify.SetTagsDiff, Schema: map[string]*schema.Schema{ @@ -113,8 +113,8 @@ func resourceContactFlowCreate(ctx context.Context, d *schema.ResourceData, meta // Grab an exclusive lock so that we're only reading one contact flow into // memory at a time. // See https://github.com/hashicorp/terraform/issues/9364 - conns.GlobalMutexKV.Lock(awsMutexConnectContactFlowKey) - defer conns.GlobalMutexKV.Unlock(awsMutexConnectContactFlowKey) + conns.GlobalMutexKV.Lock(contactFlowMutexKey) + defer conns.GlobalMutexKV.Unlock(contactFlowMutexKey) file, err := resourceContactFlowLoadFileContent(filename) if err != nil { return diag.FromErr(fmt.Errorf("unable to load %q: %w", filename, err)) @@ -230,8 +230,8 @@ func resourceContactFlowUpdate(ctx context.Context, d *schema.ResourceData, meta // Grab an exclusive lock so that we're only reading one contact flow into // memory at a time. // See https://github.com/hashicorp/terraform/issues/9364 - conns.GlobalMutexKV.Lock(awsMutexConnectContactFlowKey) - defer conns.GlobalMutexKV.Unlock(awsMutexConnectContactFlowKey) + conns.GlobalMutexKV.Lock(contactFlowMutexKey) + defer conns.GlobalMutexKV.Unlock(contactFlowMutexKey) file, err := resourceContactFlowLoadFileContent(filename) if err != nil { return diag.FromErr(fmt.Errorf("unable to load %q: %w", filename, err)) diff --git a/internal/service/connect/contact_flow_data_source_test.go b/internal/service/connect/contact_flow_data_source_test.go index 141935bacdb..b8376b3c9cc 100644 --- a/internal/service/connect/contact_flow_data_source_test.go +++ b/internal/service/connect/contact_flow_data_source_test.go @@ -21,7 +21,7 @@ func TestAccConnectContactFlowDataSource_contactFlowID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccContactFlowDataSourceConfig_ContactFlowID(rName, resourceName), + Config: testAccContactFlowDataSourceConfig_id(rName, resourceName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), @@ -50,7 +50,7 @@ func TestAccConnectContactFlowDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccContactFlowDataSourceConfig_Name(rName, rName2), + Config: testAccContactFlowDataSourceConfig_name(rName, rName2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), @@ -91,7 +91,7 @@ resource "aws_connect_contact_flow" "test" { `, rName, rName2) } -func testAccContactFlowDataSourceConfig_ContactFlowID(rName, rName2 string) string { +func testAccContactFlowDataSourceConfig_id(rName, rName2 string) string { return fmt.Sprintf(testAccContactFlowBaseDataSourceConfig(rName, rName2) + ` data "aws_connect_contact_flow" "test" { instance_id = aws_connect_instance.test.id @@ -100,7 +100,7 @@ data "aws_connect_contact_flow" "test" { `) } -func testAccContactFlowDataSourceConfig_Name(rName, rName2 string) string { +func testAccContactFlowDataSourceConfig_name(rName, rName2 string) string { return fmt.Sprintf(testAccContactFlowBaseDataSourceConfig(rName, rName2) + ` data "aws_connect_contact_flow" "test" { instance_id = aws_connect_instance.test.id diff --git a/internal/service/connect/contact_flow_module.go b/internal/service/connect/contact_flow_module.go index 1dc9b14385d..f3badf9179a 100644 --- a/internal/service/connect/contact_flow_module.go +++ b/internal/service/connect/contact_flow_module.go @@ -20,7 +20,7 @@ import ( "github.com/mitchellh/go-homedir" ) -const awsMutexConnectContactFlowModuleKey = `aws_connect_contact_flow_module` +const contactFlowModuleMutexKey = `aws_connect_contact_flow_module` func ResourceContactFlowModule() *schema.Resource { return &schema.Resource{ @@ -104,8 +104,8 @@ func resourceContactFlowModuleCreate(ctx context.Context, d *schema.ResourceData // Grab an exclusive lock so that we're only reading one contact flow module into // memory at a time. // See https://github.com/hashicorp/terraform/issues/9364 - conns.GlobalMutexKV.Lock(awsMutexConnectContactFlowModuleKey) - defer conns.GlobalMutexKV.Unlock(awsMutexConnectContactFlowModuleKey) + conns.GlobalMutexKV.Lock(contactFlowModuleMutexKey) + defer conns.GlobalMutexKV.Unlock(contactFlowModuleMutexKey) file, err := resourceContactFlowModuleLoadFileContent(filename) if err != nil { return diag.FromErr(fmt.Errorf("unable to load %q: %w", filename, err)) @@ -220,8 +220,8 @@ func resourceContactFlowModuleUpdate(ctx context.Context, d *schema.ResourceData // Grab an exclusive lock so that we're only reading one contact flow module into // memory at a time. // See https://github.com/hashicorp/terraform/issues/9364 - conns.GlobalMutexKV.Lock(awsMutexConnectContactFlowModuleKey) - defer conns.GlobalMutexKV.Unlock(awsMutexConnectContactFlowModuleKey) + conns.GlobalMutexKV.Lock(contactFlowModuleMutexKey) + defer conns.GlobalMutexKV.Unlock(contactFlowModuleMutexKey) file, err := resourceContactFlowModuleLoadFileContent(filename) if err != nil { return diag.FromErr(fmt.Errorf("unable to load %q: %w", filename, err)) diff --git a/internal/service/connect/contact_flow_module_data_source_test.go b/internal/service/connect/contact_flow_module_data_source_test.go index ce9c19d09b8..7438318f032 100644 --- a/internal/service/connect/contact_flow_module_data_source_test.go +++ b/internal/service/connect/contact_flow_module_data_source_test.go @@ -21,7 +21,7 @@ func TestAccConnectContactFlowModuleDataSource_contactFlowModuleID(t *testing.T) ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccContactFlowModuleDataSourceConfig_ContactFlowModuleID(rName, resourceName), + Config: testAccContactFlowModuleDataSourceConfig_id(rName, resourceName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), @@ -51,7 +51,7 @@ func TestAccConnectContactFlowModuleDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccContactFlowModuleDataSourceConfig_Name(rName, rName2), + Config: testAccContactFlowModuleDataSourceConfig_name(rName, rName2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), @@ -93,7 +93,7 @@ resource "aws_connect_contact_flow_module" "test" { `, rName, rName2) } -func testAccContactFlowModuleDataSourceConfig_ContactFlowModuleID(rName, rName2 string) string { +func testAccContactFlowModuleDataSourceConfig_id(rName, rName2 string) string { return acctest.ConfigCompose( testAccContactFlowModuleBaseDataSourceConfig(rName, rName2), ` @@ -104,7 +104,7 @@ data "aws_connect_contact_flow_module" "test" { `) } -func testAccContactFlowModuleDataSourceConfig_Name(rName, rName2 string) string { +func testAccContactFlowModuleDataSourceConfig_name(rName, rName2 string) string { return acctest.ConfigCompose( testAccContactFlowModuleBaseDataSourceConfig(rName, rName2), ` diff --git a/internal/service/connect/contact_flow_test.go b/internal/service/connect/contact_flow_test.go index e6fc4841f7a..dd60944732a 100644 --- a/internal/service/connect/contact_flow_test.go +++ b/internal/service/connect/contact_flow_test.go @@ -44,7 +44,7 @@ func testAccContactFlow_basic(t *testing.T) { CheckDestroy: testAccCheckContactFlowDestroy, Steps: []resource.TestStep{ { - Config: testAccContactFlowBasicConfig(rName, rName2, "Created"), + Config: testAccContactFlowConfig_basic(rName, rName2, "Created"), Check: resource.ComposeTestCheckFunc( testAccCheckContactFlowExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -63,7 +63,7 @@ func testAccContactFlow_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccContactFlowBasicConfig(rName, rName2, "Updated"), + Config: testAccContactFlowConfig_basic(rName, rName2, "Updated"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckContactFlowExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -145,7 +145,7 @@ func testAccContactFlow_disappears(t *testing.T) { CheckDestroy: testAccCheckContactFlowDestroy, Steps: []resource.TestStep{ { - Config: testAccContactFlowBasicConfig(rName, rName2, "Disappear"), + Config: testAccContactFlowConfig_basic(rName, rName2, "Disappear"), Check: resource.ComposeTestCheckFunc( testAccCheckContactFlowExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceContactFlow(), resourceName), @@ -234,7 +234,7 @@ resource "aws_connect_instance" "test" { `, rName) } -func testAccContactFlowBasicConfig(rName, rName2, label string) string { +func testAccContactFlowConfig_basic(rName, rName2, label string) string { return acctest.ConfigCompose( testAccContactFlowBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/connect/find.go b/internal/service/connect/find.go index dd477f2a857..dd01a988027 100644 --- a/internal/service/connect/find.go +++ b/internal/service/connect/find.go @@ -61,7 +61,7 @@ func FindBotAssociationV1ByNameAndRegionWithContext(ctx context.Context, conn *c return result, nil } -func FindLambdaFunctionAssociationByArnWithContext(ctx context.Context, conn *connect.Connect, instanceID string, functionArn string) (string, error) { +func FindLambdaFunctionAssociationByARNWithContext(ctx context.Context, conn *connect.Connect, instanceID string, functionArn string) (string, error) { var result string input := &connect.ListLambdaFunctionsInput{ diff --git a/internal/service/connect/hours_of_operation_data_source_test.go b/internal/service/connect/hours_of_operation_data_source_test.go index 18c1feb64b2..73a37a742e9 100644 --- a/internal/service/connect/hours_of_operation_data_source_test.go +++ b/internal/service/connect/hours_of_operation_data_source_test.go @@ -21,7 +21,7 @@ func TestAccConnectHoursOfOperationDataSource_hoursOfOperationID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccHoursOfOperationDataSourceConfig_HoursOfOperationID(rName, resourceName), + Config: testAccHoursOfOperationDataSourceConfig_id(rName, resourceName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "hours_of_operation_arn", resourceName, "hours_of_operation_arn"), // Deprecated @@ -50,7 +50,7 @@ func TestAccConnectHoursOfOperationDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccHoursOfOperationDataSourceConfig_Name(rName, rName2), + Config: testAccHoursOfOperationDataSourceConfig_name(rName, rName2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "hours_of_operation_arn", resourceName, "hours_of_operation_arn"), // Deprecated @@ -117,7 +117,7 @@ resource "aws_connect_hours_of_operation" "test" { `, rName, rName2) } -func testAccHoursOfOperationDataSourceConfig_HoursOfOperationID(rName, rName2 string) string { +func testAccHoursOfOperationDataSourceConfig_id(rName, rName2 string) string { return fmt.Sprintf(testAccHoursOfOperationBaseDataSourceConfig(rName, rName2) + ` data "aws_connect_hours_of_operation" "test" { instance_id = aws_connect_instance.test.id @@ -126,7 +126,7 @@ data "aws_connect_hours_of_operation" "test" { `) } -func testAccHoursOfOperationDataSourceConfig_Name(rName, rName2 string) string { +func testAccHoursOfOperationDataSourceConfig_name(rName, rName2 string) string { return fmt.Sprintf(testAccHoursOfOperationBaseDataSourceConfig(rName, rName2) + ` data "aws_connect_hours_of_operation" "test" { instance_id = aws_connect_instance.test.id diff --git a/internal/service/connect/hours_of_operation_test.go b/internal/service/connect/hours_of_operation_test.go index 8d227843389..300c918b2cc 100644 --- a/internal/service/connect/hours_of_operation_test.go +++ b/internal/service/connect/hours_of_operation_test.go @@ -43,7 +43,7 @@ func testAccHoursOfOperation_basic(t *testing.T) { CheckDestroy: testAccCheckHoursOfOperationDestroy, Steps: []resource.TestStep{ { - Config: testAccHoursOfOperationBasicConfig(rName, rName2, "Created"), + Config: testAccHoursOfOperationConfig_basic(rName, rName2, "Created"), Check: resource.ComposeTestCheckFunc( testAccCheckHoursOfOperationExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -65,7 +65,7 @@ func testAccHoursOfOperation_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccHoursOfOperationBasicConfig(rName, rName2, "Updated"), + Config: testAccHoursOfOperationConfig_basic(rName, rName2, "Updated"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckHoursOfOperationExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -98,7 +98,7 @@ func testAccHoursOfOperation_disappears(t *testing.T) { CheckDestroy: testAccCheckHoursOfOperationDestroy, Steps: []resource.TestStep{ { - Config: testAccHoursOfOperationBasicConfig(rName, rName2, "Disappear"), + Config: testAccHoursOfOperationConfig_basic(rName, rName2, "Disappear"), Check: resource.ComposeTestCheckFunc( testAccCheckHoursOfOperationExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceHoursOfOperation(), resourceName), @@ -187,7 +187,7 @@ resource "aws_connect_instance" "test" { `, rName) } -func testAccHoursOfOperationBasicConfig(rName, rName2, label string) string { +func testAccHoursOfOperationConfig_basic(rName, rName2, label string) string { return acctest.ConfigCompose( testAccHoursOfOperationBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/connect/instance.go b/internal/service/connect/instance.go index 00a4e880ff5..e2dad709327 100644 --- a/internal/service/connect/instance.go +++ b/internal/service/connect/instance.go @@ -28,8 +28,8 @@ func ResourceInstance() *schema.Resource { StateContext: schema.ImportStatePassthroughContext, }, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(connectInstanceCreatedTimeout), - Delete: schema.DefaultTimeout(connectInstanceDeletedTimeout), + Create: schema.DefaultTimeout(instanceCreatedTimeout), + Delete: schema.DefaultTimeout(instanceDeletedTimeout), }, Schema: map[string]*schema.Schema{ "arn": { diff --git a/internal/service/connect/instance_data_source_test.go b/internal/service/connect/instance_data_source_test.go index 1e4ed16b1f3..a194cbebae2 100644 --- a/internal/service/connect/instance_data_source_test.go +++ b/internal/service/connect/instance_data_source_test.go @@ -29,7 +29,7 @@ func TestAccConnectInstanceDataSource_basic(t *testing.T) { ExpectError: regexp.MustCompile(`error finding Connect Instance Summary by instance_alias`), }, { - Config: testAccInstanceBasicDataSourceConfig(rName), + Config: testAccInstanceDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "created_time", dataSourceName, "created_time"), @@ -46,7 +46,7 @@ func TestAccConnectInstanceDataSource_basic(t *testing.T) { ), }, { - Config: testAccInstanceAliasDataSourceConfig(rName), + Config: testAccInstanceDataSourceConfig_alias(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "created_time", dataSourceName, "created_time"), @@ -78,7 +78,7 @@ data "aws_connect_instance" "test" { } ` -func testAccInstanceBasicDataSourceConfig(rName string) string { +func testAccInstanceDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_connect_instance" "test" { instance_alias = %[1]q @@ -93,7 +93,7 @@ data "aws_connect_instance" "test" { `, rName) } -func testAccInstanceAliasDataSourceConfig(rName string) string { +func testAccInstanceDataSourceConfig_alias(rName string) string { return fmt.Sprintf(` resource "aws_connect_instance" "test" { instance_alias = %[1]q diff --git a/internal/service/connect/instance_test.go b/internal/service/connect/instance_test.go index 8df552b043f..dc3f8b68cf6 100644 --- a/internal/service/connect/instance_test.go +++ b/internal/service/connect/instance_test.go @@ -43,7 +43,7 @@ func testAccInstance_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceBasicConfig(rName), + Config: testAccInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "connect", regexp.MustCompile(`instance/.+`)), @@ -66,7 +66,7 @@ func testAccInstance_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccInstanceBasicFlippedConfig(rName), + Config: testAccInstanceConfig_basicFlipped(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "connect", regexp.MustCompile(`instance/.+`)), @@ -99,7 +99,7 @@ func testAccInstance_directory(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceDirectoryConfig(rName, domainName), + Config: testAccInstanceConfig_directory(rName, domainName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "identity_management_type", connect.DirectoryTypeExistingDirectory), @@ -128,7 +128,7 @@ func testAccInstance_saml(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceSAMLConfig(rName), + Config: testAccInstanceConfig_saml(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "identity_management_type", connect.DirectoryTypeSaml), testAccCheckInstanceExists(resourceName, &v), @@ -202,7 +202,7 @@ func testAccCheckInstanceDestroy(s *terraform.State) error { return nil } -func testAccInstanceBasicConfig(rName string) string { +func testAccInstanceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_connect_instance" "test" { identity_management_type = "CONNECT_MANAGED" @@ -213,7 +213,7 @@ resource "aws_connect_instance" "test" { `, rName) } -func testAccInstanceBasicFlippedConfig(rName string) string { +func testAccInstanceConfig_basicFlipped(rName string) string { return fmt.Sprintf(` resource "aws_connect_instance" "test" { auto_resolve_best_voices_enabled = false @@ -228,7 +228,7 @@ resource "aws_connect_instance" "test" { `, rName) } -func testAccInstanceDirectoryConfig(rName, domain string) string { +func testAccInstanceConfig_directory(rName, domain string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -285,7 +285,7 @@ resource "aws_connect_instance" "test" { `, rName, domain) } -func testAccInstanceSAMLConfig(rName string) string { +func testAccInstanceConfig_saml(rName string) string { return fmt.Sprintf(` resource "aws_connect_instance" "test" { identity_management_type = "SAML" diff --git a/internal/service/connect/lambda_function_association.go b/internal/service/connect/lambda_function_association.go index f55e42b4290..f78815891ee 100644 --- a/internal/service/connect/lambda_function_association.go +++ b/internal/service/connect/lambda_function_association.go @@ -69,7 +69,7 @@ func resourceLambdaFunctionAssociationRead(ctx context.Context, d *schema.Resour return diag.FromErr(err) } - lfaArn, err := FindLambdaFunctionAssociationByArnWithContext(ctx, conn, instanceID, functionArn) + lfaArn, err := FindLambdaFunctionAssociationByARNWithContext(ctx, conn, instanceID, functionArn) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Connect Lambda Function Association (%s) not found, removing from state", d.Id()) diff --git a/internal/service/connect/lambda_function_association_data_source.go b/internal/service/connect/lambda_function_association_data_source.go index 6f0083ba37b..e04d4426146 100644 --- a/internal/service/connect/lambda_function_association_data_source.go +++ b/internal/service/connect/lambda_function_association_data_source.go @@ -32,7 +32,7 @@ func dataSourceLambdaFunctionAssociationRead(ctx context.Context, d *schema.Reso functionArn := d.Get("function_arn") instanceID := d.Get("instance_id") - lfaArn, err := FindLambdaFunctionAssociationByArnWithContext(ctx, conn, instanceID.(string), functionArn.(string)) + lfaArn, err := FindLambdaFunctionAssociationByARNWithContext(ctx, conn, instanceID.(string), functionArn.(string)) if err != nil { return diag.FromErr(fmt.Errorf("error finding Connect Lambda Function Association by ARN (%s): %w", functionArn, err)) } diff --git a/internal/service/connect/lambda_function_association_data_source_test.go b/internal/service/connect/lambda_function_association_data_source_test.go index d6fc9bb42c7..e1f92bdac3e 100644 --- a/internal/service/connect/lambda_function_association_data_source_test.go +++ b/internal/service/connect/lambda_function_association_data_source_test.go @@ -22,7 +22,7 @@ func TestAccConnectLambdaFunctionAssociationDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLambdaFunctionAssociationDataSource_ConfigBasic(rName, rName2), + Config: testAccLambdaFunctionAssociationDataSourceConfig_basic(rName, rName2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "instance_id", resourceName, "instance_id"), resource.TestCheckResourceAttrPair(datasourceName, "function_arn", resourceName, "function_arn"), @@ -78,7 +78,7 @@ resource "aws_connect_lambda_function_association" "test" { `, rName, rName2) } -func testAccLambdaFunctionAssociationDataSource_ConfigBasic(rName string, rName2 string) string { +func testAccLambdaFunctionAssociationDataSourceConfig_basic(rName string, rName2 string) string { return fmt.Sprintf(testAccLambdaFunctionAssociationDataSource_BaseConfig(rName, rName2) + ` data "aws_connect_lambda_function_association" "test" { function_arn = aws_connect_lambda_function_association.test.function_arn diff --git a/internal/service/connect/lambda_function_association_test.go b/internal/service/connect/lambda_function_association_test.go index 24d4464cbaf..bace6f7e3b9 100644 --- a/internal/service/connect/lambda_function_association_test.go +++ b/internal/service/connect/lambda_function_association_test.go @@ -42,7 +42,7 @@ func testAccLambdaFunctionAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckLambdaFunctionAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccLambdaFunctionAssociationConfigBasic(rName, rName2), + Config: testAccLambdaFunctionAssociationConfig_basic(rName, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckLambdaFunctionAssociationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "instance_id"), @@ -70,7 +70,7 @@ func testAccLambdaFunctionAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckLambdaFunctionAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccLambdaFunctionAssociationConfigBasic(rName, rName2), + Config: testAccLambdaFunctionAssociationConfig_basic(rName, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckLambdaFunctionAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceLambdaFunctionAssociation(), resourceName), @@ -94,7 +94,7 @@ func testAccCheckLambdaFunctionAssociationDestroy(s *terraform.State) error { return err } - lfaArn, err := tfconnect.FindLambdaFunctionAssociationByArnWithContext(context.Background(), conn, instanceID, functionArn) + lfaArn, err := tfconnect.FindLambdaFunctionAssociationByARNWithContext(context.Background(), conn, instanceID, functionArn) if tfawserr.ErrCodeEquals(err, connect.ErrCodeResourceNotFoundException) { continue @@ -130,7 +130,7 @@ func testAccCheckLambdaFunctionAssociationExists(resourceName string) resource.T conn := acctest.Provider.Meta().(*conns.AWSClient).ConnectConn - lfaArn, err := tfconnect.FindLambdaFunctionAssociationByArnWithContext(context.Background(), conn, instanceID, functionArn) + lfaArn, err := tfconnect.FindLambdaFunctionAssociationByARNWithContext(context.Background(), conn, instanceID, functionArn) if err != nil { return fmt.Errorf("error finding Connect Lambda Function Association by Function Arn (%s): %w", functionArn, err) @@ -185,7 +185,7 @@ resource "aws_connect_instance" "test" { `, rName, rName2) } -func testAccLambdaFunctionAssociationConfigBasic(rName string, rName2 string) string { +func testAccLambdaFunctionAssociationConfig_basic(rName string, rName2 string) string { return acctest.ConfigCompose( testAccLambdaFunctionAssociationConfigBase(rName, rName2), ` resource "aws_connect_lambda_function_association" "test" { diff --git a/internal/service/connect/prompt_data_source_test.go b/internal/service/connect/prompt_data_source_test.go index ba1d658ed56..3edddd2924a 100644 --- a/internal/service/connect/prompt_data_source_test.go +++ b/internal/service/connect/prompt_data_source_test.go @@ -20,7 +20,7 @@ func TestAccConnectPromptDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPromptDataSourceConfig_Name(rName), + Config: testAccPromptDataSourceConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet(datasourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "instance_id", "aws_connect_instance.test", "id"), @@ -43,7 +43,7 @@ resource "aws_connect_instance" "test" { `, rName) } -func testAccPromptDataSourceConfig_Name(rName string) string { +func testAccPromptDataSourceConfig_name(rName string) string { return acctest.ConfigCompose( testAccPromptBaseDataSourceConfig(rName), ` diff --git a/internal/service/connect/queue_data_source_test.go b/internal/service/connect/queue_data_source_test.go index dabd3c3dfbf..dcd4a58c9fc 100644 --- a/internal/service/connect/queue_data_source_test.go +++ b/internal/service/connect/queue_data_source_test.go @@ -22,7 +22,7 @@ func TestAccConnectQueueDataSource_queueID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccQueueDataSourceConfig_QueueID(rName, resourceName, outboundCallerConfigName), + Config: testAccQueueDataSourceConfig_id(rName, resourceName, outboundCallerConfigName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), @@ -54,7 +54,7 @@ func TestAccConnectQueueDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccQueueDataSourceConfig_Name(rName, rName2, outboundCallerConfigName), + Config: testAccQueueDataSourceConfig_name(rName, rName2, outboundCallerConfigName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), @@ -104,7 +104,7 @@ resource "aws_connect_queue" "test" { `, rName, rName2, outboundCallerConfigName) } -func testAccQueueDataSourceConfig_QueueID(rName, rName2, outboundCallerConfigName string) string { +func testAccQueueDataSourceConfig_id(rName, rName2, outboundCallerConfigName string) string { return acctest.ConfigCompose( testAccQueueBaseDataSourceConfig(rName, rName2, outboundCallerConfigName), ` @@ -115,7 +115,7 @@ data "aws_connect_queue" "test" { `) } -func testAccQueueDataSourceConfig_Name(rName, rName2, outboundCallerConfigName string) string { +func testAccQueueDataSourceConfig_name(rName, rName2, outboundCallerConfigName string) string { return acctest.ConfigCompose( testAccQueueBaseDataSourceConfig(rName, rName2, outboundCallerConfigName), ` diff --git a/internal/service/connect/queue_test.go b/internal/service/connect/queue_test.go index a5b21f5940c..0fe6e3326c1 100644 --- a/internal/service/connect/queue_test.go +++ b/internal/service/connect/queue_test.go @@ -50,7 +50,7 @@ func testAccQueue_basic(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueBasicConfig(rName, rName2, originalDescription), + Config: testAccQueueConfig_basic(rName, rName2, originalDescription), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -70,7 +70,7 @@ func testAccQueue_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccQueueBasicConfig(rName, rName2, updatedDescription), + Config: testAccQueueConfig_basic(rName, rName2, updatedDescription), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -102,7 +102,7 @@ func testAccQueue_disappears(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueBasicConfig(rName, rName2, "Disappear"), + Config: testAccQueueConfig_basic(rName, rName2, "Disappear"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceQueue(), resourceName), @@ -126,7 +126,7 @@ func testAccQueue_updateHoursOfOperationId(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueHoursOfOperationConfig(rName, rName2, "first"), + Config: testAccQueueConfig_hoursOfOperation(rName, rName2, "first"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -146,7 +146,7 @@ func testAccQueue_updateHoursOfOperationId(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccQueueHoursOfOperationConfig(rName, rName2, "second"), + Config: testAccQueueConfig_hoursOfOperation(rName, rName2, "second"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -166,7 +166,7 @@ func testAccQueue_updateHoursOfOperationId(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccQueueHoursOfOperationConfig(rName, rName2, "first"), + Config: testAccQueueConfig_hoursOfOperation(rName, rName2, "first"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -200,7 +200,7 @@ func testAccQueue_updateMaxContacts(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueMaxContactsConfig(rName, rName2, originalMaxContacts), + Config: testAccQueueConfig_maxContacts(rName, rName2, originalMaxContacts), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -221,7 +221,7 @@ func testAccQueue_updateMaxContacts(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccQueueMaxContactsConfig(rName, rName2, updatedMaxContacts), + Config: testAccQueueConfig_maxContacts(rName, rName2, updatedMaxContacts), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -255,7 +255,7 @@ func testAccQueue_updateOutboundCallerConfig(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueOutboundCallerConfig(rName, rName2, originalOutboundCallerIdName), + Config: testAccQueueConfig_outboundCaller(rName, rName2, originalOutboundCallerIdName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -277,7 +277,7 @@ func testAccQueue_updateOutboundCallerConfig(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccQueueOutboundCallerConfig(rName, rName2, updatedOutboundCallerIdName), + Config: testAccQueueConfig_outboundCaller(rName, rName2, updatedOutboundCallerIdName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -312,7 +312,7 @@ func testAccQueue_updateStatus(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueStatusConfig(rName, rName2, originalStatus), + Config: testAccQueueConfig_status(rName, rName2, originalStatus), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -332,7 +332,7 @@ func testAccQueue_updateStatus(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccQueueStatusConfig(rName, rName2, updatedStatus), + Config: testAccQueueConfig_status(rName, rName2, updatedStatus), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -367,7 +367,7 @@ func testAccQueue_updateQuickConnectIds(t *testing.T) { Steps: []resource.TestStep{ { // start with no quick connects associated with the queue - Config: testAccQueueBasicConfig(rName, rName4, description), + Config: testAccQueueConfig_basic(rName, rName4, description), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -388,7 +388,7 @@ func testAccQueue_updateQuickConnectIds(t *testing.T) { }, { // associate one quick connect to the queue - Config: testAccQueueQuickConnectConfig1(rName, rName2, rName3, rName4, description), + Config: testAccQueueConfig_quickConnect1(rName, rName2, rName3, rName4, description), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -410,7 +410,7 @@ func testAccQueue_updateQuickConnectIds(t *testing.T) { }, { // associate two quick connects to the queue - Config: testAccQueueQuickConnectConfig2(rName, rName2, rName3, rName4, description), + Config: testAccQueueConfig_quickConnect2(rName, rName2, rName3, rName4, description), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -431,7 +431,7 @@ func testAccQueue_updateQuickConnectIds(t *testing.T) { }, { // remove one quick connect - Config: testAccQueueQuickConnectConfig1(rName, rName2, rName3, rName4, description), + Config: testAccQueueConfig_quickConnect1(rName, rName2, rName3, rName4, description), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -540,7 +540,7 @@ data "aws_connect_hours_of_operation" "test" { `, rName) } -func testAccQueueBasicConfig(rName, rName2, label string) string { +func testAccQueueConfig_basic(rName, rName2, label string) string { return acctest.ConfigCompose( testAccQueueBaseConfig(rName), fmt.Sprintf(` @@ -557,7 +557,7 @@ resource "aws_connect_queue" "test" { `, rName2, label)) } -func testAccQueueHoursOfOperationConfig(rName, rName2, selectHoursOfOperationId string) string { +func testAccQueueConfig_hoursOfOperation(rName, rName2, selectHoursOfOperationId string) string { return acctest.ConfigCompose( testAccQueueBaseConfig(rName), fmt.Sprintf(` @@ -600,7 +600,7 @@ resource "aws_connect_queue" "test" { } //lint:ignore U1000 Ignore unused function temporarily -func testAccQueueMaxContactsConfig(rName, rName2, maxContacts string) string { +func testAccQueueConfig_maxContacts(rName, rName2, maxContacts string) string { return acctest.ConfigCompose( testAccQueueBaseConfig(rName), fmt.Sprintf(` @@ -618,7 +618,7 @@ resource "aws_connect_queue" "test" { `, rName2, maxContacts)) } -func testAccQueueOutboundCallerConfig(rName, rName2, OutboundCallerIdName string) string { +func testAccQueueConfig_outboundCaller(rName, rName2, OutboundCallerIdName string) string { return acctest.ConfigCompose( testAccQueueBaseConfig(rName), fmt.Sprintf(` @@ -639,7 +639,7 @@ resource "aws_connect_queue" "test" { `, rName2, OutboundCallerIdName)) } -func testAccQueueStatusConfig(rName, rName2, status string) string { +func testAccQueueConfig_status(rName, rName2, status string) string { return acctest.ConfigCompose( testAccQueueBaseConfig(rName), fmt.Sprintf(` @@ -697,7 +697,7 @@ resource "aws_connect_quick_connect" "test2" { `, rName, rName2) } -func testAccQueueQuickConnectConfig1(rName, rName2, rName3, rName4, label string) string { +func testAccQueueConfig_quickConnect1(rName, rName2, rName3, rName4, label string) string { return acctest.ConfigCompose( testAccQueueBaseConfig(rName), testAccQueueQuickConnectBaseConfig(rName2, rName3), @@ -719,7 +719,7 @@ resource "aws_connect_queue" "test" { `, rName4, label)) } -func testAccQueueQuickConnectConfig2(rName, rName2, rName3, rName4, label string) string { +func testAccQueueConfig_quickConnect2(rName, rName2, rName3, rName4, label string) string { return acctest.ConfigCompose( testAccQueueBaseConfig(rName), testAccQueueQuickConnectBaseConfig(rName2, rName3), diff --git a/internal/service/connect/quick_connect_data_source_test.go b/internal/service/connect/quick_connect_data_source_test.go index 4befbc71336..775212f133d 100644 --- a/internal/service/connect/quick_connect_data_source_test.go +++ b/internal/service/connect/quick_connect_data_source_test.go @@ -53,7 +53,7 @@ func TestAccConnectQuickConnectDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccQuickConnectDataSourceConfig_Name(rName, rName2, phoneNumber), + Config: testAccQuickConnectDataSourceConfig_name(rName, rName2, phoneNumber), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), @@ -71,7 +71,7 @@ func TestAccConnectQuickConnectDataSource_name(t *testing.T) { }) } -func testAccQuickConnectBaseDataSourceConfig(rName, rName2, phoneNumber string) string { +func testAccQuickConnectDataSourceConfig_base(rName, rName2, phoneNumber string) string { return fmt.Sprintf(` resource "aws_connect_instance" "test" { identity_management_type = "CONNECT_MANAGED" @@ -102,7 +102,7 @@ resource "aws_connect_quick_connect" "test" { func testAccQuickConnectDataSourceConfig_id(rName, rName2, phoneNumber string) string { return acctest.ConfigCompose( - testAccQuickConnectBaseDataSourceConfig(rName, rName2, phoneNumber), + testAccQuickConnectDataSourceConfig_base(rName, rName2, phoneNumber), ` data "aws_connect_quick_connect" "test" { instance_id = aws_connect_instance.test.id @@ -111,9 +111,9 @@ data "aws_connect_quick_connect" "test" { `) } -func testAccQuickConnectDataSourceConfig_Name(rName, rName2, phoneNumber string) string { +func testAccQuickConnectDataSourceConfig_name(rName, rName2, phoneNumber string) string { return acctest.ConfigCompose( - testAccQuickConnectBaseDataSourceConfig(rName, rName2, phoneNumber), + testAccQuickConnectDataSourceConfig_base(rName, rName2, phoneNumber), ` data "aws_connect_quick_connect" "test" { instance_id = aws_connect_instance.test.id diff --git a/internal/service/connect/quick_connect_test.go b/internal/service/connect/quick_connect_test.go index 6f2ef144d83..87ba1f11add 100644 --- a/internal/service/connect/quick_connect_test.go +++ b/internal/service/connect/quick_connect_test.go @@ -43,7 +43,7 @@ func testAccQuickConnect_phoneNumber(t *testing.T) { CheckDestroy: testAccCheckQuickConnectDestroy, Steps: []resource.TestStep{ { - Config: testAccQuickConnectPhoneNumberConfig(rName, rName2, "Created", "+12345678912"), + Config: testAccQuickConnectConfig_phoneNumber(rName, rName2, "Created", "+12345678912"), Check: resource.ComposeTestCheckFunc( testAccCheckQuickConnectExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "instance_id"), @@ -66,7 +66,7 @@ func testAccQuickConnect_phoneNumber(t *testing.T) { }, { // update description - Config: testAccQuickConnectPhoneNumberConfig(rName, rName2, "Updated", "+12345678912"), + Config: testAccQuickConnectConfig_phoneNumber(rName, rName2, "Updated", "+12345678912"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQuickConnectExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "instance_id"), @@ -89,7 +89,7 @@ func testAccQuickConnect_phoneNumber(t *testing.T) { }, { // update phone number - Config: testAccQuickConnectPhoneNumberConfig(rName, rName2, "Updated", "+12345678913"), + Config: testAccQuickConnectConfig_phoneNumber(rName, rName2, "Updated", "+12345678913"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQuickConnectExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "instance_id"), @@ -122,7 +122,7 @@ func testAccQuickConnect_disappears(t *testing.T) { CheckDestroy: testAccCheckQuickConnectDestroy, Steps: []resource.TestStep{ { - Config: testAccQuickConnectPhoneNumberConfig(rName, rName2, "Disappear", "+12345678912"), + Config: testAccQuickConnectConfig_phoneNumber(rName, rName2, "Disappear", "+12345678912"), Check: resource.ComposeTestCheckFunc( testAccCheckQuickConnectExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceQuickConnect(), resourceName), @@ -211,7 +211,7 @@ resource "aws_connect_instance" "test" { `, rName) } -func testAccQuickConnectPhoneNumberConfig(rName, rName2, label string, phoneNumber string) string { +func testAccQuickConnectConfig_phoneNumber(rName, rName2, label string, phoneNumber string) string { return acctest.ConfigCompose( testAccQuickConnectBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/connect/routing_profile_data_source.go b/internal/service/connect/routing_profile_data_source.go index 519b8070e35..ef2bc2e7567 100644 --- a/internal/service/connect/routing_profile_data_source.go +++ b/internal/service/connect/routing_profile_data_source.go @@ -113,7 +113,7 @@ func dataSourceRoutingProfileRead(ctx context.Context, d *schema.ResourceData, m input.RoutingProfileId = aws.String(v.(string)) } else if v, ok := d.GetOk("name"); ok { name := v.(string) - routingProfileSummary, err := dataSourceGetConnectRoutingProfileSummaryByName(ctx, conn, instanceID, name) + routingProfileSummary, err := dataSourceGetRoutingProfileSummaryByName(ctx, conn, instanceID, name) if err != nil { return diag.FromErr(fmt.Errorf("error finding Connect Routing Profile Summary by name (%s): %w", name, err)) @@ -167,7 +167,7 @@ func dataSourceRoutingProfileRead(ctx context.Context, d *schema.ResourceData, m return nil } -func dataSourceGetConnectRoutingProfileSummaryByName(ctx context.Context, conn *connect.Connect, instanceID, name string) (*connect.RoutingProfileSummary, error) { +func dataSourceGetRoutingProfileSummaryByName(ctx context.Context, conn *connect.Connect, instanceID, name string) (*connect.RoutingProfileSummary, error) { var result *connect.RoutingProfileSummary input := &connect.ListRoutingProfilesInput{ diff --git a/internal/service/connect/routing_profile_data_source_test.go b/internal/service/connect/routing_profile_data_source_test.go index 53882a38678..8ce42eb9295 100644 --- a/internal/service/connect/routing_profile_data_source_test.go +++ b/internal/service/connect/routing_profile_data_source_test.go @@ -24,7 +24,7 @@ func TestAccConnectRoutingProfileDataSource_routingProfileID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRoutingProfileDataSourceConfig_RoutingProfileID(rName, rName2, rName3, rName4), + Config: testAccRoutingProfileDataSourceConfig_id(rName, rName2, rName3, rName4), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "default_outbound_queue_id", resourceName, "default_outbound_queue_id"), @@ -76,7 +76,7 @@ func TestAccConnectRoutingProfileDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRoutingProfileDataSourceConfig_Name(rName, rName2, rName3, rName4), + Config: testAccRoutingProfileDataSourceConfig_name(rName, rName2, rName3, rName4), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "default_outbound_queue_id", resourceName, "default_outbound_queue_id"), @@ -179,7 +179,7 @@ resource "aws_connect_routing_profile" "test" { `, rName, rName2, rName3, rName4) } -func testAccRoutingProfileDataSourceConfig_RoutingProfileID(rName, rName2, rName3, rName4 string) string { +func testAccRoutingProfileDataSourceConfig_id(rName, rName2, rName3, rName4 string) string { return acctest.ConfigCompose( testAccRoutingProfileBaseDataSourceConfig(rName, rName2, rName3, rName4), ` @@ -190,7 +190,7 @@ data "aws_connect_routing_profile" "test" { `) } -func testAccRoutingProfileDataSourceConfig_Name(rName, rName2, rName3, rName4 string) string { +func testAccRoutingProfileDataSourceConfig_name(rName, rName2, rName3, rName4 string) string { return acctest.ConfigCompose( testAccRoutingProfileBaseDataSourceConfig(rName, rName2, rName3, rName4), ` diff --git a/internal/service/connect/routing_profile_test.go b/internal/service/connect/routing_profile_test.go index 632ea3dfafb..21b3b8b20d6 100644 --- a/internal/service/connect/routing_profile_test.go +++ b/internal/service/connect/routing_profile_test.go @@ -49,7 +49,7 @@ func testAccRoutingProfile_basic(t *testing.T) { CheckDestroy: testAccCheckRoutingProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingProfileBasicConfig(rName, rName2, rName3, originalDescription), + Config: testAccRoutingProfileConfig_basic(rName, rName2, rName3, originalDescription), Check: resource.ComposeTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -70,7 +70,7 @@ func testAccRoutingProfile_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRoutingProfileBasicConfig(rName, rName2, rName3, updatedDescription), + Config: testAccRoutingProfileConfig_basic(rName, rName2, rName3, updatedDescription), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -104,7 +104,7 @@ func testAccRoutingProfile_disappears(t *testing.T) { CheckDestroy: testAccCheckRoutingProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingProfileBasicConfig(rName, rName2, rName3, "Disappear"), + Config: testAccRoutingProfileConfig_basic(rName, rName2, rName3, "Disappear"), Check: resource.ComposeTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceRoutingProfile(), resourceName), @@ -130,7 +130,7 @@ func testAccRoutingProfile_updateConcurrency(t *testing.T) { CheckDestroy: testAccCheckRoutingProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingProfileBasicConfig(rName, rName2, rName3, description), + Config: testAccRoutingProfileConfig_basic(rName, rName2, rName3, description), Check: resource.ComposeTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -151,7 +151,7 @@ func testAccRoutingProfile_updateConcurrency(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRoutingProfileMediaConcurrenciesConfig(rName, rName2, rName3, description), + Config: testAccRoutingProfileConfig_mediaConcurrencies(rName, rName2, rName3, description), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -183,7 +183,7 @@ func testAccRoutingProfile_updateDefaultOutboundQueue(t *testing.T) { CheckDestroy: testAccCheckRoutingProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingProfileDefaultOutboundQueueConfig(rName, rName2, rName3, rName4, "first"), + Config: testAccRoutingProfileConfig_defaultOutboundQueue(rName, rName2, rName3, rName4, "first"), Check: resource.ComposeTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -204,7 +204,7 @@ func testAccRoutingProfile_updateDefaultOutboundQueue(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRoutingProfileDefaultOutboundQueueConfig(rName, rName2, rName3, rName4, "second"), + Config: testAccRoutingProfileConfig_defaultOutboundQueue(rName, rName2, rName3, rName4, "second"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -240,7 +240,7 @@ func testAccRoutingProfile_updateQueues(t *testing.T) { Steps: []resource.TestStep{ { // Routing profile without queue_configs - Config: testAccRoutingProfileBasicConfig(rName, rName2, rName3, description), + Config: testAccRoutingProfileConfig_basic(rName, rName2, rName3, description), Check: resource.ComposeTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -263,7 +263,7 @@ func testAccRoutingProfile_updateQueues(t *testing.T) { }, { // Routing profile with one queue_configs - Config: testAccRoutingProfileQueueConfig1(rName, rName2, rName3, description), + Config: testAccRoutingProfileConfig_queue1(rName, rName2, rName3, description), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -292,7 +292,7 @@ func testAccRoutingProfile_updateQueues(t *testing.T) { }, { // Routing profile with two queue_configs (one new config and one edited config) - Config: testAccRoutingProfileQueueConfig2(rName, rName2, rName3, rName4, description), + Config: testAccRoutingProfileConfig_queue2(rName, rName2, rName3, rName4, description), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -318,7 +318,7 @@ func testAccRoutingProfile_updateQueues(t *testing.T) { }, { // Routing profile with one queue_configs (remove the created queue config) - Config: testAccRoutingProfileQueueConfig1(rName, rName2, rName3, description), + Config: testAccRoutingProfileConfig_queue1(rName, rName2, rName3, description), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckRoutingProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -434,7 +434,7 @@ resource "aws_connect_queue" "default_outbound_queue" { `, rName, rName2) } -func testAccRoutingProfileBasicConfig(rName, rName2, rName3, label string) string { +func testAccRoutingProfileConfig_basic(rName, rName2, rName3, label string) string { return acctest.ConfigCompose( testAccRoutingProfileBaseConfig(rName, rName2), fmt.Sprintf(` @@ -456,7 +456,7 @@ resource "aws_connect_routing_profile" "test" { `, rName3, label)) } -func testAccRoutingProfileMediaConcurrenciesConfig(rName, rName2, rName3, label string) string { +func testAccRoutingProfileConfig_mediaConcurrencies(rName, rName2, rName3, label string) string { return acctest.ConfigCompose( testAccRoutingProfileBaseConfig(rName, rName2), fmt.Sprintf(` @@ -483,7 +483,7 @@ resource "aws_connect_routing_profile" "test" { `, rName3, label)) } -func testAccRoutingProfileDefaultOutboundQueueConfig(rName, rName2, rName3, rName4, selectDefaultOutboundQueue string) string { +func testAccRoutingProfileConfig_defaultOutboundQueue(rName, rName2, rName3, rName4, selectDefaultOutboundQueue string) string { return acctest.ConfigCompose( testAccRoutingProfileBaseConfig(rName, rName2), fmt.Sprintf(` @@ -516,7 +516,7 @@ resource "aws_connect_routing_profile" "test" { `, rName3, rName4, selectDefaultOutboundQueue)) } -func testAccRoutingProfileQueueConfig1(rName, rName2, rName3, label string) string { +func testAccRoutingProfileConfig_queue1(rName, rName2, rName3, label string) string { return acctest.ConfigCompose( testAccRoutingProfileBaseConfig(rName, rName2), fmt.Sprintf(` @@ -545,7 +545,7 @@ resource "aws_connect_routing_profile" "test" { `, rName3, label)) } -func testAccRoutingProfileQueueConfig2(rName, rName2, rName3, rName4, label string) string { +func testAccRoutingProfileConfig_queue2(rName, rName2, rName3, rName4, label string) string { return acctest.ConfigCompose( testAccRoutingProfileBaseConfig(rName, rName2), fmt.Sprintf(` diff --git a/internal/service/connect/security_profile_data_source.go b/internal/service/connect/security_profile_data_source.go index 377f33952fa..281b5e32b9d 100644 --- a/internal/service/connect/security_profile_data_source.go +++ b/internal/service/connect/security_profile_data_source.go @@ -73,7 +73,7 @@ func dataSourceSecurityProfileRead(ctx context.Context, d *schema.ResourceData, input.SecurityProfileId = aws.String(v.(string)) } else if v, ok := d.GetOk("name"); ok { name := v.(string) - securityProfileSummary, err := dataSourceGetConnectSecurityProfileSummaryByName(ctx, conn, instanceID, name) + securityProfileSummary, err := dataSourceGetSecurityProfileSummaryByName(ctx, conn, instanceID, name) if err != nil { return diag.FromErr(fmt.Errorf("error finding Connect Security Profile Summary by name (%s): %w", name, err)) @@ -125,7 +125,7 @@ func dataSourceSecurityProfileRead(ctx context.Context, d *schema.ResourceData, return nil } -func dataSourceGetConnectSecurityProfileSummaryByName(ctx context.Context, conn *connect.Connect, instanceID, name string) (*connect.SecurityProfileSummary, error) { +func dataSourceGetSecurityProfileSummaryByName(ctx context.Context, conn *connect.Connect, instanceID, name string) (*connect.SecurityProfileSummary, error) { var result *connect.SecurityProfileSummary input := &connect.ListSecurityProfilesInput{ diff --git a/internal/service/connect/security_profile_data_source_test.go b/internal/service/connect/security_profile_data_source_test.go index d2e570abbdb..0b8c5727397 100644 --- a/internal/service/connect/security_profile_data_source_test.go +++ b/internal/service/connect/security_profile_data_source_test.go @@ -22,7 +22,7 @@ func TestAccConnectSecurityProfileDataSource_securityProfileID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecurityProfileDataSourceConfig_SecurityProfileID(rName, rName2), + Config: testAccSecurityProfileDataSourceConfig_id(rName, rName2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), @@ -50,7 +50,7 @@ func TestAccConnectSecurityProfileDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecurityProfileDataSourceConfig_Name(rName, rName2), + Config: testAccSecurityProfileDataSourceConfig_name(rName, rName2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), @@ -92,7 +92,7 @@ resource "aws_connect_security_profile" "test" { `, rName, rName2) } -func testAccSecurityProfileDataSourceConfig_SecurityProfileID(rName, rName2 string) string { +func testAccSecurityProfileDataSourceConfig_id(rName, rName2 string) string { return acctest.ConfigCompose( testAccSecurityProfileBaseDataSourceConfig(rName, rName2), ` @@ -103,7 +103,7 @@ data "aws_connect_security_profile" "test" { `) } -func testAccSecurityProfileDataSourceConfig_Name(rName, rName2 string) string { +func testAccSecurityProfileDataSourceConfig_name(rName, rName2 string) string { return acctest.ConfigCompose( testAccSecurityProfileBaseDataSourceConfig(rName, rName2), ` diff --git a/internal/service/connect/security_profile_test.go b/internal/service/connect/security_profile_test.go index 0329a663a26..423e2b89dd1 100644 --- a/internal/service/connect/security_profile_test.go +++ b/internal/service/connect/security_profile_test.go @@ -44,7 +44,7 @@ func testAccSecurityProfile_basic(t *testing.T) { CheckDestroy: testAccCheckSecurityProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityProfileBasicConfig(rName, rName2, "Created"), + Config: testAccSecurityProfileConfig_basic(rName, rName2, "Created"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -63,7 +63,7 @@ func testAccSecurityProfile_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSecurityProfileBasicConfig(rName, rName2, "Updated"), + Config: testAccSecurityProfileConfig_basic(rName, rName2, "Updated"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -93,7 +93,7 @@ func testAccSecurityProfile_updatePermissions(t *testing.T) { CheckDestroy: testAccCheckSecurityProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityProfileBasicConfig(rName, rName2, "TestPermissionsUpdate"), + Config: testAccSecurityProfileConfig_basic(rName, rName2, "TestPermissionsUpdate"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -113,7 +113,7 @@ func testAccSecurityProfile_updatePermissions(t *testing.T) { }, { // Test updating permissions - Config: testAccSecurityProfilePermissionsConfig(rName, rName2, "TestPermissionsUpdate"), + Config: testAccSecurityProfileConfig_permissions(rName, rName2, "TestPermissionsUpdate"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityProfileExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -143,7 +143,7 @@ func testAccSecurityProfile_disappears(t *testing.T) { CheckDestroy: testAccCheckSecurityProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityProfileBasicConfig(rName, rName2, "Disappear"), + Config: testAccSecurityProfileConfig_basic(rName, rName2, "Disappear"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityProfileExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceSecurityProfile(), resourceName), @@ -232,7 +232,7 @@ resource "aws_connect_instance" "test" { `, rName) } -func testAccSecurityProfileBasicConfig(rName, rName2, label string) string { +func testAccSecurityProfileConfig_basic(rName, rName2, label string) string { return acctest.ConfigCompose( testAccSecurityProfileBaseConfig(rName), fmt.Sprintf(` @@ -248,7 +248,7 @@ resource "aws_connect_security_profile" "test" { `, rName2, label)) } -func testAccSecurityProfilePermissionsConfig(rName, rName2, label string) string { +func testAccSecurityProfileConfig_permissions(rName, rName2, label string) string { return acctest.ConfigCompose( testAccSecurityProfileBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/connect/user_hierarchy_group.go b/internal/service/connect/user_hierarchy_group.go index 01dc6fb7833..2cf2c50ff5f 100644 --- a/internal/service/connect/user_hierarchy_group.go +++ b/internal/service/connect/user_hierarchy_group.go @@ -40,23 +40,23 @@ func ResourceUserHierarchyGroup() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "level_one": func() *schema.Schema { - schema := connectUserHierarchyPathLevelSchema() + schema := userHierarchyPathLevelSchema() return schema }(), "level_two": func() *schema.Schema { - schema := connectUserHierarchyPathLevelSchema() + schema := userHierarchyPathLevelSchema() return schema }(), "level_three": func() *schema.Schema { - schema := connectUserHierarchyPathLevelSchema() + schema := userHierarchyPathLevelSchema() return schema }(), "level_four": func() *schema.Schema { - schema := connectUserHierarchyPathLevelSchema() + schema := userHierarchyPathLevelSchema() return schema }(), "level_five": func() *schema.Schema { - schema := connectUserHierarchyPathLevelSchema() + schema := userHierarchyPathLevelSchema() return schema }(), }, @@ -88,7 +88,7 @@ func ResourceUserHierarchyGroup() *schema.Resource { } // Each level shares the same schema -func connectUserHierarchyPathLevelSchema() *schema.Schema { +func userHierarchyPathLevelSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, Computed: true, diff --git a/internal/service/connect/user_hierarchy_group_test.go b/internal/service/connect/user_hierarchy_group_test.go index 853e4bfc0c1..eb42cccc8f1 100644 --- a/internal/service/connect/user_hierarchy_group_test.go +++ b/internal/service/connect/user_hierarchy_group_test.go @@ -45,7 +45,7 @@ func testAccUserHierarchyGroup_basic(t *testing.T) { CheckDestroy: testAccCheckUserHierarchyGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccUserHierarchyGroupBasicConfig(rName, rName2), + Config: testAccUserHierarchyGroupConfig_basic(rName, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckUserHierarchyGroupExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -68,7 +68,7 @@ func testAccUserHierarchyGroup_basic(t *testing.T) { }, { // Update name - Config: testAccUserHierarchyGroupBasicConfig(rName, rName3), + Config: testAccUserHierarchyGroupConfig_basic(rName, rName3), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserHierarchyGroupExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -102,7 +102,7 @@ func testAccUserHierarchyGroup_parentGroupId(t *testing.T) { CheckDestroy: testAccCheckUserHierarchyGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccUserHierarchyGroupParentGroupIdConfig(rName, rName2, rName3), + Config: testAccUserHierarchyGroupConfig_parentID(rName, rName2, rName3), Check: resource.ComposeTestCheckFunc( testAccCheckUserHierarchyGroupExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -139,7 +139,7 @@ func testAccUserHierarchyGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckUserHierarchyGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccUserHierarchyGroupBasicConfig(rName, rName2), + Config: testAccUserHierarchyGroupConfig_basic(rName, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckUserHierarchyGroupExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceUserHierarchyGroup(), resourceName), @@ -253,7 +253,7 @@ resource "aws_connect_user_hierarchy_structure" "test" { `, rName) } -func testAccUserHierarchyGroupBasicConfig(rName, rName2 string) string { +func testAccUserHierarchyGroupConfig_basic(rName, rName2 string) string { return acctest.ConfigCompose( testAccUserHierarchyGroupBaseConfig(rName), fmt.Sprintf(` @@ -272,7 +272,7 @@ resource "aws_connect_user_hierarchy_group" "test" { `, rName2)) } -func testAccUserHierarchyGroupParentGroupIdConfig(rName, rName2, rName3 string) string { +func testAccUserHierarchyGroupConfig_parentID(rName, rName2, rName3 string) string { return acctest.ConfigCompose( testAccUserHierarchyGroupBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/connect/user_hierarchy_structure_data_source.go b/internal/service/connect/user_hierarchy_structure_data_source.go index e9596616337..90dc5e39662 100644 --- a/internal/service/connect/user_hierarchy_structure_data_source.go +++ b/internal/service/connect/user_hierarchy_structure_data_source.go @@ -22,23 +22,23 @@ func DataSourceUserHierarchyStructure() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "level_one": func() *schema.Schema { - schema := connectUserHierarchyLevelDataSourceSchema() + schema := userHierarchyLevelDataSourceSchema() return schema }(), "level_two": func() *schema.Schema { - schema := connectUserHierarchyLevelDataSourceSchema() + schema := userHierarchyLevelDataSourceSchema() return schema }(), "level_three": func() *schema.Schema { - schema := connectUserHierarchyLevelDataSourceSchema() + schema := userHierarchyLevelDataSourceSchema() return schema }(), "level_four": func() *schema.Schema { - schema := connectUserHierarchyLevelDataSourceSchema() + schema := userHierarchyLevelDataSourceSchema() return schema }(), "level_five": func() *schema.Schema { - schema := connectUserHierarchyLevelDataSourceSchema() + schema := userHierarchyLevelDataSourceSchema() return schema }(), }, @@ -54,7 +54,7 @@ func DataSourceUserHierarchyStructure() *schema.Resource { } // Each level shares the same schema -func connectUserHierarchyLevelDataSourceSchema() *schema.Schema { +func userHierarchyLevelDataSourceSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, Computed: true, diff --git a/internal/service/connect/user_hierarchy_structure_data_source_test.go b/internal/service/connect/user_hierarchy_structure_data_source_test.go index d26319a8bf1..aaf11760935 100644 --- a/internal/service/connect/user_hierarchy_structure_data_source_test.go +++ b/internal/service/connect/user_hierarchy_structure_data_source_test.go @@ -21,7 +21,7 @@ func TestAccConnectUserHierarchyStructureDataSource_instanceID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccUserHierarchyStructureDataSourceConfig_InstanceID(rName), + Config: testAccUserHierarchyStructureDataSourceConfig_instanceID(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "instance_id", resourceName, "instance_id"), resource.TestCheckResourceAttrPair(datasourceName, "hierarchy_structure.#", resourceName, "hierarchy_structure.#"), @@ -78,7 +78,7 @@ resource "aws_connect_user_hierarchy_structure" "test" { `, rName) } -func testAccUserHierarchyStructureDataSourceConfig_InstanceID(rName string) string { +func testAccUserHierarchyStructureDataSourceConfig_instanceID(rName string) string { return acctest.ConfigCompose( testAccUserHierarchyStructureBaseDataSourceConfig(rName), ` diff --git a/internal/service/connect/user_hierarchy_structure_test.go b/internal/service/connect/user_hierarchy_structure_test.go index aa90c1117e4..cf8230c67f6 100644 --- a/internal/service/connect/user_hierarchy_structure_test.go +++ b/internal/service/connect/user_hierarchy_structure_test.go @@ -47,7 +47,7 @@ func testAccUserHierarchyStructure_basic(t *testing.T) { CheckDestroy: testAccCheckUserHierarchyStructureDestroy, Steps: []resource.TestStep{ { - Config: testAccUserHierarchyStructureBasicConfig(rName, levelOneName), + Config: testAccUserHierarchyStructureConfig_basic(rName, levelOneName), Check: resource.ComposeTestCheckFunc( testAccCheckUserHierarchyStructureExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "hierarchy_structure.#", "1"), @@ -65,7 +65,7 @@ func testAccUserHierarchyStructure_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserHierarchyStructureBasicTwoLevelsConfig(rName, levelOneName, levelTwoName), + Config: testAccUserHierarchyStructureConfig_twoLevels(rName, levelOneName, levelTwoName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserHierarchyStructureExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "hierarchy_structure.#", "1"), @@ -87,7 +87,7 @@ func testAccUserHierarchyStructure_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserHierarchyStructureBasicThreeLevelsConfig(rName, levelOneName, levelTwoName, levelThreeName), + Config: testAccUserHierarchyStructureConfig_threeLevels(rName, levelOneName, levelTwoName, levelThreeName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserHierarchyStructureExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "hierarchy_structure.#", "1"), @@ -113,7 +113,7 @@ func testAccUserHierarchyStructure_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserHierarchyStructureBasicFourLevelsConfig(rName, levelOneName, levelTwoName, levelThreeName, levelFourName), + Config: testAccUserHierarchyStructureConfig_fourLevels(rName, levelOneName, levelTwoName, levelThreeName, levelFourName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserHierarchyStructureExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "hierarchy_structure.#", "1"), @@ -143,7 +143,7 @@ func testAccUserHierarchyStructure_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserHierarchyStructureBasicFiveLevelsConfig(rName, levelOneName, levelTwoName, levelThreeName, levelFourName, levelFiveName), + Config: testAccUserHierarchyStructureConfig_fiveLevels(rName, levelOneName, levelTwoName, levelThreeName, levelFourName, levelFiveName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckUserHierarchyStructureExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "hierarchy_structure.#", "1"), @@ -178,7 +178,7 @@ func testAccUserHierarchyStructure_basic(t *testing.T) { }, { // test removing 4 levels - Config: testAccUserHierarchyStructureBasicConfig(rName, levelOneName), + Config: testAccUserHierarchyStructureConfig_basic(rName, levelOneName), Check: resource.ComposeTestCheckFunc( testAccCheckUserHierarchyStructureExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "hierarchy_structure.#", "1"), @@ -207,7 +207,7 @@ func testAccUserHierarchyStructure_disappears(t *testing.T) { CheckDestroy: testAccCheckUserHierarchyStructureDestroy, Steps: []resource.TestStep{ { - Config: testAccUserHierarchyStructureBasicConfig(rName, levelOneName), + Config: testAccUserHierarchyStructureConfig_basic(rName, levelOneName), Check: resource.ComposeTestCheckFunc( testAccCheckUserHierarchyStructureExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfconnect.ResourceUserHierarchyStructure(), resourceName), @@ -291,7 +291,7 @@ resource "aws_connect_instance" "test" { `, rName) } -func testAccUserHierarchyStructureBasicConfig(rName, levelOneName string) string { +func testAccUserHierarchyStructureConfig_basic(rName, levelOneName string) string { return acctest.ConfigCompose( testAccUserHierarchyStructureBaseConfig(rName), fmt.Sprintf(` @@ -307,7 +307,7 @@ resource "aws_connect_user_hierarchy_structure" "test" { `, levelOneName)) } -func testAccUserHierarchyStructureBasicTwoLevelsConfig(rName, levelOneName, levelTwoName string) string { +func testAccUserHierarchyStructureConfig_twoLevels(rName, levelOneName, levelTwoName string) string { return acctest.ConfigCompose( testAccUserHierarchyStructureBaseConfig(rName), fmt.Sprintf(` @@ -327,7 +327,7 @@ resource "aws_connect_user_hierarchy_structure" "test" { `, levelOneName, levelTwoName)) } -func testAccUserHierarchyStructureBasicThreeLevelsConfig(rName, levelOneName, levelTwoName, levelThreeName string) string { +func testAccUserHierarchyStructureConfig_threeLevels(rName, levelOneName, levelTwoName, levelThreeName string) string { return acctest.ConfigCompose( testAccUserHierarchyStructureBaseConfig(rName), fmt.Sprintf(` @@ -351,7 +351,7 @@ resource "aws_connect_user_hierarchy_structure" "test" { `, levelOneName, levelTwoName, levelThreeName)) } -func testAccUserHierarchyStructureBasicFourLevelsConfig(rName, levelOneName, levelTwoName, levelThreeName, levelFourName string) string { +func testAccUserHierarchyStructureConfig_fourLevels(rName, levelOneName, levelTwoName, levelThreeName, levelFourName string) string { return acctest.ConfigCompose( testAccUserHierarchyStructureBaseConfig(rName), fmt.Sprintf(` @@ -379,7 +379,7 @@ resource "aws_connect_user_hierarchy_structure" "test" { `, levelOneName, levelTwoName, levelThreeName, levelFourName)) } -func testAccUserHierarchyStructureBasicFiveLevelsConfig(rName, levelOneName, levelTwoName, levelThreeName, levelFourName, levelFiveName string) string { +func testAccUserHierarchyStructureConfig_fiveLevels(rName, levelOneName, levelTwoName, levelThreeName, levelFourName, levelFiveName string) string { return acctest.ConfigCompose( testAccUserHierarchyStructureBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/connect/wait.go b/internal/service/connect/wait.go index eeb89a72971..802c8c7e5d1 100644 --- a/internal/service/connect/wait.go +++ b/internal/service/connect/wait.go @@ -10,13 +10,13 @@ import ( const ( // ConnectInstanceCreateTimeout Timeout for connect instance creation - connectInstanceCreatedTimeout = 5 * time.Minute - connectInstanceDeletedTimeout = 5 * time.Minute + instanceCreatedTimeout = 5 * time.Minute + instanceDeletedTimeout = 5 * time.Minute - connectContactFlowCreateTimeout = 5 * time.Minute - connectContactFlowUpdateTimeout = 5 * time.Minute + contactFlowCreateTimeout = 5 * time.Minute + contactFlowUpdateTimeout = 5 * time.Minute - connectBotAssociationCreateTimeout = 5 * time.Minute + botAssociationCreateTimeout = 5 * time.Minute ) func waitInstanceCreated(ctx context.Context, conn *connect.Connect, instanceId string) (*connect.DescribeInstanceOutput, error) { @@ -24,7 +24,7 @@ func waitInstanceCreated(ctx context.Context, conn *connect.Connect, instanceId Pending: []string{connect.InstanceStatusCreationInProgress}, Target: []string{connect.InstanceStatusActive}, Refresh: statusInstance(ctx, conn, instanceId), - Timeout: connectInstanceCreatedTimeout, + Timeout: instanceCreatedTimeout, } outputRaw, err := stateConf.WaitForState() @@ -44,7 +44,7 @@ func waitInstanceDeleted(ctx context.Context, conn *connect.Connect, instanceId Pending: []string{connect.InstanceStatusActive}, Target: []string{InstanceStatusStatusNotFound}, Refresh: statusInstance(ctx, conn, instanceId), - Timeout: connectInstanceDeletedTimeout, + Timeout: instanceDeletedTimeout, } outputRaw, err := stateConf.WaitForState() diff --git a/internal/service/cur/acc_test.go b/internal/service/cur/acc_test.go index 63865351f71..6491f3de25b 100644 --- a/internal/service/cur/acc_test.go +++ b/internal/service/cur/acc_test.go @@ -27,14 +27,14 @@ var testAccCurRegion string // This Provider can be used in testing code for API calls without requiring // the use of saving and referencing specific ProviderFactories instances. // -// testAccPreCheckCur(t) must be called before using this provider instance. +// testAccPreCheck(t) must be called before using this provider instance. var testAccProviderCur *schema.Provider // testAccProviderCurConfigure ensures the provider is only configured once var testAccProviderCurConfigure sync.Once -// testAccPreCheckCur verifies AWS credentials and that Cost and Usage Reporting is supported -func testAccPreCheckCur(t *testing.T) { +// testAccPreCheck verifies AWS credentials and that Cost and Usage Reporting is supported +func testAccPreCheck(t *testing.T) { acctest.PreCheckPartitionHasService(costandusagereportservice.ServiceName, t) // Since we are outside the scope of the Terraform configuration we must @@ -43,7 +43,7 @@ func testAccPreCheckCur(t *testing.T) { testAccProviderCur = provider.Provider() config := map[string]interface{}{ - "region": testAccGetCurRegion(), + "region": testAccGetRegion(), } diags := testAccProviderCur.Configure(context.Background(), terraform.NewResourceConfigRaw(config)) @@ -74,16 +74,16 @@ func testAccPreCheckCur(t *testing.T) { } } -// testAccCurRegionProviderConfig is the Terraform provider configuration for Cost and Usage Reporting region testing +// testAccRegionProviderConfig is the Terraform provider configuration for Cost and Usage Reporting region testing // // Testing Cost and Usage Reporting assumes no other provider configurations // are necessary and overwrites the "aws" provider configuration. -func testAccCurRegionProviderConfig() string { - return acctest.ConfigRegionalProvider(testAccGetCurRegion()) +func testAccRegionProviderConfig() string { + return acctest.ConfigRegionalProvider(testAccGetRegion()) } -// testAccGetCurRegion returns the Cost and Usage Reporting region for testing -func testAccGetCurRegion() string { +// testAccGetRegion returns the Cost and Usage Reporting region for testing +func testAccGetRegion() string { if testAccCurRegion != "" { return testAccCurRegion } diff --git a/internal/service/cur/report_definition_data_source_test.go b/internal/service/cur/report_definition_data_source_test.go index 7f431b8936f..3c9cb0b9543 100644 --- a/internal/service/cur/report_definition_data_source_test.go +++ b/internal/service/cur/report_definition_data_source_test.go @@ -19,7 +19,7 @@ func TestAccCURReportDefinitionDataSource_basic(t *testing.T) { bucketName := fmt.Sprintf("tf-test-bucket-%d", sdkacctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckCur(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, costandusagereportservice.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckReportDefinitionDestroy, @@ -50,7 +50,7 @@ func TestAccCURReportDefinitionDataSource_additional(t *testing.T) { bucketName := fmt.Sprintf("tf-test-bucket-%d", sdkacctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckCur(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, costandusagereportservice.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckReportDefinitionDestroy, @@ -91,7 +91,7 @@ func testAccReportDefinitionCheckExistsDataSource(datasourceName, resourceName s func testAccReportDefinitionDataSourceConfig_basic(reportName string, bucketName string) string { return acctest.ConfigCompose( - testAccCurRegionProviderConfig(), + testAccRegionProviderConfig(), fmt.Sprintf(` data "aws_billing_service_account" "test" {} @@ -163,7 +163,7 @@ data "aws_cur_report_definition" "test" { func testAccReportDefinitionDataSourceConfig_additional(reportName string, bucketName string) string { return acctest.ConfigCompose( - testAccCurRegionProviderConfig(), + testAccRegionProviderConfig(), fmt.Sprintf(` data "aws_billing_service_account" "test" {} diff --git a/internal/service/cur/report_definition_test.go b/internal/service/cur/report_definition_test.go index 8ff8054ddb3..7991c6e9a92 100644 --- a/internal/service/cur/report_definition_test.go +++ b/internal/service/cur/report_definition_test.go @@ -21,7 +21,7 @@ func testAccReportDefinition_basic(t *testing.T) { bucketName := fmt.Sprintf("tf-test-bucket-%d", sdkacctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckCur(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, cur.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckReportDefinitionDestroy, @@ -80,7 +80,7 @@ func testAccReportDefinition_textOrCSV(t *testing.T) { reportVersioning := "CREATE_NEW_REPORT" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckCur(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, cur.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckReportDefinitionDestroy, @@ -124,7 +124,7 @@ func testAccReportDefinition_parquet(t *testing.T) { reportVersioning := "CREATE_NEW_REPORT" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckCur(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, cur.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckReportDefinitionDestroy, @@ -167,7 +167,7 @@ func testAccReportDefinition_athena(t *testing.T) { reportVersioning := "OVERWRITE_REPORT" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckCur(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, cur.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckReportDefinitionDestroy, @@ -211,7 +211,7 @@ func testAccReportDefinition_refresh(t *testing.T) { reportVersioning := "CREATE_NEW_REPORT" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckCur(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, cur.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckReportDefinitionDestroy, @@ -255,7 +255,7 @@ func testAccReportDefinition_overwrite(t *testing.T) { reportVersioning := "OVERWRITE_REPORT" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckCur(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, cur.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckReportDefinitionDestroy, @@ -292,7 +292,7 @@ func testAccReportDefinition_disappears(t *testing.T) { bucketName := fmt.Sprintf("tf-test-bucket-%d", sdkacctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckCur(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, cur.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckReportDefinitionDestroy, @@ -356,7 +356,7 @@ func testAccCheckReportDefinitionExists(resourceName string) resource.TestCheckF func testAccReportDefinitionConfig_basic(reportName, bucketName, prefix string) string { return acctest.ConfigCompose( - testAccCurRegionProviderConfig(), + testAccRegionProviderConfig(), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[2]q @@ -430,7 +430,7 @@ func testAccReportDefinitionConfig_additional(reportName string, bucketName stri } return acctest.ConfigCompose( - testAccCurRegionProviderConfig(), + testAccRegionProviderConfig(), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = "%[2]s" diff --git a/internal/service/datapipeline/pipeline_test.go b/internal/service/datapipeline/pipeline_test.go index f05505b08b7..df7d55d0849 100644 --- a/internal/service/datapipeline/pipeline_test.go +++ b/internal/service/datapipeline/pipeline_test.go @@ -28,14 +28,14 @@ func TestAccDataPipelinePipeline_basic(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccPipelineConfig(rName1), + Config: testAccPipelineConfig_basic(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &conf1), resource.TestCheckResourceAttr(resourceName, "name", rName1), ), }, { - Config: testAccPipelineConfig(rName2), + Config: testAccPipelineConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &conf2), testAccCheckPipelineNotEqual(&conf1, &conf2), @@ -63,14 +63,14 @@ func TestAccDataPipelinePipeline_description(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccPipelineWithDescriptionConfig(rName, "test description"), + Config: testAccPipelineConfig_description(rName, "test description"), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &conf1), resource.TestCheckResourceAttr(resourceName, "description", "test description"), ), }, { - Config: testAccPipelineWithDescriptionConfig(rName, "update description"), + Config: testAccPipelineConfig_description(rName, "update description"), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &conf2), testAccCheckPipelineNotEqual(&conf1, &conf2), @@ -98,7 +98,7 @@ func TestAccDataPipelinePipeline_disappears(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccPipelineConfig(rName), + Config: testAccPipelineConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &conf), testAccCheckPipelineDisappears(&conf), @@ -121,7 +121,7 @@ func TestAccDataPipelinePipeline_tags(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccPipelineWithTagsConfig(rName, "foo", "bar", "fizz", "buzz"), + Config: testAccPipelineConfig_tags(rName, "foo", "bar", "fizz", "buzz"), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -132,7 +132,7 @@ func TestAccDataPipelinePipeline_tags(t *testing.T) { ), }, { - Config: testAccPipelineWithTagsConfig(rName, "foo", "bar2", "fizz2", "buzz2"), + Config: testAccPipelineConfig_tags(rName, "foo", "bar2", "fizz2", "buzz2"), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -148,7 +148,7 @@ func TestAccDataPipelinePipeline_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPipelineConfig(rName), + Config: testAccPipelineConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -252,7 +252,7 @@ func testAccCheckPipelineNotEqual(pipeline1, pipeline2 *datapipeline.PipelineDes } } -func testAccPipelineConfig(rName string) string { +func testAccPipelineConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_datapipeline_pipeline" "default" { name = "%[1]s" @@ -260,7 +260,7 @@ resource "aws_datapipeline_pipeline" "default" { } -func testAccPipelineWithDescriptionConfig(rName, description string) string { +func testAccPipelineConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_datapipeline_pipeline" "default" { name = "%[1]s" @@ -269,7 +269,7 @@ resource "aws_datapipeline_pipeline" "default" { } -func testAccPipelineWithTagsConfig(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccPipelineConfig_tags(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_datapipeline_pipeline" "default" { name = "%[1]s" diff --git a/internal/service/datasync/agent_test.go b/internal/service/datasync/agent_test.go index eaf2bd49e4f..203b4578021 100644 --- a/internal/service/datasync/agent_test.go +++ b/internal/service/datasync/agent_test.go @@ -29,7 +29,7 @@ func TestAccDataSyncAgent_basic(t *testing.T) { CheckDestroy: testAccCheckAgentDestroy, Steps: []resource.TestStep{ { - Config: testAccAgentConfig(rName), + Config: testAccAgentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAgentExists(resourceName, &agent1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`agent/agent-.+`)), @@ -63,7 +63,7 @@ func TestAccDataSyncAgent_disappears(t *testing.T) { CheckDestroy: testAccCheckAgentDestroy, Steps: []resource.TestStep{ { - Config: testAccAgentConfig(rName), + Config: testAccAgentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAgentExists(resourceName, &agent1), acctest.CheckResourceDisappears(acctest.Provider, tfdatasync.ResourceAgent(), resourceName), @@ -87,14 +87,14 @@ func TestAccDataSyncAgent_agentName(t *testing.T) { CheckDestroy: testAccCheckAgentDestroy, Steps: []resource.TestStep{ { - Config: testAccAgentNameConfig(rName1, rName1), + Config: testAccAgentConfig_name(rName1, rName1), Check: resource.ComposeTestCheckFunc( testAccCheckAgentExists(resourceName, &agent1), resource.TestCheckResourceAttr(resourceName, "name", rName1), ), }, { - Config: testAccAgentNameConfig(rName1, rName2), + Config: testAccAgentConfig_name(rName1, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckAgentExists(resourceName, &agent2), resource.TestCheckResourceAttr(resourceName, "name", rName2), @@ -122,7 +122,7 @@ func TestAccDataSyncAgent_tags(t *testing.T) { CheckDestroy: testAccCheckAgentDestroy, Steps: []resource.TestStep{ { - Config: testAccAgentTags1Config(rName, "key1", "value1"), + Config: testAccAgentConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAgentExists(resourceName, &agent1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -136,7 +136,7 @@ func TestAccDataSyncAgent_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"activation_key", "ip_address"}, }, { - Config: testAccAgentTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAgentConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAgentExists(resourceName, &agent2), testAccCheckAgentNotRecreated(&agent1, &agent2), @@ -146,7 +146,7 @@ func TestAccDataSyncAgent_tags(t *testing.T) { ), }, { - Config: testAccAgentTags1Config(rName, "key1", "value1"), + Config: testAccAgentConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAgentExists(resourceName, &agent3), testAccCheckAgentNotRecreated(&agent2, &agent3), @@ -173,7 +173,7 @@ func TestAccDataSyncAgent_vpcEndpointID(t *testing.T) { CheckDestroy: testAccCheckAgentDestroy, Steps: []resource.TestStep{ { - Config: testAccAgentVPCEndpointIDConfig(rName), + Config: testAccAgentConfig_vpcEndpointID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAgentExists(resourceName, &agent), resource.TestCheckResourceAttr(resourceName, "security_group_arns.#", "1"), @@ -339,7 +339,7 @@ resource "aws_instance" "test" { `, rName) } -func testAccAgentConfig(rName string) string { +func testAccAgentConfig_basic(rName string) string { return acctest.ConfigCompose(testAccAgentAgentBaseConfig(rName), ` resource "aws_datasync_agent" "test" { ip_address = aws_instance.test.public_ip @@ -347,7 +347,7 @@ resource "aws_datasync_agent" "test" { `) } -func testAccAgentNameConfig(rName, agentName string) string { +func testAccAgentConfig_name(rName, agentName string) string { return acctest.ConfigCompose(testAccAgentAgentBaseConfig(rName), fmt.Sprintf(` resource "aws_datasync_agent" "test" { ip_address = aws_instance.test.public_ip @@ -356,7 +356,7 @@ resource "aws_datasync_agent" "test" { `, agentName)) } -func testAccAgentTags1Config(rName, key1, value1 string) string { +func testAccAgentConfig_tags1(rName, key1, value1 string) string { return acctest.ConfigCompose(testAccAgentAgentBaseConfig(rName), fmt.Sprintf(` resource "aws_datasync_agent" "test" { ip_address = aws_instance.test.public_ip @@ -368,7 +368,7 @@ resource "aws_datasync_agent" "test" { `, key1, value1)) } -func testAccAgentTags2Config(rName, key1, value1, key2, value2 string) string { +func testAccAgentConfig_tags2(rName, key1, value1, key2, value2 string) string { return acctest.ConfigCompose(testAccAgentAgentBaseConfig(rName), fmt.Sprintf(` resource "aws_datasync_agent" "test" { ip_address = aws_instance.test.public_ip @@ -381,7 +381,7 @@ resource "aws_datasync_agent" "test" { `, key1, value1, key2, value2)) } -func testAccAgentVPCEndpointIDConfig(rName string) string { +func testAccAgentConfig_vpcEndpointID(rName string) string { return acctest.ConfigCompose(testAccAgentAgentBaseConfig(rName), fmt.Sprintf(` resource "aws_datasync_agent" "test" { name = %[1]q diff --git a/internal/service/datasync/find.go b/internal/service/datasync/find.go index c8c5f9c1ef1..72412b40f44 100644 --- a/internal/service/datasync/find.go +++ b/internal/service/datasync/find.go @@ -83,7 +83,7 @@ func FindLocationHDFSByARN(conn *datasync.DataSync, arn string) (*datasync.Descr return output, nil } -func FindFsxLustreLocationByARN(conn *datasync.DataSync, arn string) (*datasync.DescribeLocationFsxLustreOutput, error) { +func FindFSxLustreLocationByARN(conn *datasync.DataSync, arn string) (*datasync.DescribeLocationFsxLustreOutput, error) { input := &datasync.DescribeLocationFsxLustreInput{ LocationArn: aws.String(arn), } @@ -108,7 +108,7 @@ func FindFsxLustreLocationByARN(conn *datasync.DataSync, arn string) (*datasync. return output, nil } -func FindFsxOpenZfsLocationByARN(conn *datasync.DataSync, arn string) (*datasync.DescribeLocationFsxOpenZfsOutput, error) { +func FindFSxOpenZFSLocationByARN(conn *datasync.DataSync, arn string) (*datasync.DescribeLocationFsxOpenZfsOutput, error) { input := &datasync.DescribeLocationFsxOpenZfsInput{ LocationArn: aws.String(arn), } diff --git a/internal/service/datasync/location_efs.go b/internal/service/datasync/location_efs.go index 677641f3373..c4b1fccf24c 100644 --- a/internal/service/datasync/location_efs.go +++ b/internal/service/datasync/location_efs.go @@ -31,6 +31,12 @@ func ResourceLocationEFS() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "access_point_arn": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: verify.ValidARN, + }, "ec2_config": { Type: schema.TypeList, Required: true, @@ -42,13 +48,16 @@ func ResourceLocationEFS() *schema.Resource { Type: schema.TypeSet, Required: true, ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidARN, + }, }, "subnet_arn": { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validation.NoZeroValues, + ValidateFunc: verify.ValidARN, }, }, }, @@ -57,7 +66,19 @@ func ResourceLocationEFS() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validation.NoZeroValues, + ValidateFunc: verify.ValidARN, + }, + "file_system_access_role_arn": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: verify.ValidARN, + }, + "in_transit_encryption": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(datasync.EfsInTransitEncryption_Values(), false), }, "subdirectory": { Type: schema.TypeString, @@ -99,10 +120,22 @@ func resourceLocationEFSCreate(d *schema.ResourceData, meta interface{}) error { Tags: Tags(tags.IgnoreAWS()), } + if v, ok := d.GetOk("access_point_arn"); ok { + input.AccessPointArn = aws.String(v.(string)) + } + + if v, ok := d.GetOk("file_system_access_role_arn"); ok { + input.FileSystemAccessRoleArn = aws.String(v.(string)) + } + + if v, ok := d.GetOk("in_transit_encryption"); ok { + input.InTransitEncryption = aws.String(v.(string)) + } + log.Printf("[DEBUG] Creating DataSync Location EFS: %s", input) output, err := conn.CreateLocationEfs(input) if err != nil { - return fmt.Errorf("error creating DataSync Location EFS: %s", err) + return fmt.Errorf("error creating DataSync Location EFS: %w", err) } d.SetId(aws.StringValue(output.LocationArn)) @@ -129,7 +162,7 @@ func resourceLocationEFSRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading DataSync Location EFS (%s): %s", d.Id(), err) + return fmt.Errorf("error reading DataSync Location EFS (%s): %w", d.Id(), err) } subdirectory, err := SubdirectoryFromLocationURI(aws.StringValue(output.LocationUri)) @@ -141,11 +174,14 @@ func resourceLocationEFSRead(d *schema.ResourceData, meta interface{}) error { d.Set("arn", output.LocationArn) if err := d.Set("ec2_config", flattenEC2Config(output.Ec2Config)); err != nil { - return fmt.Errorf("error setting ec2_config: %s", err) + return fmt.Errorf("error setting ec2_config: %w", err) } d.Set("subdirectory", subdirectory) d.Set("uri", output.LocationUri) + d.Set("access_point_arn", output.AccessPointArn) + d.Set("file_system_access_role_arn", output.FileSystemAccessRoleArn) + d.Set("in_transit_encryption", output.InTransitEncryption) tags, err := ListTags(conn, d.Id()) @@ -174,7 +210,7 @@ func resourceLocationEFSUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating DataSync Location EFS (%s) tags: %s", d.Id(), err) + return fmt.Errorf("error updating DataSync Location EFS (%s) tags: %w", d.Id(), err) } } @@ -196,7 +232,7 @@ func resourceLocationEFSDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting DataSync Location EFS (%s): %s", d.Id(), err) + return fmt.Errorf("error deleting DataSync Location EFS (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/datasync/location_efs_test.go b/internal/service/datasync/location_efs_test.go index 7ef3d8f0833..e98a5ed5806 100644 --- a/internal/service/datasync/location_efs_test.go +++ b/internal/service/datasync/location_efs_test.go @@ -9,10 +9,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfdatasync "github.com/hashicorp/terraform-provider-aws/internal/service/datasync" ) func TestAccDataSyncLocationEFS_basic(t *testing.T) { @@ -20,6 +22,7 @@ func TestAccDataSyncLocationEFS_basic(t *testing.T) { efsFileSystemResourceName := "aws_efs_file_system.test" resourceName := "aws_datasync_location_efs.test" subnetResourceName := "aws_subnet.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, @@ -28,7 +31,7 @@ func TestAccDataSyncLocationEFS_basic(t *testing.T) { CheckDestroy: testAccCheckLocationEFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationEFSConfig(), + Config: testAccLocationEFSConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationEFSExists(resourceName, &locationEfs1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`location/loc-.+`)), @@ -51,9 +54,39 @@ func TestAccDataSyncLocationEFS_basic(t *testing.T) { }) } +func TestAccDataSyncLocationEFS_accessPointARN(t *testing.T) { + var locationEfs1 datasync.DescribeLocationEfsOutput + resourceName := "aws_datasync_location_efs.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, datasync.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLocationEFSDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLocationEFSConfig_accessPointARN(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckLocationEFSExists(resourceName, &locationEfs1), + resource.TestCheckResourceAttrPair(resourceName, "access_point_arn", "aws_efs_access_point.test", "arn"), + resource.TestCheckResourceAttr(resourceName, "in_transit_encryption", "TLS1_2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"efs_file_system_arn"}, + }, + }, + }) +} + func TestAccDataSyncLocationEFS_disappears(t *testing.T) { var locationEfs1 datasync.DescribeLocationEfsOutput resourceName := "aws_datasync_location_efs.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, @@ -62,10 +95,11 @@ func TestAccDataSyncLocationEFS_disappears(t *testing.T) { CheckDestroy: testAccCheckLocationEFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationEFSConfig(), + Config: testAccLocationEFSConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationEFSExists(resourceName, &locationEfs1), - testAccCheckLocationEFSDisappears(&locationEfs1), + acctest.CheckResourceDisappears(acctest.Provider, tfdatasync.ResourceLocationEFS(), resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfdatasync.ResourceLocationEFS(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -76,6 +110,7 @@ func TestAccDataSyncLocationEFS_disappears(t *testing.T) { func TestAccDataSyncLocationEFS_subdirectory(t *testing.T) { var locationEfs1 datasync.DescribeLocationEfsOutput resourceName := "aws_datasync_location_efs.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, @@ -84,7 +119,7 @@ func TestAccDataSyncLocationEFS_subdirectory(t *testing.T) { CheckDestroy: testAccCheckLocationEFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationEFSSubdirectoryConfig("/subdirectory1/"), + Config: testAccLocationEFSConfig_subdirectory(rName, "/subdirectory1/"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationEFSExists(resourceName, &locationEfs1), resource.TestCheckResourceAttr(resourceName, "subdirectory", "/subdirectory1/"), @@ -103,6 +138,7 @@ func TestAccDataSyncLocationEFS_subdirectory(t *testing.T) { func TestAccDataSyncLocationEFS_tags(t *testing.T) { var locationEfs1, locationEfs2, locationEfs3 datasync.DescribeLocationEfsOutput resourceName := "aws_datasync_location_efs.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, @@ -111,7 +147,7 @@ func TestAccDataSyncLocationEFS_tags(t *testing.T) { CheckDestroy: testAccCheckLocationEFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationEFSTags1Config("key1", "value1"), + Config: testAccLocationEFSConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationEFSExists(resourceName, &locationEfs1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -125,7 +161,7 @@ func TestAccDataSyncLocationEFS_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"efs_file_system_arn"}, }, { - Config: testAccLocationEFSTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccLocationEFSConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationEFSExists(resourceName, &locationEfs2), testAccCheckLocationEFSNotRecreated(&locationEfs1, &locationEfs2), @@ -135,7 +171,7 @@ func TestAccDataSyncLocationEFS_tags(t *testing.T) { ), }, { - Config: testAccLocationEFSTags1Config("key1", "value1"), + Config: testAccLocationEFSConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationEFSExists(resourceName, &locationEfs3), testAccCheckLocationEFSNotRecreated(&locationEfs2, &locationEfs3), @@ -201,20 +237,6 @@ func testAccCheckLocationEFSExists(resourceName string, locationEfs *datasync.De } } -func testAccCheckLocationEFSDisappears(location *datasync.DescribeLocationEfsOutput) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).DataSyncConn - - input := &datasync.DeleteLocationInput{ - LocationArn: location.LocationArn, - } - - _, err := conn.DeleteLocation(input) - - return err - } -} - func testAccCheckLocationEFSNotRecreated(i, j *datasync.DescribeLocationEfsOutput) resource.TestCheckFunc { return func(s *terraform.State) error { if !aws.TimeValue(i.CreationTime).Equal(aws.TimeValue(j.CreationTime)) { @@ -225,13 +247,13 @@ func testAccCheckLocationEFSNotRecreated(i, j *datasync.DescribeLocationEfsOutpu } } -func testAccLocationEFSBaseConfig() string { - return ` +func testAccLocationEFSBaseConfig(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "tf-acc-test-datasync-location-efs" + Name = %[1]q } } @@ -240,7 +262,7 @@ resource "aws_subnet" "test" { vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-test-datasync-location-efs" + Name = %[1]q } } @@ -248,21 +270,25 @@ resource "aws_security_group" "test" { vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-test-datasync-location-efs" + Name = %[1]q } } -resource "aws_efs_file_system" "test" {} +resource "aws_efs_file_system" "test" { + tags = { + Name = %[1]q + } +} resource "aws_efs_mount_target" "test" { file_system_id = aws_efs_file_system.test.id subnet_id = aws_subnet.test.id } -` +`, rName) } -func testAccLocationEFSConfig() string { - return testAccLocationEFSBaseConfig() + ` +func testAccLocationEFSConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccLocationEFSBaseConfig(rName), ` resource "aws_datasync_location_efs" "test" { efs_file_system_arn = aws_efs_mount_target.test.file_system_arn @@ -271,25 +297,25 @@ resource "aws_datasync_location_efs" "test" { subnet_arn = aws_subnet.test.arn } } -` +`) } -func testAccLocationEFSSubdirectoryConfig(subdirectory string) string { - return testAccLocationEFSBaseConfig() + fmt.Sprintf(` +func testAccLocationEFSConfig_subdirectory(rName, subdirectory string) string { + return acctest.ConfigCompose(testAccLocationEFSBaseConfig(rName), fmt.Sprintf(` resource "aws_datasync_location_efs" "test" { efs_file_system_arn = aws_efs_mount_target.test.file_system_arn - subdirectory = %q + subdirectory = %[1]q ec2_config { security_group_arns = [aws_security_group.test.arn] subnet_arn = aws_subnet.test.arn } } -`, subdirectory) +`, subdirectory)) } -func testAccLocationEFSTags1Config(key1, value1 string) string { - return testAccLocationEFSBaseConfig() + fmt.Sprintf(` +func testAccLocationEFSConfig_tags1(rName, key1, value1 string) string { + return acctest.ConfigCompose(testAccLocationEFSBaseConfig(rName), fmt.Sprintf(` resource "aws_datasync_location_efs" "test" { efs_file_system_arn = aws_efs_mount_target.test.file_system_arn @@ -299,14 +325,14 @@ resource "aws_datasync_location_efs" "test" { } tags = { - %q = %q + %[1]q = %[2]q } } -`, key1, value1) +`, key1, value1)) } -func testAccLocationEFSTags2Config(key1, value1, key2, value2 string) string { - return testAccLocationEFSBaseConfig() + fmt.Sprintf(` +func testAccLocationEFSConfig_tags2(rName, key1, value1, key2, value2 string) string { + return acctest.ConfigCompose(testAccLocationEFSBaseConfig(rName), fmt.Sprintf(` resource "aws_datasync_location_efs" "test" { efs_file_system_arn = aws_efs_mount_target.test.file_system_arn @@ -316,9 +342,32 @@ resource "aws_datasync_location_efs" "test" { } tags = { - %q = %q - %q = %q + %[1]q = %[2]q + %[3]q = %[4]q + } +} +`, key1, value1, key2, value2)) +} + +func testAccLocationEFSConfig_accessPointARN(rName string) string { + return acctest.ConfigCompose(testAccLocationEFSBaseConfig(rName), fmt.Sprintf(` +resource "aws_efs_access_point" "test" { + file_system_id = aws_efs_file_system.test.id + + tags = { + Name = %[1]q + } +} + +resource "aws_datasync_location_efs" "test" { + efs_file_system_arn = aws_efs_mount_target.test.file_system_arn + access_point_arn = aws_efs_access_point.test.arn + in_transit_encryption = "TLS1_2" + + ec2_config { + security_group_arns = [aws_security_group.test.arn] + subnet_arn = aws_subnet.test.arn } } -`, key1, value1, key2, value2) +`, rName)) } diff --git a/internal/service/datasync/location_fsx_lustre_file_system.go b/internal/service/datasync/location_fsx_lustre_file_system.go index d75a2b86fcb..e89a087470f 100644 --- a/internal/service/datasync/location_fsx_lustre_file_system.go +++ b/internal/service/datasync/location_fsx_lustre_file_system.go @@ -118,7 +118,7 @@ func resourceLocationFSxLustreFileSystemRead(d *schema.ResourceData, meta interf defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - output, err := FindFsxLustreLocationByARN(conn, d.Id()) + output, err := FindFSxLustreLocationByARN(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] DataSync Location Fsx Lustre (%s) not found, removing from state", d.Id()) diff --git a/internal/service/datasync/location_fsx_lustre_file_system_test.go b/internal/service/datasync/location_fsx_lustre_file_system_test.go index 3e6f1096afe..f982ca3dfad 100644 --- a/internal/service/datasync/location_fsx_lustre_file_system_test.go +++ b/internal/service/datasync/location_fsx_lustre_file_system_test.go @@ -31,7 +31,7 @@ func TestAccDataSyncLocationFSxLustreFileSystem_basic(t *testing.T) { CheckDestroy: testAccCheckLocationFSxLustreDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxLustreConfig(), + Config: testAccLocationFSxLustreFileSystemConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxLustreExists(resourceName, &locationFsxLustre1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`location/loc-.+`)), @@ -67,7 +67,7 @@ func TestAccDataSyncLocationFSxLustreFileSystem_disappears(t *testing.T) { CheckDestroy: testAccCheckLocationFSxLustreDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxLustreConfig(), + Config: testAccLocationFSxLustreFileSystemConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxLustreExists(resourceName, &locationFsxLustre1), acctest.CheckResourceDisappears(acctest.Provider, tfdatasync.ResourceLocationFSxLustreFileSystem(), resourceName), @@ -94,7 +94,7 @@ func TestAccDataSyncLocationFSxLustreFileSystem_subdirectory(t *testing.T) { CheckDestroy: testAccCheckLocationFSxLustreDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxLustreSubdirectoryConfig("/subdirectory1/"), + Config: testAccLocationFSxLustreFileSystemConfig_subdirectory("/subdirectory1/"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxLustreExists(resourceName, &locationFsxLustre1), resource.TestCheckResourceAttr(resourceName, "subdirectory", "/subdirectory1/"), @@ -125,7 +125,7 @@ func TestAccDataSyncLocationFSxLustreFileSystem_tags(t *testing.T) { CheckDestroy: testAccCheckLocationFSxLustreDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxLustreTags1Config("key1", "value1"), + Config: testAccLocationFSxLustreFileSystemConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxLustreExists(resourceName, &locationFsxLustre1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -139,7 +139,7 @@ func TestAccDataSyncLocationFSxLustreFileSystem_tags(t *testing.T) { ImportStateIdFunc: testAccLocationFSxLustreImportStateID(resourceName), }, { - Config: testAccLocationFSxLustreTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccLocationFSxLustreFileSystemConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxLustreExists(resourceName, &locationFsxLustre1), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -148,7 +148,7 @@ func TestAccDataSyncLocationFSxLustreFileSystem_tags(t *testing.T) { ), }, { - Config: testAccLocationFSxLustreTags1Config("key1", "value1"), + Config: testAccLocationFSxLustreFileSystemConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxLustreExists(resourceName, &locationFsxLustre1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -167,7 +167,7 @@ func testAccCheckLocationFSxLustreDestroy(s *terraform.State) error { continue } - _, err := tfdatasync.FindFsxLustreLocationByARN(conn, rs.Primary.ID) + _, err := tfdatasync.FindFSxLustreLocationByARN(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -191,7 +191,7 @@ func testAccCheckLocationFSxLustreExists(resourceName string, locationFsxLustre } conn := acctest.Provider.Meta().(*conns.AWSClient).DataSyncConn - output, err := tfdatasync.FindFsxLustreLocationByARN(conn, rs.Primary.ID) + output, err := tfdatasync.FindFSxLustreLocationByARN(conn, rs.Primary.ID) if err != nil { return err @@ -218,7 +218,7 @@ func testAccLocationFSxLustreImportStateID(resourceName string) resource.ImportS } } -func testAccLocationFSxLustreConfig() string { +func testAccLocationFSxLustreFileSystemConfig_basic() string { return acctest.ConfigCompose(testAccFSxLustreFileSystemBaseConfig(), ` resource "aws_datasync_location_fsx_lustre_file_system" "test" { fsx_filesystem_arn = aws_fsx_lustre_file_system.test.arn @@ -227,7 +227,7 @@ resource "aws_datasync_location_fsx_lustre_file_system" "test" { `) } -func testAccLocationFSxLustreSubdirectoryConfig(subdirectory string) string { +func testAccLocationFSxLustreFileSystemConfig_subdirectory(subdirectory string) string { return acctest.ConfigCompose(testAccFSxLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_datasync_location_fsx_lustre_file_system" "test" { fsx_filesystem_arn = aws_fsx_lustre_file_system.test.arn @@ -237,7 +237,7 @@ resource "aws_datasync_location_fsx_lustre_file_system" "test" { `, subdirectory)) } -func testAccLocationFSxLustreTags1Config(key1, value1 string) string { +func testAccLocationFSxLustreFileSystemConfig_tags1(key1, value1 string) string { return acctest.ConfigCompose(testAccFSxLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_datasync_location_fsx_lustre_file_system" "test" { fsx_filesystem_arn = aws_fsx_lustre_file_system.test.arn @@ -250,7 +250,7 @@ resource "aws_datasync_location_fsx_lustre_file_system" "test" { `, key1, value1)) } -func testAccLocationFSxLustreTags2Config(key1, value1, key2, value2 string) string { +func testAccLocationFSxLustreFileSystemConfig_tags2(key1, value1, key2, value2 string) string { return acctest.ConfigCompose(testAccFSxLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_datasync_location_fsx_lustre_file_system" "test" { fsx_filesystem_arn = aws_fsx_lustre_file_system.test.arn diff --git a/internal/service/datasync/location_fsx_openzfs_file_system.go b/internal/service/datasync/location_fsx_openzfs_file_system.go index b9f366432d0..7b5f2760d3b 100644 --- a/internal/service/datasync/location_fsx_openzfs_file_system.go +++ b/internal/service/datasync/location_fsx_openzfs_file_system.go @@ -156,7 +156,7 @@ func resourceLocationFSxOpenZFSFileSystemRead(d *schema.ResourceData, meta inter defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - output, err := FindFsxOpenZfsLocationByARN(conn, d.Id()) + output, err := FindFSxOpenZFSLocationByARN(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] DataSync Location Fsx OpenZfs (%s) not found, removing from state", d.Id()) diff --git a/internal/service/datasync/location_fsx_openzfs_file_system_test.go b/internal/service/datasync/location_fsx_openzfs_file_system_test.go index ba93f3ac42b..254dd88862b 100644 --- a/internal/service/datasync/location_fsx_openzfs_file_system_test.go +++ b/internal/service/datasync/location_fsx_openzfs_file_system_test.go @@ -31,7 +31,7 @@ func TestAccDataSyncLocationFSxOpenZFSFileSystem_basic(t *testing.T) { CheckDestroy: testAccCheckLocationFSxOpenZFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxOpenZFSConfig(), + Config: testAccLocationFSxOpenZFSFileSystemConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxOpenZFSExists(resourceName, &locationFsxOpenZfs1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`location/loc-.+`)), @@ -67,7 +67,7 @@ func TestAccDataSyncLocationFSxOpenZFSFileSystem_disappears(t *testing.T) { CheckDestroy: testAccCheckLocationFSxOpenZFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxOpenZFSConfig(), + Config: testAccLocationFSxOpenZFSFileSystemConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxOpenZFSExists(resourceName, &locationFsxOpenZfs1), acctest.CheckResourceDisappears(acctest.Provider, tfdatasync.ResourceLocationFSxOpenZFSFileSystem(), resourceName), @@ -94,7 +94,7 @@ func TestAccDataSyncLocationFSxOpenZFSFileSystem_subdirectory(t *testing.T) { CheckDestroy: testAccCheckLocationFSxOpenZFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxOpenZFSSubdirectoryConfig("/fsx/subdirectory1/"), + Config: testAccLocationFSxOpenZFSFileSystemConfig_subdirectory("/fsx/subdirectory1/"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxOpenZFSExists(resourceName, &locationFsxOpenZfs1), resource.TestCheckResourceAttr(resourceName, "subdirectory", "/fsx/subdirectory1/"), @@ -125,7 +125,7 @@ func TestAccDataSyncLocationFSxOpenZFSFileSystem_tags(t *testing.T) { CheckDestroy: testAccCheckLocationFSxOpenZFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxOpenZFSTags1Config("key1", "value1"), + Config: testAccLocationFSxOpenZFSFileSystemConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxOpenZFSExists(resourceName, &locationFsxOpenZfs1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -139,7 +139,7 @@ func TestAccDataSyncLocationFSxOpenZFSFileSystem_tags(t *testing.T) { ImportStateIdFunc: testAccLocationFSxOpenZFSImportStateID(resourceName), }, { - Config: testAccLocationFSxOpenZFSTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccLocationFSxOpenZFSFileSystemConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxOpenZFSExists(resourceName, &locationFsxOpenZfs1), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -148,7 +148,7 @@ func TestAccDataSyncLocationFSxOpenZFSFileSystem_tags(t *testing.T) { ), }, { - Config: testAccLocationFSxOpenZFSTags1Config("key1", "value1"), + Config: testAccLocationFSxOpenZFSFileSystemConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxOpenZFSExists(resourceName, &locationFsxOpenZfs1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -167,7 +167,7 @@ func testAccCheckLocationFSxOpenZFSDestroy(s *terraform.State) error { continue } - _, err := tfdatasync.FindFsxOpenZfsLocationByARN(conn, rs.Primary.ID) + _, err := tfdatasync.FindFSxOpenZFSLocationByARN(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -191,7 +191,7 @@ func testAccCheckLocationFSxOpenZFSExists(resourceName string, locationFsxOpenZf } conn := acctest.Provider.Meta().(*conns.AWSClient).DataSyncConn - output, err := tfdatasync.FindFsxOpenZfsLocationByARN(conn, rs.Primary.ID) + output, err := tfdatasync.FindFSxOpenZFSLocationByARN(conn, rs.Primary.ID) if err != nil { return err @@ -218,7 +218,7 @@ func testAccLocationFSxOpenZFSImportStateID(resourceName string) resource.Import } } -func testAccLocationFSxOpenZFSConfig() string { +func testAccLocationFSxOpenZFSFileSystemConfig_basic() string { return acctest.ConfigCompose(testAccFSxOpenZfsFileSystemBaseConfig(), ` resource "aws_datasync_location_fsx_openzfs_file_system" "test" { fsx_filesystem_arn = aws_fsx_openzfs_file_system.test.arn @@ -235,7 +235,7 @@ resource "aws_datasync_location_fsx_openzfs_file_system" "test" { `) } -func testAccLocationFSxOpenZFSSubdirectoryConfig(subdirectory string) string { +func testAccLocationFSxOpenZFSFileSystemConfig_subdirectory(subdirectory string) string { return acctest.ConfigCompose(testAccFSxOpenZfsFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_datasync_location_fsx_openzfs_file_system" "test" { fsx_filesystem_arn = aws_fsx_openzfs_file_system.test.arn @@ -253,7 +253,7 @@ resource "aws_datasync_location_fsx_openzfs_file_system" "test" { `, subdirectory)) } -func testAccLocationFSxOpenZFSTags1Config(key1, value1 string) string { +func testAccLocationFSxOpenZFSFileSystemConfig_tags1(key1, value1 string) string { return acctest.ConfigCompose(testAccFSxOpenZfsFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_datasync_location_fsx_openzfs_file_system" "test" { fsx_filesystem_arn = aws_fsx_openzfs_file_system.test.arn @@ -274,7 +274,7 @@ resource "aws_datasync_location_fsx_openzfs_file_system" "test" { `, key1, value1)) } -func testAccLocationFSxOpenZFSTags2Config(key1, value1, key2, value2 string) string { +func testAccLocationFSxOpenZFSFileSystemConfig_tags2(key1, value1, key2, value2 string) string { return acctest.ConfigCompose(testAccFSxOpenZfsFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_datasync_location_fsx_openzfs_file_system" "test" { fsx_filesystem_arn = aws_fsx_openzfs_file_system.test.arn diff --git a/internal/service/datasync/location_fsx_windows_file_system_test.go b/internal/service/datasync/location_fsx_windows_file_system_test.go index 2f7b24593b5..437db4e136f 100644 --- a/internal/service/datasync/location_fsx_windows_file_system_test.go +++ b/internal/service/datasync/location_fsx_windows_file_system_test.go @@ -34,7 +34,7 @@ func TestAccDataSyncLocationFSxWindowsFileSystem_basic(t *testing.T) { CheckDestroy: testAccCheckLocationFSxWindowsDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxWindowsConfig(domainName), + Config: testAccLocationFSxWindowsFileSystemConfig_basic(domainName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxWindowsExists(resourceName, &locationFsxWindows1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`location/loc-.+`)), @@ -73,7 +73,7 @@ func TestAccDataSyncLocationFSxWindowsFileSystem_disappears(t *testing.T) { CheckDestroy: testAccCheckLocationFSxWindowsDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxWindowsConfig(domainName), + Config: testAccLocationFSxWindowsFileSystemConfig_basic(domainName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxWindowsExists(resourceName, &locationFsxWindows1), acctest.CheckResourceDisappears(acctest.Provider, tfdatasync.ResourceLocationFSxWindowsFileSystem(), resourceName), @@ -101,7 +101,7 @@ func TestAccDataSyncLocationFSxWindowsFileSystem_subdirectory(t *testing.T) { CheckDestroy: testAccCheckLocationFSxWindowsDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxWindowsSubdirectoryConfig(domainName, "/subdirectory1/"), + Config: testAccLocationFSxWindowsFileSystemConfig_subdirectory(domainName, "/subdirectory1/"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxWindowsExists(resourceName, &locationFsxWindows1), resource.TestCheckResourceAttr(resourceName, "subdirectory", "/subdirectory1/"), @@ -135,7 +135,7 @@ func TestAccDataSyncLocationFSxWindowsFileSystem_tags(t *testing.T) { CheckDestroy: testAccCheckLocationFSxWindowsDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationFSxWindowsTags1Config(domainName, "key1", "value1"), + Config: testAccLocationFSxWindowsFileSystemConfig_tags1(domainName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxWindowsExists(resourceName, &locationFsxWindows1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -150,7 +150,7 @@ func TestAccDataSyncLocationFSxWindowsFileSystem_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"password"}, }, { - Config: testAccLocationFSxWindowsTags2Config(domainName, "key1", "value1updated", "key2", "value2"), + Config: testAccLocationFSxWindowsFileSystemConfig_tags2(domainName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxWindowsExists(resourceName, &locationFsxWindows1), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -159,7 +159,7 @@ func TestAccDataSyncLocationFSxWindowsFileSystem_tags(t *testing.T) { ), }, { - Config: testAccLocationFSxWindowsTags1Config(domainName, "key1", "value1"), + Config: testAccLocationFSxWindowsFileSystemConfig_tags1(domainName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationFSxWindowsExists(resourceName, &locationFsxWindows1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -235,7 +235,7 @@ func testAccLocationFSxWindowsImportStateID(resourceName string) resource.Import } } -func testAccLocationFSxWindowsConfig(domain string) string { +func testAccLocationFSxWindowsFileSystemConfig_basic(domain string) string { return acctest.ConfigCompose(testAccFSxWindowsFileSystemSecurityGroupIds1Config(domain), ` resource "aws_datasync_location_fsx_windows_file_system" "test" { fsx_filesystem_arn = aws_fsx_windows_file_system.test.arn @@ -246,7 +246,7 @@ resource "aws_datasync_location_fsx_windows_file_system" "test" { `) } -func testAccLocationFSxWindowsSubdirectoryConfig(domain, subdirectory string) string { +func testAccLocationFSxWindowsFileSystemConfig_subdirectory(domain, subdirectory string) string { return testAccFSxWindowsFileSystemSecurityGroupIds1Config(domain) + fmt.Sprintf(` resource "aws_datasync_location_fsx_windows_file_system" "test" { fsx_filesystem_arn = aws_fsx_windows_file_system.test.arn @@ -258,7 +258,7 @@ resource "aws_datasync_location_fsx_windows_file_system" "test" { `, subdirectory) } -func testAccLocationFSxWindowsTags1Config(domain, key1, value1 string) string { +func testAccLocationFSxWindowsFileSystemConfig_tags1(domain, key1, value1 string) string { return testAccFSxWindowsFileSystemSecurityGroupIds1Config(domain) + fmt.Sprintf(` resource "aws_datasync_location_fsx_windows_file_system" "test" { fsx_filesystem_arn = aws_fsx_windows_file_system.test.arn @@ -273,7 +273,7 @@ resource "aws_datasync_location_fsx_windows_file_system" "test" { `, key1, value1) } -func testAccLocationFSxWindowsTags2Config(domain, key1, value1, key2, value2 string) string { +func testAccLocationFSxWindowsFileSystemConfig_tags2(domain, key1, value1, key2, value2 string) string { return testAccFSxWindowsFileSystemSecurityGroupIds1Config(domain) + fmt.Sprintf(` resource "aws_datasync_location_fsx_windows_file_system" "test" { fsx_filesystem_arn = aws_fsx_windows_file_system.test.arn diff --git a/internal/service/datasync/location_nfs_test.go b/internal/service/datasync/location_nfs_test.go index 01b1946bc15..11051785fe1 100644 --- a/internal/service/datasync/location_nfs_test.go +++ b/internal/service/datasync/location_nfs_test.go @@ -28,7 +28,7 @@ func TestAccDataSyncLocationNFS_basic(t *testing.T) { CheckDestroy: testAccCheckLocationNFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationNFSConfig(rName), + Config: testAccLocationNFSConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`location/loc-.+`)), @@ -64,7 +64,7 @@ func TestAccDataSyncLocationNFS_mountOptions(t *testing.T) { CheckDestroy: testAccCheckLocationNFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationNFSMountOptionsConfig(rName, "NFS4_0"), + Config: testAccLocationNFSConfig_mountOptions(rName, "NFS4_0"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs1), resource.TestCheckResourceAttr(resourceName, "mount_options.0.version", "NFS4_0"), @@ -77,7 +77,7 @@ func TestAccDataSyncLocationNFS_mountOptions(t *testing.T) { ImportStateVerifyIgnore: []string{"server_hostname"}, }, { - Config: testAccLocationNFSMountOptionsConfig(rName, "NFS4_1"), + Config: testAccLocationNFSConfig_mountOptions(rName, "NFS4_1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs1), resource.TestCheckResourceAttr(resourceName, "mount_options.0.version", "NFS4_1"), @@ -99,7 +99,7 @@ func TestAccDataSyncLocationNFS_disappears(t *testing.T) { CheckDestroy: testAccCheckLocationNFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationNFSConfig(rName), + Config: testAccLocationNFSConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs1), testAccCheckLocationNFSDisappears(&locationNfs1), @@ -122,7 +122,7 @@ func TestAccDataSyncLocationNFS_AgentARNs_multiple(t *testing.T) { CheckDestroy: testAccCheckLocationNFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationNFSAgentARNsMultipleConfig(rName), + Config: testAccLocationNFSConfig_agentARNsMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs1), resource.TestCheckResourceAttr(resourceName, "on_prem_config.#", "1"), @@ -151,7 +151,7 @@ func TestAccDataSyncLocationNFS_subdirectory(t *testing.T) { CheckDestroy: testAccCheckLocationNFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationNFSSubdirectoryConfig(rName, "/subdirectory1/"), + Config: testAccLocationNFSConfig_subdirectory(rName, "/subdirectory1/"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs1), resource.TestCheckResourceAttr(resourceName, "subdirectory", "/subdirectory1/"), @@ -164,7 +164,7 @@ func TestAccDataSyncLocationNFS_subdirectory(t *testing.T) { ImportStateVerifyIgnore: []string{"server_hostname"}, }, { - Config: testAccLocationNFSSubdirectoryConfig(rName, "/subdirectory2/"), + Config: testAccLocationNFSConfig_subdirectory(rName, "/subdirectory2/"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs1), resource.TestCheckResourceAttr(resourceName, "subdirectory", "/subdirectory2/"), @@ -186,7 +186,7 @@ func TestAccDataSyncLocationNFS_tags(t *testing.T) { CheckDestroy: testAccCheckLocationNFSDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationNFSTags1Config(rName, "key1", "value1"), + Config: testAccLocationNFSConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -200,7 +200,7 @@ func TestAccDataSyncLocationNFS_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"server_hostname"}, }, { - Config: testAccLocationNFSTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccLocationNFSConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs2), testAccCheckLocationNFSNotRecreated(&locationNfs1, &locationNfs2), @@ -210,7 +210,7 @@ func TestAccDataSyncLocationNFS_tags(t *testing.T) { ), }, { - Config: testAccLocationNFSTags1Config(rName, "key1", "value1"), + Config: testAccLocationNFSConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationNFSExists(resourceName, &locationNfs3), testAccCheckLocationNFSNotRecreated(&locationNfs2, &locationNfs3), @@ -400,7 +400,7 @@ resource "aws_datasync_agent" "test" { `, rName) } -func testAccLocationNFSConfig(rName string) string { +func testAccLocationNFSConfig_basic(rName string) string { return testAccLocationNFSBaseConfig(rName) + ` resource "aws_datasync_location_nfs" "test" { server_hostname = "example.com" @@ -413,7 +413,7 @@ resource "aws_datasync_location_nfs" "test" { ` } -func testAccLocationNFSMountOptionsConfig(rName, option string) string { +func testAccLocationNFSConfig_mountOptions(rName, option string) string { return testAccLocationNFSBaseConfig(rName) + fmt.Sprintf(` resource "aws_datasync_location_nfs" "test" { server_hostname = "example.com" @@ -430,7 +430,7 @@ resource "aws_datasync_location_nfs" "test" { `, option) } -func testAccLocationNFSAgentARNsMultipleConfig(rName string) string { +func testAccLocationNFSConfig_agentARNsMultiple(rName string) string { return testAccLocationNFSBaseConfig(rName) + fmt.Sprintf(` resource "aws_instance" "test2" { depends_on = [aws_internet_gateway.test] @@ -467,7 +467,7 @@ resource "aws_datasync_location_nfs" "test" { `, rName) } -func testAccLocationNFSSubdirectoryConfig(rName, subdirectory string) string { +func testAccLocationNFSConfig_subdirectory(rName, subdirectory string) string { return testAccLocationNFSBaseConfig(rName) + fmt.Sprintf(` resource "aws_datasync_location_nfs" "test" { server_hostname = "example.com" @@ -480,7 +480,7 @@ resource "aws_datasync_location_nfs" "test" { `, subdirectory) } -func testAccLocationNFSTags1Config(rName, key1, value1 string) string { +func testAccLocationNFSConfig_tags1(rName, key1, value1 string) string { return testAccLocationNFSBaseConfig(rName) + fmt.Sprintf(` resource "aws_datasync_location_nfs" "test" { server_hostname = "example.com" @@ -497,7 +497,7 @@ resource "aws_datasync_location_nfs" "test" { `, key1, value1) } -func testAccLocationNFSTags2Config(rName, key1, value1, key2, value2 string) string { +func testAccLocationNFSConfig_tags2(rName, key1, value1, key2, value2 string) string { return testAccLocationNFSBaseConfig(rName) + fmt.Sprintf(` resource "aws_datasync_location_nfs" "test" { server_hostname = "example.com" diff --git a/internal/service/datasync/location_s3_test.go b/internal/service/datasync/location_s3_test.go index f8d1b60ce09..7d3e02c8e5f 100644 --- a/internal/service/datasync/location_s3_test.go +++ b/internal/service/datasync/location_s3_test.go @@ -31,7 +31,7 @@ func TestAccDataSyncLocationS3_basic(t *testing.T) { CheckDestroy: testAccCheckLocationS3Destroy, Steps: []resource.TestStep{ { - Config: testAccLocationS3Config(rName), + Config: testAccLocationS3Config_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationS3Exists(resourceName, &locationS31), resource.TestCheckResourceAttr(resourceName, "agent_arns.#", "0"), @@ -69,7 +69,7 @@ func TestAccDataSyncLocationS3_storageClass(t *testing.T) { CheckDestroy: testAccCheckLocationS3Destroy, Steps: []resource.TestStep{ { - Config: testAccLocationS3StorageClassConfig(rName), + Config: testAccLocationS3Config_storageClass(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationS3Exists(resourceName, &locationS31), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`location/loc-.+`)), @@ -103,7 +103,7 @@ func TestAccDataSyncLocationS3_disappears(t *testing.T) { CheckDestroy: testAccCheckLocationS3Destroy, Steps: []resource.TestStep{ { - Config: testAccLocationS3Config(rName), + Config: testAccLocationS3Config_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocationS3Exists(resourceName, &locationS31), acctest.CheckResourceDisappears(acctest.Provider, tfdatasync.ResourceLocationS3(), resourceName), @@ -126,7 +126,7 @@ func TestAccDataSyncLocationS3_tags(t *testing.T) { CheckDestroy: testAccCheckLocationS3Destroy, Steps: []resource.TestStep{ { - Config: testAccLocationS3Tags1Config(rName, "key1", "value1"), + Config: testAccLocationS3Config_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationS3Exists(resourceName, &locationS31), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -140,7 +140,7 @@ func TestAccDataSyncLocationS3_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"s3_bucket_arn"}, }, { - Config: testAccLocationS3Tags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccLocationS3Config_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationS3Exists(resourceName, &locationS32), testAccCheckLocationS3NotRecreated(&locationS31, &locationS32), @@ -150,7 +150,7 @@ func TestAccDataSyncLocationS3_tags(t *testing.T) { ), }, { - Config: testAccLocationS3Tags1Config(rName, "key1", "value1"), + Config: testAccLocationS3Config_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationS3Exists(resourceName, &locationS33), testAccCheckLocationS3NotRecreated(&locationS32, &locationS33), @@ -273,7 +273,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccLocationS3Config(rName string) string { +func testAccLocationS3Config_basic(rName string) string { return testAccLocationS3BaseConfig(rName) + ` resource "aws_datasync_location_s3" "test" { s3_bucket_arn = aws_s3_bucket.test.arn @@ -286,7 +286,7 @@ resource "aws_datasync_location_s3" "test" { ` } -func testAccLocationS3StorageClassConfig(rName string) string { +func testAccLocationS3Config_storageClass(rName string) string { return testAccLocationS3BaseConfig(rName) + ` resource "aws_datasync_location_s3" "test" { s3_bucket_arn = aws_s3_bucket.test.arn @@ -300,7 +300,7 @@ resource "aws_datasync_location_s3" "test" { ` } -func testAccLocationS3Tags1Config(rName, key1, value1 string) string { +func testAccLocationS3Config_tags1(rName, key1, value1 string) string { return testAccLocationS3BaseConfig(rName) + fmt.Sprintf(` resource "aws_datasync_location_s3" "test" { s3_bucket_arn = aws_s3_bucket.test.arn @@ -317,7 +317,7 @@ resource "aws_datasync_location_s3" "test" { `, key1, value1) } -func testAccLocationS3Tags2Config(rName, key1, value1, key2, value2 string) string { +func testAccLocationS3Config_tags2(rName, key1, value1, key2, value2 string) string { return testAccLocationS3BaseConfig(rName) + fmt.Sprintf(` resource "aws_datasync_location_s3" "test" { s3_bucket_arn = aws_s3_bucket.test.arn diff --git a/internal/service/datasync/location_smb_test.go b/internal/service/datasync/location_smb_test.go index c3f0c5b413c..acba095cca0 100644 --- a/internal/service/datasync/location_smb_test.go +++ b/internal/service/datasync/location_smb_test.go @@ -29,7 +29,7 @@ func TestAccDataSyncLocationSMB_basic(t *testing.T) { CheckDestroy: testAccCheckLocationSMBDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationSMBConfig(rName, "/test/"), + Config: testAccLocationSMBConfig_basic(rName, "/test/"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationSMBExists(resourceName, &locationSmb1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`location/loc-.+`)), @@ -48,7 +48,7 @@ func TestAccDataSyncLocationSMB_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"password", "server_hostname"}, }, { - Config: testAccLocationSMBConfig(rName, "/test2/"), + Config: testAccLocationSMBConfig_basic(rName, "/test2/"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationSMBExists(resourceName, &locationSmb1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`location/loc-.+`)), @@ -76,7 +76,7 @@ func TestAccDataSyncLocationSMB_disappears(t *testing.T) { CheckDestroy: testAccCheckLocationSMBDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationSMBConfig(rName, "/test/"), + Config: testAccLocationSMBConfig_basic(rName, "/test/"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationSMBExists(resourceName, &locationSmb1), testAccCheckLocationSMBDisappears(&locationSmb1), @@ -99,7 +99,7 @@ func TestAccDataSyncLocationSMB_tags(t *testing.T) { CheckDestroy: testAccCheckLocationSMBDestroy, Steps: []resource.TestStep{ { - Config: testAccLocationSMBTags1Config(rName, "key1", "value1"), + Config: testAccLocationSMBConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationSMBExists(resourceName, &locationSmb1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -113,7 +113,7 @@ func TestAccDataSyncLocationSMB_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"password", "server_hostname"}, }, { - Config: testAccLocationSMBTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccLocationSMBConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationSMBExists(resourceName, &locationSmb2), testAccCheckLocationSMBNotRecreated(&locationSmb1, &locationSmb2), @@ -123,7 +123,7 @@ func TestAccDataSyncLocationSMB_tags(t *testing.T) { ), }, { - Config: testAccLocationSMBTags1Config(rName, "key1", "value1"), + Config: testAccLocationSMBConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocationSMBExists(resourceName, &locationSmb3), testAccCheckLocationSMBNotRecreated(&locationSmb2, &locationSmb3), @@ -306,7 +306,7 @@ resource "aws_datasync_agent" "test" { `, rName)) } -func testAccLocationSMBConfig(rName, dir string) string { +func testAccLocationSMBConfig_basic(rName, dir string) string { return testAccLocationSMBBaseConfig(rName) + fmt.Sprintf(` resource "aws_datasync_location_smb" "test" { agent_arns = [aws_datasync_agent.test.arn] @@ -318,7 +318,7 @@ resource "aws_datasync_location_smb" "test" { `, dir) } -func testAccLocationSMBTags1Config(rName, key1, value1 string) string { +func testAccLocationSMBConfig_tags1(rName, key1, value1 string) string { return testAccLocationSMBBaseConfig(rName) + fmt.Sprintf(` resource "aws_datasync_location_smb" "test" { agent_arns = [aws_datasync_agent.test.arn] @@ -334,7 +334,7 @@ resource "aws_datasync_location_smb" "test" { `, key1, value1) } -func testAccLocationSMBTags2Config(rName, key1, value1, key2, value2 string) string { +func testAccLocationSMBConfig_tags2(rName, key1, value1, key2, value2 string) string { return testAccLocationSMBBaseConfig(rName) + fmt.Sprintf(` resource "aws_datasync_location_smb" "test" { agent_arns = [aws_datasync_agent.test.arn] diff --git a/internal/service/datasync/task_test.go b/internal/service/datasync/task_test.go index fbf0b0abbcc..b4f43878053 100644 --- a/internal/service/datasync/task_test.go +++ b/internal/service/datasync/task_test.go @@ -31,7 +31,7 @@ func TestAccDataSyncTask_basic(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskConfig(rName), + Config: testAccTaskConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "datasync", regexp.MustCompile(`task/task-.+`)), @@ -79,7 +79,7 @@ func TestAccDataSyncTask_disappears(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskConfig(rName), + Config: testAccTaskConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), acctest.CheckResourceDisappears(acctest.Provider, tfdatasync.ResourceTask(), resourceName), @@ -102,7 +102,7 @@ func TestAccDataSyncTask_schedule(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskScheduleConfig(rName, "cron(0 12 ? * SUN,WED *)"), + Config: testAccTaskConfig_schedule(rName, "cron(0 12 ? * SUN,WED *)"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "schedule.#", "1"), @@ -115,7 +115,7 @@ func TestAccDataSyncTask_schedule(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskScheduleConfig(rName, "cron(0 12 ? * SUN,MON *)"), + Config: testAccTaskConfig_schedule(rName, "cron(0 12 ? * SUN,MON *)"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "schedule.#", "1"), @@ -138,7 +138,7 @@ func TestAccDataSyncTask_cloudWatchLogGroupARN(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskCloudWatchLogGroupARNConfig(rName), + Config: testAccTaskConfig_cloudWatchLogGroupARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttrPair(resourceName, "cloudwatch_log_group_arn", "aws_cloudwatch_log_group.test1", "arn"), @@ -150,7 +150,7 @@ func TestAccDataSyncTask_cloudWatchLogGroupARN(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskCloudWatchLogGroupARN2Config(rName), + Config: testAccTaskConfig_cloudWatchLogGroupARN2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttrPair(resourceName, "cloudwatch_log_group_arn", "aws_cloudwatch_log_group.test2", "arn")), @@ -171,7 +171,7 @@ func TestAccDataSyncTask_excludes(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskExcludesConfig(rName, "/folder1|/folder2"), + Config: testAccTaskConfig_excludes(rName, "/folder1|/folder2"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "excludes.#", "1"), @@ -185,7 +185,7 @@ func TestAccDataSyncTask_excludes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskExcludesConfig(rName, "/test"), + Config: testAccTaskConfig_excludes(rName, "/test"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "excludes.#", "1"), @@ -209,7 +209,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_atimeMtime(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsAtimeMtimeConfig(rName, "NONE", "NONE"), + Config: testAccTaskConfig_defaultSyncOptionsAtimeMtime(rName, "NONE", "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -223,7 +223,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_atimeMtime(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsAtimeMtimeConfig(rName, "BEST_EFFORT", "PRESERVE"), + Config: testAccTaskConfig_defaultSyncOptionsAtimeMtime(rName, "BEST_EFFORT", "PRESERVE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -248,7 +248,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_bytesPerSecond(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsBytesPerSecondConfig(rName, 1), + Config: testAccTaskConfig_defaultSyncOptionsBytesPerSecond(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -261,7 +261,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_bytesPerSecond(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsBytesPerSecondConfig(rName, 2), + Config: testAccTaskConfig_defaultSyncOptionsBytesPerSecond(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -285,7 +285,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_gid(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsGidConfig(rName, "NONE"), + Config: testAccTaskConfig_defaultSyncOptionsGID(rName, "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -298,7 +298,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_gid(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsGidConfig(rName, "INT_VALUE"), + Config: testAccTaskConfig_defaultSyncOptionsGID(rName, "INT_VALUE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -322,7 +322,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_logLevel(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsLogLevelConfig(rName, "OFF"), + Config: testAccTaskConfig_defaultSyncOptionsLogLevel(rName, "OFF"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -335,7 +335,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_logLevel(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsLogLevelConfig(rName, "BASIC"), + Config: testAccTaskConfig_defaultSyncOptionsLogLevel(rName, "BASIC"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -359,7 +359,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_overwriteMode(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsOverwriteModeConfig(rName, "NEVER"), + Config: testAccTaskConfig_defaultSyncOptionsOverwriteMode(rName, "NEVER"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -372,7 +372,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_overwriteMode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsOverwriteModeConfig(rName, "ALWAYS"), + Config: testAccTaskConfig_defaultSyncOptionsOverwriteMode(rName, "ALWAYS"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -396,7 +396,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_posixPermissions(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsPOSIXPermissionsConfig(rName, "NONE"), + Config: testAccTaskConfig_defaultSyncOptionsPOSIXPermissions(rName, "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -409,7 +409,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_posixPermissions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsPOSIXPermissionsConfig(rName, "PRESERVE"), + Config: testAccTaskConfig_defaultSyncOptionsPOSIXPermissions(rName, "PRESERVE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -433,7 +433,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_preserveDeletedFiles(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsPreserveDeletedFilesConfig(rName, "REMOVE"), + Config: testAccTaskConfig_defaultSyncOptionsPreserveDeletedFiles(rName, "REMOVE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -446,7 +446,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_preserveDeletedFiles(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsPreserveDeletedFilesConfig(rName, "PRESERVE"), + Config: testAccTaskConfig_defaultSyncOptionsPreserveDeletedFiles(rName, "PRESERVE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -470,7 +470,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_preserveDevices(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsPreserveDevicesConfig(rName, "PRESERVE"), + Config: testAccTaskConfig_defaultSyncOptionsPreserveDevices(rName, "PRESERVE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -483,7 +483,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_preserveDevices(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsPreserveDevicesConfig(rName, "NONE"), + Config: testAccTaskConfig_defaultSyncOptionsPreserveDevices(rName, "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -507,7 +507,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_taskQueueing(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsTaskQueueingConfig(rName, "ENABLED"), + Config: testAccTaskConfig_defaultSyncOptionsQueueing(rName, "ENABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -520,7 +520,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_taskQueueing(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsTaskQueueingConfig(rName, "DISABLED"), + Config: testAccTaskConfig_defaultSyncOptionsQueueing(rName, "DISABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -544,7 +544,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_transferMode(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsTransferModeConfig(rName, "CHANGED"), + Config: testAccTaskConfig_defaultSyncOptionsTransferMode(rName, "CHANGED"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -557,7 +557,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_transferMode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsTransferModeConfig(rName, "ALL"), + Config: testAccTaskConfig_defaultSyncOptionsTransferMode(rName, "ALL"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -581,7 +581,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_uid(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsUIDConfig(rName, "NONE"), + Config: testAccTaskConfig_defaultSyncOptionsUID(rName, "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -594,7 +594,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_uid(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsUIDConfig(rName, "INT_VALUE"), + Config: testAccTaskConfig_defaultSyncOptionsUID(rName, "INT_VALUE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -618,7 +618,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_verifyMode(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefaultSyncOptionsVerifyModeConfig(rName, "NONE"), + Config: testAccTaskConfig_defaultSyncOptionsVerifyMode(rName, "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -631,7 +631,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_verifyMode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskDefaultSyncOptionsVerifyModeConfig(rName, "POINT_IN_TIME_CONSISTENT"), + Config: testAccTaskConfig_defaultSyncOptionsVerifyMode(rName, "POINT_IN_TIME_CONSISTENT"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -640,7 +640,7 @@ func TestAccDataSyncTask_DefaultSyncOptions_verifyMode(t *testing.T) { ), }, { - Config: testAccTaskDefaultSyncOptionsVerifyModeConfig(rName, "ONLY_FILES_TRANSFERRED"), + Config: testAccTaskConfig_defaultSyncOptionsVerifyMode(rName, "ONLY_FILES_TRANSFERRED"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task3), testAccCheckTaskNotRecreated(&task2, &task3), @@ -665,7 +665,7 @@ func TestAccDataSyncTask_tags(t *testing.T) { CheckDestroy: testAccCheckTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskTags1Config(rName, "key1", "value1"), + Config: testAccTaskConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -678,7 +678,7 @@ func TestAccDataSyncTask_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTaskTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTaskConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task2), testAccCheckTaskNotRecreated(&task1, &task2), @@ -688,7 +688,7 @@ func TestAccDataSyncTask_tags(t *testing.T) { ), }, { - Config: testAccTaskTags1Config(rName, "key1", "value1"), + Config: testAccTaskConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskExists(resourceName, &task3), testAccCheckTaskNotRecreated(&task2, &task3), @@ -948,7 +948,7 @@ resource "aws_datasync_location_nfs" "source" { `, rName)) } -func testAccTaskConfig(rName string) string { +func testAccTaskConfig_basic(rName string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -961,7 +961,7 @@ resource "aws_datasync_task" "test" { `, rName)) } -func testAccTaskScheduleConfig(rName, cron string) string { +func testAccTaskConfig_schedule(rName, cron string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -978,7 +978,7 @@ resource "aws_datasync_task" "test" { `, rName, cron)) } -func testAccTaskCloudWatchLogGroupARNConfig(rName string) string { +func testAccTaskConfig_cloudWatchLogGroupARN(rName string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -996,7 +996,7 @@ resource "aws_datasync_task" "test" { `, rName)) } -func testAccTaskCloudWatchLogGroupARN2Config(rName string) string { +func testAccTaskConfig_cloudWatchLogGroupARN2(rName string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1018,7 +1018,7 @@ resource "aws_datasync_task" "test" { `, rName)) } -func testAccTaskExcludesConfig(rName, value string) string { +func testAccTaskConfig_excludes(rName, value string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1036,7 +1036,7 @@ resource "aws_datasync_task" "test" { `, rName, value)) } -func testAccTaskDefaultSyncOptionsAtimeMtimeConfig(rName, atime, mtime string) string { +func testAccTaskConfig_defaultSyncOptionsAtimeMtime(rName, atime, mtime string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1054,7 +1054,7 @@ resource "aws_datasync_task" "test" { `, rName, atime, mtime)) } -func testAccTaskDefaultSyncOptionsBytesPerSecondConfig(rName string, bytesPerSecond int) string { +func testAccTaskConfig_defaultSyncOptionsBytesPerSecond(rName string, bytesPerSecond int) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1071,7 +1071,7 @@ resource "aws_datasync_task" "test" { `, rName, bytesPerSecond)) } -func testAccTaskDefaultSyncOptionsGidConfig(rName, gid string) string { +func testAccTaskConfig_defaultSyncOptionsGID(rName, gid string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1088,7 +1088,7 @@ resource "aws_datasync_task" "test" { `, rName, gid)) } -func testAccTaskDefaultSyncOptionsLogLevelConfig(rName, logLevel string) string { +func testAccTaskConfig_defaultSyncOptionsLogLevel(rName, logLevel string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1110,7 +1110,7 @@ resource "aws_datasync_task" "test" { `, rName, logLevel)) } -func testAccTaskDefaultSyncOptionsOverwriteModeConfig(rName, overwriteMode string) string { +func testAccTaskConfig_defaultSyncOptionsOverwriteMode(rName, overwriteMode string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1127,7 +1127,7 @@ resource "aws_datasync_task" "test" { `, rName, overwriteMode)) } -func testAccTaskDefaultSyncOptionsPOSIXPermissionsConfig(rName, posixPermissions string) string { +func testAccTaskConfig_defaultSyncOptionsPOSIXPermissions(rName, posixPermissions string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1144,7 +1144,7 @@ resource "aws_datasync_task" "test" { `, rName, posixPermissions)) } -func testAccTaskDefaultSyncOptionsPreserveDeletedFilesConfig(rName, preserveDeletedFiles string) string { +func testAccTaskConfig_defaultSyncOptionsPreserveDeletedFiles(rName, preserveDeletedFiles string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1161,7 +1161,7 @@ resource "aws_datasync_task" "test" { `, rName, preserveDeletedFiles)) } -func testAccTaskDefaultSyncOptionsPreserveDevicesConfig(rName, preserveDevices string) string { +func testAccTaskConfig_defaultSyncOptionsPreserveDevices(rName, preserveDevices string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1178,7 +1178,7 @@ resource "aws_datasync_task" "test" { `, rName, preserveDevices)) } -func testAccTaskDefaultSyncOptionsTaskQueueingConfig(rName, taskQueueing string) string { +func testAccTaskConfig_defaultSyncOptionsQueueing(rName, taskQueueing string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1195,7 +1195,7 @@ resource "aws_datasync_task" "test" { `, rName, taskQueueing)) } -func testAccTaskDefaultSyncOptionsTransferModeConfig(rName, transferMode string) string { +func testAccTaskConfig_defaultSyncOptionsTransferMode(rName, transferMode string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1212,7 +1212,7 @@ resource "aws_datasync_task" "test" { `, rName, transferMode)) } -func testAccTaskDefaultSyncOptionsUIDConfig(rName, uid string) string { +func testAccTaskConfig_defaultSyncOptionsUID(rName, uid string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1229,7 +1229,7 @@ resource "aws_datasync_task" "test" { `, rName, uid)) } -func testAccTaskDefaultSyncOptionsVerifyModeConfig(rName, verifyMode string) string { +func testAccTaskConfig_defaultSyncOptionsVerifyMode(rName, verifyMode string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1246,7 +1246,7 @@ resource "aws_datasync_task" "test" { `, rName, verifyMode)) } -func testAccTaskTags1Config(rName, key1, value1 string) string { +func testAccTaskConfig_tags1(rName, key1, value1 string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), @@ -1263,7 +1263,7 @@ resource "aws_datasync_task" "test" { `, rName, key1, value1)) } -func testAccTaskTags2Config(rName, key1, value1, key2, value2 string) string { +func testAccTaskConfig_tags2(rName, key1, value1, key2, value2 string) string { return acctest.ConfigCompose( testAccTaskDestinationLocationS3BaseConfig(rName), testAccTaskSourceLocationNFSBaseConfig(rName), diff --git a/internal/service/dax/cluster_test.go b/internal/service/dax/cluster_test.go index 07fd1711316..68763a2ad08 100644 --- a/internal/service/dax/cluster_test.go +++ b/internal/service/dax/cluster_test.go @@ -28,7 +28,7 @@ func TestAccDAXCluster_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rString), + Config: testAccClusterConfig_basic(rString), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dc), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "dax", regexp.MustCompile("cache/.+")), @@ -84,7 +84,7 @@ func TestAccDAXCluster_resize(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterResizeConfig_singleNode(rString), + Config: testAccClusterConfig_resizeSingleNode(rString), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dc), resource.TestCheckResourceAttr( @@ -97,7 +97,7 @@ func TestAccDAXCluster_resize(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterResizeConfig_multiNode(rString), + Config: testAccClusterConfig_resizeMultiNode(rString), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dc), resource.TestCheckResourceAttr( @@ -105,7 +105,7 @@ func TestAccDAXCluster_resize(t *testing.T) { ), }, { - Config: testAccClusterResizeConfig_singleNode(rString), + Config: testAccClusterConfig_resizeSingleNode(rString), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dc), resource.TestCheckResourceAttr( @@ -128,7 +128,7 @@ func TestAccDAXCluster_Encryption_disabled(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterWithEncryptionConfig(rString, false), + Config: testAccClusterConfig_encryption(rString, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dc), resource.TestCheckResourceAttr(resourceName, "server_side_encryption.#", "1"), @@ -142,7 +142,7 @@ func TestAccDAXCluster_Encryption_disabled(t *testing.T) { }, // Ensure it shows no difference when removing server_side_encryption configuration { - Config: testAccClusterConfig(rString), + Config: testAccClusterConfig_basic(rString), PlanOnly: true, ExpectNonEmptyPlan: false, }, @@ -162,7 +162,7 @@ func TestAccDAXCluster_Encryption_enabled(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterWithEncryptionConfig(rString, true), + Config: testAccClusterConfig_encryption(rString, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dc), resource.TestCheckResourceAttr(resourceName, "server_side_encryption.#", "1"), @@ -176,7 +176,7 @@ func TestAccDAXCluster_Encryption_enabled(t *testing.T) { }, // Ensure it shows a difference when removing server_side_encryption configuration { - Config: testAccClusterConfig(rString), + Config: testAccClusterConfig_basic(rString), PlanOnly: true, ExpectNonEmptyPlan: true, }, @@ -197,7 +197,7 @@ func TestAccDAXCluster_EndpointEncryption_disabled(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterWithEndpointEncryptionConfig(rString, clusterEndpointEncryptionType), + Config: testAccClusterConfig_endpointEncryption(rString, clusterEndpointEncryptionType), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dc), resource.TestCheckResourceAttr(resourceName, "cluster_endpoint_encryption_type", clusterEndpointEncryptionType), @@ -210,7 +210,7 @@ func TestAccDAXCluster_EndpointEncryption_disabled(t *testing.T) { }, // Ensure it shows no difference when removing cluster_endpoint_encryption_type configuration { - Config: testAccClusterConfig(rString), + Config: testAccClusterConfig_basic(rString), PlanOnly: true, ExpectNonEmptyPlan: false, }, @@ -231,7 +231,7 @@ func TestAccDAXCluster_EndpointEncryption_enabled(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterWithEndpointEncryptionConfig(rString, clusterEndpointEncryptionType), + Config: testAccClusterConfig_endpointEncryption(rString, clusterEndpointEncryptionType), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dc), resource.TestCheckResourceAttr(resourceName, "cluster_endpoint_encryption_type", clusterEndpointEncryptionType), @@ -244,7 +244,7 @@ func TestAccDAXCluster_EndpointEncryption_enabled(t *testing.T) { }, // Ensure it shows a difference when removing cluster_endpoint_encryption_type configuration { - Config: testAccClusterConfig(rString), + Config: testAccClusterConfig_basic(rString), PlanOnly: true, ExpectNonEmptyPlan: true, }, @@ -357,7 +357,7 @@ EOF } ` -func testAccClusterConfig(rString string) string { +func testAccClusterConfig_basic(rString string) string { return fmt.Sprintf(`%s resource "aws_dax_cluster" "test" { cluster_name = "tf-%s" @@ -373,7 +373,7 @@ resource "aws_dax_cluster" "test" { `, baseConfig, rString) } -func testAccClusterWithEncryptionConfig(rString string, enabled bool) string { +func testAccClusterConfig_encryption(rString string, enabled bool) string { return fmt.Sprintf(`%s resource "aws_dax_cluster" "test" { cluster_name = "tf-%s" @@ -393,7 +393,7 @@ resource "aws_dax_cluster" "test" { `, baseConfig, rString, enabled) } -func testAccClusterWithEndpointEncryptionConfig(rString string, encryptionType string) string { +func testAccClusterConfig_endpointEncryption(rString string, encryptionType string) string { return fmt.Sprintf(`%s resource "aws_dax_cluster" "test" { cluster_name = "tf-%s" @@ -410,7 +410,7 @@ resource "aws_dax_cluster" "test" { `, baseConfig, rString, encryptionType) } -func testAccClusterResizeConfig_singleNode(rString string) string { +func testAccClusterConfig_resizeSingleNode(rString string) string { return fmt.Sprintf(`%s resource "aws_dax_cluster" "test" { cluster_name = "tf-%s" @@ -421,7 +421,7 @@ resource "aws_dax_cluster" "test" { `, baseConfig, rString) } -func testAccClusterResizeConfig_multiNode(rString string) string { +func testAccClusterConfig_resizeMultiNode(rString string) string { return fmt.Sprintf(`%s resource "aws_dax_cluster" "test" { cluster_name = "tf-%s" diff --git a/internal/service/deploy/app_test.go b/internal/service/deploy/app_test.go index fec95726686..f387013c785 100644 --- a/internal/service/deploy/app_test.go +++ b/internal/service/deploy/app_test.go @@ -16,7 +16,7 @@ import ( tfcodedeploy "github.com/hashicorp/terraform-provider-aws/internal/service/deploy" ) -func TestAccCodeDeployApp_basic(t *testing.T) { +func TestAccDeployApp_basic(t *testing.T) { var application1 codedeploy.ApplicationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_codedeploy_app.test" @@ -28,7 +28,7 @@ func TestAccCodeDeployApp_basic(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppNameConfig(rName), + Config: testAccAppConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "codedeploy", fmt.Sprintf(`application:%s`, rName)), @@ -56,7 +56,7 @@ func TestAccCodeDeployApp_basic(t *testing.T) { }) } -func TestAccCodeDeployApp_computePlatform(t *testing.T) { +func TestAccDeployApp_computePlatform(t *testing.T) { var application1, application2 codedeploy.ApplicationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_codedeploy_app.test" @@ -68,14 +68,14 @@ func TestAccCodeDeployApp_computePlatform(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppComputePlatformConfig(rName, "Lambda"), + Config: testAccAppConfig_computePlatform(rName, "Lambda"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application1), resource.TestCheckResourceAttr(resourceName, "compute_platform", "Lambda"), ), }, { - Config: testAccAppComputePlatformConfig(rName, "Server"), + Config: testAccAppConfig_computePlatform(rName, "Server"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application2), testAccCheckAppRecreated(&application1, &application2), @@ -86,7 +86,7 @@ func TestAccCodeDeployApp_computePlatform(t *testing.T) { }) } -func TestAccCodeDeployApp_ComputePlatform_ecs(t *testing.T) { +func TestAccDeployApp_ComputePlatform_ecs(t *testing.T) { var application1 codedeploy.ApplicationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_codedeploy_app.test" @@ -98,7 +98,7 @@ func TestAccCodeDeployApp_ComputePlatform_ecs(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppComputePlatformConfig(rName, "ECS"), + Config: testAccAppConfig_computePlatform(rName, "ECS"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application1), resource.TestCheckResourceAttr(resourceName, "compute_platform", "ECS"), @@ -113,7 +113,7 @@ func TestAccCodeDeployApp_ComputePlatform_ecs(t *testing.T) { }) } -func TestAccCodeDeployApp_ComputePlatform_lambda(t *testing.T) { +func TestAccDeployApp_ComputePlatform_lambda(t *testing.T) { var application1 codedeploy.ApplicationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_codedeploy_app.test" @@ -125,7 +125,7 @@ func TestAccCodeDeployApp_ComputePlatform_lambda(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppComputePlatformConfig(rName, "Lambda"), + Config: testAccAppConfig_computePlatform(rName, "Lambda"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application1), resource.TestCheckResourceAttr(resourceName, "compute_platform", "Lambda"), @@ -140,7 +140,7 @@ func TestAccCodeDeployApp_ComputePlatform_lambda(t *testing.T) { }) } -func TestAccCodeDeployApp_name(t *testing.T) { +func TestAccDeployApp_name(t *testing.T) { var application1, application2 codedeploy.ApplicationInfo rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -153,14 +153,14 @@ func TestAccCodeDeployApp_name(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppNameConfig(rName1), + Config: testAccAppConfig_name(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application1), resource.TestCheckResourceAttr(resourceName, "name", rName1), ), }, { - Config: testAccAppNameConfig(rName2), + Config: testAccAppConfig_name(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application2), resource.TestCheckResourceAttr(resourceName, "name", rName2), @@ -175,7 +175,7 @@ func TestAccCodeDeployApp_name(t *testing.T) { }) } -func TestAccCodeDeployApp_tags(t *testing.T) { +func TestAccDeployApp_tags(t *testing.T) { var application codedeploy.ApplicationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_codedeploy_app.test" @@ -187,7 +187,7 @@ func TestAccCodeDeployApp_tags(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppTags1Config(rName, "key1", "value1"), + Config: testAccAppConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -200,7 +200,7 @@ func TestAccCodeDeployApp_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAppTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAppConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -209,7 +209,7 @@ func TestAccCodeDeployApp_tags(t *testing.T) { ), }, { - Config: testAccAppTags1Config(rName, "key2", "value2"), + Config: testAccAppConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -220,7 +220,7 @@ func TestAccCodeDeployApp_tags(t *testing.T) { }) } -func TestAccCodeDeployApp_disappears(t *testing.T) { +func TestAccDeployApp_disappears(t *testing.T) { var application1 codedeploy.ApplicationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_codedeploy_app.test" @@ -232,7 +232,7 @@ func TestAccCodeDeployApp_disappears(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppNameConfig(rName), + Config: testAccAppConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application1), acctest.CheckResourceDisappears(acctest.Provider, tfcodedeploy.ResourceApp(), resourceName), @@ -308,7 +308,7 @@ func testAccCheckAppRecreated(i, j *codedeploy.ApplicationInfo) resource.TestChe } } -func testAccAppComputePlatformConfig(rName string, computePlatform string) string { +func testAccAppConfig_computePlatform(rName string, computePlatform string) string { return fmt.Sprintf(` resource "aws_codedeploy_app" "test" { compute_platform = %q @@ -317,7 +317,7 @@ resource "aws_codedeploy_app" "test" { `, computePlatform, rName) } -func testAccAppNameConfig(rName string) string { +func testAccAppConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_app" "test" { name = %q @@ -325,7 +325,7 @@ resource "aws_codedeploy_app" "test" { `, rName) } -func testAccAppTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAppConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_codedeploy_app" "test" { name = %[1]q @@ -337,7 +337,7 @@ resource "aws_codedeploy_app" "test" { `, rName, tagKey1, tagValue1) } -func testAccAppTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAppConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_codedeploy_app" "test" { name = %[1]q diff --git a/internal/service/deploy/deployment_config_test.go b/internal/service/deploy/deployment_config_test.go index 24f4539711a..47df680069f 100644 --- a/internal/service/deploy/deployment_config_test.go +++ b/internal/service/deploy/deployment_config_test.go @@ -15,7 +15,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/conns" ) -func TestAccCodeDeployDeploymentConfig_basic(t *testing.T) { +func TestAccDeployDeploymentConfig_basic(t *testing.T) { var config1 codedeploy.DeploymentConfigInfo resourceName := "aws_codedeploy_deployment_config.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -24,12 +24,12 @@ func TestAccCodeDeployDeploymentConfig_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, codedeploy.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDeploymentDestroyConfig, + CheckDestroy: testAccCheckDeploymentConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentFleetConfig(rName, 75), + Config: testAccDeploymentConfigConfig_fleet(rName, 75), Check: resource.ComposeTestCheckFunc( - testAccCheckDeploymentExistsConfig(resourceName, &config1), + testAccCheckDeploymentConfigExists(resourceName, &config1), resource.TestCheckResourceAttr(resourceName, "deployment_config_name", rName), resource.TestCheckResourceAttr(resourceName, "compute_platform", "Server"), resource.TestCheckResourceAttr(resourceName, "traffic_routing_config.#", "0"), @@ -44,7 +44,7 @@ func TestAccCodeDeployDeploymentConfig_basic(t *testing.T) { }) } -func TestAccCodeDeployDeploymentConfig_fleetPercent(t *testing.T) { +func TestAccDeployDeploymentConfig_fleetPercent(t *testing.T) { var config1, config2 codedeploy.DeploymentConfigInfo resourceName := "aws_codedeploy_deployment_config.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -53,12 +53,12 @@ func TestAccCodeDeployDeploymentConfig_fleetPercent(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, codedeploy.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDeploymentDestroyConfig, + CheckDestroy: testAccCheckDeploymentConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentFleetConfig(rName, 75), + Config: testAccDeploymentConfigConfig_fleet(rName, 75), Check: resource.ComposeTestCheckFunc( - testAccCheckDeploymentExistsConfig(resourceName, &config1), + testAccCheckDeploymentConfigExists(resourceName, &config1), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.#", "1"), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.0.type", "FLEET_PERCENT"), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.0.value", "75"), @@ -67,10 +67,10 @@ func TestAccCodeDeployDeploymentConfig_fleetPercent(t *testing.T) { ), }, { - Config: testAccDeploymentFleetConfig(rName, 50), + Config: testAccDeploymentConfigConfig_fleet(rName, 50), Check: resource.ComposeTestCheckFunc( - testAccCheckDeploymentExistsConfig(resourceName, &config2), - testAccCheckDeploymentRecreatedConfig(&config1, &config2), + testAccCheckDeploymentConfigExists(resourceName, &config2), + testAccCheckDeploymentConfigRecreated(&config1, &config2), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.#", "1"), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.0.type", "FLEET_PERCENT"), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.0.value", "50"), @@ -87,7 +87,7 @@ func TestAccCodeDeployDeploymentConfig_fleetPercent(t *testing.T) { }) } -func TestAccCodeDeployDeploymentConfig_hostCount(t *testing.T) { +func TestAccDeployDeploymentConfig_hostCount(t *testing.T) { var config1, config2 codedeploy.DeploymentConfigInfo resourceName := "aws_codedeploy_deployment_config.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -96,12 +96,12 @@ func TestAccCodeDeployDeploymentConfig_hostCount(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, codedeploy.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDeploymentDestroyConfig, + CheckDestroy: testAccCheckDeploymentConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentHostCountConfig(rName, 1), + Config: testAccDeploymentConfigConfig_hostCount(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckDeploymentExistsConfig(resourceName, &config1), + testAccCheckDeploymentConfigExists(resourceName, &config1), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.#", "1"), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.0.type", "HOST_COUNT"), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.0.value", "1"), @@ -110,10 +110,10 @@ func TestAccCodeDeployDeploymentConfig_hostCount(t *testing.T) { ), }, { - Config: testAccDeploymentHostCountConfig(rName, 2), + Config: testAccDeploymentConfigConfig_hostCount(rName, 2), Check: resource.ComposeTestCheckFunc( - testAccCheckDeploymentExistsConfig(resourceName, &config2), - testAccCheckDeploymentRecreatedConfig(&config1, &config2), + testAccCheckDeploymentConfigExists(resourceName, &config2), + testAccCheckDeploymentConfigRecreated(&config1, &config2), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.#", "1"), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.0.type", "HOST_COUNT"), resource.TestCheckResourceAttr(resourceName, "minimum_healthy_hosts.0.value", "2"), @@ -130,7 +130,7 @@ func TestAccCodeDeployDeploymentConfig_hostCount(t *testing.T) { }) } -func TestAccCodeDeployDeploymentConfig_trafficCanary(t *testing.T) { +func TestAccDeployDeploymentConfig_trafficCanary(t *testing.T) { var config1, config2 codedeploy.DeploymentConfigInfo resourceName := "aws_codedeploy_deployment_config.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -139,12 +139,12 @@ func TestAccCodeDeployDeploymentConfig_trafficCanary(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, codedeploy.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDeploymentDestroyConfig, + CheckDestroy: testAccCheckDeploymentConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentTrafficCanaryConfig(rName, 10, 50), + Config: testAccDeploymentConfigConfig_trafficCanary(rName, 10, 50), Check: resource.ComposeTestCheckFunc( - testAccCheckDeploymentExistsConfig(resourceName, &config1), + testAccCheckDeploymentConfigExists(resourceName, &config1), resource.TestCheckResourceAttr(resourceName, "compute_platform", "Lambda"), resource.TestCheckResourceAttr(resourceName, "traffic_routing_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "traffic_routing_config.0.type", "TimeBasedCanary"), @@ -156,10 +156,10 @@ func TestAccCodeDeployDeploymentConfig_trafficCanary(t *testing.T) { ), }, { - Config: testAccDeploymentTrafficCanaryConfig(rName, 3, 10), + Config: testAccDeploymentConfigConfig_trafficCanary(rName, 3, 10), Check: resource.ComposeTestCheckFunc( - testAccCheckDeploymentExistsConfig(resourceName, &config2), - testAccCheckDeploymentRecreatedConfig(&config1, &config2), + testAccCheckDeploymentConfigExists(resourceName, &config2), + testAccCheckDeploymentConfigRecreated(&config1, &config2), resource.TestCheckResourceAttr(resourceName, "compute_platform", "Lambda"), resource.TestCheckResourceAttr(resourceName, "traffic_routing_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "traffic_routing_config.0.type", "TimeBasedCanary"), @@ -179,7 +179,7 @@ func TestAccCodeDeployDeploymentConfig_trafficCanary(t *testing.T) { }) } -func TestAccCodeDeployDeploymentConfig_trafficLinear(t *testing.T) { +func TestAccDeployDeploymentConfig_trafficLinear(t *testing.T) { var config1, config2 codedeploy.DeploymentConfigInfo resourceName := "aws_codedeploy_deployment_config.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -188,12 +188,12 @@ func TestAccCodeDeployDeploymentConfig_trafficLinear(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, codedeploy.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDeploymentDestroyConfig, + CheckDestroy: testAccCheckDeploymentConfigDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentTrafficLinearConfig(rName, 10, 50), + Config: testAccDeploymentConfigConfig_trafficLinear(rName, 10, 50), Check: resource.ComposeTestCheckFunc( - testAccCheckDeploymentExistsConfig(resourceName, &config1), + testAccCheckDeploymentConfigExists(resourceName, &config1), resource.TestCheckResourceAttr(resourceName, "compute_platform", "Lambda"), resource.TestCheckResourceAttr(resourceName, "traffic_routing_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "traffic_routing_config.0.type", "TimeBasedLinear"), @@ -205,10 +205,10 @@ func TestAccCodeDeployDeploymentConfig_trafficLinear(t *testing.T) { ), }, { - Config: testAccDeploymentTrafficLinearConfig(rName, 3, 10), + Config: testAccDeploymentConfigConfig_trafficLinear(rName, 3, 10), Check: resource.ComposeTestCheckFunc( - testAccCheckDeploymentExistsConfig(resourceName, &config2), - testAccCheckDeploymentRecreatedConfig(&config1, &config2), + testAccCheckDeploymentConfigExists(resourceName, &config2), + testAccCheckDeploymentConfigRecreated(&config1, &config2), resource.TestCheckResourceAttr(resourceName, "compute_platform", "Lambda"), resource.TestCheckResourceAttr(resourceName, "traffic_routing_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "traffic_routing_config.0.type", "TimeBasedLinear"), @@ -228,7 +228,7 @@ func TestAccCodeDeployDeploymentConfig_trafficLinear(t *testing.T) { }) } -func testAccCheckDeploymentDestroyConfig(s *terraform.State) error { +func testAccCheckDeploymentConfigDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).DeployConn for _, rs := range s.RootModule().Resources { @@ -256,7 +256,7 @@ func testAccCheckDeploymentDestroyConfig(s *terraform.State) error { return nil } -func testAccCheckDeploymentExistsConfig(name string, config *codedeploy.DeploymentConfigInfo) resource.TestCheckFunc { +func testAccCheckDeploymentConfigExists(name string, config *codedeploy.DeploymentConfigInfo) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { @@ -279,7 +279,7 @@ func testAccCheckDeploymentExistsConfig(name string, config *codedeploy.Deployme } } -func testAccCheckDeploymentRecreatedConfig(i, j *codedeploy.DeploymentConfigInfo) resource.TestCheckFunc { +func testAccCheckDeploymentConfigRecreated(i, j *codedeploy.DeploymentConfigInfo) resource.TestCheckFunc { return func(s *terraform.State) error { if aws.TimeValue(i.CreateTime).Equal(aws.TimeValue(j.CreateTime)) { return errors.New("CodeDeploy Deployment Config was not recreated") @@ -289,7 +289,7 @@ func testAccCheckDeploymentRecreatedConfig(i, j *codedeploy.DeploymentConfigInfo } } -func testAccDeploymentFleetConfig(rName string, value int) string { +func testAccDeploymentConfigConfig_fleet(rName string, value int) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_config" "test" { deployment_config_name = %q @@ -302,7 +302,7 @@ resource "aws_codedeploy_deployment_config" "test" { `, rName, value) } -func testAccDeploymentHostCountConfig(rName string, value int) string { +func testAccDeploymentConfigConfig_hostCount(rName string, value int) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_config" "test" { deployment_config_name = %q @@ -315,7 +315,7 @@ resource "aws_codedeploy_deployment_config" "test" { `, rName, value) } -func testAccDeploymentTrafficCanaryConfig(rName string, interval, percentage int) string { +func testAccDeploymentConfigConfig_trafficCanary(rName string, interval, percentage int) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_config" "test" { deployment_config_name = %q @@ -333,7 +333,7 @@ resource "aws_codedeploy_deployment_config" "test" { `, rName, interval, percentage) } -func testAccDeploymentTrafficLinearConfig(rName string, interval, percentage int) string { +func testAccDeploymentConfigConfig_trafficLinear(rName string, interval, percentage int) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_config" "test" { deployment_config_name = %q diff --git a/internal/service/deploy/deployment_group.go b/internal/service/deploy/deployment_group.go index c91ea7d8408..e15fe2d439a 100644 --- a/internal/service/deploy/deployment_group.go +++ b/internal/service/deploy/deployment_group.go @@ -526,7 +526,7 @@ func resourceDeploymentGroupCreate(d *schema.ResourceData, meta interface{}) err } if attr, ok := d.GetOk("ecs_service"); ok { - input.EcsServices = expandCodeDeployEcsServices(attr.([]interface{})) + input.EcsServices = expandECSServices(attr.([]interface{})) } if attr, ok := d.GetOk("trigger_configuration"); ok { @@ -646,7 +646,7 @@ func resourceDeploymentGroupRead(d *schema.ResourceData, meta interface{}) error return fmt.Errorf("error setting ec2_tag_filter: %w", err) } - if err := d.Set("ecs_service", flattenCodeDeployEcsServices(group.EcsServices)); err != nil { + if err := d.Set("ecs_service", flattenECSServices(group.EcsServices)); err != nil { return fmt.Errorf("error setting ecs_service: %w", err) } @@ -751,7 +751,7 @@ func resourceDeploymentGroupUpdate(d *schema.ResourceData, meta interface{}) err } if d.HasChange("ecs_service") { - input.EcsServices = expandCodeDeployEcsServices(d.Get("ecs_service").([]interface{})) + input.EcsServices = expandECSServices(d.Get("ecs_service").([]interface{})) } if d.HasChange("trigger_configuration") { @@ -956,7 +956,7 @@ func BuildAlarmConfig(configured []interface{}) *codedeploy.AlarmConfiguration { return result } -func expandCodeDeployEcsServices(l []interface{}) []*codedeploy.ECSService { +func expandECSServices(l []interface{}) []*codedeploy.ECSService { ecsServices := make([]*codedeploy.ECSService, 0) for _, mRaw := range l { @@ -977,7 +977,7 @@ func expandCodeDeployEcsServices(l []interface{}) []*codedeploy.ECSService { return ecsServices } -func expandCodeDeployElbInfo(l []interface{}) []*codedeploy.ELBInfo { +func expandELBInfo(l []interface{}) []*codedeploy.ELBInfo { elbInfos := []*codedeploy.ELBInfo{} for _, mRaw := range l { @@ -997,7 +997,7 @@ func expandCodeDeployElbInfo(l []interface{}) []*codedeploy.ELBInfo { return elbInfos } -func expandCodeDeployTargetGroupInfo(l []interface{}) []*codedeploy.TargetGroupInfo { +func expandTargetGroupInfo(l []interface{}) []*codedeploy.TargetGroupInfo { targetGroupInfos := []*codedeploy.TargetGroupInfo{} for _, mRaw := range l { @@ -1017,7 +1017,7 @@ func expandCodeDeployTargetGroupInfo(l []interface{}) []*codedeploy.TargetGroupI return targetGroupInfos } -func expandCodeDeployTargetGroupPairInfo(l []interface{}) []*codedeploy.TargetGroupPairInfo { +func expandTargetGroupPairInfo(l []interface{}) []*codedeploy.TargetGroupPairInfo { targetGroupPairInfos := []*codedeploy.TargetGroupPairInfo{} for _, mRaw := range l { @@ -1028,9 +1028,9 @@ func expandCodeDeployTargetGroupPairInfo(l []interface{}) []*codedeploy.TargetGr m := mRaw.(map[string]interface{}) targetGroupPairInfo := &codedeploy.TargetGroupPairInfo{ - ProdTrafficRoute: expandCodeDeployTrafficRoute(m["prod_traffic_route"].([]interface{})), - TargetGroups: expandCodeDeployTargetGroupInfo(m["target_group"].([]interface{})), - TestTrafficRoute: expandCodeDeployTrafficRoute(m["test_traffic_route"].([]interface{})), + ProdTrafficRoute: expandTrafficRoute(m["prod_traffic_route"].([]interface{})), + TargetGroups: expandTargetGroupInfo(m["target_group"].([]interface{})), + TestTrafficRoute: expandTrafficRoute(m["test_traffic_route"].([]interface{})), } targetGroupPairInfos = append(targetGroupPairInfos, targetGroupPairInfo) @@ -1039,7 +1039,7 @@ func expandCodeDeployTargetGroupPairInfo(l []interface{}) []*codedeploy.TargetGr return targetGroupPairInfos } -func expandCodeDeployTrafficRoute(l []interface{}) *codedeploy.TrafficRoute { +func expandTrafficRoute(l []interface{}) *codedeploy.TrafficRoute { if len(l) == 0 || l[0] == nil { return nil } @@ -1084,15 +1084,15 @@ func ExpandLoadBalancerInfo(list []interface{}) *codedeploy.LoadBalancerInfo { lbInfo := list[0].(map[string]interface{}) if attr, ok := lbInfo["elb_info"]; ok && attr.(*schema.Set).Len() > 0 { - loadBalancerInfo.ElbInfoList = expandCodeDeployElbInfo(attr.(*schema.Set).List()) + loadBalancerInfo.ElbInfoList = expandELBInfo(attr.(*schema.Set).List()) } if attr, ok := lbInfo["target_group_info"]; ok && attr.(*schema.Set).Len() > 0 { - loadBalancerInfo.TargetGroupInfoList = expandCodeDeployTargetGroupInfo(attr.(*schema.Set).List()) + loadBalancerInfo.TargetGroupInfoList = expandTargetGroupInfo(attr.(*schema.Set).List()) } if attr, ok := lbInfo["target_group_pair_info"]; ok && len(attr.([]interface{})) > 0 { - loadBalancerInfo.TargetGroupPairInfoList = expandCodeDeployTargetGroupPairInfo(attr.([]interface{})) + loadBalancerInfo.TargetGroupPairInfoList = expandTargetGroupPairInfo(attr.([]interface{})) } return loadBalancerInfo @@ -1273,7 +1273,7 @@ func AlarmConfigToMap(config *codedeploy.AlarmConfiguration) []map[string]interf return result } -func flattenCodeDeployEcsServices(ecsServices []*codedeploy.ECSService) []interface{} { +func flattenECSServices(ecsServices []*codedeploy.ECSService) []interface{} { l := make([]interface{}, 0) for _, ecsService := range ecsServices { @@ -1292,7 +1292,7 @@ func flattenCodeDeployEcsServices(ecsServices []*codedeploy.ECSService) []interf return l } -func flattenCodeDeployElbInfo(elbInfos []*codedeploy.ELBInfo) []interface{} { +func flattenELBInfo(elbInfos []*codedeploy.ELBInfo) []interface{} { l := make([]interface{}, 0) for _, elbInfo := range elbInfos { @@ -1310,7 +1310,7 @@ func flattenCodeDeployElbInfo(elbInfos []*codedeploy.ELBInfo) []interface{} { return l } -func flattenCodeDeployTargetGroupInfo(targetGroupInfos []*codedeploy.TargetGroupInfo) []interface{} { +func flattenTargetGroupInfo(targetGroupInfos []*codedeploy.TargetGroupInfo) []interface{} { l := make([]interface{}, 0) for _, targetGroupInfo := range targetGroupInfos { @@ -1328,7 +1328,7 @@ func flattenCodeDeployTargetGroupInfo(targetGroupInfos []*codedeploy.TargetGroup return l } -func flattenCodeDeployTargetGroupPairInfo(targetGroupPairInfos []*codedeploy.TargetGroupPairInfo) []interface{} { +func flattenTargetGroupPairInfo(targetGroupPairInfos []*codedeploy.TargetGroupPairInfo) []interface{} { l := make([]interface{}, 0) for _, targetGroupPairInfo := range targetGroupPairInfos { @@ -1337,9 +1337,9 @@ func flattenCodeDeployTargetGroupPairInfo(targetGroupPairInfos []*codedeploy.Tar } m := map[string]interface{}{ - "prod_traffic_route": flattenCodeDeployTrafficRoute(targetGroupPairInfo.ProdTrafficRoute), - "target_group": flattenCodeDeployTargetGroupInfo(targetGroupPairInfo.TargetGroups), - "test_traffic_route": flattenCodeDeployTrafficRoute(targetGroupPairInfo.TestTrafficRoute), + "prod_traffic_route": flattenTrafficRoute(targetGroupPairInfo.ProdTrafficRoute), + "target_group": flattenTargetGroupInfo(targetGroupPairInfo.TargetGroups), + "test_traffic_route": flattenTrafficRoute(targetGroupPairInfo.TestTrafficRoute), } l = append(l, m) @@ -1348,7 +1348,7 @@ func flattenCodeDeployTargetGroupPairInfo(targetGroupPairInfos []*codedeploy.Tar return l } -func flattenCodeDeployTrafficRoute(trafficRoute *codedeploy.TrafficRoute) []interface{} { +func flattenTrafficRoute(trafficRoute *codedeploy.TrafficRoute) []interface{} { if trafficRoute == nil { return []interface{}{} } @@ -1386,9 +1386,9 @@ func FlattenLoadBalancerInfo(loadBalancerInfo *codedeploy.LoadBalancerInfo) []in } m := map[string]interface{}{ - "elb_info": schema.NewSet(LoadBalancerInfoHash, flattenCodeDeployElbInfo(loadBalancerInfo.ElbInfoList)), - "target_group_info": schema.NewSet(LoadBalancerInfoHash, flattenCodeDeployTargetGroupInfo(loadBalancerInfo.TargetGroupInfoList)), - "target_group_pair_info": flattenCodeDeployTargetGroupPairInfo(loadBalancerInfo.TargetGroupPairInfoList), + "elb_info": schema.NewSet(LoadBalancerInfoHash, flattenELBInfo(loadBalancerInfo.ElbInfoList)), + "target_group_info": schema.NewSet(LoadBalancerInfoHash, flattenTargetGroupInfo(loadBalancerInfo.TargetGroupInfoList)), + "target_group_pair_info": flattenTargetGroupPairInfo(loadBalancerInfo.TargetGroupPairInfoList), } return []interface{}{m} diff --git a/internal/service/deploy/deployment_group_test.go b/internal/service/deploy/deployment_group_test.go index 4ce4d5c29d7..c98e9d27386 100644 --- a/internal/service/deploy/deployment_group_test.go +++ b/internal/service/deploy/deployment_group_test.go @@ -19,7 +19,7 @@ import ( tfcodedeploy "github.com/hashicorp/terraform-provider-aws/internal/service/deploy" ) -func TestAccCodeDeployDeploymentGroup_basic(t *testing.T) { +func TestAccDeployDeploymentGroup_basic(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -32,7 +32,7 @@ func TestAccCodeDeployDeploymentGroup_basic(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentGroup(rName, false), + Config: testAccDeploymentGroupConfig_basic(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "codedeploy", fmt.Sprintf(`deploymentgroup:%s/%s`, "tf-acc-test-"+rName, "tf-acc-test-"+rName)), @@ -60,7 +60,7 @@ func TestAccCodeDeployDeploymentGroup_basic(t *testing.T) { ), }, { - Config: testAccDeploymentGroupModified(rName, false), + Config: testAccDeploymentGroupConfig_modified(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "codedeploy", fmt.Sprintf(`deploymentgroup:%s/%s`, "tf-acc-test-"+rName, "tf-acc-test-updated-"+rName)), @@ -92,7 +92,7 @@ func TestAccCodeDeployDeploymentGroup_basic(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_Basic_tagSet(t *testing.T) { +func TestAccDeployDeploymentGroup_Basic_tagSet(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -105,7 +105,7 @@ func TestAccCodeDeployDeploymentGroup_Basic_tagSet(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentGroup(rName, true), + Config: testAccDeploymentGroupConfig_basic(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "app_name", "tf-acc-test-"+rName), @@ -130,7 +130,7 @@ func TestAccCodeDeployDeploymentGroup_Basic_tagSet(t *testing.T) { ), }, { - Config: testAccDeploymentGroupModified(rName, true), + Config: testAccDeploymentGroupConfig_modified(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "app_name", "tf-acc-test-"+rName), @@ -164,7 +164,7 @@ func TestAccCodeDeployDeploymentGroup_Basic_tagSet(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_onPremiseTag(t *testing.T) { +func TestAccDeployDeploymentGroup_onPremiseTag(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" rName := sdkacctest.RandString(5) @@ -176,7 +176,7 @@ func TestAccCodeDeployDeploymentGroup_onPremiseTag(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentGroupOnPremiseTags(rName), + Config: testAccDeploymentGroupConfig_onPremiseTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -205,7 +205,7 @@ func TestAccCodeDeployDeploymentGroup_onPremiseTag(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_disappears(t *testing.T) { +func TestAccDeployDeploymentGroup_disappears(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" rName := sdkacctest.RandString(5) @@ -217,7 +217,7 @@ func TestAccCodeDeployDeploymentGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentGroup(rName, false), + Config: testAccDeploymentGroupConfig_basic(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), acctest.CheckResourceDisappears(acctest.Provider, tfcodedeploy.ResourceDeploymentGroup(), resourceName), @@ -228,7 +228,7 @@ func TestAccCodeDeployDeploymentGroup_disappears(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_Disappears_app(t *testing.T) { +func TestAccDeployDeploymentGroup_Disappears_app(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" rName := sdkacctest.RandString(5) @@ -240,7 +240,7 @@ func TestAccCodeDeployDeploymentGroup_Disappears_app(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentGroup(rName, false), + Config: testAccDeploymentGroupConfig_basic(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), acctest.CheckResourceDisappears(acctest.Provider, tfcodedeploy.ResourceApp(), "aws_codedeploy_app.test"), @@ -251,7 +251,7 @@ func TestAccCodeDeployDeploymentGroup_Disappears_app(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_tags(t *testing.T) { +func TestAccDeployDeploymentGroup_tags(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -264,7 +264,7 @@ func TestAccCodeDeployDeploymentGroup_tags(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentGroupTags1Config(rName, "key1", "value1"), + Config: testAccDeploymentGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -278,7 +278,7 @@ func TestAccCodeDeployDeploymentGroup_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeploymentGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDeploymentGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -287,7 +287,7 @@ func TestAccCodeDeployDeploymentGroup_tags(t *testing.T) { ), }, { - Config: testAccDeploymentGroupTags1Config(rName, "key2", "value2"), + Config: testAccDeploymentGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -298,7 +298,7 @@ func TestAccCodeDeployDeploymentGroup_tags(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_Trigger_basic(t *testing.T) { +func TestAccDeployDeploymentGroup_Trigger_basic(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -311,27 +311,27 @@ func TestAccCodeDeployDeploymentGroup_Trigger_basic(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentGroup_triggerConfiguration_create(rName), + Config: testAccDeploymentGroupConfig_triggerConfigurationCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( resourceName, "app_name", "tf-acc-test-"+rName), resource.TestCheckResourceAttr( resourceName, "deployment_group_name", "tf-acc-test-"+rName), - testAccCheckCodeDeployDeploymentGroupTriggerEvents(&group, "test-trigger", []string{ + testAccCheckDeploymentGroupTriggerEvents(&group, "test-trigger", []string{ "DeploymentFailure", }), ), }, { - Config: testAccDeploymentGroup_triggerConfiguration_update(rName), + Config: testAccDeploymentGroupConfig_triggerConfigurationUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( resourceName, "app_name", "tf-acc-test-"+rName), resource.TestCheckResourceAttr( resourceName, "deployment_group_name", "tf-acc-test-"+rName), - testAccCheckCodeDeployDeploymentGroupTriggerEvents(&group, "test-trigger", []string{ + testAccCheckDeploymentGroupTriggerEvents(&group, "test-trigger", []string{ "DeploymentFailure", "DeploymentSuccess", }), @@ -347,7 +347,7 @@ func TestAccCodeDeployDeploymentGroup_Trigger_basic(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_Trigger_multiple(t *testing.T) { +func TestAccDeployDeploymentGroup_Trigger_multiple(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -360,41 +360,41 @@ func TestAccCodeDeployDeploymentGroup_Trigger_multiple(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentGroup_triggerConfiguration_createMultiple(rName), + Config: testAccDeploymentGroupConfig_triggerConfigurationCreateMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( resourceName, "app_name", "tf-acc-test-"+rName), resource.TestCheckResourceAttr( resourceName, "deployment_group_name", "tf-acc-test-"+rName), - testAccCheckCodeDeployDeploymentGroupTriggerEvents(&group, "test-trigger-1", []string{ + testAccCheckDeploymentGroupTriggerEvents(&group, "test-trigger-1", []string{ "DeploymentFailure", }), - testAccCheckCodeDeployDeploymentGroupTriggerEvents(&group, "test-trigger-2", []string{ + testAccCheckDeploymentGroupTriggerEvents(&group, "test-trigger-2", []string{ "InstanceFailure", }), - testAccCheckCodeDeployDeploymentGroupTriggerTargetArn(&group, "test-trigger-2", + testAccCheckDeploymentGroupTriggerTargetARN(&group, "test-trigger-2", regexp.MustCompile(fmt.Sprintf("^arn:%s:sns:[^:]+:[0-9]{12}:tf-acc-test-2-%s$", acctest.Partition(), rName))), ), }, { - Config: testAccDeploymentGroup_triggerConfiguration_updateMultiple(rName), + Config: testAccDeploymentGroupConfig_triggerConfigurationUpdateMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( resourceName, "app_name", "tf-acc-test-"+rName), resource.TestCheckResourceAttr( resourceName, "deployment_group_name", "tf-acc-test-"+rName), - testAccCheckCodeDeployDeploymentGroupTriggerEvents(&group, "test-trigger-1", []string{ + testAccCheckDeploymentGroupTriggerEvents(&group, "test-trigger-1", []string{ "DeploymentFailure", "DeploymentStart", "DeploymentStop", "DeploymentSuccess", }), - testAccCheckCodeDeployDeploymentGroupTriggerEvents(&group, "test-trigger-2", []string{ + testAccCheckDeploymentGroupTriggerEvents(&group, "test-trigger-2", []string{ "InstanceFailure", }), - testAccCheckCodeDeployDeploymentGroupTriggerTargetArn(&group, "test-trigger-2", + testAccCheckDeploymentGroupTriggerTargetARN(&group, "test-trigger-2", regexp.MustCompile(fmt.Sprintf("^arn:%s:sns:[^:]+:[0-9]{12}:tf-acc-test-3-%s$", acctest.Partition(), rName))), ), }, @@ -408,7 +408,7 @@ func TestAccCodeDeployDeploymentGroup_Trigger_multiple(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_AutoRollback_create(t *testing.T) { +func TestAccDeployDeploymentGroup_AutoRollback_create(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -421,7 +421,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_create(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_auto_rollback_configuration_create(rName), + Config: testAccDeploymentGroupConfig_autoRollbackConfigurationCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -443,7 +443,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_create(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_AutoRollback_update(t *testing.T) { +func TestAccDeployDeploymentGroup_AutoRollback_update(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -456,7 +456,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_update(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_auto_rollback_configuration_create(rName), + Config: testAccDeploymentGroupConfig_autoRollbackConfigurationCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -469,7 +469,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_update(t *testing.T) { ), }, { - Config: test_config_auto_rollback_configuration_update(rName), + Config: testAccDeploymentGroupConfig_autoRollbackConfigurationUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -492,7 +492,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_update(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_AutoRollback_delete(t *testing.T) { +func TestAccDeployDeploymentGroup_AutoRollback_delete(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -505,7 +505,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_delete(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_auto_rollback_configuration_create(rName), + Config: testAccDeploymentGroupConfig_autoRollbackConfigurationCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -518,7 +518,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_delete(t *testing.T) { ), }, { - Config: test_config_auto_rollback_configuration_none(rName), + Config: testAccDeploymentGroupConfig_autoRollbackConfigurationNone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -535,7 +535,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_delete(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_AutoRollback_disable(t *testing.T) { +func TestAccDeployDeploymentGroup_AutoRollback_disable(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -548,7 +548,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_disable(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_auto_rollback_configuration_create(rName), + Config: testAccDeploymentGroupConfig_autoRollbackConfigurationCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -561,7 +561,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_disable(t *testing.T) { ), }, { - Config: test_config_auto_rollback_configuration_disable(rName), + Config: testAccDeploymentGroupConfig_autoRollbackConfigurationDisable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -583,7 +583,7 @@ func TestAccCodeDeployDeploymentGroup_AutoRollback_disable(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_Alarm_create(t *testing.T) { +func TestAccDeployDeploymentGroup_Alarm_create(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -596,7 +596,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_create(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_alarm_configuration_create(rName), + Config: testAccDeploymentGroupConfig_alarmConfigurationCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -620,7 +620,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_create(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_Alarm_update(t *testing.T) { +func TestAccDeployDeploymentGroup_Alarm_update(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -633,7 +633,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_update(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_alarm_configuration_create(rName), + Config: testAccDeploymentGroupConfig_alarmConfigurationCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -648,7 +648,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_update(t *testing.T) { ), }, { - Config: test_config_alarm_configuration_update(rName), + Config: testAccDeploymentGroupConfig_alarmConfigurationUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -673,7 +673,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_update(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_Alarm_delete(t *testing.T) { +func TestAccDeployDeploymentGroup_Alarm_delete(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -686,7 +686,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_delete(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_alarm_configuration_create(rName), + Config: testAccDeploymentGroupConfig_alarmConfigurationCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -701,7 +701,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_delete(t *testing.T) { ), }, { - Config: test_config_alarm_configuration_none(rName), + Config: testAccDeploymentGroupConfig_alarmConfigurationNone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -718,7 +718,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_delete(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_Alarm_disable(t *testing.T) { +func TestAccDeployDeploymentGroup_Alarm_disable(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -731,7 +731,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_disable(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_alarm_configuration_create(rName), + Config: testAccDeploymentGroupConfig_alarmConfigurationCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -746,7 +746,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_disable(t *testing.T) { ), }, { - Config: test_config_alarm_configuration_disable(rName), + Config: testAccDeploymentGroupConfig_alarmConfigurationDisable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -771,7 +771,7 @@ func TestAccCodeDeployDeploymentGroup_Alarm_disable(t *testing.T) { } // When no configuration is provided, a deploymentStyle object with default values is computed -func TestAccCodeDeployDeploymentGroup_DeploymentStyle_default(t *testing.T) { +func TestAccDeployDeploymentGroup_DeploymentStyle_default(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -784,7 +784,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_default(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_deployment_style_default(rName), + Config: testAccDeploymentGroupConfig_styleDefault(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -805,7 +805,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_default(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_DeploymentStyle_create(t *testing.T) { +func TestAccDeployDeploymentGroup_DeploymentStyle_create(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -818,7 +818,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_create(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_deployment_style_create(rName), + Config: testAccDeploymentGroupConfig_styleCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -847,7 +847,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_create(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_DeploymentStyle_update(t *testing.T) { +func TestAccDeployDeploymentGroup_DeploymentStyle_update(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -860,7 +860,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_update(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_deployment_style_create(rName), + Config: testAccDeploymentGroupConfig_styleCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -872,7 +872,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_update(t *testing.T) { ), }, { - Config: test_config_deployment_style_update(rName), + Config: testAccDeploymentGroupConfig_styleUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -894,7 +894,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_update(t *testing.T) { } // Delete reverts to default configuration. It does not remove the deployment_style block -func TestAccCodeDeployDeploymentGroup_DeploymentStyle_delete(t *testing.T) { +func TestAccDeployDeploymentGroup_DeploymentStyle_delete(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -907,7 +907,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_delete(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_deployment_style_create(rName), + Config: testAccDeploymentGroupConfig_styleCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -919,7 +919,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_delete(t *testing.T) { ), }, { - Config: test_config_deployment_style_default(rName), + Config: testAccDeploymentGroupConfig_styleDefault(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -940,7 +940,7 @@ func TestAccCodeDeployDeploymentGroup_DeploymentStyle_delete(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_create(t *testing.T) { +func TestAccDeployDeploymentGroup_LoadBalancerInfo_create(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -953,7 +953,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_create(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_load_balancer_info_create(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -975,7 +975,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_create(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_update(t *testing.T) { +func TestAccDeployDeploymentGroup_LoadBalancerInfo_update(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -988,7 +988,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_update(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_load_balancer_info_create(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1001,7 +1001,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_update(t *testing.T) { ), }, { - Config: test_config_load_balancer_info_update(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1023,7 +1023,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_update(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_delete(t *testing.T) { +func TestAccDeployDeploymentGroup_LoadBalancerInfo_delete(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1036,7 +1036,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_delete(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_load_balancer_info_create(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1049,7 +1049,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_delete(t *testing.T) { ), }, { - Config: test_config_load_balancer_info_none(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoNone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1066,7 +1066,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfo_delete(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_create(t *testing.T) { +func TestAccDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_create(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1079,7 +1079,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_create(t * CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_load_balancer_info_target_group_info_create(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoTargetInfoCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1102,7 +1102,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_create(t * }) } -func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_update(t *testing.T) { +func TestAccDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_update(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1115,7 +1115,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_update(t * CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_load_balancer_info_target_group_info_create(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoTargetInfoCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1128,7 +1128,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_update(t * ), }, { - Config: test_config_load_balancer_info_target_group_info_update(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoTargetInfoUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1150,7 +1150,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_update(t * }) } -func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_delete(t *testing.T) { +func TestAccDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_delete(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1163,7 +1163,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_delete(t * CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_load_balancer_info_target_group_info_create(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoTargetInfoCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1176,7 +1176,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_delete(t * ), }, { - Config: test_config_load_balancer_info_target_group_info_delete(rName), + Config: testAccDeploymentGroupConfig_loadBalancerInfoTargetInfoDelete(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1193,7 +1193,7 @@ func TestAccCodeDeployDeploymentGroup_LoadBalancerInfoTargetGroupInfo_delete(t * }) } -func TestAccCodeDeployDeploymentGroup_InPlaceDeploymentWithTrafficControl_create(t *testing.T) { +func TestAccDeployDeploymentGroup_InPlaceDeploymentWithTrafficControl_create(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1206,7 +1206,7 @@ func TestAccCodeDeployDeploymentGroup_InPlaceDeploymentWithTrafficControl_create CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_in_place_deployment_with_traffic_control_create(rName), + Config: testAccDeploymentGroupConfig_inPlaceTrafficControlCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1235,7 +1235,7 @@ func TestAccCodeDeployDeploymentGroup_InPlaceDeploymentWithTrafficControl_create }) } -func TestAccCodeDeployDeploymentGroup_InPlaceDeploymentWithTrafficControl_update(t *testing.T) { +func TestAccDeployDeploymentGroup_InPlaceDeploymentWithTrafficControl_update(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1248,7 +1248,7 @@ func TestAccCodeDeployDeploymentGroup_InPlaceDeploymentWithTrafficControl_update CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_in_place_deployment_with_traffic_control_create(rName), + Config: testAccDeploymentGroupConfig_inPlaceTrafficControlCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1268,7 +1268,7 @@ func TestAccCodeDeployDeploymentGroup_InPlaceDeploymentWithTrafficControl_update ), }, { - Config: test_config_in_place_deployment_with_traffic_control_update(rName), + Config: testAccDeploymentGroupConfig_inPlaceTrafficControlUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1311,7 +1311,7 @@ func TestAccCodeDeployDeploymentGroup_InPlaceDeploymentWithTrafficControl_update }) } -func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_create(t *testing.T) { +func TestAccDeployDeploymentGroup_BlueGreenDeployment_create(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1324,7 +1324,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_create(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_blue_green_deployment_config_create_with_asg(rName), + Config: testAccDeploymentGroupConfig_blueGreenConfigCreateASG(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1367,7 +1367,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_create(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_updateWithASG(t *testing.T) { +func TestAccDeployDeploymentGroup_BlueGreenDeployment_updateWithASG(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1380,7 +1380,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_updateWithASG(t *testi CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_blue_green_deployment_config_create_with_asg(rName), + Config: testAccDeploymentGroupConfig_blueGreenConfigCreateASG(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1407,7 +1407,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_updateWithASG(t *testi ), }, { - Config: test_config_blue_green_deployment_config_update_with_asg(rName), + Config: testAccDeploymentGroupConfig_blueGreenConfigUpdateASG(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1435,7 +1435,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_updateWithASG(t *testi }) } -func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_update(t *testing.T) { +func TestAccDeployDeploymentGroup_BlueGreenDeployment_update(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1448,7 +1448,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_update(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_blue_green_deployment_config_create_no_asg(rName), + Config: testAccDeploymentGroupConfig_blueGreenConfigCreateNoASG(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1482,7 +1482,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_update(t *testing.T) { ), }, { - Config: test_config_blue_green_deployment_config_update_no_asg(rName), + Config: testAccDeploymentGroupConfig_blueGreenConfigUpdateNoASG(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1517,7 +1517,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_update(t *testing.T) { // Without "Computed: true" on blue_green_deployment_config, removing the resource // from configuration causes an error, because the remote resource still exists. -func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_delete(t *testing.T) { +func TestAccDeployDeploymentGroup_BlueGreenDeployment_delete(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1530,7 +1530,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_delete(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_blue_green_deployment_config_create_no_asg(rName), + Config: testAccDeploymentGroupConfig_blueGreenConfigCreateNoASG(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1562,7 +1562,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_delete(t *testing.T) { ), }, { - Config: test_config_blue_green_deployment_config_delete(rName), + Config: testAccDeploymentGroupConfig_blueGreenConfigDelete(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr( @@ -1585,7 +1585,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_delete(t *testing.T) { }) } -func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_complete(t *testing.T) { +func TestAccDeployDeploymentGroup_BlueGreenDeployment_complete(t *testing.T) { var group codedeploy.DeploymentGroupInfo resourceName := "aws_codedeploy_deployment_group.test" @@ -1598,7 +1598,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_complete(t *testing.T) CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: test_config_blue_green_deployment_complete(rName), + Config: testAccDeploymentGroupConfig_blueGreenComplete(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), @@ -1640,7 +1640,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_complete(t *testing.T) ), }, { - Config: test_config_blue_green_deployment_complete_updated(rName), + Config: testAccDeploymentGroupConfig_blueGreenCompleteUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), @@ -1689,7 +1689,7 @@ func TestAccCodeDeployDeploymentGroup_BlueGreenDeployment_complete(t *testing.T) }) } -func TestAccCodeDeployDeploymentGroup_ECS_blueGreen(t *testing.T) { +func TestAccDeployDeploymentGroup_ECS_blueGreen(t *testing.T) { var group codedeploy.DeploymentGroupInfo rName := fmt.Sprintf("tf-acc-test-%s", sdkacctest.RandString(5)) ecsClusterResourceName := "aws_ecs_cluster.test" @@ -1705,7 +1705,7 @@ func TestAccCodeDeployDeploymentGroup_ECS_blueGreen(t *testing.T) { CheckDestroy: testAccCheckDeploymentGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDeploymentGroupECSBlueGreenConfig(rName), + Config: testAccDeploymentGroupConfig_ecsBlueGreen(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ecs_service.#", "1"), @@ -1725,7 +1725,7 @@ func TestAccCodeDeployDeploymentGroup_ECS_blueGreen(t *testing.T) { ), }, { - Config: testAccDeploymentGroupECSBlueGreenUpdateConfig(rName), + Config: testAccDeploymentGroupConfig_ecsBlueGreenUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeploymentGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ecs_service.#", "1"), @@ -2221,7 +2221,7 @@ func TestDeploymentGroup_alarmConfigToMap(t *testing.T) { } } -func testAccCheckCodeDeployDeploymentGroupTriggerEvents(group *codedeploy.DeploymentGroupInfo, triggerName string, expectedEvents []string) resource.TestCheckFunc { +func testAccCheckDeploymentGroupTriggerEvents(group *codedeploy.DeploymentGroupInfo, triggerName string, expectedEvents []string) resource.TestCheckFunc { return func(s *terraform.State) error { found := false for _, actual := range group.TriggerConfigurations { @@ -2255,7 +2255,7 @@ func testAccCheckCodeDeployDeploymentGroupTriggerEvents(group *codedeploy.Deploy } } -func testAccCheckCodeDeployDeploymentGroupTriggerTargetArn(group *codedeploy.DeploymentGroupInfo, triggerName string, r *regexp.Regexp) resource.TestCheckFunc { +func testAccCheckDeploymentGroupTriggerTargetARN(group *codedeploy.DeploymentGroupInfo, triggerName string, r *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { found := false for _, actual := range group.TriggerConfigurations { @@ -2340,7 +2340,7 @@ func testAccDeploymentGroupImportStateIdFunc(resourceName string) resource.Impor } } -func testAccDeploymentGroupBaseConfig(rName string) string { +func testAccDeploymentGroupConfig_base2(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_app" "test" { name = "tf-acc-test-%[1]s" @@ -2401,7 +2401,7 @@ EOF `, rName) } -func testAccDeploymentGroup(rName string, tagGroup bool) string { +func testAccDeploymentGroupConfig_basic(rName string, tagGroup bool) string { var tagGroupOrFilter string if tagGroup { tagGroupOrFilter = ` @@ -2425,7 +2425,7 @@ ec2_tag_filter { } - return testAccDeploymentGroupBaseConfig(rName) + fmt.Sprintf(` + return testAccDeploymentGroupConfig_base2(rName) + fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" @@ -2435,7 +2435,7 @@ resource "aws_codedeploy_deployment_group" "test" { `, rName, tagGroupOrFilter) } -func testAccDeploymentGroupModified(rName string, tagGroup bool) string { +func testAccDeploymentGroupConfig_modified(rName string, tagGroup bool) string { var tagGroupOrFilter string if tagGroup { tagGroupOrFilter = ` @@ -2459,7 +2459,7 @@ ec2_tag_filter { } - return testAccDeploymentGroupBaseConfig(rName) + fmt.Sprintf(` + return testAccDeploymentGroupConfig_base2(rName) + fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-updated-%[1]s" @@ -2520,8 +2520,8 @@ EOF `, rName, tagGroupOrFilter) } -func testAccDeploymentGroupOnPremiseTags(rName string) string { - return testAccDeploymentGroupBaseConfig(rName) + fmt.Sprintf(` +func testAccDeploymentGroupConfig_onPremiseTags(rName string) string { + return testAccDeploymentGroupConfig_base2(rName) + fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" @@ -2536,7 +2536,7 @@ resource "aws_codedeploy_deployment_group" "test" { `, rName) } -func baseCodeDeployConfig(rName string) string { +func testAccDeploymentGroupConfig_base(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_app" "test" { name = "tf-acc-test-%[1]s" @@ -2601,7 +2601,7 @@ resource "aws_sns_topic" "test" { `, rName) } -func testAccDeploymentGroup_triggerConfiguration_create(rName string) string { +func testAccDeploymentGroupConfig_triggerConfigurationCreate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2614,10 +2614,10 @@ resource "aws_codedeploy_deployment_group" "test" { trigger_target_arn = aws_sns_topic.test.arn } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func testAccDeploymentGroup_triggerConfiguration_update(rName string) string { +func testAccDeploymentGroupConfig_triggerConfigurationUpdate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2630,10 +2630,10 @@ resource "aws_codedeploy_deployment_group" "test" { trigger_target_arn = aws_sns_topic.test.arn } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func testAccDeploymentGroup_triggerConfiguration_createMultiple(rName string) string { +func testAccDeploymentGroupConfig_triggerConfigurationCreateMultiple(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2656,10 +2656,10 @@ resource "aws_codedeploy_deployment_group" "test" { resource "aws_sns_topic" "test_2" { name = "tf-acc-test-2-%[1]s" } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func testAccDeploymentGroup_triggerConfiguration_updateMultiple(rName string) string { +func testAccDeploymentGroupConfig_triggerConfigurationUpdateMultiple(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2686,10 +2686,10 @@ resource "aws_sns_topic" "test_2" { resource "aws_sns_topic" "test_3" { name = "tf-acc-test-3-%[1]s" } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_auto_rollback_configuration_create(rName string) string { +func testAccDeploymentGroupConfig_autoRollbackConfigurationCreate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2701,10 +2701,10 @@ resource "aws_codedeploy_deployment_group" "test" { events = ["DEPLOYMENT_FAILURE"] } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_auto_rollback_configuration_update(rName string) string { +func testAccDeploymentGroupConfig_autoRollbackConfigurationUpdate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2716,20 +2716,20 @@ resource "aws_codedeploy_deployment_group" "test" { events = ["DEPLOYMENT_FAILURE", "DEPLOYMENT_STOP_ON_ALARM"] } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_auto_rollback_configuration_none(rName string) string { +func testAccDeploymentGroupConfig_autoRollbackConfigurationNone(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" service_role_arn = aws_iam_role.test.arn } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_auto_rollback_configuration_disable(rName string) string { +func testAccDeploymentGroupConfig_autoRollbackConfigurationDisable(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2741,10 +2741,10 @@ resource "aws_codedeploy_deployment_group" "test" { events = ["DEPLOYMENT_FAILURE"] } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_alarm_configuration_create(rName string) string { +func testAccDeploymentGroupConfig_alarmConfigurationCreate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2756,10 +2756,10 @@ resource "aws_codedeploy_deployment_group" "test" { enabled = true } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_alarm_configuration_update(rName string) string { +func testAccDeploymentGroupConfig_alarmConfigurationUpdate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2772,20 +2772,20 @@ resource "aws_codedeploy_deployment_group" "test" { ignore_poll_alarm_failure = true } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_alarm_configuration_none(rName string) string { +func testAccDeploymentGroupConfig_alarmConfigurationNone(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" service_role_arn = aws_iam_role.test.arn } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_alarm_configuration_disable(rName string) string { +func testAccDeploymentGroupConfig_alarmConfigurationDisable(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2797,20 +2797,20 @@ resource "aws_codedeploy_deployment_group" "test" { enabled = false } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_deployment_style_default(rName string) string { +func testAccDeploymentGroupConfig_styleDefault(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" service_role_arn = aws_iam_role.test.arn } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_deployment_style_create(rName string) string { +func testAccDeploymentGroupConfig_styleCreate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2828,10 +2828,10 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_deployment_style_update(rName string) string { +func testAccDeploymentGroupConfig_styleUpdate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2843,20 +2843,20 @@ resource "aws_codedeploy_deployment_group" "test" { deployment_type = "IN_PLACE" } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_load_balancer_info_none(rName string) string { +func testAccDeploymentGroupConfig_loadBalancerInfoNone(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" service_role_arn = aws_iam_role.test.arn } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_load_balancer_info_create(rName string) string { +func testAccDeploymentGroupConfig_loadBalancerInfoCreate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2869,10 +2869,10 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_load_balancer_info_update(rName string) string { +func testAccDeploymentGroupConfig_loadBalancerInfoUpdate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2885,10 +2885,10 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_load_balancer_info_target_group_info_create(rName string) string { +func testAccDeploymentGroupConfig_loadBalancerInfoTargetInfoCreate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2901,10 +2901,10 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_load_balancer_info_target_group_info_update(rName string) string { +func testAccDeploymentGroupConfig_loadBalancerInfoTargetInfoUpdate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2917,20 +2917,20 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_load_balancer_info_target_group_info_delete(rName string) string { +func testAccDeploymentGroupConfig_loadBalancerInfoTargetInfoDelete(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" service_role_arn = aws_iam_role.test.arn } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_in_place_deployment_with_traffic_control_create(rName string) string { +func testAccDeploymentGroupConfig_inPlaceTrafficControlCreate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2948,10 +2948,10 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_in_place_deployment_with_traffic_control_update(rName string) string { +func testAccDeploymentGroupConfig_inPlaceTrafficControlUpdate(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -2983,20 +2983,20 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_blue_green_deployment_config_delete(rName string) string { +func testAccDeploymentGroupConfig_blueGreenConfigDelete(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" service_role_arn = aws_iam_role.test.arn } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_blue_green_deployment_config_create_with_asg(rName string) string { +func testAccDeploymentGroupConfig_blueGreenConfigCreateASG(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -3086,10 +3086,10 @@ resource "aws_autoscaling_group" "test" { create_before_destroy = true } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_blue_green_deployment_config_update_with_asg(rName string) string { +func testAccDeploymentGroupConfig_blueGreenConfigUpdateASG(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -3178,10 +3178,10 @@ resource "aws_autoscaling_group" "test" { create_before_destroy = true } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_blue_green_deployment_config_create_no_asg(rName string) string { +func testAccDeploymentGroupConfig_blueGreenConfigCreateNoASG(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -3215,10 +3215,10 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_blue_green_deployment_config_update_no_asg(rName string) string { +func testAccDeploymentGroupConfig_blueGreenConfigUpdateNoASG(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -3250,10 +3250,10 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_blue_green_deployment_complete(rName string) string { +func testAccDeploymentGroupConfig_blueGreenComplete(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -3286,10 +3286,10 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func test_config_blue_green_deployment_complete_updated(rName string) string { +func testAccDeploymentGroupConfig_blueGreenCompleteUpdated(rName string) string { return fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name @@ -3321,10 +3321,10 @@ resource "aws_codedeploy_deployment_group" "test" { } } } -`, rName) + baseCodeDeployConfig(rName) +`, rName) + testAccDeploymentGroupConfig_base(rName) } -func testAccDeploymentGroupECSBaseConfig(rName string) string { +func testAccDeploymentGroupConfig_ecsBase(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -3519,8 +3519,8 @@ POLICY `, rName) } -func testAccDeploymentGroupECSBlueGreenConfig(rName string) string { - return testAccDeploymentGroupECSBaseConfig(rName) + fmt.Sprintf(` +func testAccDeploymentGroupConfig_ecsBlueGreen(rName string) string { + return testAccDeploymentGroupConfig_ecsBase(rName) + fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_config_name = "CodeDeployDefault.ECSAllAtOnce" @@ -3572,8 +3572,8 @@ resource "aws_codedeploy_deployment_group" "test" { `, rName) } -func testAccDeploymentGroupECSBlueGreenUpdateConfig(rName string) string { - return testAccDeploymentGroupECSBaseConfig(rName) + fmt.Sprintf(` +func testAccDeploymentGroupConfig_ecsBlueGreenUpdate(rName string) string { + return testAccDeploymentGroupConfig_ecsBase(rName) + fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_config_name = "CodeDeployDefault.ECSAllAtOnce" @@ -3626,8 +3626,8 @@ resource "aws_codedeploy_deployment_group" "test" { `, rName) } -func testAccDeploymentGroupTags1Config(rName, tagKey1, tagValue1 string) string { - return testAccDeploymentGroupBaseConfig(rName) + fmt.Sprintf(` +func testAccDeploymentGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { + return testAccDeploymentGroupConfig_base2(rName) + fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" @@ -3640,8 +3640,8 @@ resource "aws_codedeploy_deployment_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccDeploymentGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return testAccDeploymentGroupBaseConfig(rName) + fmt.Sprintf(` +func testAccDeploymentGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return testAccDeploymentGroupConfig_base2(rName) + fmt.Sprintf(` resource "aws_codedeploy_deployment_group" "test" { app_name = aws_codedeploy_app.test.name deployment_group_name = "tf-acc-test-%[1]s" diff --git a/internal/service/detective/find.go b/internal/service/detective/find.go index f19b817870e..0bd05414496 100644 --- a/internal/service/detective/find.go +++ b/internal/service/detective/find.go @@ -51,7 +51,7 @@ func FindGraphByARN(conn *detective.Detective, ctx context.Context, arn string) return result, nil } -func FindInvitationByGraphArn(ctx context.Context, conn *detective.Detective, graphARN string) (*string, error) { +func FindInvitationByGraphARN(ctx context.Context, conn *detective.Detective, graphARN string) (*string, error) { input := &detective.ListInvitationsInput{} var result *string @@ -85,7 +85,7 @@ func FindInvitationByGraphArn(ctx context.Context, conn *detective.Detective, gr return result, nil } -func FindMemberByGraphArnAndAccountID(ctx context.Context, conn *detective.Detective, graphARN string, accountID string) (*detective.MemberDetail, error) { +func FindMemberByGraphARNAndAccountID(ctx context.Context, conn *detective.Detective, graphARN string, accountID string) (*detective.MemberDetail, error) { input := &detective.ListMembersInput{ GraphArn: aws.String(graphARN), } diff --git a/internal/service/detective/invitation_accepter.go b/internal/service/detective/invitation_accepter.go index 6396595e87b..fa002b919ed 100644 --- a/internal/service/detective/invitation_accepter.go +++ b/internal/service/detective/invitation_accepter.go @@ -55,7 +55,7 @@ func resourceInvitationAccepterCreate(ctx context.Context, d *schema.ResourceDat func resourceInvitationAccepterRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { conn := meta.(*conns.AWSClient).DetectiveConn - graphArn, err := FindInvitationByGraphArn(ctx, conn, d.Id()) + graphArn, err := FindInvitationByGraphARN(ctx, conn, d.Id()) if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, detective.ErrCodeResourceNotFoundException) { log.Printf("[WARN] Detective InvitationAccepter (%s) not found, removing from state", d.Id()) diff --git a/internal/service/detective/invitation_accepter_test.go b/internal/service/detective/invitation_accepter_test.go index ac02dde628c..fb46f02c2a9 100644 --- a/internal/service/detective/invitation_accepter_test.go +++ b/internal/service/detective/invitation_accepter_test.go @@ -59,7 +59,7 @@ func testAccCheckInvitationAccepterExists(resourceName string) resource.TestChec conn := acctest.Provider.Meta().(*conns.AWSClient).DetectiveConn - result, err := tfdetective.FindInvitationByGraphArn(context.Background(), conn, rs.Primary.ID) + result, err := tfdetective.FindInvitationByGraphARN(context.Background(), conn, rs.Primary.ID) if err != nil { return err @@ -81,7 +81,7 @@ func testAccCheckInvitationAccepterDestroy(s *terraform.State) error { continue } - result, err := tfdetective.FindInvitationByGraphArn(context.Background(), conn, rs.Primary.ID) + result, err := tfdetective.FindInvitationByGraphARN(context.Background(), conn, rs.Primary.ID) if tfawserr.ErrCodeEquals(err, detective.ErrCodeResourceNotFoundException) || tfresource.NotFound(err) { diff --git a/internal/service/detective/member.go b/internal/service/detective/member.go index 0a4e21ec3fb..bbefce94766 100644 --- a/internal/service/detective/member.go +++ b/internal/service/detective/member.go @@ -146,7 +146,7 @@ func resourceMemberRead(ctx context.Context, d *schema.ResourceData, meta interf return diag.Errorf("error decoding ID Detective Member (%s): %s", d.Id(), err) } - resp, err := FindMemberByGraphArnAndAccountID(ctx, conn, graphArn, accountId) + resp, err := FindMemberByGraphARNAndAccountID(ctx, conn, graphArn, accountId) if err != nil { if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, detective.ErrCodeResourceNotFoundException) || diff --git a/internal/service/detective/member_test.go b/internal/service/detective/member_test.go index 3d68da26f42..b13f0b2c72e 100644 --- a/internal/service/detective/member_test.go +++ b/internal/service/detective/member_test.go @@ -143,7 +143,7 @@ func testAccCheckMemberExists(resourceName string, detectiveSession *detective.M return err } - resp, err := tfdetective.FindMemberByGraphArnAndAccountID(context.Background(), conn, graphArn, accountId) + resp, err := tfdetective.FindMemberByGraphARNAndAccountID(context.Background(), conn, graphArn, accountId) if err != nil { return err } @@ -171,7 +171,7 @@ func testAccCheckMemberDestroy(s *terraform.State) error { return err } - resp, err := tfdetective.FindMemberByGraphArnAndAccountID(context.Background(), conn, graphArn, accountId) + resp, err := tfdetective.FindMemberByGraphARNAndAccountID(context.Background(), conn, graphArn, accountId) if tfawserr.ErrCodeEquals(err, detective.ErrCodeResourceNotFoundException) { continue } diff --git a/internal/service/detective/status.go b/internal/service/detective/status.go index c55cbcb5cfc..ae92579f55d 100644 --- a/internal/service/detective/status.go +++ b/internal/service/detective/status.go @@ -11,7 +11,7 @@ import ( // MemberStatus fetches the Member and its status func MemberStatus(ctx context.Context, conn *detective.Detective, graphARN, adminAccountID string) resource.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindMemberByGraphArnAndAccountID(ctx, conn, graphARN, adminAccountID) + output, err := FindMemberByGraphARNAndAccountID(ctx, conn, graphARN, adminAccountID) if err != nil { return nil, "Unknown", err diff --git a/internal/service/devicefarm/device_pool.go b/internal/service/devicefarm/device_pool.go index a543beb5d0d..0aded4bf0b1 100644 --- a/internal/service/devicefarm/device_pool.go +++ b/internal/service/devicefarm/device_pool.go @@ -128,7 +128,7 @@ func resourceDevicePoolRead(d *schema.ResourceData, meta interface{}) error { defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - devicePool, err := FindDevicepoolByArn(conn, d.Id()) + devicePool, err := FindDevicePoolByARN(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] DeviceFarm DevicePool (%s) not found, removing from state", d.Id()) diff --git a/internal/service/devicefarm/device_pool_test.go b/internal/service/devicefarm/device_pool_test.go index 4df84011b7a..f149fd86a3e 100644 --- a/internal/service/devicefarm/device_pool_test.go +++ b/internal/service/devicefarm/device_pool_test.go @@ -185,7 +185,7 @@ func testAccCheckDevicePoolExists(n string, v *devicefarm.DevicePool) resource.T } conn := acctest.Provider.Meta().(*conns.AWSClient).DeviceFarmConn - resp, err := tfdevicefarm.FindDevicepoolByArn(conn, rs.Primary.ID) + resp, err := tfdevicefarm.FindDevicePoolByARN(conn, rs.Primary.ID) if err != nil { return err } @@ -208,7 +208,7 @@ func testAccCheckDevicePoolDestroy(s *terraform.State) error { } // Try to find the resource - _, err := tfdevicefarm.FindDevicepoolByArn(conn, rs.Primary.ID) + _, err := tfdevicefarm.FindDevicePoolByARN(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue } diff --git a/internal/service/devicefarm/find.go b/internal/service/devicefarm/find.go index 030489779aa..0c3bb02e6d3 100644 --- a/internal/service/devicefarm/find.go +++ b/internal/service/devicefarm/find.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func FindDevicepoolByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.DevicePool, error) { +func FindDevicePoolByARN(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.DevicePool, error) { input := &devicefarm.GetDevicePoolInput{ Arn: aws.String(arn), @@ -33,7 +33,7 @@ func FindDevicepoolByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.D return output.DevicePool, nil } -func FindProjectByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.Project, error) { +func FindProjectByARN(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.Project, error) { input := &devicefarm.GetProjectInput{ Arn: aws.String(arn), @@ -58,7 +58,7 @@ func FindProjectByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.Proj return output.Project, nil } -func FindUploadByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.Upload, error) { +func FindUploadByARN(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.Upload, error) { input := &devicefarm.GetUploadInput{ Arn: aws.String(arn), @@ -83,7 +83,7 @@ func FindUploadByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.Uploa return output.Upload, nil } -func FindNetworkProfileByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.NetworkProfile, error) { +func FindNetworkProfileByARN(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.NetworkProfile, error) { input := &devicefarm.GetNetworkProfileInput{ Arn: aws.String(arn), @@ -108,7 +108,7 @@ func FindNetworkProfileByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefa return output.NetworkProfile, nil } -func FindInstanceProfileByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.InstanceProfile, error) { +func FindInstanceProfileByARN(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.InstanceProfile, error) { input := &devicefarm.GetInstanceProfileInput{ Arn: aws.String(arn), @@ -133,7 +133,7 @@ func FindInstanceProfileByArn(conn *devicefarm.DeviceFarm, arn string) (*devicef return output.InstanceProfile, nil } -func FindTestGridProjectByArn(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.TestGridProject, error) { +func FindTestGridProjectByARN(conn *devicefarm.DeviceFarm, arn string) (*devicefarm.TestGridProject, error) { input := &devicefarm.GetTestGridProjectInput{ ProjectArn: aws.String(arn), diff --git a/internal/service/devicefarm/instance_profile.go b/internal/service/devicefarm/instance_profile.go index 31682732286..fb26658432f 100644 --- a/internal/service/devicefarm/instance_profile.go +++ b/internal/service/devicefarm/instance_profile.go @@ -110,7 +110,7 @@ func resourceInstanceProfileRead(d *schema.ResourceData, meta interface{}) error defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - instaceProf, err := FindInstanceProfileByArn(conn, d.Id()) + instaceProf, err := FindInstanceProfileByARN(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] DeviceFarm Instance Profile (%s) not found, removing from state", d.Id()) diff --git a/internal/service/devicefarm/instance_profile_test.go b/internal/service/devicefarm/instance_profile_test.go index 60f0a528646..af01d5d39ba 100644 --- a/internal/service/devicefarm/instance_profile_test.go +++ b/internal/service/devicefarm/instance_profile_test.go @@ -156,7 +156,7 @@ func testAccCheckInstanceProfileExists(n string, v *devicefarm.InstanceProfile) } conn := acctest.Provider.Meta().(*conns.AWSClient).DeviceFarmConn - resp, err := tfdevicefarm.FindInstanceProfileByArn(conn, rs.Primary.ID) + resp, err := tfdevicefarm.FindInstanceProfileByARN(conn, rs.Primary.ID) if err != nil { return err } @@ -179,7 +179,7 @@ func testAccCheckInstanceProfileDestroy(s *terraform.State) error { } // Try to find the resource - _, err := tfdevicefarm.FindInstanceProfileByArn(conn, rs.Primary.ID) + _, err := tfdevicefarm.FindInstanceProfileByARN(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue } diff --git a/internal/service/devicefarm/network_profile.go b/internal/service/devicefarm/network_profile.go index 99056aaa0ad..e016dc16dcc 100644 --- a/internal/service/devicefarm/network_profile.go +++ b/internal/service/devicefarm/network_profile.go @@ -173,7 +173,7 @@ func resourceNetworkProfileRead(d *schema.ResourceData, meta interface{}) error defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - project, err := FindNetworkProfileByArn(conn, d.Id()) + project, err := FindNetworkProfileByARN(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] DeviceFarm Network Profile (%s) not found, removing from state", d.Id()) diff --git a/internal/service/devicefarm/network_profile_test.go b/internal/service/devicefarm/network_profile_test.go index 44b2dc08e1c..84d5a68d31b 100644 --- a/internal/service/devicefarm/network_profile_test.go +++ b/internal/service/devicefarm/network_profile_test.go @@ -192,7 +192,7 @@ func testAccCheckNetworkProfileExists(n string, v *devicefarm.NetworkProfile) re } conn := acctest.Provider.Meta().(*conns.AWSClient).DeviceFarmConn - resp, err := tfdevicefarm.FindNetworkProfileByArn(conn, rs.Primary.ID) + resp, err := tfdevicefarm.FindNetworkProfileByARN(conn, rs.Primary.ID) if err != nil { return err } @@ -215,7 +215,7 @@ func testAccCheckNetworkProfileDestroy(s *terraform.State) error { } // Try to find the resource - _, err := tfdevicefarm.FindNetworkProfileByArn(conn, rs.Primary.ID) + _, err := tfdevicefarm.FindNetworkProfileByARN(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue } diff --git a/internal/service/devicefarm/project.go b/internal/service/devicefarm/project.go index a1d518fb35d..690b37b7b4c 100644 --- a/internal/service/devicefarm/project.go +++ b/internal/service/devicefarm/project.go @@ -85,7 +85,7 @@ func resourceProjectRead(d *schema.ResourceData, meta interface{}) error { defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - project, err := FindProjectByArn(conn, d.Id()) + project, err := FindProjectByARN(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] DeviceFarm Project (%s) not found, removing from state", d.Id()) diff --git a/internal/service/devicefarm/project_test.go b/internal/service/devicefarm/project_test.go index 8d7452c2037..4f99daede8c 100644 --- a/internal/service/devicefarm/project_test.go +++ b/internal/service/devicefarm/project_test.go @@ -195,7 +195,7 @@ func testAccCheckProjectExists(n string, v *devicefarm.Project) resource.TestChe } conn := acctest.Provider.Meta().(*conns.AWSClient).DeviceFarmConn - resp, err := tfdevicefarm.FindProjectByArn(conn, rs.Primary.ID) + resp, err := tfdevicefarm.FindProjectByARN(conn, rs.Primary.ID) if err != nil { return err } @@ -218,7 +218,7 @@ func testAccCheckProjectDestroy(s *terraform.State) error { } // Try to find the resource - _, err := tfdevicefarm.FindProjectByArn(conn, rs.Primary.ID) + _, err := tfdevicefarm.FindProjectByARN(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue } diff --git a/internal/service/devicefarm/test_grid_project.go b/internal/service/devicefarm/test_grid_project.go index 3a83d09564b..faaf7894756 100644 --- a/internal/service/devicefarm/test_grid_project.go +++ b/internal/service/devicefarm/test_grid_project.go @@ -88,7 +88,7 @@ func resourceTestGridProjectCreate(d *schema.ResourceData, meta interface{}) err } if v, ok := d.GetOk("vpc_config"); ok { - input.VpcConfig = expandTestGridProjectVpcConfig(v.([]interface{})) + input.VpcConfig = expandTestGridProjectVPCConfig(v.([]interface{})) } log.Printf("[DEBUG] Creating DeviceFarm Test Grid Project: %s", name) @@ -115,7 +115,7 @@ func resourceTestGridProjectRead(d *schema.ResourceData, meta interface{}) error defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - project, err := FindTestGridProjectByArn(conn, d.Id()) + project, err := FindTestGridProjectByARN(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] DeviceFarm Test Grid Project (%s) not found, removing from state", d.Id()) @@ -131,7 +131,7 @@ func resourceTestGridProjectRead(d *schema.ResourceData, meta interface{}) error d.Set("name", project.Name) d.Set("arn", arn) d.Set("description", project.Description) - if err := d.Set("vpc_config", flattenTestGridProjectVpcConfig(project.VpcConfig)); err != nil { + if err := d.Set("vpc_config", flattenTestGridProjectVPCConfig(project.VpcConfig)); err != nil { return fmt.Errorf("error setting vpc_config: %w", err) } @@ -208,7 +208,7 @@ func resourceTestGridProjectDelete(d *schema.ResourceData, meta interface{}) err return nil } -func expandTestGridProjectVpcConfig(l []interface{}) *devicefarm.TestGridVpcConfig { +func expandTestGridProjectVPCConfig(l []interface{}) *devicefarm.TestGridVpcConfig { if len(l) == 0 { return nil } @@ -224,7 +224,7 @@ func expandTestGridProjectVpcConfig(l []interface{}) *devicefarm.TestGridVpcConf return config } -func flattenTestGridProjectVpcConfig(conf *devicefarm.TestGridVpcConfig) []interface{} { +func flattenTestGridProjectVPCConfig(conf *devicefarm.TestGridVpcConfig) []interface{} { if conf == nil { return []interface{}{} } diff --git a/internal/service/devicefarm/test_grid_project_test.go b/internal/service/devicefarm/test_grid_project_test.go index 7ed15b7b80f..a3f8ff96ece 100644 --- a/internal/service/devicefarm/test_grid_project_test.go +++ b/internal/service/devicefarm/test_grid_project_test.go @@ -189,7 +189,7 @@ func testAccCheckProjectTestGridProjectExists(n string, v *devicefarm.TestGridPr } conn := acctest.Provider.Meta().(*conns.AWSClient).DeviceFarmConn - resp, err := tfdevicefarm.FindTestGridProjectByArn(conn, rs.Primary.ID) + resp, err := tfdevicefarm.FindTestGridProjectByARN(conn, rs.Primary.ID) if err != nil { return err } @@ -212,7 +212,7 @@ func testAccCheckProjectTestGridProjectDestroy(s *terraform.State) error { } // Try to find the resource - _, err := tfdevicefarm.FindTestGridProjectByArn(conn, rs.Primary.ID) + _, err := tfdevicefarm.FindTestGridProjectByARN(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue } diff --git a/internal/service/devicefarm/upload.go b/internal/service/devicefarm/upload.go index 3b784a62bf2..7026418de92 100644 --- a/internal/service/devicefarm/upload.go +++ b/internal/service/devicefarm/upload.go @@ -95,7 +95,7 @@ func resourceUploadCreate(d *schema.ResourceData, meta interface{}) error { func resourceUploadRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).DeviceFarmConn - upload, err := FindUploadByArn(conn, d.Id()) + upload, err := FindUploadByARN(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] DeviceFarm Upload (%s) not found, removing from state", d.Id()) diff --git a/internal/service/devicefarm/upload_test.go b/internal/service/devicefarm/upload_test.go index f86f1396892..1d83f1a7f3c 100644 --- a/internal/service/devicefarm/upload_test.go +++ b/internal/service/devicefarm/upload_test.go @@ -138,7 +138,7 @@ func testAccCheckUploadExists(n string, v *devicefarm.Upload) resource.TestCheck } conn := acctest.Provider.Meta().(*conns.AWSClient).DeviceFarmConn - resp, err := tfdevicefarm.FindUploadByArn(conn, rs.Primary.ID) + resp, err := tfdevicefarm.FindUploadByARN(conn, rs.Primary.ID) if err != nil { return err } @@ -161,7 +161,7 @@ func testAccCheckUploadDestroy(s *terraform.State) error { } // Try to find the resource - _, err := tfdevicefarm.FindUploadByArn(conn, rs.Primary.ID) + _, err := tfdevicefarm.FindUploadByARN(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue } diff --git a/internal/service/directconnect/connection_association_test.go b/internal/service/directconnect/connection_association_test.go index cb7daab79c6..a45542a2a15 100644 --- a/internal/service/directconnect/connection_association_test.go +++ b/internal/service/directconnect/connection_association_test.go @@ -45,7 +45,7 @@ func TestAccDirectConnectConnectionAssociation_lagOnConnection(t *testing.T) { CheckDestroy: testAccCheckConnectionAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionAssociationConfig_lagOnConnection(rName), + Config: testAccConnectionAssociationConfig_lagOn(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionAssociationExists(resourceName), ), @@ -151,7 +151,7 @@ resource "aws_dx_connection_association" "test" { `, rName) } -func testAccConnectionAssociationConfig_lagOnConnection(rName string) string { +func testAccConnectionAssociationConfig_lagOn(rName string) string { return fmt.Sprintf(` data "aws_dx_locations" "test" {} diff --git a/internal/service/directconnect/connection_data_source_test.go b/internal/service/directconnect/connection_data_source_test.go index 46c283ff765..a72eacadac7 100644 --- a/internal/service/directconnect/connection_data_source_test.go +++ b/internal/service/directconnect/connection_data_source_test.go @@ -21,7 +21,7 @@ func TestAccDirectConnectConnectionDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectionDataSourceConfig(rName), + Config: testAccConnectionDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "aws_device", resourceName, "aws_device"), @@ -37,7 +37,7 @@ func TestAccDirectConnectConnectionDataSource_basic(t *testing.T) { }) } -func testAccConnectionDataSourceConfig(rName string) string { +func testAccConnectionDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_dx_locations" "test" {} diff --git a/internal/service/directconnect/gateway_association_proposal_test.go b/internal/service/directconnect/gateway_association_proposal_test.go index a408ea0b47a..c5c5f19b5b1 100644 --- a/internal/service/directconnect/gateway_association_proposal_test.go +++ b/internal/service/directconnect/gateway_association_proposal_test.go @@ -33,7 +33,7 @@ func TestAccDirectConnectGatewayAssociationProposal_basicVPNGateway(t *testing.T CheckDestroy: testAccCheckGatewayAssociationProposalDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationProposalConfig_basicVPNGateway(rName, rBgpAsn), + Config: testAccGatewayAssociationProposalConfig_basicVPN(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationProposalExists(resourceName, &proposal), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "1"), @@ -44,7 +44,7 @@ func TestAccDirectConnectGatewayAssociationProposal_basicVPNGateway(t *testing.T ), }, { - Config: testAccGatewayAssociationProposalConfig_basicVPNGateway(rName, rBgpAsn), + Config: testAccGatewayAssociationProposalConfig_basicVPN(rName, rBgpAsn), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -69,7 +69,7 @@ func TestAccDirectConnectGatewayAssociationProposal_basicTransitGateway(t *testi CheckDestroy: testAccCheckGatewayAssociationProposalDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationProposalConfig_basicTransitGateway(rName, rBgpAsn), + Config: testAccGatewayAssociationProposalConfig_basicTransit(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationProposalExists(resourceName, &proposal), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "2"), @@ -82,7 +82,7 @@ func TestAccDirectConnectGatewayAssociationProposal_basicTransitGateway(t *testi ), }, { - Config: testAccGatewayAssociationProposalConfig_basicVPNGateway(rName, rBgpAsn), + Config: testAccGatewayAssociationProposalConfig_basicVPN(rName, rBgpAsn), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -105,7 +105,7 @@ func TestAccDirectConnectGatewayAssociationProposal_disappears(t *testing.T) { CheckDestroy: testAccCheckGatewayAssociationProposalDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationProposalConfig_basicVPNGateway(rName, rBgpAsn), + Config: testAccGatewayAssociationProposalConfig_basicVPN(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationProposalExists(resourceName, &proposal), acctest.CheckResourceDisappears(acctest.Provider, tfdirectconnect.ResourceGatewayAssociationProposal(), resourceName), @@ -337,7 +337,7 @@ resource "aws_vpn_gateway" "test" { `, rName, rBgpAsn)) } -func testAccGatewayAssociationProposalConfig_basicVPNGateway(rName string, rBgpAsn int) string { +func testAccGatewayAssociationProposalConfig_basicVPN(rName string, rBgpAsn int) string { return acctest.ConfigCompose(testAccGatewayAssociationProposalConfigBase_vpnGateway(rName, rBgpAsn), ` resource "aws_dx_gateway_association_proposal" "test" { dx_gateway_id = aws_dx_gateway.test.id @@ -348,7 +348,7 @@ resource "aws_dx_gateway_association_proposal" "test" { } func testAccGatewayAssociationProposalConfig_endOfLifeVPN(rName string, rBgpAsn int) string { - return acctest.ConfigCompose(testAccGatewayAssociationProposalConfig_basicVPNGateway(rName, rBgpAsn), ` + return acctest.ConfigCompose(testAccGatewayAssociationProposalConfig_basicVPN(rName, rBgpAsn), ` data "aws_caller_identity" "current" {} resource "aws_dx_gateway_association" "test" { @@ -362,7 +362,7 @@ resource "aws_dx_gateway_association" "test" { } func testAccGatewayAssociationProposalConfig_endOfLifeTgw(rName string, rBgpAsn int) string { - return acctest.ConfigCompose(testAccGatewayAssociationProposalConfig_basicTransitGateway(rName, rBgpAsn), ` + return acctest.ConfigCompose(testAccGatewayAssociationProposalConfig_basicTransit(rName, rBgpAsn), ` data "aws_caller_identity" "current" {} resource "aws_dx_gateway_association" "test" { @@ -375,7 +375,7 @@ resource "aws_dx_gateway_association" "test" { `) } -func testAccGatewayAssociationProposalConfig_basicTransitGateway(rName string, rBgpAsn int) string { +func testAccGatewayAssociationProposalConfig_basicTransit(rName string, rBgpAsn int) string { return acctest.ConfigCompose(acctest.ConfigAlternateAccountProvider(), fmt.Sprintf(` resource "aws_dx_gateway" "test" { provider = "awsalternate" diff --git a/internal/service/directconnect/gateway_association_test.go b/internal/service/directconnect/gateway_association_test.go index 40a23782f39..a467a450a37 100644 --- a/internal/service/directconnect/gateway_association_test.go +++ b/internal/service/directconnect/gateway_association_test.go @@ -32,7 +32,7 @@ func TestAccDirectConnectGatewayAssociation_v0StateUpgrade(t *testing.T) { CheckDestroy: testAccCheckGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_basicVPNGatewaySingleAccount(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_basicVPNSingleAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga, &gap), testAccCheckGatewayAssociationStateUpgradeV0(resourceName), @@ -58,7 +58,7 @@ func TestAccDirectConnectGatewayAssociation_basicVPNGatewaySingleAccount(t *test CheckDestroy: testAccCheckGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_basicVPNGatewaySingleAccount(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_basicVPNSingleAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga, &gap), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "1"), @@ -98,7 +98,7 @@ func TestAccDirectConnectGatewayAssociation_basicVPNGatewayCrossAccount(t *testi CheckDestroy: testAccCheckGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_basicVPNGatewayCrossAccount(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_basicVPNCrossAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga, &gap), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "1"), @@ -132,7 +132,7 @@ func TestAccDirectConnectGatewayAssociation_basicTransitGatewaySingleAccount(t * CheckDestroy: testAccCheckGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_basicTransitGatewaySingleAccount(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_basicTransitSingleAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga, &gap), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "2"), @@ -173,7 +173,7 @@ func TestAccDirectConnectGatewayAssociation_basicTransitGatewayCrossAccount(t *t CheckDestroy: testAccCheckGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_basicTransitGatewayCrossAccount(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_basicTransitCrossAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga, &gap), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "2"), @@ -207,7 +207,7 @@ func TestAccDirectConnectGatewayAssociation_multiVPNGatewaysSingleAccount(t *tes CheckDestroy: testAccCheckGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_multiVPNGatewaysSingleAccount(rName, rBgpAsn), + Config: testAccGatewayConfig_associationMultiVPNSingleAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName1, &ga, &gap), testAccCheckGatewayAssociationExists(resourceName2, &ga, &gap), @@ -239,7 +239,7 @@ func TestAccDirectConnectGatewayAssociation_allowedPrefixesVPNGatewaySingleAccou CheckDestroy: testAccCheckGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_allowedPrefixesVPNGatewaySingleAccount(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_allowedPrefixesVPNSingleAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga, &gap), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "2"), @@ -257,7 +257,7 @@ func TestAccDirectConnectGatewayAssociation_allowedPrefixesVPNGatewaySingleAccou ImportStateVerify: true, }, { - Config: testAccGatewayAssociationConfig_allowedPrefixesVPNGatewaySingleAccountUpdated(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_allowedPrefixesVPNSingleAccountUpdated(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga, &gap), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "1"), @@ -285,7 +285,7 @@ func TestAccDirectConnectGatewayAssociation_allowedPrefixesVPNGatewayCrossAccoun CheckDestroy: testAccCheckGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_allowedPrefixesVPNGatewayCrossAccount(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_allowedPrefixesVPNCrossAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga, &gap), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "1"), @@ -298,7 +298,7 @@ func TestAccDirectConnectGatewayAssociation_allowedPrefixesVPNGatewayCrossAccoun ExpectNonEmptyPlan: true, }, { - Config: testAccGatewayAssociationConfig_allowedPrefixesVPNGatewayCrossAccountUpdated(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_allowedPrefixesVPNCrossAccountUpdated(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga, &gap), resource.TestCheckResourceAttr(resourceName, "allowed_prefixes.#", "2"), @@ -328,13 +328,13 @@ func TestAccDirectConnectGatewayAssociation_recreateProposal(t *testing.T) { CheckDestroy: testAccCheckGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_basicVPNGatewayCrossAccount(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_basicVPNCrossAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga1, &gap1), ), }, { - Config: testAccGatewayAssociationConfig_basicVPNGatewayCrossAccountUpdatedProposal(rName, rBgpAsn), + Config: testAccGatewayAssociationConfig_basicVPNCrossAccountUpdatedProposal(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayAssociationExists(resourceName, &ga2, &gap2), testAccCheckGatewayAssociationNotRecreated(&ga1, &ga2), @@ -519,7 +519,7 @@ resource "aws_dx_gateway" "test" { `, rName, rBgpAsn)) } -func testAccGatewayAssociationConfig_basicVPNGatewaySingleAccount(rName string, rBgpAsn int) string { +func testAccGatewayAssociationConfig_basicVPNSingleAccount(rName string, rBgpAsn int) string { return acctest.ConfigCompose( testAccGatewayAssociationConfigBase_vpnGatewaySingleAccount(rName, rBgpAsn), ` @@ -530,7 +530,7 @@ resource "aws_dx_gateway_association" "test" { `) } -func testAccGatewayAssociationConfig_basicVPNGatewayCrossAccount(rName string, rBgpAsn int) string { +func testAccGatewayAssociationConfig_basicVPNCrossAccount(rName string, rBgpAsn int) string { return acctest.ConfigCompose( testAccGatewayAssociationConfigBase_vpnGatewayCrossAccount(rName, rBgpAsn), ` @@ -552,7 +552,7 @@ resource "aws_dx_gateway_association" "test" { `) } -func testAccGatewayAssociationConfig_basicVPNGatewayCrossAccountUpdatedProposal(rName string, rBgpAsn int) string { +func testAccGatewayAssociationConfig_basicVPNCrossAccountUpdatedProposal(rName string, rBgpAsn int) string { return acctest.ConfigCompose( testAccGatewayAssociationConfigBase_vpnGatewayCrossAccount(rName, rBgpAsn), ` @@ -580,7 +580,7 @@ resource "aws_dx_gateway_association" "test" { `) } -func testAccGatewayAssociationConfig_basicTransitGatewaySingleAccount(rName string, rBgpAsn int) string { +func testAccGatewayAssociationConfig_basicTransitSingleAccount(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_dx_gateway" "test" { name = %[1]q @@ -605,7 +605,7 @@ resource "aws_dx_gateway_association" "test" { `, rName, rBgpAsn) } -func testAccGatewayAssociationConfig_basicTransitGatewayCrossAccount(rName string, rBgpAsn int) string { +func testAccGatewayAssociationConfig_basicTransitCrossAccount(rName string, rBgpAsn int) string { return acctest.ConfigCompose( acctest.ConfigAlternateAccountProvider(), fmt.Sprintf(` @@ -649,7 +649,7 @@ resource "aws_dx_gateway_association" "test" { `, rName, rBgpAsn)) } -func testAccGatewayAssociationConfig_multiVPNGatewaysSingleAccount(rName string, rBgpAsn int) string { +func testAccGatewayConfig_associationMultiVPNSingleAccount(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_dx_gateway" "test" { name = %[1]q @@ -690,7 +690,7 @@ resource "aws_dx_gateway_association" "test" { `, rName, rBgpAsn) } -func testAccGatewayAssociationConfig_allowedPrefixesVPNGatewaySingleAccount(rName string, rBgpAsn int) string { +func testAccGatewayAssociationConfig_allowedPrefixesVPNSingleAccount(rName string, rBgpAsn int) string { return acctest.ConfigCompose( testAccGatewayAssociationConfigBase_vpnGatewaySingleAccount(rName, rBgpAsn), ` @@ -706,7 +706,7 @@ resource "aws_dx_gateway_association" "test" { `) } -func testAccGatewayAssociationConfig_allowedPrefixesVPNGatewaySingleAccountUpdated(rName string, rBgpAsn int) string { +func testAccGatewayAssociationConfig_allowedPrefixesVPNSingleAccountUpdated(rName string, rBgpAsn int) string { return acctest.ConfigCompose( testAccGatewayAssociationConfigBase_vpnGatewaySingleAccount(rName, rBgpAsn), ` @@ -721,7 +721,7 @@ resource "aws_dx_gateway_association" "test" { `) } -func testAccGatewayAssociationConfig_allowedPrefixesVPNGatewayCrossAccount(rName string, rBgpAsn int) string { +func testAccGatewayAssociationConfig_allowedPrefixesVPNCrossAccount(rName string, rBgpAsn int) string { return acctest.ConfigCompose( testAccGatewayAssociationConfigBase_vpnGatewayCrossAccount(rName, rBgpAsn), ` @@ -752,7 +752,7 @@ resource "aws_dx_gateway_association" "test" { `) } -func testAccGatewayAssociationConfig_allowedPrefixesVPNGatewayCrossAccountUpdated(rName string, rBgpAsn int) string { +func testAccGatewayAssociationConfig_allowedPrefixesVPNCrossAccountUpdated(rName string, rBgpAsn int) string { return acctest.ConfigCompose( testAccGatewayAssociationConfigBase_vpnGatewayCrossAccount(rName, rBgpAsn), ` diff --git a/internal/service/directconnect/gateway_data_source_test.go b/internal/service/directconnect/gateway_data_source_test.go index 004b7be9d29..a912c7493a2 100644 --- a/internal/service/directconnect/gateway_data_source_test.go +++ b/internal/service/directconnect/gateway_data_source_test.go @@ -22,11 +22,11 @@ func TestAccDirectConnectGatewayDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccGatewayDataSourceConfig_NonExistent, + Config: testAccGatewayDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`Direct Connect Gateway not found`), }, { - Config: testAccGatewayDataSourceConfig_Name(rName, sdkacctest.RandIntRange(64512, 65534)), + Config: testAccGatewayDataSourceConfig_name(rName, sdkacctest.RandIntRange(64512, 65534)), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "amazon_side_asn", resourceName, "amazon_side_asn"), resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), @@ -38,7 +38,7 @@ func TestAccDirectConnectGatewayDataSource_basic(t *testing.T) { }) } -func testAccGatewayDataSourceConfig_Name(rName string, rBgpAsn int) string { +func testAccGatewayDataSourceConfig_name(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_dx_gateway" "wrong" { amazon_side_asn = "%d" @@ -56,7 +56,7 @@ data "aws_dx_gateway" "test" { `, rBgpAsn+1, rName, rBgpAsn, rName) } -const testAccGatewayDataSourceConfig_NonExistent = ` +const testAccGatewayDataSourceConfig_nonExistent = ` data "aws_dx_gateway" "test" { name = "tf-acc-test-does-not-exist" } diff --git a/internal/service/directconnect/gateway_test.go b/internal/service/directconnect/gateway_test.go index b8a457819ed..a2167c5c543 100644 --- a/internal/service/directconnect/gateway_test.go +++ b/internal/service/directconnect/gateway_test.go @@ -79,7 +79,7 @@ func TestAccDirectConnectGateway_complex(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayAssociationConfig_multiVPNGatewaysSingleAccount(rName, rBgpAsn), + Config: testAccGatewayConfig_associationMultiVPNSingleAccount(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &v), acctest.CheckResourceAttrAccountID(resourceName, "owner_account_id"), diff --git a/internal/service/directconnect/location_data_source_test.go b/internal/service/directconnect/location_data_source_test.go index 1e42ed135aa..15e416e11d8 100644 --- a/internal/service/directconnect/location_data_source_test.go +++ b/internal/service/directconnect/location_data_source_test.go @@ -17,7 +17,7 @@ func TestAccDirectConnectLocationDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDataSourceDxLocationConfig_basic, + Config: testAccLocationDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dsResourceName, "available_port_speeds.#"), resource.TestCheckResourceAttrSet(dsResourceName, "available_providers.#"), @@ -29,7 +29,7 @@ func TestAccDirectConnectLocationDataSource_basic(t *testing.T) { }) } -const testAccDataSourceDxLocationConfig_basic = ` +const testAccLocationDataSourceConfig_basic = ` data "aws_dx_locations" "test" {} locals { diff --git a/internal/service/directconnect/private_virtual_interface_test.go b/internal/service/directconnect/private_virtual_interface_test.go index 9ad165816a8..089b220013a 100644 --- a/internal/service/directconnect/private_virtual_interface_test.go +++ b/internal/service/directconnect/private_virtual_interface_test.go @@ -239,7 +239,7 @@ func TestAccDirectConnectPrivateVirtualInterface_siteLink(t *testing.T) { CheckDestroy: testAccCheckPrivateVirtualInterfaceDestroy, Steps: []resource.TestStep{ { - Config: testAccPrivateVirtualInterfaceConfig_SiteLink_basic(connectionId, rName, amzAsn, bgpAsn, vlan, true), + Config: testAccPrivateVirtualInterfaceConfig_siteLinkBasic(connectionId, rName, amzAsn, bgpAsn, vlan, true), Check: resource.ComposeTestCheckFunc( testAccCheckPrivateVirtualInterfaceExists(resourceName, &vif), resource.TestCheckResourceAttr(resourceName, "address_family", "ipv4"), @@ -261,7 +261,7 @@ func TestAccDirectConnectPrivateVirtualInterface_siteLink(t *testing.T) { ), }, { - Config: testAccPrivateVirtualInterfaceConfig_SiteLink_updated(connectionId, rName, amzAsn, bgpAsn, vlan, false), + Config: testAccPrivateVirtualInterfaceConfig_siteLinkUpdated(connectionId, rName, amzAsn, bgpAsn, vlan, false), Check: resource.ComposeTestCheckFunc( testAccCheckPrivateVirtualInterfaceExists(resourceName, &vif), resource.TestCheckResourceAttr(resourceName, "address_family", "ipv4"), @@ -392,7 +392,7 @@ resource "aws_dx_private_virtual_interface" "test" { `, cid, rName, amzAsn, bgpAsn, vlan) } -func testAccPrivateVirtualInterfaceConfig_SiteLink_basic(cid, rName string, amzAsn, bgpAsn, vlan int, sitelink_enabled bool) string { +func testAccPrivateVirtualInterfaceConfig_siteLinkBasic(cid, rName string, amzAsn, bgpAsn, vlan int, sitelink_enabled bool) string { return fmt.Sprintf(` resource "aws_dx_gateway" "test" { amazon_side_asn = %[3]d @@ -411,7 +411,7 @@ resource "aws_dx_private_virtual_interface" "test" { `, cid, rName, amzAsn, bgpAsn, vlan, sitelink_enabled) } -func testAccPrivateVirtualInterfaceConfig_SiteLink_updated(cid, rName string, amzAsn, bgpAsn, vlan int, sitelink_enabled bool) string { +func testAccPrivateVirtualInterfaceConfig_siteLinkUpdated(cid, rName string, amzAsn, bgpAsn, vlan int, sitelink_enabled bool) string { return fmt.Sprintf(` resource "aws_dx_gateway" "test" { amazon_side_asn = %[3]d diff --git a/internal/service/directconnect/transit_virtual_interface_test.go b/internal/service/directconnect/transit_virtual_interface_test.go index 1a8bcc495f3..6cb5ef09599 100644 --- a/internal/service/directconnect/transit_virtual_interface_test.go +++ b/internal/service/directconnect/transit_virtual_interface_test.go @@ -204,7 +204,7 @@ func testAccTransitVirtualInterface_siteLink(t *testing.T) { CheckDestroy: testAccCheckTransitVirtualInterfaceDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitVirtualInterfaceConfig_SiteLink_basic(connectionId, rName, amzAsn, bgpAsn, vlan, true), + Config: testAccTransitVirtualInterfaceConfig_siteLinkBasic(connectionId, rName, amzAsn, bgpAsn, vlan, true), Check: resource.ComposeTestCheckFunc( testAccCheckTransitVirtualInterfaceExists(resourceName, &vif), resource.TestCheckResourceAttr(resourceName, "address_family", "ipv4"), @@ -226,7 +226,7 @@ func testAccTransitVirtualInterface_siteLink(t *testing.T) { ), }, { - Config: testAccTransitVirtualInterfaceConfig_SiteLink_updated(connectionId, rName, amzAsn, bgpAsn, vlan, false), + Config: testAccTransitVirtualInterfaceConfig_siteLinkUpdated(connectionId, rName, amzAsn, bgpAsn, vlan, false), Check: resource.ComposeTestCheckFunc( testAccCheckTransitVirtualInterfaceExists(resourceName, &vif), resource.TestCheckResourceAttr(resourceName, "address_family", "ipv4"), @@ -339,7 +339,7 @@ resource "aws_dx_transit_virtual_interface" "test" { `, cid, rName, bgpAsn, vlan) } -func testAccTransitVirtualInterfaceConfig_SiteLink_basic(cid, rName string, amzAsn, bgpAsn, vlan int, sitelink_enabled bool) string { +func testAccTransitVirtualInterfaceConfig_siteLinkBasic(cid, rName string, amzAsn, bgpAsn, vlan int, sitelink_enabled bool) string { return testAccTransitVirtualInterfaceConfig_base(rName, amzAsn) + fmt.Sprintf(` resource "aws_dx_transit_virtual_interface" "test" { address_family = "ipv4" @@ -354,7 +354,7 @@ resource "aws_dx_transit_virtual_interface" "test" { `, cid, rName, bgpAsn, vlan, sitelink_enabled) } -func testAccTransitVirtualInterfaceConfig_SiteLink_updated(cid, rName string, amzAsn, bgpAsn, vlan int, sitelink_enabled bool) string { +func testAccTransitVirtualInterfaceConfig_siteLinkUpdated(cid, rName string, amzAsn, bgpAsn, vlan int, sitelink_enabled bool) string { return testAccTransitVirtualInterfaceConfig_base(rName, amzAsn) + fmt.Sprintf(` resource "aws_dx_transit_virtual_interface" "test" { address_family = "ipv4" diff --git a/internal/service/dms/certificate_test.go b/internal/service/dms/certificate_test.go index 3aa31dee36b..9600d60bd8f 100644 --- a/internal/service/dms/certificate_test.go +++ b/internal/service/dms/certificate_test.go @@ -26,7 +26,7 @@ func TestAccDMSCertificate_basic(t *testing.T) { CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateConfig(randId), + Config: testAccCertificateConfig_basic(randId), Check: resource.ComposeTestCheckFunc( testAccCertificateExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "certificate_arn"), @@ -52,7 +52,7 @@ func TestAccDMSCertificate_disappears(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccCertificateConfig(randId), + Config: testAccCertificateConfig_basic(randId), Check: resource.ComposeTestCheckFunc( testAccCertificateExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfdms.ResourceCertificate(), resourceName), @@ -74,7 +74,7 @@ func TestAccDMSCertificate_certificateWallet(t *testing.T) { CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateCertificateWalletConfig(rName), + Config: testAccCertificateConfig_wallet(rName), Check: resource.ComposeTestCheckFunc( testAccCertificateExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "certificate_wallet"), @@ -100,7 +100,7 @@ func TestAccDMSCertificate_tags(t *testing.T) { CheckDestroy: testAccCheckCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccCertificateTags1Config(randId, "key1", "value1"), + Config: testAccCertificateConfig_tags1(randId, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCertificateExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -113,7 +113,7 @@ func TestAccDMSCertificate_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCertificateTags2Config(randId, "key1", "value1updated", "key2", "value2"), + Config: testAccCertificateConfig_tags2(randId, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCertificateExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -122,7 +122,7 @@ func TestAccDMSCertificate_tags(t *testing.T) { ), }, { - Config: testAccCertificateTags1Config(randId, "key2", "value2"), + Config: testAccCertificateConfig_tags1(randId, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCertificateExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -200,7 +200,7 @@ func testAccCertificateExists(n string) resource.TestCheckFunc { } } -func testAccCertificateConfig(randId string) string { +func testAccCertificateConfig_basic(randId string) string { return fmt.Sprintf(` resource "aws_dms_certificate" "dms_certificate" { certificate_id = "tf-test-dms-certificate-%[1]s" @@ -209,7 +209,7 @@ resource "aws_dms_certificate" "dms_certificate" { `, randId) } -func testAccCertificateCertificateWalletConfig(rName string) string { +func testAccCertificateConfig_wallet(rName string) string { return fmt.Sprintf(` resource "aws_dms_certificate" "dms_certificate" { certificate_id = %q @@ -218,7 +218,7 @@ resource "aws_dms_certificate" "dms_certificate" { `, rName) } -func testAccCertificateTags1Config(randId, tagKey1, tagValue1 string) string { +func testAccCertificateConfig_tags1(randId, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_dms_certificate" "dms_certificate" { certificate_id = "tf-test-dms-certificate-%[1]s" @@ -231,7 +231,7 @@ resource "aws_dms_certificate" "dms_certificate" { `, randId, tagKey1, tagValue1) } -func testAccCertificateTags2Config(randId, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccCertificateConfig_tags2(randId, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_dms_certificate" "dms_certificate" { certificate_id = "tf-test-dms-certificate-%[1]s" diff --git a/internal/service/dms/consts.go b/internal/service/dms/consts.go index 0340f91db23..38d7e1cd14f 100644 --- a/internal/service/dms/consts.go +++ b/internal/service/dms/consts.go @@ -106,13 +106,13 @@ func s3SettingsCompressionType_Values() []string { } const ( - s3SettingsEncryptionModeSseKMS = "SSE_KMS" - s3SettingsEncryptionModeSseS3 = "SSE_S3" + encryptionModeSseKMS = "SSE_KMS" + encryptionModeSseS3 = "SSE_S3" ) -func s3SettingsEncryptionMode_Values() []string { +func encryptionMode_Values() []string { return []string{ - s3SettingsEncryptionModeSseKMS, - s3SettingsEncryptionModeSseS3, + encryptionModeSseKMS, + encryptionModeSseS3, } } diff --git a/internal/service/dms/endpoint.go b/internal/service/dms/endpoint.go index 3341452fbde..43dd1315291 100644 --- a/internal/service/dms/endpoint.go +++ b/internal/service/dms/endpoint.go @@ -12,7 +12,6 @@ import ( dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "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" @@ -32,6 +31,11 @@ func ResourceEndpoint() *schema.Resource { State: schema.ImportStatePassthrough, }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(5 * time.Minute), + }, + Schema: map[string]*schema.Schema{ "certificate_arn": { Type: schema.TypeString, @@ -329,6 +333,41 @@ func ResourceEndpoint() *schema.Resource { Optional: true, ConflictsWith: []string{"secrets_manager_access_role_arn", "secrets_manager_arn"}, }, + "redshift_settings": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + DiffSuppressFunc: verify.SuppressMissingOptionalConfigurationBlock, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "bucket_folder": { + Type: schema.TypeString, + Optional: true, + }, + "bucket_name": { + Type: schema.TypeString, + Optional: true, + }, + "encryption_mode": { + Type: schema.TypeString, + Optional: true, + Default: encryptionModeSseS3, + ValidateFunc: validation.StringInSlice(encryptionMode_Values(), false), + }, + "server_side_encryption_kms_key_id": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: verify.ValidARN, + }, + "service_access_role_arn": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: verify.ValidARN, + }, + }, + }, + }, "s3_settings": { Type: schema.TypeList, Optional: true, @@ -468,8 +507,8 @@ func ResourceEndpoint() *schema.Resource { "encryption_mode": { Type: schema.TypeString, Optional: true, - Default: s3SettingsEncryptionModeSseS3, - ValidateFunc: validation.StringInSlice(s3SettingsEncryptionMode_Values(), false), + Default: encryptionModeSseS3, + ValidateFunc: validation.StringInSlice(encryptionMode_Values(), false), }, "external_table_definition": { Type: schema.TypeString, @@ -594,79 +633,120 @@ func resourceEndpointCreate(d *schema.ResourceData, meta interface{}) error { defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) - request := &dms.CreateEndpointInput{ - EndpointIdentifier: aws.String(d.Get("endpoint_id").(string)), + endpointID := d.Get("endpoint_id").(string) + input := &dms.CreateEndpointInput{ + EndpointIdentifier: aws.String(endpointID), EndpointType: aws.String(d.Get("endpoint_type").(string)), EngineName: aws.String(d.Get("engine_name").(string)), Tags: Tags(tags.IgnoreAWS()), } if v, ok := d.GetOk("certificate_arn"); ok { - request.CertificateArn = aws.String(v.(string)) + input.CertificateArn = aws.String(v.(string)) } // Send ExtraConnectionAttributes in the API request for all resource types // per https://github.com/hashicorp/terraform-provider-aws/issues/8009 if v, ok := d.GetOk("extra_connection_attributes"); ok { - request.ExtraConnectionAttributes = aws.String(v.(string)) + input.ExtraConnectionAttributes = aws.String(v.(string)) } if v, ok := d.GetOk("kms_key_arn"); ok { - request.KmsKeyId = aws.String(v.(string)) + input.KmsKeyId = aws.String(v.(string)) } if v, ok := d.GetOk("ssl_mode"); ok { - request.SslMode = aws.String(v.(string)) + input.SslMode = aws.String(v.(string)) } switch d.Get("engine_name").(string) { + case engineNameAurora, engineNameMariadb, engineNameMySQL: + if _, ok := d.GetOk("secrets_manager_arn"); ok { + input.MySQLSettings = &dms.MySQLSettings{ + SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), + SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + } + } else { + input.MySQLSettings = &dms.MySQLSettings{ + Username: aws.String(d.Get("username").(string)), + Password: aws.String(d.Get("password").(string)), + ServerName: aws.String(d.Get("server_name").(string)), + Port: aws.Int64(int64(d.Get("port").(int))), + DatabaseName: aws.String(d.Get("database_name").(string)), + } + + // Set connection info in top-level namespace as well + expandTopLevelConnectionInfo(d, input) + } + case engineNameAuroraPostgresql, engineNamePostgres: + if _, ok := d.GetOk("secrets_manager_arn"); ok { + input.PostgreSQLSettings = &dms.PostgreSQLSettings{ + SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), + SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + DatabaseName: aws.String(d.Get("database_name").(string)), + } + } else { + input.PostgreSQLSettings = &dms.PostgreSQLSettings{ + Username: aws.String(d.Get("username").(string)), + Password: aws.String(d.Get("password").(string)), + ServerName: aws.String(d.Get("server_name").(string)), + Port: aws.Int64(int64(d.Get("port").(int))), + DatabaseName: aws.String(d.Get("database_name").(string)), + } + + // Set connection info in top-level namespace as well + expandTopLevelConnectionInfo(d, input) + } case engineNameDynamoDB: - request.DynamoDbSettings = &dms.DynamoDbSettings{ + input.DynamoDbSettings = &dms.DynamoDbSettings{ ServiceAccessRoleArn: aws.String(d.Get("service_access_role").(string)), } case engineNameElasticsearch, engineNameOpenSearch: - request.ElasticsearchSettings = &dms.ElasticsearchSettings{ + input.ElasticsearchSettings = &dms.ElasticsearchSettings{ ServiceAccessRoleArn: aws.String(d.Get("elasticsearch_settings.0.service_access_role_arn").(string)), EndpointUri: aws.String(d.Get("elasticsearch_settings.0.endpoint_uri").(string)), ErrorRetryDuration: aws.Int64(int64(d.Get("elasticsearch_settings.0.error_retry_duration").(int))), FullLoadErrorPercentage: aws.Int64(int64(d.Get("elasticsearch_settings.0.full_load_error_percentage").(int))), } case engineNameKafka: - request.KafkaSettings = expandKafkaSettings(d.Get("kafka_settings").([]interface{})[0].(map[string]interface{})) + input.KafkaSettings = expandKafkaSettings(d.Get("kafka_settings").([]interface{})[0].(map[string]interface{})) case engineNameKinesis: - request.KinesisSettings = expandKinesisSettings(d.Get("kinesis_settings").([]interface{})[0].(map[string]interface{})) + input.KinesisSettings = expandKinesisSettings(d.Get("kinesis_settings").([]interface{})[0].(map[string]interface{})) case engineNameMongodb: - request.MongoDbSettings = &dms.MongoDbSettings{ - Username: aws.String(d.Get("username").(string)), - Password: aws.String(d.Get("password").(string)), - ServerName: aws.String(d.Get("server_name").(string)), - Port: aws.Int64(int64(d.Get("port").(int))), - DatabaseName: aws.String(d.Get("database_name").(string)), - KmsKeyId: aws.String(d.Get("kms_key_arn").(string)), - - AuthType: aws.String(d.Get("mongodb_settings.0.auth_type").(string)), - AuthMechanism: aws.String(d.Get("mongodb_settings.0.auth_mechanism").(string)), - NestingLevel: aws.String(d.Get("mongodb_settings.0.nesting_level").(string)), - ExtractDocId: aws.String(d.Get("mongodb_settings.0.extract_doc_id").(string)), - DocsToInvestigate: aws.String(d.Get("mongodb_settings.0.docs_to_investigate").(string)), - AuthSource: aws.String(d.Get("mongodb_settings.0.auth_source").(string)), + var settings = &dms.MongoDbSettings{} + + if _, ok := d.GetOk("secrets_manager_arn"); ok { + settings.SecretsManagerAccessRoleArn = aws.String(d.Get("secrets_manager_access_role_arn").(string)) + settings.SecretsManagerSecretId = aws.String(d.Get("secrets_manager_arn").(string)) + } else { + settings.Username = aws.String(d.Get("username").(string)) + settings.Password = aws.String(d.Get("password").(string)) + settings.ServerName = aws.String(d.Get("server_name").(string)) + settings.Port = aws.Int64(int64(d.Get("port").(int))) + + // Set connection info in top-level namespace as well + expandTopLevelConnectionInfo(d, input) } - // Set connection info in top-level namespace as well - request.Username = aws.String(d.Get("username").(string)) - request.Password = aws.String(d.Get("password").(string)) - request.ServerName = aws.String(d.Get("server_name").(string)) - request.Port = aws.Int64(int64(d.Get("port").(int))) - request.DatabaseName = aws.String(d.Get("database_name").(string)) + settings.DatabaseName = aws.String(d.Get("database_name").(string)) + settings.KmsKeyId = aws.String(d.Get("kms_key_arn").(string)) + settings.AuthType = aws.String(d.Get("mongodb_settings.0.auth_type").(string)) + settings.AuthMechanism = aws.String(d.Get("mongodb_settings.0.auth_mechanism").(string)) + settings.NestingLevel = aws.String(d.Get("mongodb_settings.0.nesting_level").(string)) + settings.ExtractDocId = aws.String(d.Get("mongodb_settings.0.extract_doc_id").(string)) + settings.DocsToInvestigate = aws.String(d.Get("mongodb_settings.0.docs_to_investigate").(string)) + settings.AuthSource = aws.String(d.Get("mongodb_settings.0.auth_source").(string)) + + input.MongoDbSettings = settings case engineNameOracle: if _, ok := d.GetOk("secrets_manager_arn"); ok { - request.OracleSettings = &dms.OracleSettings{ + input.OracleSettings = &dms.OracleSettings{ SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), DatabaseName: aws.String(d.Get("database_name").(string)), } } else { - request.OracleSettings = &dms.OracleSettings{ + input.OracleSettings = &dms.OracleSettings{ Username: aws.String(d.Get("username").(string)), Password: aws.String(d.Get("password").(string)), ServerName: aws.String(d.Get("server_name").(string)), @@ -675,21 +755,60 @@ func resourceEndpointCreate(d *schema.ResourceData, meta interface{}) error { } // Set connection info in top-level namespace as well - request.Username = aws.String(d.Get("username").(string)) - request.Password = aws.String(d.Get("password").(string)) - request.ServerName = aws.String(d.Get("server_name").(string)) - request.Port = aws.Int64(int64(d.Get("port").(int))) - request.DatabaseName = aws.String(d.Get("database_name").(string)) + expandTopLevelConnectionInfo(d, input) + } + case engineNameRedshift: + var settings = &dms.RedshiftSettings{ + DatabaseName: aws.String(d.Get("database_name").(string)), + } + + if _, ok := d.GetOk("secrets_manager_arn"); ok { + settings.SecretsManagerAccessRoleArn = aws.String(d.Get("secrets_manager_access_role_arn").(string)) + settings.SecretsManagerSecretId = aws.String(d.Get("secrets_manager_arn").(string)) + } else { + settings.Username = aws.String(d.Get("username").(string)) + settings.Password = aws.String(d.Get("password").(string)) + settings.ServerName = aws.String(d.Get("server_name").(string)) + settings.Port = aws.Int64(int64(d.Get("port").(int))) + + // Set connection info in top-level namespace as well + expandTopLevelConnectionInfo(d, input) + } + + if v, ok := d.GetOk("redshift_settings"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + tfMap := v.([]interface{})[0].(map[string]interface{}) + + if v, ok := tfMap["bucket_folder"].(string); ok && v != "" { + settings.BucketFolder = aws.String(v) + } + + if v, ok := tfMap["bucket_name"].(string); ok && v != "" { + settings.BucketName = aws.String(v) + } + + if v, ok := tfMap["encryption_mode"].(string); ok && v != "" { + settings.EncryptionMode = aws.String(v) + } + + if v, ok := tfMap["server_side_encryption_kms_key_id"].(string); ok && v != "" { + settings.ServerSideEncryptionKmsKeyId = aws.String(v) + } + + if v, ok := tfMap["service_access_role_arn"].(string); ok && v != "" { + settings.ServiceAccessRoleArn = aws.String(v) + } } - case engineNamePostgres: + + input.RedshiftSettings = settings + case engineNameSQLServer: if _, ok := d.GetOk("secrets_manager_arn"); ok { - request.PostgreSQLSettings = &dms.PostgreSQLSettings{ + input.MicrosoftSQLServerSettings = &dms.MicrosoftSQLServerSettings{ SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), DatabaseName: aws.String(d.Get("database_name").(string)), } } else { - request.PostgreSQLSettings = &dms.PostgreSQLSettings{ + input.MicrosoftSQLServerSettings = &dms.MicrosoftSQLServerSettings{ Username: aws.String(d.Get("username").(string)), Password: aws.String(d.Get("password").(string)), ServerName: aws.String(d.Get("server_name").(string)), @@ -698,47 +817,27 @@ func resourceEndpointCreate(d *schema.ResourceData, meta interface{}) error { } // Set connection info in top-level namespace as well - request.Username = aws.String(d.Get("username").(string)) - request.Password = aws.String(d.Get("password").(string)) - request.ServerName = aws.String(d.Get("server_name").(string)) - request.Port = aws.Int64(int64(d.Get("port").(int))) - request.DatabaseName = aws.String(d.Get("database_name").(string)) + expandTopLevelConnectionInfo(d, input) } case engineNameS3: - request.S3Settings = expandS3Settings(d.Get("s3_settings").([]interface{})[0].(map[string]interface{})) + input.S3Settings = expandS3Settings(d.Get("s3_settings").([]interface{})[0].(map[string]interface{})) default: - request.Password = aws.String(d.Get("password").(string)) - request.Port = aws.Int64(int64(d.Get("port").(int))) - request.ServerName = aws.String(d.Get("server_name").(string)) - request.Username = aws.String(d.Get("username").(string)) - - if v, ok := d.GetOk("database_name"); ok { - request.DatabaseName = aws.String(v.(string)) - } + expandTopLevelConnectionInfo(d, input) } - log.Println("[DEBUG] DMS create endpoint:", request) - - err := resource.Retry(5*time.Minute, func() *resource.RetryError { - _, err := conn.CreateEndpoint(request) - if tfawserr.ErrCodeEquals(err, "AccessDeniedFault") { - return resource.RetryableError(err) - } - if err != nil { - return resource.NonRetryableError(err) - } + log.Printf("[DEBUG] Creating DMS Endpoint: %s", input) + _, err := tfresource.RetryWhenAWSErrCodeEquals(d.Timeout(schema.TimeoutCreate), + func() (interface{}, error) { + return conn.CreateEndpoint(input) + }, + dms.ErrCodeAccessDeniedFault) - // Successful delete - return nil - }) - if tfresource.TimedOut(err) { - _, err = conn.CreateEndpoint(request) - } if err != nil { - return fmt.Errorf("Error creating DMS endpoint: %s", err) + return fmt.Errorf("creating DMS Endpoint (%s): %w", endpointID, err) } - d.SetId(d.Get("endpoint_id").(string)) + d.SetId(endpointID) + return resourceEndpointRead(d, meta) } @@ -756,7 +855,7 @@ func resourceEndpointRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading DMS Endpoint (%s): %w", d.Id(), err) + return fmt.Errorf("reading DMS Endpoint (%s): %w", d.Id(), err) } err = resourceEndpointSetState(d, endpoint) @@ -768,18 +867,18 @@ func resourceEndpointRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, d.Get("endpoint_arn").(string)) if err != nil { - return fmt.Errorf("error listing tags for DMS Endpoint (%s): %w", d.Get("endpoint_arn").(string), err) + return fmt.Errorf("listing tags for DMS Endpoint (%s): %w", d.Get("endpoint_arn").(string), err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -788,226 +887,299 @@ func resourceEndpointRead(d *schema.ResourceData, meta interface{}) error { func resourceEndpointUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).DMSConn - request := &dms.ModifyEndpointInput{ - EndpointArn: aws.String(d.Get("endpoint_arn").(string)), - } - hasChanges := false - - if d.HasChange("endpoint_type") { - request.EndpointType = aws.String(d.Get("endpoint_type").(string)) - hasChanges = true - } - - if d.HasChange("certificate_arn") { - request.CertificateArn = aws.String(d.Get("certificate_arn").(string)) - hasChanges = true - } - - if d.HasChange("service_access_role") { - request.DynamoDbSettings = &dms.DynamoDbSettings{ - ServiceAccessRoleArn: aws.String(d.Get("service_access_role").(string)), + if d.HasChangesExcept("tags", "tags_all") { + input := &dms.ModifyEndpointInput{ + EndpointArn: aws.String(d.Get("endpoint_arn").(string)), } - hasChanges = true - } - - if d.HasChange("endpoint_type") { - request.EndpointType = aws.String(d.Get("endpoint_type").(string)) - hasChanges = true - } - - if d.HasChange("engine_name") { - request.EngineName = aws.String(d.Get("engine_name").(string)) - hasChanges = true - } - if d.HasChange("extra_connection_attributes") { - request.ExtraConnectionAttributes = aws.String(d.Get("extra_connection_attributes").(string)) - hasChanges = true - } + if d.HasChange("certificate_arn") { + input.CertificateArn = aws.String(d.Get("certificate_arn").(string)) + } - if d.HasChange("ssl_mode") { - request.SslMode = aws.String(d.Get("ssl_mode").(string)) - hasChanges = true - } + if d.HasChange("endpoint_type") { + input.EndpointType = aws.String(d.Get("endpoint_type").(string)) + } - if d.HasChange("tags_all") { - arn := d.Get("endpoint_arn").(string) - o, n := d.GetChange("tags_all") + if d.HasChange("engine_name") { + input.EngineName = aws.String(d.Get("engine_name").(string)) + } - if err := UpdateTags(conn, arn, o, n); err != nil { - return fmt.Errorf("error updating DMS Endpoint (%s) tags: %s", arn, err) + if d.HasChange("extra_connection_attributes") { + input.ExtraConnectionAttributes = aws.String(d.Get("extra_connection_attributes").(string)) } - } - switch engineName := d.Get("engine_name").(string); engineName { - case engineNameDynamoDB: if d.HasChange("service_access_role") { - request.DynamoDbSettings = &dms.DynamoDbSettings{ + input.DynamoDbSettings = &dms.DynamoDbSettings{ ServiceAccessRoleArn: aws.String(d.Get("service_access_role").(string)), } - hasChanges = true } - case engineNameElasticsearch, engineNameOpenSearch: - if d.HasChanges( - "elasticsearch_settings.0.endpoint_uri", - "elasticsearch_settings.0.error_retry_duration", - "elasticsearch_settings.0.full_load_error_percentage", - "elasticsearch_settings.0.service_access_role_arn") { - request.ElasticsearchSettings = &dms.ElasticsearchSettings{ - ServiceAccessRoleArn: aws.String(d.Get("elasticsearch_settings.0.service_access_role_arn").(string)), - EndpointUri: aws.String(d.Get("elasticsearch_settings.0.endpoint_uri").(string)), - ErrorRetryDuration: aws.Int64(int64(d.Get("elasticsearch_settings.0.error_retry_duration").(int))), - FullLoadErrorPercentage: aws.Int64(int64(d.Get("elasticsearch_settings.0.full_load_error_percentage").(int))), - } - request.EngineName = aws.String(engineName) - hasChanges = true - } - case engineNameKafka: - if d.HasChange("kafka_settings") { - request.KafkaSettings = expandKafkaSettings(d.Get("kafka_settings").([]interface{})[0].(map[string]interface{})) - request.EngineName = aws.String(engineName) - hasChanges = true - } - case engineNameKinesis: - if d.HasChanges("kinesis_settings") { - request.KinesisSettings = expandKinesisSettings(d.Get("kinesis_settings").([]interface{})[0].(map[string]interface{})) - request.EngineName = aws.String(engineName) - hasChanges = true - } - case engineNameMongodb: - if d.HasChanges( - "username", "password", "server_name", "port", "database_name", "mongodb_settings.0.auth_type", - "mongodb_settings.0.auth_mechanism", "mongodb_settings.0.nesting_level", "mongodb_settings.0.extract_doc_id", - "mongodb_settings.0.docs_to_investigate", "mongodb_settings.0.auth_source") { - request.MongoDbSettings = &dms.MongoDbSettings{ - Username: aws.String(d.Get("username").(string)), - Password: aws.String(d.Get("password").(string)), - ServerName: aws.String(d.Get("server_name").(string)), - Port: aws.Int64(int64(d.Get("port").(int))), - DatabaseName: aws.String(d.Get("database_name").(string)), - KmsKeyId: aws.String(d.Get("kms_key_arn").(string)), - - AuthType: aws.String(d.Get("mongodb_settings.0.auth_type").(string)), - AuthMechanism: aws.String(d.Get("mongodb_settings.0.auth_mechanism").(string)), - NestingLevel: aws.String(d.Get("mongodb_settings.0.nesting_level").(string)), - ExtractDocId: aws.String(d.Get("mongodb_settings.0.extract_doc_id").(string)), - DocsToInvestigate: aws.String(d.Get("mongodb_settings.0.docs_to_investigate").(string)), - AuthSource: aws.String(d.Get("mongodb_settings.0.auth_source").(string)), - } - request.EngineName = aws.String(engineName) - // Update connection info in top-level namespace as well - request.Username = aws.String(d.Get("username").(string)) - request.Password = aws.String(d.Get("password").(string)) - request.ServerName = aws.String(d.Get("server_name").(string)) - request.Port = aws.Int64(int64(d.Get("port").(int))) - request.DatabaseName = aws.String(d.Get("database_name").(string)) - - hasChanges = true + if d.HasChange("ssl_mode") { + input.SslMode = aws.String(d.Get("ssl_mode").(string)) } - case engineNameOracle: - if d.HasChanges( - "username", "password", "server_name", "port", "database_name", "secrets_manager_access_role_arn", - "secrets_manager_arn") { - if _, ok := d.GetOk("secrets_manager_arn"); ok { - request.OracleSettings = &dms.OracleSettings{ - DatabaseName: aws.String(d.Get("database_name").(string)), - SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), - SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + + switch engineName := d.Get("engine_name").(string); engineName { + case engineNameAurora, engineNameMariadb, engineNameMySQL: + if d.HasChanges( + "username", "password", "server_name", "port", "database_name", "secrets_manager_access_role_arn", + "secrets_manager_arn") { + if _, ok := d.GetOk("secrets_manager_arn"); ok { + input.MySQLSettings = &dms.MySQLSettings{ + SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), + SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + } + } else { + input.MySQLSettings = &dms.MySQLSettings{ + Username: aws.String(d.Get("username").(string)), + Password: aws.String(d.Get("password").(string)), + ServerName: aws.String(d.Get("server_name").(string)), + Port: aws.Int64(int64(d.Get("port").(int))), + DatabaseName: aws.String(d.Get("database_name").(string)), + } + input.EngineName = aws.String(engineName) + + // Update connection info in top-level namespace as well + expandTopLevelConnectionInfoModify(d, input) } - } else { - request.OracleSettings = &dms.OracleSettings{ - Username: aws.String(d.Get("username").(string)), - Password: aws.String(d.Get("password").(string)), - ServerName: aws.String(d.Get("server_name").(string)), - Port: aws.Int64(int64(d.Get("port").(int))), - DatabaseName: aws.String(d.Get("database_name").(string)), + } + case engineNameAuroraPostgresql, engineNamePostgres: + if d.HasChanges( + "username", "password", "server_name", "port", "database_name", "secrets_manager_access_role_arn", + "secrets_manager_arn") { + if _, ok := d.GetOk("secrets_manager_arn"); ok { + input.PostgreSQLSettings = &dms.PostgreSQLSettings{ + DatabaseName: aws.String(d.Get("database_name").(string)), + SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), + SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + } + } else { + input.PostgreSQLSettings = &dms.PostgreSQLSettings{ + Username: aws.String(d.Get("username").(string)), + Password: aws.String(d.Get("password").(string)), + ServerName: aws.String(d.Get("server_name").(string)), + Port: aws.Int64(int64(d.Get("port").(int))), + DatabaseName: aws.String(d.Get("database_name").(string)), + } + input.EngineName = aws.String(engineName) // Must be included (should be 'postgres') + + // Update connection info in top-level namespace as well + expandTopLevelConnectionInfoModify(d, input) } - request.EngineName = aws.String(d.Get("engine_name").(string)) // Must be included (should be 'oracle') - - // Update connection info in top-level namespace as well - request.Username = aws.String(d.Get("username").(string)) - request.Password = aws.String(d.Get("password").(string)) - request.ServerName = aws.String(d.Get("server_name").(string)) - request.Port = aws.Int64(int64(d.Get("port").(int))) - request.DatabaseName = aws.String(d.Get("database_name").(string)) } - hasChanges = true - } - case engineNamePostgres: - if d.HasChanges( - "username", "password", "server_name", "port", "database_name", "secrets_manager_access_role_arn", - "secrets_manager_arn") { - if _, ok := d.GetOk("secrets_manager_arn"); ok { - request.PostgreSQLSettings = &dms.PostgreSQLSettings{ - DatabaseName: aws.String(d.Get("database_name").(string)), - SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), - SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + case engineNameDynamoDB: + if d.HasChange("service_access_role") { + input.DynamoDbSettings = &dms.DynamoDbSettings{ + ServiceAccessRoleArn: aws.String(d.Get("service_access_role").(string)), } - } else { - request.PostgreSQLSettings = &dms.PostgreSQLSettings{ - Username: aws.String(d.Get("username").(string)), - Password: aws.String(d.Get("password").(string)), - ServerName: aws.String(d.Get("server_name").(string)), - Port: aws.Int64(int64(d.Get("port").(int))), - DatabaseName: aws.String(d.Get("database_name").(string)), + } + case engineNameElasticsearch, engineNameOpenSearch: + if d.HasChanges( + "elasticsearch_settings.0.endpoint_uri", + "elasticsearch_settings.0.error_retry_duration", + "elasticsearch_settings.0.full_load_error_percentage", + "elasticsearch_settings.0.service_access_role_arn") { + input.ElasticsearchSettings = &dms.ElasticsearchSettings{ + ServiceAccessRoleArn: aws.String(d.Get("elasticsearch_settings.0.service_access_role_arn").(string)), + EndpointUri: aws.String(d.Get("elasticsearch_settings.0.endpoint_uri").(string)), + ErrorRetryDuration: aws.Int64(int64(d.Get("elasticsearch_settings.0.error_retry_duration").(int))), + FullLoadErrorPercentage: aws.Int64(int64(d.Get("elasticsearch_settings.0.full_load_error_percentage").(int))), } - request.EngineName = aws.String(d.Get("engine_name").(string)) // Must be included (should be 'postgres') - - // Update connection info in top-level namespace as well - request.Username = aws.String(d.Get("username").(string)) - request.Password = aws.String(d.Get("password").(string)) - request.ServerName = aws.String(d.Get("server_name").(string)) - request.Port = aws.Int64(int64(d.Get("port").(int))) - request.DatabaseName = aws.String(d.Get("database_name").(string)) + input.EngineName = aws.String(engineName) + } + case engineNameKafka: + if d.HasChange("kafka_settings") { + input.KafkaSettings = expandKafkaSettings(d.Get("kafka_settings").([]interface{})[0].(map[string]interface{})) + input.EngineName = aws.String(engineName) + } + case engineNameKinesis: + if d.HasChanges("kinesis_settings") { + input.KinesisSettings = expandKinesisSettings(d.Get("kinesis_settings").([]interface{})[0].(map[string]interface{})) + input.EngineName = aws.String(engineName) + } + case engineNameMongodb: + if d.HasChanges( + "username", "password", "server_name", "port", "database_name", "mongodb_settings.0.auth_type", + "mongodb_settings.0.auth_mechanism", "mongodb_settings.0.nesting_level", "mongodb_settings.0.extract_doc_id", + "mongodb_settings.0.docs_to_investigate", "mongodb_settings.0.auth_source", "secrets_manager_access_role_arn", + "secrets_manager_arn") { + if _, ok := d.GetOk("secrets_manager_arn"); ok { + input.MongoDbSettings = &dms.MongoDbSettings{ + SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), + SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + DatabaseName: aws.String(d.Get("database_name").(string)), + KmsKeyId: aws.String(d.Get("kms_key_arn").(string)), + + AuthType: aws.String(d.Get("mongodb_settings.0.auth_type").(string)), + AuthMechanism: aws.String(d.Get("mongodb_settings.0.auth_mechanism").(string)), + NestingLevel: aws.String(d.Get("mongodb_settings.0.nesting_level").(string)), + ExtractDocId: aws.String(d.Get("mongodb_settings.0.extract_doc_id").(string)), + DocsToInvestigate: aws.String(d.Get("mongodb_settings.0.docs_to_investigate").(string)), + AuthSource: aws.String(d.Get("mongodb_settings.0.auth_source").(string)), + } + } else { + input.MongoDbSettings = &dms.MongoDbSettings{ + Username: aws.String(d.Get("username").(string)), + Password: aws.String(d.Get("password").(string)), + ServerName: aws.String(d.Get("server_name").(string)), + Port: aws.Int64(int64(d.Get("port").(int))), + DatabaseName: aws.String(d.Get("database_name").(string)), + KmsKeyId: aws.String(d.Get("kms_key_arn").(string)), + + AuthType: aws.String(d.Get("mongodb_settings.0.auth_type").(string)), + AuthMechanism: aws.String(d.Get("mongodb_settings.0.auth_mechanism").(string)), + NestingLevel: aws.String(d.Get("mongodb_settings.0.nesting_level").(string)), + ExtractDocId: aws.String(d.Get("mongodb_settings.0.extract_doc_id").(string)), + DocsToInvestigate: aws.String(d.Get("mongodb_settings.0.docs_to_investigate").(string)), + AuthSource: aws.String(d.Get("mongodb_settings.0.auth_source").(string)), + } + input.EngineName = aws.String(engineName) + + // Update connection info in top-level namespace as well + expandTopLevelConnectionInfoModify(d, input) + } + } + case engineNameOracle: + if d.HasChanges( + "username", "password", "server_name", "port", "database_name", "secrets_manager_access_role_arn", + "secrets_manager_arn") { + if _, ok := d.GetOk("secrets_manager_arn"); ok { + input.OracleSettings = &dms.OracleSettings{ + DatabaseName: aws.String(d.Get("database_name").(string)), + SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), + SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + } + } else { + input.OracleSettings = &dms.OracleSettings{ + Username: aws.String(d.Get("username").(string)), + Password: aws.String(d.Get("password").(string)), + ServerName: aws.String(d.Get("server_name").(string)), + Port: aws.Int64(int64(d.Get("port").(int))), + DatabaseName: aws.String(d.Get("database_name").(string)), + } + input.EngineName = aws.String(engineName) // Must be included (should be 'oracle') + + // Update connection info in top-level namespace as well + expandTopLevelConnectionInfoModify(d, input) + } + } + case engineNameRedshift: + if d.HasChanges( + "username", "password", "server_name", "port", "database_name", + "redshift_settings", "secrets_manager_access_role_arn", + "secrets_manager_arn") { + if _, ok := d.GetOk("secrets_manager_arn"); ok { + input.RedshiftSettings = &dms.RedshiftSettings{ + DatabaseName: aws.String(d.Get("database_name").(string)), + SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), + SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + } + } else { + input.RedshiftSettings = &dms.RedshiftSettings{ + Username: aws.String(d.Get("username").(string)), + Password: aws.String(d.Get("password").(string)), + ServerName: aws.String(d.Get("server_name").(string)), + Port: aws.Int64(int64(d.Get("port").(int))), + DatabaseName: aws.String(d.Get("database_name").(string)), + } + input.EngineName = aws.String(engineName) // Must be included (should be 'redshift') + + // Update connection info in top-level namespace as well + expandTopLevelConnectionInfoModify(d, input) + + if v, ok := d.GetOk("redshift_settings"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + tfMap := v.([]interface{})[0].(map[string]interface{}) + + if v, ok := tfMap["bucket_folder"].(string); ok && v != "" { + input.RedshiftSettings.BucketFolder = aws.String(v) + } + + if v, ok := tfMap["bucket_name"].(string); ok && v != "" { + input.RedshiftSettings.BucketName = aws.String(v) + } + + if v, ok := tfMap["encryption_mode"].(string); ok && v != "" { + input.RedshiftSettings.EncryptionMode = aws.String(v) + } + + if v, ok := tfMap["server_side_encryption_kms_key_id"].(string); ok && v != "" { + input.RedshiftSettings.ServerSideEncryptionKmsKeyId = aws.String(v) + } + + if v, ok := tfMap["service_access_role_arn"].(string); ok && v != "" { + input.RedshiftSettings.ServiceAccessRoleArn = aws.String(v) + } + } + } + } + case engineNameSQLServer: + if d.HasChanges( + "username", "password", "server_name", "port", "database_name", "secrets_manager_access_role_arn", + "secrets_manager_arn") { + if _, ok := d.GetOk("secrets_manager_arn"); ok { + input.MicrosoftSQLServerSettings = &dms.MicrosoftSQLServerSettings{ + DatabaseName: aws.String(d.Get("database_name").(string)), + SecretsManagerAccessRoleArn: aws.String(d.Get("secrets_manager_access_role_arn").(string)), + SecretsManagerSecretId: aws.String(d.Get("secrets_manager_arn").(string)), + } + } else { + input.MicrosoftSQLServerSettings = &dms.MicrosoftSQLServerSettings{ + Username: aws.String(d.Get("username").(string)), + Password: aws.String(d.Get("password").(string)), + ServerName: aws.String(d.Get("server_name").(string)), + Port: aws.Int64(int64(d.Get("port").(int))), + DatabaseName: aws.String(d.Get("database_name").(string)), + } + input.EngineName = aws.String(engineName) // Must be included (should be 'postgres') + + // Update connection info in top-level namespace as well + expandTopLevelConnectionInfoModify(d, input) + } + } + case engineNameS3: + if d.HasChanges("s3_settings") { + input.S3Settings = expandS3Settings(d.Get("s3_settings").([]interface{})[0].(map[string]interface{})) + input.EngineName = aws.String(engineName) + } + default: + if d.HasChange("database_name") { + input.DatabaseName = aws.String(d.Get("database_name").(string)) } - hasChanges = true - } - case engineNameS3: - if d.HasChanges("s3_settings") { - request.S3Settings = expandS3Settings(d.Get("s3_settings").([]interface{})[0].(map[string]interface{})) - request.EngineName = aws.String(engineName) - hasChanges = true - } - default: - if d.HasChange("database_name") { - request.DatabaseName = aws.String(d.Get("database_name").(string)) - hasChanges = true - } - if d.HasChange("password") { - request.Password = aws.String(d.Get("password").(string)) - hasChanges = true - } + if d.HasChange("password") { + input.Password = aws.String(d.Get("password").(string)) + } - if d.HasChange("port") { - request.Port = aws.Int64(int64(d.Get("port").(int))) - hasChanges = true - } + if d.HasChange("port") { + input.Port = aws.Int64(int64(d.Get("port").(int))) + } - if d.HasChange("server_name") { - request.ServerName = aws.String(d.Get("server_name").(string)) - hasChanges = true - } + if d.HasChange("server_name") { + input.ServerName = aws.String(d.Get("server_name").(string)) + } - if d.HasChange("username") { - request.Username = aws.String(d.Get("username").(string)) - hasChanges = true + if d.HasChange("username") { + input.Username = aws.String(d.Get("username").(string)) + } } - } - if hasChanges { - log.Println("[DEBUG] DMS update endpoint:", request) + log.Printf("[DEBUG] Modifying DMS Endpoint: %s", input) + _, err := conn.ModifyEndpoint(input) - _, err := conn.ModifyEndpoint(request) if err != nil { - return err + return fmt.Errorf("updating DMS Endpoint (%s): %w", d.Id(), err) } + } + + if d.HasChange("tags_all") { + arn := d.Get("endpoint_arn").(string) + o, n := d.GetChange("tags_all") - return resourceEndpointRead(d, meta) + if err := UpdateTags(conn, arn, o, n); err != nil { + return fmt.Errorf("updating DMS Endpoint (%s) tags: %w", arn, err) + } } - return nil + return resourceEndpointRead(d, meta) } func resourceEndpointDelete(d *schema.ResourceData, meta interface{}) error { @@ -1023,13 +1195,11 @@ func resourceEndpointDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting DMS Endpoint (%s): %w", d.Id(), err) + return fmt.Errorf("deleting DMS Endpoint (%s): %w", d.Id(), err) } - _, err = waitEndpointDeleted(conn, d.Id()) - - if err != nil { - return fmt.Errorf("error waiting for DMS Endpoint (%s) delete: %w", d.Id(), err) + if _, err = waitEndpointDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + return fmt.Errorf("waiting for DMS Endpoint (%s) delete: %w", d.Id(), err) } return err @@ -1074,6 +1244,28 @@ func resourceEndpointSetState(d *schema.ResourceData, endpoint *dms.Endpoint) er d.Set("extra_connection_attributes", endpoint.ExtraConnectionAttributes) switch aws.StringValue(endpoint.EngineName) { + case engineNameAurora, engineNameMariadb, engineNameMySQL: + if endpoint.MySQLSettings != nil { + d.Set("username", endpoint.MySQLSettings.Username) + d.Set("server_name", endpoint.MySQLSettings.ServerName) + d.Set("port", endpoint.MySQLSettings.Port) + d.Set("database_name", endpoint.MySQLSettings.DatabaseName) + d.Set("secrets_manager_access_role_arn", endpoint.MySQLSettings.SecretsManagerAccessRoleArn) + d.Set("secrets_manager_arn", endpoint.MySQLSettings.SecretsManagerSecretId) + } else { + flattenTopLevelConnectionInfo(d, endpoint) + } + case engineNameAuroraPostgresql, engineNamePostgres: + if endpoint.PostgreSQLSettings != nil { + d.Set("username", endpoint.PostgreSQLSettings.Username) + d.Set("server_name", endpoint.PostgreSQLSettings.ServerName) + d.Set("port", endpoint.PostgreSQLSettings.Port) + d.Set("database_name", endpoint.PostgreSQLSettings.DatabaseName) + d.Set("secrets_manager_access_role_arn", endpoint.PostgreSQLSettings.SecretsManagerAccessRoleArn) + d.Set("secrets_manager_arn", endpoint.PostgreSQLSettings.SecretsManagerSecretId) + } else { + flattenTopLevelConnectionInfo(d, endpoint) + } case engineNameDynamoDB: if endpoint.DynamoDbSettings != nil { d.Set("service_access_role", endpoint.DynamoDbSettings.ServiceAccessRoleArn) @@ -1082,7 +1274,7 @@ func resourceEndpointSetState(d *schema.ResourceData, endpoint *dms.Endpoint) er } case engineNameElasticsearch, engineNameOpenSearch: if err := d.Set("elasticsearch_settings", flattenOpenSearchSettings(endpoint.ElasticsearchSettings)); err != nil { - return fmt.Errorf("Error setting elasticsearch for DMS: %s", err) + return fmt.Errorf("setting elasticsearch_settings: %w", err) } case engineNameKafka: if endpoint.KafkaSettings != nil { @@ -1091,14 +1283,14 @@ func resourceEndpointSetState(d *schema.ResourceData, endpoint *dms.Endpoint) er tfMap["sasl_password"] = d.Get("kafka_settings.0.sasl_password").(string) if err := d.Set("kafka_settings", []interface{}{tfMap}); err != nil { - return fmt.Errorf("error setting kafka_settings: %w", err) + return fmt.Errorf("setting kafka_settings: %w", err) } } else { d.Set("kafka_settings", nil) } case engineNameKinesis: if err := d.Set("kinesis_settings", []interface{}{flattenKinesisSettings(endpoint.KinesisSettings)}); err != nil { - return fmt.Errorf("error setting kinesis_settings: %w", err) + return fmt.Errorf("setting kinesis_settings: %w", err) } case engineNameMongodb: if endpoint.MongoDbSettings != nil { @@ -1106,14 +1298,13 @@ func resourceEndpointSetState(d *schema.ResourceData, endpoint *dms.Endpoint) er d.Set("server_name", endpoint.MongoDbSettings.ServerName) d.Set("port", endpoint.MongoDbSettings.Port) d.Set("database_name", endpoint.MongoDbSettings.DatabaseName) + d.Set("secrets_manager_access_role_arn", endpoint.MongoDbSettings.SecretsManagerAccessRoleArn) + d.Set("secrets_manager_arn", endpoint.MongoDbSettings.SecretsManagerSecretId) } else { - d.Set("username", endpoint.Username) - d.Set("server_name", endpoint.ServerName) - d.Set("port", endpoint.Port) - d.Set("database_name", endpoint.DatabaseName) + flattenTopLevelConnectionInfo(d, endpoint) } if err := d.Set("mongodb_settings", flattenMongoDBSettings(endpoint.MongoDbSettings)); err != nil { - return fmt.Errorf("Error setting mongodb_settings for DMS: %s", err) + return fmt.Errorf("setting mongodb_settings: %w", err) } case engineNameOracle: if endpoint.OracleSettings != nil { @@ -1124,24 +1315,32 @@ func resourceEndpointSetState(d *schema.ResourceData, endpoint *dms.Endpoint) er d.Set("secrets_manager_access_role_arn", endpoint.OracleSettings.SecretsManagerAccessRoleArn) d.Set("secrets_manager_arn", endpoint.OracleSettings.SecretsManagerSecretId) } else { - d.Set("username", endpoint.Username) - d.Set("server_name", endpoint.ServerName) - d.Set("port", endpoint.Port) - d.Set("database_name", endpoint.DatabaseName) + flattenTopLevelConnectionInfo(d, endpoint) } - case engineNamePostgres: - if endpoint.PostgreSQLSettings != nil { - d.Set("username", endpoint.PostgreSQLSettings.Username) - d.Set("server_name", endpoint.PostgreSQLSettings.ServerName) - d.Set("port", endpoint.PostgreSQLSettings.Port) - d.Set("database_name", endpoint.PostgreSQLSettings.DatabaseName) - d.Set("secrets_manager_access_role_arn", endpoint.PostgreSQLSettings.SecretsManagerAccessRoleArn) - d.Set("secrets_manager_arn", endpoint.PostgreSQLSettings.SecretsManagerSecretId) + case engineNameRedshift: + if endpoint.RedshiftSettings != nil { + d.Set("username", endpoint.RedshiftSettings.Username) + d.Set("server_name", endpoint.RedshiftSettings.ServerName) + d.Set("port", endpoint.RedshiftSettings.Port) + d.Set("database_name", endpoint.RedshiftSettings.DatabaseName) + d.Set("secrets_manager_access_role_arn", endpoint.RedshiftSettings.SecretsManagerAccessRoleArn) + d.Set("secrets_manager_arn", endpoint.RedshiftSettings.SecretsManagerSecretId) + } else { + flattenTopLevelConnectionInfo(d, endpoint) + } + if err := d.Set("redshift_settings", flattenRedshiftSettings(endpoint.RedshiftSettings)); err != nil { + return fmt.Errorf("setting redshift_settings: %w", err) + } + case engineNameSQLServer: + if endpoint.MicrosoftSQLServerSettings != nil { + d.Set("username", endpoint.MicrosoftSQLServerSettings.Username) + d.Set("server_name", endpoint.MicrosoftSQLServerSettings.ServerName) + d.Set("port", endpoint.MicrosoftSQLServerSettings.Port) + d.Set("database_name", endpoint.MicrosoftSQLServerSettings.DatabaseName) + d.Set("secrets_manager_access_role_arn", endpoint.MicrosoftSQLServerSettings.SecretsManagerAccessRoleArn) + d.Set("secrets_manager_arn", endpoint.MicrosoftSQLServerSettings.SecretsManagerSecretId) } else { - d.Set("username", endpoint.Username) - d.Set("server_name", endpoint.ServerName) - d.Set("port", endpoint.Port) - d.Set("database_name", endpoint.DatabaseName) + flattenTopLevelConnectionInfo(d, endpoint) } case engineNameS3: if err := d.Set("s3_settings", flattenS3Settings(endpoint.S3Settings)); err != nil { @@ -1449,6 +1648,22 @@ func flattenMongoDBSettings(settings *dms.MongoDbSettings) []map[string]interfac return []map[string]interface{}{m} } +func flattenRedshiftSettings(settings *dms.RedshiftSettings) []map[string]interface{} { + if settings == nil { + return []map[string]interface{}{} + } + + m := map[string]interface{}{ + "bucket_folder": aws.StringValue(settings.BucketFolder), + "bucket_name": aws.StringValue(settings.BucketName), + "encryption_mode": aws.StringValue(settings.EncryptionMode), + "server_side_encryption_kms_key_id": aws.StringValue(settings.ServerSideEncryptionKmsKeyId), + "service_access_role_arn": aws.StringValue(settings.ServiceAccessRoleArn), + } + + return []map[string]interface{}{m} +} + func expandS3Settings(tfMap map[string]interface{}) *dms.S3Settings { if tfMap == nil { return nil @@ -1770,3 +1985,32 @@ func engineSettingsToSet(l []interface{}) *schema.Set { return s } + +func expandTopLevelConnectionInfo(d *schema.ResourceData, input *dms.CreateEndpointInput) { + input.Username = aws.String(d.Get("username").(string)) + input.Password = aws.String(d.Get("password").(string)) + input.ServerName = aws.String(d.Get("server_name").(string)) + input.Port = aws.Int64(int64(d.Get("port").(int))) + + if v, ok := d.GetOk("database_name"); ok { + input.DatabaseName = aws.String(v.(string)) + } +} + +func expandTopLevelConnectionInfoModify(d *schema.ResourceData, input *dms.ModifyEndpointInput) { + input.Username = aws.String(d.Get("username").(string)) + input.Password = aws.String(d.Get("password").(string)) + input.ServerName = aws.String(d.Get("server_name").(string)) + input.Port = aws.Int64(int64(d.Get("port").(int))) + + if v, ok := d.GetOk("database_name"); ok { + input.DatabaseName = aws.String(v.(string)) + } +} + +func flattenTopLevelConnectionInfo(d *schema.ResourceData, endpoint *dms.Endpoint) { + d.Set("username", endpoint.Username) + d.Set("server_name", endpoint.ServerName) + d.Set("port", endpoint.Port) + d.Set("database_name", endpoint.DatabaseName) +} diff --git a/internal/service/dms/endpoint_test.go b/internal/service/dms/endpoint_test.go index 2a4188140cb..406d6f5690f 100644 --- a/internal/service/dms/endpoint_test.go +++ b/internal/service/dms/endpoint_test.go @@ -55,6 +55,192 @@ func TestAccDMSEndpoint_basic(t *testing.T) { }) } +func TestAccDMSEndpoint_Aurora_basic(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_aurora(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + +func TestAccDMSEndpoint_Aurora_secretID(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_auroraSecretID(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccDMSEndpoint_Aurora_update(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_aurora(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + Config: testAccEndpointConfig_auroraUpdate(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "server_name", "tftest-new-server_name"), + resource.TestCheckResourceAttr(resourceName, "port", "3307"), + resource.TestCheckResourceAttr(resourceName, "username", "tftest-new-username"), + resource.TestCheckResourceAttr(resourceName, "password", "tftest-new-password"), + resource.TestCheckResourceAttr(resourceName, "database_name", "tftest-new-database_name"), + resource.TestCheckResourceAttr(resourceName, "ssl_mode", "none"), + resource.TestMatchResourceAttr(resourceName, "extra_connection_attributes", regexp.MustCompile(`key=value;`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + +func TestAccDMSEndpoint_AuroraPostgreSQL_basic(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_auroraPostgreSQL(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + +func TestAccDMSEndpoint_AuroraPostgreSQL_secretID(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_auroraPostgreSQLSecretID(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccDMSEndpoint_AuroraPostgreSQL_update(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_auroraPostgreSQL(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + Config: testAccEndpointConfig_auroraPostgreSQLUpdate(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "server_name", "tftest-new-server_name"), + resource.TestCheckResourceAttr(resourceName, "port", "27018"), + resource.TestCheckResourceAttr(resourceName, "username", "tftest-new-username"), + resource.TestCheckResourceAttr(resourceName, "password", "tftest-new-password"), + resource.TestCheckResourceAttr(resourceName, "database_name", "tftest-new-database_name"), + resource.TestCheckResourceAttr(resourceName, "ssl_mode", "require"), + resource.TestMatchResourceAttr(resourceName, "extra_connection_attributes", regexp.MustCompile(`key=value;`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + func TestAccDMSEndpoint_S3_basic(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -94,7 +280,7 @@ func TestAccDMSEndpoint_S3_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"password"}, }, { - Config: testAccEndpointConfig_s3Config(rName), + Config: testAccEndpointConfig_s3Update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestMatchResourceAttr(resourceName, "extra_connection_attributes", regexp.MustCompile(`key=value;`)), @@ -460,6 +646,33 @@ func TestAccDMSEndpoint_MongoDB_basic(t *testing.T) { }) } +func TestAccDMSEndpoint_MongoDB_secretID(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_mongoDBSecretID(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + // TestAccDMSEndpoint_MongoDB_update validates engine-specific // configured fields and extra_connection_attributes now set in the resource // per https://github.com/hashicorp/terraform-provider-aws/issues/8009 @@ -508,7 +721,7 @@ func TestAccDMSEndpoint_MongoDB_update(t *testing.T) { }) } -func TestAccDMSEndpoint_Oracle_basic(t *testing.T) { +func TestAccDMSEndpoint_MariaDB_basic(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -519,7 +732,7 @@ func TestAccDMSEndpoint_Oracle_basic(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig_oracle(rName), + Config: testAccEndpointConfig_mariaDB(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), @@ -535,7 +748,7 @@ func TestAccDMSEndpoint_Oracle_basic(t *testing.T) { }) } -func TestAccDMSEndpoint_Oracle_secretID(t *testing.T) { +func TestAccDMSEndpoint_MariaDB_secretID(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -546,7 +759,7 @@ func TestAccDMSEndpoint_Oracle_secretID(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig_oracleSecretID(rName), + Config: testAccEndpointConfig_mariaDBSecretID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), @@ -561,7 +774,7 @@ func TestAccDMSEndpoint_Oracle_secretID(t *testing.T) { }) } -func TestAccDMSEndpoint_Oracle_update(t *testing.T) { +func TestAccDMSEndpoint_MariaDB_update(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -572,18 +785,18 @@ func TestAccDMSEndpoint_Oracle_update(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig_oracle(rName), + Config: testAccEndpointConfig_mariaDB(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), ), }, { - Config: testAccEndpointConfig_oracleUpdate(rName), + Config: testAccEndpointConfig_mariaDBUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "server_name", "tftest-new-server_name"), - resource.TestCheckResourceAttr(resourceName, "port", "27018"), + resource.TestCheckResourceAttr(resourceName, "port", "3307"), resource.TestCheckResourceAttr(resourceName, "username", "tftest-new-username"), resource.TestCheckResourceAttr(resourceName, "password", "tftest-new-password"), resource.TestCheckResourceAttr(resourceName, "database_name", "tftest-new-database_name"), @@ -601,7 +814,7 @@ func TestAccDMSEndpoint_Oracle_update(t *testing.T) { }) } -func TestAccDMSEndpoint_PostgreSQL_basic(t *testing.T) { +func TestAccDMSEndpoint_MySQL_basic(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -612,7 +825,7 @@ func TestAccDMSEndpoint_PostgreSQL_basic(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig_postgreSQL(rName), + Config: testAccEndpointConfig_mySQL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), @@ -628,7 +841,7 @@ func TestAccDMSEndpoint_PostgreSQL_basic(t *testing.T) { }) } -func TestAccDMSEndpoint_PostgreSQL_secretID(t *testing.T) { +func TestAccDMSEndpoint_MySQL_secretID(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -639,7 +852,7 @@ func TestAccDMSEndpoint_PostgreSQL_secretID(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig_postgreSQLSecretID(rName), + Config: testAccEndpointConfig_mySQLSecretID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), @@ -654,7 +867,7 @@ func TestAccDMSEndpoint_PostgreSQL_secretID(t *testing.T) { }) } -func TestAccDMSEndpoint_PostgreSQL_update(t *testing.T) { +func TestAccDMSEndpoint_MySQL_update(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -665,22 +878,22 @@ func TestAccDMSEndpoint_PostgreSQL_update(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig_postgreSQL(rName), + Config: testAccEndpointConfig_mySQL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), ), }, { - Config: testAccEndpointConfig_postgreSQLUpdate(rName), + Config: testAccEndpointConfig_mySQLUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "server_name", "tftest-new-server_name"), - resource.TestCheckResourceAttr(resourceName, "port", "27018"), + resource.TestCheckResourceAttr(resourceName, "port", "3307"), resource.TestCheckResourceAttr(resourceName, "username", "tftest-new-username"), resource.TestCheckResourceAttr(resourceName, "password", "tftest-new-password"), resource.TestCheckResourceAttr(resourceName, "database_name", "tftest-new-database_name"), - resource.TestCheckResourceAttr(resourceName, "ssl_mode", "require"), + resource.TestCheckResourceAttr(resourceName, "ssl_mode", "none"), resource.TestMatchResourceAttr(resourceName, "extra_connection_attributes", regexp.MustCompile(`key=value;`)), ), }, @@ -694,8 +907,7 @@ func TestAccDMSEndpoint_PostgreSQL_update(t *testing.T) { }) } -// https://github.com/hashicorp/terraform-provider-aws/issues/23143 -func TestAccDMSEndpoint_PostgreSQL_kmsKey(t *testing.T) { +func TestAccDMSEndpoint_Oracle_basic(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -706,17 +918,23 @@ func TestAccDMSEndpoint_PostgreSQL_kmsKey(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig_postgresKey(rName), + Config: testAccEndpointConfig_oracle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, }, }) } -func TestAccDMSEndpoint_docDB(t *testing.T) { +func TestAccDMSEndpoint_Oracle_secretID(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -727,36 +945,22 @@ func TestAccDMSEndpoint_docDB(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig_docDB(rName), + Config: testAccEndpointConfig_oracleSecretID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"password"}, - }, - { - Config: testAccEndpointConfig_docDBUpdate(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckEndpointExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "database_name", "tf-test-dms-db-updated"), - resource.TestCheckResourceAttr(resourceName, "extra_connection_attributes", "extra"), - resource.TestCheckResourceAttr(resourceName, "password", "tftestupdate"), - resource.TestCheckResourceAttr(resourceName, "port", "27019"), - resource.TestCheckResourceAttr(resourceName, "ssl_mode", "none"), - resource.TestCheckResourceAttr(resourceName, "server_name", "tftestupdate"), - resource.TestCheckResourceAttr(resourceName, "username", "tftestupdate"), - ), + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) } -func TestAccDMSEndpoint_db2(t *testing.T) { +func TestAccDMSEndpoint_Oracle_update(t *testing.T) { resourceName := "aws_dms_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -767,16 +971,326 @@ func TestAccDMSEndpoint_db2(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig_db2(rName), + Config: testAccEndpointConfig_oracle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + Config: testAccEndpointConfig_oracleUpdate(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "server_name", "tftest-new-server_name"), + resource.TestCheckResourceAttr(resourceName, "port", "27018"), + resource.TestCheckResourceAttr(resourceName, "username", "tftest-new-username"), + resource.TestCheckResourceAttr(resourceName, "password", "tftest-new-password"), + resource.TestCheckResourceAttr(resourceName, "database_name", "tftest-new-database_name"), + resource.TestCheckResourceAttr(resourceName, "ssl_mode", "none"), + resource.TestMatchResourceAttr(resourceName, "extra_connection_attributes", regexp.MustCompile(`key=value;`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + +func TestAccDMSEndpoint_PostgreSQL_basic(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_postgreSQL(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + +func TestAccDMSEndpoint_PostgreSQL_secretID(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_postgreSQLSecretID(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccDMSEndpoint_PostgreSQL_update(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_postgreSQL(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + Config: testAccEndpointConfig_postgreSQLUpdate(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "server_name", "tftest-new-server_name"), + resource.TestCheckResourceAttr(resourceName, "port", "27018"), + resource.TestCheckResourceAttr(resourceName, "username", "tftest-new-username"), + resource.TestCheckResourceAttr(resourceName, "password", "tftest-new-password"), + resource.TestCheckResourceAttr(resourceName, "database_name", "tftest-new-database_name"), + resource.TestCheckResourceAttr(resourceName, "ssl_mode", "require"), + resource.TestMatchResourceAttr(resourceName, "extra_connection_attributes", regexp.MustCompile(`key=value;`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + +// https://github.com/hashicorp/terraform-provider-aws/issues/23143 +func TestAccDMSEndpoint_PostgreSQL_kmsKey(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_postgresKey(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + }, + }) +} + +func TestAccDMSEndpoint_SQLServer_basic(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_sqlServer(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + +func TestAccDMSEndpoint_SQLServer_secretID(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_sqlServerSecretID(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccDMSEndpoint_SQLServer_update(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_sqlServer(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + Config: testAccEndpointConfig_sqlServerUpdate(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "server_name", "tftest-new-server_name"), + resource.TestCheckResourceAttr(resourceName, "port", "27018"), + resource.TestCheckResourceAttr(resourceName, "username", "tftest-new-username"), + resource.TestCheckResourceAttr(resourceName, "password", "tftest-new-password"), + resource.TestCheckResourceAttr(resourceName, "database_name", "tftest-new-database_name"), + resource.TestCheckResourceAttr(resourceName, "ssl_mode", "require"), + resource.TestMatchResourceAttr(resourceName, "extra_connection_attributes", regexp.MustCompile(`key=value;`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + +// https://github.com/hashicorp/terraform-provider-aws/issues/23143 +func TestAccDMSEndpoint_SQLServer_kmsKey(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_sqlserverKey(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + }, + }) +} + +func TestAccDMSEndpoint_docDB(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_docDB(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + { + Config: testAccEndpointConfig_docDBUpdate(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "database_name", "tf-test-dms-db-updated"), + resource.TestCheckResourceAttr(resourceName, "extra_connection_attributes", "extra"), + resource.TestCheckResourceAttr(resourceName, "password", "tftestupdate"), + resource.TestCheckResourceAttr(resourceName, "port", "27019"), + resource.TestCheckResourceAttr(resourceName, "ssl_mode", "none"), + resource.TestCheckResourceAttr(resourceName, "server_name", "tftestupdate"), + resource.TestCheckResourceAttr(resourceName, "username", "tftestupdate"), + ), + }, + }, + }) +} + +func TestAccDMSEndpoint_db2(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_db2(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, ImportStateVerifyIgnore: []string{"password"}, }, { @@ -796,6 +1310,107 @@ func TestAccDMSEndpoint_db2(t *testing.T) { }) } +func TestAccDMSEndpoint_Redshift_basic(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_redshift(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + +func TestAccDMSEndpoint_Redshift_secretID(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_redshiftSecretID(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + resource.TestCheckResourceAttrSet(resourceName, "secrets_manager_access_role_arn"), + resource.TestCheckResourceAttrSet(resourceName, "secrets_manager_arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccDMSEndpoint_Redshift_update(t *testing.T) { + resourceName := "aws_dms_endpoint.test" + iamRoleResourceName := "aws_iam_role.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, dms.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfig_redshift(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), + resource.TestCheckResourceAttr(resourceName, "redshift_settings.#", "1"), + ), + }, + { + Config: testAccEndpointConfig_redshiftUpdate(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckEndpointExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "database_name", "tftest-new-database_name"), + resource.TestMatchResourceAttr(resourceName, "extra_connection_attributes", regexp.MustCompile(`key=value;`)), + resource.TestCheckResourceAttr(resourceName, "port", "27018"), + resource.TestCheckResourceAttr(resourceName, "username", "tftest-new-username"), + resource.TestCheckResourceAttr(resourceName, "password", "tftest-new-password"), + resource.TestCheckResourceAttr(resourceName, "redshift_settings.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "redshift_settings.0.service_access_role_arn", iamRoleResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "redshift_settings.0.bucket_name", "bucket_name"), + resource.TestCheckResourceAttr(resourceName, "redshift_settings.0.bucket_folder", "bucket_folder"), + resource.TestCheckResourceAttr(resourceName, "redshift_settings.0.server_side_encryption_kms_key_id", ""), + resource.TestCheckResourceAttr(resourceName, "redshift_settings.0.encryption_mode", "SSE_S3"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"password"}, + }, + }, + }) +} + // testAccCheckResourceAttrRegionalHostname ensures the Terraform state exactly matches a formatted DNS hostname with region and partition DNS suffix func testAccCheckResourceAttrRegionalHostname(resourceName, attributeName, serviceName, hostnamePrefix string) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -852,6 +1467,58 @@ func testAccCheckEndpointExists(n string) resource.TestCheckFunc { } } +func testAccEndpointConfig_secretBase(rName string) string { + return fmt.Sprintf(` +data "aws_kms_alias" "dms" { + name = "alias/aws/dms" +} + +data "aws_region" "current" {} +data "aws_partition" "current" {} + +resource "aws_secretsmanager_secret" "test" { + name = %[1]q + recovery_window_in_days = 0 +} + +resource "aws_iam_role" "test" { + name = %[1]q + assume_role_policy = < 0 { + input.OwnerIds = flex.ExpandStringList(v.([]interface{})) } - params := &ec2.DescribeSnapshotsInput{} - if restorableUsersOk { - params.RestorableByUserIds = flex.ExpandStringList(restorableUsers.([]interface{})) - } - if filtersOk { - params.Filters = BuildFiltersDataSource(filters.(*schema.Set)) + if v, ok := d.GetOk("restorable_by_user_ids"); ok && len(v.([]interface{})) > 0 { + input.RestorableByUserIds = flex.ExpandStringList(v.([]interface{})) } - if ownersOk { - params.OwnerIds = flex.ExpandStringList(owners.([]interface{})) + + if v, ok := d.GetOk("snapshot_ids"); ok && len(v.([]interface{})) > 0 { + input.SnapshotIds = flex.ExpandStringList(v.([]interface{})) } - if snapshotIdsOk { - params.SnapshotIds = flex.ExpandStringList(snapshotIds.([]interface{})) + + input.Filters = append(input.Filters, BuildFiltersDataSource( + d.Get("filter").(*schema.Set), + )...) + + if len(input.Filters) == 0 { + input.Filters = nil } - log.Printf("[DEBUG] Reading EBS Snapshot: %s", params) - resp, err := conn.DescribeSnapshots(params) + snapshots, err := FindSnapshots(conn, input) + if err != nil { - return err + return fmt.Errorf("reading EBS Snapshots: %w", err) } - if len(resp.Snapshots) < 1 { + if len(snapshots) < 1 { return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.") } - if len(resp.Snapshots) > 1 { + if len(snapshots) > 1 { if !d.Get("most_recent").(bool) { return fmt.Errorf("Your query returned more than one result. Please try a more " + "specific search criteria, or set `most_recent` attribute to true.") } - sort.Slice(resp.Snapshots, func(i, j int) bool { - return aws.TimeValue(resp.Snapshots[i].StartTime).Unix() > aws.TimeValue(resp.Snapshots[j].StartTime).Unix() + + sort.Slice(snapshots, func(i, j int) bool { + return aws.TimeValue(snapshots[i].StartTime).Unix() > aws.TimeValue(snapshots[j].StartTime).Unix() }) } - //Single Snapshot found so set to state - return snapshotDescriptionAttributes(d, resp.Snapshots[0], meta) -} - -func snapshotDescriptionAttributes(d *schema.ResourceData, snapshot *ec2.Snapshot, meta interface{}) error { - ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + snapshot := snapshots[0] d.SetId(aws.StringValue(snapshot.SnapshotId)) - d.Set("snapshot_id", snapshot.SnapshotId) - d.Set("volume_id", snapshot.VolumeId) + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: ec2.ServiceName, + Region: meta.(*conns.AWSClient).Region, + Resource: fmt.Sprintf("snapshot/%s", d.Id()), + }.String() + d.Set("arn", arn) d.Set("data_encryption_key_id", snapshot.DataEncryptionKeyId) d.Set("description", snapshot.Description) d.Set("encrypted", snapshot.Encrypted) d.Set("kms_key_id", snapshot.KmsKeyId) - d.Set("volume_size", snapshot.VolumeSize) - d.Set("state", snapshot.State) - d.Set("owner_id", snapshot.OwnerId) + d.Set("outpost_arn", snapshot.OutpostArn) d.Set("owner_alias", snapshot.OwnerAlias) + d.Set("owner_id", snapshot.OwnerId) + d.Set("snapshot_id", snapshot.SnapshotId) + d.Set("state", snapshot.State) d.Set("storage_tier", snapshot.StorageTier) - d.Set("outpost_arn", snapshot.OutpostArn) + d.Set("volume_id", snapshot.VolumeId) + d.Set("volume_size", snapshot.VolumeSize) if err := d.Set("tags", KeyValueTags(snapshot.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } - snapshotArn := arn.ARN{ - Partition: meta.(*conns.AWSClient).Partition, - Region: meta.(*conns.AWSClient).Region, - Resource: fmt.Sprintf("snapshot/%s", d.Id()), - Service: ec2.ServiceName, - }.String() - - d.Set("arn", snapshotArn) - return nil } diff --git a/internal/service/ec2/ebs_snapshot_data_source_test.go b/internal/service/ec2/ebs_snapshot_data_source_test.go index 9efeb523efb..a0fa6fb98a8 100644 --- a/internal/service/ec2/ebs_snapshot_data_source_test.go +++ b/internal/service/ec2/ebs_snapshot_data_source_test.go @@ -5,14 +5,15 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" ) func TestAccEC2EBSSnapshotDataSource_basic(t *testing.T) { dataSourceName := "data.aws_ebs_snapshot.test" resourceName := "aws_ebs_snapshot.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -20,20 +21,19 @@ func TestAccEC2EBSSnapshotDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckEBSSnapshotDataSourceConfig, + Config: testAccEBSSnapshotDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEBSSnapshotIDDataSource(dataSourceName), - resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "description", resourceName, "description"), resource.TestCheckResourceAttrPair(dataSourceName, "encrypted", resourceName, "encrypted"), + resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "kms_key_id", resourceName, "kms_key_id"), resource.TestCheckResourceAttrPair(dataSourceName, "owner_alias", resourceName, "owner_alias"), resource.TestCheckResourceAttrPair(dataSourceName, "owner_id", resourceName, "owner_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "storage_tier", resourceName, "storage_tier"), resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"), resource.TestCheckResourceAttrPair(dataSourceName, "volume_id", resourceName, "volume_id"), resource.TestCheckResourceAttrPair(dataSourceName, "volume_size", resourceName, "volume_size"), - resource.TestCheckResourceAttrPair(dataSourceName, "storage_tier", resourceName, "storage_tier"), ), }, }, @@ -43,6 +43,7 @@ func TestAccEC2EBSSnapshotDataSource_basic(t *testing.T) { func TestAccEC2EBSSnapshotDataSource_filter(t *testing.T) { dataSourceName := "data.aws_ebs_snapshot.test" resourceName := "aws_ebs_snapshot.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -50,9 +51,8 @@ func TestAccEC2EBSSnapshotDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckEBSSnapshotFilterDataSourceConfig, + Config: testAccEBSSnapshotDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEBSSnapshotIDDataSource(dataSourceName), resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), ), }, @@ -62,7 +62,8 @@ func TestAccEC2EBSSnapshotDataSource_filter(t *testing.T) { func TestAccEC2EBSSnapshotDataSource_mostRecent(t *testing.T) { dataSourceName := "data.aws_ebs_snapshot.test" - resourceName := "aws_ebs_snapshot.test" + resourceName := "aws_ebs_snapshot.b" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -70,9 +71,8 @@ func TestAccEC2EBSSnapshotDataSource_mostRecent(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckEBSSnapshotMostRecentDataSourceConfig, + Config: testAccEBSSnapshotDataSourceConfig_mostRecent(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEBSSnapshotIDDataSource(dataSourceName), resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), ), }, @@ -80,45 +80,50 @@ func TestAccEC2EBSSnapshotDataSource_mostRecent(t *testing.T) { }) } -func testAccCheckEBSSnapshotIDDataSource(n string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Can't find snapshot data source: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("Snapshot data source ID not set") - } - return nil - } -} - -var testAccCheckEBSSnapshotDataSourceConfig = acctest.ConfigAvailableAZsNoOptIn() + ` +func testAccEBSSnapshotDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] type = "gp2" size = 1 + + tags = { + Name = %[1]q + } } resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id + + tags = { + Name = %[1]q + } } data "aws_ebs_snapshot" "test" { snapshot_ids = [aws_ebs_snapshot.test.id] } -` +`, rName)) +} -var testAccCheckEBSSnapshotFilterDataSourceConfig = acctest.ConfigAvailableAZsNoOptIn() + ` +func testAccEBSSnapshotDataSourceConfig_filter(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] type = "gp2" size = 1 + + tags = { + Name = %[1]q + } } resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id + + tags = { + Name = %[1]q + } } data "aws_ebs_snapshot" "test" { @@ -127,28 +132,35 @@ data "aws_ebs_snapshot" "test" { values = [aws_ebs_snapshot.test.id] } } -` +`, rName)) +} -var testAccCheckEBSSnapshotMostRecentDataSourceConfig = acctest.ConfigAvailableAZsNoOptIn() + ` +func testAccEBSSnapshotDataSourceConfig_mostRecent(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] type = "gp2" size = 1 + + tags = { + Name = %[1]q + } } -resource "aws_ebs_snapshot" "incorrect" { +resource "aws_ebs_snapshot" "a" { volume_id = aws_ebs_volume.test.id tags = { - Name = "tf-acc-test-ec2-ebs-snapshot-data-source-most-recent" + Name = %[1]q } } -resource "aws_ebs_snapshot" "test" { - volume_id = aws_ebs_snapshot.incorrect.volume_id +resource "aws_ebs_snapshot" "b" { + # Ensure that this snapshot is created after the other. + volume_id = aws_ebs_snapshot.a.volume_id tags = { - Name = "tf-acc-test-ec2-ebs-snapshot-data-source-most-recent" + Name = %[1]q } } @@ -157,7 +169,10 @@ data "aws_ebs_snapshot" "test" { filter { name = "tag:Name" - values = [aws_ebs_snapshot.test.tags.Name] + values = [%[1]q] } + + depends_on = [aws_ebs_snapshot.a, aws_ebs_snapshot.b] +} +`, rName)) } -` diff --git a/internal/service/ec2/ebs_snapshot_ids_data_source.go b/internal/service/ec2/ebs_snapshot_ids_data_source.go index 7545d164d16..4c2d3de2873 100644 --- a/internal/service/ec2/ebs_snapshot_ids_data_source.go +++ b/internal/service/ec2/ebs_snapshot_ids_data_source.go @@ -2,7 +2,6 @@ package ec2 import ( "fmt" - "log" "sort" "github.com/aws/aws-sdk-go/aws" @@ -18,19 +17,19 @@ func DataSourceEBSSnapshotIDs() *schema.Resource { Schema: map[string]*schema.Schema{ "filter": DataSourceFiltersSchema(), - "owners": { + "ids": { Type: schema.TypeList, - Optional: true, + Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "restorable_by_user_ids": { + "owners": { Type: schema.TypeList, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "ids": { + "restorable_by_user_ids": { Type: schema.TypeList, - Computed: true, + Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, }, }, @@ -40,44 +39,42 @@ func DataSourceEBSSnapshotIDs() *schema.Resource { func dataSourceEBSSnapshotIDsRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - restorableUsers, restorableUsersOk := d.GetOk("restorable_by_user_ids") - filters, filtersOk := d.GetOk("filter") - owners, ownersOk := d.GetOk("owners") + input := &ec2.DescribeSnapshotsInput{} - if restorableUsers == false && !filtersOk && !ownersOk { - return fmt.Errorf("One of filters, restorable_by_user_ids, or owners must be assigned") + if v, ok := d.GetOk("owners"); ok && len(v.([]interface{})) > 0 { + input.OwnerIds = flex.ExpandStringList(v.([]interface{})) } - params := &ec2.DescribeSnapshotsInput{} - - if restorableUsersOk { - params.RestorableByUserIds = flex.ExpandStringList(restorableUsers.([]interface{})) - } - if filtersOk { - params.Filters = BuildFiltersDataSource(filters.(*schema.Set)) + if v, ok := d.GetOk("restorable_by_user_ids"); ok && len(v.([]interface{})) > 0 { + input.RestorableByUserIds = flex.ExpandStringList(v.([]interface{})) } - if ownersOk { - params.OwnerIds = flex.ExpandStringList(owners.([]interface{})) + + input.Filters = append(input.Filters, BuildFiltersDataSource( + d.Get("filter").(*schema.Set), + )...) + + if len(input.Filters) == 0 { + input.Filters = nil } - log.Printf("[DEBUG] Reading EBS Snapshot IDs: %s", params) - resp, err := conn.DescribeSnapshots(params) + snapshots, err := FindSnapshots(conn, input) + if err != nil { - return err + return fmt.Errorf("reading EBS Snapshots: %w", err) } - snapshotIds := make([]string, 0) - - sort.Slice(resp.Snapshots, func(i, j int) bool { - return aws.TimeValue(resp.Snapshots[i].StartTime).Unix() > aws.TimeValue(resp.Snapshots[j].StartTime).Unix() + sort.Slice(snapshots, func(i, j int) bool { + return aws.TimeValue(snapshots[i].StartTime).Unix() > aws.TimeValue(snapshots[j].StartTime).Unix() }) - for _, snapshot := range resp.Snapshots { - snapshotIds = append(snapshotIds, *snapshot.SnapshotId) + + var snapshotIDs []string + + for _, v := range snapshots { + snapshotIDs = append(snapshotIDs, aws.StringValue(v.SnapshotId)) } d.SetId(meta.(*conns.AWSClient).Region) - - d.Set("ids", snapshotIds) + d.Set("ids", snapshotIDs) return nil } diff --git a/internal/service/ec2/ebs_snapshot_ids_data_source_test.go b/internal/service/ec2/ebs_snapshot_ids_data_source_test.go index 6e71447e888..3bc4ac26149 100644 --- a/internal/service/ec2/ebs_snapshot_ids_data_source_test.go +++ b/internal/service/ec2/ebs_snapshot_ids_data_source_test.go @@ -11,15 +11,19 @@ import ( ) func TestAccEC2EBSSnapshotIDsDataSource_basic(t *testing.T) { + dataSourceName := "data.aws_ebs_snapshot_ids.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotIdsDataSourceConfig_basic(), + Config: testAccEBSSnapshotIdsDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEBSSnapshotIDDataSource("data.aws_ebs_snapshot_ids.test"), + acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "ids.#", "0"), + resource.TestCheckTypeSetElemAttrPair(dataSourceName, "ids.*", "aws_ebs_snapshot.test", "id"), ), }, }, @@ -27,6 +31,9 @@ func TestAccEC2EBSSnapshotIDsDataSource_basic(t *testing.T) { } func TestAccEC2EBSSnapshotIDsDataSource_sorted(t *testing.T) { + dataSourceName := "data.aws_ebs_snapshot_ids.test" + resource1Name := "aws_ebs_snapshot.a" + resource2Name := "aws_ebs_snapshot.b" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ @@ -35,23 +42,11 @@ func TestAccEC2EBSSnapshotIDsDataSource_sorted(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotIdsDataSourceConfig_sorted1(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("aws_ebs_snapshot.a", "id"), - resource.TestCheckResourceAttrSet("aws_ebs_snapshot.b", "id"), - ), - }, - { - Config: testAccEBSSnapshotIdsDataSourceConfig_sorted2(rName), + Config: testAccEBSSnapshotIdsDataSourceConfig_sorted(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEBSSnapshotIDDataSource("data.aws_ebs_snapshot_ids.test"), - resource.TestCheckResourceAttr("data.aws_ebs_snapshot_ids.test", "ids.#", "2"), - resource.TestCheckResourceAttrPair( - "data.aws_ebs_snapshot_ids.test", "ids.0", - "aws_ebs_snapshot.b", "id"), - resource.TestCheckResourceAttrPair( - "data.aws_ebs_snapshot_ids.test", "ids.1", - "aws_ebs_snapshot.a", "id"), + resource.TestCheckResourceAttr(dataSourceName, "ids.#", "2"), + resource.TestCheckResourceAttrPair(dataSourceName, "ids.0", resource2Name, "id"), + resource.TestCheckResourceAttrPair(dataSourceName, "ids.1", resource1Name, "id"), ), }, }, @@ -67,7 +62,6 @@ func TestAccEC2EBSSnapshotIDsDataSource_empty(t *testing.T) { { Config: testAccEBSSnapshotIdsDataSourceConfig_empty, Check: resource.ComposeTestCheckFunc( - testAccCheckEBSSnapshotIDDataSource("data.aws_ebs_snapshot_ids.empty"), resource.TestCheckResourceAttr("data.aws_ebs_snapshot_ids.empty", "ids.#", "0"), ), }, @@ -75,35 +69,53 @@ func TestAccEC2EBSSnapshotIDsDataSource_empty(t *testing.T) { }) } -func testAccEBSSnapshotIdsDataSourceConfig_basic() string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` +func testAccEBSSnapshotIdsDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] size = 1 + + tags = { + Name = %[1]q + } } resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id + + tags = { + Name = %[1]q + } } data "aws_ebs_snapshot_ids" "test" { owners = ["self"] + + depends_on = [aws_ebs_snapshot.test] } -`) +`, rName)) } -func testAccEBSSnapshotIdsDataSourceConfig_sorted1(rName string) string { +func testAccEBSSnapshotIdsDataSourceConfig_sorted(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] size = 1 count = 2 + + tags = { + Name = %[1]q + } } resource "aws_ebs_snapshot" "a" { volume_id = aws_ebs_volume.test.*.id[0] description = %[1]q + + tags = { + Name = %[1]q + } } resource "aws_ebs_snapshot" "b" { @@ -114,19 +126,21 @@ resource "aws_ebs_snapshot" "b" { # 'aws_ebs_snapshot.b.creation_date'/ so that we can ensure that the # snapshots are being sorted correctly. depends_on = [aws_ebs_snapshot.a] -} -`, rName)) + + tags = { + Name = %[1]q + } } -func testAccEBSSnapshotIdsDataSourceConfig_sorted2(rName string) string { - return acctest.ConfigCompose(testAccEBSSnapshotIdsDataSourceConfig_sorted1(rName), fmt.Sprintf(` data "aws_ebs_snapshot_ids" "test" { owners = ["self"] filter { name = "description" - values = [%q] + values = [%[1]q] } + + depends_on = [aws_ebs_snapshot.a, aws_ebs_snapshot.b] } `, rName)) } diff --git a/internal/service/ec2/ebs_snapshot_import.go b/internal/service/ec2/ebs_snapshot_import.go index b078336b363..e2f487a7bc6 100644 --- a/internal/service/ec2/ebs_snapshot_import.go +++ b/internal/service/ec2/ebs_snapshot_import.go @@ -8,7 +8,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -20,10 +19,11 @@ import ( func ResourceEBSSnapshotImport() *schema.Resource { return &schema.Resource{ - Create: resourceEBSSnapshotImportCreate, - Read: resourceEBSSnapshotImportRead, - Update: resourceEBSSnapshotUpdate, - Delete: resourceEBSSnapshotDelete, + Create: resourceEBSSnapshotImportCreate, + Read: resourceEBSSnapshotImportRead, + Update: resourceEBSSnapshotUpdate, + Delete: resourceEBSSnapshotDelete, + CustomizeDiff: verify.SetTagsDiff, Timeouts: &schema.ResourceTimeout{ @@ -49,9 +49,10 @@ func ResourceEBSSnapshotImport() *schema.Resource { ForceNew: true, }, "upload_end": { - Type: schema.TypeString, - Optional: true, - Computed: true, + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.IsRFC3339Time, }, "upload_size": { Type: schema.TypeFloat, @@ -59,9 +60,10 @@ func ResourceEBSSnapshotImport() *schema.Resource { Computed: true, }, "upload_start": { - Type: schema.TypeString, - Optional: true, - Computed: true, + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.IsRFC3339Time, }, }, }, @@ -101,11 +103,10 @@ func ResourceEBSSnapshotImport() *schema.Resource { ExactlyOneOf: []string{"disk_container.0.user_bucket", "disk_container.0.url"}, }, "user_bucket": { - Type: schema.TypeList, - Optional: true, - ForceNew: true, - ExactlyOneOf: []string{"disk_container.0.user_bucket", "disk_container.0.url"}, - MaxItems: 1, + Type: schema.TypeList, + Optional: true, + ForceNew: true, + MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "s3_bucket": { @@ -120,6 +121,7 @@ func ResourceEBSSnapshotImport() *schema.Resource { }, }, }, + ExactlyOneOf: []string{"disk_container.0.user_bucket", "disk_container.0.url"}, }, }, }, @@ -154,16 +156,13 @@ func ResourceEBSSnapshotImport() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: "vmimport", + Default: DefaultSnapshotImportRoleName, }, "storage_tier": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.Any( - validation.StringInSlice(ec2.TargetStorageTier_Values(), false), - validation.StringInSlice([]string{"standard"}, false), //Enum slice does not include `standard` type. - ), + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice(append(ec2.TargetStorageTier_Values(), TargetStorageTierStandard), false), }, "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), @@ -186,90 +185,60 @@ func ResourceEBSSnapshotImport() *schema.Resource { func resourceEBSSnapshotImportCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig - tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) - request := &ec2.ImportSnapshotInput{ + input := &ec2.ImportSnapshotInput{ + ClientToken: aws.String(resource.UniqueId()), TagSpecifications: tagSpecificationsFromKeyValueTags(tags, ec2.ResourceTypeImportSnapshotTask), } - if clientData, ok := d.GetOk("client_data"); ok { - for _, v := range clientData.([]interface{}) { - if cdv, ok := v.(map[string]interface{}); ok { - - clientData, err := expandEBSSnapshotClientData(cdv) - if err != nil { - return err - } - - request.ClientData = clientData - } - } + if v, ok := d.GetOk("client_data"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.ClientData = expandClientData(v.([]interface{})[0].(map[string]interface{})) } - request.ClientToken = aws.String(resource.UniqueId()) - if v, ok := d.GetOk("description"); ok { - request.Description = aws.String(v.(string)) + input.Description = aws.String(v.(string)) } - diskContainer := d.Get("disk_container") - for _, v := range diskContainer.([]interface{}) { - if dcv, ok := v.(map[string]interface{}); ok { - - diskContainer := expandEBSSnapshotDiskContainer(dcv) - request.DiskContainer = diskContainer - } + if v, ok := d.GetOk("disk_container"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.DiskContainer = expandSnapshotDiskContainer(v.([]interface{})[0].(map[string]interface{})) } if v, ok := d.GetOk("encrypted"); ok { - request.Encrypted = aws.Bool(v.(bool)) + input.Encrypted = aws.Bool(v.(bool)) } if v, ok := d.GetOk("kms_key_id"); ok { - request.KmsKeyId = aws.String(v.(string)) + input.KmsKeyId = aws.String(v.(string)) } if v, ok := d.GetOk("role_name"); ok { - request.RoleName = aws.String(v.(string)) + input.RoleName = aws.String(v.(string)) } - err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { - resp, err := conn.ImportSnapshot(request) - - if tfawserr.ErrMessageContains(err, "InvalidParameter", "provided does not exist or does not have sufficient permissions") { - return resource.RetryableError(err) - } + outputRaw, err := tfresource.RetryWhenAWSErrMessageContains(propagationTimeout, + func() (interface{}, error) { + return conn.ImportSnapshot(input) + }, + errCodeInvalidParameter, "provided does not exist or does not have sufficient permissions") - if err != nil { - return resource.NonRetryableError(err) - } + if err != nil { + return fmt.Errorf("creating EBS Snapshot Import: %w", err) + } - importTaskId := aws.StringValue(resp.ImportTaskId) + taskID := aws.StringValue(outputRaw.(*ec2.ImportSnapshotOutput).ImportTaskId) + output, err := WaitEBSSnapshotImportComplete(conn, taskID, d.Timeout(schema.TimeoutCreate)) - res, err := WaitEBSSnapshotImportComplete(conn, importTaskId) - if err != nil { - return resource.NonRetryableError(fmt.Errorf("Error waiting for snapshot (%s) to be imported: %s", importTaskId, err)) - } + if err != nil { + return fmt.Errorf("waiting for EBS Snapshot Import (%s) create: %w", taskID, err) + } - d.SetId(aws.StringValue(res.SnapshotId)) + d.SetId(aws.StringValue(output.SnapshotId)) - tags := d.Get("tags").(map[string]interface{}) - if len(tags) > 0 { - if err := CreateTags(conn, d.Id(), tags); err != nil { - return resource.NonRetryableError(fmt.Errorf("error setting tags: %s", err)) - } + if len(tags) > 0 { + if err := CreateTags(conn, d.Id(), tags); err != nil { + return fmt.Errorf("setting EBS Snapshot Import (%s) tags: %w", d.Id(), err) } - - return nil - }) - - if tfresource.TimedOut(err) { - return fmt.Errorf("timeout error importing EBS Snapshot: %s", err) - } - - if err != nil { - return fmt.Errorf("error importing EBS Snapshot: %s", err) } if v, ok := d.GetOk("storage_tier"); ok && v.(string) == ec2.TargetStorageTierArchive { @@ -279,12 +248,13 @@ func resourceEBSSnapshotImportCreate(d *schema.ResourceData, meta interface{}) e }) if err != nil { - return fmt.Errorf("error setting EBS Snapshot Import (%s) Storage Tier: %w", d.Id(), err) + return fmt.Errorf("setting EBS Snapshot Import (%s) Storage Tier: %w", d.Id(), err) } - _, err = WaitEBSSnapshotTierArchive(conn, d.Id()) + _, err = waitEBSSnapshotTierArchive(conn, d.Id(), ebsSnapshotArchivedTimeout) + if err != nil { - return fmt.Errorf("Error waiting for EBS Snapshot Import (%s) Storage Tier to be archived: %w", d.Id(), err) + return fmt.Errorf("waiting for EBS Snapshot Import (%s) Storage Tier archive: %w", d.Id(), err) } } @@ -296,102 +266,118 @@ func resourceEBSSnapshotImportRead(d *schema.ResourceData, meta interface{}) err defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - snapshot, err := FindSnapshotById(conn, d.Id()) + snapshot, err := FindSnapshotByID(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] EBS Snapshot (%s) Not found - removing from state", d.Id()) + log.Printf("[WARN] EBS Snapshot %s not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("error reading EBS Snapshot (%s): %w", d.Id(), err) + return fmt.Errorf("reading EBS Snapshot (%s): %w", d.Id(), err) } + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: ec2.ServiceName, + Region: meta.(*conns.AWSClient).Region, + Resource: fmt.Sprintf("snapshot/%s", d.Id()), + }.String() + d.Set("arn", arn) + d.Set("data_encryption_key_id", snapshot.DataEncryptionKeyId) d.Set("description", snapshot.Description) - d.Set("owner_id", snapshot.OwnerId) d.Set("encrypted", snapshot.Encrypted) - d.Set("owner_alias", snapshot.OwnerAlias) - d.Set("data_encryption_key_id", snapshot.DataEncryptionKeyId) d.Set("kms_key_id", snapshot.KmsKeyId) - d.Set("volume_size", snapshot.VolumeSize) + d.Set("owner_alias", snapshot.OwnerAlias) + d.Set("owner_id", snapshot.OwnerId) d.Set("storage_tier", snapshot.StorageTier) + d.Set("volume_size", snapshot.VolumeSize) tags := KeyValueTags(snapshot.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } - snapshotArn := arn.ARN{ - Partition: meta.(*conns.AWSClient).Partition, - Region: meta.(*conns.AWSClient).Region, - Resource: fmt.Sprintf("snapshot/%s", d.Id()), - Service: "ec2", - }.String() - - d.Set("arn", snapshotArn) - return nil } -func expandEBSSnapshotClientData(tfMap map[string]interface{}) (*ec2.ClientData, error) { - clientData := &ec2.ClientData{} +func expandClientData(tfMap map[string]interface{}) *ec2.ClientData { + if tfMap == nil { + return nil + } + + apiObject := &ec2.ClientData{} - if v, ok := tfMap["comment"].(string); ok { - clientData.Comment = aws.String(v) + if v, ok := tfMap["comment"].(string); ok && v != "" { + apiObject.Comment = aws.String(v) } - if v, ok := tfMap["upload_end"].(string); ok { - upload_end, err := time.Parse(time.RFC3339, v) - if err != nil { - return nil, fmt.Errorf("error parsing upload_end to timestamp: %s", err) - } - clientData.UploadEnd = aws.Time(upload_end) + if v, ok := tfMap["upload_end"].(string); ok && v != "" { + v, _ := time.Parse(time.RFC3339, v) + + apiObject.UploadEnd = aws.Time(v) } - if v, ok := tfMap["upload_size"].(float64); ok { - clientData.UploadSize = aws.Float64(v) + if v, ok := tfMap["upload_size"].(float64); ok && v != 0.0 { + apiObject.UploadSize = aws.Float64(v) } if v, ok := tfMap["upload_start"].(string); ok { - upload_start, err := time.Parse(time.RFC3339, v) - if err != nil { - return nil, fmt.Errorf("error parsing upload_start to timestamp: %s", err) - } - clientData.UploadStart = aws.Time(upload_start) + v, _ := time.Parse(time.RFC3339, v) + + apiObject.UploadStart = aws.Time(v) } - return clientData, nil + return apiObject } -func expandEBSSnapshotDiskContainer(tfMap map[string]interface{}) *ec2.SnapshotDiskContainer { - diskContainer := &ec2.SnapshotDiskContainer{ - Format: aws.String(tfMap["format"].(string)), +func expandSnapshotDiskContainer(tfMap map[string]interface{}) *ec2.SnapshotDiskContainer { + if tfMap == nil { + return nil } - if v, ok := tfMap["description"].(string); ok { - diskContainer.Description = aws.String(v) + apiObject := &ec2.SnapshotDiskContainer{} + + if v, ok := tfMap["description"].(string); ok && v != "" { + apiObject.Description = aws.String(v) + } + + if v, ok := tfMap["format"].(string); ok && v != "" { + apiObject.Format = aws.String(v) } if v, ok := tfMap["url"].(string); ok && v != "" { - diskContainer.Url = aws.String(v) + apiObject.Url = aws.String(v) } - if v, ok := tfMap["user_bucket"]; ok { - vL := v.([]interface{}) - for _, v := range vL { - ub := v.(map[string]interface{}) - diskContainer.UserBucket = &ec2.UserBucket{ - S3Bucket: aws.String(ub["s3_bucket"].(string)), - S3Key: aws.String(ub["s3_key"].(string)), - } - } + if v, ok := tfMap["user_bucket"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + apiObject.UserBucket = expandUserBucket(v[0].(map[string]interface{})) + } + + return apiObject +} + +func expandUserBucket(tfMap map[string]interface{}) *ec2.UserBucket { + if tfMap == nil { + return nil + } + + apiObject := &ec2.UserBucket{} + + if v, ok := tfMap["s3_bucket"].(string); ok && v != "" { + apiObject.S3Bucket = aws.String(v) + } + + if v, ok := tfMap["s3_key"].(string); ok && v != "" { + apiObject.S3Key = aws.String(v) } - return diskContainer + return apiObject } diff --git a/internal/service/ec2/ebs_snapshot_import_test.go b/internal/service/ec2/ebs_snapshot_import_test.go index a0c13625858..9579f713f9a 100644 --- a/internal/service/ec2/ebs_snapshot_import_test.go +++ b/internal/service/ec2/ebs_snapshot_import_test.go @@ -29,20 +29,19 @@ func TestAccEC2EBSSnapshotImport_basic(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotImportBasicConfig(rName, t), + Config: testAccEBSSnapshotImportConfig_basic(t, rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`snapshot/snap-.+`)), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "tags_all.%", "0"), acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, }, }) } -func TestAccEC2EBSSnapshotImport_tags(t *testing.T) { +func TestAccEC2EBSSnapshotImport_disappears(t *testing.T) { var v ec2.Snapshot rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_ebs_snapshot_import.test" @@ -54,43 +53,21 @@ func TestAccEC2EBSSnapshotImport_tags(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotImportTags1Config(rName, t, "key1", "value1"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSnapshotExists(resourceName, &v), - acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`snapshot/snap-.+`)), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - ), - }, - { - Config: testAccEBSSnapshotImportTags2Config(rName, t, "key1", "value1updated", "key2", "value2"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSnapshotExists(resourceName, &v), - acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`snapshot/snap-.+`)), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - ), - }, - { - Config: testAccEBSSnapshotImportTags1Config(rName, t, "key2", "value2"), + Config: testAccEBSSnapshotImportConfig_basic(t, rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), - acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`snapshot/snap-.+`)), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceEBSSnapshotImport(), resourceName), ), + ExpectNonEmptyPlan: true, }, }, }) } -func TestAccEC2EBSSnapshotImport_storageTier(t *testing.T) { +func TestAccEC2EBSSnapshotImport_Disappears_s3Object(t *testing.T) { var v ec2.Snapshot rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + parentResourceName := "aws_s3_object.test" resourceName := "aws_ebs_snapshot_import.test" resource.ParallelTest(t, resource.TestCase{ @@ -100,17 +77,18 @@ func TestAccEC2EBSSnapshotImport_storageTier(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotImportStorageTierConfig(rName, t), + Config: testAccEBSSnapshotImportConfig_basic(t, rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "storage_tier", "archive"), + acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceObject(), parentResourceName), ), + ExpectNonEmptyPlan: true, }, }, }) } -func TestAccEC2EBSSnapshotImport_disappears(t *testing.T) { +func TestAccEC2EBSSnapshotImport_tags(t *testing.T) { var v ec2.Snapshot rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_ebs_snapshot_import.test" @@ -122,24 +100,37 @@ func TestAccEC2EBSSnapshotImport_disappears(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotImportBasicConfig(rName, t), + Config: testAccEBSSnapshotImportConfig_tags1(t, rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), - acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`snapshot/snap-.+`)), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceEBSSnapshotImport(), resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + Config: testAccEBSSnapshotImportConfig_tags2(t, rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckSnapshotExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccEBSSnapshotImportConfig_tags1(t, rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckSnapshotExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), - ExpectNonEmptyPlan: true, }, }, }) } -func TestAccEC2EBSSnapshotImport_Disappears_s3Object(t *testing.T) { +func TestAccEC2EBSSnapshotImport_storageTier(t *testing.T) { var v ec2.Snapshot rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - parentResourceName := "aws_s3_object.image" resourceName := "aws_ebs_snapshot_import.test" resource.ParallelTest(t, resource.TestCase{ @@ -149,41 +140,37 @@ func TestAccEC2EBSSnapshotImport_Disappears_s3Object(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotImportBasicConfig(rName, t), + Config: testAccEBSSnapshotImportConfig_storageTier(t, rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), - acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`snapshot/snap-.+`)), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceObject(), parentResourceName), + resource.TestCheckResourceAttr(resourceName, "storage_tier", "archive"), ), - ExpectNonEmptyPlan: true, }, }, }) } -func testAccEBSSnapshotImportConfig_Base(t *testing.T) string { +func testAccEBSSnapshotImportBaseConfig(t *testing.T, rName string) string { return fmt.Sprintf(` -resource "aws_s3_bucket" "images" { - bucket_prefix = "tf-acc-test-" +resource "aws_s3_bucket" "test" { + bucket = %[1]q force_destroy = true } -resource "aws_s3_object" "image" { - bucket = aws_s3_bucket.images.id +resource "aws_s3_object" "test" { + bucket = aws_s3_bucket.test.id key = "diskimage.vhd" - content_base64 = %[1]q + content_base64 = %[2]q } # The following resources are for the *vmimport service user* # See: https://docs.aws.amazon.com/vm-import/latest/userguide/vmie_prereqs.html#vmimport-role -resource "aws_iam_role" "vmimport" { +resource "aws_iam_role" "test" { assume_role_policy = data.aws_iam_policy_document.vmimport-trust.json } -resource "aws_iam_role_policy" "vmimport-access" { - role = aws_iam_role.vmimport.id +resource "aws_iam_role_policy" "test" { + role = aws_iam_role.test.id policy = data.aws_iam_policy_document.vmimport-access.json } @@ -196,8 +183,8 @@ data "aws_iam_policy_document" "vmimport-access" { "s3:ListBucket", ] resources = [ - aws_s3_bucket.images.arn, - "${aws_s3_bucket.images.arn}/*" + aws_s3_bucket.test.arn, + "${aws_s3_bucket.test.arn}/*" ] } statement { @@ -214,7 +201,6 @@ data "aws_iam_policy_document" "vmimport-access" { } } - data "aws_iam_policy_document" "vmimport-trust" { statement { effect = "Allow" @@ -234,105 +220,89 @@ data "aws_iam_policy_document" "vmimport-trust" { } } } -`, testAccEBSSnapshotDisk(t)) +`, rName, testAccEBSSnapshotDisk(t)) } -func testAccEBSSnapshotImportBasicConfig(rName string, t *testing.T) string { - return acctest.ConfigCompose(testAccEBSSnapshotImportConfig_Base(t), fmt.Sprintf(` +func testAccEBSSnapshotImportConfig_basic(t *testing.T, rName string) string { + return acctest.ConfigCompose(testAccEBSSnapshotImportBaseConfig(t, rName), ` resource "aws_ebs_snapshot_import" "test" { disk_container { - description = %[1]q + description = "test" format = "VHD" user_bucket { - s3_bucket = aws_s3_bucket.images.id - s3_key = aws_s3_object.image.key + s3_bucket = aws_s3_bucket.test.id + s3_key = aws_s3_object.test.key } } - role_name = aws_iam_role.vmimport.name - - timeouts { - create = "10m" - delete = "10m" - } + role_name = aws_iam_role.test.name } -`, rName)) +`) } -func testAccEBSSnapshotImportStorageTierConfig(rName string, t *testing.T) string { - return acctest.ConfigCompose(testAccEBSSnapshotImportConfig_Base(t), fmt.Sprintf(` +func testAccEBSSnapshotImportConfig_storageTier(t *testing.T, rName string) string { + return acctest.ConfigCompose(testAccEBSSnapshotImportBaseConfig(t, rName), fmt.Sprintf(` resource "aws_ebs_snapshot_import" "test" { disk_container { - description = %[1]q + description = "test" format = "VHD" user_bucket { - s3_bucket = aws_s3_bucket.images.id - s3_key = aws_s3_object.image.key + s3_bucket = aws_s3_bucket.test.id + s3_key = aws_s3_object.test.key } } - role_name = aws_iam_role.vmimport.name + role_name = aws_iam_role.test.name storage_tier = "archive" - timeouts { - create = "10m" - delete = "10m" + tags = { + Name = %[1]q } } `, rName)) } -func testAccEBSSnapshotImportTags1Config(rName string, t *testing.T, tagKey1 string, tagValue1 string) string { - return acctest.ConfigCompose(testAccEBSSnapshotImportConfig_Base(t), fmt.Sprintf(` +func testAccEBSSnapshotImportConfig_tags1(t *testing.T, rName, tagKey1, tagValue1 string) string { + return acctest.ConfigCompose(testAccEBSSnapshotImportBaseConfig(t, rName), fmt.Sprintf(` resource "aws_ebs_snapshot_import" "test" { disk_container { - description = %[1]q + description = "test" format = "VHD" user_bucket { - s3_bucket = aws_s3_bucket.images.id - s3_key = aws_s3_object.image.key + s3_bucket = aws_s3_bucket.test.id + s3_key = aws_s3_object.test.key } } - role_name = aws_iam_role.vmimport.name - - timeouts { - create = "10m" - delete = "10m" - } + role_name = aws_iam_role.test.name tags = { - %[2]q = %[3]q + %[1]q = %[2]q } } -`, rName, tagKey1, tagValue1)) +`, tagKey1, tagValue1)) } -func testAccEBSSnapshotImportTags2Config(rName string, t *testing.T, tagKey1 string, tagValue1 string, tagKey2 string, tagValue2 string) string { - return acctest.ConfigCompose(testAccEBSSnapshotImportConfig_Base(t), fmt.Sprintf(` +func testAccEBSSnapshotImportConfig_tags2(t *testing.T, rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return acctest.ConfigCompose(testAccEBSSnapshotImportBaseConfig(t, rName), fmt.Sprintf(` resource "aws_ebs_snapshot_import" "test" { disk_container { - description = %[1]q + description = "test" format = "VHD" user_bucket { - s3_bucket = aws_s3_bucket.images.id - s3_key = aws_s3_object.image.key + s3_bucket = aws_s3_bucket.test.id + s3_key = aws_s3_object.test.key } } - role_name = aws_iam_role.vmimport.name - - timeouts { - create = "10m" - delete = "10m" - } + role_name = aws_iam_role.test.name tags = { - %[2]q = %[3]q - %[4]q = %[5]q + %[1]q = %[2]q + %[3]q = %[4]q } } -`, rName, tagKey1, tagValue1, tagKey2, tagValue2)) +`, tagKey1, tagValue1, tagKey2, tagValue2)) } func testAccEBSSnapshotDisk(t *testing.T) string { @@ -344,10 +314,9 @@ func testAccEBSSnapshotDisk(t *testing.T) string { // $ VBoxManage createmedium disk --filename ./image.vhd --sizebytes 512 --format vhd // $ cat image.vhd | gzip --best | base64 b64_compressed := "H4sIAAAAAAACA0vOz0tNLsmsYGBgYGJgZIACJgZ1789hZUn5FQxsDIzhmUbZMHEEzSIIJJj///+QlV1rMXFVnLzHwteXYmWDDfYxjIIhA5IrigsSi4pT/0MBRJSNAZoWGBkUGBj+//9SNhpSo2AUDD+AyPOjYESW/6P1/4gGAAvDpVcACgAA" - decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(b64_compressed)) - zr, err := gzip.NewReader(decoder) + if err != nil { t.Fatal(err) } @@ -356,9 +325,11 @@ func testAccEBSSnapshotDisk(t *testing.T) string { encoder := base64.NewEncoder(base64.StdEncoding, &out) _, err = io.Copy(encoder, zr) + if err != nil { t.Fatal(err) } + encoder.Close() return out.String() diff --git a/internal/service/ec2/ebs_snapshot_test.go b/internal/service/ec2/ebs_snapshot_test.go index f480d8cce51..fa3aec54dd5 100644 --- a/internal/service/ec2/ebs_snapshot_test.go +++ b/internal/service/ec2/ebs_snapshot_test.go @@ -17,7 +17,7 @@ import ( func TestAccEC2EBSSnapshot_basic(t *testing.T) { var v ec2.Snapshot - rName := fmt.Sprintf("tf-acc-ebs-snapshot-basic-%s", sdkacctest.RandString(7)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_ebs_snapshot.test" resource.ParallelTest(t, resource.TestCase{ @@ -27,15 +27,15 @@ func TestAccEC2EBSSnapshot_basic(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotBasicConfig(rName), + Config: testAccEBSSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`snapshot/snap-.+`)), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - resource.TestCheckResourceAttr(resourceName, "outpost_arn", ""), resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "outpost_arn", ""), + acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), resource.TestCheckResourceAttr(resourceName, "storage_tier", "standard"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -47,9 +47,32 @@ func TestAccEC2EBSSnapshot_basic(t *testing.T) { }) } +func TestAccEC2EBSSnapshot_disappears(t *testing.T) { + var v ec2.Snapshot + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_ebs_snapshot.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEBSSnapshotDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEBSSnapshotConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckSnapshotExists(resourceName, &v), + acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceEBSSnapshot(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccEC2EBSSnapshot_storageTier(t *testing.T) { var v ec2.Snapshot - rName := fmt.Sprintf("tf-acc-ebs-snapshot-basic-%s", sdkacctest.RandString(7)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_ebs_snapshot.test" resource.ParallelTest(t, resource.TestCase{ @@ -59,7 +82,7 @@ func TestAccEC2EBSSnapshot_storageTier(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotStorageTierConfig(rName, "archive"), + Config: testAccEBSSnapshotConfig_storageTier(rName, "archive"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "storage_tier", "archive"), @@ -78,7 +101,7 @@ func TestAccEC2EBSSnapshot_outpost(t *testing.T) { var v ec2.Snapshot outpostDataSourceName := "data.aws_outposts_outpost.test" resourceName := "aws_ebs_snapshot.test" - rName := fmt.Sprintf("tf-acc-ebs-snapshot-basic-%s", sdkacctest.RandString(7)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckOutpostsOutposts(t) }, @@ -87,7 +110,7 @@ func TestAccEC2EBSSnapshot_outpost(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotOutpostConfig(rName), + Config: testAccEBSSnapshotConfig_outpost(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "outpost_arn", outpostDataSourceName, "arn"), @@ -104,7 +127,7 @@ func TestAccEC2EBSSnapshot_outpost(t *testing.T) { func TestAccEC2EBSSnapshot_tags(t *testing.T) { var v ec2.Snapshot - rName := fmt.Sprintf("tf-acc-ebs-snapshot-desc-%s", sdkacctest.RandString(7)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_ebs_snapshot.test" resource.ParallelTest(t, resource.TestCase{ @@ -114,10 +137,10 @@ func TestAccEC2EBSSnapshot_tags(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotBasicTags1Config(rName, "key1", "value1"), + Config: testAccEBSSnapshotConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, @@ -127,19 +150,19 @@ func TestAccEC2EBSSnapshot_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEBSSnapshotBasicTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccEBSSnapshotConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { - Config: testAccEBSSnapshotBasicTags1Config(rName, "key2", "value2"), + Config: testAccEBSSnapshotConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, @@ -149,7 +172,7 @@ func TestAccEC2EBSSnapshot_tags(t *testing.T) { func TestAccEC2EBSSnapshot_withDescription(t *testing.T) { var v ec2.Snapshot - rName := fmt.Sprintf("tf-acc-ebs-snapshot-desc-%s", sdkacctest.RandString(7)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_ebs_snapshot.test" resource.ParallelTest(t, resource.TestCase{ @@ -159,10 +182,10 @@ func TestAccEC2EBSSnapshot_withDescription(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotWithDescriptionConfig(rName), + Config: testAccEBSSnapshotConfig_description(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "description", rName), + resource.TestCheckResourceAttr(resourceName, "description", "test description"), ), }, { @@ -176,7 +199,7 @@ func TestAccEC2EBSSnapshot_withDescription(t *testing.T) { func TestAccEC2EBSSnapshot_withKMS(t *testing.T) { var v ec2.Snapshot - rName := fmt.Sprintf("tf-acc-ebs-snapshot-kms-%s", sdkacctest.RandString(7)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) kmsKeyResourceName := "aws_kms_key.test" resourceName := "aws_ebs_snapshot.test" @@ -187,7 +210,7 @@ func TestAccEC2EBSSnapshot_withKMS(t *testing.T) { CheckDestroy: testAccCheckEBSSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSSnapshotWithKMSConfig(rName), + Config: testAccEBSSnapshotConfig_kms(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsKeyResourceName, "arn"), @@ -202,29 +225,6 @@ func TestAccEC2EBSSnapshot_withKMS(t *testing.T) { }) } -func TestAccEC2EBSSnapshot_disappears(t *testing.T) { - var v ec2.Snapshot - rName := fmt.Sprintf("tf-acc-ebs-snapshot-basic-%s", sdkacctest.RandString(7)) - resourceName := "aws_ebs_snapshot.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckEBSSnapshotDestroy, - Steps: []resource.TestStep{ - { - Config: testAccEBSSnapshotBasicConfig(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckSnapshotExists(resourceName, &v), - acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceEBSSnapshot(), resourceName), - ), - ExpectNonEmptyPlan: true, - }, - }, - }) -} - func testAccCheckSnapshotExists(n string, v *ec2.Snapshot) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -233,11 +233,12 @@ func testAccCheckSnapshotExists(n string, v *ec2.Snapshot) resource.TestCheckFun } if rs.Primary.ID == "" { - return fmt.Errorf("No ID is set") + return fmt.Errorf("No EBS Snapshot ID is set") } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - output, err := tfec2.FindSnapshotById(conn, rs.Primary.ID) + + output, err := tfec2.FindSnapshotByID(conn, rs.Primary.ID) if err != nil { return err @@ -257,7 +258,7 @@ func testAccCheckEBSSnapshotDestroy(s *terraform.State) error { continue } - _, err := tfec2.FindSnapshotById(conn, rs.Primary.ID) + _, err := tfec2.FindSnapshotByID(conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -286,35 +287,29 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccEBSSnapshotBasicConfig(rName string) string { +func testAccEBSSnapshotConfig_basic(rName string) string { return acctest.ConfigCompose(testAccEBSSnapshotBaseConfig(rName), ` resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id - - timeouts { - create = "10m" - delete = "10m" - } } `) } -func testAccEBSSnapshotStorageTierConfig(rName, tier string) string { +func testAccEBSSnapshotConfig_storageTier(rName, tier string) string { return acctest.ConfigCompose(testAccEBSSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id - storage_tier = %[1]q + storage_tier = %[2]q - timeouts { - create = "10m" - delete = "10m" + tags = { + Name = %[1]q } } -`, tier)) +`, rName, tier)) } -func testAccEBSSnapshotOutpostConfig(rName string) string { - return acctest.ConfigCompose(testAccEBSSnapshotBaseConfig(rName), ` +func testAccEBSSnapshotConfig_outpost(rName string) string { + return acctest.ConfigCompose(testAccEBSSnapshotBaseConfig(rName), fmt.Sprintf(` data "aws_outposts_outposts" "test" {} data "aws_outposts_outpost" "test" { @@ -325,61 +320,52 @@ resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id outpost_arn = data.aws_outposts_outpost.test.arn - timeouts { - create = "10m" - delete = "10m" + tags = { + Name = %[1]q } } -`) +`, rName)) } -func testAccEBSSnapshotBasicTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccEBSSnapshotConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccEBSSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id tags = { - Name = "%s" - "%s" = "%s" - } - - timeouts { - create = "10m" - delete = "10m" + %[1]q = %[2]q } } -`, rName, tagKey1, tagValue1)) +`, tagKey1, tagValue1)) } -func testAccEBSSnapshotBasicTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccEBSSnapshotConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccEBSSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id tags = { - Name = "%s" - "%s" = "%s" - "%s" = "%s" - } - - timeouts { - create = "10m" - delete = "10m" + %[1]q = %[2]q + %[3]q = %[4]q } } -`, rName, tagKey1, tagValue1, tagKey2, tagValue2)) +`, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccEBSSnapshotWithDescriptionConfig(rName string) string { +func testAccEBSSnapshotConfig_description(rName string) string { return acctest.ConfigCompose(testAccEBSSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id - description = %[1]q + description = "test description" + + tags = { + Name = %[1]q + } } `, rName)) } -func testAccEBSSnapshotWithKMSConfig(rName string) string { +func testAccEBSSnapshotConfig_kms(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -402,6 +388,10 @@ resource "aws_ebs_volume" "test" { resource "aws_ebs_snapshot" "test" { volume_id = aws_ebs_volume.test.id + + tags = { + Name = %[1]q + } } `, rName)) } diff --git a/internal/service/ec2/ebs_volume.go b/internal/service/ec2/ebs_volume.go index a9a4edbc06a..4fbdfb3ba7d 100644 --- a/internal/service/ec2/ebs_volume.go +++ b/internal/service/ec2/ebs_volume.go @@ -57,6 +57,11 @@ func ResourceEBSVolume() *schema.Resource { Computed: true, ForceNew: true, }, + "final_snapshot": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, "iops": { Type: schema.TypeInt, Optional: true, @@ -186,7 +191,7 @@ func resourceEBSVolumeRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("reading EBS Volume(%s): %w", d.Id(), err) + return fmt.Errorf("reading EBS Volume (%s): %w", d.Id(), err) } arn := arn.ARN{ @@ -246,13 +251,21 @@ func resourceEBSVolumeUpdate(d *schema.ResourceData, meta interface{}) error { } if d.HasChange("type") { - input.VolumeType = aws.String(d.Get("type").(string)) + volumeType := d.Get("type").(string) + input.VolumeType = aws.String(volumeType) + + // Get Iops value because in the ec2.ModifyVolumeInput API, + // if you change the volume type to io1, io2, or gp3, the default is 3,000. + // https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyVolume.html + if volumeType == ec2.VolumeTypeIo1 || volumeType == ec2.VolumeTypeIo2 || volumeType == ec2.VolumeTypeGp3 { + input.Iops = aws.Int64(int64(d.Get("iops").(int))) + } } _, err := conn.ModifyVolume(input) if err != nil { - return fmt.Errorf("modifying EBS Volume(%s): %w", d.Id(), err) + return fmt.Errorf("modifying EBS Volume (%s): %w", d.Id(), err) } if _, err := WaitVolumeUpdated(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { @@ -274,6 +287,38 @@ func resourceEBSVolumeUpdate(d *schema.ResourceData, meta interface{}) error { func resourceEBSVolumeDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn + if d.Get("final_snapshot").(bool) { + input := &ec2.CreateSnapshotInput{ + TagSpecifications: tagSpecificationsFromMap(d.Get("tags_all").(map[string]interface{}), ec2.ResourceTypeSnapshot), + VolumeId: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Creating EBS Snapshot: %s", input) + outputRaw, err := tfresource.RetryWhenAWSErrMessageContains(1*time.Minute, + func() (interface{}, error) { + return conn.CreateSnapshot(input) + }, + errCodeSnapshotCreationPerVolumeRateExceeded, "The maximum per volume CreateSnapshot request rate has been exceeded") + + if err != nil { + return fmt.Errorf("creating EBS Snapshot (%s): %w", d.Id(), err) + } + + snapshotID := aws.StringValue(outputRaw.(*ec2.Snapshot).SnapshotId) + + _, err = tfresource.RetryWhenAWSErrCodeEquals(d.Timeout(schema.TimeoutDelete), + func() (interface{}, error) { + return nil, conn.WaitUntilSnapshotCompleted(&ec2.DescribeSnapshotsInput{ + SnapshotIds: aws.StringSlice([]string{snapshotID}), + }) + }, + errCodeResourceNotReady) + + if err != nil { + return fmt.Errorf("waiting for EBS Snapshot (%s) create: %w", snapshotID, err) + } + } + log.Printf("[DEBUG] Deleting EBS Volume: %s", d.Id()) _, err := tfresource.RetryWhenAWSErrCodeEquals(d.Timeout(schema.TimeoutDelete), func() (interface{}, error) { @@ -340,7 +385,7 @@ func resourceEBSVolumeCustomizeDiff(_ context.Context, diff *schema.ResourceDiff // Update. // Setting 'iops = 0' is a no-op if the volume type does not require Iops to be specified. - if diff.HasChange("iops") && volumeType != ec2.VolumeTypeIo1 && volumeType != ec2.VolumeTypeIo2 && iops == 0 { + if diff.HasChange("iops") && volumeType != ec2.VolumeTypeIo1 && volumeType != ec2.VolumeTypeIo2 && volumeType != ec2.VolumeTypeGp3 && iops == 0 { return diff.Clear("iops") } } diff --git a/internal/service/ec2/ebs_volume_attachment.go b/internal/service/ec2/ebs_volume_attachment.go index 01049d49509..410c3b51074 100644 --- a/internal/service/ec2/ebs_volume_attachment.go +++ b/internal/service/ec2/ebs_volume_attachment.go @@ -9,7 +9,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "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" @@ -180,40 +179,6 @@ func resourceVolumeAttachmentDelete(d *schema.ResourceData, meta interface{}) er return nil } -func volumeAttachmentStateRefreshFunc(conn *ec2.EC2, name, volumeID, instanceID string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - request := &ec2.DescribeVolumesInput{ - VolumeIds: []*string{aws.String(volumeID)}, - Filters: []*ec2.Filter{ - { - Name: aws.String("attachment.device"), - Values: []*string{aws.String(name)}, - }, - { - Name: aws.String("attachment.instance-id"), - Values: []*string{aws.String(instanceID)}, - }, - }, - } - - resp, err := conn.DescribeVolumes(request) - if err != nil { - return nil, "failed", err - } - - if len(resp.Volumes) > 0 { - v := resp.Volumes[0] - for _, a := range v.Attachments { - if aws.StringValue(a.InstanceId) == instanceID { - return a, aws.StringValue(a.State), nil - } - } - } - // assume detached if volume count is 0 - return 42, ec2.VolumeAttachmentStateDetached, nil - } -} - func volumeAttachmentID(name, volumeID, instanceID string) string { var buf bytes.Buffer buf.WriteString(fmt.Sprintf("%s-", name)) diff --git a/internal/service/ec2/ebs_volume_attachment_test.go b/internal/service/ec2/ebs_volume_attachment_test.go index 57de5e6ac45..0a5224db86c 100644 --- a/internal/service/ec2/ebs_volume_attachment_test.go +++ b/internal/service/ec2/ebs_volume_attachment_test.go @@ -27,7 +27,7 @@ func TestAccEC2EBSVolumeAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckVolumeAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccVolumeAttachmentConfig(rName), + Config: testAccEBSVolumeAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeAttachmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "device_name", "/dev/sdh"), @@ -54,7 +54,7 @@ func TestAccEC2EBSVolumeAttachment_skipDestroy(t *testing.T) { CheckDestroy: testAccCheckVolumeAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccVolumeAttachmentConfigSkipDestroy(rName), + Config: testAccEBSVolumeAttachmentConfig_skipDestroy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeAttachmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "device_name", "/dev/sdh"), @@ -95,14 +95,14 @@ func TestAccEC2EBSVolumeAttachment_attachStopped(t *testing.T) { CheckDestroy: testAccCheckVolumeAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccVolumeAttachmentBaseConfig(rName), + Config: testAccEBSVolumeAttachmentConfig_base(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists("aws_instance.test", &i), ), }, { PreConfig: stopInstance, - Config: testAccVolumeAttachmentConfig(rName), + Config: testAccEBSVolumeAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeAttachmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "device_name", "/dev/sdh"), @@ -129,7 +129,7 @@ func TestAccEC2EBSVolumeAttachment_update(t *testing.T) { CheckDestroy: testAccCheckVolumeAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccVolumeAttachmentUpdateConfig(rName, false), + Config: testAccEBSVolumeAttachmentConfig_update(rName, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "force_detach", "false"), resource.TestCheckResourceAttr(resourceName, "skip_destroy", "false"), @@ -146,7 +146,7 @@ func TestAccEC2EBSVolumeAttachment_update(t *testing.T) { }, }, { - Config: testAccVolumeAttachmentUpdateConfig(rName, true), + Config: testAccEBSVolumeAttachmentConfig_update(rName, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "force_detach", "true"), resource.TestCheckResourceAttr(resourceName, "skip_destroy", "true"), @@ -179,7 +179,7 @@ func TestAccEC2EBSVolumeAttachment_disappears(t *testing.T) { CheckDestroy: testAccCheckVolumeAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccVolumeAttachmentConfig(rName), + Config: testAccEBSVolumeAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists("aws_instance.test", &i), testAccCheckVolumeExists("aws_ebs_volume.test", &v), @@ -203,7 +203,7 @@ func TestAccEC2EBSVolumeAttachment_stopInstance(t *testing.T) { CheckDestroy: testAccCheckVolumeAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccVolumeAttachmentStopInstanceConfig(rName), + Config: testAccEBSVolumeAttachmentConfig_stopInstance(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeAttachmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "device_name", "/dev/sdh"), @@ -271,7 +271,7 @@ func testAccCheckVolumeAttachmentDestroy(s *terraform.State) error { func testAccVolumeAttachmentInstanceOnlyBaseConfig(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), fmt.Sprintf(` @@ -287,7 +287,7 @@ resource "aws_instance" "test" { `, rName)) } -func testAccVolumeAttachmentBaseConfig(rName string) string { +func testAccEBSVolumeAttachmentConfig_base(rName string) string { return acctest.ConfigCompose(testAccVolumeAttachmentInstanceOnlyBaseConfig(rName), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] @@ -300,8 +300,8 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccVolumeAttachmentConfig(rName string) string { - return acctest.ConfigCompose(testAccVolumeAttachmentBaseConfig(rName), ` +func testAccEBSVolumeAttachmentConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccEBSVolumeAttachmentConfig_base(rName), ` resource "aws_volume_attachment" "test" { device_name = "/dev/sdh" volume_id = aws_ebs_volume.test.id @@ -310,7 +310,7 @@ resource "aws_volume_attachment" "test" { `) } -func testAccVolumeAttachmentStopInstanceConfig(rName string) string { +func testAccEBSVolumeAttachmentConfig_stopInstance(rName string) string { return acctest.ConfigCompose(testAccVolumeAttachmentInstanceOnlyBaseConfig(rName), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] @@ -330,8 +330,8 @@ resource "aws_volume_attachment" "test" { `, rName)) } -func testAccVolumeAttachmentConfigSkipDestroy(rName string) string { - return acctest.ConfigCompose(testAccVolumeAttachmentBaseConfig(rName), fmt.Sprintf(` +func testAccEBSVolumeAttachmentConfig_skipDestroy(rName string) string { + return acctest.ConfigCompose(testAccEBSVolumeAttachmentConfig_base(rName), fmt.Sprintf(` data "aws_ebs_volume" "test" { filter { name = "size" @@ -358,8 +358,8 @@ resource "aws_volume_attachment" "test" { `, rName)) } -func testAccVolumeAttachmentUpdateConfig(rName string, detach bool) string { - return acctest.ConfigCompose(testAccVolumeAttachmentBaseConfig(rName), fmt.Sprintf(` +func testAccEBSVolumeAttachmentConfig_update(rName string, detach bool) string { + return acctest.ConfigCompose(testAccEBSVolumeAttachmentConfig_base(rName), fmt.Sprintf(` resource "aws_volume_attachment" "test" { device_name = "/dev/sdh" volume_id = aws_ebs_volume.test.id diff --git a/internal/service/ec2/ebs_volume_data_source.go b/internal/service/ec2/ebs_volume_data_source.go index ab93f49a7e4..9396169ae4f 100644 --- a/internal/service/ec2/ebs_volume_data_source.go +++ b/internal/service/ec2/ebs_volume_data_source.go @@ -93,7 +93,7 @@ func dataSourceEBSVolumeRead(d *schema.ResourceData, meta interface{}) error { output, err := FindEBSVolumes(conn, input) if err != nil { - return fmt.Errorf("reading EC2 Volumes: %w", err) + return fmt.Errorf("reading EBS Volumes: %w", err) } if len(output) < 1 { diff --git a/internal/service/ec2/ebs_volume_data_source_test.go b/internal/service/ec2/ebs_volume_data_source_test.go index 8e4a78b89cd..a76637db4b0 100644 --- a/internal/service/ec2/ebs_volume_data_source_test.go +++ b/internal/service/ec2/ebs_volume_data_source_test.go @@ -22,7 +22,7 @@ func TestAccEC2EBSVolumeDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckEBSVolumeDataSourceConfig(rName), + Config: testAccEBSVolumeDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEBSVolumeIDDataSource(dataSourceName), resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), @@ -48,7 +48,7 @@ func TestAccEC2EBSVolumeDataSource_multipleFilters(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckEBSVolumeWithMultipleFiltersDataSourceConfig(rName), + Config: testAccEBSVolumeDataSourceConfig_multipleFilters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEBSVolumeIDDataSource(dataSourceName), resource.TestCheckResourceAttrPair(dataSourceName, "size", resourceName, "size"), @@ -74,7 +74,7 @@ func testAccCheckEBSVolumeIDDataSource(n string) resource.TestCheckFunc { } } -func testAccCheckEBSVolumeDataSourceConfig(rName string) string { +func testAccEBSVolumeDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -104,7 +104,7 @@ data "aws_ebs_volume" "test" { `, rName)) } -func testAccCheckEBSVolumeWithMultipleFiltersDataSourceConfig(rName string) string { +func testAccEBSVolumeDataSourceConfig_multipleFilters(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` diff --git a/internal/service/ec2/ebs_volume_test.go b/internal/service/ec2/ebs_volume_test.go index 96f6754515d..f079d320d2d 100644 --- a/internal/service/ec2/ebs_volume_test.go +++ b/internal/service/ec2/ebs_volume_test.go @@ -5,6 +5,7 @@ import ( "regexp" "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -26,7 +27,7 @@ func TestAccEC2EBSVolume_basic(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeConfig, + Config: testAccEBSVolumeConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -42,9 +43,10 @@ func TestAccEC2EBSVolume_basic(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, }, }) @@ -61,7 +63,7 @@ func TestAccEC2EBSVolume_disappears(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeConfig, + Config: testAccEBSVolumeConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceEBSVolume(), resourceName), @@ -84,7 +86,7 @@ func TestAccEC2EBSVolume_updateAttachedEBSVolume(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSAttachedVolumeConfig(rName), + Config: testAccEBSVolumeConfig_attached(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "size", "10"), @@ -92,12 +94,13 @@ func TestAccEC2EBSVolume_updateAttachedEBSVolume(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, { - Config: testAccEBSAttachedVolumeUpdateSizeConfig(rName), + Config: testAccEBSVolumeConfig_attachedUpdateSize(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "size", "20"), @@ -120,7 +123,7 @@ func TestAccEC2EBSVolume_updateSize(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeBasicConfig(rName), + Config: testAccEBSVolumeConfig_tags1("Name", rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "size", "1"), @@ -128,12 +131,13 @@ func TestAccEC2EBSVolume_updateSize(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, { - Config: testAccEBSVolumeUpdateSizeConfig(rName), + Config: testAccEBSVolumeConfig_updateSize(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "size", "10"), @@ -156,7 +160,7 @@ func TestAccEC2EBSVolume_updateType(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeBasicConfig(rName), + Config: testAccEBSVolumeConfig_tags1("Name", rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "type", "gp2"), @@ -164,12 +168,13 @@ func TestAccEC2EBSVolume_updateType(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, { - Config: testAccEBSVolumeUpdateTypeConfig(rName), + Config: testAccEBSVolumeConfig_updateType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "type", "sc1"), @@ -192,7 +197,7 @@ func TestAccEC2EBSVolume_UpdateIops_io1(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeWithIopsIo1Config(rName), + Config: testAccEBSVolumeConfig_iopsIo1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "iops", "100"), @@ -200,12 +205,13 @@ func TestAccEC2EBSVolume_UpdateIops_io1(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, { - Config: testAccEBSVolumeWithIopsIo1UpdatedConfig(rName), + Config: testAccEBSVolumeConfig_iopsIo1Updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "iops", "200"), @@ -228,7 +234,7 @@ func TestAccEC2EBSVolume_UpdateIops_io2(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeWithIopsIo2Config(rName), + Config: testAccEBSVolumeConfig_iopsIo2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "iops", "100"), @@ -236,12 +242,13 @@ func TestAccEC2EBSVolume_UpdateIops_io2(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, { - Config: testAccEBSVolumeWithIopsIo2UpdatedConfig(rName), + Config: testAccEBSVolumeConfig_iopsIo2Updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "iops", "200"), @@ -265,7 +272,7 @@ func TestAccEC2EBSVolume_kmsKey(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeWithKMSKeyConfig(rName), + Config: testAccEBSVolumeConfig_kmsKey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "encrypted", "true"), @@ -274,9 +281,10 @@ func TestAccEC2EBSVolume_kmsKey(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, }, }) @@ -294,16 +302,17 @@ func TestAccEC2EBSVolume_noIops(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeWithNoIopsConfig(rName), + Config: testAccEBSVolumeConfig_noIOPS(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "throughput", "0"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, }, }) @@ -318,7 +327,7 @@ func TestAccEC2EBSVolume_invalidIopsForType(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeWithInvalidIopsForTypeConfig, + Config: testAccEBSVolumeConfig_invalidIOPSForType, ExpectError: regexp.MustCompile(`'iops' must not be set when 'type' is`), }, }, @@ -333,7 +342,7 @@ func TestAccEC2EBSVolume_invalidThroughputForType(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeWithInvalidThroughputForTypeConfig, + Config: testAccEBSVolumeConfig_invalidThroughputForType, ExpectError: regexp.MustCompile(`'throughput' must not be set when 'type' is`), }, }, @@ -351,7 +360,7 @@ func TestAccEC2EBSVolume_withTags(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeConfigTags1("key1", "value1"), + Config: testAccEBSVolumeConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -359,12 +368,13 @@ func TestAccEC2EBSVolume_withTags(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, { - Config: testAccEBSVolumeConfigTags2("key1", "value1updated", "key2", "value2"), + Config: testAccEBSVolumeConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -373,7 +383,7 @@ func TestAccEC2EBSVolume_withTags(t *testing.T) { ), }, { - Config: testAccEBSVolumeConfigTags1("key2", "value2"), + Config: testAccEBSVolumeConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -396,7 +406,7 @@ func TestAccEC2EBSVolume_multiAttach_io1(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeMultiAttachConfig(rName, "io1"), + Config: testAccEBSVolumeConfig_multiAttach(rName, "io1"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "multi_attach_enabled", "true"), @@ -405,9 +415,10 @@ func TestAccEC2EBSVolume_multiAttach_io1(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, }, }) @@ -425,7 +436,7 @@ func TestAccEC2EBSVolume_multiAttach_io2(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeMultiAttachConfig(rName, "io2"), + Config: testAccEBSVolumeConfig_multiAttach(rName, "io2"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "multi_attach_enabled", "true"), @@ -434,9 +445,10 @@ func TestAccEC2EBSVolume_multiAttach_io2(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, }, }) @@ -450,7 +462,7 @@ func TestAccEC2EBSVolume_multiAttach_gp2(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeWithInvalidMultiAttachEnabledForTypeConfig, + Config: testAccEBSVolumeConfig_invalidMultiAttachEnabledForType, ExpectError: regexp.MustCompile(`'multi_attach_enabled' must not be set when 'type' is`), }, }, @@ -470,16 +482,17 @@ func TestAccEC2EBSVolume_outpost(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeOutpostConfig(rName), + Config: testAccEBSVolumeConfig_outpost(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "outpost_arn", outpostDataSourceName, "arn"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, }, }) @@ -497,7 +510,7 @@ func TestAccEC2EBSVolume_GP3_basic(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeSizeTypeIopsThroughputConfig(rName, "10", "gp3", "", ""), + Config: testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, "10", "gp3", "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -515,9 +528,10 @@ func TestAccEC2EBSVolume_GP3_basic(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, }, }) @@ -535,7 +549,7 @@ func TestAccEC2EBSVolume_GP3_iops(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeSizeTypeIopsThroughputConfig(rName, "10", "gp3", "4000", "200"), + Config: testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, "10", "gp3", "4000", "200"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -553,12 +567,13 @@ func TestAccEC2EBSVolume_GP3_iops(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, { - Config: testAccEBSVolumeSizeTypeIopsThroughputConfig(rName, "10", "gp3", "5000", "200"), + Config: testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, "10", "gp3", "5000", "200"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -591,7 +606,7 @@ func TestAccEC2EBSVolume_GP3_throughput(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeSizeTypeIopsThroughputConfig(rName, "10", "gp3", "", "400"), + Config: testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, "10", "gp3", "", "400"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -609,12 +624,13 @@ func TestAccEC2EBSVolume_GP3_throughput(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, { - Config: testAccEBSVolumeSizeTypeIopsThroughputConfig(rName, "10", "gp3", "", "600"), + Config: testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, "10", "gp3", "", "600"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -647,7 +663,7 @@ func TestAccEC2EBSVolume_gp3ToGP2(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeSizeTypeIopsThroughputConfig(rName, "10", "gp3", "3000", "400"), + Config: testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, "10", "gp3", "3000", "400"), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -665,12 +681,13 @@ func TestAccEC2EBSVolume_gp3ToGP2(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, { - Config: testAccEBSVolumeSizeTypeIopsThroughputConfig(rName, "10", "gp2", "", ""), + Config: testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, "10", "gp2", "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -691,6 +708,63 @@ func TestAccEC2EBSVolume_gp3ToGP2(t *testing.T) { }) } +func TestAccEC2EBSVolume_io1ToGP3(t *testing.T) { + var v ec2.Volume + resourceName := "aws_ebs_volume.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckVolumeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, "100", "io1", "4000", ""), + Check: resource.ComposeTestCheckFunc( + testAccCheckVolumeExists(resourceName, &v), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), + resource.TestCheckResourceAttr(resourceName, "encrypted", "false"), + resource.TestCheckResourceAttr(resourceName, "iops", "4000"), + resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), + resource.TestCheckResourceAttr(resourceName, "multi_attach_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "outpost_arn", ""), + resource.TestCheckResourceAttr(resourceName, "size", "100"), + resource.TestCheckResourceAttr(resourceName, "snapshot_id", ""), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), + resource.TestCheckResourceAttr(resourceName, "throughput", "0"), + resource.TestCheckResourceAttr(resourceName, "type", "io1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, + }, + { + Config: testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, "100", "gp3", "4000", "125"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVolumeExists(resourceName, &v), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), + resource.TestCheckResourceAttr(resourceName, "encrypted", "false"), + resource.TestCheckResourceAttr(resourceName, "iops", "4000"), + resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), + resource.TestCheckResourceAttr(resourceName, "multi_attach_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "outpost_arn", ""), + resource.TestCheckResourceAttr(resourceName, "size", "100"), + resource.TestCheckResourceAttr(resourceName, "snapshot_id", ""), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), + resource.TestCheckResourceAttr(resourceName, "throughput", "125"), + resource.TestCheckResourceAttr(resourceName, "type", "gp3"), + ), + }, + }, + }) +} + func TestAccEC2EBSVolume_snapshotID(t *testing.T) { var v ec2.Volume resourceName := "aws_ebs_volume.test" @@ -704,7 +778,7 @@ func TestAccEC2EBSVolume_snapshotID(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeSnapshotIDConfig(rName), + Config: testAccEBSVolumeConfig_snapshotID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -722,9 +796,10 @@ func TestAccEC2EBSVolume_snapshotID(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, }, }, }) @@ -743,7 +818,7 @@ func TestAccEC2EBSVolume_snapshotIDAndSize(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeSnapshotIdAndSizeConfig(rName, 20), + Config: testAccEBSVolumeConfig_snapshotIdAndSize(rName, 20), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`volume/vol-.+`)), @@ -761,9 +836,44 @@ func TestAccEC2EBSVolume_snapshotIDAndSize(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, + }, + }, + }) +} + +func TestAccEC2EBSVolume_finalSnapshot(t *testing.T) { + var v ec2.Volume + resourceName := "aws_ebs_volume.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckVolumeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEBSVolumeConfig_finalSnapshot(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckVolumeExists(resourceName, &v), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"final_snapshot"}, + }, + { + Config: testAccEBSVolumeConfig_finalSnapshot(rName), + Destroy: true, + Check: resource.ComposeTestCheckFunc( + testAccCheckVolumeFinalSnapshotExists(&v), + ), }, }, }) @@ -818,31 +928,47 @@ func testAccCheckVolumeExists(n string, v *ec2.Volume) resource.TestCheckFunc { } } -var testAccEBSVolumeConfig = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` -resource "aws_ebs_volume" "test" { - availability_zone = data.aws_availability_zones.available.names[0] - type = "gp2" - size = 1 +func testAccCheckVolumeFinalSnapshotExists(v *ec2.Volume) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := acctest.Provider.Meta().(*conns.AWSClient) + conn := client.EC2Conn + + input := &ec2.DescribeSnapshotsInput{ + Filters: tfec2.BuildAttributeFilterList(map[string]string{ + "volume-id": aws.StringValue(v.VolumeId), + "status": ec2.SnapshotStateCompleted, + }), + } + + output, err := tfec2.FindSnapshot(conn, input) + + if err != nil { + return err + } + + r := tfec2.ResourceEBSSnapshot() + d := r.Data(nil) + d.SetId(aws.StringValue(output.SnapshotId)) + + if err := r.Delete(d, client); err != nil { + return err + } + + return nil + } } -`) -func testAccEBSVolumeBasicConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` +var testAccEBSVolumeConfig_basic = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] type = "gp2" size = 1 - - tags = { - Name = %[1]q - } -} -`, rName)) } +`) -func testAccEBSAttachedVolumeConfig(rName string) string { +func testAccEBSVolumeConfig_attached(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -879,9 +1005,9 @@ resource "aws_volume_attachment" "test" { `, rName)) } -func testAccEBSAttachedVolumeUpdateSizeConfig(rName string) string { +func testAccEBSVolumeConfig_attachedUpdateSize(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -918,7 +1044,7 @@ resource "aws_volume_attachment" "test" { `, rName)) } -func testAccEBSVolumeUpdateSizeConfig(rName string) string { +func testAccEBSVolumeConfig_updateSize(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -934,7 +1060,7 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccEBSVolumeUpdateTypeConfig(rName string) string { +func testAccEBSVolumeConfig_updateType(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -950,7 +1076,7 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccEBSVolumeWithIopsIo1Config(rName string) string { +func testAccEBSVolumeConfig_iopsIo1(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -967,7 +1093,7 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccEBSVolumeWithIopsIo1UpdatedConfig(rName string) string { +func testAccEBSVolumeConfig_iopsIo1Updated(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -984,7 +1110,7 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccEBSVolumeWithIopsIo2Config(rName string) string { +func testAccEBSVolumeConfig_iopsIo2(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1001,7 +1127,7 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccEBSVolumeWithIopsIo2UpdatedConfig(rName string) string { +func testAccEBSVolumeConfig_iopsIo2Updated(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1018,7 +1144,7 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccEBSVolumeWithKMSKeyConfig(rName string) string { +func testAccEBSVolumeConfig_kmsKey(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1056,7 +1182,7 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccEBSVolumeConfigTags1(tagKey1, tagValue1 string) string { +func testAccEBSVolumeConfig_tags1(tagKey1, tagValue1 string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1071,7 +1197,7 @@ resource "aws_ebs_volume" "test" { `, tagKey1, tagValue1)) } -func testAccEBSVolumeConfigTags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccEBSVolumeConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1087,7 +1213,7 @@ resource "aws_ebs_volume" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccEBSVolumeWithNoIopsConfig(rName string) string { +func testAccEBSVolumeConfig_noIOPS(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1104,7 +1230,7 @@ resource "aws_ebs_volume" "test" { `, rName)) } -var testAccEBSVolumeWithInvalidIopsForTypeConfig = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` +var testAccEBSVolumeConfig_invalidIOPSForType = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] size = 10 @@ -1112,7 +1238,7 @@ resource "aws_ebs_volume" "test" { } `) -var testAccEBSVolumeWithInvalidThroughputForTypeConfig = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` +var testAccEBSVolumeConfig_invalidThroughputForType = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] size = 10 @@ -1122,7 +1248,7 @@ resource "aws_ebs_volume" "test" { } `) -var testAccEBSVolumeWithInvalidMultiAttachEnabledForTypeConfig = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` +var testAccEBSVolumeConfig_invalidMultiAttachEnabledForType = acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] size = 10 @@ -1131,7 +1257,7 @@ resource "aws_ebs_volume" "test" { } `) -func testAccEBSVolumeOutpostConfig(rName string) string { +func testAccEBSVolumeConfig_outpost(rName string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -1151,7 +1277,7 @@ resource "aws_ebs_volume" "test" { `, rName) } -func testAccEBSVolumeMultiAttachConfig(rName, volumeType string) string { +func testAccEBSVolumeConfig_multiAttach(rName, volumeType string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = data.aws_availability_zones.available.names[0] @@ -1167,7 +1293,7 @@ resource "aws_ebs_volume" "test" { `, rName, volumeType)) } -func testAccEBSVolumeSizeTypeIopsThroughputConfig(rName, size, volumeType, iops, throughput string) string { +func testAccEBSVolumeConfig_sizeTypeIOPSThroughput(rName, size, volumeType, iops, throughput string) string { if volumeType == "" { volumeType = "null" } @@ -1195,7 +1321,7 @@ resource "aws_ebs_volume" "test" { `, rName, size, volumeType, iops, throughput)) } -func testAccEBSVolumeSnapshotIDConfig(rName string) string { +func testAccEBSVolumeConfig_snapshotID(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1227,7 +1353,7 @@ resource "aws_ebs_volume" "test" { `, rName)) } -func testAccEBSVolumeSnapshotIdAndSizeConfig(rName string, size int) string { +func testAccEBSVolumeConfig_snapshotIdAndSize(rName string, size int) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1259,3 +1385,17 @@ resource "aws_ebs_volume" "test" { } `, rName, size)) } + +func testAccEBSVolumeConfig_finalSnapshot(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` +resource "aws_ebs_volume" "test" { + availability_zone = data.aws_availability_zones.available.names[0] + size = 10 + final_snapshot = true + + tags = { + Name = %[1]q + } +} +`, rName)) +} diff --git a/internal/service/ec2/ebs_volumes_data_source_test.go b/internal/service/ec2/ebs_volumes_data_source_test.go index 8f53cc09327..9fe0f68033b 100644 --- a/internal/service/ec2/ebs_volumes_data_source_test.go +++ b/internal/service/ec2/ebs_volumes_data_source_test.go @@ -20,7 +20,7 @@ func TestAccEC2EBSVolumesDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSVolumeIDsDataSourceConfig(rName), + Config: testAccEBSVolumesDataSourceConfig_volumeIDs(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_ebs_volumes.by_tags", "ids.#", "2"), resource.TestCheckResourceAttr("data.aws_ebs_volumes.by_filter", "ids.#", "1"), @@ -31,7 +31,7 @@ func TestAccEC2EBSVolumesDataSource_basic(t *testing.T) { }) } -func testAccEBSVolumeIDsDataSourceConfig(rName string) string { +func testAccEBSVolumesDataSourceConfig_volumeIDs(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` data "aws_region" "current" {} diff --git a/internal/service/ec2/ec2_ami.go b/internal/service/ec2/ec2_ami.go index 9dbcf5181c3..f2d401ce3d0 100644 --- a/internal/service/ec2/ec2_ami.go +++ b/internal/service/ec2/ec2_ami.go @@ -250,10 +250,16 @@ func ResourceAMI() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: "simple", + Default: SriovNetSupportSimple, }, "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), + "tpm_support": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(ec2.TpmSupportValues_Values(), false), + }, "usage_operation": { Type: schema.TypeString, Computed: true, @@ -300,6 +306,10 @@ func resourceAMICreate(d *schema.ResourceData, meta interface{}) error { input.RamdiskId = aws.String(ramdiskId) } + if v := d.Get("tpm_support").(string); v != "" { + input.TpmSupport = aws.String(v) + } + if v, ok := d.GetOk("ebs_block_device"); ok && v.(*schema.Set).Len() > 0 { for _, tfMapRaw := range v.(*schema.Set).List() { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -419,6 +429,7 @@ func resourceAMIRead(d *schema.ResourceData, meta interface{}) error { d.Set("root_device_name", image.RootDeviceName) d.Set("root_snapshot_id", amiRootSnapshotId(image)) d.Set("sriov_net_support", image.SriovNetSupport) + d.Set("tpm_support", image.TpmSupport) d.Set("usage_operation", image.UsageOperation) d.Set("virtualization_type", image.VirtualizationType) @@ -485,7 +496,7 @@ func resourceAMIDelete(d *schema.ResourceData, meta interface{}) error { ImageId: aws.String(d.Id()), }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidAMIIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidAMIIDNotFound, errCodeInvalidAMIIDUnavailable) { return nil } diff --git a/internal/service/ec2/ec2_ami_copy.go b/internal/service/ec2/ec2_ami_copy.go index 1c8c7b0692a..0eec09e0c22 100644 --- a/internal/service/ec2/ec2_ami_copy.go +++ b/internal/service/ec2/ec2_ami_copy.go @@ -236,6 +236,10 @@ func ResourceAMICopy() *schema.Resource { }, "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), + "tpm_support": { + Type: schema.TypeString, + Computed: true, + }, "usage_operation": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/ec2/ec2_ami_copy_test.go b/internal/service/ec2/ec2_ami_copy_test.go index 43b34e4d3da..c1525c26d5a 100644 --- a/internal/service/ec2/ec2_ami_copy_test.go +++ b/internal/service/ec2/ec2_ami_copy_test.go @@ -25,7 +25,7 @@ func TestAccEC2AMICopy_basic(t *testing.T) { CheckDestroy: testAccCheckAMIDestroy, Steps: []resource.TestStep{ { - Config: testAccAMICopyConfig(rName), + Config: testAccAMICopyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), testAccCheckAMICopyAttributes(&image, rName), @@ -53,14 +53,14 @@ func TestAccEC2AMICopy_description(t *testing.T) { CheckDestroy: testAccCheckAMIDestroy, Steps: []resource.TestStep{ { - Config: testAccAMICopyDescriptionConfig(rName, "description1"), + Config: testAccAMICopyConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "description", "description1"), ), }, { - Config: testAccAMICopyDescriptionConfig(rName, "description2"), + Config: testAccAMICopyConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -82,7 +82,7 @@ func TestAccEC2AMICopy_enaSupport(t *testing.T) { CheckDestroy: testAccCheckAMIDestroy, Steps: []resource.TestStep{ { - Config: testAccAMICopyENASupportConfig(rName), + Config: testAccAMICopyConfig_enaSupport(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "ena_support", "true"), @@ -105,7 +105,7 @@ func TestAccEC2AMICopy_destinationOutpost(t *testing.T) { CheckDestroy: testAccCheckAMIDestroy, Steps: []resource.TestStep{ { - Config: testAccAMICopyDestOutpostConfig(rName), + Config: testAccAMICopyConfig_destOutpost(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), resource.TestCheckResourceAttrPair(resourceName, "destination_outpost_arn", outpostDataSourceName, "arn"), @@ -127,7 +127,7 @@ func TestAccEC2AMICopy_tags(t *testing.T) { CheckDestroy: testAccCheckAMIDestroy, Steps: []resource.TestStep{ { - Config: testAccAMICopyTags1Config(rName, "key1", "value1"), + Config: testAccAMICopyConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), testAccCheckAMICopyAttributes(&ami, rName), @@ -136,7 +136,7 @@ func TestAccEC2AMICopy_tags(t *testing.T) { ), }, { - Config: testAccAMICopyTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAMICopyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), testAccCheckAMICopyAttributes(&ami, rName), @@ -146,7 +146,7 @@ func TestAccEC2AMICopy_tags(t *testing.T) { ), }, { - Config: testAccAMICopyTags1Config(rName, "key2", "value2"), + Config: testAccAMICopyConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), testAccCheckAMICopyAttributes(&ami, rName), @@ -220,7 +220,7 @@ resource "aws_ebs_snapshot" "test" { `, rName) } -func testAccAMICopyTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAMICopyConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccAMICopyBaseConfig(rName), fmt.Sprintf(` resource "aws_ami" "test" { name = %[1]q @@ -245,7 +245,7 @@ resource "aws_ami_copy" "test" { `, rName, tagKey1, tagValue1)) } -func testAccAMICopyTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAMICopyConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccAMICopyBaseConfig(rName), fmt.Sprintf(` resource "aws_ami" "test" { name = %[1]q @@ -271,7 +271,7 @@ resource "aws_ami_copy" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccAMICopyConfig(rName string) string { +func testAccAMICopyConfig_basic(rName string) string { return acctest.ConfigCompose(testAccAMICopyBaseConfig(rName), fmt.Sprintf(` resource "aws_ami" "test" { name = "%s-source" @@ -292,7 +292,7 @@ resource "aws_ami_copy" "test" { `, rName, rName)) } -func testAccAMICopyDescriptionConfig(rName, description string) string { +func testAccAMICopyConfig_description(rName, description string) string { return acctest.ConfigCompose(testAccAMICopyBaseConfig(rName), fmt.Sprintf(` resource "aws_ami" "test" { name = "%s-source" @@ -314,7 +314,7 @@ resource "aws_ami_copy" "test" { `, rName, description, rName)) } -func testAccAMICopyENASupportConfig(rName string) string { +func testAccAMICopyConfig_enaSupport(rName string) string { return acctest.ConfigCompose(testAccAMICopyBaseConfig(rName), fmt.Sprintf(` resource "aws_ami" "test" { ena_support = true @@ -336,7 +336,7 @@ resource "aws_ami_copy" "test" { `, rName, rName)) } -func testAccAMICopyDestOutpostConfig(rName string) string { +func testAccAMICopyConfig_destOutpost(rName string) string { return acctest.ConfigCompose(testAccAMICopyBaseConfig(rName), fmt.Sprintf(` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/ec2/ec2_ami_data_source.go b/internal/service/ec2/ec2_ami_data_source.go index 5dafbe39483..321f3ec5621 100644 --- a/internal/service/ec2/ec2_ami_data_source.go +++ b/internal/service/ec2/ec2_ami_data_source.go @@ -194,6 +194,10 @@ func DataSourceAMI() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, }, "tags": tftags.TagsSchemaComputed(), + "tpm_support": { + Type: schema.TypeString, + Computed: true, + }, "usage_operation": { Type: schema.TypeString, Computed: true, @@ -296,6 +300,7 @@ func amiDescriptionAttributes(d *schema.ResourceData, image *ec2.Image, meta int d.Set("root_snapshot_id", amiRootSnapshotId(image)) d.Set("sriov_net_support", image.SriovNetSupport) d.Set("state", image.State) + d.Set("tpm_support", image.TpmSupport) d.Set("usage_operation", image.UsageOperation) d.Set("virtualization_type", image.VirtualizationType) diff --git a/internal/service/ec2/ec2_ami_data_source_test.go b/internal/service/ec2/ec2_ami_data_source_test.go index 2bc30bfa3fa..042e783f7cf 100644 --- a/internal/service/ec2/ec2_ami_data_source_test.go +++ b/internal/service/ec2/ec2_ami_data_source_test.go @@ -21,7 +21,7 @@ func TestAccEC2AMIDataSource_natInstance(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAMIDataSourceConfig_basic, - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIIDDataSource(resourceName), // Check attributes. Some attributes are tough to test - any not contained here should not be considered // stable and should not be used in interpolation. Exception to block_device_mappings which should both @@ -30,12 +30,13 @@ func TestAccEC2AMIDataSource_natInstance(t *testing.T) { // deep inspection is not included, simply the count is checked. // Tags and product codes may need more testing, but I'm having a hard time finding images with // these attributes set. - acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), + acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "1"), resource.TestMatchResourceAttr(resourceName, "creation_date", regexp.MustCompile("^20[0-9]{2}-")), resource.TestMatchResourceAttr(resourceName, "deprecation_time", regexp.MustCompile("^20[0-9]{2}-")), resource.TestMatchResourceAttr(resourceName, "description", regexp.MustCompile("^Amazon Linux AMI")), + resource.TestCheckResourceAttr(resourceName, "ena_support", "true"), resource.TestCheckResourceAttr(resourceName, "hypervisor", "xen"), resource.TestMatchResourceAttr(resourceName, "image_id", regexp.MustCompile("^ami-")), resource.TestMatchResourceAttr(resourceName, "image_location", regexp.MustCompile("^amazon/")), @@ -44,8 +45,9 @@ func TestAccEC2AMIDataSource_natInstance(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "most_recent", "true"), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile("^amzn-ami-vpc-nat")), acctest.MatchResourceAttrAccountID(resourceName, "owner_id"), - resource.TestCheckResourceAttr(resourceName, "public", "true"), + resource.TestCheckResourceAttr(resourceName, "platform_details", "Linux/UNIX"), resource.TestCheckResourceAttr(resourceName, "product_codes.#", "0"), + resource.TestCheckResourceAttr(resourceName, "public", "true"), resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/xvda"), resource.TestCheckResourceAttr(resourceName, "root_device_type", "ebs"), resource.TestMatchResourceAttr(resourceName, "root_snapshot_id", regexp.MustCompile("^snap-")), @@ -54,10 +56,8 @@ func TestAccEC2AMIDataSource_natInstance(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "state_reason.code", "UNSET"), resource.TestCheckResourceAttr(resourceName, "state_reason.message", "UNSET"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), - resource.TestCheckResourceAttr(resourceName, "platform_details", "Linux/UNIX"), - resource.TestCheckResourceAttr(resourceName, "ena_support", "true"), resource.TestCheckResourceAttr(resourceName, "usage_operation", "RunInstances"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, }, @@ -73,13 +73,14 @@ func TestAccEC2AMIDataSource_windowsInstance(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAMIDataSourceConfig_windows, - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIIDDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "27"), resource.TestMatchResourceAttr(resourceName, "creation_date", regexp.MustCompile("^20[0-9]{2}-")), resource.TestMatchResourceAttr(resourceName, "deprecation_time", regexp.MustCompile("^20[0-9]{2}-")), resource.TestMatchResourceAttr(resourceName, "description", regexp.MustCompile("^Microsoft Windows Server")), + resource.TestCheckResourceAttr(resourceName, "ena_support", "true"), resource.TestCheckResourceAttr(resourceName, "hypervisor", "xen"), resource.TestMatchResourceAttr(resourceName, "image_id", regexp.MustCompile("^ami-")), resource.TestMatchResourceAttr(resourceName, "image_location", regexp.MustCompile("^amazon/")), @@ -89,8 +90,9 @@ func TestAccEC2AMIDataSource_windowsInstance(t *testing.T) { resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile("^Windows_Server-2012-R2")), acctest.MatchResourceAttrAccountID(resourceName, "owner_id"), resource.TestCheckResourceAttr(resourceName, "platform", "windows"), - resource.TestCheckResourceAttr(resourceName, "public", "true"), + resource.TestMatchResourceAttr(resourceName, "platform_details", regexp.MustCompile(`Windows`)), resource.TestCheckResourceAttr(resourceName, "product_codes.#", "0"), + resource.TestCheckResourceAttr(resourceName, "public", "true"), resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/sda1"), resource.TestCheckResourceAttr(resourceName, "root_device_type", "ebs"), resource.TestMatchResourceAttr(resourceName, "root_snapshot_id", regexp.MustCompile("^snap-")), @@ -99,10 +101,9 @@ func TestAccEC2AMIDataSource_windowsInstance(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "state_reason.code", "UNSET"), resource.TestCheckResourceAttr(resourceName, "state_reason.message", "UNSET"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), - resource.TestMatchResourceAttr(resourceName, "platform_details", regexp.MustCompile(`Windows`)), - resource.TestCheckResourceAttr(resourceName, "ena_support", "true"), + resource.TestCheckResourceAttr(resourceName, "tpm_support", ""), resource.TestMatchResourceAttr(resourceName, "usage_operation", regexp.MustCompile(`^RunInstances`)), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, }, @@ -117,13 +118,14 @@ func TestAccEC2AMIDataSource_instanceStore(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLatestAmazonLinuxHVMInstanceStoreAMIConfig(), - Check: resource.ComposeTestCheckFunc( + Config: testAccAMIDataSourceConfig_latestAmazonLinuxHVMInstanceStore(), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIIDDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "0"), resource.TestMatchResourceAttr(resourceName, "creation_date", regexp.MustCompile("^20[0-9]{2}-")), resource.TestMatchResourceAttr(resourceName, "deprecation_time", regexp.MustCompile("^20[0-9]{2}-")), + resource.TestCheckResourceAttr(resourceName, "ena_support", "true"), resource.TestCheckResourceAttr(resourceName, "hypervisor", "xen"), resource.TestMatchResourceAttr(resourceName, "image_id", regexp.MustCompile("^ami-")), resource.TestMatchResourceAttr(resourceName, "image_location", regexp.MustCompile("amzn-ami-minimal-hvm")), @@ -131,8 +133,9 @@ func TestAccEC2AMIDataSource_instanceStore(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "most_recent", "true"), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile("amzn-ami-minimal-hvm")), acctest.MatchResourceAttrAccountID(resourceName, "owner_id"), - resource.TestCheckResourceAttr(resourceName, "public", "true"), + resource.TestCheckResourceAttr(resourceName, "platform_details", "Linux/UNIX"), resource.TestCheckResourceAttr(resourceName, "product_codes.#", "0"), + resource.TestCheckResourceAttr(resourceName, "public", "true"), resource.TestCheckResourceAttr(resourceName, "root_device_type", "instance-store"), resource.TestCheckResourceAttr(resourceName, "root_snapshot_id", ""), resource.TestCheckResourceAttr(resourceName, "sriov_net_support", "simple"), @@ -140,10 +143,9 @@ func TestAccEC2AMIDataSource_instanceStore(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "state_reason.code", "UNSET"), resource.TestCheckResourceAttr(resourceName, "state_reason.message", "UNSET"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), - resource.TestCheckResourceAttr(resourceName, "platform_details", "Linux/UNIX"), - resource.TestCheckResourceAttr(resourceName, "ena_support", "true"), + resource.TestCheckResourceAttr(resourceName, "tpm_support", ""), resource.TestCheckResourceAttr(resourceName, "usage_operation", "RunInstances"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, }, @@ -213,10 +215,10 @@ func testAccCheckAMIIDDataSource(n string) resource.TestCheckFunc { } } -// testAccLatestAmazonLinuxHVMInstanceStoreAMIConfig returns the configuration for a data source that +// testAccAMIDataSourceConfig_latestAmazonLinuxHVMInstanceStore returns the configuration for a data source that // describes the latest Amazon Linux AMI using HVM virtualization and an instance store root device. // The data source is named 'amzn-ami-minimal-hvm-instance-store'. -func testAccLatestAmazonLinuxHVMInstanceStoreAMIConfig() string { +func testAccAMIDataSourceConfig_latestAmazonLinuxHVMInstanceStore() string { return ` data "aws_ami" "amzn-ami-minimal-hvm-instance-store" { most_recent = true diff --git a/internal/service/ec2/ec2_ami_from_instance.go b/internal/service/ec2/ec2_ami_from_instance.go index bc7210fbb7a..305170b4696 100644 --- a/internal/service/ec2/ec2_ami_from_instance.go +++ b/internal/service/ec2/ec2_ami_from_instance.go @@ -218,6 +218,10 @@ func ResourceAMIFromInstance() *schema.Resource { }, "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), + "tpm_support": { + Type: schema.TypeString, + Computed: true, + }, "usage_operation": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/ec2/ec2_ami_from_instance_test.go b/internal/service/ec2/ec2_ami_from_instance_test.go index 94012cf806e..a3860fbac36 100644 --- a/internal/service/ec2/ec2_ami_from_instance_test.go +++ b/internal/service/ec2/ec2_ami_from_instance_test.go @@ -24,7 +24,7 @@ func TestAccEC2AMIFromInstance_basic(t *testing.T) { CheckDestroy: testAccCheckAMIDestroy, Steps: []resource.TestStep{ { - Config: testAccAMIFromInstanceConfig(rName), + Config: testAccAMIFromInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), @@ -53,7 +53,7 @@ func TestAccEC2AMIFromInstance_tags(t *testing.T) { CheckDestroy: testAccCheckAMIDestroy, Steps: []resource.TestStep{ { - Config: testAccAMIFromInstanceTags1Config(rName, "key1", "value1"), + Config: testAccAMIFromInstanceConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -61,7 +61,7 @@ func TestAccEC2AMIFromInstance_tags(t *testing.T) { ), }, { - Config: testAccAMIFromInstanceTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAMIFromInstanceConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -70,7 +70,7 @@ func TestAccEC2AMIFromInstance_tags(t *testing.T) { ), }, { - Config: testAccAMIFromInstanceTags1Config(rName, "key2", "value2"), + Config: testAccAMIFromInstanceConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -93,7 +93,7 @@ func TestAccEC2AMIFromInstance_disappears(t *testing.T) { CheckDestroy: testAccCheckAMIDestroy, Steps: []resource.TestStep{ { - Config: testAccAMIFromInstanceConfig(rName), + Config: testAccAMIFromInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMIExists(resourceName, &image), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceAMIFromInstance(), resourceName), @@ -106,7 +106,7 @@ func TestAccEC2AMIFromInstance_disappears(t *testing.T) { func testAccAMIFromInstanceBaseConfig(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { @@ -120,7 +120,7 @@ resource "aws_instance" "test" { `, rName)) } -func testAccAMIFromInstanceConfig(rName string) string { +func testAccAMIFromInstanceConfig_basic(rName string) string { return acctest.ConfigCompose( testAccAMIFromInstanceBaseConfig(rName), fmt.Sprintf(` @@ -132,7 +132,7 @@ resource "aws_ami_from_instance" "test" { `, rName)) } -func testAccAMIFromInstanceTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAMIFromInstanceConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( testAccAMIFromInstanceBaseConfig(rName), fmt.Sprintf(` @@ -148,7 +148,7 @@ resource "aws_ami_from_instance" "test" { `, rName, tagKey1, tagValue1)) } -func testAccAMIFromInstanceTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAMIFromInstanceConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( testAccAMIFromInstanceBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/ec2/ec2_ami_ids_data_source_test.go b/internal/service/ec2/ec2_ami_ids_data_source_test.go index f7d1c387af5..5d33d8827f2 100644 --- a/internal/service/ec2/ec2_ami_ids_data_source_test.go +++ b/internal/service/ec2/ec2_ami_ids_data_source_test.go @@ -34,7 +34,6 @@ func TestAccEC2AMIIDsDataSource_sorted(t *testing.T) { { Config: testAccAMIIdsDataSourceConfig_sorted(false), Check: resource.ComposeTestCheckFunc( - testAccCheckEBSSnapshotIDDataSource("data.aws_ami_ids.test"), resource.TestCheckResourceAttr("data.aws_ami_ids.test", "ids.#", "2"), resource.TestCheckResourceAttrPair( "data.aws_ami_ids.test", "ids.0", diff --git a/internal/service/ec2/ec2_ami_launch_permission_test.go b/internal/service/ec2/ec2_ami_launch_permission_test.go index c60005a8a6f..fb41aea5d29 100644 --- a/internal/service/ec2/ec2_ami_launch_permission_test.go +++ b/internal/service/ec2/ec2_ami_launch_permission_test.go @@ -26,7 +26,7 @@ func TestAccEC2AMILaunchPermission_basic(t *testing.T) { CheckDestroy: testAccCheckAMILaunchPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccAMILaunchPermissionAccountIDConfig(rName), + Config: testAccAMILaunchPermissionConfig_accountID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMILaunchPermissionExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -56,7 +56,7 @@ func TestAccEC2AMILaunchPermission_disappears(t *testing.T) { CheckDestroy: testAccCheckAMILaunchPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccAMILaunchPermissionAccountIDConfig(rName), + Config: testAccAMILaunchPermissionConfig_accountID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMILaunchPermissionExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceAMILaunchPermission(), resourceName), @@ -78,7 +78,7 @@ func TestAccEC2AMILaunchPermission_Disappears_ami(t *testing.T) { CheckDestroy: testAccCheckAMILaunchPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccAMILaunchPermissionAccountIDConfig(rName), + Config: testAccAMILaunchPermissionConfig_accountID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMILaunchPermissionExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceAMICopy(), "aws_ami_copy.test"), @@ -100,7 +100,7 @@ func TestAccEC2AMILaunchPermission_group(t *testing.T) { CheckDestroy: testAccCheckAMILaunchPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccAMILaunchPermissionGroupConfig(rName), + Config: testAccAMILaunchPermissionConfig_group(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMILaunchPermissionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "account_id", ""), @@ -130,7 +130,7 @@ func TestAccEC2AMILaunchPermission_organizationARN(t *testing.T) { CheckDestroy: testAccCheckAMILaunchPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccAMILaunchPermissionOrganizationARNConfig(rName), + Config: testAccAMILaunchPermissionConfig_organizationARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMILaunchPermissionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "account_id", ""), @@ -160,7 +160,7 @@ func TestAccEC2AMILaunchPermission_organizationalUnitARN(t *testing.T) { CheckDestroy: testAccCheckAMILaunchPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccAMILaunchPermissionOrganizationalUnitARNConfig(rName), + Config: testAccAMILaunchPermissionConfig_organizationalUnitARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAMILaunchPermissionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "account_id", ""), @@ -259,8 +259,8 @@ func testAccCheckAMILaunchPermissionDestroy(s *terraform.State) error { return nil } -func testAccAMILaunchPermissionAccountIDConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccAMILaunchPermissionConfig_accountID(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` data "aws_caller_identity" "current" {} data "aws_region" "current" {} @@ -279,8 +279,8 @@ resource "aws_ami_launch_permission" "test" { `, rName)) } -func testAccAMILaunchPermissionGroupConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccAMILaunchPermissionConfig_group(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` data "aws_region" "current" {} resource "aws_ami_copy" "test" { @@ -298,8 +298,8 @@ resource "aws_ami_launch_permission" "test" { `, rName)) } -func testAccAMILaunchPermissionOrganizationARNConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccAMILaunchPermissionConfig_organizationARN(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` data "aws_organizations_organization" "current" {} data "aws_region" "current" {} @@ -318,8 +318,8 @@ resource "aws_ami_launch_permission" "test" { `, rName)) } -func testAccAMILaunchPermissionOrganizationalUnitARNConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccAMILaunchPermissionConfig_organizationalUnitARN(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_organizations_organization" "test" {} resource "aws_organizations_organizational_unit" "test" { diff --git a/internal/service/ec2/ec2_ami_test.go b/internal/service/ec2/ec2_ami_test.go index b4cfd3cb6ce..f75d2994d59 100644 --- a/internal/service/ec2/ec2_ami_test.go +++ b/internal/service/ec2/ec2_ami_test.go @@ -30,7 +30,7 @@ func TestAccEC2AMI_basic(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAMIConfig_basic(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), @@ -49,20 +49,20 @@ func TestAccEC2AMI_basic(t *testing.T) { resource.TestCheckTypeSetElemAttrPair(resourceName, "ebs_block_device.*.snapshot_id", snapshotResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "ena_support", "true"), resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.#", "0"), + resource.TestCheckResourceAttr(resourceName, "hypervisor", "xen"), + resource.TestCheckResourceAttr(resourceName, "image_type", "machine"), resource.TestCheckResourceAttr(resourceName, "kernel_id", ""), resource.TestCheckResourceAttr(resourceName, "name", rName), acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "platform_details", "Linux/UNIX"), resource.TestCheckResourceAttr(resourceName, "ramdisk_id", ""), resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/sda1"), resource.TestCheckResourceAttrPair(resourceName, "root_snapshot_id", snapshotResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "sriov_net_support", "simple"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tpm_support", ""), resource.TestCheckResourceAttr(resourceName, "usage_operation", "RunInstances"), - resource.TestCheckResourceAttr(resourceName, "platform_details", "Linux/UNIX"), - resource.TestCheckResourceAttr(resourceName, "image_type", "machine"), - resource.TestCheckResourceAttr(resourceName, "hypervisor", "xen"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, { @@ -93,7 +93,7 @@ func TestAccEC2AMI_deprecateAt(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAMIConfig_deprecateAt(rName, deprecateAt), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), @@ -120,8 +120,8 @@ func TestAccEC2AMI_deprecateAt(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/sda1"), resource.TestCheckResourceAttrPair(resourceName, "root_snapshot_id", snapshotResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "sriov_net_support", "simple"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, { @@ -134,7 +134,7 @@ func TestAccEC2AMI_deprecateAt(t *testing.T) { }, { Config: testAccAMIConfig_deprecateAt(rName, deprecateAtUpdated), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), @@ -161,8 +161,8 @@ func TestAccEC2AMI_deprecateAt(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/sda1"), resource.TestCheckResourceAttrPair(resourceName, "root_snapshot_id", snapshotResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "sriov_net_support", "simple"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, }, @@ -185,7 +185,7 @@ func TestAccEC2AMI_description(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAMIConfig_desc(rName, desc), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), @@ -211,8 +211,8 @@ func TestAccEC2AMI_description(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/sda1"), resource.TestCheckResourceAttrPair(resourceName, "root_snapshot_id", snapshotResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "sriov_net_support", "simple"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, { @@ -225,7 +225,7 @@ func TestAccEC2AMI_description(t *testing.T) { }, { Config: testAccAMIConfig_desc(rName, descUpdated), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), @@ -251,8 +251,8 @@ func TestAccEC2AMI_description(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/sda1"), resource.TestCheckResourceAttrPair(resourceName, "root_snapshot_id", snapshotResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "sriov_net_support", "simple"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, }, @@ -296,7 +296,7 @@ func TestAccEC2AMI_ephemeralBlockDevices(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAMIConfig_ephemeralBlockDevices(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), @@ -329,8 +329,8 @@ func TestAccEC2AMI_ephemeralBlockDevices(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/sda1"), resource.TestCheckResourceAttrPair(resourceName, "root_snapshot_id", snapshotResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "sriov_net_support", "simple"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, { @@ -359,7 +359,7 @@ func TestAccEC2AMI_gp3BlockDevice(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAMIConfig_gp3BlockDevice(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAMIExists(resourceName, &ami), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), @@ -395,8 +395,8 @@ func TestAccEC2AMI_gp3BlockDevice(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/sda1"), resource.TestCheckResourceAttrPair(resourceName, "root_snapshot_id", snapshotResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "sriov_net_support", "simple"), - resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), ), }, { @@ -519,6 +519,36 @@ func TestAccEC2AMI_boot(t *testing.T) { }) } +func TestAccEC2AMI_tpmSupport(t *testing.T) { + var ami ec2.Image + resourceName := "aws_ami.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAMIDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAMIConfig_tpmSupport(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAMIExists(resourceName, &ami), + resource.TestCheckResourceAttr(resourceName, "tpm_support", "v2.0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "manage_ebs_snapshots", + }, + }, + }, + }) +} + func testAccCheckAMIDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn @@ -798,3 +828,23 @@ resource "aws_ami" "test" { } `, rName)) } + +func testAccAMIConfig_tpmSupport(rName string) string { + return acctest.ConfigCompose( + testAccAMIConfig_base(rName), + fmt.Sprintf(` +resource "aws_ami" "test" { + ena_support = true + name = %[1]q + root_device_name = "/dev/xvda" + virtualization_type = "hvm" + boot_mode = "uefi" + tpm_support = "v2.0" + + ebs_block_device { + device_name = "/dev/xvda" + snapshot_id = aws_ebs_snapshot.test.id + } +} +`, rName)) +} diff --git a/internal/service/ec2/ec2_availability_zone_data_source_test.go b/internal/service/ec2/ec2_availability_zone_data_source_test.go index 04ded75d416..08a2042f1a6 100644 --- a/internal/service/ec2/ec2_availability_zone_data_source_test.go +++ b/internal/service/ec2/ec2_availability_zone_data_source_test.go @@ -22,7 +22,7 @@ func TestAccEC2AvailabilityZoneDataSource_allAvailabilityZones(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAvailabilityZoneAllAvailabilityZonesDataSourceConfig(), + Config: testAccAvailabilityZoneDataSourceConfig_allAZs(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "group_name", acctest.Region()), resource.TestCheckResourceAttrPair(dataSourceName, "name", availabilityZonesDataSourceName, "names.0"), @@ -50,7 +50,7 @@ func TestAccEC2AvailabilityZoneDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAvailabilityZoneFilterDataSourceConfig(), + Config: testAccAvailabilityZoneDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "group_name", acctest.Region()), resource.TestCheckResourceAttrPair(dataSourceName, "name", availabilityZonesDataSourceName, "names.0"), @@ -78,7 +78,7 @@ func TestAccEC2AvailabilityZoneDataSource_localZone(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAvailabilityZoneZoneTypeDataSourceConfig("local-zone"), + Config: testAccAvailabilityZoneDataSourceConfig_type("local-zone"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "group_name"), resource.TestCheckResourceAttrPair(dataSourceName, "name", availabilityZonesDataSourceName, "names.0"), @@ -106,7 +106,7 @@ func TestAccEC2AvailabilityZoneDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAvailabilityZoneNameDataSourceConfig(), + Config: testAccAvailabilityZoneDataSourceConfig_name(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "group_name", acctest.Region()), resource.TestCheckResourceAttrPair(dataSourceName, "name", availabilityZonesDataSourceName, "names.0"), @@ -134,7 +134,7 @@ func TestAccEC2AvailabilityZoneDataSource_wavelengthZone(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAvailabilityZoneZoneTypeDataSourceConfig("wavelength-zone"), + Config: testAccAvailabilityZoneDataSourceConfig_type("wavelength-zone"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "group_name"), resource.TestCheckResourceAttrPair(dataSourceName, "name", availabilityZonesDataSourceName, "names.0"), @@ -162,7 +162,7 @@ func TestAccEC2AvailabilityZoneDataSource_zoneID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAvailabilityZoneZoneIDDataSourceConfig(), + Config: testAccAvailabilityZoneDataSourceConfig_id(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "group_name", acctest.Region()), resource.TestCheckResourceAttrPair(dataSourceName, "name", availabilityZonesDataSourceName, "names.0"), @@ -205,7 +205,7 @@ func testAccPreCheckLocalZoneAvailable(t *testing.T) { } } -func testAccAvailabilityZoneAllAvailabilityZonesDataSourceConfig() string { +func testAccAvailabilityZoneDataSourceConfig_allAZs() string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), ` @@ -216,7 +216,7 @@ data "aws_availability_zone" "test" { `) } -func testAccAvailabilityZoneFilterDataSourceConfig() string { +func testAccAvailabilityZoneDataSourceConfig_filter() string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), ` @@ -229,7 +229,7 @@ data "aws_availability_zone" "test" { `) } -func testAccAvailabilityZoneNameDataSourceConfig() string { +func testAccAvailabilityZoneDataSourceConfig_name() string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), ` @@ -239,7 +239,7 @@ data "aws_availability_zone" "test" { `) } -func testAccAvailabilityZoneZoneIDDataSourceConfig() string { +func testAccAvailabilityZoneDataSourceConfig_id() string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), ` @@ -249,7 +249,7 @@ data "aws_availability_zone" "test" { `) } -func testAccAvailabilityZoneZoneTypeDataSourceConfig(zoneType string) string { +func testAccAvailabilityZoneDataSourceConfig_type(zoneType string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" diff --git a/internal/service/ec2/ec2_availability_zone_group_test.go b/internal/service/ec2/ec2_availability_zone_group_test.go index 54651e19e08..c09bf93b79c 100644 --- a/internal/service/ec2/ec2_availability_zone_group_test.go +++ b/internal/service/ec2/ec2_availability_zone_group_test.go @@ -38,13 +38,13 @@ func TestAccEC2AvailabilityZoneGroup_optInStatus(t *testing.T) { // InvalidOptInStatus: Opting out of Local Zones is not currently supported. Contact AWS Support for additional assistance. /* { - Config: testAccEc2AvailabilityZoneGroupConfigOptInStatus(ec2.AvailabilityZoneOptInStatusNotOptedIn), + Config: testAccAvailabilityZoneGroupConfig_optInStatus(ec2.AvailabilityZoneOptInStatusNotOptedIn), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "opt_in_status", ec2.AvailabilityZoneOptInStatusNotOptedIn), ), }, { - Config: testAccEc2AvailabilityZoneGroupConfigOptInStatus(ec2.AvailabilityZoneOptInStatusOptedIn), + Config: testAccAvailabilityZoneGroupConfig_optInStatus(ec2.AvailabilityZoneOptInStatusOptedIn), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "opt_in_status", ec2.AvailabilityZoneOptInStatusOptedIn), ), diff --git a/internal/service/ec2/ec2_availability_zones_data_source_test.go b/internal/service/ec2/ec2_availability_zones_data_source_test.go index 16db862f4a3..efb1a300718 100644 --- a/internal/service/ec2/ec2_availability_zones_data_source_test.go +++ b/internal/service/ec2/ec2_availability_zones_data_source_test.go @@ -99,7 +99,7 @@ func TestAccEC2AvailabilityZonesDataSource_allAvailabilityZones(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAvailabilityZonesAllAvailabilityZonesConfig(), + Config: testAccAvailabilityZonesDataSourceConfig_all(), Check: resource.ComposeTestCheckFunc( testAccCheckAvailabilityZonesMeta(dataSourceName), ), @@ -117,7 +117,7 @@ func TestAccEC2AvailabilityZonesDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAvailabilityZonesFilterConfig(), + Config: testAccAvailabilityZonesDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( testAccCheckAvailabilityZonesMeta(dataSourceName), ), @@ -136,7 +136,7 @@ func TestAccEC2AvailabilityZonesDataSource_excludeNames(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAvailabilityZonesExcludeNamesConfig(), + Config: testAccAvailabilityZonesDataSourceConfig_excludeNames(), Check: resource.ComposeTestCheckFunc( testAccCheckAvailabilityZonesExcluded(allDataSourceName, excludeDataSourceName), ), @@ -155,7 +155,7 @@ func TestAccEC2AvailabilityZonesDataSource_excludeZoneIDs(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAvailabilityZonesExcludeZoneIDsConfig(), + Config: testAccAvailabilityZonesDataSourceConfig_excludeZoneIDs(), Check: resource.ComposeTestCheckFunc( testAccCheckAvailabilityZonesExcluded(allDataSourceName, excludeDataSourceName), ), @@ -306,7 +306,7 @@ const testAccAvailabilityZonesDataSourceConfig_basic = ` data "aws_availability_zones" "availability_zones" {} ` -func testAccCheckAvailabilityZonesAllAvailabilityZonesConfig() string { +func testAccAvailabilityZonesDataSourceConfig_all() string { return ` data "aws_availability_zones" "test" { all_availability_zones = true @@ -314,7 +314,7 @@ data "aws_availability_zones" "test" { ` } -func testAccCheckAvailabilityZonesFilterConfig() string { +func testAccAvailabilityZonesDataSourceConfig_filter() string { return ` data "aws_availability_zones" "test" { filter { @@ -325,7 +325,7 @@ data "aws_availability_zones" "test" { ` } -func testAccCheckAvailabilityZonesExcludeNamesConfig() string { +func testAccAvailabilityZonesDataSourceConfig_excludeNames() string { return ` data "aws_availability_zones" "all" {} @@ -335,7 +335,7 @@ data "aws_availability_zones" "test" { ` } -func testAccCheckAvailabilityZonesExcludeZoneIDsConfig() string { +func testAccAvailabilityZonesDataSourceConfig_excludeZoneIDs() string { return ` data "aws_availability_zones" "all" {} diff --git a/internal/service/ec2/ec2_eip_association_test.go b/internal/service/ec2/ec2_eip_association_test.go index 515ade7d8d0..52a5e2c7ff5 100644 --- a/internal/service/ec2/ec2_eip_association_test.go +++ b/internal/service/ec2/ec2_eip_association_test.go @@ -78,7 +78,7 @@ func TestAccEC2EIPAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckEIPAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPAssociationConfig(rName), + Config: testAccEIPAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists("aws_eip.test.0", false, &a), testAccCheckEIPAssociationExists("aws_eip_association.by_allocation_id", &a), @@ -108,7 +108,7 @@ func TestAccEC2EIPAssociation_ec2Classic(t *testing.T) { CheckDestroy: testAccCheckEIPAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPAssociationConfig_ec2Classic(), + Config: testAccEIPAssociationConfig_classic(), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists("aws_eip.test", true, &a), testAccCheckEIPAssociationClassicExists(resourceName, &a), @@ -172,7 +172,7 @@ func TestAccEC2EIPAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckEIPAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPAssociationDisappearsConfig(rName), + Config: testAccEIPAssociationConfig_disappears(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists("aws_eip.test", false, &a), testAccCheckEIPAssociationExists(resourceName, &a), @@ -314,10 +314,10 @@ func testAccCheckEIPAssociationDestroy(s *terraform.State) error { return nil } -func testAccEIPAssociationConfig(rName string) string { +func testAccEIPAssociationConfig_basic(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "192.168.0.0/24" @@ -383,10 +383,10 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccEIPAssociationDisappearsConfig(rName string) string { +func testAccEIPAssociationConfig_disappears(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_vpc" "main" { cidr_block = "192.168.0.0/24" @@ -426,7 +426,7 @@ resource "aws_eip_association" "test" { `, rName)) } -func testAccEIPAssociationConfig_ec2Classic() string { // nosemgrep:ec2-in-func-name +func testAccEIPAssociationConfig_classic() string { // nosemgrep:ec2-in-func-name return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), testAccLatestAmazonLinuxPVEBSAMIConfig(), @@ -448,7 +448,7 @@ resource "aws_eip_association" "test" { func testAccEIPAssociationConfig_spotInstance(rName, publicKey string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("aws_subnet.test.availability_zone", "t3.micro", "t2.micro"), acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -495,7 +495,7 @@ func testAccEIPAssociationConfig_instance() string { return acctest.ConfigCompose( acctest.AvailableEC2InstanceTypeForAvailabilityZone("aws_subnet.test.availability_zone", "t3.micro", "t2.micro"), acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/ec2_eip_data_source_test.go b/internal/service/ec2/ec2_eip_data_source_test.go index cf7c180adf3..ce88087c3c8 100644 --- a/internal/service/ec2/ec2_eip_data_source_test.go +++ b/internal/service/ec2/ec2_eip_data_source_test.go @@ -21,7 +21,7 @@ func TestAccEC2EIPDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPFilterDataSourceConfig(rName), + Config: testAccEIPDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "public_dns", resourceName, "public_dns"), @@ -42,7 +42,7 @@ func TestAccEC2EIPDataSource_id(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPIDDataSourceConfig, + Config: testAccEIPDataSourceConfig_id, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "public_dns", resourceName, "public_dns"), @@ -63,7 +63,7 @@ func TestAccEC2EIPDataSource_PublicIP_ec2Classic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPPublicIPClassicDataSourceConfig(), + Config: testAccEIPDataSourceConfig_publicIPClassic(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "public_dns", resourceName, "public_dns"), @@ -84,7 +84,7 @@ func TestAccEC2EIPDataSource_PublicIP_vpc(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPPublicIPVPCDataSourceConfig, + Config: testAccEIPDataSourceConfig_publicIPVPC, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "public_dns", resourceName, "public_dns"), @@ -107,7 +107,7 @@ func TestAccEC2EIPDataSource_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPTagsDataSourceConfig(rName), + Config: testAccEIPDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "public_dns", resourceName, "public_dns"), @@ -128,7 +128,7 @@ func TestAccEC2EIPDataSource_networkInterface(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPNetworkInterfaceDataSourceConfig, + Config: testAccEIPDataSourceConfig_networkInterface, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "network_interface_id", resourceName, "network_interface"), @@ -151,7 +151,7 @@ func TestAccEC2EIPDataSource_instance(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPInstanceDataSourceConfig, + Config: testAccEIPDataSourceConfig_instance, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "instance_id", resourceName, "instance"), @@ -173,7 +173,7 @@ func TestAccEC2EIPDataSource_carrierIP(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPCarrierIPDataSourceConfig(rName), + Config: testAccEIPDataSourceConfig_carrierIP(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "carrier_ip", resourceName, "carrier_ip"), resource.TestCheckResourceAttrPair(dataSourceName, "public_ip", resourceName, "public_ip"), @@ -193,7 +193,7 @@ func TestAccEC2EIPDataSource_customerOwnedIPv4Pool(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPCustomerOwnedIPv4PoolDataSourceConfig(), + Config: testAccEIPDataSourceConfig_customerOwnedIPv4Pool(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "customer_owned_ipv4_pool", dataSourceName, "customer_owned_ipv4_pool"), resource.TestCheckResourceAttrPair(resourceName, "customer_owned_ip", dataSourceName, "customer_owned_ip"), @@ -203,7 +203,7 @@ func TestAccEC2EIPDataSource_customerOwnedIPv4Pool(t *testing.T) { }) } -func testAccEIPCustomerOwnedIPv4PoolDataSourceConfig() string { +func testAccEIPDataSourceConfig_customerOwnedIPv4Pool() string { return ` data "aws_ec2_coip_pools" "test" {} @@ -218,7 +218,7 @@ data "aws_eip" "test" { ` } -func testAccEIPFilterDataSourceConfig(rName string) string { +func testAccEIPDataSourceConfig_filter(rName string) string { return fmt.Sprintf(` resource "aws_eip" "test" { vpc = true @@ -237,7 +237,7 @@ data "aws_eip" "test" { `, rName) } -const testAccEIPIDDataSourceConfig = ` +const testAccEIPDataSourceConfig_id = ` resource "aws_eip" "test" { vpc = true } @@ -247,7 +247,7 @@ data "aws_eip" "test" { } ` -func testAccEIPPublicIPClassicDataSourceConfig() string { +func testAccEIPDataSourceConfig_publicIPClassic() string { return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), ` @@ -259,7 +259,7 @@ data "aws_eip" "test" { `) } -const testAccEIPPublicIPVPCDataSourceConfig = ` +const testAccEIPDataSourceConfig_publicIPVPC = ` resource "aws_eip" "test" { vpc = true } @@ -269,7 +269,7 @@ data "aws_eip" "test" { } ` -func testAccEIPTagsDataSourceConfig(rName string) string { +func testAccEIPDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` resource "aws_eip" "test" { vpc = true @@ -287,7 +287,7 @@ data "aws_eip" "test" { `, rName) } -const testAccEIPNetworkInterfaceDataSourceConfig = ` +const testAccEIPDataSourceConfig_networkInterface = ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" } @@ -318,7 +318,7 @@ data "aws_eip" "test" { } ` -var testAccEIPInstanceDataSourceConfig = acctest.ConfigCompose( +var testAccEIPDataSourceConfig_instance = acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), ` resource "aws_vpc" "test" { cidr_block = "10.2.0.0/16" @@ -362,7 +362,7 @@ data "aws_eip" "test" { } `) -func testAccEIPCarrierIPDataSourceConfig(rName string) string { +func testAccEIPDataSourceConfig_carrierIP(rName string) string { return acctest.ConfigCompose( testAccAvailableAZsWavelengthZonesDefaultExcludeConfig(), fmt.Sprintf(` diff --git a/internal/service/ec2/ec2_eip_test.go b/internal/service/ec2/ec2_eip_test.go index 2402b5a2052..ffd3f3bafda 100644 --- a/internal/service/ec2/ec2_eip_test.go +++ b/internal/service/ec2/ec2_eip_test.go @@ -36,7 +36,7 @@ func TestAccEC2EIP_basic(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPConfig, + Config: testAccEIPConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -64,7 +64,7 @@ func TestAccEC2EIP_disappears(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPConfig, + Config: testAccEIPConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceEIP(), resourceName), @@ -86,7 +86,7 @@ func TestAccEC2EIP_instance(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPInstanceConfig(), + Config: testAccEIPConfig_instance(), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -115,13 +115,13 @@ func TestAccEC2EIP_Instance_reassociate(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPInstanceReassociateConfig(rName), + Config: testAccEIPConfig_instanceReassociate(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "instance", instanceResourceName, "id"), ), }, { - Config: testAccEIPInstanceReassociateConfig(rName), + Config: testAccEIPConfig_instanceReassociate(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "instance", instanceResourceName, "id"), ), @@ -145,7 +145,7 @@ func TestAccEC2EIP_Instance_associatedUserPrivateIP(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPInstanceAssociatedConfig(rName), + Config: testAccEIPConfig_instanceAssociated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &one), testAccCheckEIPAttributes(&one), @@ -160,7 +160,7 @@ func TestAccEC2EIP_Instance_associatedUserPrivateIP(t *testing.T) { ImportStateVerifyIgnore: []string{"associate_with_private_ip"}, }, { - Config: testAccEIPInstanceAssociatedSwitchConfig(rName), + Config: testAccEIPConfig_instanceAssociatedSwitch(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &one), testAccCheckEIPAttributes(&one), @@ -183,7 +183,7 @@ func TestAccEC2EIP_Instance_notAssociated(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPInstanceAssociateNotAssociatedConfig(), + Config: testAccEIPConfig_instanceAssociateNotAssociated(), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -195,7 +195,7 @@ func TestAccEC2EIP_Instance_notAssociated(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEIPInstanceAssociateAssociatedConfig(), + Config: testAccEIPConfig_instanceAssociateAssociated(), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -246,7 +246,7 @@ func TestAccEC2EIP_networkInterface(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPNetworkInterfaceConfig(rName), + Config: testAccEIPConfig_networkInterface(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -278,7 +278,7 @@ func TestAccEC2EIP_NetworkInterface_twoEIPsOneInterface(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPMultiNetworkInterfaceConfig(rName), + Config: testAccEIPConfig_multiNetworkInterface(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &one), testAccCheckEIPAttributes(&one), @@ -456,7 +456,7 @@ func TestAccEC2EIP_PublicIPv4Pool_default(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPPublicIPv4PoolDefaultConfig, + Config: testAccEIPConfig_publicIPv4PoolDefault, Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -490,7 +490,7 @@ func TestAccEC2EIP_PublicIPv4Pool_custom(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPPublicIPv4PoolCustomConfig(poolName), + Config: testAccEIPConfig_publicIPv4PoolCustom(poolName), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -518,7 +518,7 @@ func TestAccEC2EIP_customerOwnedIPv4Pool(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPCustomerOwnedIPv4PoolConfig(), + Config: testAccEIPConfig_customerOwnedIPv4Pool(), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), resource.TestMatchResourceAttr(resourceName, "customer_owned_ipv4_pool", regexp.MustCompile(`^ipv4pool-coip-.+$`)), @@ -545,7 +545,7 @@ func TestAccEC2EIP_networkBorderGroup(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPNetworkBorderGroupConfig, + Config: testAccEIPConfig_networkBorderGroup, Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -574,7 +574,7 @@ func TestAccEC2EIP_carrierIP(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPCarrierIPConfig(rName), + Config: testAccEIPConfig_carrierIP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), resource.TestCheckResourceAttrSet(resourceName, "carrier_ip"), @@ -603,7 +603,7 @@ func TestAccEC2EIP_BYOIPAddress_default(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPConfig_BYOIPAddress_custom_default, + Config: testAccEIPConfig_byoipAddressCustomDefault, Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -632,7 +632,7 @@ func TestAccEC2EIP_BYOIPAddress_custom(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPConfig_BYOIPAddress_custom(address), + Config: testAccEIPConfig_byoipAddressCustom(address), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -666,7 +666,7 @@ func TestAccEC2EIP_BYOIPAddress_customWithPublicIPv4Pool(t *testing.T) { CheckDestroy: testAccCheckEIPDestroy, Steps: []resource.TestStep{ { - Config: testAccEIPConfig_BYOIPAddress_custom_with_PublicIPv4Pool(address, poolName), + Config: testAccEIPConfig_byoipAddressCustomPublicIPv4Pool(address, poolName), Check: resource.ComposeTestCheckFunc( testAccCheckEIPExists(resourceName, false, &conf), testAccCheckEIPAttributes(&conf), @@ -881,7 +881,7 @@ func testAccCheckEIPPublicDNSClassic(resourceName string) resource.TestCheckFunc } } -const testAccEIPConfig = ` +const testAccEIPConfig_basic = ` resource "aws_eip" "test" { vpc = true } @@ -915,13 +915,13 @@ resource "aws_eip" "test" { `, vpcConfig, rName)) } -const testAccEIPPublicIPv4PoolDefaultConfig = ` +const testAccEIPConfig_publicIPv4PoolDefault = ` resource "aws_eip" "test" { vpc = true } ` -func testAccEIPPublicIPv4PoolCustomConfig(poolName string) string { +func testAccEIPConfig_publicIPv4PoolCustom(poolName string) string { return fmt.Sprintf(` resource "aws_eip" "test" { vpc = true @@ -947,13 +947,13 @@ resource "aws_eip" "test" { `) } -const testAccEIPConfig_BYOIPAddress_custom_default = ` +const testAccEIPConfig_byoipAddressCustomDefault = ` resource "aws_eip" "test" { vpc = true } ` -func testAccEIPConfig_BYOIPAddress_custom(address string) string { +func testAccEIPConfig_byoipAddressCustom(address string) string { return fmt.Sprintf(` resource "aws_eip" "test" { vpc = true @@ -962,7 +962,7 @@ resource "aws_eip" "test" { `, address) } -func testAccEIPConfig_BYOIPAddress_custom_with_PublicIPv4Pool(address string, poolname string) string { +func testAccEIPConfig_byoipAddressCustomPublicIPv4Pool(address string, poolname string) string { return fmt.Sprintf(` resource "aws_eip" "test" { vpc = true @@ -972,9 +972,9 @@ resource "aws_eip" "test" { `, address, poolname) } -func testAccEIPInstanceConfig() string { +func testAccEIPConfig_instance() string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("aws_subnet.test.availability_zone", "t3.micro", "t2.micro"), acctest.ConfigAvailableAZsNoOptIn(), ` @@ -1005,9 +1005,9 @@ resource "aws_eip" "test" { `) } -func testAccEIPInstanceAssociatedConfig(rName string) string { +func testAccEIPConfig_instanceAssociated(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("aws_subnet.test.availability_zone", "t3.micro", "t2.micro"), fmt.Sprintf(` @@ -1074,9 +1074,9 @@ resource "aws_eip" "test" { `, rName)) } -func testAccEIPInstanceAssociatedSwitchConfig(rName string) string { +func testAccEIPConfig_instanceAssociatedSwitch(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" @@ -1141,7 +1141,7 @@ resource "aws_eip" "test" { `, rName)) } -func testAccEIPNetworkInterfaceConfig(rName string) string { +func testAccEIPConfig_networkInterface(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1179,7 +1179,7 @@ resource "aws_eip" "test" { `, rName)) } -func testAccEIPMultiNetworkInterfaceConfig(rName string) string { +func testAccEIPConfig_multiNetworkInterface(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1225,9 +1225,9 @@ resource "aws_eip" "test2" { `, rName)) } -func testAccEIPInstanceReassociateConfig(rName string) string { +func testAccEIPConfig_instanceReassociate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("aws_subnet.test.availability_zone", "t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_eip" "test" { @@ -1299,11 +1299,11 @@ resource "aws_route_table_association" "test" { `, rName)) } -func testAccEIPInstanceAssociateNotAssociatedConfig() string { +func testAccEIPConfig_instanceAssociateNotAssociated() string { return acctest.ConfigCompose( acctest.AvailableEC2InstanceTypeForAvailabilityZone("aws_subnet.test.availability_zone", "t3.micro", "t2.micro"), acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), ` + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" } @@ -1329,11 +1329,11 @@ resource "aws_eip" "test" { `) } -func testAccEIPInstanceAssociateAssociatedConfig() string { +func testAccEIPConfig_instanceAssociateAssociated() string { return acctest.ConfigCompose( acctest.AvailableEC2InstanceTypeForAvailabilityZone("aws_subnet.test.availability_zone", "t3.micro", "t2.micro"), acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), ` + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" } @@ -1361,7 +1361,7 @@ resource "aws_eip" "test" { `) } -func testAccEIPCustomerOwnedIPv4PoolConfig() string { +func testAccEIPConfig_customerOwnedIPv4Pool() string { return ` data "aws_ec2_coip_pools" "test" {} @@ -1372,7 +1372,7 @@ resource "aws_eip" "test" { ` } -const testAccEIPNetworkBorderGroupConfig = ` +const testAccEIPConfig_networkBorderGroup = ` data "aws_region" current {} resource "aws_eip" "test" { @@ -1381,7 +1381,7 @@ resource "aws_eip" "test" { } ` -func testAccEIPCarrierIPConfig(rName string) string { +func testAccEIPConfig_carrierIP(rName string) string { return acctest.ConfigCompose( testAccAvailableAZsWavelengthZonesDefaultExcludeConfig(), fmt.Sprintf(` diff --git a/internal/service/ec2/ec2_eips_data_source_test.go b/internal/service/ec2/ec2_eips_data_source_test.go index 9cfab5e60b2..8f915f41eb3 100644 --- a/internal/service/ec2/ec2_eips_data_source_test.go +++ b/internal/service/ec2/ec2_eips_data_source_test.go @@ -19,7 +19,7 @@ func TestAccEC2EIPsDataSource_vpcDomain(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPsVPCDomainDataSourceConfig(rName), + Config: testAccEIPsDataSourceConfig_vpcDomain(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue("data.aws_eips.all", "allocation_ids.#", "1"), resource.TestCheckResourceAttr("data.aws_eips.by_tags", "allocation_ids.#", "1"), @@ -39,7 +39,7 @@ func TestAccEC2EIPsDataSource_standardDomain(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEIPsStandardDomainDataSourceConfig(), + Config: testAccEIPsDataSourceConfig_standardDomain(), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue("data.aws_eips.all", "public_ips.#", "0"), ), @@ -48,7 +48,7 @@ func TestAccEC2EIPsDataSource_standardDomain(t *testing.T) { }) } -func testAccEIPsVPCDomainDataSourceConfig(rName string) string { +func testAccEIPsDataSourceConfig_vpcDomain(rName string) string { return fmt.Sprintf(` resource "aws_eip" "test1" { vpc = true @@ -89,7 +89,7 @@ data "aws_eips" "none" { `, rName) } -func testAccEIPsStandardDomainDataSourceConfig() string { +func testAccEIPsDataSourceConfig_standardDomain() string { return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), ` resource "aws_eip" "test" {} diff --git a/internal/service/ec2/ec2_fleet_test.go b/internal/service/ec2/ec2_fleet_test.go index ae60bcfa9cd..9175a5885c3 100644 --- a/internal/service/ec2/ec2_fleet_test.go +++ b/internal/service/ec2/ec2_fleet_test.go @@ -31,7 +31,7 @@ func TestAccEC2Fleet_basic(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_Basic(rName), + Config: testAccFleetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`fleet/.+`)), @@ -80,7 +80,7 @@ func TestAccEC2Fleet_disappears(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_Basic(rName), + Config: testAccFleetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceFleet(), resourceName), @@ -103,7 +103,7 @@ func TestAccEC2Fleet_tags(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfigTags1(rName, "key1", "value1"), + Config: testAccFleetConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -117,7 +117,7 @@ func TestAccEC2Fleet_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccFleetConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -126,7 +126,7 @@ func TestAccEC2Fleet_tags(t *testing.T) { ), }, { - Config: testAccFleetConfigTags1(rName, "key2", "value2"), + Config: testAccFleetConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -149,7 +149,7 @@ func TestAccEC2Fleet_excessCapacityTerminationPolicy(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_ExcessCapacityTerminationPolicy(rName, "no-termination"), + Config: testAccFleetConfig_excessCapacityTerminationPolicy(rName, "no-termination"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "excess_capacity_termination_policy", "no-termination"), @@ -162,7 +162,7 @@ func TestAccEC2Fleet_excessCapacityTerminationPolicy(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_ExcessCapacityTerminationPolicy(rName, "termination"), + Config: testAccFleetConfig_excessCapacityTerminationPolicy(rName, "termination"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -187,7 +187,7 @@ func TestAccEC2Fleet_LaunchTemplateLaunchTemplateSpecification_launchTemplateID( CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_LaunchTemplateSpecification_LaunchTemplateID(rName, launchTemplateResourceName1), + Config: testAccFleetConfig_launchTemplateID(rName, launchTemplateResourceName1), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -203,7 +203,7 @@ func TestAccEC2Fleet_LaunchTemplateLaunchTemplateSpecification_launchTemplateID( ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_LaunchTemplateSpecification_LaunchTemplateID(rName, launchTemplateResourceName2), + Config: testAccFleetConfig_launchTemplateID(rName, launchTemplateResourceName2), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -231,7 +231,7 @@ func TestAccEC2Fleet_LaunchTemplateLaunchTemplateSpecification_launchTemplateNam CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_LaunchTemplateSpecification_LaunchTemplateName(rName, launchTemplateResourceName1), + Config: testAccFleetConfig_launchTemplateName(rName, launchTemplateResourceName1), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -247,7 +247,7 @@ func TestAccEC2Fleet_LaunchTemplateLaunchTemplateSpecification_launchTemplateNam ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_LaunchTemplateSpecification_LaunchTemplateName(rName, launchTemplateResourceName2), + Config: testAccFleetConfig_launchTemplateName(rName, launchTemplateResourceName2), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -275,7 +275,7 @@ func TestAccEC2Fleet_LaunchTemplateLaunchTemplateSpecification_version(t *testin CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_LaunchTemplateSpecification_Version(rName, "t3.micro"), + Config: testAccFleetConfig_launchTemplateVersion(rName, "t3.micro"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(launchTemplateResourceName, &launchTemplate), resource.TestCheckResourceAttr(launchTemplateResourceName, "instance_type", "t3.micro"), @@ -294,7 +294,7 @@ func TestAccEC2Fleet_LaunchTemplateLaunchTemplateSpecification_version(t *testin ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_LaunchTemplateSpecification_Version(rName, "t3.small"), + Config: testAccFleetConfig_launchTemplateVersion(rName, "t3.small"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(launchTemplateResourceName, &launchTemplate), resource.TestCheckResourceAttr(launchTemplateResourceName, "instance_type", "t3.small"), @@ -324,7 +324,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_availabilityZone(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_AvailabilityZone(rName, 0), + Config: testAccFleetConfig_launchTemplateOverrideAvailabilityZone(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -339,7 +339,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_availabilityZone(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_AvailabilityZone(rName, 1), + Config: testAccFleetConfig_launchTemplateOverrideAvailabilityZone(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -362,7 +362,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_memoryMiBAndVCP CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `memory_mib { min = 500 } @@ -388,7 +388,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_memoryMiBAndVCP ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `memory_mib { min = 500 max = 24000 @@ -432,7 +432,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorCoun CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_count { min = 1 } @@ -459,7 +459,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorCoun ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_count { min = 1 max = 4 @@ -488,7 +488,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorCoun ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_count { max = 0 } @@ -529,7 +529,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorManu CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_manufacturers = ["amd"] memory_mib { min = 500 @@ -554,7 +554,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorManu ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_manufacturers = ["amazon-web-services", "amd", "nvidia", "xilinx"] memory_mib { min = 500 @@ -596,7 +596,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorName CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_names = ["a100"] memory_mib { min = 500 @@ -621,7 +621,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorName ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_names = ["a100", "v100", "k80", "t4", "m60", "radeon-pro-v520", "vu9p"] memory_mib { min = 500 @@ -666,7 +666,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorTota CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_total_memory_mib { min = 1000 } @@ -693,7 +693,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorTota ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_total_memory_mib { max = 24000 } @@ -720,7 +720,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorTota ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_total_memory_mib { min = 1000 max = 24000 @@ -763,7 +763,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorType CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_types = ["fpga"] memory_mib { min = 500 @@ -788,7 +788,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_acceleratorType ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `accelerator_types = ["fpga", "gpu", "inference"] memory_mib { min = 500 @@ -829,7 +829,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_bareMetal(t *te CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `bare_metal = "excluded" memory_mib { min = 500 @@ -853,7 +853,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_bareMetal(t *te ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `bare_metal = "included" memory_mib { min = 500 @@ -877,7 +877,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_bareMetal(t *te ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `bare_metal = "required" memory_mib { min = 500 @@ -915,7 +915,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_baselineEBSBand CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `baseline_ebs_bandwidth_mbps { min = 10 } @@ -942,7 +942,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_baselineEBSBand ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `baseline_ebs_bandwidth_mbps { max = 20000 } @@ -969,7 +969,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_baselineEBSBand ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `baseline_ebs_bandwidth_mbps { min = 10 max = 20000 @@ -1012,7 +1012,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_burstablePerfor CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `burstable_performance = "excluded" memory_mib { min = 500 @@ -1036,7 +1036,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_burstablePerfor ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `burstable_performance = "included" memory_mib { min = 1000 @@ -1060,7 +1060,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_burstablePerfor ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `burstable_performance = "required" memory_mib { min = 1000 @@ -1098,7 +1098,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_cpuManufacturer CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `cpu_manufacturers = ["amd"] memory_mib { min = 500 @@ -1123,7 +1123,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_cpuManufacturer ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `cpu_manufacturers = ["amazon-web-services", "amd", "intel"] memory_mib { min = 500 @@ -1164,7 +1164,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_excludedInstanc CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `excluded_instance_types = ["t2.nano"] memory_mib { min = 500 @@ -1189,7 +1189,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_excludedInstanc ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `excluded_instance_types = ["t2.nano", "t3*", "t4g.*"] memory_mib { min = 500 @@ -1230,7 +1230,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_instanceGenerat CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `instance_generations = ["current"] memory_mib { min = 500 @@ -1255,7 +1255,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_instanceGenerat ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `instance_generations = ["current", "previous"] memory_mib { min = 500 @@ -1295,7 +1295,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_localStorage(t CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `local_storage = "excluded" memory_mib { min = 500 @@ -1319,7 +1319,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_localStorage(t ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `local_storage = "included" memory_mib { min = 500 @@ -1343,7 +1343,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_localStorage(t ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `local_storage = "required" memory_mib { min = 500 @@ -1381,7 +1381,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_localStorageTyp CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `local_storage_types = ["hdd"] memory_mib { min = 500 @@ -1406,7 +1406,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_localStorageTyp ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `local_storage_types = ["hdd", "ssd"] memory_mib { min = 500 @@ -1446,7 +1446,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_memoryGiBPerVCP CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `memory_gib_per_vcpu { min = 0.5 } @@ -1473,7 +1473,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_memoryGiBPerVCP ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `memory_gib_per_vcpu { max = 9.5 } @@ -1500,7 +1500,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_memoryGiBPerVCP ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `memory_gib_per_vcpu { min = 0.5 max = 9.5 @@ -1543,7 +1543,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_networkInterfac CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `network_interface_count { min = 1 } @@ -1570,7 +1570,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_networkInterfac ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `network_interface_count { max = 10 } @@ -1597,7 +1597,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_networkInterfac ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `network_interface_count { min = 1 max = 10 @@ -1640,7 +1640,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_onDemandMaxPric CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `on_demand_max_price_percentage_over_lowest_price = 50 memory_mib { min = 500 @@ -1678,7 +1678,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_requireHibernat CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `require_hibernate_support = false memory_mib { min = 500 @@ -1702,7 +1702,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_requireHibernat ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `require_hibernate_support = true memory_mib { min = 500 @@ -1740,7 +1740,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_spotMaxPricePer CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `spot_max_price_percentage_over_lowest_price = 75 memory_mib { min = 500 @@ -1778,7 +1778,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_totalLocalStora CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `total_local_storage_gb { min = 0.5 } @@ -1805,7 +1805,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_totalLocalStora ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `total_local_storage_gb { max = 20.5 } @@ -1832,7 +1832,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceRequirements_totalLocalStora ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), + Config: testAccFleetConfig_launchTemplateOverrideInstanceRequirements(sdkacctest.RandomWithPrefix(acctest.ResourcePrefix), `total_local_storage_gb { min = 0.5 max = 20.5 @@ -1876,7 +1876,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceType(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceType(rName, "t3.small"), + Config: testAccFleetConfig_launchTemplateOverrideInstanceType(rName, "t3.small"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -1891,7 +1891,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_instanceType(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_InstanceType(rName, "t3.medium"), + Config: testAccFleetConfig_launchTemplateOverrideInstanceType(rName, "t3.medium"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -1918,7 +1918,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_maxPrice(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_MaxPrice(rName, "1.01"), + Config: testAccFleetConfig_launchTemplateOverrideMaxPrice(rName, "1.01"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -1933,7 +1933,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_maxPrice(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_MaxPrice(rName, "1.02"), + Config: testAccFleetConfig_launchTemplateOverrideMaxPrice(rName, "1.02"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -1958,7 +1958,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_priority(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_Priority(rName, 1), + Config: testAccFleetConfig_launchTemplateOverridePriority(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -1973,7 +1973,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_priority(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_Priority(rName, 2), + Config: testAccFleetConfig_launchTemplateOverridePriority(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -1998,7 +1998,7 @@ func TestAccEC2Fleet_LaunchTemplateOverridePriority_multiple(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_Priority_Multiple(rName, 1, 2), + Config: testAccFleetConfig_launchTemplateOverridePriorityMultiple(rName, 1, 2), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -2014,7 +2014,7 @@ func TestAccEC2Fleet_LaunchTemplateOverridePriority_multiple(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_Priority_Multiple(rName, 2, 1), + Config: testAccFleetConfig_launchTemplateOverridePriorityMultiple(rName, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -2042,7 +2042,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_subnetID(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_SubnetID(rName, 0), + Config: testAccFleetConfig_launchTemplateOverrideSubnetID(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -2057,7 +2057,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_subnetID(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_SubnetID(rName, 1), + Config: testAccFleetConfig_launchTemplateOverrideSubnetID(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -2082,7 +2082,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_weightedCapacity(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_WeightedCapacity(rName, 1), + Config: testAccFleetConfig_launchTemplateOverrideWeightedCapacity(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -2097,7 +2097,7 @@ func TestAccEC2Fleet_LaunchTemplateOverride_weightedCapacity(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_WeightedCapacity(rName, 2), + Config: testAccFleetConfig_launchTemplateOverrideWeightedCapacity(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -2122,7 +2122,7 @@ func TestAccEC2Fleet_LaunchTemplateOverrideWeightedCapacity_multiple(t *testing. CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_WeightedCapacity_Multiple(rName, 1, 1), + Config: testAccFleetConfig_launchTemplateOverrideWeightedCapacityMultiple(rName, 1, 1), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "launch_template_config.#", "1"), @@ -2138,7 +2138,7 @@ func TestAccEC2Fleet_LaunchTemplateOverrideWeightedCapacity_multiple(t *testing. ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_LaunchTemplateConfig_Override_WeightedCapacity_Multiple(rName, 1, 2), + Config: testAccFleetConfig_launchTemplateOverrideWeightedCapacityMultiple(rName, 1, 2), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -2164,7 +2164,7 @@ func TestAccEC2Fleet_OnDemandOptions_allocationStrategy(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_OnDemandOptions_AllocationStrategy(rName, "prioritized"), + Config: testAccFleetConfig_onDemandOptionsAllocationStrategy(rName, "prioritized"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "on_demand_options.#", "1"), @@ -2178,7 +2178,7 @@ func TestAccEC2Fleet_OnDemandOptions_allocationStrategy(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_OnDemandOptions_AllocationStrategy(rName, "lowestPrice"), + Config: testAccFleetConfig_onDemandOptionsAllocationStrategy(rName, "lowestPrice"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetRecreated(&fleet1, &fleet2), @@ -2202,7 +2202,7 @@ func TestAccEC2Fleet_replaceUnhealthyInstances(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_ReplaceUnhealthyInstances(rName, true), + Config: testAccFleetConfig_replaceUnhealthyInstances(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "replace_unhealthy_instances", "true"), @@ -2215,7 +2215,7 @@ func TestAccEC2Fleet_replaceUnhealthyInstances(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_ReplaceUnhealthyInstances(rName, false), + Config: testAccFleetConfig_replaceUnhealthyInstances(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetRecreated(&fleet1, &fleet2), @@ -2238,7 +2238,7 @@ func TestAccEC2Fleet_SpotOptions_allocationStrategy(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_SpotOptions_AllocationStrategy(rName, "diversified"), + Config: testAccFleetConfig_spotOptionsAllocationStrategy(rName, "diversified"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "spot_options.#", "1"), @@ -2252,7 +2252,7 @@ func TestAccEC2Fleet_SpotOptions_allocationStrategy(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_SpotOptions_AllocationStrategy(rName, "lowestPrice"), + Config: testAccFleetConfig_spotOptionsAllocationStrategy(rName, "lowestPrice"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetRecreated(&fleet1, &fleet2), @@ -2276,7 +2276,7 @@ func TestAccEC2Fleet_SpotOptions_capacityRebalance(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_SpotOptions_CapacityRebalance(rName, "diversified"), + Config: testAccFleetConfig_spotOptionsCapacityRebalance(rName, "diversified"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "spot_options.#", "1"), @@ -2304,7 +2304,7 @@ func TestAccEC2Fleet_capacityRebalanceInvalidType(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfigWithInvalidTypeForCapacityRebalance(rName), + Config: testAccFleetConfig_invalidTypeForCapacityRebalance(rName), ExpectError: regexp.MustCompile(`Capacity Rebalance maintenance strategies can only be specified for fleets of type maintain`), }, }, @@ -2323,7 +2323,7 @@ func TestAccEC2Fleet_SpotOptions_instanceInterruptionBehavior(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_SpotOptions_InstanceInterruptionBehavior(rName, "stop"), + Config: testAccFleetConfig_spotOptionsInstanceInterruptionBehavior(rName, "stop"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "spot_options.#", "1"), @@ -2337,7 +2337,7 @@ func TestAccEC2Fleet_SpotOptions_instanceInterruptionBehavior(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_SpotOptions_InstanceInterruptionBehavior(rName, "terminate"), + Config: testAccFleetConfig_spotOptionsInstanceInterruptionBehavior(rName, "terminate"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetRecreated(&fleet1, &fleet2), @@ -2361,7 +2361,7 @@ func TestAccEC2Fleet_SpotOptions_instancePoolsToUseCount(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_SpotOptions_InstancePoolsToUseCount(rName, 2), + Config: testAccFleetConfig_spotOptionsInstancePoolsToUseCount(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "spot_options.#", "1"), @@ -2375,7 +2375,7 @@ func TestAccEC2Fleet_SpotOptions_instancePoolsToUseCount(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_SpotOptions_InstancePoolsToUseCount(rName, 3), + Config: testAccFleetConfig_spotOptionsInstancePoolsToUseCount(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetRecreated(&fleet1, &fleet2), @@ -2399,7 +2399,7 @@ func TestAccEC2Fleet_TargetCapacitySpecification_defaultTargetCapacityType(t *te CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_TargetCapacitySpecification_DefaultTargetCapacityType(rName, "on-demand"), + Config: testAccFleetConfig_targetCapacitySpecificationDefaultTargetCapacityType(rName, "on-demand"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "target_capacity_specification.#", "1"), @@ -2407,7 +2407,7 @@ func TestAccEC2Fleet_TargetCapacitySpecification_defaultTargetCapacityType(t *te ), }, { - Config: testAccFleetConfig_TargetCapacitySpecification_DefaultTargetCapacityType(rName, "spot"), + Config: testAccFleetConfig_targetCapacitySpecificationDefaultTargetCapacityType(rName, "spot"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetRecreated(&fleet1, &fleet2), @@ -2431,7 +2431,7 @@ func TestAccEC2Fleet_TargetCapacitySpecificationDefaultTargetCapacityType_onDema CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_TargetCapacitySpecification_DefaultTargetCapacityType(rName, "on-demand"), + Config: testAccFleetConfig_targetCapacitySpecificationDefaultTargetCapacityType(rName, "on-demand"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "target_capacity_specification.#", "1"), @@ -2460,7 +2460,7 @@ func TestAccEC2Fleet_TargetCapacitySpecificationDefaultTargetCapacityType_spot(t CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_TargetCapacitySpecification_DefaultTargetCapacityType(rName, "spot"), + Config: testAccFleetConfig_targetCapacitySpecificationDefaultTargetCapacityType(rName, "spot"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "target_capacity_specification.#", "1"), @@ -2489,7 +2489,7 @@ func TestAccEC2Fleet_TargetCapacitySpecification_totalTargetCapacity(t *testing. CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_TargetCapacitySpecification_TotalTargetCapacity(rName, 1), + Config: testAccFleetConfig_targetCapacitySpecificationTotalTargetCapacity(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "target_capacity_specification.#", "1"), @@ -2503,7 +2503,7 @@ func TestAccEC2Fleet_TargetCapacitySpecification_totalTargetCapacity(t *testing. ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_TargetCapacitySpecification_TotalTargetCapacity(rName, 2), + Config: testAccFleetConfig_targetCapacitySpecificationTotalTargetCapacity(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetNotRecreated(&fleet1, &fleet2), @@ -2527,7 +2527,7 @@ func TestAccEC2Fleet_terminateInstancesWithExpiration(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_TerminateInstancesWithExpiration(rName, true), + Config: testAccFleetConfig_terminateInstancesExpiration(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "terminate_instances_with_expiration", "true"), @@ -2540,7 +2540,7 @@ func TestAccEC2Fleet_terminateInstancesWithExpiration(t *testing.T) { ImportStateVerifyIgnore: []string{"terminate_instances"}, }, { - Config: testAccFleetConfig_TerminateInstancesWithExpiration(rName, false), + Config: testAccFleetConfig_terminateInstancesExpiration(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet2), testAccCheckFleetRecreated(&fleet1, &fleet2), @@ -2563,7 +2563,7 @@ func TestAccEC2Fleet_type(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetConfig_Type(rName, "maintain"), + Config: testAccFleetConfig_type(rName, "maintain"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &fleet1), resource.TestCheckResourceAttr(resourceName, "type", "maintain"), @@ -2577,7 +2577,7 @@ func TestAccEC2Fleet_type(t *testing.T) { }, // This configuration will fulfill immediately, skip until ValidFrom is implemented // { - // Config: testAccFleetConfig_Type(rName, "request"), + // Config: testAccFleetConfig_type(rName, "request"), // Check: resource.ComposeTestCheckFunc( // testAccCheckFleetExists(resourceName, &fleet2), // testAccCheckFleetRecreated(&fleet1, &fleet2), @@ -2747,7 +2747,7 @@ func testAccPreCheckFleet(t *testing.T) { } func testAccFleetConfig_BaseLaunchTemplate(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_template" "test" { image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t3.micro" @@ -2756,7 +2756,7 @@ resource "aws_launch_template" "test" { `, rName)) } -func testAccFleetConfig_Basic(rName string) string { +func testAccFleetConfig_basic(rName string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), ` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -2776,7 +2776,7 @@ resource "aws_ec2_fleet" "test" { func testAccFleetConfig_multipleNetworkInterfaces(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2892,7 +2892,7 @@ resource "aws_ec2_fleet" "test" { `, rName)) } -func testAccFleetConfig_ExcessCapacityTerminationPolicy(rName, excessCapacityTerminationPolicy string) string { +func testAccFleetConfig_excessCapacityTerminationPolicy(rName, excessCapacityTerminationPolicy string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { excess_capacity_termination_policy = %[2]q @@ -2916,8 +2916,8 @@ resource "aws_ec2_fleet" "test" { `, rName, excessCapacityTerminationPolicy)) } -func testAccFleetConfig_LaunchTemplateConfig_LaunchTemplateSpecification_LaunchTemplateID(rName, launchTemplateResourceName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccFleetConfig_launchTemplateID(rName, launchTemplateResourceName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_template" "test1" { image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t3.micro" @@ -2950,8 +2950,8 @@ resource "aws_ec2_fleet" "test" { `, rName, launchTemplateResourceName)) } -func testAccFleetConfig_LaunchTemplateConfig_LaunchTemplateSpecification_LaunchTemplateName(rName, launchTemplateResourceName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccFleetConfig_launchTemplateName(rName, launchTemplateResourceName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_template" "test1" { image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t3.micro" @@ -2984,8 +2984,8 @@ resource "aws_ec2_fleet" "test" { `, rName, launchTemplateResourceName)) } -func testAccFleetConfig_LaunchTemplateConfig_LaunchTemplateSpecification_Version(rName, instanceType string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccFleetConfig_launchTemplateVersion(rName, instanceType string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_launch_template" "test" { image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = %[2]q @@ -3012,7 +3012,7 @@ resource "aws_ec2_fleet" "test" { `, rName, instanceType)) } -func testAccFleetConfig_LaunchTemplateConfig_Override_AvailabilityZone(rName string, availabilityZoneIndex int) string { +func testAccFleetConfig_launchTemplateOverrideAvailabilityZone(rName string, availabilityZoneIndex int) string { return acctest.ConfigCompose( testAccFleetConfig_BaseLaunchTemplate(rName), acctest.ConfigAvailableAZsNoOptIn(), @@ -3041,7 +3041,7 @@ resource "aws_ec2_fleet" "test" { `, rName, availabilityZoneIndex)) } -func testAccFleetConfig_LaunchTemplateConfig_Override_InstanceRequirements(rName, instanceRequirements string) string { +func testAccFleetConfig_launchTemplateOverrideInstanceRequirements(rName, instanceRequirements string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3069,7 +3069,7 @@ resource "aws_ec2_fleet" "test" { `, rName, instanceRequirements)) } -func testAccFleetConfig_LaunchTemplateConfig_Override_InstanceType(rName, instanceType string) string { +func testAccFleetConfig_launchTemplateOverrideInstanceType(rName, instanceType string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3095,7 +3095,7 @@ resource "aws_ec2_fleet" "test" { `, rName, instanceType)) } -func testAccFleetConfig_LaunchTemplateConfig_Override_MaxPrice(rName, maxPrice string) string { +func testAccFleetConfig_launchTemplateOverrideMaxPrice(rName, maxPrice string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3121,7 +3121,7 @@ resource "aws_ec2_fleet" "test" { `, rName, maxPrice)) } -func testAccFleetConfig_LaunchTemplateConfig_Override_Priority(rName string, priority int) string { +func testAccFleetConfig_launchTemplateOverridePriority(rName string, priority int) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3147,7 +3147,7 @@ resource "aws_ec2_fleet" "test" { `, rName, priority)) } -func testAccFleetConfig_LaunchTemplateConfig_Override_Priority_Multiple(rName string, priority1, priority2 int) string { +func testAccFleetConfig_launchTemplateOverridePriorityMultiple(rName string, priority1, priority2 int) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3179,7 +3179,7 @@ resource "aws_ec2_fleet" "test" { `, rName, priority1, priority2)) } -func testAccFleetConfig_LaunchTemplateConfig_Override_SubnetID(rName string, subnetIndex int) string { +func testAccFleetConfig_launchTemplateOverrideSubnetID(rName string, subnetIndex int) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3224,7 +3224,7 @@ resource "aws_ec2_fleet" "test" { `, rName, subnetIndex)) } -func testAccFleetConfig_LaunchTemplateConfig_Override_WeightedCapacity(rName string, weightedCapacity int) string { +func testAccFleetConfig_launchTemplateOverrideWeightedCapacity(rName string, weightedCapacity int) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3250,7 +3250,7 @@ resource "aws_ec2_fleet" "test" { `, rName, weightedCapacity)) } -func testAccFleetConfig_LaunchTemplateConfig_Override_WeightedCapacity_Multiple(rName string, weightedCapacity1, weightedCapacity2 int) string { +func testAccFleetConfig_launchTemplateOverrideWeightedCapacityMultiple(rName string, weightedCapacity1, weightedCapacity2 int) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3282,7 +3282,7 @@ resource "aws_ec2_fleet" "test" { `, rName, weightedCapacity1, weightedCapacity2)) } -func testAccFleetConfig_OnDemandOptions_AllocationStrategy(rName, allocationStrategy string) string { +func testAccFleetConfig_onDemandOptionsAllocationStrategy(rName, allocationStrategy string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3308,7 +3308,7 @@ resource "aws_ec2_fleet" "test" { `, rName, allocationStrategy)) } -func testAccFleetConfig_ReplaceUnhealthyInstances(rName string, replaceUnhealthyInstances bool) string { +func testAccFleetConfig_replaceUnhealthyInstances(rName string, replaceUnhealthyInstances bool) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { replace_unhealthy_instances = %[2]t @@ -3332,7 +3332,7 @@ resource "aws_ec2_fleet" "test" { `, rName, replaceUnhealthyInstances)) } -func testAccFleetConfig_SpotOptions_AllocationStrategy(rName, allocationStrategy string) string { +func testAccFleetConfig_spotOptionsAllocationStrategy(rName, allocationStrategy string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3358,7 +3358,7 @@ resource "aws_ec2_fleet" "test" { `, rName, allocationStrategy)) } -func testAccFleetConfig_SpotOptions_CapacityRebalance(rName, allocationStrategy string) string { +func testAccFleetConfig_spotOptionsCapacityRebalance(rName, allocationStrategy string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3389,7 +3389,7 @@ resource "aws_ec2_fleet" "test" { `, rName, allocationStrategy)) } -func testAccFleetConfigWithInvalidTypeForCapacityRebalance(rName string) string { +func testAccFleetConfig_invalidTypeForCapacityRebalance(rName string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { type = "request" @@ -3422,7 +3422,7 @@ resource "aws_ec2_fleet" "test" { `, rName)) } -func testAccFleetConfig_SpotOptions_InstanceInterruptionBehavior(rName, instanceInterruptionBehavior string) string { +func testAccFleetConfig_spotOptionsInstanceInterruptionBehavior(rName, instanceInterruptionBehavior string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3448,7 +3448,7 @@ resource "aws_ec2_fleet" "test" { `, rName, instanceInterruptionBehavior)) } -func testAccFleetConfig_SpotOptions_InstancePoolsToUseCount(rName string, instancePoolsToUseCount int) string { +func testAccFleetConfig_spotOptionsInstancePoolsToUseCount(rName string, instancePoolsToUseCount int) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3474,7 +3474,7 @@ resource "aws_ec2_fleet" "test" { `, rName, instancePoolsToUseCount)) } -func testAccFleetConfigTags1(rName, key1, value1 string) string { +func testAccFleetConfig_tags1(rName, key1, value1 string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3496,7 +3496,7 @@ resource "aws_ec2_fleet" "test" { `, key1, value1)) } -func testAccFleetConfigTags2(rName, key1, value1, key2, value2 string) string { +func testAccFleetConfig_tags2(rName, key1, value1, key2, value2 string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3519,7 +3519,7 @@ resource "aws_ec2_fleet" "test" { `, key1, value1, key2, value2)) } -func testAccFleetConfig_TargetCapacitySpecification_DefaultTargetCapacityType(rName, defaultTargetCapacityType string) string { +func testAccFleetConfig_targetCapacitySpecificationDefaultTargetCapacityType(rName, defaultTargetCapacityType string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { launch_template_config { @@ -3541,7 +3541,7 @@ resource "aws_ec2_fleet" "test" { `, rName, defaultTargetCapacityType)) } -func testAccFleetConfig_TargetCapacitySpecification_TotalTargetCapacity(rName string, totalTargetCapacity int) string { +func testAccFleetConfig_targetCapacitySpecificationTotalTargetCapacity(rName string, totalTargetCapacity int) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { terminate_instances = true @@ -3565,7 +3565,7 @@ resource "aws_ec2_fleet" "test" { `, rName, totalTargetCapacity)) } -func testAccFleetConfig_TerminateInstancesWithExpiration(rName string, terminateInstancesWithExpiration bool) string { +func testAccFleetConfig_terminateInstancesExpiration(rName string, terminateInstancesWithExpiration bool) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { terminate_instances_with_expiration = %[2]t @@ -3589,7 +3589,7 @@ resource "aws_ec2_fleet" "test" { `, rName, terminateInstancesWithExpiration)) } -func testAccFleetConfig_Type(rName, fleetType string) string { +func testAccFleetConfig_type(rName, fleetType string) string { return acctest.ConfigCompose(testAccFleetConfig_BaseLaunchTemplate(rName), fmt.Sprintf(` resource "aws_ec2_fleet" "test" { type = %[2]q diff --git a/internal/service/ec2/ec2_host.go b/internal/service/ec2/ec2_host.go index ff43b9b798b..6c44575b437 100644 --- a/internal/service/ec2/ec2_host.go +++ b/internal/service/ec2/ec2_host.go @@ -61,6 +61,11 @@ func ResourceHost() *schema.Resource { Optional: true, ExactlyOneOf: []string{"instance_family", "instance_type"}, }, + "outpost_arn": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, "owner_id": { Type: schema.TypeString, Computed: true, @@ -91,6 +96,10 @@ func resourceHostCreate(d *schema.ResourceData, meta interface{}) error { input.InstanceType = aws.String(v.(string)) } + if v, ok := d.GetOk("outpost_arn"); ok { + input.OutpostArn = aws.String(v.(string)) + } + if len(tags) > 0 { input.TagSpecifications = tagSpecificationsFromKeyValueTags(tags, ec2.ResourceTypeDedicatedHost) } @@ -141,6 +150,7 @@ func resourceHostRead(d *schema.ResourceData, meta interface{}) error { d.Set("host_recovery", host.HostRecovery) d.Set("instance_family", host.HostProperties.InstanceFamily) d.Set("instance_type", host.HostProperties.InstanceType) + d.Set("outpost_arn", host.OutpostArn) d.Set("owner_id", host.OwnerId) tags := KeyValueTags(host.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) diff --git a/internal/service/ec2/ec2_host_data_source.go b/internal/service/ec2/ec2_host_data_source.go index 73495a061c3..da5653c23a4 100644 --- a/internal/service/ec2/ec2_host_data_source.go +++ b/internal/service/ec2/ec2_host_data_source.go @@ -51,6 +51,10 @@ func DataSourceHost() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "outpost_arn": { + Type: schema.TypeString, + Computed: true, + }, "owner_id": { Type: schema.TypeString, Computed: true, @@ -95,6 +99,7 @@ func dataSourceHostRead(d *schema.ResourceData, meta interface{}) error { d.Set("host_recovery", host.HostRecovery) d.Set("instance_family", host.HostProperties.InstanceFamily) d.Set("instance_type", host.HostProperties.InstanceType) + d.Set("outpost_arn", host.OutpostArn) d.Set("owner_id", host.OwnerId) d.Set("sockets", host.HostProperties.Sockets) d.Set("total_vcpus", host.HostProperties.TotalVCpus) diff --git a/internal/service/ec2/ec2_host_data_source_test.go b/internal/service/ec2/ec2_host_data_source_test.go index 3a0abc3c11b..a231d7cce1d 100644 --- a/internal/service/ec2/ec2_host_data_source_test.go +++ b/internal/service/ec2/ec2_host_data_source_test.go @@ -21,7 +21,7 @@ func TestAccEC2HostDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccHostDataSourceConfig(rName), + Config: testAccHostDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "auto_placement", resourceName, "auto_placement"), @@ -31,6 +31,7 @@ func TestAccEC2HostDataSource_basic(t *testing.T) { resource.TestCheckResourceAttrPair(dataSourceName, "host_recovery", resourceName, "host_recovery"), resource.TestCheckResourceAttrPair(dataSourceName, "instance_family", resourceName, "instance_family"), resource.TestCheckResourceAttrPair(dataSourceName, "instance_type", resourceName, "instance_type"), + resource.TestCheckResourceAttrPair(dataSourceName, "outpost_arn", resourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(dataSourceName, "owner_id", resourceName, "owner_id"), resource.TestCheckResourceAttrSet(dataSourceName, "sockets"), resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"), @@ -52,7 +53,7 @@ func TestAccEC2HostDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccHostFilterDataSourceConfig(rName), + Config: testAccHostDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "auto_placement", resourceName, "auto_placement"), @@ -62,6 +63,7 @@ func TestAccEC2HostDataSource_filter(t *testing.T) { resource.TestCheckResourceAttrPair(dataSourceName, "host_recovery", resourceName, "host_recovery"), resource.TestCheckResourceAttrPair(dataSourceName, "instance_family", resourceName, "instance_family"), resource.TestCheckResourceAttrPair(dataSourceName, "instance_type", resourceName, "instance_type"), + resource.TestCheckResourceAttrPair(dataSourceName, "outpost_arn", resourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(dataSourceName, "owner_id", resourceName, "owner_id"), resource.TestCheckResourceAttrSet(dataSourceName, "sockets"), resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"), @@ -72,7 +74,7 @@ func TestAccEC2HostDataSource_filter(t *testing.T) { }) } -func testAccHostDataSourceConfig(rName string) string { +func testAccHostDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ec2_host" "test" { availability_zone = data.aws_availability_zones.available.names[0] @@ -89,7 +91,7 @@ data "aws_ec2_host" "test" { `, rName)) } -func testAccHostFilterDataSourceConfig(rName string) string { +func testAccHostDataSourceConfig_filter(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ec2_host" "test" { availability_zone = data.aws_availability_zones.available.names[0] diff --git a/internal/service/ec2/ec2_host_test.go b/internal/service/ec2/ec2_host_test.go index b34e7abab28..b2e642f0328 100644 --- a/internal/service/ec2/ec2_host_test.go +++ b/internal/service/ec2/ec2_host_test.go @@ -26,7 +26,7 @@ func TestAccEC2Host_basic(t *testing.T) { CheckDestroy: testAccCheckHostDestroy, Steps: []resource.TestStep{ { - Config: testAccHostConfig(), + Config: testAccHostConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckHostExists(resourceName, &host), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`dedicated-host/.+`)), @@ -34,6 +34,7 @@ func TestAccEC2Host_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "host_recovery", "off"), resource.TestCheckResourceAttr(resourceName, "instance_family", ""), resource.TestCheckResourceAttr(resourceName, "instance_type", "a1.large"), + resource.TestCheckResourceAttr(resourceName, "outpost_arn", ""), acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), @@ -58,7 +59,7 @@ func TestAccEC2Host_disappears(t *testing.T) { CheckDestroy: testAccCheckHostDestroy, Steps: []resource.TestStep{ { - Config: testAccHostConfig(), + Config: testAccHostConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckHostExists(resourceName, &host), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceHost(), resourceName), @@ -81,7 +82,7 @@ func TestAccEC2Host_instanceFamily(t *testing.T) { CheckDestroy: testAccCheckHostDestroy, Steps: []resource.TestStep{ { - Config: testAccHostInstanceFamilyConfig(rName), + Config: testAccHostConfig_instanceFamily(rName), Check: resource.ComposeTestCheckFunc( testAccCheckHostExists(resourceName, &host), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`dedicated-host/.+`)), @@ -100,7 +101,7 @@ func TestAccEC2Host_instanceFamily(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccHostInstanceTypeConfig(rName), + Config: testAccHostConfig_instanceType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckHostExists(resourceName, &host), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`dedicated-host/.+`)), @@ -128,7 +129,7 @@ func TestAccEC2Host_tags(t *testing.T) { CheckDestroy: testAccCheckHostDestroy, Steps: []resource.TestStep{ { - Config: testAccHostTags1Config("key1", "value1"), + Config: testAccHostConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckHostExists(resourceName, &host), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -141,7 +142,7 @@ func TestAccEC2Host_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccHostTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccHostConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckHostExists(resourceName, &host), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -150,7 +151,7 @@ func TestAccEC2Host_tags(t *testing.T) { ), }, { - Config: testAccHostTags1Config("key2", "value2"), + Config: testAccHostConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckHostExists(resourceName, &host), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -161,6 +162,34 @@ func TestAccEC2Host_tags(t *testing.T) { }) } +func TestAccEC2Host_outpost(t *testing.T) { + var host ec2.Host + resourceName := "aws_ec2_host.test" + outpostDataSourceName := "data.aws_outposts_outpost.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckOutpostsOutposts(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckHostDestroy, + Steps: []resource.TestStep{ + { + Config: testAccHostConfig_outpost(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHostExists(resourceName, &host), + resource.TestCheckResourceAttrPair(resourceName, "outpost_arn", outpostDataSourceName, "arn"), + ), + }, + { + ResourceName: rName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func testAccCheckHostExists(n string, v *ec2.Host) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -210,7 +239,7 @@ func testAccCheckHostDestroy(s *terraform.State) error { return nil } -func testAccHostConfig() string { +func testAccHostConfig_basic() string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` resource "aws_ec2_host" "test" { availability_zone = data.aws_availability_zones.available.names[0] @@ -219,7 +248,7 @@ resource "aws_ec2_host" "test" { `) } -func testAccHostInstanceFamilyConfig(rName string) string { +func testAccHostConfig_instanceFamily(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ec2_host" "test" { auto_placement = "off" @@ -234,7 +263,7 @@ resource "aws_ec2_host" "test" { `, rName)) } -func testAccHostInstanceTypeConfig(rName string) string { +func testAccHostConfig_instanceType(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ec2_host" "test" { auto_placement = "on" @@ -249,7 +278,7 @@ resource "aws_ec2_host" "test" { `, rName)) } -func testAccHostTags1Config(tagKey1, tagValue1 string) string { +func testAccHostConfig_tags1(tagKey1, tagValue1 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ec2_host" "test" { availability_zone = data.aws_availability_zones.available.names[0] @@ -262,7 +291,7 @@ resource "aws_ec2_host" "test" { `, tagKey1, tagValue1)) } -func testAccHostTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccHostConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ec2_host" "test" { availability_zone = data.aws_availability_zones.available.names[0] @@ -275,3 +304,23 @@ resource "aws_ec2_host" "test" { } `, tagKey1, tagValue1, tagKey2, tagValue2)) } + +func testAccHostConfig_outpost(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` +data "aws_outposts_outposts" "test" {} + +data "aws_outposts_outpost" "test" { + id = tolist(data.aws_outposts_outposts.test.ids)[0] +} + +resource "aws_ec2_host" "test" { + instance_family = "r5d" + availability_zone = data.aws_availability_zones.available.names[1] + outpost_arn = data.aws_outposts_outpost.test.arn + + tags = { + Name = %[1]q + } +} +`, rName)) +} diff --git a/internal/service/ec2/ec2_instance.go b/internal/service/ec2/ec2_instance.go index f2cdf93ec9b..4b4a7878489 100644 --- a/internal/service/ec2/ec2_instance.go +++ b/internal/service/ec2/ec2_instance.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "log" + "regexp" "strconv" "strings" "time" @@ -136,8 +137,9 @@ func ResourceInstance() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cpu_credits": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice(CPUCredits_Values(), false), DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { // Only work with existing instances if d.Id() == "" { @@ -157,6 +159,11 @@ func ResourceInstance() *schema.Resource { }, }, }, + "disable_api_stop": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, "disable_api_termination": { Type: schema.TypeBool, Optional: true, @@ -500,6 +507,36 @@ func ResourceInstance() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "private_dns_name_options": { + Type: schema.TypeList, + Optional: true, + Computed: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enable_resource_name_dns_aaaa_record": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + ForceNew: true, + }, + "enable_resource_name_dns_a_record": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + ForceNew: true, + }, + "hostname_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(ec2.HostnameType_Values(), false), + }, + }, + }, + }, "private_ip": { Type: schema.TypeString, Optional: true, @@ -773,6 +810,7 @@ func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { CapacityReservationSpecification: instanceOpts.CapacityReservationSpecification, CpuOptions: instanceOpts.CpuOptions, CreditSpecification: instanceOpts.CreditSpecification, + DisableApiStop: instanceOpts.DisableAPIStop, DisableApiTermination: instanceOpts.DisableAPITermination, EbsOptimized: instanceOpts.EBSOptimized, EnclaveOptions: instanceOpts.EnclaveOptions, @@ -792,6 +830,7 @@ func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { Monitoring: instanceOpts.Monitoring, NetworkInterfaces: instanceOpts.NetworkInterfaces, Placement: instanceOpts.Placement, + PrivateDnsNameOptions: instanceOpts.PrivateDNSNameOptions, PrivateIpAddress: instanceOpts.PrivateIPAddress, SecurityGroupIds: instanceOpts.SecurityGroupIDs, SecurityGroups: instanceOpts.SecurityGroups, @@ -902,6 +941,13 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("reading EC2 Instance (%s): %w", d.Id(), err) } + instanceType := aws.StringValue(instance.InstanceType) + instanceTypeInfo, err := FindInstanceTypeByName(conn, instanceType) + + if err != nil { + return fmt.Errorf("reading EC2 Instance Type (%s): %w", instanceType, err) + } + d.Set("instance_state", instance.State.Name) if v := instance.Placement; v != nil { @@ -949,8 +995,16 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting metadata_options: %w", err) } + if instance.PrivateDnsNameOptions != nil { + if err := d.Set("private_dns_name_options", []interface{}{flattenPrivateDNSNameOptionsResponse(instance.PrivateDnsNameOptions)}); err != nil { + return fmt.Errorf("error setting private_dns_name_options: %w", err) + } + } else { + d.Set("private_dns_name_options", nil) + } + d.Set("ami", instance.ImageId) - d.Set("instance_type", instance.InstanceType) + d.Set("instance_type", instanceType) d.Set("key_name", instance.KeyName) d.Set("public_dns", instance.PublicDnsName) d.Set("public_ip", instance.PublicIpAddress) @@ -1128,6 +1182,16 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { d.Set("arn", arn.String()) // Instance attributes + { + attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{ + Attribute: aws.String(ec2.InstanceAttributeNameDisableApiStop), + InstanceId: aws.String(d.Id()), + }) + if err != nil { + return fmt.Errorf("reading EC2 Instance (%s) attribute: %w ", d.Id(), err) + } + d.Set("disable_api_stop", attr.DisableApiStop.Value) + } { if isSnowballEdgeInstance(d.Id()) { log.Printf("[INFO] Determined deploying to Snowball Edge based off Instance ID %s. Skip setting the 'disable_api_termination' attribute.", d.Id()) @@ -1168,7 +1232,7 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { // AWS Standard will return InstanceCreditSpecification.NotSupported errors for EC2 Instance IDs outside T2 and T3 instance types // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/8055 - if strings.HasPrefix(aws.StringValue(instance.InstanceType), "t2") || strings.HasPrefix(aws.StringValue(instance.InstanceType), "t3") { + if aws.BoolValue(instanceTypeInfo.BurstablePerformanceSupported) { instanceCreditSpecification, err := FindInstanceCreditSpecificationByID(conn, d.Id()) // Ignore UnsupportedOperation errors for AWS China and GovCloud (US). @@ -1506,16 +1570,20 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { } if err := modifyInstanceAttributeWithStopStart(conn, input); err != nil { - return fmt.Errorf("updating Ec2 Instance (%s) user data base64: %w", d.Id(), err) + return fmt.Errorf("updating EC2 Instance (%s) user data base64: %w", d.Id(), err) } } } - if d.HasChange("disable_api_termination") && !d.IsNewResource() { - err := disableInstanceAPITermination(conn, d.Id(), d.Get("disable_api_termination").(bool)) + if d.HasChange("disable_api_stop") && !d.IsNewResource() { + if err := disableInstanceAPIStop(conn, d.Id(), d.Get("disable_api_stop").(bool)); err != nil { + return err + } + } - if err != nil { - return fmt.Errorf("error modifying instance (%s) attribute (%s): %w", d.Id(), ec2.InstanceAttributeNameDisableApiTermination, err) + if d.HasChange("disable_api_termination") && !d.IsNewResource() { + if err := disableInstanceAPITermination(conn, d.Id(), d.Get("disable_api_termination").(bool)); err != nil { + return err } } @@ -1742,10 +1810,14 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { func resourceInstanceDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - if err := disableInstanceAPITermination(conn, d.Id(), d.Get("disable_api_termination").(bool)); err != nil { + if err := disableInstanceAPITermination(conn, d.Id(), false); err != nil { log.Printf("[WARN] attempting to terminate EC2 Instance (%s) despite error disabling API termination: %s", d.Id(), err) } + if err := disableInstanceAPIStop(conn, d.Id(), d.Get("disable_api_stop").(bool)); err != nil { + log.Printf("[WARN] attempting to terminate EC2 Instance (%s) despite error disabling API stop: %s", d.Id(), err) + } + if err := terminateInstance(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { return err } @@ -1753,6 +1825,26 @@ func resourceInstanceDelete(d *schema.ResourceData, meta interface{}) error { return nil } +func disableInstanceAPIStop(conn *ec2.EC2, id string, disableAPIStop bool) error { + _, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{ + DisableApiStop: &ec2.AttributeBooleanValue{ + Value: aws.Bool(disableAPIStop), + }, + InstanceId: aws.String(id), + }) + + if tfawserr.ErrMessageContains(err, errCodeUnsupportedOperation, "not supported for spot instances") { + log.Printf("[WARN] failed to modify EC2 Instance (%s) attribute: %s", id, err) + return nil + } + + if err != nil { + return fmt.Errorf("modifying EC2 Instance (%s) DisableApiStop attribute: %w", id, err) + } + + return nil +} + func disableInstanceAPITermination(conn *ec2.EC2, id string, disableAPITermination bool) error { _, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{ DisableApiTermination: &ec2.AttributeBooleanValue{ @@ -1767,7 +1859,7 @@ func disableInstanceAPITermination(conn *ec2.EC2, id string, disableAPITerminati } if err != nil { - return fmt.Errorf("modifying EC2 Instance (%s) attribute: %w", id, err) + return fmt.Errorf("modifying EC2 Instance (%s) DisableApiTermination attribute: %w", id, err) } return nil @@ -1989,62 +2081,6 @@ func blockDeviceIsRoot(bd *ec2.InstanceBlockDeviceMapping, instance *ec2.Instanc aws.StringValue(bd.DeviceName) == aws.StringValue(instance.RootDeviceName) } -func fetchLaunchTemplateAMI(specs []interface{}, conn *ec2.EC2) (string, error) { - if len(specs) < 1 { - return "", errors.New("Cannot fetch AMI for blank launch template.") - } - - spec := specs[0].(map[string]interface{}) - - idValue, idOk := spec["id"] - nameValue, nameOk := spec["name"] - - request := &ec2.DescribeLaunchTemplateVersionsInput{} - - if idOk && idValue != "" { - request.LaunchTemplateId = aws.String(idValue.(string)) - } else if nameOk && nameValue != "" { - request.LaunchTemplateName = aws.String(nameValue.(string)) - } - - var isLatest bool - defaultFilter := []*ec2.Filter{ - { - Name: aws.String("is-default-version"), - Values: aws.StringSlice([]string{"true"}), - }, - } - if v, ok := spec["version"]; ok && v != "" { - switch v { - case LaunchTemplateVersionDefault: - request.Filters = defaultFilter - case LaunchTemplateVersionLatest: - isLatest = true - default: - request.Versions = []*string{aws.String(v.(string))} - } - } - - dltv, err := conn.DescribeLaunchTemplateVersions(request) - if err != nil { - return "", err - } - - var ltData *ec2.ResponseLaunchTemplateData - if isLatest { - index := len(dltv.LaunchTemplateVersions) - 1 - ltData = dltv.LaunchTemplateVersions[index].LaunchTemplateData - } else { - ltData = dltv.LaunchTemplateVersions[0].LaunchTemplateData - } - - if ltData.ImageId != nil { - return *ltData.ImageId, nil - } - - return "", nil -} - func FetchRootDeviceName(conn *ec2.EC2, amiID string) (*string, error) { if amiID == "" { return nil, errors.New("Cannot fetch root device name for blank AMI ID.") @@ -2292,21 +2328,24 @@ func readBlockDeviceMappingsFromConfig(d *schema.ResourceData, conn *ec2.EC2) ([ } var amiID string - if v, ok := d.GetOk("launch_template"); ok { - var err error - amiID, err = fetchLaunchTemplateAMI(v.([]interface{}), conn) + + if v, ok := d.GetOk("launch_template"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + launchTemplateData, err := findLaunchTemplateData(conn, expandLaunchTemplateSpecification(v.([]interface{})[0].(map[string]interface{}))) + if err != nil { return nil, err } + + amiID = aws.StringValue(launchTemplateData.ImageId) } - // AMI id from attributes overrides ami from launch template + // AMI from configuration overrides the one from the launch template. if v, ok := d.GetOk("ami"); ok { amiID = v.(string) } if amiID == "" { - return nil, errors.New("`ami` must be set or provided via launch template") + return nil, errors.New("`ami` must be set or provided via `launch_template`") } if dn, err := FetchRootDeviceName(conn, amiID); err == nil { @@ -2463,9 +2502,13 @@ func getInstancePasswordData(instanceID string, conn *ec2.EC2) (string, error) { type awsInstanceOpts struct { BlockDeviceMappings []*ec2.BlockDeviceMapping CapacityReservationSpecification *ec2.CapacityReservationSpecification + CpuOptions *ec2.CpuOptionsRequest + CreditSpecification *ec2.CreditSpecificationRequest + DisableAPIStop *bool DisableAPITermination *bool EBSOptimized *bool - Monitoring *ec2.RunInstancesMonitoringEnabled + EnclaveOptions *ec2.EnclaveOptionsRequest + HibernationOptions *ec2.HibernationOptionsRequest IAMInstanceProfile *ec2.IamInstanceProfileSpecification ImageID *string InstanceInitiatedShutdownBehavior *string @@ -2474,30 +2517,29 @@ type awsInstanceOpts struct { Ipv6Addresses []*ec2.InstanceIpv6Address KeyName *string LaunchTemplate *ec2.LaunchTemplateSpecification + MaintenanceOptions *ec2.InstanceMaintenanceOptionsRequest + MetadataOptions *ec2.InstanceMetadataOptionsRequest + Monitoring *ec2.RunInstancesMonitoringEnabled NetworkInterfaces []*ec2.InstanceNetworkInterfaceSpecification Placement *ec2.Placement + PrivateDNSNameOptions *ec2.PrivateDnsNameOptionsRequest PrivateIPAddress *string SecurityGroupIDs []*string SecurityGroups []*string SpotPlacement *ec2.SpotPlacement SubnetID *string UserData64 *string - CreditSpecification *ec2.CreditSpecificationRequest - CpuOptions *ec2.CpuOptionsRequest - HibernationOptions *ec2.HibernationOptionsRequest - MetadataOptions *ec2.InstanceMetadataOptionsRequest - EnclaveOptions *ec2.EnclaveOptionsRequest - MaintenanceOptions *ec2.InstanceMaintenanceOptionsRequest } func buildInstanceOpts(d *schema.ResourceData, meta interface{}) (*awsInstanceOpts, error) { conn := meta.(*conns.AWSClient).EC2Conn opts := &awsInstanceOpts{ + DisableAPIStop: aws.Bool(d.Get("disable_api_stop").(bool)), DisableAPITermination: aws.Bool(d.Get("disable_api_termination").(bool)), EBSOptimized: aws.Bool(d.Get("ebs_optimized").(bool)), - MetadataOptions: expandInstanceMetadataOptions(d.Get("metadata_options").([]interface{})), EnclaveOptions: expandEnclaveOptions(d.Get("enclave_options").([]interface{})), + MetadataOptions: expandInstanceMetadataOptions(d.Get("metadata_options").([]interface{})), } if v, ok := d.GetOk("ami"); ok { @@ -2508,29 +2550,49 @@ func buildInstanceOpts(d *schema.ResourceData, meta interface{}) (*awsInstanceOp opts.InstanceType = aws.String(v.(string)) } - if v, ok := d.GetOk("launch_template"); ok { - opts.LaunchTemplate = expandLaunchTemplateSpecification(v.([]interface{})) + var instanceInterruptionBehavior string + + if v, ok := d.GetOk("launch_template"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + launchTemplateSpecification := expandLaunchTemplateSpecification(v.([]interface{})[0].(map[string]interface{})) + launchTemplateData, err := findLaunchTemplateData(conn, launchTemplateSpecification) + + if err != nil { + return nil, err + } + + opts.LaunchTemplate = launchTemplateSpecification + + if launchTemplateData.InstanceMarketOptions != nil && launchTemplateData.InstanceMarketOptions.SpotOptions != nil { + instanceInterruptionBehavior = aws.StringValue(launchTemplateData.InstanceMarketOptions.SpotOptions.InstanceInterruptionBehavior) + } } instanceType := d.Get("instance_type").(string) - // Set default cpu_credits as Unlimited for T3 instance type + // Set default cpu_credits as Unlimited for T3/T3a instance type if strings.HasPrefix(instanceType, "t3") { opts.CreditSpecification = &ec2.CreditSpecificationRequest{ - CpuCredits: aws.String("unlimited"), + CpuCredits: aws.String(CPUCreditsUnlimited), } } if v, ok := d.GetOk("credit_specification"); ok && len(v.([]interface{})) > 0 { - // Only T2 and T3 are burstable performance instance types and supports Unlimited. - if strings.HasPrefix(instanceType, "t2") || strings.HasPrefix(instanceType, "t3") { - if v, ok := v.([]interface{})[0].(map[string]interface{}); ok { - opts.CreditSpecification = expandCreditSpecificationRequest(v) + if instanceType != "" { + instanceTypeInfo, err := FindInstanceTypeByName(conn, instanceType) + + if err != nil { + return nil, fmt.Errorf("reading EC2 Instance Type (%s): %w", instanceType, err) + } + + if aws.BoolValue(instanceTypeInfo.BurstablePerformanceSupported) { + if v, ok := v.([]interface{})[0].(map[string]interface{}); ok { + opts.CreditSpecification = expandCreditSpecificationRequest(v) + } else { + log.Print("[WARN] credit_specification is defined but the value of cpu_credits is missing, default value will be used.") + } } else { - log.Print("[WARN] credit_specification is defined but the value of cpu_credits is missing, default value will be used.") + log.Print("[WARN] credit_specification is defined but instance type does not support burstable performance. Ignoring...") } - } else { - log.Print("[WARN] credit_specification is defined but instance type is not T2/T3. Ignoring...") } } @@ -2563,7 +2625,6 @@ func buildInstanceOpts(d *schema.ResourceData, meta interface{}) (*awsInstanceOp // aws_spot_instance_request. They represent the same data. :-| opts.Placement = &ec2.Placement{ AvailabilityZone: aws.String(d.Get("availability_zone").(string)), - GroupName: aws.String(d.Get("placement_group").(string)), } if v, ok := d.GetOk("placement_partition_number"); ok { @@ -2572,7 +2633,11 @@ func buildInstanceOpts(d *schema.ResourceData, meta interface{}) (*awsInstanceOp opts.SpotPlacement = &ec2.SpotPlacement{ AvailabilityZone: aws.String(d.Get("availability_zone").(string)), - GroupName: aws.String(d.Get("placement_group").(string)), + } + + if v := d.Get("placement_group").(string); instanceInterruptionBehavior == "" || instanceInterruptionBehavior == ec2.InstanceInterruptionBehaviorTerminate { + opts.Placement.GroupName = aws.String(v) + opts.SpotPlacement.GroupName = aws.String(v) } if v := d.Get("tenancy").(string); v != "" { @@ -2678,6 +2743,10 @@ func buildInstanceOpts(d *schema.ResourceData, meta interface{}) (*awsInstanceOp opts.MaintenanceOptions = expandInstanceMaintenanceOptionsRequest(v.([]interface{})[0].(map[string]interface{})) } + if v, ok := d.GetOk("private_dns_name_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + opts.PrivateDNSNameOptions = expandPrivateDNSNameOptionsRequest(v.([]interface{})[0].(map[string]interface{})) + } + return opts, nil } @@ -3071,29 +3140,70 @@ func flattenInstanceMaintenanceOptions(apiObject *ec2.InstanceMaintenanceOptions return tfMap } -func expandLaunchTemplateSpecification(specs []interface{}) *ec2.LaunchTemplateSpecification { - if len(specs) < 1 { +func expandPrivateDNSNameOptionsRequest(tfMap map[string]interface{}) *ec2.PrivateDnsNameOptionsRequest { + if tfMap == nil { return nil } - spec := specs[0].(map[string]interface{}) + apiObject := &ec2.PrivateDnsNameOptionsRequest{} + + if v, ok := tfMap["enable_resource_name_dns_aaaa_record"].(bool); ok { + apiObject.EnableResourceNameDnsAAAARecord = aws.Bool(v) + } + + if v, ok := tfMap["enable_resource_name_dns_a_record"].(bool); ok { + apiObject.EnableResourceNameDnsARecord = aws.Bool(v) + } - idValue, idOk := spec["id"] - nameValue, nameOk := spec["name"] + if v, ok := tfMap["hostname_type"].(string); ok && v != "" { + apiObject.HostnameType = aws.String(v) + } - result := &ec2.LaunchTemplateSpecification{} + return apiObject +} - if idOk && idValue != "" { - result.LaunchTemplateId = aws.String(idValue.(string)) - } else if nameOk && nameValue != "" { - result.LaunchTemplateName = aws.String(nameValue.(string)) +func flattenPrivateDNSNameOptionsResponse(apiObject *ec2.PrivateDnsNameOptionsResponse) map[string]interface{} { + if apiObject == nil { + return nil } - if v, ok := spec["version"]; ok && v != "" { - result.Version = aws.String(v.(string)) + tfMap := map[string]interface{}{} + + if v := apiObject.EnableResourceNameDnsAAAARecord; v != nil { + tfMap["enable_resource_name_dns_aaaa_record"] = aws.BoolValue(v) } - return result + if v := apiObject.EnableResourceNameDnsARecord; v != nil { + tfMap["enable_resource_name_dns_a_record"] = aws.BoolValue(v) + } + + if v := apiObject.HostnameType; v != nil { + tfMap["hostname_type"] = aws.StringValue(v) + } + + return tfMap +} + +func expandLaunchTemplateSpecification(tfMap map[string]interface{}) *ec2.LaunchTemplateSpecification { + if tfMap == nil { + return nil + } + + apiObject := &ec2.LaunchTemplateSpecification{} + + // DescribeLaunchTemplates returns both name and id but LaunchTemplateSpecification + // allows only one of them to be set. + if v, ok := tfMap["id"]; ok && v != "" { + apiObject.LaunchTemplateId = aws.String(v.(string)) + } else if v, ok := tfMap["name"]; ok && v != "" { + apiObject.LaunchTemplateName = aws.String(v.(string)) + } + + if v, ok := tfMap["version"].(string); ok && v != "" { + apiObject.Version = aws.String(v) + } + + return apiObject } func flattenInstanceLaunchTemplate(conn *ec2.EC2, instanceID, previousLaunchTemplateVersion string) ([]interface{}, error) { @@ -3178,6 +3288,43 @@ func findInstanceLaunchTemplateVersion(conn *ec2.EC2, id string) (string, error) return launchTemplateVersion, nil } +func findLaunchTemplateData(conn *ec2.EC2, launchTemplateSpecification *ec2.LaunchTemplateSpecification) (*ec2.ResponseLaunchTemplateData, error) { + input := &ec2.DescribeLaunchTemplateVersionsInput{} + + if v := aws.StringValue(launchTemplateSpecification.LaunchTemplateId); v != "" { + input.LaunchTemplateId = aws.String(v) + } else if v := aws.StringValue(launchTemplateSpecification.LaunchTemplateName); v != "" { + input.LaunchTemplateName = aws.String(v) + } + + var latestVersion bool + + if v := aws.StringValue(launchTemplateSpecification.Version); v != "" { + switch v { + case LaunchTemplateVersionDefault: + input.Filters = BuildAttributeFilterList(map[string]string{ + "is-default-version": "true", + }) + case LaunchTemplateVersionLatest: + latestVersion = true + default: + input.Versions = aws.StringSlice([]string{v}) + } + } + + output, err := FindLaunchTemplateVersions(conn, input) + + if err != nil { + return nil, fmt.Errorf("reading EC2 Launch Template versions: %w", err) + } + + if latestVersion { + return output[len(output)-1].LaunchTemplateData, nil + } + + return output[0].LaunchTemplateData, nil +} + // findLaunchTemplateNameAndVersions returns the specified launch template's name, default version and latest version. func findLaunchTemplateNameAndVersions(conn *ec2.EC2, id string) (string, string, string, error) { lt, err := FindLaunchTemplateByID(conn, id) @@ -3217,3 +3364,39 @@ func findInstanceTagValue(conn *ec2.EC2, instanceID, tagKey string) (string, err func isSnowballEdgeInstance(id string) bool { return strings.Contains(id, "s.") } + +// InstanceType describes an EC2 instance type. +type InstanceType struct { + // e.g. "m6i" + Type string + // e.g. "m" + Family string + // e.g. 6 + Generation int + // e.g. "i" + AdditionalCapabilities string + // e.g. "9xlarge" + Size string +} + +func ParseInstanceType(s string) (*InstanceType, error) { + matches := regexp.MustCompile(`(([[:alpha:]]+)([[:digit:]])+([[:alpha:]]*))\.([[:alnum:]]+)`).FindStringSubmatch(s) + + if matches == nil { + return nil, fmt.Errorf("invalid EC2 Instance Type name: %s", s) + } + + generation, err := strconv.Atoi(matches[3]) + + if err != nil { + return nil, err + } + + return &InstanceType{ + Type: matches[1], + Family: matches[2], + Generation: generation, + AdditionalCapabilities: matches[4], + Size: matches[5], + }, nil +} diff --git a/internal/service/ec2/ec2_instance_data_source.go b/internal/service/ec2/ec2_instance_data_source.go index f479bf45d58..33d2e018cda 100644 --- a/internal/service/ec2/ec2_instance_data_source.go +++ b/internal/service/ec2/ec2_instance_data_source.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "log" - "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" @@ -50,6 +49,10 @@ func DataSourceInstance() *schema.Resource { }, }, }, + "disable_api_stop": { + Type: schema.TypeBool, + Computed: true, + }, "disable_api_termination": { Type: schema.TypeBool, Computed: true, @@ -256,6 +259,26 @@ func DataSourceInstance() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "private_dns_name_options": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enable_resource_name_dns_aaaa_record": { + Type: schema.TypeBool, + Computed: true, + }, + "enable_resource_name_dns_a_record": { + Type: schema.TypeBool, + Computed: true, + }, + "hostname_type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, "public_dns": { Type: schema.TypeString, Computed: true, @@ -414,6 +437,14 @@ func dataSourceInstanceRead(d *schema.ResourceData, meta interface{}) error { // Populate instance attribute fields with the returned instance func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instance, conn *ec2.EC2, ignoreTagsConfig *tftags.IgnoreConfig) error { d.SetId(aws.StringValue(instance.InstanceId)) + + instanceType := aws.StringValue(instance.InstanceType) + instanceTypeInfo, err := FindInstanceTypeByName(conn, instanceType) + + if err != nil { + return fmt.Errorf("reading EC2 Instance Type (%s): %w", instanceType, err) + } + // Set the easy attributes d.Set("instance_state", instance.State.Name) if instance.Placement != nil { @@ -433,7 +464,7 @@ func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instanc } d.Set("ami", instance.ImageId) - d.Set("instance_type", instance.InstanceType) + d.Set("instance_type", instanceType) d.Set("key_name", instance.KeyName) d.Set("outpost_arn", instance.OutpostArn) d.Set("private_dns", instance.PrivateDnsName) @@ -515,7 +546,17 @@ func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instanc // Lookup and Set Instance Attributes { attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{ - Attribute: aws.String("disableApiTermination"), + Attribute: aws.String(ec2.InstanceAttributeNameDisableApiStop), + InstanceId: aws.String(d.Id()), + }) + if err != nil { + return err + } + d.Set("disable_api_stop", attr.DisableApiStop.Value) + } + { + attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{ + Attribute: aws.String(ec2.InstanceAttributeNameDisableApiTermination), InstanceId: aws.String(d.Id()), }) if err != nil { @@ -541,7 +582,7 @@ func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instanc // AWS Standard will return InstanceCreditSpecification.NotSupported errors for EC2 Instance IDs outside T2 and T3 instance types // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/8055 - if strings.HasPrefix(aws.StringValue(instance.InstanceType), "t2") || strings.HasPrefix(aws.StringValue(instance.InstanceType), "t3") { + if aws.BoolValue(instanceTypeInfo.BurstablePerformanceSupported) { instanceCreditSpecification, err := FindInstanceCreditSpecificationByID(conn, d.Id()) // Ignore UnsupportedOperation errors for AWS China and GovCloud (US). @@ -581,5 +622,13 @@ func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instanc return fmt.Errorf("error setting metadata_options: %w", err) } + if instance.PrivateDnsNameOptions != nil { + if err := d.Set("private_dns_name_options", []interface{}{flattenPrivateDNSNameOptionsResponse(instance.PrivateDnsNameOptions)}); err != nil { + return fmt.Errorf("error setting private_dns_name_options: %w", err) + } + } else { + d.Set("private_dns_name_options", nil) + } + return nil } diff --git a/internal/service/ec2/ec2_instance_data_source_test.go b/internal/service/ec2/ec2_instance_data_source_test.go index bacb732ae53..5d4b9b1c5ea 100644 --- a/internal/service/ec2/ec2_instance_data_source_test.go +++ b/internal/service/ec2/ec2_instance_data_source_test.go @@ -21,7 +21,7 @@ func TestAccEC2InstanceDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceConfig(rName), + Config: testAccInstanceDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), @@ -46,7 +46,7 @@ func TestAccEC2InstanceDataSource_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceTagsConfig(rName), + Config: testAccInstanceDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), @@ -68,7 +68,7 @@ func TestAccEC2InstanceDataSource_azUserData(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceAzUserDataConfig(rName), + Config: testAccInstanceDataSourceConfig_azUser(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), @@ -144,7 +144,7 @@ func TestAccEC2InstanceDataSource_blockDevices(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceBlockDevicesConfig(rName), + Config: testAccInstanceDataSourceConfig_blockDevices(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), @@ -204,7 +204,7 @@ func TestAccEC2InstanceDataSource_rootInstanceStore(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceRootInstanceStoreConfig(rName), + Config: testAccInstanceDataSourceConfig_rootStore(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), @@ -228,10 +228,14 @@ func TestAccEC2InstanceDataSource_privateIP(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourcePrivateIPConfig(rName), + Config: testAccInstanceDataSourceConfig_privateIP(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_name_options.#", resourceName, "private_dns_name_options.#"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_name_options.0.enable_resource_name_dns_aaaa_record", resourceName, "private_dns_name_options.0.enable_resource_name_dns_aaaa_record"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_name_options.0.enable_resource_name_dns_a_record", resourceName, "private_dns_name_options.0.enable_resource_name_dns_a_record"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_name_options.0.hostname_type", resourceName, "private_dns_name_options.0.hostname_type"), resource.TestCheckResourceAttrPair(datasourceName, "private_ip", resourceName, "private_ip"), ), }, @@ -250,7 +254,7 @@ func TestAccEC2InstanceDataSource_secondaryPrivateIPs(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceSecondaryPrivateIPsConfig(rName), + Config: testAccInstanceDataSourceConfig_secondaryPrivateIPs(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), @@ -299,7 +303,7 @@ func TestAccEC2InstanceDataSource_keyPair(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceKeyPairConfig(rName, publicKey), + Config: testAccInstanceDataSourceConfig_keyPair(rName, publicKey), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), @@ -322,7 +326,7 @@ func TestAccEC2InstanceDataSource_vpc(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceVPCConfig(rName), + Config: testAccInstanceDataSourceConfig_vpc(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), @@ -346,7 +350,7 @@ func TestAccEC2InstanceDataSource_placementGroup(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourcePlacementGroupConfig(rName), + Config: testAccInstanceDataSourceConfig_placementGroup(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "placement_group", resourceName, "placement_group"), ), @@ -366,7 +370,7 @@ func TestAccEC2InstanceDataSource_securityGroups(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceSecurityGroupsConfig(rName), + Config: testAccInstanceDataSourceConfig_securityGroups(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), @@ -390,7 +394,7 @@ func TestAccEC2InstanceDataSource_vpcSecurityGroups(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceVPCSecurityGroupsConfig(rName), + Config: testAccInstanceDataSourceConfig_vpcSecurityGroups(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "ami", resourceName, "ami"), resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), @@ -417,14 +421,14 @@ func TestAccEC2InstanceDataSource_GetPasswordData_trueToFalse(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceGetPasswordDataConfig(rName, publicKey, true), + Config: testAccInstanceDataSourceConfig_getPassword(rName, publicKey, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_password_data", "true"), resource.TestCheckResourceAttrSet(datasourceName, "password_data"), ), }, { - Config: testAccInstanceDataSourceGetPasswordDataConfig(rName, publicKey, false), + Config: testAccInstanceDataSourceConfig_getPassword(rName, publicKey, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_password_data", "false"), resource.TestCheckNoResourceAttr(datasourceName, "password_data"), @@ -449,14 +453,14 @@ func TestAccEC2InstanceDataSource_GetPasswordData_falseToTrue(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceGetPasswordDataConfig(rName, publicKey, false), + Config: testAccInstanceDataSourceConfig_getPassword(rName, publicKey, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_password_data", "false"), resource.TestCheckNoResourceAttr(datasourceName, "password_data"), ), }, { - Config: testAccInstanceDataSourceGetPasswordDataConfig(rName, publicKey, true), + Config: testAccInstanceDataSourceConfig_getPassword(rName, publicKey, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_password_data", "true"), resource.TestCheckResourceAttrSet(datasourceName, "password_data"), @@ -476,21 +480,21 @@ func TestAccEC2InstanceDataSource_getUserData(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceGetUserDataConfig(rName, true), + Config: testAccInstanceDataSourceConfig_getUser(rName, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_user_data", "true"), resource.TestCheckResourceAttr(datasourceName, "user_data_base64", "IyEvYmluL2Jhc2gKCmVjaG8gImhlbGxvIHdvcmxkIgo="), ), }, { - Config: testAccInstanceDataSourceGetUserDataConfig(rName, false), + Config: testAccInstanceDataSourceConfig_getUser(rName, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_user_data", "false"), resource.TestCheckNoResourceAttr(datasourceName, "user_data_base64"), ), }, { - Config: testAccInstanceDataSourceGetUserDataConfig(rName, true), + Config: testAccInstanceDataSourceConfig_getUser(rName, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_user_data", "true"), resource.TestCheckResourceAttr(datasourceName, "user_data_base64", "IyEvYmluL2Jhc2gKCmVjaG8gImhlbGxvIHdvcmxkIgo="), @@ -511,7 +515,7 @@ func TestAccEC2InstanceDataSource_GetUserData_noUserData(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceGetUserDataNoUserDataConfig(rName, true), + Config: testAccInstanceDataSourceConfig_getUserNoUser(rName, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_user_data", "true"), resource.TestCheckNoResourceAttr(datasourceName, "user_data_base64"), @@ -519,7 +523,7 @@ func TestAccEC2InstanceDataSource_GetUserData_noUserData(t *testing.T) { ), }, { - Config: testAccInstanceDataSourceGetUserDataNoUserDataConfig(rName, false), + Config: testAccInstanceDataSourceConfig_getUserNoUser(rName, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_user_data", "false"), resource.TestCheckNoResourceAttr(datasourceName, "user_data_base64"), @@ -527,7 +531,7 @@ func TestAccEC2InstanceDataSource_GetUserData_noUserData(t *testing.T) { ), }, { - Config: testAccInstanceDataSourceGetUserDataNoUserDataConfig(rName, true), + Config: testAccInstanceDataSourceConfig_getUserNoUser(rName, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "get_user_data", "true"), resource.TestCheckNoResourceAttr(datasourceName, "user_data_base64"), @@ -548,14 +552,14 @@ func TestAccEC2InstanceDataSource_autoRecovery(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceAutoRecoveryConfig(rName, "default"), + Config: testAccInstanceDataSourceConfig_autoRecovery(rName, "default"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "maintenance_options.#", "1"), resource.TestCheckResourceAttr(datasourceName, "maintenance_options.0.auto_recovery", "default"), ), }, { - Config: testAccInstanceDataSourceAutoRecoveryConfig(rName, "disabled"), + Config: testAccInstanceDataSourceConfig_autoRecovery(rName, "disabled"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "maintenance_options.#", "1"), resource.TestCheckResourceAttr(datasourceName, "maintenance_options.0.auto_recovery", "disabled"), @@ -577,7 +581,7 @@ func TestAccEC2InstanceDataSource_creditSpecification(t *testing.T) { Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceCreditSpecificationConfig(rName), + Config: testAccInstanceDataSourceConfig_creditSpecification(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), resource.TestCheckResourceAttrPair(datasourceName, "credit_specification.#", resourceName, "credit_specification.#"), @@ -599,7 +603,7 @@ func TestAccEC2InstanceDataSource_metadataOptions(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceMetadataOptionsConfig(rName), + Config: testAccInstanceDataSourceConfig_metaOptions(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "metadata_options.#", resourceName, "metadata_options.#"), resource.TestCheckResourceAttrPair(datasourceName, "metadata_options.0.http_endpoint", resourceName, "metadata_options.0.http_endpoint"), @@ -623,7 +627,7 @@ func TestAccEC2InstanceDataSource_enclaveOptions(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceEnclaveOptionsConfig(rName), + Config: testAccInstanceDataSourceConfig_enclaveOptions(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "enclave_options.#", resourceName, "enclave_options.#"), resource.TestCheckResourceAttrPair(datasourceName, "enclave_options.0.enabled", resourceName, "enclave_options.0.enabled"), @@ -644,7 +648,7 @@ func TestAccEC2InstanceDataSource_blockDeviceTags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceBlockDeviceTagsConfig(rName), + Config: testAccInstanceDataSourceConfig_blockDeviceTags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "instance_type", resourceName, "instance_type"), ), @@ -653,9 +657,36 @@ func TestAccEC2InstanceDataSource_blockDeviceTags(t *testing.T) { }) } +func TestAccEC2InstanceDataSource_disableAPIStopTermination(t *testing.T) { + datasourceName := "data.aws_instance.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccInstanceDataSourceConfig_disableAPIStopTermination(rName, true), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(datasourceName, "disable_api_stop", "true"), + resource.TestCheckResourceAttr(datasourceName, "disable_api_termination", "true"), + ), + }, + { + Config: testAccInstanceDataSourceConfig_disableAPIStopTermination(rName, false), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(datasourceName, "disable_api_stop", "false"), + resource.TestCheckResourceAttr(datasourceName, "disable_api_termination", "false"), + ), + }, + }, + }) +} + // Lookup based on InstanceID -func testAccInstanceDataSourceConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t2.small" @@ -675,8 +706,8 @@ data "aws_instance" "test" { } // Use the tags attribute to filter -func testAccInstanceDataSourceTagsConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceDataSourceConfig_tags(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t2.small" @@ -697,10 +728,10 @@ data "aws_instance" "test" { } // filter on tag, populate more attributes -func testAccInstanceDataSourceAzUserDataConfig(rName string) string { +func testAccInstanceDataSourceConfig_azUser(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -722,7 +753,7 @@ data "aws_instance" "test" { // GP2IopsDevice func testAccInstanceDataSourceConfig_gp2IOPSDevice(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t3.medium" @@ -745,7 +776,7 @@ data "aws_instance" "test" { // GP3ThroughputDevice func testAccInstanceDataSourceConfig_gp3ThroughputDevice(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t3.medium" @@ -768,8 +799,8 @@ data "aws_instance" "test" { } // Block Device -func testAccInstanceDataSourceBlockDevicesConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceDataSourceConfig_blockDevices(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t3.medium" @@ -822,7 +853,7 @@ data "aws_instance" "test" { } func testAccInstanceDataSourceConfig_ebsKMSKeyID(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 } @@ -855,7 +886,7 @@ data "aws_instance" "test" { } func testAccInstanceDataSourceConfig_rootBlockDeviceKMSKeyID(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 } @@ -882,8 +913,8 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourceRootInstanceStoreConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceDataSourceConfig_rootStore(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t3.medium" @@ -899,9 +930,9 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourcePrivateIPConfig(rName string) string { +func testAccInstanceDataSourceConfig_privateIP(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 1), fmt.Sprintf(` resource "aws_instance" "test" { @@ -921,9 +952,9 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourceSecondaryPrivateIPsConfig(rName string) string { +func testAccInstanceDataSourceConfig_secondaryPrivateIPs(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 1), fmt.Sprintf(` resource "aws_instance" "test" { @@ -945,7 +976,7 @@ data "aws_instance" "test" { func testAccInstanceDataSourceConfig_ipv6Addresses(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCIPv6Config(rName), fmt.Sprintf(` resource "aws_instance" "test" { @@ -965,8 +996,8 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourceKeyPairConfig(rName, publicKey string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceDataSourceConfig_keyPair(rName, publicKey string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_key_pair" "test" { key_name = %[1]q public_key = %[2]q @@ -996,9 +1027,9 @@ data "aws_instance" "test" { `, rName, publicKey)) } -func testAccInstanceDataSourceVPCConfig(rName string) string { +func testAccInstanceDataSourceConfig_vpc(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 1), fmt.Sprintf(` resource "aws_instance" "test" { @@ -1021,9 +1052,9 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourcePlacementGroupConfig(rName string) string { +func testAccInstanceDataSourceConfig_placementGroup(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 1), fmt.Sprintf(` resource "aws_placement_group" "test" { @@ -1053,8 +1084,8 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourceSecurityGroupsConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceDataSourceConfig_securityGroups(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -1087,8 +1118,8 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourceVPCSecurityGroupsConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), +func testAccInstanceDataSourceConfig_vpcSecurityGroups(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 1), testAccInstanceVPCSecurityGroupConfig(rName), fmt.Sprintf(` @@ -1110,7 +1141,7 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourceGetPasswordDataConfig(rName, publicKey string, val bool) string { +func testAccInstanceDataSourceConfig_getPassword(rName, publicKey string, val bool) string { return acctest.ConfigCompose(testAccLatestWindowsServer2016CoreAMIConfig(), fmt.Sprintf(` resource "aws_key_pair" "test" { key_name = %[1]q @@ -1135,9 +1166,9 @@ data "aws_instance" "test" { `, rName, publicKey, val)) } -func testAccInstanceDataSourceGetUserDataConfig(rName string, getUserData bool) string { +func testAccInstanceDataSourceConfig_getUser(rName string, getUserData bool) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 1), fmt.Sprintf(` resource "aws_instance" "test" { @@ -1163,9 +1194,9 @@ data "aws_instance" "test" { `, rName, getUserData)) } -func testAccInstanceDataSourceGetUserDataNoUserDataConfig(rName string, getUserData bool) string { +func testAccInstanceDataSourceConfig_getUserNoUser(rName string, getUserData bool) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 1), fmt.Sprintf(` resource "aws_instance" "test" { @@ -1185,9 +1216,9 @@ data "aws_instance" "test" { `, rName, getUserData)) } -func testAccInstanceDataSourceAutoRecoveryConfig(rName string, val string) string { +func testAccInstanceDataSourceConfig_autoRecovery(rName string, val string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 1), fmt.Sprintf(` resource "aws_instance" "test" { @@ -1210,9 +1241,9 @@ data "aws_instance" "test" { `, rName, val)) } -func testAccInstanceDataSourceCreditSpecificationConfig(rName string) string { +func testAccInstanceDataSourceConfig_creditSpecification(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 1), fmt.Sprintf(` resource "aws_instance" "test" { @@ -1235,9 +1266,9 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourceMetadataOptionsConfig(rName string) string { +func testAccInstanceDataSourceConfig_metaOptions(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -1264,9 +1295,9 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourceEnclaveOptionsConfig(rName string) string { +func testAccInstanceDataSourceConfig_enclaveOptions(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), acctest.AvailableEC2InstanceTypeForRegion("c5a.xlarge", "c5.xlarge"), fmt.Sprintf(` @@ -1290,9 +1321,9 @@ data "aws_instance" "test" { `, rName)) } -func testAccInstanceDataSourceBlockDeviceTagsConfig(rName string) string { +func testAccInstanceDataSourceConfig_blockDeviceTags(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { @@ -1326,3 +1357,26 @@ data "aws_instance" "test" { } `, rName)) } + +func testAccInstanceDataSourceConfig_disableAPIStopTermination(rName string, disableApiStopTermination bool) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccInstanceVPCConfig(rName, false, 1), + fmt.Sprintf(` +resource "aws_instance" "test" { + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + disable_api_stop = %[2]t + disable_api_termination = %[2]t + instance_type = "t2.micro" + subnet_id = aws_subnet.test.id + + tags = { + Name = %[1]q + } +} + +data "aws_instance" "test" { + instance_id = aws_instance.test.id +} +`, rName, disableApiStopTermination)) +} diff --git a/internal/service/ec2/ec2_instance_test.go b/internal/service/ec2/ec2_instance_test.go index 7b08d53a6ea..82612ba0982 100644 --- a/internal/service/ec2/ec2_instance_test.go +++ b/internal/service/ec2/ec2_instance_test.go @@ -36,6 +36,9 @@ func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { "You have reached the maximum allowed number of license configurations created in one day", "specified zone does not support multi-attach-enabled volumes", "Unsupported volume type", + "HostLimitExceeded", + "ReservationCapacityExceeded", + "InsufficientInstanceCapacity", ) } @@ -100,6 +103,75 @@ func TestFetchRootDevice(t *testing.T) { } } +func TestParseInstanceType(t *testing.T) { + invalidInstanceTypes := []string{ + "", + "abc", + "abc4", + "abc4.", + "abc.xlarge", + "4g.3xlarge", + } + + for _, v := range invalidInstanceTypes { + if _, err := tfec2.ParseInstanceType(v); err == nil { + t.Errorf("Expected error for %s", v) + } + } + + v, err := tfec2.ParseInstanceType("c4.large") + + if err != nil { + t.Errorf("Unexpected error: %s", err) + } + + if got, want := v.Type, "c4"; got != want { + t.Errorf("Got: %s, want: %s", got, want) + } + + if got, want := v.Family, "c"; got != want { + t.Errorf("Got: %s, want: %s", got, want) + } + + if got, want := v.Generation, 4; got != want { + t.Errorf("Got: %d, want: %d", got, want) + } + + if got, want := v.AdditionalCapabilities, ""; got != want { + t.Errorf("Got: %s, want: %s", got, want) + } + + if got, want := v.Size, "large"; got != want { + t.Errorf("Got: %s, want: %s", got, want) + } + + v, err = tfec2.ParseInstanceType("im4gn.16xlarge") + + if err != nil { + t.Errorf("Unexpected error: %s", err) + } + + if got, want := v.Type, "im4gn"; got != want { + t.Errorf("Got: %s, want: %s", got, want) + } + + if got, want := v.Family, "im"; got != want { + t.Errorf("Got: %s, want: %s", got, want) + } + + if got, want := v.Generation, 4; got != want { + t.Errorf("Got: %d, want: %d", got, want) + } + + if got, want := v.AdditionalCapabilities, "gn"; got != want { + t.Errorf("Got: %s, want: %s", got, want) + } + + if got, want := v.Size, "16xlarge"; got != want { + t.Errorf("Got: %s, want: %s", got, want) + } +} + func TestAccEC2Instance_basic(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" @@ -115,7 +187,7 @@ func TestAccEC2Instance_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigBasic(), + Config: testAccInstanceConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`instance/i-[a-z0-9]+`)), @@ -148,7 +220,7 @@ func TestAccEC2Instance_disappears(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigBasic(), + Config: testAccInstanceConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceInstance(), resourceName), @@ -174,7 +246,7 @@ func TestAccEC2Instance_tags(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigTags1("key1", "value1"), + Config: testAccInstanceConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -188,7 +260,7 @@ func TestAccEC2Instance_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigTags2("key1", "value1updated", "key2", "value2"), + Config: testAccInstanceConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -197,7 +269,7 @@ func TestAccEC2Instance_tags(t *testing.T) { ), }, { - Config: testAccInstanceConfigTags1("key2", "value2"), + Config: testAccInstanceConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -247,7 +319,7 @@ func TestAccEC2Instance_inDefaultVPCBySgID(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_inDefaultVPCBySgId(rName), + Config: testAccInstanceConfig_inDefaultVPCBySGID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -273,13 +345,13 @@ func TestAccEC2Instance_inEC2Classic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ec2Classic(), + Config: testAccInstanceConfig_classic(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceClassicExists(resourceName, &v), ), }, { - Config: testAccInstanceConfig_ec2Classic(), + Config: testAccInstanceConfig_classic(), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -372,7 +444,7 @@ func TestAccEC2Instance_EBSBlockDevice_invalidIopsForVolumeType(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigEBSBlockDeviceInvalidIops, + Config: testAccInstanceConfig_ebsBlockDeviceInvalidIOPS, ExpectError: regexp.MustCompile(`error creating resource: iops attribute not supported for ebs_block_device with volume_type gp2`), }, }, @@ -387,7 +459,7 @@ func TestAccEC2Instance_EBSBlockDevice_invalidThroughputForVolumeType(t *testing CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigEBSBlockDeviceInvalidThroughput, + Config: testAccInstanceConfig_ebsBlockDeviceInvalidThroughput, ExpectError: regexp.MustCompile(`error creating resource: throughput attribute not supported for ebs_block_device with volume_type gp2`), }, }, @@ -409,7 +481,7 @@ func TestAccEC2Instance_EBSBlockDevice_RootBlockDevice_removed(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigEBSAndRootBlockDevice(rName), + Config: testAccInstanceConfig_ebsAndRootBlockDevice(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), // Instance must be stopped before detaching a root block device @@ -465,7 +537,7 @@ func TestAccEC2Instance_userDataBase64(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithUserDataBase64(rName, "hello world"), + Config: testAccInstanceConfig_userDataBase64(rName, "hello world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "user_data_base64", "aGVsbG8gd29ybGQ="), @@ -493,14 +565,14 @@ func TestAccEC2Instance_userDataBase64_updateWithBashFile(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithUserDataBase64(rName, "hello world"), + Config: testAccInstanceConfig_userDataBase64(rName, "hello world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "user_data_base64", "aGVsbG8gd29ybGQ="), ), }, { - Config: testAccInstanceConfigWithUserDataBase64_Base64EncodedFile(rName, "test-fixtures/userdata-test.sh"), + Config: testAccInstanceConfig_userDataBase64Base64EncodedFile(rName, "test-fixtures/userdata-test.sh"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -527,14 +599,14 @@ func TestAccEC2Instance_userDataBase64_updateWithZipFile(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithUserDataBase64(rName, "hello world"), + Config: testAccInstanceConfig_userDataBase64(rName, "hello world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "user_data_base64", "aGVsbG8gd29ybGQ="), ), }, { - Config: testAccInstanceConfigWithUserDataBase64_Base64EncodedFile(rName, "test-fixtures/userdata-test.zip"), + Config: testAccInstanceConfig_userDataBase64Base64EncodedFile(rName, "test-fixtures/userdata-test.zip"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -561,14 +633,14 @@ func TestAccEC2Instance_userDataBase64_update(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithUserDataBase64(rName, "hello world"), + Config: testAccInstanceConfig_userDataBase64(rName, "hello world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "user_data_base64", "aGVsbG8gd29ybGQ="), ), }, { - Config: testAccInstanceConfigWithUserDataBase64(rName, "new world"), + Config: testAccInstanceConfig_userDataBase64(rName, "new world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "user_data_base64", "bmV3IHdvcmxk"), @@ -613,7 +685,7 @@ func TestAccEC2Instance_gp2IopsDevice(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceGP2IopsDevice(rName), + Config: testAccInstanceConfig_gp2IOPSDevice(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), @@ -646,7 +718,7 @@ func TestAccEC2Instance_gp2WithIopsValue(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceGP2WithIopsValue(rName), + Config: testAccInstanceConfig_gp2IOPSValue(rName), ExpectError: regexp.MustCompile(`error creating resource: iops attribute not supported for root_block_device with volume_type gp2`), }, }, @@ -707,7 +779,7 @@ func TestAccEC2Instance_blockDevices(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceBlockDevicesConfig(rName, rootVolumeSize), + Config: testAccInstanceConfig_blockDevices(rName, rootVolumeSize), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), @@ -783,7 +855,7 @@ func TestAccEC2Instance_rootInstanceStore(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigRootInstanceStore(rName), + Config: testAccInstanceConfig_rootStore(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "0"), @@ -839,7 +911,7 @@ func TestAccEC2Instance_noAMIEphemeralDevices(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigNoAMIEphemeralDevices(rName), + Config: testAccInstanceConfig_noAMIEphemeralDevices(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", "false"), @@ -894,7 +966,7 @@ func TestAccEC2Instance_sourceDestCheck(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigSourceDestDisable(rName), + Config: testAccInstanceConfig_sourceDestDisable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testCheck(false), @@ -907,14 +979,14 @@ func TestAccEC2Instance_sourceDestCheck(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigSourceDestEnable(rName), + Config: testAccInstanceConfig_sourceDestEnable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testCheck(true), ), }, { - Config: testAccInstanceConfigSourceDestDisable(rName), + Config: testAccInstanceConfig_sourceDestDisable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testCheck(false), @@ -936,7 +1008,7 @@ func TestAccEC2Instance_autoRecovery(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceAutoRecoveryConfig(rName, "default"), + Config: testAccInstanceConfig_autoRecovery(rName, "default"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "maintenance_options.#", "1"), @@ -950,7 +1022,7 @@ func TestAccEC2Instance_autoRecovery(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceAutoRecoveryConfig(rName, "disabled"), + Config: testAccInstanceConfig_autoRecovery(rName, "disabled"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "maintenance_options.#", "1"), @@ -961,28 +1033,45 @@ func TestAccEC2Instance_autoRecovery(t *testing.T) { }) } -func TestAccEC2Instance_disableAPITermination(t *testing.T) { +func TestAccEC2Instance_disableAPIStop(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - checkDisableApiTermination := func(expected bool) resource.TestCheckFunc { - return func(*terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - r, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{ - InstanceId: v.InstanceId, - Attribute: aws.String("disableApiTermination"), - }) - if err != nil { - return err - } - got := *r.DisableApiTermination.Value - if got != expected { - return fmt.Errorf("expected: %t, got: %t", expected, got) - } - return nil - } - } + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_disableAPIStop(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "disable_api_stop", "true"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, + }, + { + Config: testAccInstanceConfig_disableAPIStop(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "disable_api_stop", "false"), + ), + }, + }, + }) +} + +func TestAccEC2Instance_disableAPITerminationFinalFalse(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -991,10 +1080,10 @@ func TestAccEC2Instance_disableAPITermination(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigDisableAPITermination(rName, true), + Config: testAccInstanceConfig_disableAPITermination(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - checkDisableApiTermination(true), + resource.TestCheckResourceAttr(resourceName, "disable_api_termination", "true"), ), }, { @@ -1004,16 +1093,44 @@ func TestAccEC2Instance_disableAPITermination(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigDisableAPITermination(rName, false), + Config: testAccInstanceConfig_disableAPITermination(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - checkDisableApiTermination(false), + resource.TestCheckResourceAttr(resourceName, "disable_api_termination", "false"), ), }, }, }) } +func TestAccEC2Instance_disableAPITerminationFinalTrue(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_disableAPITermination(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "disable_api_termination", "true"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, + }, + }, + }) +} + func TestAccEC2Instance_dedicatedInstance(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" @@ -1060,7 +1177,7 @@ func TestAccEC2Instance_outpost(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigOutpost(rName), + Config: testAccInstanceConfig_outpost(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "outpost_arn", outpostDataSourceName, "arn"), @@ -1088,7 +1205,7 @@ func TestAccEC2Instance_placementGroup(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPlacementGroup(rName), + Config: testAccInstanceConfig_placementGroup(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "placement_group", rName), @@ -1116,7 +1233,7 @@ func TestAccEC2Instance_placementPartitionNumber(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPlacementPartitionNumber(rName), + Config: testAccInstanceConfig_placementPartitionNumber(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "placement_group", rName), @@ -1171,7 +1288,7 @@ func TestAccEC2Instance_ipv6AddressCountAndSingleAddressCausesError(t *testing.T CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ipv6ErrorConfig(rName), + Config: testAccInstanceConfig_ipv6Error(rName), ExpectError: regexp.MustCompile("Conflicting configuration arguments"), }, }, @@ -1190,7 +1307,7 @@ func TestAccEC2Instance_IPv6_supportAddressCountWithIPv4(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ipv6SupportWithv4(rName), + Config: testAccInstanceConfig_ipv6Supportv4(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", "1"), @@ -1218,7 +1335,7 @@ func TestAccEC2Instance_networkInstanceSecurityGroups(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceNetworkInstanceSecurityGroups(rName), + Config: testAccInstanceConfig_networkSecurityGroups(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -1245,7 +1362,7 @@ func TestAccEC2Instance_networkInstanceRemovingAllSecurityGroups(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceNetworkInstanceVPCSecurityGroupIDs(rName), + Config: testAccInstanceConfig_networkVPCSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "security_groups.#", "0"), @@ -1259,7 +1376,7 @@ func TestAccEC2Instance_networkInstanceRemovingAllSecurityGroups(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceNetworkInstanceVPCRemoveSecurityGroupIDs(rName), + Config: testAccInstanceConfig_networkVPCRemoveSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "security_groups.#", "0"), @@ -1283,7 +1400,7 @@ func TestAccEC2Instance_networkInstanceVPCSecurityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceNetworkInstanceVPCSecurityGroupIDs(rName), + Config: testAccInstanceConfig_networkVPCSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "security_groups.#", "0"), @@ -1312,7 +1429,7 @@ func TestAccEC2Instance_BlockDeviceTags_volumeTags(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigBlockDeviceTagsNoVolumeTags(rName), + Config: testAccInstanceConfig_blockDeviceTagsNoVolumeTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckNoResourceAttr(resourceName, "volume_tags"), @@ -1325,7 +1442,7 @@ func TestAccEC2Instance_BlockDeviceTags_volumeTags(t *testing.T) { ImportStateVerifyIgnore: []string{"ephemeral_block_device", "user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigBlockDeviceTagsVolumeTags(rName), + Config: testAccInstanceConfig_blockDeviceTagsVolumeTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "volume_tags.%", "1"), @@ -1333,7 +1450,7 @@ func TestAccEC2Instance_BlockDeviceTags_volumeTags(t *testing.T) { ), }, { - Config: testAccInstanceConfigBlockDeviceTagsVolumeTagsUpdate(rName), + Config: testAccInstanceConfig_blockDeviceTagsVolumeTagsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "volume_tags.%", "2"), @@ -1342,7 +1459,7 @@ func TestAccEC2Instance_BlockDeviceTags_volumeTags(t *testing.T) { ), }, { - Config: testAccInstanceConfigBlockDeviceTagsNoVolumeTags(rName), + Config: testAccInstanceConfig_blockDeviceTagsNoVolumeTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "volume_tags.%", "0"), @@ -1365,7 +1482,7 @@ func TestAccEC2Instance_BlockDeviceTags_withAttachedVolume(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigBlockDeviceTagsAttachedVolumeWithTags(rName), + Config: testAccInstanceConfig_blockDeviceTagsAttachedVolumeTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(ebsVolumeName, "tags.%", "2"), @@ -1375,7 +1492,7 @@ func TestAccEC2Instance_BlockDeviceTags_withAttachedVolume(t *testing.T) { }, { //https://github.com/hashicorp/terraform-provider-aws/issues/17074 - Config: testAccInstanceConfigBlockDeviceTagsAttachedVolumeWithTags(rName), + Config: testAccInstanceConfig_blockDeviceTagsAttachedVolumeTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(ebsVolumeName, "tags.%", "2"), @@ -1384,7 +1501,7 @@ func TestAccEC2Instance_BlockDeviceTags_withAttachedVolume(t *testing.T) { ), }, { - Config: testAccInstanceConfigBlockDeviceTagsAttachedVolumeWithTagsUpdate(rName), + Config: testAccInstanceConfig_blockDeviceTagsAttachedVolumeTagsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(ebsVolumeName, "tags.%", "2"), @@ -1414,15 +1531,15 @@ func TestAccEC2Instance_BlockDeviceTags_ebsAndRoot(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigBlockDeviceTagsRootTagsConflict(rName), + Config: testAccInstanceConfig_blockDeviceTagsRootTagsConflict(rName), ExpectError: regexp.MustCompile(`"root_block_device\.0\.tags": conflicts with volume_tags`), }, { - Config: testAccInstanceConfigBlockDeviceTagsEBSTagsConflict(rName), + Config: testAccInstanceConfig_blockDeviceTagsEBSTagsConflict(rName), ExpectError: regexp.MustCompile(`"ebs_block_device\.0\.tags": conflicts with volume_tags`), }, { - Config: testAccInstanceConfigBlockDeviceTagsEBSTags(rName), + Config: testAccInstanceConfig_blockDeviceTagsEBSTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.tags.%", "0"), @@ -1432,7 +1549,7 @@ func TestAccEC2Instance_BlockDeviceTags_ebsAndRoot(t *testing.T) { ), }, { - Config: testAccInstanceConfigBlockDeviceTagsEBSAndRootTags(rName), + Config: testAccInstanceConfig_blockDeviceTagsEBSAndRootTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.tags.%", "2"), @@ -1441,7 +1558,7 @@ func TestAccEC2Instance_BlockDeviceTags_ebsAndRoot(t *testing.T) { ), }, { - Config: testAccInstanceConfigBlockDeviceTagsEBSAndRootTagsUpdate(rName), + Config: testAccInstanceConfig_blockDeviceTagsEBSAndRootTagsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.tags.%", "2"), @@ -1482,7 +1599,7 @@ func TestAccEC2Instance_instanceProfileChange(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithoutInstanceProfile(rName1), + Config: testAccInstanceConfig_noProfile(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -1494,20 +1611,20 @@ func TestAccEC2Instance_instanceProfileChange(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigWithInstanceProfile(rName1), + Config: testAccInstanceConfig_profile(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testCheckInstanceProfile(), ), }, { - Config: testAccInstanceConfigWithInstanceProfile(rName1), + Config: testAccInstanceConfig_profile(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckStopInstance(&v), // GH-8262: Error on EC2 instance role change when stopped ), }, { - Config: testAccInstanceConfigWithInstanceProfile(rName2), + Config: testAccInstanceConfig_profile(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testCheckInstanceProfile(), @@ -1539,7 +1656,7 @@ func TestAccEC2Instance_withIAMInstanceProfile(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithInstanceProfile(rName), + Config: testAccInstanceConfig_profile(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testCheckInstanceProfile(), @@ -1568,7 +1685,7 @@ func TestAccEC2Instance_withIAMInstanceProfilePath(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithInstanceProfilePath(rName), + Config: testAccInstanceConfig_profilePath(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), ), @@ -1605,7 +1722,7 @@ func TestAccEC2Instance_privateIP(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPrivateIP(rName), + Config: testAccInstanceConfig_privateIP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testCheckPrivateIP(), @@ -1643,7 +1760,7 @@ func TestAccEC2Instance_associatePublicIPAndPrivateIP(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigAssociatePublicIPAndPrivateIP(rName), + Config: testAccInstanceConfig_associatePublicIPAndPrivateIP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testCheckPrivateIP(), @@ -1683,7 +1800,7 @@ func TestAccEC2Instance_Empty_privateIP(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigEmptyPrivateIP(rName), + Config: testAccInstanceConfig_emptyPrivateIP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testCheckPrivateIP(), @@ -1699,6 +1816,68 @@ func TestAccEC2Instance_Empty_privateIP(t *testing.T) { }) } +func TestAccEC2Instance_PrivateDNSNameOptions_computed(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_PrivateDNSNameOptions_computed(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "private_dns_name_options.#", "1"), + resource.TestCheckResourceAttr(resourceName, "private_dns_name_options.0.enable_resource_name_dns_aaaa_record", "true"), + resource.TestCheckResourceAttr(resourceName, "private_dns_name_options.0.enable_resource_name_dns_a_record", "true"), + resource.TestCheckResourceAttr(resourceName, "private_dns_name_options.0.hostname_type", "resource-name"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, + }, + }, + }) +} + +func TestAccEC2Instance_PrivateDNSNameOptions_configured(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_PrivateDNSNameOptions_configured(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "private_dns_name_options.#", "1"), + resource.TestCheckResourceAttr(resourceName, "private_dns_name_options.0.enable_resource_name_dns_aaaa_record", "false"), + resource.TestCheckResourceAttr(resourceName, "private_dns_name_options.0.enable_resource_name_dns_a_record", "true"), + resource.TestCheckResourceAttr(resourceName, "private_dns_name_options.0.hostname_type", "ip-name"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, + }, + }, + }) +} + // Guard against regression with KeyPairs // https://github.com/hashicorp/terraform/issues/2302 func TestAccEC2Instance_keyPairCheck(t *testing.T) { @@ -1719,7 +1898,7 @@ func TestAccEC2Instance_keyPairCheck(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigKeyPair(rName, publicKey), + Config: testAccInstanceConfig_keyPair(rName, publicKey), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "key_name", keyPairResourceName, "key_name"), @@ -1741,7 +1920,7 @@ func TestAccEC2Instance_rootBlockDeviceMismatch(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigRootBlockDeviceMismatch(rName), + Config: testAccInstanceConfig_rootBlockDeviceMismatch(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", "13"), @@ -1778,7 +1957,7 @@ func TestAccEC2Instance_forceNewAndTagsDrift(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigForceNewAndTagsDrift(rName), + Config: testAccInstanceConfig_forceNewAndTagsDrift(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), driftTags(&v), @@ -1786,7 +1965,7 @@ func TestAccEC2Instance_forceNewAndTagsDrift(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: testAccInstanceConfigForceNewAndTagsDrift_Update(rName), + Config: testAccInstanceConfig_forceNewAndTagsDriftUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -1814,7 +1993,7 @@ func TestAccEC2Instance_changeInstanceType(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithSmallInstanceType(rName), + Config: testAccInstanceConfig_smallType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "instance_type", "t2.medium"), @@ -1827,7 +2006,7 @@ func TestAccEC2Instance_changeInstanceType(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigUpdateInstanceType(rName), + Config: testAccInstanceConfig_updateType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &after), testAccCheckInstanceNotRecreated(&before, &after), @@ -1855,7 +2034,7 @@ func TestAccEC2Instance_changeInstanceTypeAndUserData(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigInstanceTypeAndUserData(rName, "t2.medium", "hello world"), + Config: testAccInstanceConfig_typeAndUserData(rName, "t2.medium", "hello world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "instance_type", "t2.medium"), @@ -1863,7 +2042,7 @@ func TestAccEC2Instance_changeInstanceTypeAndUserData(t *testing.T) { ), }, { - Config: testAccInstanceConfigInstanceTypeAndUserData(rName, "t2.large", "new world"), + Config: testAccInstanceConfig_typeAndUserData(rName, "t2.large", "new world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "instance_type", "t2.large"), @@ -1892,7 +2071,7 @@ func TestAccEC2Instance_changeInstanceTypeAndUserDataBase64(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigInstanceTypeAndUserDataBase64(rName, "t2.medium", "hello world"), + Config: testAccInstanceConfig_typeAndUserDataBase64(rName, "t2.medium", "hello world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "instance_type", "t2.medium"), @@ -1900,7 +2079,7 @@ func TestAccEC2Instance_changeInstanceTypeAndUserDataBase64(t *testing.T) { ), }, { - Config: testAccInstanceConfigInstanceTypeAndUserDataBase64(rName, "t2.large", "new world"), + Config: testAccInstanceConfig_typeAndUserDataBase64(rName, "t2.large", "new world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "instance_type", "t2.large"), @@ -1929,7 +2108,7 @@ func TestAccEC2Instance_EBSRootDevice_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceEBSRootDeviceBasic(rName), + Config: testAccInstanceConfig_ebsRootDeviceBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), @@ -1965,7 +2144,7 @@ func TestAccEC2Instance_EBSRootDevice_modifySize(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceRootBlockDevice(rName, originalSize, deleteOnTermination, volumeType), + Config: testAccInstanceConfig_rootBlockDevice(rName, originalSize, deleteOnTermination, volumeType), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", originalSize), @@ -1974,7 +2153,7 @@ func TestAccEC2Instance_EBSRootDevice_modifySize(t *testing.T) { ), }, { - Config: testAccInstanceRootBlockDevice(rName, updatedSize, deleteOnTermination, volumeType), + Config: testAccInstanceConfig_rootBlockDevice(rName, updatedSize, deleteOnTermination, volumeType), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &updated), testAccCheckInstanceNotRecreated(&original, &updated), @@ -2006,7 +2185,7 @@ func TestAccEC2Instance_EBSRootDevice_modifyType(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceRootBlockDevice(rName, volumeSize, deleteOnTermination, originalType), + Config: testAccInstanceConfig_rootBlockDevice(rName, volumeSize, deleteOnTermination, originalType), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", volumeSize), @@ -2015,7 +2194,7 @@ func TestAccEC2Instance_EBSRootDevice_modifyType(t *testing.T) { ), }, { - Config: testAccInstanceRootBlockDevice(rName, volumeSize, deleteOnTermination, updatedType), + Config: testAccInstanceConfig_rootBlockDevice(rName, volumeSize, deleteOnTermination, updatedType), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &updated), testAccCheckInstanceNotRecreated(&original, &updated), @@ -2048,7 +2227,7 @@ func TestAccEC2Instance_EBSRootDeviceModifyIOPS_io1(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceRootBlockDeviceWithIOPS(rName, volumeSize, deleteOnTermination, volumeType, originalIOPS), + Config: testAccInstanceConfig_rootBlockDeviceIOPS(rName, volumeSize, deleteOnTermination, volumeType, originalIOPS), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", volumeSize), @@ -2058,7 +2237,7 @@ func TestAccEC2Instance_EBSRootDeviceModifyIOPS_io1(t *testing.T) { ), }, { - Config: testAccInstanceRootBlockDeviceWithIOPS(rName, volumeSize, deleteOnTermination, volumeType, updatedIOPS), + Config: testAccInstanceConfig_rootBlockDeviceIOPS(rName, volumeSize, deleteOnTermination, volumeType, updatedIOPS), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &updated), testAccCheckInstanceNotRecreated(&original, &updated), @@ -2092,7 +2271,7 @@ func TestAccEC2Instance_EBSRootDeviceModifyIOPS_io2(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceRootBlockDeviceWithIOPS(rName, volumeSize, deleteOnTermination, volumeType, originalIOPS), + Config: testAccInstanceConfig_rootBlockDeviceIOPS(rName, volumeSize, deleteOnTermination, volumeType, originalIOPS), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", volumeSize), @@ -2102,7 +2281,7 @@ func TestAccEC2Instance_EBSRootDeviceModifyIOPS_io2(t *testing.T) { ), }, { - Config: testAccInstanceRootBlockDeviceWithIOPS(rName, volumeSize, deleteOnTermination, volumeType, updatedIOPS), + Config: testAccInstanceConfig_rootBlockDeviceIOPS(rName, volumeSize, deleteOnTermination, volumeType, updatedIOPS), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &updated), testAccCheckInstanceNotRecreated(&original, &updated), @@ -2136,7 +2315,7 @@ func TestAccEC2Instance_EBSRootDeviceModifyThroughput_gp3(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceRootBlockDeviceWithThroughput(rName, volumeSize, deleteOnTermination, volumeType, originalThroughput), + Config: testAccInstanceConfig_rootBlockDeviceThroughput(rName, volumeSize, deleteOnTermination, volumeType, originalThroughput), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", volumeSize), @@ -2146,7 +2325,7 @@ func TestAccEC2Instance_EBSRootDeviceModifyThroughput_gp3(t *testing.T) { ), }, { - Config: testAccInstanceRootBlockDeviceWithThroughput(rName, volumeSize, deleteOnTermination, volumeType, updatedThroughput), + Config: testAccInstanceConfig_rootBlockDeviceThroughput(rName, volumeSize, deleteOnTermination, volumeType, updatedThroughput), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &updated), testAccCheckInstanceNotRecreated(&original, &updated), @@ -2179,7 +2358,7 @@ func TestAccEC2Instance_EBSRootDevice_modifyDeleteOnTermination(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceRootBlockDevice(rName, volumeSize, originalDeleteOnTermination, volumeType), + Config: testAccInstanceConfig_rootBlockDevice(rName, volumeSize, originalDeleteOnTermination, volumeType), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", volumeSize), @@ -2188,7 +2367,7 @@ func TestAccEC2Instance_EBSRootDevice_modifyDeleteOnTermination(t *testing.T) { ), }, { - Config: testAccInstanceRootBlockDevice(rName, volumeSize, updatedDeleteOnTermination, volumeType), + Config: testAccInstanceConfig_rootBlockDevice(rName, volumeSize, updatedDeleteOnTermination, volumeType), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &updated), testAccCheckInstanceNotRecreated(&original, &updated), @@ -2225,7 +2404,7 @@ func TestAccEC2Instance_EBSRootDevice_modifyAll(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceRootBlockDevice(rName, originalSize, originalDeleteOnTermination, originalType), + Config: testAccInstanceConfig_rootBlockDevice(rName, originalSize, originalDeleteOnTermination, originalType), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", originalSize), @@ -2234,7 +2413,7 @@ func TestAccEC2Instance_EBSRootDevice_modifyAll(t *testing.T) { ), }, { - Config: testAccInstanceRootBlockDeviceWithIOPS(rName, updatedSize, updatedDeleteOnTermination, updatedType, updatedIOPS), + Config: testAccInstanceConfig_rootBlockDeviceIOPS(rName, updatedSize, updatedDeleteOnTermination, updatedType, updatedIOPS), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &updated), testAccCheckInstanceNotRecreated(&original, &updated), @@ -2266,7 +2445,7 @@ func TestAccEC2Instance_EBSRootDeviceMultipleBlockDevices_modifySize(t *testing. CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceBlockDevicesWithDeleteOnTerminateConfig(rName, originalRootVolumeSize, deleteOnTermination), + Config: testAccInstanceConfig_blockDevicesDeleteOnTerminate(rName, originalRootVolumeSize, deleteOnTermination), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", originalRootVolumeSize), @@ -2282,7 +2461,7 @@ func TestAccEC2Instance_EBSRootDeviceMultipleBlockDevices_modifySize(t *testing. ), }, { - Config: testAccInstanceBlockDevicesWithDeleteOnTerminateConfig(rName, updatedRootVolumeSize, deleteOnTermination), + Config: testAccInstanceConfig_blockDevicesDeleteOnTerminate(rName, updatedRootVolumeSize, deleteOnTermination), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &after), testAccCheckInstanceNotRecreated(&before, &after), @@ -2320,7 +2499,7 @@ func TestAccEC2Instance_EBSRootDeviceMultipleBlockDevices_modifyDeleteOnTerminat CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceBlockDevicesWithDeleteOnTerminateConfig(rName, rootVolumeSize, originalDeleteOnTermination), + Config: testAccInstanceConfig_blockDevicesDeleteOnTerminate(rName, rootVolumeSize, originalDeleteOnTermination), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", rootVolumeSize), @@ -2337,7 +2516,7 @@ func TestAccEC2Instance_EBSRootDeviceMultipleBlockDevices_modifyDeleteOnTerminat ), }, { - Config: testAccInstanceBlockDevicesWithDeleteOnTerminateConfig(rName, rootVolumeSize, updatedDeleteOnTermination), + Config: testAccInstanceConfig_blockDevicesDeleteOnTerminate(rName, rootVolumeSize, updatedDeleteOnTermination), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &after), testAccCheckInstanceNotRecreated(&before, &after), @@ -2371,7 +2550,7 @@ func TestAccEC2Instance_EBSRootDevice_multipleDynamicEBSBlockDevices(t *testing. CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceDynamicEBSBlockDevicesConfig(rName), + Config: testAccInstanceConfig_dynamicEBSBlockDevices(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "3"), @@ -2440,7 +2619,7 @@ func TestAccEC2Instance_gp3RootBlockDevice(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigGP3RootBlockDevice(rName), + Config: testAccInstanceConfig_gp3RootBlockDevice(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), @@ -2475,7 +2654,7 @@ func TestAccEC2Instance_primaryNetworkInterface(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPrimaryNetworkInterface(rName), + Config: testAccInstanceConfig_primaryNetworkInterface(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), testAccCheckENIExists(eniResourceName, &eni), @@ -2511,7 +2690,7 @@ func TestAccEC2Instance_networkCardIndex(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigNetworkCardIndex(rName), + Config: testAccInstanceConfig_networkCardIndex(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), resource.TestCheckResourceAttr(resourceName, "network_interface.#", "1"), @@ -2545,7 +2724,7 @@ func TestAccEC2Instance_primaryNetworkInterfaceSourceDestCheck(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPrimaryNetworkInterfaceSourceDestCheck(rName), + Config: testAccInstanceConfig_primaryNetworkInterfaceSourceDestCheck(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), testAccCheckENIExists(eniResourceName, &eni), @@ -2579,7 +2758,7 @@ func TestAccEC2Instance_addSecondaryInterface(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigAddSecondaryNetworkInterfaceBefore(rName), + Config: testAccInstanceConfig_addSecondaryNetworkInterfaceBefore(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), testAccCheckENIExists(eniPrimaryResourceName, &eniPrimary), @@ -2593,7 +2772,7 @@ func TestAccEC2Instance_addSecondaryInterface(t *testing.T) { ImportStateVerifyIgnore: []string{"network_interface", "user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigAddSecondaryNetworkInterfaceAfter(rName), + Config: testAccInstanceConfig_addSecondaryNetworkInterfaceAfter(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &after), testAccCheckENIExists(eniSecondaryResourceName, &eniSecondary), @@ -2618,7 +2797,7 @@ func TestAccEC2Instance_addSecurityGroupNetworkInterface(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigAddSecurityGroupBefore(rName), + Config: testAccInstanceConfig_addSecurityGroupBefore(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "1"), @@ -2631,7 +2810,7 @@ func TestAccEC2Instance_addSecurityGroupNetworkInterface(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigAddSecurityGroupAfter(rName), + Config: testAccInstanceConfig_addSecurityGroupAfter(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "2"), @@ -2654,7 +2833,7 @@ func TestAccEC2Instance_NewNetworkInterface_publicIPAndSecondaryPrivateIPs(t *te CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPublicAndPrivateSecondaryIPs(rName, true), + Config: testAccInstanceConfig_publicAndPrivateSecondaryIPs(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), @@ -2663,7 +2842,7 @@ func TestAccEC2Instance_NewNetworkInterface_publicIPAndSecondaryPrivateIPs(t *te ), }, { - Config: testAccInstanceConfigPublicAndPrivateSecondaryIPs(rName, false), + Config: testAccInstanceConfig_publicAndPrivateSecondaryIPs(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), @@ -2695,7 +2874,7 @@ func TestAccEC2Instance_NewNetworkInterface_emptyPrivateIPAndSecondaryPrivateIPs CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPrivateIPAndSecondaryIPsNullPrivate(rName, secondaryIPs), + Config: testAccInstanceConfig_privateIPAndSecondaryIPsNullPrivate(rName, secondaryIPs), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "private_ip"), @@ -2727,7 +2906,7 @@ func TestAccEC2Instance_NewNetworkInterface_emptyPrivateIPAndSecondaryPrivateIPs CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPrivateIPAndSecondaryIPsNullPrivate(rName, secondaryIPs), + Config: testAccInstanceConfig_privateIPAndSecondaryIPsNullPrivate(rName, secondaryIPs), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "private_ip"), @@ -2735,7 +2914,7 @@ func TestAccEC2Instance_NewNetworkInterface_emptyPrivateIPAndSecondaryPrivateIPs ), }, { - Config: testAccInstanceConfigPrivateIPAndSecondaryIPsNullPrivate(rName, ""), + Config: testAccInstanceConfig_privateIPAndSecondaryIPsNullPrivate(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "private_ip"), @@ -2743,7 +2922,7 @@ func TestAccEC2Instance_NewNetworkInterface_emptyPrivateIPAndSecondaryPrivateIPs ), }, { - Config: testAccInstanceConfigPrivateIPAndSecondaryIPsNullPrivate(rName, secondaryIP), + Config: testAccInstanceConfig_privateIPAndSecondaryIPsNullPrivate(rName, secondaryIP), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "private_ip"), @@ -2775,7 +2954,7 @@ func TestAccEC2Instance_NewNetworkInterface_privateIPAndSecondaryPrivateIPs(t *t CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, secondaryIPs), + Config: testAccInstanceConfig_privateIPAndSecondaryIPs(rName, privateIP, secondaryIPs), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "private_ip", privateIP), @@ -2808,7 +2987,7 @@ func TestAccEC2Instance_NewNetworkInterface_privateIPAndSecondaryPrivateIPsUpdat CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, secondaryIPs), + Config: testAccInstanceConfig_privateIPAndSecondaryIPs(rName, privateIP, secondaryIPs), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "private_ip", privateIP), @@ -2816,7 +2995,7 @@ func TestAccEC2Instance_NewNetworkInterface_privateIPAndSecondaryPrivateIPsUpdat ), }, { - Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, ""), + Config: testAccInstanceConfig_privateIPAndSecondaryIPs(rName, privateIP, ""), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "private_ip"), @@ -2824,7 +3003,7 @@ func TestAccEC2Instance_NewNetworkInterface_privateIPAndSecondaryPrivateIPsUpdat ), }, { - Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, secondaryIP), + Config: testAccInstanceConfig_privateIPAndSecondaryIPs(rName, privateIP, secondaryIP), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "private_ip", privateIP), @@ -2854,7 +3033,7 @@ func TestAccEC2Instance_AssociatePublic_defaultPrivate(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_defaultPrivate(rName), + Config: testAccInstanceConfig_associatePublicDefaultPrivate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), @@ -2884,7 +3063,7 @@ func TestAccEC2Instance_AssociatePublic_defaultPublic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_defaultPublic(rName), + Config: testAccInstanceConfig_associatePublicDefaultPublic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), @@ -2914,7 +3093,7 @@ func TestAccEC2Instance_AssociatePublic_explicitPublic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_explicitPublic(rName), + Config: testAccInstanceConfig_associatePublicExplicitPublic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), @@ -2944,7 +3123,7 @@ func TestAccEC2Instance_AssociatePublic_explicitPrivate(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_explicitPrivate(rName), + Config: testAccInstanceConfig_associatePublicExplicitPrivate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), @@ -2974,7 +3153,7 @@ func TestAccEC2Instance_AssociatePublic_overridePublic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_overridePublic(rName), + Config: testAccInstanceConfig_associatePublicOverridePublic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), @@ -3004,7 +3183,7 @@ func TestAccEC2Instance_AssociatePublic_overridePrivate(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_overridePrivate(rName), + Config: testAccInstanceConfig_associatePublicOverridePrivate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), @@ -3036,7 +3215,7 @@ func TestAccEC2Instance_LaunchTemplate_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_WithTemplate_Basic(rName), + Config: testAccInstanceConfig_templateBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", launchTemplateResourceName, "id"), @@ -3065,7 +3244,7 @@ func TestAccEC2Instance_LaunchTemplate_overrideTemplate(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_WithTemplate_OverrideTemplate(rName), + Config: testAccInstanceConfig_templateOverrideTemplate(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", launchTemplateResourceName, "id"), @@ -3090,7 +3269,7 @@ func TestAccEC2Instance_LaunchTemplate_setSpecificVersion(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_WithTemplate_Basic(rName), + Config: testAccInstanceConfig_templateBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v1), resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", launchTemplateResourceName, "id"), @@ -3098,7 +3277,7 @@ func TestAccEC2Instance_LaunchTemplate_setSpecificVersion(t *testing.T) { ), }, { - Config: testAccInstanceConfig_WithTemplate_SpecificVersion(rName), + Config: testAccInstanceConfig_templateSpecificVersion(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v2), testAccCheckInstanceNotRecreated(&v1, &v2), @@ -3123,7 +3302,7 @@ func TestAccEC2Instance_LaunchTemplateModifyTemplate_defaultVersion(t *testing.T CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_WithTemplate_Basic(rName), + Config: testAccInstanceConfig_templateBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v1), resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", launchTemplateResourceName, "id"), @@ -3131,7 +3310,7 @@ func TestAccEC2Instance_LaunchTemplateModifyTemplate_defaultVersion(t *testing.T ), }, { - Config: testAccInstanceConfig_WithTemplate_ModifyTemplate(rName), + Config: testAccInstanceConfig_templateModifyTemplate(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v2), testAccCheckInstanceNotRecreated(&v1, &v2), @@ -3156,7 +3335,7 @@ func TestAccEC2Instance_LaunchTemplate_updateTemplateVersion(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_WithTemplate_SpecificVersion(rName), + Config: testAccInstanceConfig_templateSpecificVersion(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v1), resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", launchTemplateResourceName, "id"), @@ -3164,7 +3343,7 @@ func TestAccEC2Instance_LaunchTemplate_updateTemplateVersion(t *testing.T) { ), }, { - Config: testAccInstanceConfig_WithTemplate_UpdateVersion(rName), + Config: testAccInstanceConfig_templateUpdateVersion(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v2), testAccCheckInstanceRecreated(&v1, &v2), @@ -3189,7 +3368,7 @@ func TestAccEC2Instance_LaunchTemplate_swapIDAndName(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_WithTemplate_Basic(rName), + Config: testAccInstanceConfig_templateBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v1), resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", launchTemplateResourceName, "id"), @@ -3197,7 +3376,7 @@ func TestAccEC2Instance_LaunchTemplate_swapIDAndName(t *testing.T) { ), }, { - Config: testAccInstanceConfig_WithTemplate_WithName(rName), + Config: testAccInstanceConfig_templateName(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &v2), testAccCheckInstanceNotRecreated(&v1, &v2), @@ -3209,6 +3388,29 @@ func TestAccEC2Instance_LaunchTemplate_swapIDAndName(t *testing.T) { }) } +func TestAccEC2Instance_LaunchTemplate_spotAndStop(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + launchTemplateResourceName := "aws_launch_template.test" + rName := sdkacctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_templateSpotAndStop(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", launchTemplateResourceName, "id"), + ), + }, + }, + }) +} + func TestAccEC2Instance_GetPasswordData_falseToTrue(t *testing.T) { var before, after ec2.Instance resourceName := "aws_instance.test" @@ -3311,7 +3513,7 @@ func TestAccEC2Instance_CreditSpecificationEmpty_nonBurstable(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_Empty_NonBurstable(rName), + Config: testAccInstanceConfig_creditSpecificationEmptyNonBurstable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -3339,7 +3541,7 @@ func TestAccEC2Instance_CreditSpecificationUnspecifiedToEmpty_nonBurstable(t *te CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_Unspecified_NonBurstable(rName), + Config: testAccInstanceConfig_creditSpecificationUnspecifiedNonBurstable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), ), @@ -3351,7 +3553,7 @@ func TestAccEC2Instance_CreditSpecificationUnspecifiedToEmpty_nonBurstable(t *te ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfig_CreditSpecification_Empty_NonBurstable(rName), + Config: testAccInstanceConfig_creditSpecificationEmptyNonBurstable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), ), @@ -3372,7 +3574,7 @@ func TestAccEC2Instance_CreditSpecification_unspecifiedDefaultsToStandard(t *tes CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_creditSpecification_unspecified(rName), + Config: testAccInstanceConfig_creditSpecificationUnspecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3401,7 +3603,7 @@ func TestAccEC2Instance_CreditSpecification_standardCPUCredits(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_standardCPUCredits(rName), + Config: testAccInstanceConfig_creditSpecificationStandardCPUCredits(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &first), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3415,7 +3617,7 @@ func TestAccEC2Instance_CreditSpecification_standardCPUCredits(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfig_creditSpecification_unspecified(rName), + Config: testAccInstanceConfig_creditSpecificationUnspecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &second), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3438,7 +3640,7 @@ func TestAccEC2Instance_CreditSpecification_unlimitedCPUCredits(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_unlimitedCPUCredits(rName), + Config: testAccInstanceConfig_creditSpecificationUnlimitedCPUCredits(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &first), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3452,7 +3654,7 @@ func TestAccEC2Instance_CreditSpecification_unlimitedCPUCredits(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfig_creditSpecification_unspecified(rName), + Config: testAccInstanceConfig_creditSpecificationUnspecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &second), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3475,7 +3677,7 @@ func TestAccEC2Instance_CreditSpecificationUnknownCPUCredits_t2(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_unknownCPUCredits(rName, "t2.micro"), + Config: testAccInstanceConfig_creditSpecificationUnknownCPUCredits(rName, "t2.micro"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3504,7 +3706,65 @@ func TestAccEC2Instance_CreditSpecificationUnknownCPUCredits_t3(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_unknownCPUCredits(rName, "t3.micro"), + Config: testAccInstanceConfig_creditSpecificationUnknownCPUCredits(rName, "t3.micro"), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), + resource.TestCheckResourceAttr(resourceName, "credit_specification.0.cpu_credits", "unlimited"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, + }, + }, + }) +} + +func TestAccEC2Instance_CreditSpecificationUnknownCPUCredits_t3a(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_creditSpecificationUnknownCPUCredits(rName, "t3a.micro"), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), + resource.TestCheckResourceAttr(resourceName, "credit_specification.0.cpu_credits", "unlimited"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, + }, + }, + }) +} + +func TestAccEC2Instance_CreditSpecificationUnknownCPUCredits_t4g(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_creditSpecificationUnknownCPUCredits(rName, "t4g.micro"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3533,7 +3793,7 @@ func TestAccEC2Instance_CreditSpecification_updateCPUCredits(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_standardCPUCredits(rName), + Config: testAccInstanceConfig_creditSpecificationStandardCPUCredits(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &first), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3547,7 +3807,7 @@ func TestAccEC2Instance_CreditSpecification_updateCPUCredits(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfig_CreditSpecification_unlimitedCPUCredits(rName), + Config: testAccInstanceConfig_creditSpecificationUnlimitedCPUCredits(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &second), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3555,7 +3815,7 @@ func TestAccEC2Instance_CreditSpecification_updateCPUCredits(t *testing.T) { ), }, { - Config: testAccInstanceConfig_CreditSpecification_standardCPUCredits(rName), + Config: testAccInstanceConfig_creditSpecificationStandardCPUCredits(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &third), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3578,7 +3838,7 @@ func TestAccEC2Instance_CreditSpecification_isNotAppliedToNonBurstable(t *testin CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_creditSpecification_isNotAppliedToNonBurstable(rName), + Config: testAccInstanceConfig_creditSpecificationIsNotAppliedToNonBurstable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -3605,7 +3865,7 @@ func TestAccEC2Instance_CreditSpecificationT3_unspecifiedDefaultsToUnlimited(t * CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_creditSpecification_unspecified_t3(rName), + Config: testAccInstanceConfig_creditSpecificationUnspecifiedT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3634,7 +3894,7 @@ func TestAccEC2Instance_CreditSpecificationT3_standardCPUCredits(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_standardCPUCreditsT3(rName), + Config: testAccInstanceConfig_creditSpecificationStandardCPUCreditsT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &first), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3648,7 +3908,7 @@ func TestAccEC2Instance_CreditSpecificationT3_standardCPUCredits(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfig_creditSpecification_unspecified_t3(rName), + Config: testAccInstanceConfig_creditSpecificationUnspecifiedT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &second), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3671,7 +3931,7 @@ func TestAccEC2Instance_CreditSpecificationT3_unlimitedCPUCredits(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_unlimitedCPUCreditsT3(rName), + Config: testAccInstanceConfig_creditSpecificationUnlimitedCPUCreditsT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &first), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3685,7 +3945,7 @@ func TestAccEC2Instance_CreditSpecificationT3_unlimitedCPUCredits(t *testing.T) ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfig_creditSpecification_unspecified_t3(rName), + Config: testAccInstanceConfig_creditSpecificationUnspecifiedT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &second), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3708,7 +3968,7 @@ func TestAccEC2Instance_CreditSpecificationT3_updateCPUCredits(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_standardCPUCreditsT3(rName), + Config: testAccInstanceConfig_creditSpecificationStandardCPUCreditsT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &first), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3722,7 +3982,7 @@ func TestAccEC2Instance_CreditSpecificationT3_updateCPUCredits(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfig_CreditSpecification_unlimitedCPUCreditsT3(rName), + Config: testAccInstanceConfig_creditSpecificationUnlimitedCPUCreditsT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &second), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3730,7 +3990,7 @@ func TestAccEC2Instance_CreditSpecificationT3_updateCPUCredits(t *testing.T) { ), }, { - Config: testAccInstanceConfig_CreditSpecification_standardCPUCreditsT3(rName), + Config: testAccInstanceConfig_creditSpecificationStandardCPUCreditsT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &third), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3753,7 +4013,7 @@ func TestAccEC2Instance_CreditSpecificationStandardCPUCredits_t2Tot3Taint(t *tes CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_standardCPUCredits(rName), + Config: testAccInstanceConfig_creditSpecificationStandardCPUCredits(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3767,7 +4027,7 @@ func TestAccEC2Instance_CreditSpecificationStandardCPUCredits_t2Tot3Taint(t *tes ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfig_CreditSpecification_standardCPUCreditsT3(rName), + Config: testAccInstanceConfig_creditSpecificationStandardCPUCreditsT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3791,7 +4051,7 @@ func TestAccEC2Instance_CreditSpecificationUnlimitedCPUCredits_t2Tot3Taint(t *te CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CreditSpecification_unlimitedCPUCredits(rName), + Config: testAccInstanceConfig_creditSpecificationUnlimitedCPUCredits(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3805,7 +4065,7 @@ func TestAccEC2Instance_CreditSpecificationUnlimitedCPUCredits_t2Tot3Taint(t *te ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfig_CreditSpecification_unlimitedCPUCreditsT3(rName), + Config: testAccInstanceConfig_creditSpecificationUnlimitedCPUCreditsT3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), @@ -3829,7 +4089,7 @@ func TestAccEC2Instance_UserData(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithUserData(rName, "hello world"), + Config: testAccInstanceConfig_userData(rName, "hello world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -3856,13 +4116,13 @@ func TestAccEC2Instance_UserData_update(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithUserData(rName, "hello world"), + Config: testAccInstanceConfig_userData(rName, "hello world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), }, { - Config: testAccInstanceConfigWithUserData(rName, "new world"), + Config: testAccInstanceConfig_userData(rName, "new world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -3889,13 +4149,13 @@ func TestAccEC2Instance_UserData_stringToEncodedString(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithUserData(rName, "hello world"), + Config: testAccInstanceConfig_userData(rName, "hello world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), }, { - Config: testAccInstanceConfigWithUserDataBase64Encoded(rName, "new world"), + Config: testAccInstanceConfig_userDataBase64Encoded(rName, "new world"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -3922,7 +4182,7 @@ func TestAccEC2Instance_UserData_emptyStringToUnspecified(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_UserData_EmptyString(rName), + Config: testAccInstanceConfig_userDataEmptyString(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -3935,7 +4195,7 @@ func TestAccEC2Instance_UserData_emptyStringToUnspecified(t *testing.T) { }, // Switching should show no difference { - Config: testAccInstanceConfig_UserData_Unspecified(rName), + Config: testAccInstanceConfig_userDataUnspecified(rName), ExpectNonEmptyPlan: false, PlanOnly: true, }, @@ -3955,7 +4215,7 @@ func TestAccEC2Instance_UserData_unspecifiedToEmptyString(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_UserData_Unspecified(rName), + Config: testAccInstanceConfig_userDataUnspecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -3968,7 +4228,7 @@ func TestAccEC2Instance_UserData_unspecifiedToEmptyString(t *testing.T) { }, // Switching should show no difference { - Config: testAccInstanceConfig_UserData_EmptyString(rName), + Config: testAccInstanceConfig_userDataEmptyString(rName), ExpectNonEmptyPlan: false, PlanOnly: true, }, @@ -3988,7 +4248,7 @@ func TestAccEC2Instance_UserDataReplaceOnChange_On(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_UserData_Specified_With_Replace_Flag(rName, "TestData1", "true"), + Config: testAccInstanceConfig_userDataSpecifiedReplaceFlag(rName, "TestData1", "true"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance1), ), @@ -4001,7 +4261,7 @@ func TestAccEC2Instance_UserDataReplaceOnChange_On(t *testing.T) { }, // Switching should force a recreate { - Config: testAccInstanceConfig_UserData_Specified_With_Replace_Flag(rName, "TestData2", "true"), + Config: testAccInstanceConfig_userDataSpecifiedReplaceFlag(rName, "TestData2", "true"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance2), testAccCheckInstanceRecreated(&instance1, &instance2), @@ -4023,7 +4283,7 @@ func TestAccEC2Instance_UserDataReplaceOnChange_On_Base64(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_UserData64_Specified_With_Replace_Flag(rName, "3dc39dda39be1205215e776bad998da361a5955d", "true"), + Config: testAccInstanceConfig_userData64SpecifiedReplaceFlag(rName, "3dc39dda39be1205215e776bad998da361a5955d", "true"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance1), ), @@ -4036,7 +4296,7 @@ func TestAccEC2Instance_UserDataReplaceOnChange_On_Base64(t *testing.T) { }, // Switching should force a recreate { - Config: testAccInstanceConfig_UserData64_Specified_With_Replace_Flag(rName, "3dc39dda39be1205215e776bad998da361a5955e", "true"), + Config: testAccInstanceConfig_userData64SpecifiedReplaceFlag(rName, "3dc39dda39be1205215e776bad998da361a5955e", "true"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance2), testAccCheckInstanceRecreated(&instance1, &instance2), @@ -4058,7 +4318,7 @@ func TestAccEC2Instance_UserDataReplaceOnChange_Off(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_UserData_Specified_With_Replace_Flag(rName, "TestData1", "false"), + Config: testAccInstanceConfig_userDataSpecifiedReplaceFlag(rName, "TestData1", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance1), ), @@ -4071,7 +4331,7 @@ func TestAccEC2Instance_UserDataReplaceOnChange_Off(t *testing.T) { }, // Switching should not force a recreate { - Config: testAccInstanceConfig_UserData_Specified_With_Replace_Flag(rName, "TestData2", "false"), + Config: testAccInstanceConfig_userDataSpecifiedReplaceFlag(rName, "TestData2", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance2), testAccCheckInstanceNotRecreated(&instance1, &instance2), @@ -4093,7 +4353,7 @@ func TestAccEC2Instance_UserDataReplaceOnChange_Off_Base64(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_UserData64_Specified_With_Replace_Flag(rName, "3dc39dda39be1205215e776bad998da361a5955d", "false"), + Config: testAccInstanceConfig_userData64SpecifiedReplaceFlag(rName, "3dc39dda39be1205215e776bad998da361a5955d", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance1), ), @@ -4106,7 +4366,7 @@ func TestAccEC2Instance_UserDataReplaceOnChange_Off_Base64(t *testing.T) { }, // Switching should not force a recreate { - Config: testAccInstanceConfig_UserData64_Specified_With_Replace_Flag(rName, "3dc39dda39be1205215e776bad998da361a5955e", "false"), + Config: testAccInstanceConfig_userData64SpecifiedReplaceFlag(rName, "3dc39dda39be1205215e776bad998da361a5955e", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance2), testAccCheckInstanceNotRecreated(&instance1, &instance2), @@ -4128,7 +4388,7 @@ func TestAccEC2Instance_hibernation(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigHibernation(rName, true), + Config: testAccInstanceConfig_hibernation(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "hibernation", "true"), @@ -4141,7 +4401,7 @@ func TestAccEC2Instance_hibernation(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigHibernation(rName, false), + Config: testAccInstanceConfig_hibernation(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v2), testAccCheckInstanceRecreated(&v1, &v2), @@ -4164,7 +4424,7 @@ func TestAccEC2Instance_metadataOptions(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigMetadataOptions(rName), + Config: testAccInstanceConfig_metadataOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "metadata_options.#", "1"), @@ -4175,7 +4435,7 @@ func TestAccEC2Instance_metadataOptions(t *testing.T) { ), }, { - Config: testAccInstanceConfigMetadataOptionsUpdated(rName), + Config: testAccInstanceConfig_metadataOptionsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "metadata_options.#", "1"), @@ -4207,7 +4467,7 @@ func TestAccEC2Instance_enclaveOptions(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigEnclaveOptions(rName, true), + Config: testAccInstanceConfig_enclaveOptions(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "enclave_options.#", "1"), @@ -4221,7 +4481,7 @@ func TestAccEC2Instance_enclaveOptions(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change"}, }, { - Config: testAccInstanceConfigEnclaveOptions(rName, false), + Config: testAccInstanceConfig_enclaveOptions(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v2), testAccCheckInstanceRecreated(&v1, &v2), @@ -4245,7 +4505,7 @@ func TestAccEC2Instance_CapacityReservation_unspecifiedDefaultsToOpen(t *testing CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigCapacityReservationSpecification_unspecified(rName), + Config: testAccInstanceConfig_capacityReservationSpecificationUnspecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.#", "1"), @@ -4261,7 +4521,7 @@ func TestAccEC2Instance_CapacityReservation_unspecifiedDefaultsToOpen(t *testing }, // Adding 'open' preference should show no difference { - Config: testAccInstanceConfigCapacityReservationSpecification_preference(rName, "open"), + Config: testAccInstanceConfig_capacityReservationSpecificationPreference(rName, "open"), ExpectNonEmptyPlan: false, PlanOnly: true, }, @@ -4281,7 +4541,7 @@ func TestAccEC2Instance_CapacityReservationPreference_open(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigCapacityReservationSpecification_preference(rName, "open"), + Config: testAccInstanceConfig_capacityReservationSpecificationPreference(rName, "open"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.#", "1"), @@ -4311,7 +4571,7 @@ func TestAccEC2Instance_CapacityReservationPreference_none(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigCapacityReservationSpecification_preference(rName, "none"), + Config: testAccInstanceConfig_capacityReservationSpecificationPreference(rName, "none"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.#", "1"), @@ -4341,7 +4601,7 @@ func TestAccEC2Instance_CapacityReservation_targetID(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigCapacityReservationSpecification_targetId(rName), + Config: testAccInstanceConfig_capacityReservationSpecificationTargetID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.0.capacity_reservation_target.#", "1"), @@ -4372,7 +4632,7 @@ func TestAccEC2Instance_CapacityReservation_modifyPreference(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigCapacityReservationSpecification_preference(rName, "open"), + Config: testAccInstanceConfig_capacityReservationSpecificationPreference(rName, "open"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.#", "1"), @@ -4380,13 +4640,13 @@ func TestAccEC2Instance_CapacityReservation_modifyPreference(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.0.capacity_reservation_target.#", "0"), ), }, - {Config: testAccInstanceConfigCapacityReservationSpecification_preference(rName, "open"), + {Config: testAccInstanceConfig_capacityReservationSpecificationPreference(rName, "open"), Check: resource.ComposeTestCheckFunc( testAccCheckStopInstance(&original), // Stop instance to modify capacity reservation ), }, { - Config: testAccInstanceConfigCapacityReservationSpecification_preference(rName, "none"), + Config: testAccInstanceConfig_capacityReservationSpecificationPreference(rName, "none"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &updated), testAccCheckInstanceNotRecreated(&original, &updated), @@ -4412,7 +4672,7 @@ func TestAccEC2Instance_CapacityReservation_modifyTarget(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigCapacityReservationSpecification_preference(rName, "none"), + Config: testAccInstanceConfig_capacityReservationSpecificationPreference(rName, "none"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &original), resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.#", "1"), @@ -4420,13 +4680,13 @@ func TestAccEC2Instance_CapacityReservation_modifyTarget(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.0.capacity_reservation_target.#", "0"), ), }, - {Config: testAccInstanceConfigCapacityReservationSpecification_preference(rName, "none"), + {Config: testAccInstanceConfig_capacityReservationSpecificationPreference(rName, "none"), Check: resource.ComposeTestCheckFunc( testAccCheckStopInstance(&original), // Stop instance to modify capacity reservation ), }, { - Config: testAccInstanceConfigCapacityReservationSpecification_targetId(rName), + Config: testAccInstanceConfig_capacityReservationSpecificationTargetID(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &updated), testAccCheckInstanceNotRecreated(&original, &updated), @@ -4539,28 +4799,29 @@ func testAccCheckDetachVolumes(instance *ec2.Instance) resource.TestCheckFunc { client := acctest.Provider.Meta().(*conns.AWSClient) conn := client.EC2Conn - for _, bd := range instance.BlockDeviceMappings { - if bd.Ebs != nil && bd.Ebs.VolumeId != nil { - name := aws.StringValue(bd.DeviceName) - volID := aws.StringValue(bd.Ebs.VolumeId) + for _, v := range instance.BlockDeviceMappings { + if v.Ebs != nil && v.Ebs.VolumeId != nil { + deviceName := aws.StringValue(v.DeviceName) instanceID := aws.StringValue(instance.InstanceId) + volumeID := aws.StringValue(v.Ebs.VolumeId) - // Make sure in correct state before detaching - if err := tfec2.WaitVolumeAttachmentAttached(conn, name, volID, instanceID); err != nil { + // Make sure in correct state before detaching. + if _, err := tfec2.WaitVolumeAttachmentCreated(conn, volumeID, instanceID, deviceName, 5*time.Minute); err != nil { return err } r := tfec2.ResourceVolumeAttachment() d := r.Data(nil) - d.Set("device_name", name) - d.Set("volume_id", volID) + d.Set("device_name", deviceName) d.Set("instance_id", instanceID) + d.Set("volume_id", volumeID) if err := r.Delete(d, client); err != nil { return err } } } + return nil } } @@ -4847,9 +5108,9 @@ resource "aws_subnet" "test" { `, rName)) } -func testAccInstanceConfigBasic() string { +func testAccInstanceConfig_basic() string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-classic-platform.html#ec2-classic-instance-types acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro", "t1.micro", "m1.small"), ` @@ -4861,8 +5122,8 @@ resource "aws_instance" "test" { `) } -func testAccInstanceConfigTags1(tagKey1, tagValue1 string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_tags1(tagKey1, tagValue1 string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t2.small" @@ -4874,8 +5135,8 @@ resource "aws_instance" "test" { `, tagKey1, tagValue1)) } -func testAccInstanceConfigTags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t2.small" @@ -4891,7 +5152,7 @@ resource "aws_instance" "test" { func testAccInstanceConfig_inDefaultVPCBySgName(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` data "aws_vpc" "default" { default = true @@ -4916,10 +5177,10 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_inDefaultVPCBySgId(rName string) string { +func testAccInstanceConfig_inDefaultVPCBySGID(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` data "aws_vpc" "default" { default = true @@ -4944,10 +5205,10 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_ec2Classic() string { // nosempgrep:ec2-in-func-name +func testAccInstanceConfig_classic() string { // nosempgrep:ec2-in-func-name return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t1.micro", "m3.medium", "m3.large", "c3.large", "r3.large"), ` resource "aws_instance" "test" { @@ -4959,7 +5220,7 @@ resource "aws_instance" "test" { func testAccInstanceConfig_atLeastOneOtherEBSVolume(rName string) string { return acctest.ConfigCompose( - testAccLatestAmazonLinuxHVMInstanceStoreAMIConfig(), + testAccAMIDataSourceConfig_latestAmazonLinuxHVMInstanceStore(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` # Ensure that there is at least 1 EBS volume in the current region. @@ -4990,9 +5251,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigWithUserData(rName, userData string) string { +func testAccInstanceConfig_userData(rName, userData string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5009,9 +5270,9 @@ resource "aws_instance" "test" { `, rName, userData)) } -func testAccInstanceConfigWithUserDataBase64Encoded(rName, userData string) string { +func testAccInstanceConfig_userDataBase64Encoded(rName, userData string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5028,9 +5289,9 @@ resource "aws_instance" "test" { `, rName, userData)) } -func testAccInstanceConfigWithUserDataBase64(rName, userData string) string { +func testAccInstanceConfig_userDataBase64(rName, userData string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5047,9 +5308,9 @@ resource "aws_instance" "test" { `, rName, userData)) } -func testAccInstanceConfigWithUserDataBase64_Base64EncodedFile(rName, filename string) string { +func testAccInstanceConfig_userDataBase64Base64EncodedFile(rName, filename string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5066,9 +5327,9 @@ resource "aws_instance" "test" { `, rName, filename)) } -func testAccInstanceConfigWithSmallInstanceType(rName string) string { +func testAccInstanceConfig_smallType(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5084,9 +5345,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigUpdateInstanceType(rName string) string { +func testAccInstanceConfig_updateType(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5102,9 +5363,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigInstanceTypeAndUserData(rName, instanceType, userData string) string { +func testAccInstanceConfig_typeAndUserData(rName, instanceType, userData string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5121,9 +5382,9 @@ resource "aws_instance" "test" { `, rName, instanceType, userData)) } -func testAccInstanceConfigInstanceTypeAndUserDataBase64(rName, instanceType, userData string) string { +func testAccInstanceConfig_typeAndUserDataBase64(rName, instanceType, userData string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5140,8 +5401,8 @@ resource "aws_instance" "test" { `, rName, instanceType, userData)) } -func testAccInstanceGP2IopsDevice(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_gp2IOPSDevice(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t2.medium" @@ -5158,8 +5419,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceGP2WithIopsValue(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_gp2IOPSValue(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t2.medium" @@ -5178,8 +5439,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigRootInstanceStore(rName string) string { - return acctest.ConfigCompose(testAccLatestAmazonLinuxHVMInstanceStoreAMIConfig(), fmt.Sprintf(` +func testAccInstanceConfig_rootStore(rName string) string { + return acctest.ConfigCompose(testAccAMIDataSourceConfig_latestAmazonLinuxHVMInstanceStore(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-instance-store.id @@ -5195,9 +5456,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigNoAMIEphemeralDevices(rName string) string { +func testAccInstanceConfig_noAMIEphemeralDevices(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5226,7 +5487,7 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceEBSRootDeviceBasic(rName string) string { +func testAccInstanceConfig_ebsRootDeviceBasic(rName string) string { return acctest.ConfigCompose(testAccInstanceAMIWithEBSRootVolume, fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.ami.id @@ -5240,11 +5501,11 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceRootBlockDevice(rName, size, delete, volumeType string) string { - return testAccInstanceRootBlockDeviceWithIOPS(rName, size, delete, volumeType, "") +func testAccInstanceConfig_rootBlockDevice(rName, size, delete, volumeType string) string { + return testAccInstanceConfig_rootBlockDeviceIOPS(rName, size, delete, volumeType, "") } -func testAccInstanceRootBlockDeviceWithIOPS(rName, size, delete, volumeType, iops string) string { +func testAccInstanceConfig_rootBlockDeviceIOPS(rName, size, delete, volumeType, iops string) string { if iops == "" { iops = "null" } @@ -5269,7 +5530,7 @@ resource "aws_instance" "test" { `, rName, size, delete, volumeType, iops)) } -func testAccInstanceRootBlockDeviceWithThroughput(rName, size, delete, volumeType, throughput string) string { +func testAccInstanceConfig_rootBlockDeviceThroughput(rName, size, delete, volumeType, throughput string) string { if throughput == "" { throughput = "null" } @@ -5294,8 +5555,8 @@ resource "aws_instance" "test" { `, rName, size, delete, volumeType, throughput)) } -func testAccInstanceConfigGP3RootBlockDevice(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_gp3RootBlockDevice(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t2.medium" @@ -5336,16 +5597,16 @@ data "aws_ami" "ami" { } ` -func testAccInstanceBlockDevicesConfig(rName, size string) string { - return testAccInstanceBlockDevicesWithDeleteOnTerminateConfig(rName, size, "") +func testAccInstanceConfig_blockDevices(rName, size string) string { + return testAccInstanceConfig_blockDevicesDeleteOnTerminate(rName, size, "") } -func testAccInstanceBlockDevicesWithDeleteOnTerminateConfig(rName, size, delete string) string { +func testAccInstanceConfig_blockDevicesDeleteOnTerminate(rName, size, delete string) string { if delete == "" { delete = "null" } - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -5404,9 +5665,9 @@ resource "aws_instance" "test" { `, rName, size, delete)) } -func testAccInstanceConfigSourceDestEnable(rName string) string { +func testAccInstanceConfig_sourceDestEnable(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5421,9 +5682,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigSourceDestDisable(rName string) string { +func testAccInstanceConfig_sourceDestDisable(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5439,9 +5700,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceAutoRecoveryConfig(rName string, val string) string { +func testAccInstanceConfig_autoRecovery(rName string, val string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5459,9 +5720,27 @@ resource "aws_instance" "test" { `, rName, val)) } -func testAccInstanceConfigDisableAPITermination(rName string, val bool) string { +func testAccInstanceConfig_disableAPIStop(rName string, val bool) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccInstanceVPCConfig(rName, false, 0), + fmt.Sprintf(` +resource "aws_instance" "test" { + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.small" + subnet_id = aws_subnet.test.id + disable_api_stop = %[2]t + + tags = { + Name = %[1]q + } +} +`, rName, val)) +} + +func testAccInstanceConfig_disableAPITermination(rName string, val bool) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5479,7 +5758,7 @@ resource "aws_instance" "test" { func testAccInstanceConfig_dedicated(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), // Prevent frequent errors like // "InsufficientInstanceCapacity: We currently do not have sufficient m1.small capacity in the Availability Zone you requested (us-west-2a)." testAccInstanceVPCConfig(rName, false, 1), @@ -5502,8 +5781,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigOutpost(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_outpost(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` data "aws_outposts_outposts" "test" {} data "aws_outposts_outpost" "test" { @@ -5550,9 +5829,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigPlacementGroup(rName string) string { +func testAccInstanceConfig_placementGroup(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_placement_group" "test" { @@ -5578,9 +5857,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigPlacementPartitionNumber(rName string) string { +func testAccInstanceConfig_placementPartitionNumber(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_placement_group" "test" { @@ -5608,9 +5887,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_ipv6ErrorConfig(rName string) string { +func testAccInstanceConfig_ipv6Error(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCIPv6Config(rName), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5629,7 +5908,7 @@ resource "aws_instance" "test" { func testAccInstanceConfig_ipv6Support(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCIPv6Config(rName), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5645,9 +5924,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_ipv6SupportWithv4(rName string) string { +func testAccInstanceConfig_ipv6Supportv4(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCIPv6Config(rName), fmt.Sprintf(` resource "aws_instance" "test" { @@ -5665,7 +5944,7 @@ resource "aws_instance" "test" { } func testAccInstanceConfig_ebsKMSKeyARN(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 } @@ -5698,7 +5977,7 @@ resource "aws_instance" "test" { func testAccInstanceConfig_rootBlockDeviceKMSKeyARN(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_kms_key" "test" { @@ -5723,10 +6002,10 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsAttachedVolumeWithTags(rName string) string { +func testAccInstanceConfig_blockDeviceTagsAttachedVolumeTags(rName string) string { // https://github.com/hashicorp/terraform-provider-aws/issues/17074 return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), fmt.Sprintf(` @@ -5759,10 +6038,10 @@ resource "aws_volume_attachment" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsAttachedVolumeWithTagsUpdate(rName string) string { +func testAccInstanceConfig_blockDeviceTagsAttachedVolumeTagsUpdate(rName string) string { // https://github.com/hashicorp/terraform-provider-aws/issues/17074 return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), fmt.Sprintf(` @@ -5795,8 +6074,8 @@ resource "aws_volume_attachment" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsRootTagsConflict(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_blockDeviceTagsRootTagsConflict(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -5827,8 +6106,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsEBSTagsConflict(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_blockDeviceTagsEBSTagsConflict(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -5859,8 +6138,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsNoVolumeTags(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_blockDeviceTagsNoVolumeTags(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -5901,8 +6180,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsEBSTags(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_blockDeviceTagsEBSTags(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -5938,8 +6217,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsEBSAndRootTags(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_blockDeviceTagsEBSAndRootTags(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -5980,8 +6259,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsEBSAndRootTagsUpdate(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_blockDeviceTagsEBSAndRootTagsUpdate(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -6022,7 +6301,7 @@ resource "aws_instance" "test" { `, rName)) } -var testAccInstanceConfigEBSBlockDeviceInvalidIops = acctest.ConfigCompose(testAccInstanceAMIWithEBSRootVolume, ` +var testAccInstanceConfig_ebsBlockDeviceInvalidIOPS = acctest.ConfigCompose(testAccInstanceAMIWithEBSRootVolume, ` resource "aws_instance" "test" { ami = data.aws_ami.ami.id @@ -6037,7 +6316,7 @@ resource "aws_instance" "test" { } `) -var testAccInstanceConfigEBSBlockDeviceInvalidThroughput = acctest.ConfigCompose(testAccInstanceAMIWithEBSRootVolume, ` +var testAccInstanceConfig_ebsBlockDeviceInvalidThroughput = acctest.ConfigCompose(testAccInstanceAMIWithEBSRootVolume, ` resource "aws_instance" "test" { ami = data.aws_ami.ami.id @@ -6052,8 +6331,8 @@ resource "aws_instance" "test" { } `) -func testAccInstanceConfigEBSAndRootBlockDevice(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_ebsAndRootBlockDevice(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -6077,8 +6356,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsVolumeTags(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_blockDeviceTagsVolumeTags(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -6123,8 +6402,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigBlockDeviceTagsVolumeTagsUpdate(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_blockDeviceTagsVolumeTagsUpdate(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -6170,8 +6449,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigWithoutInstanceProfile(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_noProfile(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -6206,8 +6485,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigWithInstanceProfile(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_profile(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -6248,8 +6527,8 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigWithInstanceProfilePath(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_profilePath(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` data "aws_partition" "current" {} resource "aws_iam_role" "test" { @@ -6293,9 +6572,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigPrivateIP(rName string) string { +func testAccInstanceConfig_privateIP(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6311,9 +6590,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigEmptyPrivateIP(rName string) string { +func testAccInstanceConfig_emptyPrivateIP(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6329,9 +6608,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigAssociatePublicIPAndPrivateIP(rName string) string { +func testAccInstanceConfig_associatePublicIPAndPrivateIP(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6348,9 +6627,80 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceNetworkInstanceSecurityGroups(rName string) string { +func testAccInstancePrivateDNSNameOptionsBaseConfig(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigAvailableAZsNoOptInDefaultExclude(), + fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + assign_generated_ipv6_cidr_block = true + + tags = { + Name = %[1]q + } +} + +resource "aws_subnet" "test" { + cidr_block = cidrsubnet(aws_vpc.test.cidr_block, 8, 0) + vpc_id = aws_vpc.test.id + availability_zone = data.aws_availability_zones.available.names[2] + ipv6_cidr_block = cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1) + assign_ipv6_address_on_creation = true + + enable_resource_name_dns_aaaa_record_on_launch = true + enable_resource_name_dns_a_record_on_launch = true + private_dns_hostname_type_on_launch = "resource-name" + + tags = { + Name = %[1]q + } +} +`, rName)) +} + +func testAccInstanceConfig_PrivateDNSNameOptions_computed(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccInstancePrivateDNSNameOptionsBaseConfig(rName), + fmt.Sprintf(` +resource "aws_instance" "test" { + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + subnet_id = aws_subnet.test.id + + tags = { + Name = %[1]q + } +} +`, rName)) +} + +func testAccInstanceConfig_PrivateDNSNameOptions_configured(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccInstancePrivateDNSNameOptionsBaseConfig(rName), + fmt.Sprintf(` +resource "aws_instance" "test" { + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + subnet_id = aws_subnet.test.id + + private_dns_name_options { + enable_resource_name_dns_aaaa_record = false + enable_resource_name_dns_a_record = true + hostname_type = "ip-name" + } + + tags = { + Name = %[1]q + } +} +`, rName)) +} + +func testAccInstanceConfig_networkSecurityGroups(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), testAccInstanceVPCSecurityGroupConfig(rName), fmt.Sprintf(` @@ -6379,9 +6729,9 @@ resource "aws_eip" "test" { `, rName)) } -func testAccInstanceNetworkInstanceVPCSecurityGroupIDs(rName string) string { +func testAccInstanceConfig_networkVPCSecurityGroupIDs(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), testAccInstanceVPCSecurityGroupConfig(rName), fmt.Sprintf(` @@ -6409,9 +6759,9 @@ resource "aws_eip" "test" { `, rName)) } -func testAccInstanceNetworkInstanceVPCRemoveSecurityGroupIDs(rName string) string { +func testAccInstanceConfig_networkVPCRemoveSecurityGroupIDs(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), testAccInstanceVPCSecurityGroupConfig(rName), fmt.Sprintf(` @@ -6439,9 +6789,9 @@ resource "aws_eip" "test" { `, rName)) } -func testAccInstanceConfigKeyPair(rName, publicKey string) string { +func testAccInstanceConfig_keyPair(rName, publicKey string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_key_pair" "test" { key_name = %[1]q @@ -6460,7 +6810,7 @@ resource "aws_instance" "test" { `, rName, publicKey)) } -func testAccInstanceConfigRootBlockDeviceMismatch(rName string) string { +func testAccInstanceConfig_rootBlockDeviceMismatch(rName string) string { return acctest.ConfigCompose( testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6482,9 +6832,9 @@ resource "aws_instance" "test" { `, rName)) //lintignore:AWSAT002 } -func testAccInstanceConfigForceNewAndTagsDrift(rName string) string { +func testAccInstanceConfig_forceNewAndTagsDrift(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6499,9 +6849,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigForceNewAndTagsDrift_Update(rName string) string { +func testAccInstanceConfig_forceNewAndTagsDriftUpdate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6516,9 +6866,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigPrimaryNetworkInterface(rName string) string { +func testAccInstanceConfig_primaryNetworkInterface(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_network_interface" "test" { @@ -6546,9 +6896,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigNetworkCardIndex(rName string) string { +func testAccInstanceConfig_networkCardIndex(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_network_interface" "test" { @@ -6577,9 +6927,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigPrimaryNetworkInterfaceSourceDestCheck(rName string) string { +func testAccInstanceConfig_primaryNetworkInterfaceSourceDestCheck(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_network_interface" "test" { @@ -6608,9 +6958,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigAddSecondaryNetworkInterfaceBefore(rName string) string { +func testAccInstanceConfig_addSecondaryNetworkInterfaceBefore(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_network_interface" "primary" { @@ -6647,9 +6997,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigAddSecondaryNetworkInterfaceAfter(rName string) string { +func testAccInstanceConfig_addSecondaryNetworkInterfaceAfter(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_network_interface" "primary" { @@ -6692,9 +7042,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigAddSecurityGroupBefore(rName string) string { +func testAccInstanceConfig_addSecurityGroupBefore(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_subnet" "test2" { @@ -6752,9 +7102,9 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccInstanceConfigAddSecurityGroupAfter(rName string) string { +func testAccInstanceConfig_addSecurityGroupAfter(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_subnet" "test2" { @@ -6813,9 +7163,9 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccInstanceConfigPublicAndPrivateSecondaryIPs(rName string, isPublic bool) string { +func testAccInstanceConfig_publicAndPrivateSecondaryIPs(rName string, isPublic bool) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_security_group" "test" { @@ -6844,9 +7194,9 @@ resource "aws_instance" "test" { `, rName, isPublic)) } -func testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, secondaryIPs string) string { +func testAccInstanceConfig_privateIPAndSecondaryIPs(rName, privateIP, secondaryIPs string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_security_group" "test" { @@ -6874,9 +7224,9 @@ resource "aws_instance" "test" { `, rName, privateIP, secondaryIPs)) } -func testAccInstanceConfigPrivateIPAndSecondaryIPsNullPrivate(rName, secondaryIPs string) string { +func testAccInstanceConfig_privateIPAndSecondaryIPsNullPrivate(rName, secondaryIPs string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_security_group" "test" { @@ -6904,9 +7254,9 @@ resource "aws_instance" "test" { `, rName, secondaryIPs)) } -func testAccInstanceConfig_associatePublic_defaultPrivate(rName string) string { +func testAccInstanceConfig_associatePublicDefaultPrivate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6921,9 +7271,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_associatePublic_defaultPublic(rName string) string { +func testAccInstanceConfig_associatePublicDefaultPublic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, true, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6938,9 +7288,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_associatePublic_explicitPublic(rName string) string { +func testAccInstanceConfig_associatePublicExplicitPublic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, true, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6956,9 +7306,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_associatePublic_explicitPrivate(rName string) string { +func testAccInstanceConfig_associatePublicExplicitPrivate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, true, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6974,9 +7324,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_associatePublic_overridePublic(rName string) string { +func testAccInstanceConfig_associatePublicOverridePublic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -6992,9 +7342,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_associatePublic_overridePrivate(rName string) string { +func testAccInstanceConfig_associatePublicOverridePrivate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, true, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7031,9 +7381,9 @@ resource "aws_instance" "test" { `, rName, publicKey, val)) } -func testAccInstanceConfig_CreditSpecification_Empty_NonBurstable(rName string) string { +func testAccInstanceConfig_creditSpecificationEmptyNonBurstable(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7050,9 +7400,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_CreditSpecification_Unspecified_NonBurstable(rName string) string { +func testAccInstanceConfig_creditSpecificationUnspecifiedNonBurstable(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7067,9 +7417,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_creditSpecification_unspecified(rName string) string { +func testAccInstanceConfig_creditSpecificationUnspecified(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7084,9 +7434,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_creditSpecification_unspecified_t3(rName string) string { +func testAccInstanceConfig_creditSpecificationUnspecifiedT3(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7101,9 +7451,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_CreditSpecification_standardCPUCredits(rName string) string { +func testAccInstanceConfig_creditSpecificationStandardCPUCredits(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7122,9 +7472,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_CreditSpecification_standardCPUCreditsT3(rName string) string { +func testAccInstanceConfig_creditSpecificationStandardCPUCreditsT3(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7143,9 +7493,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_CreditSpecification_unlimitedCPUCredits(rName string) string { +func testAccInstanceConfig_creditSpecificationUnlimitedCPUCredits(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7164,9 +7514,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_CreditSpecification_unlimitedCPUCreditsT3(rName string) string { +func testAccInstanceConfig_creditSpecificationUnlimitedCPUCreditsT3(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7185,14 +7535,14 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_creditSpecification_isNotAppliedToNonBurstable(rName string) string { +func testAccInstanceConfig_creditSpecificationIsNotAppliedToNonBurstable(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id - instance_type = "t2.small" + instance_type = "c6i.large" subnet_id = aws_subnet.test.id credit_specification { @@ -7206,13 +7556,23 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_CreditSpecification_unknownCPUCredits(rName, instanceType string) string { +func testAccInstanceConfig_creditSpecificationUnknownCPUCredits(rName, instanceType string) string { + var amiConfig, amiIDRef string + + if v, err := tfec2.ParseInstanceType(instanceType); err == nil && v.Type == "t4g" { + amiConfig = acctest.ConfigLatestAmazonLinux2HVMEBSARM64AMI() + amiIDRef = "data.aws_ami.amzn2-ami-minimal-hvm-ebs-arm64.id" + } else { + amiConfig = acctest.ConfigLatestAmazonLinux2HVMEBSX8664AMI() + amiIDRef = "data.aws_ami.amzn2-ami-minimal-hvm-ebs-x86_64.id" + } + return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + amiConfig, testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { - ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + ami = %[3]s instance_type = %[2]q subnet_id = aws_subnet.test.id @@ -7222,12 +7582,12 @@ resource "aws_instance" "test" { Name = %[1]q } } -`, rName, instanceType)) +`, rName, instanceType, amiIDRef)) } -func testAccInstanceConfig_UserData_Unspecified(rName string) string { +func testAccInstanceConfig_userDataUnspecified(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7242,9 +7602,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_UserData_EmptyString(rName string) string { +func testAccInstanceConfig_userDataEmptyString(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7260,9 +7620,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_UserData_Specified_With_Replace_Flag(rName string, userData string, replaceOnChange string) string { +func testAccInstanceConfig_userDataSpecifiedReplaceFlag(rName string, userData string, replaceOnChange string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7279,9 +7639,9 @@ resource "aws_instance" "test" { `, rName, userData, replaceOnChange)) } -func testAccInstanceConfig_UserData64_Specified_With_Replace_Flag(rName string, userData string, replaceOnChange string) string { +func testAccInstanceConfig_userData64SpecifiedReplaceFlag(rName string, userData string, replaceOnChange string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7298,9 +7658,9 @@ resource "aws_instance" "test" { `, rName, userData, replaceOnChange)) } -func testAccInstanceConfigHibernation(rName string, hibernation bool) string { +func testAccInstanceConfig_hibernation(rName string, hibernation bool) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -7338,9 +7698,9 @@ resource "aws_instance" "test" { `, rName, hibernation)) } -func testAccInstanceConfigMetadataOptions(rName string) string { +func testAccInstanceConfig_metadataOptions(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -7360,9 +7720,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigMetadataOptionsUpdated(rName string) string { +func testAccInstanceConfig_metadataOptionsUpdated(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -7385,9 +7745,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigEnclaveOptions(rName string, enabled bool) string { +func testAccInstanceConfig_enclaveOptions(rName string, enabled bool) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccInstanceVPCConfig(rName, false, 0), acctest.AvailableEC2InstanceTypeForRegion("c5a.xlarge", "c5.xlarge"), fmt.Sprintf(` @@ -7407,7 +7767,7 @@ resource "aws_instance" "test" { `, rName, enabled)) } -func testAccInstanceDynamicEBSBlockDevicesConfig(rName string) string { +func testAccInstanceConfig_dynamicEBSBlockDevices(rName string) string { return acctest.ConfigCompose(testAccLatestAmazonLinuxPVEBSAMIConfig(), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-pv-ebs.id @@ -7432,9 +7792,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigCapacityReservationSpecification_unspecified(rName string) string { +func testAccInstanceConfig_capacityReservationSpecificationUnspecified(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7448,9 +7808,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfigCapacityReservationSpecification_preference(rName, crPreference string) string { +func testAccInstanceConfig_capacityReservationSpecificationPreference(rName, crPreference string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { @@ -7468,9 +7828,9 @@ resource "aws_instance" "test" { `, rName, crPreference)) } -func testAccInstanceConfigCapacityReservationSpecification_targetId(rName string) string { +func testAccInstanceConfig_capacityReservationSpecificationTargetID(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t2.micro"), fmt.Sprintf(` @@ -7502,9 +7862,9 @@ resource "aws_ec2_capacity_reservation" "test" { `, rName, ec2.CapacityReservationInstancePlatformLinuxUnix)) } -func testAccInstanceConfig_WithTemplate_Basic(rName string) string { +func testAccInstanceConfig_templateBasic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro", "t1.micro", "m1.small"), fmt.Sprintf(` resource "aws_launch_template" "test" { @@ -7525,9 +7885,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_WithTemplate_OverrideTemplate(rName string) string { +func testAccInstanceConfig_templateOverrideTemplate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegionNamed("micro", "t3.micro", "t2.micro", "t1.micro", "m1.small"), acctest.AvailableEC2InstanceTypeForRegionNamed("small", "t3.small", "t2.small", "t1.small", "m1.medium"), fmt.Sprintf(` @@ -7551,9 +7911,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_WithTemplate_SpecificVersion(rName string) string { +func testAccInstanceConfig_templateSpecificVersion(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro", "t1.micro", "m1.small"), fmt.Sprintf(` resource "aws_launch_template" "test" { @@ -7575,9 +7935,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_WithTemplate_ModifyTemplate(rName string) string { +func testAccInstanceConfig_templateModifyTemplate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.small", "t2.small", "t1.small", "m1.medium"), fmt.Sprintf(` resource "aws_launch_template" "test" { @@ -7598,9 +7958,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_WithTemplate_UpdateVersion(rName string) string { +func testAccInstanceConfig_templateUpdateVersion(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.small", "t2.small", "t1.small", "m1.medium"), fmt.Sprintf(` resource "aws_launch_template" "test" { @@ -7624,9 +7984,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccInstanceConfig_WithTemplate_WithName(rName string) string { +func testAccInstanceConfig_templateName(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro", "t1.micro", "m1.small"), fmt.Sprintf(` resource "aws_launch_template" "test" { @@ -7646,3 +8006,35 @@ resource "aws_instance" "test" { } `, rName)) } + +func testAccInstanceConfig_templateSpotAndStop(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro", "t1.micro", "m1.small"), + fmt.Sprintf(` +resource "aws_launch_template" "test" { + name = %[1]q + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = data.aws_ec2_instance_type_offering.available.instance_type + + instance_market_options { + market_type = "spot" + + spot_options { + instance_interruption_behavior = "stop" + spot_instance_type = "persistent" + } + } +} + +resource "aws_instance" "test" { + launch_template { + name = aws_launch_template.test.name + } + + tags = { + Name = %[1]q + } +} +`, rName)) +} diff --git a/internal/service/ec2/ec2_instance_type_data_source.go b/internal/service/ec2/ec2_instance_type_data_source.go index a660865283b..c22ab56c6cd 100644 --- a/internal/service/ec2/ec2_instance_type_data_source.go +++ b/internal/service/ec2/ec2_instance_type_data_source.go @@ -1,13 +1,10 @@ package ec2 import ( - "fmt" - "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func DataSourceInstanceType() *schema.Resource { @@ -19,125 +16,99 @@ func DataSourceInstanceType() *schema.Resource { Type: schema.TypeBool, Computed: true, }, - "bare_metal": { Type: schema.TypeBool, Computed: true, }, - "burstable_performance_supported": { Type: schema.TypeBool, Computed: true, }, - "current_generation": { Type: schema.TypeBool, Computed: true, }, - "dedicated_hosts_supported": { Type: schema.TypeBool, Computed: true, }, - "default_cores": { Type: schema.TypeInt, Computed: true, - Optional: true, }, - "default_threads_per_core": { Type: schema.TypeInt, Computed: true, - Optional: true, }, - "default_vcpus": { Type: schema.TypeInt, Computed: true, }, - "ebs_encryption_support": { Type: schema.TypeString, Computed: true, }, - "ebs_nvme_support": { Type: schema.TypeString, Computed: true, }, - "ebs_optimized_support": { Type: schema.TypeString, Computed: true, }, - "ebs_performance_baseline_bandwidth": { Type: schema.TypeInt, Computed: true, }, - "ebs_performance_baseline_throughput": { Type: schema.TypeFloat, Computed: true, }, - "ebs_performance_baseline_iops": { Type: schema.TypeInt, Computed: true, }, - "ebs_performance_maximum_bandwidth": { Type: schema.TypeInt, Computed: true, }, - "ebs_performance_maximum_throughput": { Type: schema.TypeFloat, Computed: true, }, - "ebs_performance_maximum_iops": { Type: schema.TypeInt, Computed: true, }, - "efa_supported": { Type: schema.TypeBool, Computed: true, }, - "ena_support": { Type: schema.TypeString, Computed: true, }, - "encryption_in_transit_supported": { Type: schema.TypeBool, Computed: true, }, - "fpgas": { Type: schema.TypeSet, Computed: true, - Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "count": { Type: schema.TypeInt, Computed: true, }, - "manufacturer": { Type: schema.TypeString, Computed: true, }, - "memory_size": { Type: schema.TypeInt, Computed: true, }, - "name": { Type: schema.TypeString, Computed: true, @@ -145,15 +116,12 @@ func DataSourceInstanceType() *schema.Resource { }, }, }, - "free_tier_eligible": { Type: schema.TypeBool, Computed: true, }, - "gpus": { Type: schema.TypeSet, - Optional: true, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -161,17 +129,14 @@ func DataSourceInstanceType() *schema.Resource { Type: schema.TypeInt, Computed: true, }, - "manufacturer": { Type: schema.TypeString, Computed: true, }, - "memory_size": { Type: schema.TypeInt, Computed: true, }, - "name": { Type: schema.TypeString, Computed: true, @@ -179,58 +144,47 @@ func DataSourceInstanceType() *schema.Resource { }, }, }, - "hibernation_supported": { Type: schema.TypeBool, Computed: true, }, - "hypervisor": { Type: schema.TypeString, Computed: true, - Optional: true, }, - "inference_accelerators": { Type: schema.TypeSet, Computed: true, - Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "count": { Type: schema.TypeInt, Computed: true, }, - - "name": { + "manufacturer": { Type: schema.TypeString, Computed: true, }, - - "manufacturer": { + "name": { Type: schema.TypeString, Computed: true, }, }, }, }, - "instance_disks": { Type: schema.TypeSet, Computed: true, - Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "count": { Type: schema.TypeInt, Computed: true, }, - "size": { Type: schema.TypeInt, Computed: true, }, - "type": { Type: schema.TypeString, Computed: true, @@ -238,107 +192,84 @@ func DataSourceInstanceType() *schema.Resource { }, }, }, - "instance_storage_supported": { Type: schema.TypeBool, Computed: true, }, - "instance_type": { Type: schema.TypeString, Required: true, }, - "ipv6_supported": { Type: schema.TypeBool, Computed: true, }, - "maximum_ipv4_addresses_per_interface": { Type: schema.TypeInt, Computed: true, }, - "maximum_ipv6_addresses_per_interface": { Type: schema.TypeInt, Computed: true, - Optional: true, }, - "maximum_network_interfaces": { Type: schema.TypeInt, Computed: true, }, - "memory_size": { Type: schema.TypeInt, Computed: true, }, - "network_performance": { Type: schema.TypeString, Computed: true, }, - "supported_architectures": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "supported_placement_strategies": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "supported_root_device_types": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "supported_usages_classes": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "supported_virtualization_types": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "sustained_clock_speed": { Type: schema.TypeFloat, Computed: true, }, - "total_fpga_memory": { Type: schema.TypeInt, Computed: true, - Optional: true, }, - "total_gpu_memory": { Type: schema.TypeInt, Computed: true, - Optional: true, }, - "total_instance_storage": { Type: schema.TypeInt, Computed: true, - Optional: true, }, - "valid_cores": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeInt}, }, - "valid_threads_per_core": { Type: schema.TypeList, Computed: true, @@ -351,23 +282,13 @@ func DataSourceInstanceType() *schema.Resource { func dataSourceInstanceTypeRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - params := &ec2.DescribeInstanceTypesInput{} - - instanceType := d.Get("instance_type").(string) - params.InstanceTypes = []*string{aws.String(instanceType)} - log.Printf("[DEBUG] Reading instances types: %s", params) + v, err := FindInstanceTypeByName(conn, d.Get("instance_type").(string)) - resp, err := conn.DescribeInstanceTypes(params) if err != nil { - return err - } - if len(resp.InstanceTypes) == 0 { - return fmt.Errorf("no Instance Type found for %s", instanceType) - } - if len(resp.InstanceTypes) > 1 { - return fmt.Errorf("multiple instance types found for type %s", instanceType) + return tfresource.SingularDataSourceFindError("EC2 Instance Type", err) } - v := resp.InstanceTypes[0] + + d.SetId(aws.StringValue(v.InstanceType)) d.Set("auto_recovery_supported", v.AutoRecoverySupported) d.Set("bare_metal", v.BareMetal) d.Set("burstable_performance_supported", v.BurstablePerformanceSupported) @@ -464,6 +385,6 @@ func dataSourceInstanceTypeRead(d *schema.ResourceData, meta interface{}) error d.Set("sustained_clock_speed", v.ProcessorInfo.SustainedClockSpeedInGhz) d.Set("valid_cores", v.VCpuInfo.ValidCores) d.Set("valid_threads_per_core", v.VCpuInfo.ValidThreadsPerCore) - d.SetId(aws.StringValue(v.InstanceType)) + return nil } diff --git a/internal/service/ec2/ec2_instance_type_data_source_test.go b/internal/service/ec2/ec2_instance_type_data_source_test.go index a814f4b9984..11f954cb098 100644 --- a/internal/service/ec2/ec2_instance_type_data_source_test.go +++ b/internal/service/ec2/ec2_instance_type_data_source_test.go @@ -9,7 +9,8 @@ import ( ) func TestAccEC2InstanceTypeDataSource_basic(t *testing.T) { - resourceBasic := "data.aws_ec2_instance_type.basic" + dataSourceName := "data.aws_ec2_instance_type.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), @@ -18,50 +19,50 @@ func TestAccEC2InstanceTypeDataSource_basic(t *testing.T) { { Config: testAccInstanceTypeDataSourceConfig_basic, Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr(resourceBasic, "auto_recovery_supported", "true"), - resource.TestCheckResourceAttr(resourceBasic, "bare_metal", "false"), - resource.TestCheckResourceAttr(resourceBasic, "burstable_performance_supported", "false"), - resource.TestCheckResourceAttr(resourceBasic, "current_generation", "true"), - resource.TestCheckResourceAttr(resourceBasic, "dedicated_hosts_supported", "true"), - resource.TestCheckResourceAttr(resourceBasic, "default_cores", "1"), - resource.TestCheckResourceAttr(resourceBasic, "default_threads_per_core", "2"), - resource.TestCheckResourceAttr(resourceBasic, "default_vcpus", "2"), - resource.TestCheckResourceAttr(resourceBasic, "ebs_encryption_support", "supported"), - resource.TestCheckResourceAttr(resourceBasic, "ebs_nvme_support", "required"), - resource.TestCheckResourceAttr(resourceBasic, "ebs_optimized_support", "default"), - resource.TestCheckResourceAttr(resourceBasic, "efa_supported", "false"), - resource.TestCheckResourceAttr(resourceBasic, "ena_support", "required"), - resource.TestCheckResourceAttr(resourceBasic, "encryption_in_transit_supported", "false"), - resource.TestCheckResourceAttr(resourceBasic, "free_tier_eligible", "false"), - resource.TestCheckResourceAttr(resourceBasic, "hibernation_supported", "true"), - resource.TestCheckResourceAttr(resourceBasic, "hypervisor", "nitro"), - resource.TestCheckResourceAttr(resourceBasic, "instance_storage_supported", "false"), - resource.TestCheckResourceAttr(resourceBasic, "instance_type", "m5.large"), - resource.TestCheckResourceAttr(resourceBasic, "ipv6_supported", "true"), - resource.TestCheckResourceAttr(resourceBasic, "maximum_ipv4_addresses_per_interface", "10"), - resource.TestCheckResourceAttr(resourceBasic, "maximum_ipv6_addresses_per_interface", "10"), - resource.TestCheckResourceAttr(resourceBasic, "maximum_network_interfaces", "3"), - resource.TestCheckResourceAttr(resourceBasic, "memory_size", "8192"), - resource.TestCheckResourceAttr(resourceBasic, "network_performance", "Up to 10 Gigabit"), - resource.TestCheckResourceAttr(resourceBasic, "supported_architectures.#", "1"), - resource.TestCheckResourceAttr(resourceBasic, "supported_architectures.0", "x86_64"), - resource.TestCheckResourceAttr(resourceBasic, "supported_placement_strategies.#", "3"), - resource.TestCheckResourceAttr(resourceBasic, "supported_placement_strategies.0", "cluster"), - resource.TestCheckResourceAttr(resourceBasic, "supported_placement_strategies.1", "partition"), - resource.TestCheckResourceAttr(resourceBasic, "supported_placement_strategies.2", "spread"), - resource.TestCheckResourceAttr(resourceBasic, "supported_root_device_types.#", "1"), - resource.TestCheckResourceAttr(resourceBasic, "supported_root_device_types.0", "ebs"), - resource.TestCheckResourceAttr(resourceBasic, "supported_usages_classes.#", "2"), - resource.TestCheckResourceAttr(resourceBasic, "supported_usages_classes.0", "on-demand"), - resource.TestCheckResourceAttr(resourceBasic, "supported_usages_classes.1", "spot"), - resource.TestCheckResourceAttr(resourceBasic, "supported_virtualization_types.#", "1"), - resource.TestCheckResourceAttr(resourceBasic, "supported_virtualization_types.0", "hvm"), - resource.TestCheckResourceAttr(resourceBasic, "sustained_clock_speed", "3.1"), - resource.TestCheckResourceAttr(resourceBasic, "valid_cores.#", "1"), - resource.TestCheckResourceAttr(resourceBasic, "valid_cores.0", "1"), - resource.TestCheckResourceAttr(resourceBasic, "valid_threads_per_core.#", "2"), - resource.TestCheckResourceAttr(resourceBasic, "valid_threads_per_core.0", "1"), - resource.TestCheckResourceAttr(resourceBasic, "valid_threads_per_core.1", "2"), + resource.TestCheckResourceAttr(dataSourceName, "auto_recovery_supported", "true"), + resource.TestCheckResourceAttr(dataSourceName, "bare_metal", "false"), + resource.TestCheckResourceAttr(dataSourceName, "burstable_performance_supported", "false"), + resource.TestCheckResourceAttr(dataSourceName, "current_generation", "true"), + resource.TestCheckResourceAttr(dataSourceName, "dedicated_hosts_supported", "true"), + resource.TestCheckResourceAttr(dataSourceName, "default_cores", "1"), + resource.TestCheckResourceAttr(dataSourceName, "default_threads_per_core", "2"), + resource.TestCheckResourceAttr(dataSourceName, "default_vcpus", "2"), + resource.TestCheckResourceAttr(dataSourceName, "ebs_encryption_support", "supported"), + resource.TestCheckResourceAttr(dataSourceName, "ebs_nvme_support", "required"), + resource.TestCheckResourceAttr(dataSourceName, "ebs_optimized_support", "default"), + resource.TestCheckResourceAttr(dataSourceName, "efa_supported", "false"), + resource.TestCheckResourceAttr(dataSourceName, "ena_support", "required"), + resource.TestCheckResourceAttr(dataSourceName, "encryption_in_transit_supported", "false"), + resource.TestCheckResourceAttr(dataSourceName, "free_tier_eligible", "false"), + resource.TestCheckResourceAttr(dataSourceName, "hibernation_supported", "true"), + resource.TestCheckResourceAttr(dataSourceName, "hypervisor", "nitro"), + resource.TestCheckResourceAttr(dataSourceName, "instance_storage_supported", "false"), + resource.TestCheckResourceAttr(dataSourceName, "instance_type", "m5.large"), + resource.TestCheckResourceAttr(dataSourceName, "ipv6_supported", "true"), + resource.TestCheckResourceAttr(dataSourceName, "maximum_ipv4_addresses_per_interface", "10"), + resource.TestCheckResourceAttr(dataSourceName, "maximum_ipv6_addresses_per_interface", "10"), + resource.TestCheckResourceAttr(dataSourceName, "maximum_network_interfaces", "3"), + resource.TestCheckResourceAttr(dataSourceName, "memory_size", "8192"), + resource.TestCheckResourceAttr(dataSourceName, "network_performance", "Up to 10 Gigabit"), + resource.TestCheckResourceAttr(dataSourceName, "supported_architectures.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "supported_architectures.0", "x86_64"), + resource.TestCheckResourceAttr(dataSourceName, "supported_placement_strategies.#", "3"), + resource.TestCheckResourceAttr(dataSourceName, "supported_placement_strategies.0", "cluster"), + resource.TestCheckResourceAttr(dataSourceName, "supported_placement_strategies.1", "partition"), + resource.TestCheckResourceAttr(dataSourceName, "supported_placement_strategies.2", "spread"), + resource.TestCheckResourceAttr(dataSourceName, "supported_root_device_types.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "supported_root_device_types.0", "ebs"), + resource.TestCheckResourceAttr(dataSourceName, "supported_usages_classes.#", "2"), + resource.TestCheckResourceAttr(dataSourceName, "supported_usages_classes.0", "on-demand"), + resource.TestCheckResourceAttr(dataSourceName, "supported_usages_classes.1", "spot"), + resource.TestCheckResourceAttr(dataSourceName, "supported_virtualization_types.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "supported_virtualization_types.0", "hvm"), + resource.TestCheckResourceAttr(dataSourceName, "sustained_clock_speed", "3.1"), + resource.TestCheckResourceAttr(dataSourceName, "valid_cores.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "valid_cores.0", "1"), + resource.TestCheckResourceAttr(dataSourceName, "valid_threads_per_core.#", "2"), + resource.TestCheckResourceAttr(dataSourceName, "valid_threads_per_core.0", "1"), + resource.TestCheckResourceAttr(dataSourceName, "valid_threads_per_core.1", "2"), ), }, }, @@ -69,7 +70,8 @@ func TestAccEC2InstanceTypeDataSource_basic(t *testing.T) { } func TestAccEC2InstanceTypeDataSource_metal(t *testing.T) { - resourceMetal := "data.aws_ec2_instance_type.metal" + dataSourceName := "data.aws_ec2_instance_type.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), @@ -78,17 +80,17 @@ func TestAccEC2InstanceTypeDataSource_metal(t *testing.T) { { Config: testAccInstanceTypeDataSourceConfig_metal, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceMetal, "ebs_performance_baseline_bandwidth", "19000"), - resource.TestCheckResourceAttr(resourceMetal, "ebs_performance_baseline_throughput", "2375"), - resource.TestCheckResourceAttr(resourceMetal, "ebs_performance_baseline_iops", "80000"), - resource.TestCheckResourceAttr(resourceMetal, "ebs_performance_maximum_bandwidth", "19000"), - resource.TestCheckResourceAttr(resourceMetal, "ebs_performance_maximum_throughput", "2375"), - resource.TestCheckResourceAttr(resourceMetal, "ebs_performance_maximum_iops", "80000"), - resource.TestCheckResourceAttr(resourceMetal, "instance_disks.#", "1"), - resource.TestCheckResourceAttr(resourceMetal, "instance_disks.0.count", "8"), - resource.TestCheckResourceAttr(resourceMetal, "instance_disks.0.size", "7500"), - resource.TestCheckResourceAttr(resourceMetal, "instance_disks.0.type", "ssd"), - resource.TestCheckResourceAttr(resourceMetal, "total_instance_storage", "60000"), + resource.TestCheckResourceAttr(dataSourceName, "ebs_performance_baseline_bandwidth", "19000"), + resource.TestCheckResourceAttr(dataSourceName, "ebs_performance_baseline_throughput", "2375"), + resource.TestCheckResourceAttr(dataSourceName, "ebs_performance_baseline_iops", "80000"), + resource.TestCheckResourceAttr(dataSourceName, "ebs_performance_maximum_bandwidth", "19000"), + resource.TestCheckResourceAttr(dataSourceName, "ebs_performance_maximum_throughput", "2375"), + resource.TestCheckResourceAttr(dataSourceName, "ebs_performance_maximum_iops", "80000"), + resource.TestCheckResourceAttr(dataSourceName, "instance_disks.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "instance_disks.0.count", "8"), + resource.TestCheckResourceAttr(dataSourceName, "instance_disks.0.size", "7500"), + resource.TestCheckResourceAttr(dataSourceName, "instance_disks.0.type", "ssd"), + resource.TestCheckResourceAttr(dataSourceName, "total_instance_storage", "60000"), ), }, }, @@ -96,7 +98,8 @@ func TestAccEC2InstanceTypeDataSource_metal(t *testing.T) { } func TestAccEC2InstanceTypeDataSource_gpu(t *testing.T) { - resourceGpu := "data.aws_ec2_instance_type.gpu" + dataSourceName := "data.aws_ec2_instance_type.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), @@ -105,11 +108,11 @@ func TestAccEC2InstanceTypeDataSource_gpu(t *testing.T) { { Config: testAccInstanceTypeDataSourceConfig_gpu, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceGpu, "gpus.#", "1"), - resource.TestCheckResourceAttr(resourceGpu, "gpus.0.count", "1"), - resource.TestCheckResourceAttr(resourceGpu, "gpus.0.manufacturer", "NVIDIA"), - resource.TestCheckResourceAttr(resourceGpu, "gpus.0.memory_size", "8192"), - resource.TestCheckResourceAttr(resourceGpu, "gpus.0.name", "M60"), + resource.TestCheckResourceAttr(dataSourceName, "gpus.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "gpus.0.count", "1"), + resource.TestCheckResourceAttr(dataSourceName, "gpus.0.manufacturer", "NVIDIA"), + resource.TestCheckResourceAttr(dataSourceName, "gpus.0.memory_size", "8192"), + resource.TestCheckResourceAttr(dataSourceName, "gpus.0.name", "M60"), ), }, }, @@ -117,7 +120,8 @@ func TestAccEC2InstanceTypeDataSource_gpu(t *testing.T) { } func TestAccEC2InstanceTypeDataSource_fpga(t *testing.T) { - resourceFpga := "data.aws_ec2_instance_type.fpga" + dataSourceName := "data.aws_ec2_instance_type.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), @@ -126,12 +130,12 @@ func TestAccEC2InstanceTypeDataSource_fpga(t *testing.T) { { Config: testAccInstanceTypeDataSourceConfig_fgpa, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceFpga, "fpgas.#", "1"), - resource.TestCheckResourceAttr(resourceFpga, "fpgas.0.count", "1"), - resource.TestCheckResourceAttr(resourceFpga, "fpgas.0.manufacturer", "Xilinx"), - resource.TestCheckResourceAttr(resourceFpga, "fpgas.0.memory_size", "65536"), - resource.TestCheckResourceAttr(resourceFpga, "fpgas.0.name", "Virtex UltraScale (VU9P)"), - resource.TestCheckResourceAttr(resourceFpga, "total_fpga_memory", "65536"), + resource.TestCheckResourceAttr(dataSourceName, "fpgas.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "fpgas.0.count", "1"), + resource.TestCheckResourceAttr(dataSourceName, "fpgas.0.manufacturer", "Xilinx"), + resource.TestCheckResourceAttr(dataSourceName, "fpgas.0.memory_size", "65536"), + resource.TestCheckResourceAttr(dataSourceName, "fpgas.0.name", "Virtex UltraScale (VU9P)"), + resource.TestCheckResourceAttr(dataSourceName, "total_fpga_memory", "65536"), ), }, }, @@ -139,25 +143,25 @@ func TestAccEC2InstanceTypeDataSource_fpga(t *testing.T) { } const testAccInstanceTypeDataSourceConfig_basic = ` -data "aws_ec2_instance_type" "basic" { +data "aws_ec2_instance_type" "test" { instance_type = "m5.large" } ` const testAccInstanceTypeDataSourceConfig_metal = ` -data "aws_ec2_instance_type" "metal" { +data "aws_ec2_instance_type" "test" { instance_type = "i3en.metal" } ` const testAccInstanceTypeDataSourceConfig_gpu = ` -data "aws_ec2_instance_type" "gpu" { +data "aws_ec2_instance_type" "test" { instance_type = "g3.4xlarge" } ` const testAccInstanceTypeDataSourceConfig_fgpa = ` -data "aws_ec2_instance_type" "fpga" { +data "aws_ec2_instance_type" "test" { instance_type = "f1.2xlarge" } ` diff --git a/internal/service/ec2/ec2_instance_type_offering_data_source.go b/internal/service/ec2/ec2_instance_type_offering_data_source.go index 2d540d82c96..e4c43c96aba 100644 --- a/internal/service/ec2/ec2_instance_type_offering_data_source.go +++ b/internal/service/ec2/ec2_instance_type_offering_data_source.go @@ -21,13 +21,9 @@ func DataSourceInstanceTypeOffering() *schema.Resource { Computed: true, }, "location_type": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - ec2.LocationTypeAvailabilityZone, - ec2.LocationTypeAvailabilityZoneId, - ec2.LocationTypeRegion, - }, false), + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice(ec2.LocationType_Values(), false), }, "preferred_instance_types": { Type: schema.TypeList, @@ -51,60 +47,40 @@ func dataSourceInstanceTypeOfferingRead(d *schema.ResourceData, meta interface{} input.LocationType = aws.String(v.(string)) } - var foundInstanceTypes []string - - for { - output, err := conn.DescribeInstanceTypeOfferings(input) - - if err != nil { - return fmt.Errorf("error reading EC2 Instance Type Offerings: %w", err) - } - - if output == nil { - break - } - - for _, instanceTypeOffering := range output.InstanceTypeOfferings { - if instanceTypeOffering == nil { - continue - } - - foundInstanceTypes = append(foundInstanceTypes, aws.StringValue(instanceTypeOffering.InstanceType)) - } - - if aws.StringValue(output.NextToken) == "" { - break - } + instanceTypeOfferings, err := FindInstanceTypeOfferings(conn, input) - input.NextToken = output.NextToken + if err != nil { + return fmt.Errorf("reading EC2 Instance Type Offerings: %w", err) } - if len(foundInstanceTypes) == 0 { + if len(instanceTypeOfferings) == 0 { return fmt.Errorf("no EC2 Instance Type Offerings found matching criteria; try different search") } + var foundInstanceTypes []string + + for _, instanceTypeOffering := range instanceTypeOfferings { + foundInstanceTypes = append(foundInstanceTypes, aws.StringValue(instanceTypeOffering.InstanceType)) + } + var resultInstanceType string // Search preferred instance types in their given order and set result // instance type for first match found - if l := d.Get("preferred_instance_types").([]interface{}); len(l) > 0 { - for _, elem := range l { - preferredInstanceType, ok := elem.(string) - - if !ok { - continue - } + if v, ok := d.GetOk("preferred_instance_types"); ok { + for _, v := range v.([]interface{}) { + if v, ok := v.(string); ok { + for _, foundInstanceType := range foundInstanceTypes { + if foundInstanceType == v { + resultInstanceType = v + break + } + } - for _, foundInstanceType := range foundInstanceTypes { - if foundInstanceType == preferredInstanceType { - resultInstanceType = preferredInstanceType + if resultInstanceType != "" { break } } - - if resultInstanceType != "" { - break - } } } @@ -120,9 +96,8 @@ func dataSourceInstanceTypeOfferingRead(d *schema.ResourceData, meta interface{} return fmt.Errorf("no EC2 Instance Type Offerings found matching criteria; try different search") } - d.Set("instance_type", resultInstanceType) - d.SetId(resultInstanceType) + d.Set("instance_type", resultInstanceType) return nil } diff --git a/internal/service/ec2/ec2_instance_type_offering_data_source_test.go b/internal/service/ec2/ec2_instance_type_offering_data_source_test.go index 92d139f5854..5cfbd1bee50 100644 --- a/internal/service/ec2/ec2_instance_type_offering_data_source_test.go +++ b/internal/service/ec2/ec2_instance_type_offering_data_source_test.go @@ -3,24 +3,22 @@ package ec2_test import ( "testing" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/acctest" - "github.com/hashicorp/terraform-provider-aws/internal/conns" ) func TestAccEC2InstanceTypeOfferingDataSource_filter(t *testing.T) { dataSourceName := "data.aws_ec2_instance_type_offering.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckInstanceTypeOffering(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckInstanceTypeOfferings(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccInstanceTypeOfferingFilterDataSourceConfig(), + Config: testAccInstanceTypeOfferingDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "instance_type"), ), @@ -33,13 +31,13 @@ func TestAccEC2InstanceTypeOfferingDataSource_locationType(t *testing.T) { dataSourceName := "data.aws_ec2_instance_type_offering.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckInstanceTypeOffering(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckInstanceTypeOfferings(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccInstanceTypeOfferingLocationTypeDataSourceConfig(), + Config: testAccInstanceTypeOfferingDataSourceConfig_location(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "instance_type"), ), @@ -52,13 +50,13 @@ func TestAccEC2InstanceTypeOfferingDataSource_preferredInstanceTypes(t *testing. dataSourceName := "data.aws_ec2_instance_type_offering.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckInstanceTypeOffering(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckInstanceTypeOfferings(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccInstanceTypeOfferingPreferredInstanceTypesDataSourceConfig(), + Config: testAccInstanceTypeOfferingDataSourceConfig_preferreds(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "instance_type", "t3.micro"), ), @@ -67,25 +65,7 @@ func TestAccEC2InstanceTypeOfferingDataSource_preferredInstanceTypes(t *testing. }) } -func testAccPreCheckInstanceTypeOffering(t *testing.T) { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - - input := &ec2.DescribeInstanceTypeOfferingsInput{ - MaxResults: aws.Int64(5), - } - - _, err := conn.DescribeInstanceTypeOfferings(input) - - if acctest.PreCheckSkipError(err) { - t.Skipf("skipping acceptance testing: %s", err) - } - - if err != nil { - t.Fatalf("unexpected PreCheck error: %s", err) - } -} - -func testAccInstanceTypeOfferingFilterDataSourceConfig() string { +func testAccInstanceTypeOfferingDataSourceConfig_filter() string { return ` # Rather than hardcode an instance type in the testing, # use the first result from all available offerings. @@ -100,8 +80,8 @@ data "aws_ec2_instance_type_offering" "test" { ` } -func testAccInstanceTypeOfferingLocationTypeDataSourceConfig() string { - return acctest.ConfigAvailableAZsNoOptIn() + ` +func testAccInstanceTypeOfferingDataSourceConfig_location() string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` # Rather than hardcode an instance type in the testing, # use the first result from all available offerings. data "aws_ec2_instance_type_offerings" "test" { @@ -126,10 +106,10 @@ data "aws_ec2_instance_type_offering" "test" { location_type = "availability-zone" } -` +`) } -func testAccInstanceTypeOfferingPreferredInstanceTypesDataSourceConfig() string { +func testAccInstanceTypeOfferingDataSourceConfig_preferreds() string { return ` data "aws_ec2_instance_type_offering" "test" { filter { diff --git a/internal/service/ec2/ec2_instance_type_offerings_data_source.go b/internal/service/ec2/ec2_instance_type_offerings_data_source.go index b6b36bb4129..d2eababc3a0 100644 --- a/internal/service/ec2/ec2_instance_type_offerings_data_source.go +++ b/internal/service/ec2/ec2_instance_type_offerings_data_source.go @@ -57,39 +57,22 @@ func dataSourceInstanceTypeOfferingsRead(d *schema.ResourceData, meta interface{ var locations []string var locationTypes []string - err := conn.DescribeInstanceTypeOfferingsPages(input, func(page *ec2.DescribeInstanceTypeOfferingsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, instanceTypeOffering := range page.InstanceTypeOfferings { - if instanceTypeOffering == nil { - continue - } - - instanceTypes = append(instanceTypes, aws.StringValue(instanceTypeOffering.InstanceType)) - locations = append(locations, aws.StringValue(instanceTypeOffering.Location)) - locationTypes = append(locationTypes, aws.StringValue(instanceTypeOffering.LocationType)) - } - - return !lastPage - }) + instanceTypeOfferings, err := FindInstanceTypeOfferings(conn, input) if err != nil { - return fmt.Errorf("error reading EC2 Instance Type Offerings: %w", err) + return fmt.Errorf("reading EC2 Instance Type Offerings: %w", err) } - if err := d.Set("instance_types", instanceTypes); err != nil { - return fmt.Errorf("error setting instance_types: %w", err) - } - if err := d.Set("locations", locations); err != nil { - return fmt.Errorf("error setting locations: %w", err) - } - if err := d.Set("location_types", locationTypes); err != nil { - return fmt.Errorf("error setting location_types: %w", err) + for _, instanceTypeOffering := range instanceTypeOfferings { + instanceTypes = append(instanceTypes, aws.StringValue(instanceTypeOffering.InstanceType)) + locations = append(locations, aws.StringValue(instanceTypeOffering.Location)) + locationTypes = append(locationTypes, aws.StringValue(instanceTypeOffering.LocationType)) } d.SetId(meta.(*conns.AWSClient).Region) + d.Set("instance_types", instanceTypes) + d.Set("locations", locations) + d.Set("location_types", locationTypes) return nil } diff --git a/internal/service/ec2/ec2_instance_type_offerings_data_source_test.go b/internal/service/ec2/ec2_instance_type_offerings_data_source_test.go index 803da1ef52e..050156c3cfb 100644 --- a/internal/service/ec2/ec2_instance_type_offerings_data_source_test.go +++ b/internal/service/ec2/ec2_instance_type_offerings_data_source_test.go @@ -1,13 +1,11 @@ package ec2_test import ( - "fmt" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -22,9 +20,11 @@ func TestAccEC2InstanceTypeOfferingsDataSource_filter(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccInstanceTypeOfferingsFilterDataSourceConfig(), + Config: testAccInstanceTypeOfferingsDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( - testAccCheckInstanceTypeOfferingsInstanceTypes(dataSourceName), + acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "instance_types.#", "0"), + acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "locations.#", "0"), + acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "location_types.#", "0"), ), }, }, @@ -41,54 +41,17 @@ func TestAccEC2InstanceTypeOfferingsDataSource_locationType(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccInstanceTypeOfferingsLocationTypeDataSourceConfig(), + Config: testAccInstanceTypeOfferingsDataSourceConfig_location(), Check: resource.ComposeTestCheckFunc( - testAccCheckInstanceTypeOfferingsInstanceTypes(dataSourceName), - testAccCheckInstanceTypeOfferingsLocations(dataSourceName), + acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "instance_types.#", "0"), + acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "locations.#", "0"), + acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "location_types.#", "0"), ), }, }, }) } -func testAccCheckInstanceTypeOfferingsInstanceTypes(dataSourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[dataSourceName] - if !ok { - return fmt.Errorf("Not found: %s", dataSourceName) - } - - if v := rs.Primary.Attributes["instance_types.#"]; v == "0" { - return fmt.Errorf("expected at least one instance_types result, got none") - } - - if v := rs.Primary.Attributes["locations.#"]; v == "0" { - return fmt.Errorf("expected at least one locations result, got none") - } - - if v := rs.Primary.Attributes["location_types.#"]; v == "0" { - return fmt.Errorf("expected at least one location_types result, got none") - } - - return nil - } -} - -func testAccCheckInstanceTypeOfferingsLocations(dataSourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[dataSourceName] - if !ok { - return fmt.Errorf("Not found: %s", dataSourceName) - } - - if v := rs.Primary.Attributes["locations.#"]; v == "0" { - return fmt.Errorf("expected at least one locations result, got none") - } - - return nil - } -} - func testAccPreCheckInstanceTypeOfferings(t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn @@ -107,7 +70,7 @@ func testAccPreCheckInstanceTypeOfferings(t *testing.T) { } } -func testAccInstanceTypeOfferingsFilterDataSourceConfig() string { +func testAccInstanceTypeOfferingsDataSourceConfig_filter() string { return ` data "aws_ec2_instance_type_offerings" "test" { filter { @@ -118,7 +81,7 @@ data "aws_ec2_instance_type_offerings" "test" { ` } -func testAccInstanceTypeOfferingsLocationTypeDataSourceConfig() string { +func testAccInstanceTypeOfferingsDataSourceConfig_location() string { return acctest.ConfigAvailableAZsNoOptIn() + ` data "aws_ec2_instance_type_offerings" "test" { filter { diff --git a/internal/service/ec2/ec2_instance_types_data_source.go b/internal/service/ec2/ec2_instance_types_data_source.go index 7a8d97ea40f..e9ca20c4457 100644 --- a/internal/service/ec2/ec2_instance_types_data_source.go +++ b/internal/service/ec2/ec2_instance_types_data_source.go @@ -33,26 +33,16 @@ func dataSourceInstanceTypesRead(d *schema.ResourceData, meta interface{}) error input.Filters = BuildFiltersDataSource(v.(*schema.Set)) } - var instanceTypes []string - - err := conn.DescribeInstanceTypesPages(input, func(page *ec2.DescribeInstanceTypesOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + output, err := FindInstanceTypes(conn, input) - for _, instanceType := range page.InstanceTypes { - if instanceType == nil { - continue - } - - instanceTypes = append(instanceTypes, aws.StringValue(instanceType.InstanceType)) - } + if err != nil { + return fmt.Errorf("reading EC2 Instance Types: %w", err) + } - return !lastPage - }) + var instanceTypes []string - if err != nil { - return fmt.Errorf("error listing EC2 Instance Types: %w", err) + for _, instanceType := range output { + instanceTypes = append(instanceTypes, aws.StringValue(instanceType.InstanceType)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/ec2/ec2_instance_types_data_source_test.go b/internal/service/ec2/ec2_instance_types_data_source_test.go index d8565f29c32..591056be21c 100644 --- a/internal/service/ec2/ec2_instance_types_data_source_test.go +++ b/internal/service/ec2/ec2_instance_types_data_source_test.go @@ -19,7 +19,7 @@ func TestAccEC2InstanceTypesDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccInstanceTypesDataSourceConfig(), + Config: testAccInstanceTypesDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "instance_types.#", "0"), ), @@ -38,7 +38,7 @@ func TestAccEC2InstanceTypesDataSource_filter(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccInstanceTypesDataSourceConfigFilter(), + Config: testAccInstanceTypesDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "instance_types.#", "0"), ), @@ -63,13 +63,13 @@ func testAccPreCheckInstanceTypes(t *testing.T) { } } -func testAccInstanceTypesDataSourceConfig() string { +func testAccInstanceTypesDataSourceConfig_basic() string { return ` data "aws_ec2_instance_types" "test" {} ` } -func testAccInstanceTypesDataSourceConfigFilter() string { +func testAccInstanceTypesDataSourceConfig_filter() string { return ` data "aws_ec2_instance_types" "test" { filter { diff --git a/internal/service/ec2/ec2_instances_data_source_test.go b/internal/service/ec2/ec2_instances_data_source_test.go index 1a4a4097bea..9786a89581b 100644 --- a/internal/service/ec2/ec2_instances_data_source_test.go +++ b/internal/service/ec2/ec2_instances_data_source_test.go @@ -89,7 +89,7 @@ func TestAccEC2InstancesDataSource_empty(t *testing.T) { func testAccInstancesDataSourceConfig_ids(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { @@ -113,7 +113,7 @@ data "aws_instances" "test" { func testAccInstancesDataSourceConfig_tags(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { @@ -140,7 +140,7 @@ data "aws_instances" "test" { func testAccInstancesDataSourceConfig_instanceStateNames(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { diff --git a/internal/service/ec2/ec2_key_pair_data_source_test.go b/internal/service/ec2/ec2_key_pair_data_source_test.go index 5edc58e790e..2e76f0efb49 100644 --- a/internal/service/ec2/ec2_key_pair_data_source_test.go +++ b/internal/service/ec2/ec2_key_pair_data_source_test.go @@ -28,7 +28,7 @@ func TestAccEC2KeyPairDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccKeyPairDataSourceConfig(rName, publicKey), + Config: testAccKeyPairDataSourceConfig_basic(rName, publicKey), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSource1Name, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSource1Name, "fingerprint", resourceName, "fingerprint"), @@ -53,7 +53,7 @@ func TestAccEC2KeyPairDataSource_basic(t *testing.T) { }) } -func testAccKeyPairDataSourceConfig(rName, publicKey string) string { +func testAccKeyPairDataSourceConfig_basic(rName, publicKey string) string { return fmt.Sprintf(` data "aws_key_pair" "by_name" { key_name = aws_key_pair.test.key_name diff --git a/internal/service/ec2/ec2_key_pair_test.go b/internal/service/ec2/ec2_key_pair_test.go index ae62934167b..8ba1ff20338 100644 --- a/internal/service/ec2/ec2_key_pair_test.go +++ b/internal/service/ec2/ec2_key_pair_test.go @@ -33,7 +33,7 @@ func TestAccEC2KeyPair_basic(t *testing.T) { CheckDestroy: testAccCheckKeyPairDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyPairConfig(rName, publicKey), + Config: testAccKeyPairConfig_basic(rName, publicKey), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckKeyPairExists(resourceName, &keyPair), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ec2", fmt.Sprintf("key-pair/%s", rName)), @@ -70,7 +70,7 @@ func TestAccEC2KeyPair_tags(t *testing.T) { CheckDestroy: testAccCheckKeyPairDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyPairTags1Config(rName, publicKey, "key1", "value1"), + Config: testAccKeyPairConfig_tags1(rName, publicKey, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckKeyPairExists(resourceName, &keyPair), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -84,7 +84,7 @@ func TestAccEC2KeyPair_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"public_key"}, }, { - Config: testAccKeyPairTags2Config(rName, publicKey, "key1", "value1updated", "key2", "value2"), + Config: testAccKeyPairConfig_tags2(rName, publicKey, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckKeyPairExists(resourceName, &keyPair), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -93,7 +93,7 @@ func TestAccEC2KeyPair_tags(t *testing.T) { ), }, { - Config: testAccKeyPairTags1Config(rName, publicKey, "key2", "value2"), + Config: testAccKeyPairConfig_tags1(rName, publicKey, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckKeyPairExists(resourceName, &keyPair), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -120,7 +120,7 @@ func TestAccEC2KeyPair_nameGenerated(t *testing.T) { CheckDestroy: testAccCheckKeyPairDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyPairNameGeneratedConfig(publicKey), + Config: testAccKeyPairConfig_nameGenerated(publicKey), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckKeyPairExists(resourceName, &keyPair), create.TestCheckResourceAttrNameGenerated(resourceName, "key_name"), @@ -153,7 +153,7 @@ func TestAccEC2KeyPair_namePrefix(t *testing.T) { CheckDestroy: testAccCheckKeyPairDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckKeyPairNamePrefixConfig("tf-acc-test-prefix-", publicKey), + Config: testAccKeyPairConfig_namePrefix("tf-acc-test-prefix-", publicKey), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckKeyPairExists(resourceName, &keyPair), create.TestCheckResourceAttrNameFromPrefix(resourceName, "key_name", "tf-acc-test-prefix-"), @@ -187,7 +187,7 @@ func TestAccEC2KeyPair_disappears(t *testing.T) { CheckDestroy: testAccCheckKeyPairDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyPairConfig(rName, publicKey), + Config: testAccKeyPairConfig_basic(rName, publicKey), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckKeyPairExists(resourceName, &keyPair), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceKeyPair(), resourceName), @@ -247,7 +247,7 @@ func testAccCheckKeyPairExists(n string, v *ec2.KeyPairInfo) resource.TestCheckF } } -func testAccKeyPairConfig(rName, publicKey string) string { +func testAccKeyPairConfig_basic(rName, publicKey string) string { return fmt.Sprintf(` resource "aws_key_pair" "test" { key_name = %[1]q @@ -256,7 +256,7 @@ resource "aws_key_pair" "test" { `, rName, publicKey) } -func testAccKeyPairTags1Config(rName, publicKey, tagKey1, tagValue1 string) string { +func testAccKeyPairConfig_tags1(rName, publicKey, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_key_pair" "test" { key_name = %[1]q @@ -269,7 +269,7 @@ resource "aws_key_pair" "test" { `, rName, publicKey, tagKey1, tagValue1) } -func testAccKeyPairTags2Config(rName, publicKey, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccKeyPairConfig_tags2(rName, publicKey, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_key_pair" "test" { key_name = %[1]q @@ -283,7 +283,7 @@ resource "aws_key_pair" "test" { `, rName, publicKey, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccKeyPairNameGeneratedConfig(publicKey string) string { +func testAccKeyPairConfig_nameGenerated(publicKey string) string { return fmt.Sprintf(` resource "aws_key_pair" "test" { public_key = %[1]q @@ -291,7 +291,7 @@ resource "aws_key_pair" "test" { `, publicKey) } -func testAccCheckKeyPairNamePrefixConfig(namePrefix, publicKey string) string { +func testAccKeyPairConfig_namePrefix(namePrefix, publicKey string) string { return fmt.Sprintf(` resource "aws_key_pair" "test" { key_name_prefix = %[1]q diff --git a/internal/service/ec2/ec2_launch_template.go b/internal/service/ec2/ec2_launch_template.go index c1cdebeb0b1..aa4cc37b5c6 100644 --- a/internal/service/ec2/ec2_launch_template.go +++ b/internal/service/ec2/ec2_launch_template.go @@ -5,7 +5,6 @@ import ( "fmt" "log" "strconv" - "strings" "time" "github.com/aws/aws-sdk-go/aws" @@ -197,6 +196,10 @@ func ResourceLaunchTemplate() *schema.Resource { Optional: true, ValidateFunc: validation.StringLenBetween(0, 255), }, + "disable_api_stop": { + Type: schema.TypeBool, + Optional: true, + }, "disable_api_termination": { Type: schema.TypeBool, Optional: true, @@ -957,7 +960,6 @@ func resourceLaunchTemplateCreate(d *schema.ResourceData, meta interface{}) erro input := &ec2.CreateLaunchTemplateInput{ ClientToken: aws.String(resource.UniqueId()), LaunchTemplateName: aws.String(name), - LaunchTemplateData: expandRequestLaunchTemplateData(d), TagSpecifications: tagSpecificationsFromKeyValueTags(tags, ec2.ResourceTypeLaunchTemplate), } @@ -965,6 +967,12 @@ func resourceLaunchTemplateCreate(d *schema.ResourceData, meta interface{}) erro input.VersionDescription = aws.String(v.(string)) } + if v, err := expandRequestLaunchTemplateData(conn, d); err == nil { + input.LaunchTemplateData = v + } else { + return err + } + log.Printf("[DEBUG] Creating EC2 Launch Template: %s", input) output, err := conn.CreateLaunchTemplate(input) @@ -1015,7 +1023,7 @@ func resourceLaunchTemplateRead(d *schema.ResourceData, meta interface{}) error d.Set("name", lt.LaunchTemplateName) d.Set("name_prefix", create.NamePrefixFromName(aws.StringValue(lt.LaunchTemplateName))) - if err := flattenResponseLaunchTemplateData(d, ltv.LaunchTemplateData); err != nil { + if err := flattenResponseLaunchTemplateData(conn, d, ltv.LaunchTemplateData); err != nil { return err } @@ -1042,6 +1050,7 @@ func resourceLaunchTemplateUpdate(d *schema.ResourceData, meta interface{}) erro "cpu_options", "credit_specification", "description", + "disable_api_stop", "disable_api_termination", "ebs_optimized", "elastic_gpu_specifications", @@ -1072,15 +1081,20 @@ func resourceLaunchTemplateUpdate(d *schema.ResourceData, meta interface{}) erro if d.HasChanges(updateKeys...) { input := &ec2.CreateLaunchTemplateVersionInput{ - ClientToken: aws.String(resource.UniqueId()), - LaunchTemplateData: expandRequestLaunchTemplateData(d), - LaunchTemplateId: aws.String(d.Id()), + ClientToken: aws.String(resource.UniqueId()), + LaunchTemplateId: aws.String(d.Id()), } if v, ok := d.GetOk("description"); ok { input.VersionDescription = aws.String(v.(string)) } + if v, err := expandRequestLaunchTemplateData(conn, d); err == nil { + input.LaunchTemplateData = v + } else { + return err + } + output, err := conn.CreateLaunchTemplateVersion(input) if err != nil { @@ -1139,7 +1153,7 @@ func resourceLaunchTemplateDelete(d *schema.ResourceData, meta interface{}) erro return nil } -func expandRequestLaunchTemplateData(d *schema.ResourceData) *ec2.RequestLaunchTemplateData { +func expandRequestLaunchTemplateData(conn *ec2.EC2, d *schema.ResourceData) (*ec2.RequestLaunchTemplateData, error) { apiObject := &ec2.RequestLaunchTemplateData{ // Always set at least one field. UserData: aws.String(d.Get("user_data").(string)), @@ -1165,8 +1179,22 @@ func expandRequestLaunchTemplateData(d *schema.ResourceData) *ec2.RequestLaunchT apiObject.CpuOptions = expandLaunchTemplateCPUOptionsRequest(v.([]interface{})[0].(map[string]interface{})) } - if v, ok := d.GetOk("credit_specification"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil && (strings.HasPrefix(instanceType, "t2") || strings.HasPrefix(instanceType, "t3")) { - apiObject.CreditSpecification = expandCreditSpecificationRequest(v.([]interface{})[0].(map[string]interface{})) + if v, ok := d.GetOk("credit_specification"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + if instanceType != "" { + instanceTypeInfo, err := FindInstanceTypeByName(conn, instanceType) + + if err != nil { + return nil, fmt.Errorf("reading EC2 Instance Type (%s): %w", instanceType, err) + } + + if aws.BoolValue(instanceTypeInfo.BurstablePerformanceSupported) { + apiObject.CreditSpecification = expandCreditSpecificationRequest(v.([]interface{})[0].(map[string]interface{})) + } + } + } + + if v, ok := d.GetOk("disable_api_stop"); ok { + apiObject.DisableApiStop = aws.Bool(v.(bool)) } if v, ok := d.GetOk("disable_api_termination"); ok { @@ -1279,7 +1307,7 @@ func expandRequestLaunchTemplateData(d *schema.ResourceData) *ec2.RequestLaunchT apiObject.SecurityGroupIds = flex.ExpandStringSet(v.(*schema.Set)) } - return apiObject + return apiObject, nil } func expandLaunchTemplateBlockDeviceMappingRequest(tfMap map[string]interface{}) *ec2.LaunchTemplateBlockDeviceMappingRequest { @@ -2142,7 +2170,9 @@ func expandLaunchTemplateTagSpecificationRequests(tfList []interface{}) []*ec2.L return apiObjects } -func flattenResponseLaunchTemplateData(d *schema.ResourceData, apiObject *ec2.ResponseLaunchTemplateData) error { +func flattenResponseLaunchTemplateData(conn *ec2.EC2, d *schema.ResourceData, apiObject *ec2.ResponseLaunchTemplateData) error { + instanceType := aws.StringValue(apiObject.InstanceType) + if err := d.Set("block_device_mappings", flattenLaunchTemplateBlockDeviceMappings(apiObject.BlockDeviceMappings)); err != nil { return fmt.Errorf("error setting block_device_mappings: %w", err) } @@ -2160,11 +2190,20 @@ func flattenResponseLaunchTemplateData(d *schema.ResourceData, apiObject *ec2.Re } else { d.Set("cpu_options", nil) } - if apiObject.CreditSpecification != nil && (strings.HasPrefix(aws.StringValue(apiObject.InstanceType), "t2") || strings.HasPrefix(aws.StringValue(apiObject.InstanceType), "t3")) { - if err := d.Set("credit_specification", []interface{}{flattenCreditSpecification(apiObject.CreditSpecification)}); err != nil { - return fmt.Errorf("error setting credit_specification: %w", err) + if apiObject.CreditSpecification != nil && instanceType != "" { + instanceTypeInfo, err := FindInstanceTypeByName(conn, instanceType) + + if err != nil { + return fmt.Errorf("reading EC2 Instance Type (%s): %w", instanceType, err) + } + + if aws.BoolValue(instanceTypeInfo.BurstablePerformanceSupported) { + if err := d.Set("credit_specification", []interface{}{flattenCreditSpecification(apiObject.CreditSpecification)}); err != nil { + return fmt.Errorf("error setting credit_specification: %w", err) + } } } // Don't overwrite any configured value. + d.Set("disable_api_stop", apiObject.DisableApiStop) d.Set("disable_api_termination", apiObject.DisableApiTermination) if apiObject.EbsOptimized != nil { d.Set("ebs_optimized", strconv.FormatBool(aws.BoolValue(apiObject.EbsOptimized))) @@ -2222,7 +2261,7 @@ func flattenResponseLaunchTemplateData(d *schema.ResourceData, apiObject *ec2.Re } else { d.Set("instance_requirements", nil) } - d.Set("instance_type", apiObject.InstanceType) + d.Set("instance_type", instanceType) d.Set("kernel_id", apiObject.KernelId) d.Set("key_name", apiObject.KeyName) if err := d.Set("license_specification", flattenLaunchTemplateLicenseConfigurations(apiObject.LicenseSpecifications)); err != nil { diff --git a/internal/service/ec2/ec2_launch_template_data_source.go b/internal/service/ec2/ec2_launch_template_data_source.go index a2bbb233af2..5c0c7949b4e 100644 --- a/internal/service/ec2/ec2_launch_template_data_source.go +++ b/internal/service/ec2/ec2_launch_template_data_source.go @@ -146,6 +146,10 @@ func DataSourceLaunchTemplate() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "disable_api_stop": { + Type: schema.TypeBool, + Computed: true, + }, "disable_api_termination": { Type: schema.TypeBool, Computed: true, @@ -791,7 +795,7 @@ func dataSourceLaunchTemplateRead(d *schema.ResourceData, meta interface{}) erro d.Set("latest_version", lt.LatestVersionNumber) d.Set("name", lt.LaunchTemplateName) - if err := flattenResponseLaunchTemplateData(d, ltv.LaunchTemplateData); err != nil { + if err := flattenResponseLaunchTemplateData(conn, d, ltv.LaunchTemplateData); err != nil { return err } diff --git a/internal/service/ec2/ec2_launch_template_data_source_test.go b/internal/service/ec2/ec2_launch_template_data_source_test.go index 69a3c046a26..678af2c571e 100644 --- a/internal/service/ec2/ec2_launch_template_data_source_test.go +++ b/internal/service/ec2/ec2_launch_template_data_source_test.go @@ -22,7 +22,7 @@ func TestAccEC2LaunchTemplateDataSource_name(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateDataSourceNameConfig(rName), + Config: testAccLaunchTemplateDataSourceConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "block_device_mappings.#", dataSourceName, "block_device_mappings.#"), @@ -31,6 +31,7 @@ func TestAccEC2LaunchTemplateDataSource_name(t *testing.T) { resource.TestCheckResourceAttrPair(resourceName, "credit_specification.#", dataSourceName, "credit_specification.#"), resource.TestCheckResourceAttrPair(resourceName, "default_version", dataSourceName, "default_version"), resource.TestCheckResourceAttrPair(resourceName, "description", dataSourceName, "description"), + resource.TestCheckResourceAttrPair(resourceName, "disable_api_stop", dataSourceName, "disable_api_stop"), resource.TestCheckResourceAttrPair(resourceName, "disable_api_termination", dataSourceName, "disable_api_termination"), resource.TestCheckResourceAttrPair(resourceName, "ebs_optimized", dataSourceName, "ebs_optimized"), resource.TestCheckResourceAttrPair(resourceName, "elastic_gpu_specifications.#", dataSourceName, "elastic_gpu_specifications.#"), @@ -78,7 +79,7 @@ func TestAccEC2LaunchTemplateDataSource_id(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateDataSourceIDConfig(rName), + Config: testAccLaunchTemplateDataSourceConfig_id(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "id"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "name"), @@ -100,7 +101,7 @@ func TestAccEC2LaunchTemplateDataSource_filter(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateDataSourceFilterConfig(rName), + Config: testAccLaunchTemplateDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "id"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "name"), @@ -122,7 +123,7 @@ func TestAccEC2LaunchTemplateDataSource_tags(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateDataSourceTagsConfig(rName), + Config: testAccLaunchTemplateDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "id"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "name"), @@ -133,9 +134,9 @@ func TestAccEC2LaunchTemplateDataSource_tags(t *testing.T) { }) } -func testAccLaunchTemplateDataSourceNameConfig(rName string) string { +func testAccLaunchTemplateDataSourceConfig_name(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -177,6 +178,7 @@ resource "aws_launch_template" "test" { auto_recovery = "disabled" } + disable_api_stop = true disable_api_termination = true ebs_optimized = false @@ -230,7 +232,7 @@ data "aws_launch_template" "test" { `, rName)) } -func testAccLaunchTemplateDataSourceIDConfig(rName string) string { +func testAccLaunchTemplateDataSourceConfig_id(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -242,7 +244,7 @@ data "aws_launch_template" "test" { `, rName) } -func testAccLaunchTemplateDataSourceFilterConfig(rName string) string { +func testAccLaunchTemplateDataSourceConfig_filter(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -257,7 +259,7 @@ data "aws_launch_template" "test" { `, rName) } -func testAccLaunchTemplateDataSourceTagsConfig(rName string) string { +func testAccLaunchTemplateDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q diff --git a/internal/service/ec2/ec2_launch_template_test.go b/internal/service/ec2/ec2_launch_template_test.go index d94bee1ea41..ac3c607a62b 100644 --- a/internal/service/ec2/ec2_launch_template_test.go +++ b/internal/service/ec2/ec2_launch_template_test.go @@ -28,7 +28,7 @@ func TestAccEC2LaunchTemplate_basic(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateNameConfig(rName), + Config: testAccLaunchTemplateConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`launch-template/.+`)), @@ -38,6 +38,7 @@ func TestAccEC2LaunchTemplate_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "0"), resource.TestCheckResourceAttr(resourceName, "default_version", "1"), resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "disable_api_stop", "false"), resource.TestCheckResourceAttr(resourceName, "disable_api_termination", "false"), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", ""), resource.TestCheckResourceAttr(resourceName, "elastic_gpu_specifications.#", "0"), @@ -90,7 +91,7 @@ func TestAccEC2LaunchTemplate_Name_generated(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateNameGeneratedConfig(), + Config: testAccLaunchTemplateConfig_nameGenerated(), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -117,7 +118,7 @@ func TestAccEC2LaunchTemplate_Name_prefix(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateNamePrefixConfig("tf-acc-test-prefix-"), + Config: testAccLaunchTemplateConfig_namePrefix("tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), @@ -145,7 +146,7 @@ func TestAccEC2LaunchTemplate_disappears(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateNameConfig(rName), + Config: testAccLaunchTemplateConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &launchTemplate), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceLaunchTemplate(), resourceName), @@ -168,7 +169,7 @@ func TestAccEC2LaunchTemplate_BlockDeviceMappings_ebs(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_BlockDeviceMappings_EBS(rName), + Config: testAccLaunchTemplateConfig_blockDeviceMappingsEBS(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "1"), @@ -199,7 +200,7 @@ func TestAccEC2LaunchTemplate_BlockDeviceMappingsEBS_deleteOnTermination(t *test CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_BlockDeviceMappings_EBS_DeleteOnTermination(rName, true), + Config: testAccLaunchTemplateConfig_blockDeviceMappingsEBSDeleteOnTermination(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "1"), @@ -210,7 +211,7 @@ func TestAccEC2LaunchTemplate_BlockDeviceMappingsEBS_deleteOnTermination(t *test ), }, { - Config: testAccLaunchTemplateConfig_BlockDeviceMappings_EBS_DeleteOnTermination(rName, false), + Config: testAccLaunchTemplateConfig_blockDeviceMappingsEBSDeleteOnTermination(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "1"), @@ -241,7 +242,7 @@ func TestAccEC2LaunchTemplate_BlockDeviceMappingsEBS_gp3(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_BlockDeviceMappings_EBS_GP3(rName), + Config: testAccLaunchTemplateConfig_blockDeviceMappingsEBSGP3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "1"), @@ -274,7 +275,7 @@ func TestAccEC2LaunchTemplate_ebsOptimized(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_EBSOptimized(rName, "true"), + Config: testAccLaunchTemplateConfig_ebsOptimized(rName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", "true"), @@ -286,28 +287,28 @@ func TestAccEC2LaunchTemplate_ebsOptimized(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLaunchTemplateConfig_EBSOptimized(rName, "false"), + Config: testAccLaunchTemplateConfig_ebsOptimized(rName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", "false"), ), }, { - Config: testAccLaunchTemplateConfig_EBSOptimized(rName, "\"true\""), + Config: testAccLaunchTemplateConfig_ebsOptimized(rName, "\"true\""), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", "true"), ), }, { - Config: testAccLaunchTemplateConfig_EBSOptimized(rName, "\"false\""), + Config: testAccLaunchTemplateConfig_ebsOptimized(rName, "\"false\""), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", "false"), ), }, { - Config: testAccLaunchTemplateConfig_EBSOptimized(rName, "\"\""), + Config: testAccLaunchTemplateConfig_ebsOptimized(rName, "\"\""), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", ""), @@ -329,7 +330,7 @@ func TestAccEC2LaunchTemplate_elasticInferenceAccelerator(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateElasticInferenceAcceleratorConfig(rName, "eia1.medium"), + Config: testAccLaunchTemplateConfig_elasticInferenceAccelerator(rName, "eia1.medium"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template1), resource.TestCheckResourceAttr(resourceName, "elastic_inference_accelerator.#", "1"), @@ -342,7 +343,7 @@ func TestAccEC2LaunchTemplate_elasticInferenceAccelerator(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLaunchTemplateElasticInferenceAcceleratorConfig(rName, "eia1.large"), + Config: testAccLaunchTemplateConfig_elasticInferenceAccelerator(rName, "eia1.large"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template1), resource.TestCheckResourceAttr(resourceName, "elastic_inference_accelerator.#", "1"), @@ -365,7 +366,7 @@ func TestAccEC2LaunchTemplate_NetworkInterfaces_deleteOnTermination(t *testing.T CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName, "true"), + Config: testAccLaunchTemplateConfig_networkInterfacesDeleteOnTermination(rName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), @@ -374,7 +375,7 @@ func TestAccEC2LaunchTemplate_NetworkInterfaces_deleteOnTermination(t *testing.T ), }, { - Config: testAccLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName, "false"), + Config: testAccLaunchTemplateConfig_networkInterfacesDeleteOnTermination(rName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), @@ -383,7 +384,7 @@ func TestAccEC2LaunchTemplate_NetworkInterfaces_deleteOnTermination(t *testing.T ), }, { - Config: testAccLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName, "\"\""), + Config: testAccLaunchTemplateConfig_networkInterfacesDeleteOnTermination(rName, "\"\""), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), @@ -392,7 +393,7 @@ func TestAccEC2LaunchTemplate_NetworkInterfaces_deleteOnTermination(t *testing.T ), }, { - Config: testAccLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName, "null"), + Config: testAccLaunchTemplateConfig_networkInterfacesDeleteOnTermination(rName, "null"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), @@ -425,6 +426,7 @@ func TestAccEC2LaunchTemplate_data(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "disable_api_stop"), resource.TestCheckResourceAttrSet(resourceName, "disable_api_termination"), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", "false"), resource.TestCheckResourceAttr(resourceName, "elastic_gpu_specifications.#", "1"), @@ -502,7 +504,7 @@ func TestAccEC2LaunchTemplate_update(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_ASG_basic(rName), + Config: testAccLaunchTemplateConfig_asgBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "default_version", "1"), @@ -517,7 +519,7 @@ func TestAccEC2LaunchTemplate_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLaunchTemplateConfig_ASG_update(rName), + Config: testAccLaunchTemplateConfig_asgUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "default_version", "1"), @@ -542,7 +544,7 @@ func TestAccEC2LaunchTemplate_tags(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateTags1Config(rName, "key1", "value1"), + Config: testAccLaunchTemplateConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -555,7 +557,7 @@ func TestAccEC2LaunchTemplate_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLaunchTemplateTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccLaunchTemplateConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -564,7 +566,7 @@ func TestAccEC2LaunchTemplate_tags(t *testing.T) { ), }, { - Config: testAccLaunchTemplateTags1Config(rName, "key2", "value2"), + Config: testAccLaunchTemplateConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -587,7 +589,7 @@ func TestAccEC2LaunchTemplate_CapacityReservation_preference(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_capacityReservation_preference(rName, "open"), + Config: testAccLaunchTemplateConfig_capacityReservationPreference(rName, "open"), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.#", "1"), @@ -616,7 +618,7 @@ func TestAccEC2LaunchTemplate_CapacityReservation_target(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_capacityReservation_target(rName), + Config: testAccLaunchTemplateConfig_capacityReservationTarget(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "capacity_reservation_specification.#", "1"), @@ -739,6 +741,34 @@ func TestAccEC2LaunchTemplate_CreditSpecification_t3(t *testing.T) { }) } +func TestAccEC2LaunchTemplate_CreditSpecification_t4g(t *testing.T) { + var template ec2.LaunchTemplate + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_launch_template.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLaunchTemplateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLaunchTemplateConfig_creditSpecification(rName, "t4g.micro", "unlimited"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLaunchTemplateExists(resourceName, &template), + resource.TestCheckResourceAttr(resourceName, "credit_specification.#", "1"), + resource.TestCheckResourceAttr(resourceName, "credit_specification.0.cpu_credits", "unlimited"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/6757 func TestAccEC2LaunchTemplate_IAMInstanceProfile_emptyBlock(t *testing.T) { var template1 ec2.LaunchTemplate @@ -752,7 +782,7 @@ func TestAccEC2LaunchTemplate_IAMInstanceProfile_emptyBlock(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateIAMInstanceProfileEmptyConfigurationBlockConfig(rName), + Config: testAccLaunchTemplateConfig_iamInstanceProfileEmptyConfigurationBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template1), ), @@ -850,7 +880,7 @@ func TestAccEC2LaunchTemplate_networkInterfaceType(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_networkInterfaceType_efa(rName), + Config: testAccLaunchTemplateConfig_networkInterfaceTypeEFA(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), @@ -1119,7 +1149,7 @@ func TestAccEC2LaunchTemplate_Placement_hostResourceGroupARN(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplatePlacementHostResourceGroupARNConfig(rName), + Config: testAccLaunchTemplateConfig_placementHostResourceGroupARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttrPair(resourceName, "placement.0.host_resource_group_arn", "aws_resourcegroups_group.test", "arn"), @@ -1146,7 +1176,7 @@ func TestAccEC2LaunchTemplate_Placement_partitionNum(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplatePartitionConfig(rName, 1), + Config: testAccLaunchTemplateConfig_partition(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "placement.0.partition_number", "1"), @@ -1158,7 +1188,7 @@ func TestAccEC2LaunchTemplate_Placement_partitionNum(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLaunchTemplatePartitionConfig(rName, 2), + Config: testAccLaunchTemplateConfig_partition(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "placement.0.partition_number", "2"), @@ -1180,7 +1210,7 @@ func TestAccEC2LaunchTemplate_privateDNSNameOptions(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplatePrivateDNSNameOptionsConfig(rName), + Config: testAccLaunchTemplateConfig_privateDNSNameOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "private_dns_name_options.#", "1"), @@ -1210,7 +1240,7 @@ func TestAccEC2LaunchTemplate_NetworkInterface_ipv6Addresses(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_networkInterface_ipv6Addresses(rName), + Config: testAccLaunchTemplateConfig_networkInterfaceIPv6Addresses(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), @@ -1238,7 +1268,7 @@ func TestAccEC2LaunchTemplate_NetworkInterface_ipv6AddressCount(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_ipv6_count(rName), + Config: testAccLaunchTemplateConfig_ipv6Count(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), @@ -1267,7 +1297,7 @@ func TestAccEC2LaunchTemplate_instanceMarketOptions(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateConfig_InstanceMarketOptions_basic(rName), + Config: testAccLaunchTemplateConfig_instanceMarketOptionsBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "instance_market_options.#", "1"), @@ -1282,7 +1312,7 @@ func TestAccEC2LaunchTemplate_instanceMarketOptions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLaunchTemplateConfig_InstanceMarketOptions_update(rName), + Config: testAccLaunchTemplateConfig_instanceMarketOptionsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "instance_market_options.#", "1"), @@ -2764,7 +2794,7 @@ func TestAccEC2LaunchTemplate_hibernation(t *testing.T) { CheckDestroy: testAccCheckLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccLaunchTemplateHibernationConfig(rName, true), + Config: testAccLaunchTemplateConfig_hibernation(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "hibernation_options.0.configured", "true"), @@ -2776,14 +2806,14 @@ func TestAccEC2LaunchTemplate_hibernation(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLaunchTemplateHibernationConfig(rName, false), + Config: testAccLaunchTemplateConfig_hibernation(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "hibernation_options.0.configured", "false"), ), }, { - Config: testAccLaunchTemplateHibernationConfig(rName, true), + Config: testAccLaunchTemplateConfig_hibernation(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "hibernation_options.0.configured", "true"), @@ -2861,7 +2891,7 @@ func TestAccEC2LaunchTemplate_updateDefaultVersion(t *testing.T) { // Updating a field should create a new version but not update the default_version // if update_default_version is set to false { - Config: testAccLaunchTemplateconfig_descriptionUpdateDefaultVersion(rName, descriptionNew, false), + Config: testAccLaunchTemplateConfig_configDescriptionUpdateDefaultVersion(rName, descriptionNew, false), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "default_version", "1"), resource.TestCheckResourceAttr(resourceName, "latest_version", "2"), @@ -2870,7 +2900,7 @@ func TestAccEC2LaunchTemplate_updateDefaultVersion(t *testing.T) { // Only updating the update_default_version to true should not create a new version // but update the template version to the latest available { - Config: testAccLaunchTemplateconfig_descriptionUpdateDefaultVersion(rName, descriptionNew, true), + Config: testAccLaunchTemplateConfig_configDescriptionUpdateDefaultVersion(rName, descriptionNew, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "default_version", "2"), resource.TestCheckResourceAttr(resourceName, "latest_version", "2"), @@ -2879,7 +2909,7 @@ func TestAccEC2LaunchTemplate_updateDefaultVersion(t *testing.T) { // Updating a field should create a new version and update the default_version // if update_default_version is set to true { - Config: testAccLaunchTemplateconfig_descriptionUpdateDefaultVersion(rName, description, true), + Config: testAccLaunchTemplateConfig_configDescriptionUpdateDefaultVersion(rName, description, true), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "default_version", "3"), resource.TestCheckResourceAttr(resourceName, "latest_version", "3"), @@ -2946,7 +2976,7 @@ func testAccCheckLaunchTemplateDestroy(s *terraform.State) error { return nil } -func testAccLaunchTemplateNameConfig(rName string) string { +func testAccLaunchTemplateConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -2954,13 +2984,13 @@ resource "aws_launch_template" "test" { `, rName) } -func testAccLaunchTemplateNameGeneratedConfig() string { +func testAccLaunchTemplateConfig_nameGenerated() string { return ` resource "aws_launch_template" "test" {} ` } -func testAccLaunchTemplateNamePrefixConfig(namePrefix string) string { +func testAccLaunchTemplateConfig_namePrefix(namePrefix string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name_prefix = %[1]q @@ -2968,7 +2998,7 @@ resource "aws_launch_template" "test" { `, namePrefix) } -func testAccLaunchTemplateConfig_ipv6_count(rName string) string { +func testAccLaunchTemplateConfig_ipv6Count(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -2980,9 +3010,9 @@ resource "aws_launch_template" "test" { `, rName) } -func testAccLaunchTemplateConfig_BlockDeviceMappings_EBS(rName string) string { +func testAccLaunchTemplateConfig_blockDeviceMappingsEBS(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -3017,9 +3047,9 @@ resource "aws_autoscaling_group" "test" { `, rName)) } -func testAccLaunchTemplateConfig_BlockDeviceMappings_EBS_DeleteOnTermination(rName string, deleteOnTermination bool) string { +func testAccLaunchTemplateConfig_blockDeviceMappingsEBSDeleteOnTermination(rName string, deleteOnTermination bool) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -3055,9 +3085,9 @@ resource "aws_autoscaling_group" "test" { `, rName, deleteOnTermination)) } -func testAccLaunchTemplateConfig_BlockDeviceMappings_EBS_GP3(rName string) string { +func testAccLaunchTemplateConfig_blockDeviceMappingsEBSGP3(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -3095,7 +3125,7 @@ resource "aws_autoscaling_group" "test" { `, rName)) } -func testAccLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName string, deleteOnTermination string) string { +func testAccLaunchTemplateConfig_networkInterfacesDeleteOnTermination(rName string, deleteOnTermination string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3109,7 +3139,7 @@ resource "aws_launch_template" "test" { `, rName, deleteOnTermination) } -func testAccLaunchTemplateConfig_EBSOptimized(rName, ebsOptimized string) string { +func testAccLaunchTemplateConfig_ebsOptimized(rName, ebsOptimized string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { ebs_optimized = %[1]s @@ -3118,7 +3148,7 @@ resource "aws_launch_template" "test" { `, ebsOptimized, rName) } -func testAccLaunchTemplateElasticInferenceAcceleratorConfig(rName, elasticInferenceAcceleratorType string) string { +func testAccLaunchTemplateConfig_elasticInferenceAccelerator(rName, elasticInferenceAcceleratorType string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3143,6 +3173,7 @@ resource "aws_launch_template" "test" { auto_recovery = "disabled" } + disable_api_stop = true disable_api_termination = true ebs_optimized = false @@ -3224,7 +3255,7 @@ resource "aws_launch_template" "test" { `, rName)) //lintignore:AWSAT002 } -func testAccLaunchTemplateTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccLaunchTemplateConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3236,7 +3267,7 @@ resource "aws_launch_template" "test" { `, rName, tagKey1, tagValue1) } -func testAccLaunchTemplateTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccLaunchTemplateConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3249,7 +3280,7 @@ resource "aws_launch_template" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccLaunchTemplateConfig_capacityReservation_preference(rName string, preference string) string { +func testAccLaunchTemplateConfig_capacityReservationPreference(rName string, preference string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3261,7 +3292,7 @@ resource "aws_launch_template" "test" { `, rName, preference) } -func testAccLaunchTemplateConfig_capacityReservation_target(rName string) string { +func testAccLaunchTemplateConfig_capacityReservationTarget(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ec2_capacity_reservation" "test" { availability_zone = data.aws_availability_zones.available.names[0] @@ -3312,7 +3343,7 @@ resource "aws_launch_template" "test" { `, instanceType, rName, cpuCredits) } -func testAccLaunchTemplateIAMInstanceProfileEmptyConfigurationBlockConfig(rName string) string { +func testAccLaunchTemplateConfig_iamInstanceProfileEmptyConfigurationBlock(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3386,7 +3417,7 @@ resource "aws_launch_template" "test" { `, rName) } -func testAccLaunchTemplatePartitionConfig(rName string, partNum int) string { +func testAccLaunchTemplateConfig_partition(rName string, partNum int) string { return fmt.Sprintf(` resource "aws_placement_group" "test" { name = %[1]q @@ -3404,7 +3435,7 @@ resource "aws_launch_template" "test" { `, rName, partNum) } -func testAccLaunchTemplatePlacementHostResourceGroupARNConfig(rName string) string { +func testAccLaunchTemplateConfig_placementHostResourceGroupARN(rName string) string { return fmt.Sprintf(` resource "aws_resourcegroups_group" "test" { name = %[1]q @@ -3432,7 +3463,7 @@ resource "aws_launch_template" "test" { `, rName) } -func testAccLaunchTemplatePrivateDNSNameOptionsConfig(rName string) string { +func testAccLaunchTemplateConfig_privateDNSNameOptions(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3562,7 +3593,7 @@ resource "aws_launch_template" "test" { `, rName, associateCarrierIPAddress) } -func testAccLaunchTemplateConfig_networkInterface_ipv6Addresses(rName string) string { +func testAccLaunchTemplateConfig_networkInterfaceIPv6Addresses(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3577,7 +3608,7 @@ resource "aws_launch_template" "test" { `, rName) } -func testAccLaunchTemplateConfig_networkInterfaceType_efa(rName string) string { +func testAccLaunchTemplateConfig_networkInterfaceTypeEFA(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3650,9 +3681,9 @@ resource "aws_launch_template" "test" { `, rName) } -func testAccLaunchTemplateConfig_ASG_basic(rName string) string { +func testAccLaunchTemplateConfig_asgBasic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -3677,9 +3708,9 @@ resource "aws_autoscaling_group" "test" { `, rName)) } -func testAccLaunchTemplateConfig_ASG_update(rName string) string { +func testAccLaunchTemplateConfig_asgUpdate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t3.nano", "t2.nano"), fmt.Sprintf(` @@ -3704,9 +3735,9 @@ resource "aws_autoscaling_group" "test" { `, rName)) } -func testAccLaunchTemplateConfig_InstanceMarketOptions_basic(rName string) string { +func testAccLaunchTemplateConfig_instanceMarketOptionsBasic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -3739,9 +3770,9 @@ resource "aws_autoscaling_group" "test" { `, rName)) } -func testAccLaunchTemplateConfig_InstanceMarketOptions_update(rName string) string { +func testAccLaunchTemplateConfig_instanceMarketOptionsUpdate(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -3855,7 +3886,7 @@ resource "aws_launch_template" "test" { `, rName, enabled) } -func testAccLaunchTemplateHibernationConfig(rName string, enabled bool) string { +func testAccLaunchTemplateConfig_hibernation(rName string, enabled bool) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3877,7 +3908,7 @@ resource "aws_launch_template" "test" { `, rName, description, version) } -func testAccLaunchTemplateconfig_descriptionUpdateDefaultVersion(rName, description string, update bool) string { +func testAccLaunchTemplateConfig_configDescriptionUpdateDefaultVersion(rName, description string, update bool) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q diff --git a/internal/service/ec2/ec2_placement_group_test.go b/internal/service/ec2/ec2_placement_group_test.go index 55a3235a391..778806c4f5f 100644 --- a/internal/service/ec2/ec2_placement_group_test.go +++ b/internal/service/ec2/ec2_placement_group_test.go @@ -26,7 +26,7 @@ func TestAccEC2PlacementGroup_basic(t *testing.T) { CheckDestroy: testAccCheckPlacementGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccPlacementGroupConfig(rName), + Config: testAccPlacementGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlacementGroupExists(resourceName, &pg), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -55,7 +55,7 @@ func TestAccEC2PlacementGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckPlacementGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccPlacementGroupConfig(rName), + Config: testAccPlacementGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlacementGroupExists(resourceName, &pg), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourcePlacementGroup(), resourceName), @@ -78,7 +78,7 @@ func TestAccEC2PlacementGroup_tags(t *testing.T) { CheckDestroy: testAccCheckPlacementGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccPlacementGroupTags1Config(rName, "key1", "value1"), + Config: testAccPlacementGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckPlacementGroupExists(resourceName, &pg), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -91,7 +91,7 @@ func TestAccEC2PlacementGroup_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPlacementGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccPlacementGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckPlacementGroupExists(resourceName, &pg), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -100,7 +100,7 @@ func TestAccEC2PlacementGroup_tags(t *testing.T) { ), }, { - Config: testAccPlacementGroupTags1Config(rName, "key2", "value2"), + Config: testAccPlacementGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckPlacementGroupExists(resourceName, &pg), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -122,7 +122,7 @@ func TestAccEC2PlacementGroup_partitionCount(t *testing.T) { CheckDestroy: testAccCheckPlacementGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccPlacementGroupPartitionCountConfig(rName), + Config: testAccPlacementGroupConfig_partitionCount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPlacementGroupExists(resourceName, &pg), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -188,7 +188,7 @@ func testAccCheckPlacementGroupExists(n string, v *ec2.PlacementGroup) resource. } } -func testAccPlacementGroupConfig(rName string) string { +func testAccPlacementGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_placement_group" "test" { name = %[1]q @@ -197,7 +197,7 @@ resource "aws_placement_group" "test" { `, rName) } -func testAccPlacementGroupTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccPlacementGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_placement_group" "test" { name = %[1]q @@ -210,7 +210,7 @@ resource "aws_placement_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccPlacementGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccPlacementGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_placement_group" "test" { name = %[1]q @@ -224,7 +224,7 @@ resource "aws_placement_group" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccPlacementGroupPartitionCountConfig(rName string) string { +func testAccPlacementGroupConfig_partitionCount(rName string) string { return fmt.Sprintf(` resource "aws_placement_group" "test" { name = %[1]q diff --git a/internal/service/ec2/ec2_serial_console_access_data_source_test.go b/internal/service/ec2/ec2_serial_console_access_data_source_test.go index ff24264594f..e80d859abd3 100644 --- a/internal/service/ec2/ec2_serial_console_access_data_source_test.go +++ b/internal/service/ec2/ec2_serial_console_access_data_source_test.go @@ -20,7 +20,7 @@ func TestAccEC2SerialConsoleAccessDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSerialConsoleAccessDataSourceConfig, + Config: testAccSerialConsoleAccessDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckSerialConsoleAccessDataSource("data.aws_ec2_serial_console_access.current"), ), @@ -57,6 +57,6 @@ func testAccCheckSerialConsoleAccessDataSource(n string) resource.TestCheckFunc } } -const testAccSerialConsoleAccessDataSourceConfig = ` +const testAccSerialConsoleAccessDataSourceConfig_basic = ` data "aws_ec2_serial_console_access" "current" {} ` diff --git a/internal/service/ec2/ec2_serial_console_access_test.go b/internal/service/ec2/ec2_serial_console_access_test.go index 5a51a7e327c..17e06725d5d 100644 --- a/internal/service/ec2/ec2_serial_console_access_test.go +++ b/internal/service/ec2/ec2_serial_console_access_test.go @@ -22,7 +22,7 @@ func TestAccEC2SerialConsoleAccess_basic(t *testing.T) { CheckDestroy: testAccCheckSerialConsoleAccessDestroy, Steps: []resource.TestStep{ { - Config: testAccSerialConsoleAccessConfig(false), + Config: testAccSerialConsoleAccessConfig_basic(false), Check: resource.ComposeTestCheckFunc( testAccCheckSerialConsoleAccess(resourceName, false), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -34,7 +34,7 @@ func TestAccEC2SerialConsoleAccess_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSerialConsoleAccessConfig(true), + Config: testAccSerialConsoleAccessConfig_basic(true), Check: resource.ComposeTestCheckFunc( testAccCheckSerialConsoleAccess(resourceName, true), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), @@ -85,7 +85,7 @@ func testAccCheckSerialConsoleAccess(n string, enabled bool) resource.TestCheckF } } -func testAccSerialConsoleAccessConfig(enabled bool) string { +func testAccSerialConsoleAccessConfig_basic(enabled bool) string { return fmt.Sprintf(` resource "aws_ec2_serial_console_access" "test" { enabled = %[1]t diff --git a/internal/service/ec2/ec2_spot_datafeed_subscription_test.go b/internal/service/ec2/ec2_spot_datafeed_subscription_test.go index fe1368950dd..8bdd5adceec 100644 --- a/internal/service/ec2/ec2_spot_datafeed_subscription_test.go +++ b/internal/service/ec2/ec2_spot_datafeed_subscription_test.go @@ -39,7 +39,7 @@ func testAccSpotDatafeedSubscription_basic(t *testing.T) { CheckDestroy: testAccCheckSpotDatafeedSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotDatafeedSubscription(rName), + Config: testAccSpotDatafeedSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSpotDatafeedSubscriptionExists(resourceName, &subscription), ), @@ -65,7 +65,7 @@ func testAccSpotDatafeedSubscription_disappears(t *testing.T) { CheckDestroy: testAccCheckSpotDatafeedSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotDatafeedSubscription(rName), + Config: testAccSpotDatafeedSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSpotDatafeedSubscriptionExists(resourceName, &subscription), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSpotDataFeedSubscription(), resourceName), @@ -142,7 +142,7 @@ func testAccPreCheckSpotDatafeedSubscription(t *testing.T) { } } -func testAccSpotDatafeedSubscription(rName string) string { +func testAccSpotDatafeedSubscriptionConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_canonical_user_id" "current" {} diff --git a/internal/service/ec2/ec2_spot_fleet_request_test.go b/internal/service/ec2/ec2_spot_fleet_request_test.go index 0df16d02b64..c3ae2845cee 100644 --- a/internal/service/ec2/ec2_spot_fleet_request_test.go +++ b/internal/service/ec2/ec2_spot_fleet_request_test.go @@ -37,7 +37,7 @@ func TestAccEC2SpotFleetRequest_basic(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -74,7 +74,7 @@ func TestAccEC2SpotFleetRequest_disappears(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSpotFleetRequest(), resourceName), @@ -103,7 +103,7 @@ func TestAccEC2SpotFleetRequest_tags(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestConfigTags1(rName, publicKey, validUntil, "key1", "value1"), + Config: testAccSpotFleetRequestConfig_tags1(rName, publicKey, validUntil, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -117,7 +117,7 @@ func TestAccEC2SpotFleetRequest_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccSpotFleetRequestConfigTags2(rName, publicKey, validUntil, "key1", "value1updated", "key2", "value2"), + Config: testAccSpotFleetRequestConfig_tags2(rName, publicKey, validUntil, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -126,7 +126,7 @@ func TestAccEC2SpotFleetRequest_tags(t *testing.T) { ), }, { - Config: testAccSpotFleetRequestConfigTags1(rName, publicKey, validUntil, "key2", "value2"), + Config: testAccSpotFleetRequestConfig_tags1(rName, publicKey, validUntil, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -155,7 +155,7 @@ func TestAccEC2SpotFleetRequest_associatePublicIPAddress(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestAssociatePublicIPAddressConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_associatePublicIPAddress(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -193,7 +193,7 @@ func TestAccEC2SpotFleetRequest_launchTemplate(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchTemplateConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_launchTemplate(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -229,7 +229,7 @@ func TestAccEC2SpotFleetRequest_LaunchTemplate_multiple(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchTemplateMultipleConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_launchTemplateMultiple(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -259,7 +259,7 @@ func TestAccEC2SpotFleetRequest_launchTemplateWithInstanceTypeOverrides(t *testi CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchTemplateWithInstanceTypeOverridesConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_launchTemplateInstanceTypeOverrides(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -309,7 +309,7 @@ func TestAccEC2SpotFleetRequest_launchTemplateWithInstanceRequirementsOverrides( CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchTemplateWithInstanceRequirementsOverridesConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_launchTemplateInstanceRequirementsOverrides(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -359,7 +359,7 @@ func TestAccEC2SpotFleetRequest_launchTemplateToLaunchSpec(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchTemplateConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_launchTemplate(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -374,7 +374,7 @@ func TestAccEC2SpotFleetRequest_launchTemplateToLaunchSpec(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -405,7 +405,7 @@ func TestAccEC2SpotFleetRequest_launchSpecToLaunchTemplate(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -414,7 +414,7 @@ func TestAccEC2SpotFleetRequest_launchSpecToLaunchTemplate(t *testing.T) { ), }, { - Config: testAccSpotFleetRequestLaunchTemplateConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_launchTemplate(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -445,7 +445,7 @@ func TestAccEC2SpotFleetRequest_onDemandTargetCapacity(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestOnDemandTargetCapacityConfig(rName, publicKey, validUntil, 0), + Config: testAccSpotFleetRequestConfig_onDemandTargetCapacity(rName, publicKey, validUntil, 0), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "on_demand_target_capacity", "0"), @@ -458,14 +458,14 @@ func TestAccEC2SpotFleetRequest_onDemandTargetCapacity(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccSpotFleetRequestOnDemandTargetCapacityConfig(rName, publicKey, validUntil, 1), + Config: testAccSpotFleetRequestConfig_onDemandTargetCapacity(rName, publicKey, validUntil, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "on_demand_target_capacity", "1"), ), }, { - Config: testAccSpotFleetRequestOnDemandTargetCapacityConfig(rName, publicKey, validUntil, 0), + Config: testAccSpotFleetRequestConfig_onDemandTargetCapacity(rName, publicKey, validUntil, 0), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "on_demand_target_capacity", "0"), @@ -493,7 +493,7 @@ func TestAccEC2SpotFleetRequest_onDemandMaxTotalPrice(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestOnDemandMaxTotalPriceConfig(rName, publicKey, validUntil, "0.05"), + Config: testAccSpotFleetRequestConfig_onDemandMaxTotalPrice(rName, publicKey, validUntil, "0.05"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "on_demand_max_total_price", "0.05"), @@ -527,7 +527,7 @@ func TestAccEC2SpotFleetRequest_onDemandAllocationStrategy(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestOnDemandAllocationStrategyConfig(rName, publicKey, validUntil, "prioritized"), + Config: testAccSpotFleetRequestConfig_onDemandAllocationStrategy(rName, publicKey, validUntil, "prioritized"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "on_demand_allocation_strategy", "prioritized"), @@ -561,7 +561,7 @@ func TestAccEC2SpotFleetRequest_instanceInterruptionBehavior(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -596,7 +596,7 @@ func TestAccEC2SpotFleetRequest_fleetType(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestFleetTypeConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_type(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -631,7 +631,7 @@ func TestAccEC2SpotFleetRequest_iamInstanceProfileARN(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestIAMInstanceProfileARNConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_iamInstanceProfileARN(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -666,7 +666,7 @@ func TestAccEC2SpotFleetRequest_changePriceForcesNewRequest(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -681,7 +681,7 @@ func TestAccEC2SpotFleetRequest_changePriceForcesNewRequest(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccSpotFleetRequestChangeSpotBidPriceConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_changeBidPrice(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -712,7 +712,7 @@ func TestAccEC2SpotFleetRequest_updateTargetCapacity(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -726,14 +726,14 @@ func TestAccEC2SpotFleetRequest_updateTargetCapacity(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccSpotFleetRequestTargetCapacityConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_targetCapacity(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "target_capacity", "3"), ), }, { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -762,7 +762,7 @@ func TestAccEC2SpotFleetRequest_updateExcessCapacityTerminationPolicy(t *testing CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -776,7 +776,7 @@ func TestAccEC2SpotFleetRequest_updateExcessCapacityTerminationPolicy(t *testing ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccSpotFleetRequestExcessCapacityTerminationConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_excessCapacityTermination(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "excess_capacity_termination_policy", "NoTermination"), @@ -804,7 +804,7 @@ func TestAccEC2SpotFleetRequest_lowestPriceAzOrSubnetInRegion(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -840,7 +840,7 @@ func TestAccEC2SpotFleetRequest_lowestPriceAzInGivenList(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestWithAzsConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_azs(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -877,7 +877,7 @@ func TestAccEC2SpotFleetRequest_lowestPriceSubnetInGivenList(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestWithSubnetConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_subnet(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -914,7 +914,7 @@ func TestAccEC2SpotFleetRequest_multipleInstanceTypesInSameAz(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestMultipleInstanceTypesinSameAzConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_multipleInstanceTypesinSameAZ(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -954,7 +954,7 @@ func TestAccEC2SpotFleetRequest_multipleInstanceTypesInSameSubnet(t *testing.T) CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestMultipleInstanceTypesinSameSubnetConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_multipleInstanceTypesinSameSubnet(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -990,7 +990,7 @@ func TestAccEC2SpotFleetRequest_overridingSpotPrice(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestOverridingSpotPriceConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_overridingPrice(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1031,7 +1031,7 @@ func TestAccEC2SpotFleetRequest_withoutSpotPrice(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestWithoutSpotPriceConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_noPrice(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1066,7 +1066,7 @@ func TestAccEC2SpotFleetRequest_diversifiedAllocation(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestDiversifiedAllocationConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_diversifiedAllocation(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1102,7 +1102,7 @@ func TestAccEC2SpotFleetRequest_multipleInstancePools(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestMultipleInstancePoolsConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_multipleInstancePools(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1153,7 +1153,7 @@ func TestAccEC2SpotFleetRequest_withWeightedCapacity(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestWithWeightedCapacityConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_weightedCapacity(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( fulfillSleep(), testAccCheckSpotFleetRequestExists(resourceName, &sfr), @@ -1197,7 +1197,7 @@ func TestAccEC2SpotFleetRequest_withEBSDisk(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestEBSConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_ebs(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &config), testAccCheckSpotFleetRequest_EBSAttributes(&config), @@ -1231,7 +1231,7 @@ func TestAccEC2SpotFleetRequest_LaunchSpecificationEBSBlockDevice_kmsKeyID(t *te CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchSpecificationEBSBlockDeviceKMSKeyID(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_launchSpecificationEBSBlockDeviceKMSKeyID(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &config), ), @@ -1264,7 +1264,7 @@ func TestAccEC2SpotFleetRequest_LaunchSpecificationRootBlockDevice_kmsKeyID(t *t CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchSpecificationRootBlockDeviceKMSKeyID(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_launchSpecificationRootBlockDeviceKMSKeyID(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &config), ), @@ -1296,7 +1296,7 @@ func TestAccEC2SpotFleetRequest_LaunchSpecification_ebsBlockDeviceGP3(t *testing CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchSpecificationEBSBlockDeviceGP3(rName, publicKey), + Config: testAccSpotFleetRequestConfig_launchSpecificationEBSBlockDeviceGP3(rName, publicKey), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &config), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*.ebs_block_device.*", map[string]string{ @@ -1335,7 +1335,7 @@ func TestAccEC2SpotFleetRequest_LaunchSpecification_rootBlockDeviceGP3(t *testin CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchSpecificationRootBlockDeviceGP3(rName, publicKey), + Config: testAccSpotFleetRequestConfig_launchSpecificationRootBlockDeviceGP3(rName, publicKey), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &config), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*.root_block_device.*", map[string]string{ @@ -1374,7 +1374,7 @@ func TestAccEC2SpotFleetRequest_withTags(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestTagsConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_tags(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &config), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ @@ -1413,7 +1413,7 @@ func TestAccEC2SpotFleetRequest_placementTenancyAndGroup(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestTenancyGroupConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_tenancyGroup(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1448,7 +1448,7 @@ func TestAccEC2SpotFleetRequest_withELBs(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestWithELBsConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_elbs(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1484,7 +1484,7 @@ func TestAccEC2SpotFleetRequest_withTargetGroups(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestWithTargetGroupsConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_targetGroups(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1520,7 +1520,7 @@ func TestAccEC2SpotFleetRequest_Zero_capacity(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestZeroCapacityConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_zeroCapacity(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "target_capacity", "0"), @@ -1533,14 +1533,14 @@ func TestAccEC2SpotFleetRequest_Zero_capacity(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccSpotFleetRequestConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "target_capacity", "2"), ), }, { - Config: testAccSpotFleetRequestZeroCapacityConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_zeroCapacity(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "target_capacity", "0"), @@ -1568,7 +1568,7 @@ func TestAccEC2SpotFleetRequest_capacityRebalance(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestCapacityRebalance(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_capacityRebalance(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_maintenance_strategies.0.capacity_rebalance.0.replacement_strategy", "launch"), @@ -1601,7 +1601,7 @@ func TestAccEC2SpotFleetRequest_withInstanceStoreAMI(t *testing.T) { CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestLaunchSpecificationWithInstanceStoreAMI(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_launchSpecificationInstanceStoreAMI(rName, publicKey, validUntil), ExpectError: regexp.MustCompile("Instance store backed AMIs do not provide a root device name"), }, }, @@ -1626,7 +1626,7 @@ func TestAccEC2SpotFleetRequest_noTerminateInstancesWithExpiration(t *testing.T) CheckDestroy: testAccCheckSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotFleetRequestNoTerminateInstancesWithExpirationConfig(rName, publicKey, validUntil), + Config: testAccSpotFleetRequestConfig_noTerminateInstancesExpiration(rName, publicKey, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "terminate_instances_on_delete", "true"), @@ -1791,7 +1791,7 @@ func testAccCheckSpotFleetRequest_IAMInstanceProfileARN(sfr *ec2.SpotFleetReques func testAccSpotFleetRequestBaseConfig(rName, publicKey string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` @@ -1869,7 +1869,7 @@ resource "aws_iam_policy_attachment" "test" { `, rName, publicKey)) } -func testAccSpotFleetRequestConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_basic(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -1895,7 +1895,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestConfigTags1(rName, publicKey, validUntil, tagKey1, tagValue1 string) string { +func testAccSpotFleetRequestConfig_tags1(rName, publicKey, validUntil, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -1925,7 +1925,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil, tagKey1, tagValue1)) } -func testAccSpotFleetRequestConfigTags2(rName, publicKey, validUntil, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSpotFleetRequestConfig_tags2(rName, publicKey, validUntil, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -1956,7 +1956,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccSpotFleetRequestAssociatePublicIPAddressConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_associatePublicIPAddress(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -1982,7 +1982,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestTargetCapacityConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_targetCapacity(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2007,7 +2007,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestLaunchTemplateConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_launchTemplate(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -2045,7 +2045,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestLaunchTemplateMultipleConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_launchTemplateMultiple(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` data "aws_ec2_instance_type_offering" "test" { filter { @@ -2114,7 +2114,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestLaunchTemplateWithInstanceTypeOverridesConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_launchTemplateInstanceTypeOverrides(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -2163,7 +2163,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestLaunchTemplateWithInstanceRequirementsOverridesConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_launchTemplateInstanceRequirementsOverrides(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -2219,7 +2219,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestExcessCapacityTerminationConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_excessCapacityTermination(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2245,7 +2245,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestFleetTypeConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_type(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2270,7 +2270,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestIAMInstanceProfileARNConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_iamInstanceProfileARN(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_iam_role" "test-role1" { name = "tf-test-role1-%[1]s" @@ -2341,7 +2341,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestChangeSpotBidPriceConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_changeBidPrice(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2366,7 +2366,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestWithAzsConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_azs(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2403,7 +2403,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestWithSubnetConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_subnet(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2468,7 +2468,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestWithELBsConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_elbs(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2536,7 +2536,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestWithTargetGroupsConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_targetGroups(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2615,7 +2615,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestMultipleInstanceTypesinSameAzConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_multipleInstanceTypesinSameAZ(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2652,7 +2652,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestMultipleInstanceTypesinSameSubnetConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_multipleInstanceTypesinSameSubnet(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2703,7 +2703,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestOverridingSpotPriceConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_overridingPrice(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2741,7 +2741,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestWithoutSpotPriceConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_noPrice(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2777,7 +2777,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestMultipleInstancePoolsConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_multipleInstancePools(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2826,7 +2826,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestDiversifiedAllocationConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_diversifiedAllocation(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2875,7 +2875,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestWithWeightedCapacityConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_weightedCapacity(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2914,7 +2914,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestEBSConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_ebs(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -2950,7 +2950,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestLaunchSpecificationEBSBlockDeviceKMSKeyID(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_launchSpecificationEBSBlockDeviceKMSKeyID(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -2996,7 +2996,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestLaunchSpecificationRootBlockDeviceKMSKeyID(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_launchSpecificationRootBlockDeviceKMSKeyID(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -3035,7 +3035,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestLaunchSpecificationEBSBlockDeviceGP3(rName, publicKey string) string { +func testAccSpotFleetRequestConfig_launchSpecificationEBSBlockDeviceGP3(rName, publicKey string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -3072,7 +3072,7 @@ resource "aws_spot_fleet_request" "test" { `, rName)) } -func testAccSpotFleetRequestLaunchSpecificationRootBlockDeviceGP3(rName, publicKey string) string { +func testAccSpotFleetRequestConfig_launchSpecificationRootBlockDeviceGP3(rName, publicKey string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -3102,9 +3102,9 @@ resource "aws_spot_fleet_request" "test" { `, rName)) } -func testAccSpotFleetRequestLaunchSpecificationWithInstanceStoreAMI(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_launchSpecificationInstanceStoreAMI(rName, publicKey, validUntil string) string { return acctest.ConfigCompose( - testAccLatestAmazonLinuxHVMInstanceStoreAMIConfig(), + testAccAMIDataSourceConfig_latestAmazonLinuxHVMInstanceStore(), testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { @@ -3129,7 +3129,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestTagsConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_tags(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -3155,7 +3155,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestTenancyGroupConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_tenancyGroup(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_placement_group" "test" { name = %[1]q @@ -3186,7 +3186,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestZeroCapacityConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_zeroCapacity(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -3212,7 +3212,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestCapacityRebalance(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_capacityRebalance(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn @@ -3243,7 +3243,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil)) } -func testAccSpotFleetRequestOnDemandTargetCapacityConfig(rName, publicKey, validUntil string, targetCapacity int) string { +func testAccSpotFleetRequestConfig_onDemandTargetCapacity(rName, publicKey, validUntil string, targetCapacity int) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3282,7 +3282,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil, targetCapacity)) } -func testAccSpotFleetRequestOnDemandMaxTotalPriceConfig(rName, publicKey, validUntil, price string) string { +func testAccSpotFleetRequestConfig_onDemandMaxTotalPrice(rName, publicKey, validUntil, price string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3321,7 +3321,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil, price)) } -func testAccSpotFleetRequestOnDemandAllocationStrategyConfig(rName, publicKey, validUntil, strategy string) string { +func testAccSpotFleetRequestConfig_onDemandAllocationStrategy(rName, publicKey, validUntil, strategy string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q @@ -3360,7 +3360,7 @@ resource "aws_spot_fleet_request" "test" { `, rName, validUntil, strategy)) } -func testAccSpotFleetRequestNoTerminateInstancesWithExpirationConfig(rName, publicKey, validUntil string) string { +func testAccSpotFleetRequestConfig_noTerminateInstancesExpiration(rName, publicKey, validUntil string) string { return acctest.ConfigCompose(testAccSpotFleetRequestBaseConfig(rName, publicKey), fmt.Sprintf(` resource "aws_spot_fleet_request" "test" { iam_fleet_role = aws_iam_role.test.arn diff --git a/internal/service/ec2/ec2_spot_instance_request_test.go b/internal/service/ec2/ec2_spot_instance_request_test.go index e78256fc7e7..d717c348a40 100644 --- a/internal/service/ec2/ec2_spot_instance_request_test.go +++ b/internal/service/ec2/ec2_spot_instance_request_test.go @@ -28,7 +28,7 @@ func TestAccEC2SpotInstanceRequest_basic(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestConfig(rName), + Config: testAccSpotInstanceRequestConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), testAccCheckSpotInstanceRequestAttributes(&sir), @@ -60,7 +60,7 @@ func TestAccEC2SpotInstanceRequest_disappears(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestConfig(rName), + Config: testAccSpotInstanceRequestConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSpotInstanceRequest(), resourceName), @@ -83,7 +83,7 @@ func TestAccEC2SpotInstanceRequest_tags(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestConfigTags1(rName, "key1", "value1"), + Config: testAccSpotInstanceRequestConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -97,7 +97,7 @@ func TestAccEC2SpotInstanceRequest_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"user_data_replace_on_change", "wait_for_fulfillment"}, }, { - Config: testAccSpotInstanceRequestConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccSpotInstanceRequestConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -106,7 +106,7 @@ func TestAccEC2SpotInstanceRequest_tags(t *testing.T) { ), }, { - Config: testAccSpotInstanceRequestConfigTags1(rName, "key2", "value2"), + Config: testAccSpotInstanceRequestConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -135,7 +135,7 @@ func TestAccEC2SpotInstanceRequest_keyName(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestConfig_KeyName(rName, publicKey), + Config: testAccSpotInstanceRequestConfig_keyName(rName, publicKey), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), resource.TestCheckResourceAttrPair(resourceName, "key_name", keyPairResourceName, "key_name"), @@ -163,7 +163,7 @@ func TestAccEC2SpotInstanceRequest_withLaunchGroup(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestConfig_withLaunchGroup(rName), + Config: testAccSpotInstanceRequestConfig_launchGroup(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), testAccCheckSpotInstanceRequestAttributes(&sir), @@ -194,7 +194,7 @@ func TestAccEC2SpotInstanceRequest_withBlockDuration(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestConfig_withBlockDuration(rName), + Config: testAccSpotInstanceRequestConfig_blockDuration(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), testAccCheckSpotInstanceRequestAttributes(&sir), @@ -225,7 +225,7 @@ func TestAccEC2SpotInstanceRequest_vpc(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestVPCConfig(rName), + Config: testAccSpotInstanceRequestConfig_vpc(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), testAccCheckSpotInstanceRequestAttributes(&sir), @@ -257,7 +257,7 @@ func TestAccEC2SpotInstanceRequest_validUntil(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestValidUntilConfig(rName, validUntil), + Config: testAccSpotInstanceRequestConfig_validUntil(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), testAccCheckSpotInstanceRequestAttributes(&sir), @@ -288,7 +288,7 @@ func TestAccEC2SpotInstanceRequest_withoutSpotPrice(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestConfig_withoutSpotPrice(rName), + Config: testAccSpotInstanceRequestConfig_noPrice(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), testAccCheckSpotInstanceRequestAttributesCheckSIRWithoutSpot(&sir), @@ -318,7 +318,7 @@ func TestAccEC2SpotInstanceRequest_subnetAndSGAndPublicIPAddress(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestConfig_SubnetAndSGAndPublicIPAddress(rName), + Config: testAccSpotInstanceRequestConfig_subnetAndSGAndPublicIPAddress(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), testAccCheckSpotInstanceRequest_InstanceAttributes(&sir, rName), @@ -347,7 +347,7 @@ func TestAccEC2SpotInstanceRequest_networkInterfaceAttributes(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestConfig_SubnetAndSGAndPublicIPAddress(rName), + Config: testAccSpotInstanceRequestConfig_subnetAndSGAndPublicIPAddress(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), testAccCheckSpotInstanceRequest_InstanceAttributes(&sir, rName), @@ -410,7 +410,7 @@ func TestAccEC2SpotInstanceRequest_interruptStop(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestInterruptConfig(rName, "stop"), + Config: testAccSpotInstanceRequestConfig_interrupt(rName, "stop"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), resource.TestCheckResourceAttr(resourceName, "spot_bid_status", "fulfilled"), @@ -440,7 +440,7 @@ func TestAccEC2SpotInstanceRequest_interruptHibernate(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestInterruptConfig(rName, "hibernate"), + Config: testAccSpotInstanceRequestConfig_interrupt(rName, "hibernate"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir), resource.TestCheckResourceAttr(resourceName, "spot_bid_status", "fulfilled"), @@ -470,14 +470,14 @@ func TestAccEC2SpotInstanceRequest_interruptUpdate(t *testing.T) { CheckDestroy: testAccCheckSpotInstanceRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccSpotInstanceRequestInterruptConfig(rName, "hibernate"), + Config: testAccSpotInstanceRequestConfig_interrupt(rName, "hibernate"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir1), resource.TestCheckResourceAttr(resourceName, "instance_interruption_behavior", "hibernate"), ), }, { - Config: testAccSpotInstanceRequestInterruptConfig(rName, "terminate"), + Config: testAccSpotInstanceRequestConfig_interrupt(rName, "terminate"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSpotInstanceRequestExists(resourceName, &sir2), testAccCheckSpotInstanceRequestRecreated(&sir1, &sir2), @@ -660,9 +660,9 @@ func testAccCheckSpotInstanceRequestRecreated(before, after *ec2.SpotInstanceReq } } -func testAccSpotInstanceRequestConfig(rName string) string { +func testAccSpotInstanceRequestConfig_basic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { @@ -680,9 +680,9 @@ resource "aws_ec2_tag" "test" { `, rName)) } -func testAccSpotInstanceRequestConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccSpotInstanceRequestConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { @@ -704,9 +704,9 @@ resource "aws_ec2_tag" "test" { `, rName, tagKey1, tagValue1)) } -func testAccSpotInstanceRequestConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSpotInstanceRequestConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { @@ -729,9 +729,9 @@ resource "aws_ec2_tag" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccSpotInstanceRequestValidUntilConfig(rName string, validUntil string) string { +func testAccSpotInstanceRequestConfig_validUntil(rName string, validUntil string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { @@ -754,9 +754,9 @@ resource "aws_ec2_tag" "test" { `, rName, validUntil)) } -func testAccSpotInstanceRequestConfig_withoutSpotPrice(rName string) string { +func testAccSpotInstanceRequestConfig_noPrice(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { @@ -777,9 +777,9 @@ resource "aws_ec2_tag" "test" { `, rName)) } -func testAccSpotInstanceRequestConfig_KeyName(rName, publicKey string) string { +func testAccSpotInstanceRequestConfig_keyName(rName, publicKey string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { @@ -810,9 +810,9 @@ resource "aws_ec2_tag" "test" { `, rName, publicKey)) } -func testAccSpotInstanceRequestConfig_withLaunchGroup(rName string) string { +func testAccSpotInstanceRequestConfig_launchGroup(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { @@ -835,9 +835,9 @@ resource "aws_ec2_tag" "test" { `, rName)) } -func testAccSpotInstanceRequestConfig_withBlockDuration(rName string) string { +func testAccSpotInstanceRequestConfig_blockDuration(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { @@ -860,10 +860,10 @@ resource "aws_ec2_tag" "test" { `, rName)) } -func testAccSpotInstanceRequestVPCConfig(rName string) string { +func testAccSpotInstanceRequestConfig_vpc(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_vpc" "test" { @@ -904,10 +904,10 @@ resource "aws_ec2_tag" "test" { `, rName)) } -func testAccSpotInstanceRequestConfig_SubnetAndSGAndPublicIPAddress(rName string) string { +func testAccSpotInstanceRequestConfig_subnetAndSGAndPublicIPAddress(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { @@ -996,9 +996,9 @@ resource "aws_ec2_tag" "test" { `, rName, publicKey)) } -func testAccSpotInstanceRequestInterruptConfig(rName, interruptionBehavior string) string { +func testAccSpotInstanceRequestConfig_interrupt(rName, interruptionBehavior string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("c5.large", "c4.large"), fmt.Sprintf(` resource "aws_spot_instance_request" "test" { diff --git a/internal/service/ec2/ec2_spot_price_data_source_test.go b/internal/service/ec2/ec2_spot_price_data_source_test.go index 276f34fc12a..f741362332a 100644 --- a/internal/service/ec2/ec2_spot_price_data_source_test.go +++ b/internal/service/ec2/ec2_spot_price_data_source_test.go @@ -21,7 +21,7 @@ func TestAccEC2SpotPriceDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccSpotPriceDataSourceConfig(), + Config: testAccSpotPriceDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "spot_price", regexp.MustCompile(`^\d+\.\d+$`)), resource.TestMatchResourceAttr(dataSourceName, "spot_price_timestamp", regexp.MustCompile(acctest.RFC3339RegexPattern)), @@ -41,7 +41,7 @@ func TestAccEC2SpotPriceDataSource_filter(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccSpotPriceFilterDataSourceConfig(), + Config: testAccSpotPriceDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "spot_price", regexp.MustCompile(`^\d+\.\d+$`)), resource.TestMatchResourceAttr(dataSourceName, "spot_price_timestamp", regexp.MustCompile(acctest.RFC3339RegexPattern)), @@ -69,7 +69,7 @@ func testAccPreCheckSpotPrice(t *testing.T) { } } -func testAccSpotPriceDataSourceConfig() string { +func testAccSpotPriceDataSourceConfig_basic() string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` data "aws_region" "current" {} @@ -93,7 +93,7 @@ data "aws_ec2_spot_price" "test" { `) } -func testAccSpotPriceFilterDataSourceConfig() string { +func testAccSpotPriceDataSourceConfig_filter() string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` data "aws_region" "current" {} diff --git a/internal/service/ec2/errors.go b/internal/service/ec2/errors.go index 1f6f42fb7e3..6489b37ead3 100644 --- a/internal/service/ec2/errors.go +++ b/internal/service/ec2/errors.go @@ -25,11 +25,12 @@ const ( errCodeInvalidCapacityReservationIdNotFound = "InvalidCapacityReservationId.NotFound'" ErrCodeInvalidCarrierGatewayIDNotFound = "InvalidCarrierGatewayID.NotFound" errCodeInvalidClientVPNActiveAssociationNotFound = "InvalidClientVpnActiveAssociationNotFound" - errCodeInvalidClientVPNAssociationIDNotFound = "InvalidClientVpnAssociationIdNotFound" + errCodeInvalidClientVPNAssociationIdNotFound = "InvalidClientVpnAssociationIdNotFound" errCodeInvalidClientVPNAuthorizationRuleNotFound = "InvalidClientVpnEndpointAuthorizationRuleNotFound" - errCodeInvalidClientVPNEndpointIDNotFound = "InvalidClientVpnEndpointId.NotFound" + errCodeInvalidClientVPNEndpointIdNotFound = "InvalidClientVpnEndpointId.NotFound" errCodeInvalidClientVPNRouteNotFound = "InvalidClientVpnRouteNotFound" ErrCodeInvalidConnectionNotification = "InvalidConnectionNotification" + errCodeInvalidConversionTaskIdMalformed = "InvalidConversionTaskId.Malformed" errCodeInvalidCustomerGatewayIDNotFound = "InvalidCustomerGatewayID.NotFound" errCodeInvalidDHCPOptionIDNotFound = "InvalidDhcpOptionID.NotFound" errCodeInvalidFleetIdNotFound = "InvalidFleetId.NotFound" @@ -56,10 +57,12 @@ const ( errCodeInvalidPlacementGroupUnknown = "InvalidPlacementGroup.Unknown" errCodeInvalidPoolIDNotFound = "InvalidPoolID.NotFound" errCodeInvalidPrefixListIDNotFound = "InvalidPrefixListID.NotFound" + errCodeInvalidPrefixListIdNotFound = "InvalidPrefixListId.NotFound" errCodeInvalidRouteNotFound = "InvalidRoute.NotFound" errCodeInvalidRouteTableIDNotFound = "InvalidRouteTableID.NotFound" errCodeInvalidRouteTableIdNotFound = "InvalidRouteTableId.NotFound" errCodeInvalidSecurityGroupIDNotFound = "InvalidSecurityGroupID.NotFound" + errCodeInvalidServiceName = "InvalidServiceName" errCodeInvalidSnapshotInUse = "InvalidSnapshot.InUse" errCodeInvalidSnapshotNotFound = "InvalidSnapshot.NotFound" ErrCodeInvalidSpotDatafeedNotFound = "InvalidSpotDatafeed.NotFound" @@ -75,15 +78,17 @@ const ( errCodeInvalidTransitGatewayMulticastDomainIdNotFound = "InvalidTransitGatewayMulticastDomainId.NotFound" errCodeInvalidVolumeNotFound = "InvalidVolume.NotFound" errCodeInvalidVPCCIDRBlockAssociationIDNotFound = "InvalidVpcCidrBlockAssociationID.NotFound" - errCodeInvalidVPCEndpointIDNotFound = "InvalidVpcEndpointId.NotFound" + errCodeInvalidVPCEndpointIdNotFound = "InvalidVpcEndpointId.NotFound" errCodeInvalidVPCEndpointNotFound = "InvalidVpcEndpoint.NotFound" - errCodeInvalidVPCEndpointServiceIDNotFound = "InvalidVpcEndpointServiceId.NotFound" + errCodeInvalidVPCEndpointServiceIdNotFound = "InvalidVpcEndpointServiceId.NotFound" errCodeInvalidVPCIDNotFound = "InvalidVpcID.NotFound" errCodeInvalidVPCPeeringConnectionIDNotFound = "InvalidVpcPeeringConnectionID.NotFound" errCodeInvalidVPNConnectionIDNotFound = "InvalidVpnConnectionID.NotFound" errCodeInvalidVPNGatewayAttachmentNotFound = "InvalidVpnGatewayAttachment.NotFound" errCodeInvalidVPNGatewayIDNotFound = "InvalidVpnGatewayID.NotFound" errCodeNatGatewayNotFound = "NatGatewayNotFound" + errCodeResourceNotReady = "ResourceNotReady" + errCodeSnapshotCreationPerVolumeRateExceeded = "SnapshotCreationPerVolumeRateExceeded" errCodeUnsupportedOperation = "UnsupportedOperation" errCodeVolumeInUse = "VolumeInUse" ) diff --git a/internal/service/ec2/filter.go b/internal/service/ec2/filter.go index 60ca4a2b682..3497a706640 100644 --- a/internal/service/ec2/filter.go +++ b/internal/service/ec2/filter.go @@ -28,28 +28,32 @@ import ( // for the "Filters" attribute on most of the "Describe..." API functions in // the EC2 API, to aid in the implementation of Terraform data sources that // retrieve data about EC2 objects. -func BuildAttributeFilterList(attrs map[string]string) []*ec2.Filter { +func BuildAttributeFilterList(m map[string]string) []*ec2.Filter { var filters []*ec2.Filter // sort the filters by name to make the output deterministic var names []string - for filterName := range attrs { - names = append(names, filterName) + for k := range m { + names = append(names, k) } sort.Strings(names) - for _, filterName := range names { - value := attrs[filterName] + for _, name := range names { + value := m[name] if value == "" { continue } - filters = append(filters, &ec2.Filter{ - Name: aws.String(filterName), - Values: []*string{aws.String(value)}, - }) + filters = append(filters, NewFilter(name, []string{value})) } return filters } + +func NewFilter(name string, values []string) *ec2.Filter { + return &ec2.Filter{ + Name: aws.String(name), + Values: aws.StringSlice(values), + } +} diff --git a/internal/service/ec2/find.go b/internal/service/ec2/find.go index 6fd4e5cc25f..a7ca496a082 100644 --- a/internal/service/ec2/find.go +++ b/internal/service/ec2/find.go @@ -210,7 +210,7 @@ func FindClientVPNEndpoints(conn *ec2.EC2, input *ec2.DescribeClientVpnEndpoints return !lastPage }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { return nil, &resource.NotFoundError{ LastError: err, LastRequest: input, @@ -303,7 +303,7 @@ func FindClientVPNAuthorizationRules(conn *ec2.EC2, input *ec2.DescribeClientVpn return !lastPage }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { return nil, &resource.NotFoundError{ LastError: err, LastRequest: input, @@ -369,7 +369,7 @@ func FindClientVPNNetworkAssociations(conn *ec2.EC2, input *ec2.DescribeClientVp return !lastPage }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIDNotFound, errCodeInvalidClientVPNAssociationIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound, errCodeInvalidClientVPNAssociationIdNotFound) { return nil, &resource.NotFoundError{ LastError: err, LastRequest: input, @@ -449,7 +449,7 @@ func FindClientVPNRoutes(conn *ec2.EC2, input *ec2.DescribeClientVpnRoutesInput) return !lastPage }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { return nil, &resource.NotFoundError{ LastError: err, LastRequest: input, @@ -987,6 +987,86 @@ func FindInstanceCreditSpecificationByID(conn *ec2.EC2, id string) (*ec2.Instanc return output, nil } +func FindInstanceTypes(conn *ec2.EC2, input *ec2.DescribeInstanceTypesInput) ([]*ec2.InstanceTypeInfo, error) { + var output []*ec2.InstanceTypeInfo + + err := conn.DescribeInstanceTypesPages(input, func(page *ec2.DescribeInstanceTypesOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.InstanceTypes { + if v != nil { + output = append(output, v) + } + } + + return !lastPage + }) + + if err != nil { + return nil, err + } + + return output, nil +} + +func FindInstanceType(conn *ec2.EC2, input *ec2.DescribeInstanceTypesInput) (*ec2.InstanceTypeInfo, error) { + output, err := FindInstanceTypes(conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 || output[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output[0], nil +} + +func FindInstanceTypeByName(conn *ec2.EC2, name string) (*ec2.InstanceTypeInfo, error) { + input := &ec2.DescribeInstanceTypesInput{ + InstanceTypes: aws.StringSlice([]string{name}), + } + + output, err := FindInstanceType(conn, input) + + if err != nil { + return nil, err + } + + return output, nil +} + +func FindInstanceTypeOfferings(conn *ec2.EC2, input *ec2.DescribeInstanceTypeOfferingsInput) ([]*ec2.InstanceTypeOffering, error) { + var output []*ec2.InstanceTypeOffering + + err := conn.DescribeInstanceTypeOfferingsPages(input, func(page *ec2.DescribeInstanceTypeOfferingsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.InstanceTypeOfferings { + if v != nil { + output = append(output, v) + } + } + + return !lastPage + }) + + if err != nil { + return nil, err + } + + return output, nil +} + func FindLocalGatewayRouteTables(conn *ec2.EC2, input *ec2.DescribeLocalGatewayRouteTablesInput) ([]*ec2.LocalGatewayRouteTable, error) { var output []*ec2.LocalGatewayRouteTable @@ -2480,7 +2560,7 @@ func FindVPCEndpoints(conn *ec2.EC2, input *ec2.DescribeVpcEndpointsInput) ([]*e return !lastPage }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIdNotFound) { return nil, &resource.NotFoundError{ LastError: err, LastRequest: input, @@ -2494,9 +2574,9 @@ func FindVPCEndpoints(conn *ec2.EC2, input *ec2.DescribeVpcEndpointsInput) ([]*e return output, nil } -func FindVPCEndpointByID(conn *ec2.EC2, vpcEndpointID string) (*ec2.VpcEndpoint, error) { +func FindVPCEndpointByID(conn *ec2.EC2, id string) (*ec2.VpcEndpoint, error) { input := &ec2.DescribeVpcEndpointsInput{ - VpcEndpointIds: aws.StringSlice([]string{vpcEndpointID}), + VpcEndpointIds: aws.StringSlice([]string{id}), } output, err := FindVPCEndpoint(conn, input) @@ -2513,7 +2593,7 @@ func FindVPCEndpointByID(conn *ec2.EC2, vpcEndpointID string) (*ec2.VpcEndpoint, } // Eventual consistency check. - if aws.StringValue(output.VpcEndpointId) != vpcEndpointID { + if aws.StringValue(output.VpcEndpointId) != id { return nil, &resource.NotFoundError{ LastRequest: input, } @@ -2522,6 +2602,186 @@ func FindVPCEndpointByID(conn *ec2.EC2, vpcEndpointID string) (*ec2.VpcEndpoint, return output, nil } +func FindVPCEndpointServiceConfiguration(conn *ec2.EC2, input *ec2.DescribeVpcEndpointServiceConfigurationsInput) (*ec2.ServiceConfiguration, error) { + output, err := FindVPCEndpointServiceConfigurations(conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 || output[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output[0], nil +} + +func FindVPCEndpointServiceConfigurations(conn *ec2.EC2, input *ec2.DescribeVpcEndpointServiceConfigurationsInput) ([]*ec2.ServiceConfiguration, error) { + var output []*ec2.ServiceConfiguration + + err := conn.DescribeVpcEndpointServiceConfigurationsPages(input, func(page *ec2.DescribeVpcEndpointServiceConfigurationsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.ServiceConfigurations { + if v != nil { + output = append(output, v) + } + } + + return !lastPage + }) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIdNotFound) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + return output, nil +} + +func FindVPCEndpointServiceConfigurationByServiceName(conn *ec2.EC2, name string) (*ec2.ServiceConfiguration, error) { + input := &ec2.DescribeVpcEndpointServiceConfigurationsInput{ + Filters: BuildAttributeFilterList(map[string]string{ + "service-name": name, + }), + } + + return FindVPCEndpointServiceConfiguration(conn, input) +} + +func FindVPCEndpointServices(conn *ec2.EC2, input *ec2.DescribeVpcEndpointServicesInput) ([]*ec2.ServiceDetail, []string, error) { + var serviceDetails []*ec2.ServiceDetail + var serviceNames []string + + err := describeVPCEndpointServicesPages(conn, input, func(page *ec2.DescribeVpcEndpointServicesOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.ServiceDetails { + if v != nil { + serviceDetails = append(serviceDetails, v) + } + } + + for _, v := range page.ServiceNames { + serviceNames = append(serviceNames, aws.StringValue(v)) + } + + return !lastPage + }) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidServiceName) { + return nil, nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, nil, err + } + + return serviceDetails, serviceNames, nil +} + +func FindVPCEndpointServiceConfigurationByID(conn *ec2.EC2, id string) (*ec2.ServiceConfiguration, error) { + input := &ec2.DescribeVpcEndpointServiceConfigurationsInput{ + ServiceIds: aws.StringSlice([]string{id}), + } + + output, err := FindVPCEndpointServiceConfiguration(conn, input) + + if err != nil { + return nil, err + } + + if state := aws.StringValue(output.ServiceState); state == ec2.ServiceStateDeleted || state == ec2.ServiceStateFailed { + return nil, &resource.NotFoundError{ + Message: state, + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.StringValue(output.ServiceId) != id { + return nil, &resource.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func FindVPCEndpointServicePermissions(conn *ec2.EC2, input *ec2.DescribeVpcEndpointServicePermissionsInput) ([]*ec2.AllowedPrincipal, error) { + var output []*ec2.AllowedPrincipal + + err := conn.DescribeVpcEndpointServicePermissionsPages(input, func(page *ec2.DescribeVpcEndpointServicePermissionsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.AllowedPrincipals { + if v != nil { + output = append(output, v) + } + } + + return !lastPage + }) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIdNotFound) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + return output, nil +} + +func FindVPCEndpointServicePermissionsByID(conn *ec2.EC2, id string) ([]*ec2.AllowedPrincipal, error) { + input := &ec2.DescribeVpcEndpointServicePermissionsInput{ + ServiceId: aws.String(id), + } + + return FindVPCEndpointServicePermissions(conn, input) +} + +func FindVPCEndpointServicePermissionExists(conn *ec2.EC2, serviceID, principalARN string) error { + allowedPrincipals, err := FindVPCEndpointServicePermissionsByID(conn, serviceID) + + if err != nil { + return err + } + + for _, v := range allowedPrincipals { + if aws.StringValue(v.Principal) == principalARN { + return nil + } + } + + return &resource.NotFoundError{ + LastError: fmt.Errorf("VPC Endpoint Service (%s) Principal (%s) not found", serviceID, principalARN), + } +} + // FindVPCEndpointRouteTableAssociationExists returns NotFoundError if no association for the specified VPC endpoint and route table IDs is found. func FindVPCEndpointRouteTableAssociationExists(conn *ec2.EC2, vpcEndpointID string, routeTableID string) error { vpcEndpoint, err := FindVPCEndpointByID(conn, vpcEndpointID) @@ -4185,7 +4445,7 @@ func FindLaunchTemplateVersion(conn *ec2.EC2, input *ec2.DescribeLaunchTemplateV return nil, err } - if len(output) == 0 || output[0] == nil { + if len(output) == 0 || output[0] == nil || output[0].LaunchTemplateData == nil { return nil, tfresource.NewEmptyResultError(input) } @@ -4213,7 +4473,7 @@ func FindLaunchTemplateVersions(conn *ec2.EC2, input *ec2.DescribeLaunchTemplate return !lastPage }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidLaunchTemplateIdNotFound, errCodeInvalidLaunchTemplateIdVersionNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidLaunchTemplateIdNotFound, errCodeInvalidLaunchTemplateNameNotFoundException, errCodeInvalidLaunchTemplateIdVersionNotFound) { return nil, &resource.NotFoundError{ LastError: err, LastRequest: input, @@ -4455,6 +4715,65 @@ func FindPlacementGroupByName(conn *ec2.EC2, name string) (*ec2.PlacementGroup, return placementGroup, nil } +func FindPrefixList(conn *ec2.EC2, input *ec2.DescribePrefixListsInput) (*ec2.PrefixList, error) { + output, err := FindPrefixLists(conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 || output[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output[0], nil +} + +func FindPrefixLists(conn *ec2.EC2, input *ec2.DescribePrefixListsInput) ([]*ec2.PrefixList, error) { + var output []*ec2.PrefixList + + err := conn.DescribePrefixListsPages(input, func(page *ec2.DescribePrefixListsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.PrefixLists { + if v != nil { + output = append(output, v) + } + } + + return !lastPage + }) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidPrefixListIdNotFound) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + return output, nil +} + +func FindPrefixListByName(conn *ec2.EC2, name string) (*ec2.PrefixList, error) { + input := &ec2.DescribePrefixListsInput{ + Filters: BuildAttributeFilterList(map[string]string{ + "prefix-list-name": name, + }), + } + + return FindPrefixList(conn, input) +} + func FindVPCEndpointConnectionByServiceIDAndVPCEndpointID(conn *ec2.EC2, serviceID, vpcEndpointID string) (*ec2.VpcEndpointConnection, error) { input := &ec2.DescribeVpcEndpointConnectionsInput{ Filters: BuildAttributeFilterList(map[string]string{ @@ -4500,12 +4819,92 @@ func FindVPCEndpointConnectionByServiceIDAndVPCEndpointID(conn *ec2.EC2, service return output, nil } -func FindSnapshotById(conn *ec2.EC2, name string) (*ec2.Snapshot, error) { - input := &ec2.DescribeSnapshotsInput{ - SnapshotIds: aws.StringSlice([]string{name}), +func FindImportSnapshotTasks(conn *ec2.EC2, input *ec2.DescribeImportSnapshotTasksInput) ([]*ec2.ImportSnapshotTask, error) { + var output []*ec2.ImportSnapshotTask + + err := conn.DescribeImportSnapshotTasksPages(input, func(page *ec2.DescribeImportSnapshotTasksOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.ImportSnapshotTasks { + if v != nil { + output = append(output, v) + } + } + + return !lastPage + }) + + if tfawserr.ErrMessageContains(err, errCodeInvalidConversionTaskIdMalformed, "not found") { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + return output, nil +} + +func FindImportSnapshotTask(conn *ec2.EC2, input *ec2.DescribeImportSnapshotTasksInput) (*ec2.ImportSnapshotTask, error) { + output, err := FindImportSnapshotTasks(conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 || output[0] == nil || output[0].SnapshotTaskDetail == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output[0], nil +} + +func FindImportSnapshotTaskByID(conn *ec2.EC2, id string) (*ec2.ImportSnapshotTask, error) { + input := &ec2.DescribeImportSnapshotTasksInput{ + ImportTaskIds: aws.StringSlice([]string{id}), + } + + output, err := FindImportSnapshotTask(conn, input) + + if err != nil { + return nil, err } - output, err := conn.DescribeSnapshots(input) + // Eventual consistency check. + if aws.StringValue(output.ImportTaskId) != id { + return nil, &resource.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func FindSnapshots(conn *ec2.EC2, input *ec2.DescribeSnapshotsInput) ([]*ec2.Snapshot, error) { + var output []*ec2.Snapshot + + err := conn.DescribeSnapshotsPages(input, func(page *ec2.DescribeSnapshotsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.Snapshots { + if v != nil { + output = append(output, v) + } + } + + return !lastPage + }) if tfawserr.ErrCodeEquals(err, errCodeInvalidSnapshotNotFound) { return nil, &resource.NotFoundError{ @@ -4518,27 +4917,50 @@ func FindSnapshotById(conn *ec2.EC2, name string) (*ec2.Snapshot, error) { return nil, err } - if output == nil || len(output.Snapshots) == 0 || output.Snapshots[0] == nil { + return output, nil +} + +func FindSnapshot(conn *ec2.EC2, input *ec2.DescribeSnapshotsInput) (*ec2.Snapshot, error) { + output, err := FindSnapshots(conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 || output[0] == nil { return nil, tfresource.NewEmptyResultError(input) } - if count := len(output.Snapshots); count > 1 { + if count := len(output); count > 1 { return nil, tfresource.NewTooManyResultsError(count, input) } - return output.Snapshots[0], nil + return output[0], nil } -func FindSnapshotTierStatusById(conn *ec2.EC2, id string) (*ec2.SnapshotTierStatus, error) { - filters := map[string]string{ - "snapshot-id": id, +func FindSnapshotByID(conn *ec2.EC2, id string) (*ec2.Snapshot, error) { + input := &ec2.DescribeSnapshotsInput{ + SnapshotIds: aws.StringSlice([]string{id}), } - input := &ec2.DescribeSnapshotTierStatusInput{ - Filters: BuildAttributeFilterList(filters), + output, err := FindSnapshot(conn, input) + + if err != nil { + return nil, err } - output, err := conn.DescribeSnapshotTierStatus(input) + // Eventual consistency check. + if aws.StringValue(output.SnapshotId) != id { + return nil, &resource.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func FindSnapshotAttribute(conn *ec2.EC2, input *ec2.DescribeSnapshotAttributeInput) (*ec2.DescribeSnapshotAttributeOutput, error) { + output, err := conn.DescribeSnapshotAttribute(input) if tfawserr.ErrCodeEquals(err, errCodeInvalidSnapshotNotFound) { return nil, &resource.NotFoundError{ @@ -4551,13 +4973,95 @@ func FindSnapshotTierStatusById(conn *ec2.EC2, id string) (*ec2.SnapshotTierStat return nil, err } - if output == nil || len(output.SnapshotTierStatuses) == 0 || output.SnapshotTierStatuses[0] == nil { + if output == nil { return nil, tfresource.NewEmptyResultError(input) } - if count := len(output.SnapshotTierStatuses); count > 1 { + return output, nil +} + +func FindCreateSnapshotCreateVolumePermissionByTwoPartKey(conn *ec2.EC2, snapshotID, accountID string) (*ec2.CreateVolumePermission, error) { + input := &ec2.DescribeSnapshotAttributeInput{ + Attribute: aws.String(ec2.SnapshotAttributeNameCreateVolumePermission), + SnapshotId: aws.String(snapshotID), + } + + output, err := FindSnapshotAttribute(conn, input) + + if err != nil { + return nil, err + } + + for _, v := range output.CreateVolumePermissions { + if aws.StringValue(v.UserId) == accountID { + return v, nil + } + } + + return nil, &resource.NotFoundError{LastRequest: input} +} + +func FindFindSnapshotTierStatuses(conn *ec2.EC2, input *ec2.DescribeSnapshotTierStatusInput) ([]*ec2.SnapshotTierStatus, error) { + var output []*ec2.SnapshotTierStatus + + err := conn.DescribeSnapshotTierStatusPages(input, func(page *ec2.DescribeSnapshotTierStatusOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.SnapshotTierStatuses { + if v != nil { + output = append(output, v) + } + } + + return !lastPage + }) + + if err != nil { + return nil, err + } + + return output, nil +} + +func FindFindSnapshotTierStatus(conn *ec2.EC2, input *ec2.DescribeSnapshotTierStatusInput) (*ec2.SnapshotTierStatus, error) { + output, err := FindFindSnapshotTierStatuses(conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 || output[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output); count > 1 { return nil, tfresource.NewTooManyResultsError(count, input) } - return output.SnapshotTierStatuses[0], nil + return output[0], nil +} + +func FindSnapshotTierStatusBySnapshotID(conn *ec2.EC2, id string) (*ec2.SnapshotTierStatus, error) { + input := &ec2.DescribeSnapshotTierStatusInput{ + Filters: BuildAttributeFilterList(map[string]string{ + "snapshot-id": id, + }), + } + + output, err := FindFindSnapshotTierStatus(conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.StringValue(output.SnapshotId) != id { + return nil, &resource.NotFoundError{ + LastRequest: input, + } + } + + return output, nil } diff --git a/internal/service/ec2/generate.go b/internal/service/ec2/generate.go index f85c6ad795a..987c7c0e0ac 100644 --- a/internal/service/ec2/generate.go +++ b/internal/service/ec2/generate.go @@ -1,7 +1,7 @@ //go:generate go run ../../generate/tagresource/main.go -IDAttribName=resource_id //go:generate go run ../../generate/tags/main.go -GetTag -ListTags -ListTagsOp=DescribeTags -ListTagsInFiltIDName=resource-id -ListTagsInIDElem=Resources -ServiceTagsSlice -TagOp=CreateTags -TagInIDElem=Resources -TagInIDNeedSlice=yes -TagType2=TagDescription -UntagOp=DeleteTags -UntagInNeedTagType -UntagInTagsElem=Tags -UpdateTags //go:generate go run generate/createtags/main.go -//go:generate go run ../../generate/listpages/main.go -ListOps=DescribeSpotFleetInstances,DescribeSpotFleetRequestHistory +//go:generate go run ../../generate/listpages/main.go -ListOps=DescribeSpotFleetInstances,DescribeSpotFleetRequestHistory,DescribeVpcEndpointServices // ONLY generate directives and package declaration! Do not add anything else to this file. package ec2 diff --git a/internal/service/ec2/ipam_byoip_test.go b/internal/service/ec2/ipam_byoip_test.go index fb3359f8b3d..d8a477b6ffa 100644 --- a/internal/service/ec2/ipam_byoip_test.go +++ b/internal/service/ec2/ipam_byoip_test.go @@ -54,7 +54,7 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { CheckDestroy: testAccCheckVPCIPv6CIDRBlockAssociationDestroy, Steps: []resource.TestStep{ { - Config: ipv4IPAMBYOIPIPv6DefaultNetmask(p, m, s), + Config: testAccIPAMBYOIPConfig_ipv4IPv6DefaultNetmask(p, m, s), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc/vpc-.+`)), @@ -65,13 +65,13 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { }, // disassociate ipv6 { - Config: testAccIPAMConfig_ipv6BYOIPCIDRBase(p, m, s), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", "")), }, { - Config: testAccIPAMConfig_ipv6BYOIPExplicitNetmask(p, m, s, netmaskLength), + Config: testAccIPAMBYOIPConfig_ipv6ExplicitNetmask(p, m, s, netmaskLength), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc/vpc-.+`)), @@ -82,13 +82,13 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { }, // // disassociate ipv6 { - Config: testAccIPAMConfig_ipv6BYOIPCIDRBase(p, m, s), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", "")), }, { - Config: testAccIPAMConfig_ipv6BYOIPExplicitCIDR(p, m, s, ipv6CidrVPC), + Config: testAccIPAMBYOIPConfig_ipv6ExplicitCIDR(p, m, s, ipv6CidrVPC), SkipFunc: testAccIPAMConfig_ipv6BYOIPSkipExplicitCIDR(t, ipv6CidrVPC), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), @@ -99,7 +99,7 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { }, // disassociate ipv6 { - Config: testAccIPAMConfig_ipv6BYOIPCIDRBase(p, m, s), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), SkipFunc: testAccIPAMConfig_ipv6BYOIPSkipExplicitCIDR(t, ipv6CidrVPC), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), @@ -107,7 +107,7 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { }, // aws_vpc_ipv6_cidr_block_association { - Config: testAccIPAMConfig_byoipIPv6CIDRBlockAssociationIPAMDefaultNetmask(p, m, s), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBlockAssociationDefaultNetmask(p, m, s), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), testAccCheckVPCIPv6CIDRBlockAssociationExists(assocName, &associationIPv6), @@ -116,19 +116,19 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { }, // disassociate ipv6 { - Config: testAccIPAMConfig_ipv6BYOIPCIDRBase(p, m, s), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc)), // vpc will still have association id because its based on the aws_vpc_ipv6_cidr_block_association resource }, { - Config: testAccIPAMConfig_ipv6BYOIPCIDRBase(p, m, s), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", "")), }, { - Config: testAccIPAMConfig_byoipIPv6CIDRBlockAssociationIPAMExplicitNetmask(p, m, s, netmaskLength), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBlockAssociationExplicitNetmask(p, m, s, netmaskLength), Check: resource.ComposeTestCheckFunc( testAccCheckVPCIPv6CIDRBlockAssociationExists(assocName, &associationIPv6), testAccCheckVPCAssociationIPv6CIDRPrefix(&associationIPv6, strconv.Itoa(netmaskLength)), @@ -136,19 +136,19 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { }, // disassociate ipv6 { - Config: testAccIPAMConfig_ipv6BYOIPCIDRBase(p, m, s), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc)), // vpc will still have association id because its based on the aws_vpc_ipv6_cidr_block_association resource }, { - Config: testAccIPAMConfig_ipv6BYOIPCIDRBase(p, m, s), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", "")), }, { - Config: testAccIPAMConfig_byoipIPv6CIDRBlockAssociationIPAMExplicitCIDR(p, m, s, ipv6CidrAssoc), + Config: testAccIPAMBYOIPConfig_ipv6CIDRBlockAssociationExplicitCIDR(p, m, s, ipv6CidrAssoc), SkipFunc: testAccIPAMConfig_ipv6BYOIPSkipExplicitCIDR(t, ipv6CidrAssoc), Check: resource.ComposeTestCheckFunc( testAccCheckVPCIPv6CIDRBlockAssociationExists(assocName, &associationIPv6), @@ -169,7 +169,7 @@ func testAccIPAMConfig_ipv6BYOIPSkipExplicitCIDR(t *testing.T, ipv6CidrVPC strin } } -func testAccIPAMConfig_ipv6BYOIPCIDRBase(cidr, msg, signature string) string { +func testAccIPAMBYOIPConfig_ipv6CIDRBase(cidr, msg, signature string) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -204,7 +204,7 @@ resource "aws_vpc" "test" { `, cidr, msg, signature) } -func ipv4IPAMBYOIPIPv6DefaultNetmask(cidr, msg, signature string) string { +func testAccIPAMBYOIPConfig_ipv4IPv6DefaultNetmask(cidr, msg, signature string) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -243,7 +243,7 @@ resource "aws_vpc" "test" { `, cidr, msg, signature) } -func testAccIPAMConfig_ipv6BYOIPExplicitNetmask(cidr, msg, signature string, netmask int) string { +func testAccIPAMBYOIPConfig_ipv6ExplicitNetmask(cidr, msg, signature string, netmask int) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -283,7 +283,7 @@ resource "aws_vpc" "test" { `, cidr, msg, signature, netmask) } -func testAccIPAMConfig_ipv6BYOIPExplicitCIDR(cidr, msg, signature, vpcCidr string) string { +func testAccIPAMBYOIPConfig_ipv6ExplicitCIDR(cidr, msg, signature, vpcCidr string) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -323,7 +323,7 @@ resource "aws_vpc" "test" { `, cidr, msg, signature, vpcCidr) } -func testAccIPAMConfig_byoipIPv6CIDRBlockAssociationIPAMDefaultNetmask(cidr, msg, signature string) string { +func testAccIPAMBYOIPConfig_ipv6CIDRBlockAssociationDefaultNetmask(cidr, msg, signature string) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -366,7 +366,7 @@ resource "aws_vpc_ipv6_cidr_block_association" "test" { `, cidr, msg, signature) } -func testAccIPAMConfig_byoipIPv6CIDRBlockAssociationIPAMExplicitNetmask(cidr, msg, signature string, netmask int) string { +func testAccIPAMBYOIPConfig_ipv6CIDRBlockAssociationExplicitNetmask(cidr, msg, signature string, netmask int) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -410,7 +410,7 @@ resource "aws_vpc_ipv6_cidr_block_association" "test" { `, cidr, msg, signature, netmask) } -func testAccIPAMConfig_byoipIPv6CIDRBlockAssociationIPAMExplicitCIDR(cidr, msg, signature, vpcCidr string) string { +func testAccIPAMBYOIPConfig_ipv6CIDRBlockAssociationExplicitCIDR(cidr, msg, signature, vpcCidr string) string { return fmt.Sprintf(` data "aws_region" "current" {} diff --git a/internal/service/ec2/ipam_organization_admin_account_test.go b/internal/service/ec2/ipam_organization_admin_account_test.go index 27444bf0bc4..b1afccb0dcf 100644 --- a/internal/service/ec2/ipam_organization_admin_account_test.go +++ b/internal/service/ec2/ipam_organization_admin_account_test.go @@ -31,7 +31,7 @@ func TestAccIPAMOrganizationAdminAccount_basic(t *testing.T) { CheckDestroy: testAccCheckIPAMOrganizationAdminAccountDestroy, Steps: []resource.TestStep{ { - Config: testAccIPAMOrganizationAdminAccount_basic(), + Config: testAccIPAMOrganizationAdminAccountConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckIPAMOrganizationAdminAccountExists(resourceName, &organization), resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceIdentity, "account_id"), @@ -114,7 +114,7 @@ func testAccCheckIPAMOrganizationAdminAccountExists(n string, org *organizations } } -func testAccIPAMOrganizationAdminAccount_basic() string { +func testAccIPAMOrganizationAdminAccountConfig_basic() string { return acctest.ConfigCompose(acctest.ConfigAlternateAccountProvider() + ` data "aws_caller_identity" "delegated" { provider = "awsalternate" diff --git a/internal/service/ec2/ipam_pool_cidr.go b/internal/service/ec2/ipam_pool_cidr.go index bd23ef9ee04..c8b5262fd30 100644 --- a/internal/service/ec2/ipam_pool_cidr.go +++ b/internal/service/ec2/ipam_pool_cidr.go @@ -88,17 +88,16 @@ func resourceIPAMPoolCIDRCreate(d *schema.ResourceData, meta interface{}) error input.Cidr = aws.String(v.(string)) } - log.Printf("[DEBUG] Provisioning IPAM Pool Cidr: %s", input) output, err := conn.ProvisionIpamPoolCidr(input) if err != nil { - return fmt.Errorf("Error provisioning ipam pool cidr in ipam pool (%s): %w", d.Get("ipam_pool_id").(string), err) + return fmt.Errorf("Error provisioning CIDR in IPAM pool (%s): %w", d.Get("ipam_pool_id").(string), err) } cidr := aws.StringValue(output.IpamPoolCidr.Cidr) id := encodeIPAMPoolCIDRId(cidr, pool_id) if _, err = WaitIPAMPoolCIDRAvailable(conn, id, ipamPoolCIDRCreateTimeout); err != nil { - return fmt.Errorf("error waiting for IPAM Pool Cidr (%s) to be provision: %w", id, err) + return fmt.Errorf("error waiting for IPAM Pool CIDR (%s) to be provisioned: %w", id, err) } d.SetId(id) @@ -114,13 +113,13 @@ func resourceIPAMPoolCIDRRead(d *schema.ResourceData, meta interface{}) error { } if !d.IsNewResource() && cidr == nil { - log.Printf("[WARN] IPAM Pool Cidr (%s) not found or was deprovisioned, removing from state", cidr) + log.Printf("[WARN] IPAM Pool CIDR (%s) not found, removing from state", cidr) d.SetId("") return nil } if aws.StringValue(cidr.State) == ec2.IpamPoolCidrStateDeprovisioned { - log.Printf("[WARN] IPAM Pool Cidr (%s) not found or was deprovisioned, removing from state", cidr) + log.Printf("[WARN] IPAM Pool CIDR (%s) was deprovisioned, removing from state", cidr) d.SetId("") return nil } @@ -141,7 +140,6 @@ func resourceIPAMPoolCIDRDelete(d *schema.ResourceData, meta interface{}) error IpamPoolId: aws.String(pool_id), } return resource.Retry(ipamPoolCIDRDeleteTimeout, func() *resource.RetryError { - log.Printf("[DEBUG] Deprovisioning IPAM Pool Cidr: %s", input) // releasing allocations is eventually consistent and can cause deprovisioning to fail _, err = conn.DeprovisionIpamPoolCidr(input) @@ -151,18 +149,18 @@ func resourceIPAMPoolCIDRDelete(d *schema.ResourceData, meta interface{}) error output, err := WaitIPAMPoolCIDRDeleted(conn, d.Id(), ipamPoolCIDRDeleteTimeout) if err != nil { // State = failed-deprovision - return resource.RetryableError(fmt.Errorf("Expected cidr to be deprovisioned but was in state %s", aws.StringValue(output.State))) + return resource.RetryableError(fmt.Errorf("Expected CIDR to be deprovisioned but was in state %s", aws.StringValue(output.State))) } // State = deprovisioned return nil } - return resource.NonRetryableError(fmt.Errorf("error deprovisioning ipam pool cidr: (%s): %w", cidr, err)) + return resource.NonRetryableError(fmt.Errorf("error deprovisioning IPAM pool CIDR: (%s): %w", cidr, err)) } output, err := WaitIPAMPoolCIDRDeleted(conn, d.Id(), ipamPoolCIDRDeleteTimeout) if err != nil { // State = failed-deprovision - return resource.RetryableError(fmt.Errorf("Expected cidr to be deprovisioned but was in state %s", aws.StringValue(output.State))) + return resource.RetryableError(fmt.Errorf("Expected CIDR to be deprovisioned but was in state %s", aws.StringValue(output.State))) } // State = deprovisioned return nil diff --git a/internal/service/ec2/ipam_pool_cidr_allocation.go b/internal/service/ec2/ipam_pool_cidr_allocation.go index d290bdde290..f54e2539f42 100644 --- a/internal/service/ec2/ipam_pool_cidr_allocation.go +++ b/internal/service/ec2/ipam_pool_cidr_allocation.go @@ -118,7 +118,7 @@ func resourceIPAMPoolCIDRAllocationCreate(d *schema.ResourceData, meta interface log.Printf("[DEBUG] Creating IPAM Pool Allocation: %s", input) output, err := conn.AllocateIpamPoolCidr(input) if err != nil { - return fmt.Errorf("Error allocating cidr from IPAM pool (%s): %w", d.Get("ipam_pool_id").(string), err) + return fmt.Errorf("Error allocating CIDR from IPAM Pool (%s): %w", d.Get("ipam_pool_id").(string), err) } d.SetId(encodeIPAMPoolCIDRAllocationID(aws.StringValue(output.IpamPoolAllocation.IpamPoolAllocationId), pool_id)) @@ -135,7 +135,7 @@ func resourceIPAMPoolCIDRAllocationRead(d *schema.ResourceData, meta interface{} } if !d.IsNewResource() && cidr_allocation == nil { - log.Printf("[WARN] IPAM Pool Cidr Allocation (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] IPAM Pool Allocation (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -167,13 +167,12 @@ func resourceIPAMPoolCIDRAllocationDelete(d *schema.ResourceData, meta interface Cidr: aws.String(d.Get("cidr").(string)), } - log.Printf("[DEBUG] Releasing IPAM Pool CIDR Allocation: %s", input) output, err := conn.ReleaseIpamPoolAllocation(input) if err != nil || !aws.BoolValue(output.Success) { if tfawserr.ErrCodeEquals(err, InvalidIPAMPoolIDNotFound) { return nil } - return fmt.Errorf("error releasing IPAM CIDR Allocation: (%s): %w", d.Id(), err) + return fmt.Errorf("error releasing IPAM Pool Allocation (%s): %w", d.Id(), err) } return nil @@ -187,13 +186,8 @@ func FindIPAMPoolCIDRAllocation(conn *ec2.EC2, id string) (*ec2.IpamPoolAllocati } input := &ec2.GetIpamPoolAllocationsInput{ - IpamPoolId: aws.String(pool_id), - Filters: []*ec2.Filter{ - { - Name: aws.String("ipam-pool-allocation-id"), - Values: aws.StringSlice([]string{allocation_id}), - }, - }, + IpamPoolId: aws.String(pool_id), + IpamPoolAllocationId: aws.String(allocation_id), } output, err := conn.GetIpamPoolAllocations(input) diff --git a/internal/service/ec2/ipam_pool_cidr_allocation_test.go b/internal/service/ec2/ipam_pool_cidr_allocation_test.go index 4598c4d31c6..4e1ac14fdd9 100644 --- a/internal/service/ec2/ipam_pool_cidr_allocation_test.go +++ b/internal/service/ec2/ipam_pool_cidr_allocation_test.go @@ -28,7 +28,7 @@ func TestAccIPAMPoolAllocation_ipv4Basic(t *testing.T) { CheckDestroy: testAccCheckIPAMPoolAllocationDestroy, Steps: []resource.TestStep{ { - Config: testAccIPAMPoolAllocationConfig_ipv4(cidr), + Config: testAccIPAMPoolCIDRAllocationConfig_ipv4(cidr), Check: resource.ComposeTestCheckFunc( testAccCheckIPAMAllocationExists(resourceName, &allocation), resource.TestCheckResourceAttr(resourceName, "cidr", cidr), @@ -58,7 +58,7 @@ func TestAccIPAMPoolAllocation_ipv4BasicNetmask(t *testing.T) { CheckDestroy: testAccCheckIPAMPoolAllocationDestroy, Steps: []resource.TestStep{ { - Config: testAccIPAMPoolAllocationConfig_ipv4Netmask(netmask), + Config: testAccIPAMPoolCIDRAllocationConfig_ipv4Netmask(netmask), Check: resource.ComposeTestCheckFunc( testAccCheckIPAMAllocationExists(resourceName, &allocation), testAccCheckIPAMCIDRPrefix(&allocation, netmask), @@ -87,7 +87,7 @@ func TestAccIPAMPoolAllocation_ipv4DisallowedCIDR(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIPAMPoolAllocationConfig_ipv4DisallowedCIDR(netmaskLength, disallowedCidr), + Config: testAccIPAMPoolCIDRAllocationConfig_ipv4Disallowed(netmaskLength, disallowedCidr), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "cidr", expectedCidr), resource.TestCheckResourceAttr(resourceName, "disallowed_cidrs.#", "1"), @@ -101,6 +101,48 @@ func TestAccIPAMPoolAllocation_ipv4DisallowedCIDR(t *testing.T) { }) } +func TestAccIPAMPoolAllocation_multiple(t *testing.T) { + var allocation1, allocation2 ec2.IpamPoolAllocation + resourceName := "aws_vpc_ipam_pool_cidr_allocation.test" + resourceName2 := "aws_vpc_ipam_pool_cidr_allocation.test2" + cidr1 := "172.2.0.0/28" + cidr2 := "10.1.0.0/28" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccIPAMPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIPAMPoolAllocationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIPAMPoolCIDRAllocationConfig_multiple(cidr1, cidr2), + Check: resource.ComposeTestCheckFunc( + testAccCheckIPAMAllocationExists(resourceName, &allocation1), + testAccCheckIPAMAllocationExists(resourceName2, &allocation2), + resource.TestCheckResourceAttr(resourceName, "cidr", cidr1), + resource.TestMatchResourceAttr(resourceName, "id", regexp.MustCompile(`^ipam-pool-alloc-[\da-f]+_ipam-pool(-[\da-f]+)$`)), + resource.TestMatchResourceAttr(resourceName, "ipam_pool_allocation_id", regexp.MustCompile(`^ipam-pool-alloc-[\da-f]+$`)), + resource.TestCheckResourceAttrPair(resourceName, "ipam_pool_id", "aws_vpc_ipam_pool.test", "id"), + resource.TestCheckResourceAttr(resourceName2, "cidr", cidr2), + resource.TestMatchResourceAttr(resourceName2, "id", regexp.MustCompile(`^ipam-pool-alloc-[\da-f]+_ipam-pool(-[\da-f]+)$`)), + resource.TestMatchResourceAttr(resourceName2, "ipam_pool_allocation_id", regexp.MustCompile(`^ipam-pool-alloc-[\da-f]+$`)), + resource.TestCheckResourceAttrPair(resourceName2, "ipam_pool_id", "aws_vpc_ipam_pool.test", "id"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + ResourceName: resourceName2, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func testAccCheckIPAMAllocationExists(n string, allocation *ec2.IpamPoolAllocation) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -176,7 +218,7 @@ resource "aws_vpc_ipam_pool_cidr" "test" { } ` -func testAccIPAMPoolAllocationConfig_ipv4(cidr string) string { +func testAccIPAMPoolCIDRAllocationConfig_ipv4(cidr string) string { return acctest.ConfigCompose( testAccIPAMPoolCIDRConfig_privateBase, fmt.Sprintf(` @@ -190,7 +232,7 @@ resource "aws_vpc_ipam_pool_cidr_allocation" "test" { `, cidr)) } -func testAccIPAMPoolAllocationConfig_ipv4Netmask(netmask string) string { +func testAccIPAMPoolCIDRAllocationConfig_ipv4Netmask(netmask string) string { return acctest.ConfigCompose( testAccIPAMPoolCIDRConfig_privateBase, fmt.Sprintf(` @@ -204,7 +246,7 @@ resource "aws_vpc_ipam_pool_cidr_allocation" "test" { `, netmask)) } -func testAccIPAMPoolAllocationConfig_ipv4DisallowedCIDR(netmaskLength, disallowedCidr string) string { +func testAccIPAMPoolCIDRAllocationConfig_ipv4Disallowed(netmaskLength, disallowedCidr string) string { return acctest.ConfigCompose( testAccIPAMPoolCIDRConfig_privateBase, fmt.Sprintf(` @@ -222,3 +264,30 @@ resource "aws_vpc_ipam_pool_cidr_allocation" "test" { } `, netmaskLength, disallowedCidr)) } + +func testAccIPAMPoolCIDRAllocationConfig_multiple(cidr1, cidr2 string) string { + return acctest.ConfigCompose( + testAccIPAMPoolCIDRConfig_privateBase, + fmt.Sprintf(` +resource "aws_vpc_ipam_pool_cidr_allocation" "test" { + ipam_pool_id = aws_vpc_ipam_pool.test.id + cidr = %[1]q + depends_on = [ + aws_vpc_ipam_pool_cidr.test + ] +} + +resource "aws_vpc_ipam_pool_cidr" "test2" { + ipam_pool_id = aws_vpc_ipam_pool.test.id + cidr = "10.1.0.0/24" +} + +resource "aws_vpc_ipam_pool_cidr_allocation" "test2" { + ipam_pool_id = aws_vpc_ipam_pool.test.id + cidr = %[2]q + depends_on = [ + aws_vpc_ipam_pool_cidr.test2 + ] +} +`, cidr1, cidr2)) +} diff --git a/internal/service/ec2/ipam_pool_cidr_test.go b/internal/service/ec2/ipam_pool_cidr_test.go index f13d214f6f3..ed09d68d353 100644 --- a/internal/service/ec2/ipam_pool_cidr_test.go +++ b/internal/service/ec2/ipam_pool_cidr_test.go @@ -25,7 +25,7 @@ func TestAccIPAMPool_cidrIPv4Basic(t *testing.T) { CheckDestroy: testAccCheckIPAMProvisionedPoolCIDRDestroy, Steps: []resource.TestStep{ { - Config: testAccIPAMConfig_provisionedPoolCIDRIPv4(cidr_range), + Config: testAccIPAMPoolCIDRConfig_provisionedIPv4(cidr_range), Check: resource.ComposeTestCheckFunc( testAccCheckIPAMCIDRExists(resourceName, &cidr), resource.TestCheckResourceAttr(resourceName, "cidr", cidr_range), @@ -106,7 +106,7 @@ resource "aws_vpc_ipam_pool" "test" { } ` -func testAccIPAMConfig_provisionedPoolCIDRIPv4(cidr string) string { +func testAccIPAMPoolCIDRConfig_provisionedIPv4(cidr string) string { return testAccIPAMPoolCIDRConfig_base + testAccIPAMPoolCIDRConfig_privatePool + fmt.Sprintf(` resource "aws_vpc_ipam_pool_cidr" "test" { ipam_pool_id = aws_vpc_ipam_pool.test.id diff --git a/internal/service/ec2/ipam_pool_data_source_test.go b/internal/service/ec2/ipam_pool_data_source_test.go index cbbb8f81530..95c16937c59 100644 --- a/internal/service/ec2/ipam_pool_data_source_test.go +++ b/internal/service/ec2/ipam_pool_data_source_test.go @@ -18,7 +18,7 @@ func TestAccIPAMPoolDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccIPAMPoolOptions_basic, + Config: testAccIPAMPoolDataSourceConfig_optionsBasic, Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "address_family", resourceName, "address_family"), resource.TestCheckResourceAttrPair(dataSourceName, "allocation_default_netmask_length", resourceName, "allocation_default_netmask_length"), @@ -43,7 +43,7 @@ func TestAccIPAMPoolDataSource_basic(t *testing.T) { }) } -var testAccIPAMPoolOptions_basic = acctest.ConfigCompose(testAccIPAMPoolConfig_base, ` +var testAccIPAMPoolDataSourceConfig_optionsBasic = acctest.ConfigCompose(testAccIPAMPoolConfig_base, ` resource "aws_vpc_ipam_pool" "test" { address_family = "ipv4" ipam_scope_id = aws_vpc_ipam.test.private_default_scope_id diff --git a/internal/service/ec2/ipam_preview_next_cidr_data_source_test.go b/internal/service/ec2/ipam_preview_next_cidr_data_source_test.go index 052c27e9172..cbe2a34806f 100644 --- a/internal/service/ec2/ipam_preview_next_cidr_data_source_test.go +++ b/internal/service/ec2/ipam_preview_next_cidr_data_source_test.go @@ -76,7 +76,7 @@ func TestAccIPAMPreviewNextCIDRDataSource_ipv4DisallowedCIDR(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIPAMPreviewNextCIDRDataSourceConfig_ipv4DisallowedCIDR(netmaskLength, disallowedCidr), + Config: testAccIPAMPreviewNextCIDRDataSourceConfig_ipv4Disallowed(netmaskLength, disallowedCidr), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "cidr", expectedCidr), resource.TestCheckResourceAttr(datasourceName, "disallowed_cidrs.#", "1"), @@ -150,7 +150,7 @@ resource "aws_vpc_ipam_pool_cidr_allocation" "test" { `, netmaskLength)) } -func testAccIPAMPreviewNextCIDRDataSourceConfig_ipv4DisallowedCIDR(netmaskLength, disallowedCidr string) string { +func testAccIPAMPreviewNextCIDRDataSourceConfig_ipv4Disallowed(netmaskLength, disallowedCidr string) string { return testAccIPAMPreviewNextCIDRDataSourceConfig_base + fmt.Sprintf(` data "aws_vpc_ipam_preview_next_cidr" "test" { ipam_pool_id = aws_vpc_ipam_pool.test.id diff --git a/internal/service/ec2/ipam_preview_next_cidr_test.go b/internal/service/ec2/ipam_preview_next_cidr_test.go index 5d9a8088b53..5ec60aa5be9 100644 --- a/internal/service/ec2/ipam_preview_next_cidr_test.go +++ b/internal/service/ec2/ipam_preview_next_cidr_test.go @@ -79,7 +79,7 @@ func TestAccIPAMPreviewNextCIDR_ipv4DisallowedCIDR(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccIPAMPreviewNextCIDRConfig_ipv4DisallowedCIDR(netmaskLength, disallowedCidr), + Config: testAccIPAMPreviewNextCIDRConfig_ipv4Disallowed(netmaskLength, disallowedCidr), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "cidr", expectedCidr), resource.TestCheckResourceAttr(resourceName, "disallowed_cidrs.#", "1"), @@ -150,7 +150,7 @@ resource "aws_vpc_ipam_pool_cidr_allocation" "test" { `, netmaskLength)) } -func testAccIPAMPreviewNextCIDRConfig_ipv4DisallowedCIDR(netmaskLength, disallowedCidr string) string { +func testAccIPAMPreviewNextCIDRConfig_ipv4Disallowed(netmaskLength, disallowedCidr string) string { return testAccIPAMPreviewNextCIDRConfig_ipv4Base + fmt.Sprintf(` resource "aws_vpc_ipam_preview_next_cidr" "test" { ipam_pool_id = aws_vpc_ipam_pool.test.id diff --git a/internal/service/ec2/list_pages_gen.go b/internal/service/ec2/list_pages_gen.go index d8acffa16be..c19d4b5bc72 100644 --- a/internal/service/ec2/list_pages_gen.go +++ b/internal/service/ec2/list_pages_gen.go @@ -1,4 +1,4 @@ -// Code generated by "internal/generate/listpages/main.go -ListOps=DescribeSpotFleetInstances,DescribeSpotFleetRequestHistory"; DO NOT EDIT. +// Code generated by "internal/generate/listpages/main.go -ListOps=DescribeSpotFleetInstances,DescribeSpotFleetRequestHistory,DescribeVpcEndpointServices"; DO NOT EDIT. package ec2 @@ -50,3 +50,24 @@ func describeSpotFleetRequestHistoryPagesWithContext(ctx context.Context, conn * } return nil } + +func describeVPCEndpointServicesPages(conn *ec2.EC2, input *ec2.DescribeVpcEndpointServicesInput, fn func(*ec2.DescribeVpcEndpointServicesOutput, bool) bool) error { + return describeVPCEndpointServicesPagesWithContext(context.Background(), conn, input, fn) +} + +func describeVPCEndpointServicesPagesWithContext(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeVpcEndpointServicesInput, fn func(*ec2.DescribeVpcEndpointServicesOutput, bool) bool) error { + for { + output, err := conn.DescribeVpcEndpointServicesWithContext(ctx, input) + if err != nil { + return err + } + + lastPage := aws.StringValue(output.NextToken) == "" + if !fn(output, lastPage) || lastPage { + break + } + + input.NextToken = output.NextToken + } + return nil +} diff --git a/internal/service/ec2/outposts_coip_pool_data_source_test.go b/internal/service/ec2/outposts_coip_pool_data_source_test.go index 3865ab89b6e..c53ac10f618 100644 --- a/internal/service/ec2/outposts_coip_pool_data_source_test.go +++ b/internal/service/ec2/outposts_coip_pool_data_source_test.go @@ -18,7 +18,7 @@ func TestAccEC2OutpostsCoIPPoolDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCoIPPoolDataSourceFilterDataSourceConfig(), + Config: testAccOutpostsCoIPPoolDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "local_gateway_route_table_id", regexp.MustCompile(`^lgw-rtb-`)), resource.TestMatchResourceAttr(dataSourceName, "pool_id", regexp.MustCompile(`^ipv4pool-coip-`)), @@ -38,7 +38,7 @@ func TestAccEC2OutpostsCoIPPoolDataSource_id(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCoIPPoolDataSourceIDDataSourceConfig(), + Config: testAccOutpostsCoIPPoolDataSourceConfig_id(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "local_gateway_route_table_id", regexp.MustCompile(`^lgw-rtb-`)), resource.TestMatchResourceAttr(dataSourceName, "pool_id", regexp.MustCompile(`^ipv4pool-coip-`)), @@ -50,7 +50,7 @@ func TestAccEC2OutpostsCoIPPoolDataSource_id(t *testing.T) { }) } -func testAccCoIPPoolDataSourceFilterDataSourceConfig() string { +func testAccOutpostsCoIPPoolDataSourceConfig_filter() string { return ` data "aws_ec2_coip_pools" "test" {} @@ -63,7 +63,7 @@ data "aws_ec2_coip_pool" "test" { ` } -func testAccCoIPPoolDataSourceIDDataSourceConfig() string { +func testAccOutpostsCoIPPoolDataSourceConfig_id() string { return ` data "aws_ec2_coip_pools" "test" {} diff --git a/internal/service/ec2/outposts_coip_pools_data_source_test.go b/internal/service/ec2/outposts_coip_pools_data_source_test.go index b49505d014d..9cab012f7f4 100644 --- a/internal/service/ec2/outposts_coip_pools_data_source_test.go +++ b/internal/service/ec2/outposts_coip_pools_data_source_test.go @@ -17,7 +17,7 @@ func TestAccEC2OutpostsCoIPPoolsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCoIPPoolsDataSourceConfig(), + Config: testAccOutpostsCoIPPoolsDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "pool_ids.#", "0"), ), @@ -35,7 +35,7 @@ func TestAccEC2OutpostsCoIPPoolsDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCoIPPoolsFilterDataSourceConfig(), + Config: testAccOutpostsCoIPPoolsDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "pool_ids.#", "1"), ), @@ -44,13 +44,13 @@ func TestAccEC2OutpostsCoIPPoolsDataSource_filter(t *testing.T) { }) } -func testAccCoIPPoolsDataSourceConfig() string { +func testAccOutpostsCoIPPoolsDataSourceConfig_basic() string { return ` data "aws_ec2_coip_pools" "test" {} ` } -func testAccCoIPPoolsFilterDataSourceConfig() string { +func testAccOutpostsCoIPPoolsDataSourceConfig_filter() string { return ` data "aws_ec2_coip_pools" "all" {} diff --git a/internal/service/ec2/outposts_local_gateway_data_source_test.go b/internal/service/ec2/outposts_local_gateway_data_source_test.go index 5e1619b1ea2..83f1226e545 100644 --- a/internal/service/ec2/outposts_local_gateway_data_source_test.go +++ b/internal/service/ec2/outposts_local_gateway_data_source_test.go @@ -18,7 +18,7 @@ func TestAccEC2OutpostsLocalGatewayDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayIDDataSourceConfig(), + Config: testAccOutpostsLocalGatewayDataSourceConfig_id(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^lgw-`)), acctest.MatchResourceAttrRegionalARN(dataSourceName, "outpost_arn", "outposts", regexp.MustCompile(`outpost/op-.+`)), @@ -30,7 +30,7 @@ func TestAccEC2OutpostsLocalGatewayDataSource_basic(t *testing.T) { }) } -func testAccLocalGatewayIDDataSourceConfig() string { +func testAccOutpostsLocalGatewayDataSourceConfig_id() string { return ` data "aws_ec2_local_gateways" "test" {} diff --git a/internal/service/ec2/outposts_local_gateway_route_table_data_source_test.go b/internal/service/ec2/outposts_local_gateway_route_table_data_source_test.go index 00f4cba688c..562e3782182 100644 --- a/internal/service/ec2/outposts_local_gateway_route_table_data_source_test.go +++ b/internal/service/ec2/outposts_local_gateway_route_table_data_source_test.go @@ -18,7 +18,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteTableLocalGatewayRouteTableIDDataSourceConfig(), + Config: testAccOutpostsLocalGatewayRouteTableDataSourceConfig_routeTableID(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), resource.TestMatchResourceAttr(dataSourceName, "local_gateway_route_table_id", regexp.MustCompile(`^lgw-rtb-`)), @@ -39,7 +39,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteTableFilterDataSourceConfig(), + Config: testAccOutpostsLocalGatewayRouteTableDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), resource.TestMatchResourceAttr(dataSourceName, "local_gateway_route_table_id", regexp.MustCompile(`^lgw-rtb-`)), @@ -60,7 +60,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableDataSource_localGatewayID(t *testin ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteTableLocalGatewayIDDataSourceConfig(), + Config: testAccOutpostsLocalGatewayRouteTableDataSourceConfig_localGatewayID(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), resource.TestMatchResourceAttr(dataSourceName, "local_gateway_route_table_id", regexp.MustCompile(`^lgw-rtb-`)), @@ -81,7 +81,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableDataSource_outpostARN(t *testing.T) ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteTableOutpostARNDataSourceConfig(), + Config: testAccOutpostsLocalGatewayRouteTableDataSourceConfig_outpostARN(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), resource.TestMatchResourceAttr(dataSourceName, "local_gateway_route_table_id", regexp.MustCompile(`^lgw-rtb-`)), @@ -93,7 +93,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableDataSource_outpostARN(t *testing.T) }) } -func testAccLocalGatewayRouteTableFilterDataSourceConfig() string { +func testAccOutpostsLocalGatewayRouteTableDataSourceConfig_filter() string { return ` data "aws_outposts_outposts" "test" {} @@ -106,7 +106,7 @@ data "aws_ec2_local_gateway_route_table" "test" { ` } -func testAccLocalGatewayRouteTableLocalGatewayIDDataSourceConfig() string { +func testAccOutpostsLocalGatewayRouteTableDataSourceConfig_localGatewayID() string { return ` data "aws_ec2_local_gateways" "test" {} @@ -116,7 +116,7 @@ data "aws_ec2_local_gateway_route_table" "test" { ` } -func testAccLocalGatewayRouteTableLocalGatewayRouteTableIDDataSourceConfig() string { +func testAccOutpostsLocalGatewayRouteTableDataSourceConfig_routeTableID() string { return ` data "aws_ec2_local_gateway_route_tables" "test" {} @@ -126,7 +126,7 @@ data "aws_ec2_local_gateway_route_table" "test" { ` } -func testAccLocalGatewayRouteTableOutpostARNDataSourceConfig() string { +func testAccOutpostsLocalGatewayRouteTableDataSourceConfig_outpostARN() string { return ` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/ec2/outposts_local_gateway_route_table_vpc_association_test.go b/internal/service/ec2/outposts_local_gateway_route_table_vpc_association_test.go index a0ce786dca2..4c7b11811a9 100644 --- a/internal/service/ec2/outposts_local_gateway_route_table_vpc_association_test.go +++ b/internal/service/ec2/outposts_local_gateway_route_table_vpc_association_test.go @@ -27,7 +27,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableVPCAssociation_basic(t *testing.T) CheckDestroy: testAccCheckLocalGatewayRouteTableVPCAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteTableVPCAssociationConfig(rName), + Config: testAccOutpostsLocalGatewayRouteTableVPCAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocalGatewayRouteTableVPCAssociationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "local_gateway_id", localGatewayRouteTableDataSourceName, "local_gateway_id"), @@ -56,7 +56,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableVPCAssociation_disappears(t *testin CheckDestroy: testAccCheckLocalGatewayRouteTableVPCAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteTableVPCAssociationConfig(rName), + Config: testAccOutpostsLocalGatewayRouteTableVPCAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLocalGatewayRouteTableVPCAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceLocalGatewayRouteTableVPCAssociation(), resourceName), @@ -78,7 +78,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableVPCAssociation_tags(t *testing.T) { CheckDestroy: testAccCheckLocalGatewayRouteTableVPCAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteTableVPCAssociationTags1Config(rName, "key1", "value1"), + Config: testAccOutpostsLocalGatewayRouteTableVPCAssociationConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLocalGatewayRouteTableVPCAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -91,7 +91,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableVPCAssociation_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLocalGatewayRouteTableVPCAssociationTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccOutpostsLocalGatewayRouteTableVPCAssociationConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLocalGatewayRouteTableVPCAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -100,7 +100,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTableVPCAssociation_tags(t *testing.T) { ), }, { - Config: testAccLocalGatewayRouteTableVPCAssociationTags1Config(rName, "key2", "value2"), + Config: testAccOutpostsLocalGatewayRouteTableVPCAssociationConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLocalGatewayRouteTableVPCAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -182,7 +182,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccLocalGatewayRouteTableVPCAssociationConfig(rName string) string { +func testAccOutpostsLocalGatewayRouteTableVPCAssociationConfig_basic(rName string) string { return acctest.ConfigCompose( testAccLocalGatewayRouteTableVPCAssociationBaseConfig(rName), ` @@ -193,7 +193,7 @@ resource "aws_ec2_local_gateway_route_table_vpc_association" "test" { `) } -func testAccLocalGatewayRouteTableVPCAssociationTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccOutpostsLocalGatewayRouteTableVPCAssociationConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( testAccLocalGatewayRouteTableVPCAssociationBaseConfig(rName), fmt.Sprintf(` @@ -208,7 +208,7 @@ resource "aws_ec2_local_gateway_route_table_vpc_association" "test" { `, tagKey1, tagValue1)) } -func testAccLocalGatewayRouteTableVPCAssociationTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccOutpostsLocalGatewayRouteTableVPCAssociationConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( testAccLocalGatewayRouteTableVPCAssociationBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/ec2/outposts_local_gateway_route_tables_data_source_test.go b/internal/service/ec2/outposts_local_gateway_route_tables_data_source_test.go index d90ba639aaf..a82db54c53d 100644 --- a/internal/service/ec2/outposts_local_gateway_route_tables_data_source_test.go +++ b/internal/service/ec2/outposts_local_gateway_route_tables_data_source_test.go @@ -17,7 +17,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTablesDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteTablesDataSourceConfig(), + Config: testAccOutpostsLocalGatewayRouteTablesDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "ids.#", "0"), ), @@ -35,7 +35,7 @@ func TestAccEC2OutpostsLocalGatewayRouteTablesDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteTablesFilterDataSourceConfig(), + Config: testAccOutpostsLocalGatewayRouteTablesDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), ), @@ -44,13 +44,13 @@ func TestAccEC2OutpostsLocalGatewayRouteTablesDataSource_filter(t *testing.T) { }) } -func testAccLocalGatewayRouteTablesDataSourceConfig() string { +func testAccOutpostsLocalGatewayRouteTablesDataSourceConfig_basic() string { return ` data "aws_ec2_local_gateway_route_tables" "test" {} ` } -func testAccLocalGatewayRouteTablesFilterDataSourceConfig() string { +func testAccOutpostsLocalGatewayRouteTablesDataSourceConfig_filter() string { return ` data "aws_ec2_local_gateway_route_tables" "all" {} diff --git a/internal/service/ec2/outposts_local_gateway_route_test.go b/internal/service/ec2/outposts_local_gateway_route_test.go index 4b153777287..66d63495dd9 100644 --- a/internal/service/ec2/outposts_local_gateway_route_test.go +++ b/internal/service/ec2/outposts_local_gateway_route_test.go @@ -28,7 +28,7 @@ func TestAccEC2OutpostsLocalGatewayRoute_basic(t *testing.T) { CheckDestroy: testAccCheckLocalGatewayRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteDestinationCIDRBlockConfig(destinationCidrBlock), + Config: testAccOutpostsLocalGatewayRouteConfig_destinationCIDRBlock(destinationCidrBlock), Check: resource.ComposeTestCheckFunc( testAccCheckLocalGatewayRouteExists(resourceName), resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", destinationCidrBlock), @@ -57,7 +57,7 @@ func TestAccEC2OutpostsLocalGatewayRoute_disappears(t *testing.T) { CheckDestroy: testAccCheckLocalGatewayRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayRouteDestinationCIDRBlockConfig(destinationCidrBlock), + Config: testAccOutpostsLocalGatewayRouteConfig_destinationCIDRBlock(destinationCidrBlock), Check: resource.ComposeTestCheckFunc( testAccCheckLocalGatewayRouteExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceLocalGatewayRoute(), resourceName), @@ -135,7 +135,7 @@ func testAccCheckLocalGatewayRouteDestroy(s *terraform.State) error { return nil } -func testAccLocalGatewayRouteDestinationCIDRBlockConfig(destinationCidrBlock string) string { +func testAccOutpostsLocalGatewayRouteConfig_destinationCIDRBlock(destinationCidrBlock string) string { return fmt.Sprintf(` data "aws_ec2_local_gateways" "test" {} diff --git a/internal/service/ec2/outposts_local_gateway_virtual_interface_data_source_test.go b/internal/service/ec2/outposts_local_gateway_virtual_interface_data_source_test.go index b7dd7110e29..f67931f20ef 100644 --- a/internal/service/ec2/outposts_local_gateway_virtual_interface_data_source_test.go +++ b/internal/service/ec2/outposts_local_gateway_virtual_interface_data_source_test.go @@ -20,7 +20,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceDataSource_filter(t *testing. ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayVirtualInterfaceFilterDataSourceConfig(), + Config: testAccOutpostsLocalGatewayVirtualInterfaceDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^lgw-vif-`)), resource.TestMatchResourceAttr(dataSourceName, "local_address", regexp.MustCompile(`^\d+\.\d+\.\d+\.\d+/\d+$`)), @@ -44,7 +44,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceDataSource_id(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayVirtualInterfaceIDDataSourceConfig(), + Config: testAccOutpostsLocalGatewayVirtualInterfaceDataSourceConfig_id(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^lgw-vif-`)), resource.TestMatchResourceAttr(dataSourceName, "local_address", regexp.MustCompile(`^\d+\.\d+\.\d+\.\d+/\d+$`)), @@ -70,7 +70,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceDataSource_tags(t *testing.T) ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayVirtualInterfaceTagsDataSourceConfig(rName), + Config: testAccOutpostsLocalGatewayVirtualInterfaceDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", sourceDataSourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "local_address", sourceDataSourceName, "local_address"), @@ -85,7 +85,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceDataSource_tags(t *testing.T) }) } -func testAccLocalGatewayVirtualInterfaceFilterDataSourceConfig() string { +func testAccOutpostsLocalGatewayVirtualInterfaceDataSourceConfig_filter() string { return ` data "aws_ec2_local_gateways" "test" {} @@ -102,7 +102,7 @@ data "aws_ec2_local_gateway_virtual_interface" "test" { ` } -func testAccLocalGatewayVirtualInterfaceIDDataSourceConfig() string { +func testAccOutpostsLocalGatewayVirtualInterfaceDataSourceConfig_id() string { return ` data "aws_ec2_local_gateways" "test" {} @@ -116,7 +116,7 @@ data "aws_ec2_local_gateway_virtual_interface" "test" { ` } -func testAccLocalGatewayVirtualInterfaceTagsDataSourceConfig(rName string) string { +func testAccOutpostsLocalGatewayVirtualInterfaceDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` data "aws_ec2_local_gateways" "test" {} diff --git a/internal/service/ec2/outposts_local_gateway_virtual_interface_group_data_source_test.go b/internal/service/ec2/outposts_local_gateway_virtual_interface_group_data_source_test.go index b488a8119c4..adce7ae21a2 100644 --- a/internal/service/ec2/outposts_local_gateway_virtual_interface_group_data_source_test.go +++ b/internal/service/ec2/outposts_local_gateway_virtual_interface_group_data_source_test.go @@ -20,7 +20,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceGroupDataSource_filter(t *tes ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayVirtualInterfaceGroupFilterDataSourceConfig(), + Config: testAccOutpostsLocalGatewayVirtualInterfaceGroupDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^lgw-vif-grp-`)), resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), @@ -40,7 +40,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceGroupDataSource_localGatewayI ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayVirtualInterfaceGroupLocalGatewayIDDataSourceConfig(), + Config: testAccOutpostsLocalGatewayVirtualInterfaceGroupDataSourceConfig_id(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^lgw-vif-grp-`)), resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), @@ -62,7 +62,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceGroupDataSource_tags(t *testi ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayVirtualInterfaceGroupTagsDataSourceConfig(rName), + Config: testAccOutpostsLocalGatewayVirtualInterfaceGroupDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", sourceDataSourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "local_gateway_id", sourceDataSourceName, "local_gateway_id"), @@ -72,7 +72,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceGroupDataSource_tags(t *testi }) } -func testAccLocalGatewayVirtualInterfaceGroupFilterDataSourceConfig() string { +func testAccOutpostsLocalGatewayVirtualInterfaceGroupDataSourceConfig_filter() string { return ` data "aws_ec2_local_gateways" "test" {} @@ -85,7 +85,7 @@ data "aws_ec2_local_gateway_virtual_interface_group" "test" { ` } -func testAccLocalGatewayVirtualInterfaceGroupLocalGatewayIDDataSourceConfig() string { +func testAccOutpostsLocalGatewayVirtualInterfaceGroupDataSourceConfig_id() string { return ` data "aws_ec2_local_gateways" "test" {} @@ -95,7 +95,7 @@ data "aws_ec2_local_gateway_virtual_interface_group" "test" { ` } -func testAccLocalGatewayVirtualInterfaceGroupTagsDataSourceConfig(rName string) string { +func testAccOutpostsLocalGatewayVirtualInterfaceGroupDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` data "aws_ec2_local_gateways" "test" {} diff --git a/internal/service/ec2/outposts_local_gateway_virtual_interface_groups_data_source_test.go b/internal/service/ec2/outposts_local_gateway_virtual_interface_groups_data_source_test.go index 5445b20b7b9..dbc8912fb85 100644 --- a/internal/service/ec2/outposts_local_gateway_virtual_interface_groups_data_source_test.go +++ b/internal/service/ec2/outposts_local_gateway_virtual_interface_groups_data_source_test.go @@ -19,7 +19,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceGroupsDataSource_basic(t *tes ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayVirtualInterfaceGroupsDataSourceConfig(), + Config: testAccOutpostsLocalGatewayVirtualInterfaceGroupsDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), resource.TestCheckResourceAttr(dataSourceName, "local_gateway_virtual_interface_ids.#", "2"), @@ -38,7 +38,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceGroupsDataSource_filter(t *te ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayVirtualInterfaceGroupsFilterDataSourceConfig(), + Config: testAccOutpostsLocalGatewayVirtualInterfaceGroupsDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), resource.TestCheckResourceAttr(dataSourceName, "local_gateway_virtual_interface_ids.#", "2"), @@ -58,7 +58,7 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceGroupsDataSource_tags(t *test ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewayVirtualInterfaceGroupsTagsDataSourceConfig(rName), + Config: testAccOutpostsLocalGatewayVirtualInterfaceGroupsDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), resource.TestCheckResourceAttr(dataSourceName, "local_gateway_virtual_interface_ids.#", "2"), @@ -68,13 +68,13 @@ func TestAccEC2OutpostsLocalGatewayVirtualInterfaceGroupsDataSource_tags(t *test }) } -func testAccLocalGatewayVirtualInterfaceGroupsDataSourceConfig() string { +func testAccOutpostsLocalGatewayVirtualInterfaceGroupsDataSourceConfig_basic() string { return ` data "aws_ec2_local_gateway_virtual_interface_groups" "test" {} ` } -func testAccLocalGatewayVirtualInterfaceGroupsFilterDataSourceConfig() string { +func testAccOutpostsLocalGatewayVirtualInterfaceGroupsDataSourceConfig_filter() string { return ` data "aws_ec2_local_gateways" "test" {} @@ -87,7 +87,7 @@ data "aws_ec2_local_gateway_virtual_interface_groups" "test" { ` } -func testAccLocalGatewayVirtualInterfaceGroupsTagsDataSourceConfig(rName string) string { +func testAccOutpostsLocalGatewayVirtualInterfaceGroupsDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` data "aws_ec2_local_gateways" "test" {} diff --git a/internal/service/ec2/outposts_local_gateways_data_source_test.go b/internal/service/ec2/outposts_local_gateways_data_source_test.go index 5cda1988884..bf37c5ede0b 100644 --- a/internal/service/ec2/outposts_local_gateways_data_source_test.go +++ b/internal/service/ec2/outposts_local_gateways_data_source_test.go @@ -17,7 +17,7 @@ func TestAccEC2OutpostsLocalGatewaysDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLocalGatewaysDataSourceConfig(), + Config: testAccOutpostsLocalGatewaysDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "ids.#", "0"), ), @@ -26,7 +26,7 @@ func TestAccEC2OutpostsLocalGatewaysDataSource_basic(t *testing.T) { }) } -func testAccLocalGatewaysDataSourceConfig() string { +func testAccOutpostsLocalGatewaysDataSourceConfig_basic() string { return ` data "aws_ec2_local_gateways" "test" {} ` diff --git a/internal/service/ec2/status.go b/internal/service/ec2/status.go index 628bc50b935..63517bf5e1a 100644 --- a/internal/service/ec2/status.go +++ b/internal/service/ec2/status.go @@ -1103,13 +1103,28 @@ func StatusVPCEndpointState(conn *ec2.EC2, id string) resource.StateRefreshFunc } } -const ( - VPCEndpointRouteTableAssociationStatusReady = "ready" -) +func StatusVPCEndpointServiceStateAvailable(conn *ec2.EC2, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + // Don't call FindVPCEndpointServiceConfigurationByID as it maps useful status codes to NotFoundError. + output, err := FindVPCEndpointServiceConfiguration(conn, &ec2.DescribeVpcEndpointServiceConfigurationsInput{ + ServiceIds: aws.StringSlice([]string{id}), + }) -func StatusVPCEndpointRouteTableAssociation(conn *ec2.EC2, vpcEndpointID, routeTableID string) resource.StateRefreshFunc { + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.StringValue(output.ServiceState), nil + } +} + +func StatusVPCEndpointServiceStateDeleted(conn *ec2.EC2, id string) resource.StateRefreshFunc { return func() (interface{}, string, error) { - err := FindVPCEndpointRouteTableAssociationExists(conn, vpcEndpointID, routeTableID) + output, err := FindVPCEndpointServiceConfigurationByID(conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -1119,38 +1134,43 @@ func StatusVPCEndpointRouteTableAssociation(conn *ec2.EC2, vpcEndpointID, routeT return nil, "", err } - return "", VPCEndpointRouteTableAssociationStatusReady, nil + return output, aws.StringValue(output.ServiceState), nil } } const ( - snapshotImportNotFound = "NotFound" + VPCEndpointRouteTableAssociationStatusReady = "ready" ) -func StatusEBSSnapshotImport(conn *ec2.EC2, importTaskId string) resource.StateRefreshFunc { +func StatusVPCEndpointRouteTableAssociation(conn *ec2.EC2, vpcEndpointID, routeTableID string) resource.StateRefreshFunc { return func() (interface{}, string, error) { - params := &ec2.DescribeImportSnapshotTasksInput{ - ImportTaskIds: []*string{aws.String(importTaskId)}, + err := FindVPCEndpointRouteTableAssociationExists(conn, vpcEndpointID, routeTableID) + + if tfresource.NotFound(err) { + return nil, "", nil } - resp, err := conn.DescribeImportSnapshotTasks(params) if err != nil { return nil, "", err } - if resp == nil || len(resp.ImportSnapshotTasks) < 1 { - return nil, snapshotImportNotFound, nil + return "", VPCEndpointRouteTableAssociationStatusReady, nil + } +} + +func StatusEBSSnapshotImport(conn *ec2.EC2, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindImportSnapshotTaskByID(conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil } - if task := resp.ImportSnapshotTasks[0]; task != nil { - detail := task.SnapshotTaskDetail - if detail.Status != nil && aws.StringValue(detail.Status) == EBSSnapshotImportStateDeleting { - err = fmt.Errorf("Snapshot import task is deleting") - } - return detail, aws.StringValue(detail.Status), err - } else { - return nil, snapshotImportNotFound, nil + if err != nil { + return nil, "", err } + + return output.SnapshotTaskDetail, aws.StringValue(output.SnapshotTaskDetail.Status), nil } } @@ -1170,9 +1190,9 @@ func statusVPCEndpointConnectionVPCEndpointState(conn *ec2.EC2, serviceID, vpcEn } } -func StatusSnapshotTierStatus(conn *ec2.EC2, id string) resource.StateRefreshFunc { +func StatusSnapshotStorageTier(conn *ec2.EC2, id string) resource.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSnapshotTierStatusById(conn, id) + output, err := FindSnapshotTierStatusBySnapshotID(conn, id) if tfresource.NotFound(err) { return nil, "", nil diff --git a/internal/service/ec2/sweep.go b/internal/service/ec2/sweep.go index 5a21f870170..4481c563329 100644 --- a/internal/service/ec2/sweep.go +++ b/internal/service/ec2/sweep.go @@ -98,6 +98,7 @@ func init() { Dependencies: []string{ "aws_autoscaling_group", "aws_spot_fleet_request", + "aws_spot_instance_request", }, }) @@ -115,6 +116,7 @@ func init() { "aws_elastic_beanstalk_environment", "aws_instance", "aws_spot_fleet_request", + "aws_spot_instance_request", }, F: sweepKeyPairs, }) @@ -159,6 +161,7 @@ func init() { "aws_instance", "aws_launch_template", "aws_spot_fleet_request", + "aws_spot_instance_request", }, }) @@ -180,6 +183,11 @@ func init() { F: sweepSpotFleetRequests, }) + resource.AddTestSweepers("aws_spot_instance_request", &resource.Sweeper{ + Name: "aws_spot_instance_request", + F: sweepSpotInstanceRequests, + }) + resource.AddTestSweepers("aws_subnet", &resource.Sweeper{ Name: "aws_subnet", F: sweepSubnets, @@ -222,6 +230,7 @@ func init() { "aws_route53_resolver_endpoint", "aws_sagemaker_notebook_instance", "aws_spot_fleet_request", + "aws_spot_instance_request", "aws_vpc_endpoint", }, }) @@ -326,10 +335,16 @@ func init() { }, }) + resource.AddTestSweepers("aws_vpc_ipam_pool_cidr_allocation", &resource.Sweeper{ + Name: "aws_vpc_ipam_pool_cidr_allocation", + F: sweepIPAMPoolCIDRAllocations, + }) + resource.AddTestSweepers("aws_vpc_ipam_pool_cidr", &resource.Sweeper{ Name: "aws_vpc_ipam_pool_cidr", F: sweepIPAMPoolCIDRs, Dependencies: []string{ + "aws_vpc_ipam_pool_cidr_allocation", "aws_vpc", }, }) @@ -1536,6 +1551,57 @@ func sweepSpotFleetRequests(region string) error { return errs.ErrorOrNil() } +func sweepSpotInstanceRequests(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + + conn := client.(*conns.AWSClient).EC2Conn + sweepResources := make([]*sweep.SweepResource, 0) + var errs *multierror.Error + + err = conn.DescribeSpotInstanceRequestsPages(&ec2.DescribeSpotInstanceRequestsInput{}, func(page *ec2.DescribeSpotInstanceRequestsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + if len(page.SpotInstanceRequests) == 0 { + log.Print("[DEBUG] No Spot Instance Requests to sweep") + return false + } + + for _, config := range page.SpotInstanceRequests { + id := aws.StringValue(config.SpotInstanceRequestId) + + r := ResourceSpotInstanceRequest() + d := r.Data(nil) + d.SetId(id) + d.Set("spot_instance_id", config.InstanceId) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + return !lastPage + }) + + if err != nil { + errs = multierror.Append(errs, fmt.Errorf("error describing EC2 Spot Instance Requests for %s: %w", region, err)) + } + + if err = sweep.SweepOrchestrator(sweepResources); err != nil { + errs = multierror.Append(errs, fmt.Errorf("error sweeping EC2 Spot Instance Requests for %s: %w", region, err)) + } + + if sweep.SkipSweepError(errs.ErrorOrNil()) { + log.Printf("[WARN] Skipping EC2 Spot Instance Requests sweep for %s: %s", region, errs) + return nil + } + + return errs.ErrorOrNil() +} + func sweepSubnets(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { @@ -2289,6 +2355,76 @@ func sweepCustomerGateways(region string) error { return nil } +func sweepIPAMPoolCIDRAllocations(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + conn := client.(*conns.AWSClient).EC2Conn + input := &ec2.DescribeIpamPoolsInput{} + var sweeperErrs *multierror.Error + sweepResources := make([]*sweep.SweepResource, 0) + + err = conn.DescribeIpamPoolsPages(input, func(page *ec2.DescribeIpamPoolsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.IpamPools { + poolID := aws.StringValue(v.IpamPoolId) + input := &ec2.GetIpamPoolAllocationsInput{ + IpamPoolId: v.IpamPoolId, + } + + err := conn.GetIpamPoolAllocationsPages(input, func(page *ec2.GetIpamPoolAllocationsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.IpamPoolAllocations { + r := ResourceIPAMPoolCIDRAllocation() + d := r.Data(nil) + d.SetId(encodeIPAMPoolCIDRAllocationID(aws.StringValue(v.IpamPoolAllocationId), poolID)) + d.Set("ipam_pool_id", poolID) + d.Set("ipam_pool_allocation_id", v.IpamPoolAllocationId) + d.Set("cidr", v.Cidr) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + return !lastPage + }) + + if sweep.SkipSweepError(err) { + continue + } + + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing IPAM Pool (%s) Allocations (%s): %w", poolID, region, err)) + } + } + + return !lastPage + }) + + if sweep.SkipSweepError(err) { + log.Printf("[WARN] Skipping IPAM Pool Allocations sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing IPAM Pools (%s): %w", region, err)) + } + + err = sweep.SweepOrchestrator(sweepResources) + + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping IPAM Pool Allocations (%s): %w", region, err)) + } + + return sweeperErrs.ErrorOrNil() +} + func sweepIPAMPoolCIDRs(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { @@ -2350,7 +2486,7 @@ func sweepIPAMPoolCIDRs(region string) error { err = sweep.SweepOrchestrator(sweepResources) if err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping IPAM Pools (%s): %w", region, err)) + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping IPAM Pool CIDRs (%s): %w", region, err)) } return sweeperErrs.ErrorOrNil() diff --git a/internal/service/ec2/transitgateway_connect_data_source_test.go b/internal/service/ec2/transitgateway_connect_data_source_test.go index 7052b3da7fd..91d5500dd7e 100644 --- a/internal/service/ec2/transitgateway_connect_data_source_test.go +++ b/internal/service/ec2/transitgateway_connect_data_source_test.go @@ -22,7 +22,7 @@ func testAccTransitGatewayConnectDataSource_Filter(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectFilterDataSourceConfig(rName), + Config: testAccTransitGatewayConnectDataSourceConfig_filter(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "protocol", resourceName, "protocol"), resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"), @@ -47,7 +47,7 @@ func testAccTransitGatewayConnectDataSource_ID(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectIDDataSourceConfig(rName), + Config: testAccTransitGatewayConnectDataSourceConfig_id(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "protocol", resourceName, "protocol"), resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"), @@ -60,7 +60,7 @@ func testAccTransitGatewayConnectDataSource_ID(t *testing.T) { }) } -func testAccTransitGatewayConnectFilterDataSourceConfig(rName string) string { +func testAccTransitGatewayConnectDataSourceConfig_filter(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -114,7 +114,7 @@ data "aws_ec2_transit_gateway_connect" "test" { `, rName)) } -func testAccTransitGatewayConnectIDDataSourceConfig(rName string) string { +func testAccTransitGatewayConnectDataSourceConfig_id(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_connect_peer_data_source_test.go b/internal/service/ec2/transitgateway_connect_peer_data_source_test.go index fbf47997ccf..0e8a461cd35 100644 --- a/internal/service/ec2/transitgateway_connect_peer_data_source_test.go +++ b/internal/service/ec2/transitgateway_connect_peer_data_source_test.go @@ -22,7 +22,7 @@ func testAccTransitGatewayConnectPeerDataSource_Filter(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectPeerFilterDataSourceConfig(rName), + Config: testAccTransitGatewayConnectPeerDataSourceConfig_filter(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "bgp_asn", resourceName, "bgp_asn"), @@ -50,7 +50,7 @@ func testAccTransitGatewayConnectPeerDataSource_ID(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectPeerIDDataSourceConfig(rName), + Config: testAccTransitGatewayConnectPeerDataSourceConfig_id(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "bgp_asn", resourceName, "bgp_asn"), @@ -66,7 +66,7 @@ func testAccTransitGatewayConnectPeerDataSource_ID(t *testing.T) { }) } -func testAccTransitGatewayConnectPeerFilterDataSourceConfig(rName string) string { +func testAccTransitGatewayConnectPeerDataSourceConfig_filter(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -132,7 +132,7 @@ data "aws_ec2_transit_gateway_connect_peer" "test" { `, rName)) } -func testAccTransitGatewayConnectPeerIDDataSourceConfig(rName string) string { +func testAccTransitGatewayConnectPeerDataSourceConfig_id(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_connect_peer_test.go b/internal/service/ec2/transitgateway_connect_peer_test.go index 862c24b99e6..f36bb1011d7 100644 --- a/internal/service/ec2/transitgateway_connect_peer_test.go +++ b/internal/service/ec2/transitgateway_connect_peer_test.go @@ -27,7 +27,7 @@ func testAccTransitGatewayConnectPeer_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayConnectPeerDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectPeerConfig(rName), + Config: testAccTransitGatewayConnectPeerConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectPeerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "bgp_asn", "64512"), @@ -59,7 +59,7 @@ func testAccTransitGatewayConnectPeer_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayConnectPeerDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectPeerConfig(rName), + Config: testAccTransitGatewayConnectPeerConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectPeerExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayConnectPeer(), resourceName), @@ -133,7 +133,7 @@ func testAccTransitGatewayConnectPeer_tags(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayConnectPeerDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectPeerConfigTags1(rName, "key1", "value1"), + Config: testAccTransitGatewayConnectPeerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectPeerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -146,7 +146,7 @@ func testAccTransitGatewayConnectPeer_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayConnectPeerConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTransitGatewayConnectPeerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectPeerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -155,7 +155,7 @@ func testAccTransitGatewayConnectPeer_tags(t *testing.T) { ), }, { - Config: testAccTransitGatewayConnectPeerConfigTags1(rName, "key2", "value2"), + Config: testAccTransitGatewayConnectPeerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectPeerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -178,7 +178,7 @@ func testAccTransitGatewayConnectPeer_TransitGatewayAddress(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayConnectPeerDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectPeerTransitGatewayAddressConfig(rName, "10.20.30.200"), + Config: testAccTransitGatewayConnectPeerConfig_address(rName, "10.20.30.200"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectPeerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "transit_gateway_address", "10.20.30.200"), @@ -237,7 +237,7 @@ func testAccCheckTransitGatewayConnectPeerDestroy(s *terraform.State) error { return nil } -func testAccTransitGatewayConnectPeerConfig(rName string) string { +func testAccTransitGatewayConnectPeerConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -352,7 +352,7 @@ resource "aws_ec2_transit_gateway_connect_peer" "test" { `, rName, bgpAsn)) } -func testAccTransitGatewayConnectPeerConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccTransitGatewayConnectPeerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -411,7 +411,7 @@ resource "aws_ec2_transit_gateway_connect_peer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccTransitGatewayConnectPeerConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTransitGatewayConnectPeerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -530,7 +530,7 @@ resource "aws_ec2_transit_gateway_connect_peer" "test" { `, rName)) } -func testAccTransitGatewayConnectPeerTransitGatewayAddressConfig(rName, transitGatewayAddress string) string { +func testAccTransitGatewayConnectPeerConfig_address(rName, transitGatewayAddress string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_connect_test.go b/internal/service/ec2/transitgateway_connect_test.go index 06bdee99d0c..9cb242604bc 100644 --- a/internal/service/ec2/transitgateway_connect_test.go +++ b/internal/service/ec2/transitgateway_connect_test.go @@ -31,7 +31,7 @@ func testAccTransitGatewayConnect_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayConnectDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectConfig(rName), + Config: testAccTransitGatewayConnectConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "protocol", "gre"), @@ -63,7 +63,7 @@ func testAccTransitGatewayConnect_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayConnectDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectConfig(rName), + Config: testAccTransitGatewayConnectConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayConnect(), resourceName), @@ -86,7 +86,7 @@ func testAccTransitGatewayConnect_tags(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayConnectDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectConfigTags1(rName, "key1", "value1"), + Config: testAccTransitGatewayConnectConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -99,7 +99,7 @@ func testAccTransitGatewayConnect_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayConnectConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTransitGatewayConnectConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -108,7 +108,7 @@ func testAccTransitGatewayConnect_tags(t *testing.T) { ), }, { - Config: testAccTransitGatewayConnectConfigTags1(rName, "key2", "value2"), + Config: testAccTransitGatewayConnectConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -133,7 +133,7 @@ func testAccTransitGatewayConnect_TransitGatewayDefaultRouteTableAssociationAndP CheckDestroy: testAccCheckTransitGatewayConnectDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectTransitGatewayDefaultRouteTableAssociationAndPropagationDisabledConfig(rName), + Config: testAccTransitGatewayConnectConfig_defaultRouteTableAssociationAndPropagationDisabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway1), testAccCheckTransitGatewayConnectExists(resourceName, &transitGatewayConnect1), @@ -166,7 +166,7 @@ func testAccTransitGatewayConnect_TransitGatewayDefaultRouteTableAssociation(t * CheckDestroy: testAccCheckTransitGatewayConnectDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectTransitGatewayDefaultRouteTableAssociationConfig(rName, false), + Config: testAccTransitGatewayConnectConfig_defaultRouteTableAssociation(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway1), testAccCheckTransitGatewayConnectExists(resourceName, &transitGatewayConnect1), @@ -180,7 +180,7 @@ func testAccTransitGatewayConnect_TransitGatewayDefaultRouteTableAssociation(t * ImportStateVerify: true, }, { - Config: testAccTransitGatewayConnectTransitGatewayDefaultRouteTableAssociationConfig(rName, true), + Config: testAccTransitGatewayConnectConfig_defaultRouteTableAssociation(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway2), testAccCheckTransitGatewayConnectExists(resourceName, &transitGatewayConnect2), @@ -190,7 +190,7 @@ func testAccTransitGatewayConnect_TransitGatewayDefaultRouteTableAssociation(t * ), }, { - Config: testAccTransitGatewayConnectTransitGatewayDefaultRouteTableAssociationConfig(rName, false), + Config: testAccTransitGatewayConnectConfig_defaultRouteTableAssociation(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway3), testAccCheckTransitGatewayConnectExists(resourceName, &transitGatewayConnect3), @@ -217,7 +217,7 @@ func testAccTransitGatewayConnect_TransitGatewayDefaultRouteTablePropagation(t * CheckDestroy: testAccCheckTransitGatewayConnectDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectTransitGatewayDefaultRouteTablePropagationConfig(rName, false), + Config: testAccTransitGatewayConnectConfig_defaultRouteTablePropagation(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway1), testAccCheckTransitGatewayConnectExists(resourceName, &transitGatewayConnect1), @@ -231,7 +231,7 @@ func testAccTransitGatewayConnect_TransitGatewayDefaultRouteTablePropagation(t * ImportStateVerify: true, }, { - Config: testAccTransitGatewayConnectTransitGatewayDefaultRouteTablePropagationConfig(rName, true), + Config: testAccTransitGatewayConnectConfig_defaultRouteTablePropagation(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway2), testAccCheckTransitGatewayConnectExists(resourceName, &transitGatewayConnect2), @@ -241,7 +241,7 @@ func testAccTransitGatewayConnect_TransitGatewayDefaultRouteTablePropagation(t * ), }, { - Config: testAccTransitGatewayConnectTransitGatewayDefaultRouteTablePropagationConfig(rName, false), + Config: testAccTransitGatewayConnectConfig_defaultRouteTablePropagation(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway3), testAccCheckTransitGatewayConnectExists(resourceName, &transitGatewayConnect3), @@ -331,7 +331,7 @@ func testAccPreCheckTransitGatewayConnect(t *testing.T) { } } -func testAccTransitGatewayConnectConfig(rName string) string { +func testAccTransitGatewayConnectConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -374,7 +374,7 @@ resource "aws_ec2_transit_gateway_connect" "test" { `, rName)) } -func testAccTransitGatewayConnectConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccTransitGatewayConnectConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -421,7 +421,7 @@ resource "aws_ec2_transit_gateway_connect" "test" { `, rName, tagKey1, tagValue1)) } -func testAccTransitGatewayConnectConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTransitGatewayConnectConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -469,7 +469,7 @@ resource "aws_ec2_transit_gateway_connect" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccTransitGatewayConnectTransitGatewayDefaultRouteTableAssociationAndPropagationDisabledConfig(rName string) string { +func testAccTransitGatewayConnectConfig_defaultRouteTableAssociationAndPropagationDisabled(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -523,7 +523,7 @@ resource "aws_ec2_transit_gateway_connect" "test" { `, rName)) } -func testAccTransitGatewayConnectTransitGatewayDefaultRouteTableAssociationConfig(rName string, transitGatewayDefaultRouteTableAssociation bool) string { +func testAccTransitGatewayConnectConfig_defaultRouteTableAssociation(rName string, transitGatewayDefaultRouteTableAssociation bool) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -572,7 +572,7 @@ resource "aws_ec2_transit_gateway_connect" "test" { `, rName, transitGatewayDefaultRouteTableAssociation)) } -func testAccTransitGatewayConnectTransitGatewayDefaultRouteTablePropagationConfig(rName string, transitGatewayDefaultRouteTablePropagation bool) string { +func testAccTransitGatewayConnectConfig_defaultRouteTablePropagation(rName string, transitGatewayDefaultRouteTablePropagation bool) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_data_source_test.go b/internal/service/ec2/transitgateway_data_source_test.go index 728fc685065..8908e40c995 100644 --- a/internal/service/ec2/transitgateway_data_source_test.go +++ b/internal/service/ec2/transitgateway_data_source_test.go @@ -84,7 +84,7 @@ func testAccTransitGatewayDataSource_Filter(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayFilterDataSourceConfig(), + Config: testAccTransitGatewayDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "amazon_side_asn", dataSourceName, "amazon_side_asn"), resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), @@ -117,7 +117,7 @@ func testAccTransitGatewayDataSource_ID(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayIDDataSourceConfig(), + Config: testAccTransitGatewayDataSourceConfig_id(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "amazon_side_asn", dataSourceName, "amazon_side_asn"), resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), @@ -138,7 +138,7 @@ func testAccTransitGatewayDataSource_ID(t *testing.T) { }) } -func testAccTransitGatewayFilterDataSourceConfig() string { +func testAccTransitGatewayDataSourceConfig_filter() string { return ` resource "aws_ec2_transit_gateway" "test" {} @@ -151,7 +151,7 @@ data "aws_ec2_transit_gateway" "test" { ` } -func testAccTransitGatewayIDDataSourceConfig() string { +func testAccTransitGatewayDataSourceConfig_id() string { return ` resource "aws_ec2_transit_gateway" "test" {} diff --git a/internal/service/ec2/transitgateway_dx_gateway_attachment_data_source_test.go b/internal/service/ec2/transitgateway_dx_gateway_attachment_data_source_test.go index 26b653a9f52..ea6292a8e44 100644 --- a/internal/service/ec2/transitgateway_dx_gateway_attachment_data_source_test.go +++ b/internal/service/ec2/transitgateway_dx_gateway_attachment_data_source_test.go @@ -27,7 +27,7 @@ func testAccTransitGatewayDxGatewayAttachmentDataSource_TransitGatewayIdAndDxGat CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayDxAttachmentDataSourceConfig(rName, rBgpAsn), + Config: testAccTransitGatewayDxGatewayAttachmentDataSourceConfig_transit(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "tags.%", "0"), resource.TestCheckResourceAttrPair(dataSourceName, "transit_gateway_id", transitGatewayResourceName, "id"), @@ -55,7 +55,7 @@ func testAccTransitGatewayDxGatewayAttachmentDataSource_filter(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayDxAttachmentFilterDataSourceConfig(rName, rBgpAsn), + Config: testAccTransitGatewayDxGatewayAttachmentDataSourceConfig_transitFilter(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "tags.%", "0"), resource.TestCheckResourceAttrPair(dataSourceName, "transit_gateway_id", transitGatewayResourceName, "id"), @@ -66,7 +66,7 @@ func testAccTransitGatewayDxGatewayAttachmentDataSource_filter(t *testing.T) { }) } -func testAccTransitGatewayDxAttachmentDataSourceConfig(rName string, rBgpAsn int) string { +func testAccTransitGatewayDxGatewayAttachmentDataSourceConfig_transit(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_dx_gateway" "test" { name = %[1]q @@ -96,7 +96,7 @@ data "aws_ec2_transit_gateway_dx_gateway_attachment" "test" { `, rName, rBgpAsn) } -func testAccTransitGatewayDxAttachmentFilterDataSourceConfig(rName string, rBgpAsn int) string { +func testAccTransitGatewayDxGatewayAttachmentDataSourceConfig_transitFilter(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_dx_gateway" "test" { name = %[1]q diff --git a/internal/service/ec2/transitgateway_multicast_domain_association_test.go b/internal/service/ec2/transitgateway_multicast_domain_association_test.go index 5e71adc8318..29c77a493aa 100644 --- a/internal/service/ec2/transitgateway_multicast_domain_association_test.go +++ b/internal/service/ec2/transitgateway_multicast_domain_association_test.go @@ -26,7 +26,7 @@ func testAccTransitGatewayMulticastDomainAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastDomainAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainAssociationConfig(rName), + Config: testAccTransitGatewayMulticastDomainAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastDomainAssociationExists(resourceName, &v), ), @@ -47,7 +47,7 @@ func testAccTransitGatewayMulticastDomainAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastDomainAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainAssociationConfig(rName), + Config: testAccTransitGatewayMulticastDomainAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastDomainAssociationExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayMulticastDomainAssociation(), resourceName), @@ -71,7 +71,7 @@ func testAccTransitGatewayMulticastDomainAssociation_Disappears_domain(t *testin CheckDestroy: testAccCheckTransitGatewayMulticastDomainAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainAssociationConfig(rName), + Config: testAccTransitGatewayMulticastDomainAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastDomainAssociationExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayMulticastDomain(), domainResourceName), @@ -95,7 +95,7 @@ func testAccTransitGatewayMulticastDomainAssociation_twoAssociations(t *testing. CheckDestroy: testAccCheckTransitGatewayMulticastDomainAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainAssociationTwoAssociationsConfig(rName), + Config: testAccTransitGatewayMulticastDomainAssociationConfig_twoAssociations(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastDomainAssociationExists(resource1Name, &v1), testAccCheckTransitGatewayMulticastDomainAssociationExists(resource2Name, &v2), @@ -166,7 +166,7 @@ func testAccCheckTransitGatewayMulticastDomainAssociationDestroy(s *terraform.St return nil } -func testAccTransitGatewayMulticastDomainAssociationConfig(rName string) string { +func testAccTransitGatewayMulticastDomainAssociationConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -220,7 +220,7 @@ resource "aws_ec2_transit_gateway_multicast_domain_association" "test" { `, rName)) } -func testAccTransitGatewayMulticastDomainAssociationTwoAssociationsConfig(rName string) string { +func testAccTransitGatewayMulticastDomainAssociationConfig_twoAssociations(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_multicast_domain_data_source_test.go b/internal/service/ec2/transitgateway_multicast_domain_data_source_test.go index a1ac364e777..48ab89ff471 100644 --- a/internal/service/ec2/transitgateway_multicast_domain_data_source_test.go +++ b/internal/service/ec2/transitgateway_multicast_domain_data_source_test.go @@ -21,7 +21,7 @@ func testAccTransitGatewayMulticastDomainDataSource_Filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainFilterDataSourceConfig(rName), + Config: testAccTransitGatewayMulticastDomainDataSourceConfig_filter(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttr(dataSourceName, "associations.#", "0"), @@ -51,7 +51,7 @@ func testAccTransitGatewayMulticastDomainDataSource_ID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainIDDataSourceConfig(rName), + Config: testAccTransitGatewayMulticastDomainDataSourceConfig_iD(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttr(dataSourceName, "associations.#", "1"), @@ -70,7 +70,7 @@ func testAccTransitGatewayMulticastDomainDataSource_ID(t *testing.T) { }) } -func testAccTransitGatewayMulticastDomainFilterDataSourceConfig(rName string) string { +func testAccTransitGatewayMulticastDomainDataSourceConfig_filter(rName string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { multicast_support = "enable" @@ -97,7 +97,7 @@ data "aws_ec2_transit_gateway_multicast_domain" "test" { `, rName) } -func testAccTransitGatewayMulticastDomainIDDataSourceConfig(rName string) string { +func testAccTransitGatewayMulticastDomainDataSourceConfig_iD(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_multicast_domain_test.go b/internal/service/ec2/transitgateway_multicast_domain_test.go index 5dd1bc49389..4937e634e0f 100644 --- a/internal/service/ec2/transitgateway_multicast_domain_test.go +++ b/internal/service/ec2/transitgateway_multicast_domain_test.go @@ -27,7 +27,7 @@ func testAccTransitGatewayMulticastDomain_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainConfig(rName), + Config: testAccTransitGatewayMulticastDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastDomainExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`transit-gateway-multicast-domain/.+`)), @@ -60,7 +60,7 @@ func testAccTransitGatewayMulticastDomain_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainConfig(rName), + Config: testAccTransitGatewayMulticastDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastDomainExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayMulticastDomain(), resourceName), @@ -83,7 +83,7 @@ func testAccTransitGatewayMulticastDomain_tags(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainConfigTags1(rName, "key1", "value1"), + Config: testAccTransitGatewayMulticastDomainConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastDomainExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -96,7 +96,7 @@ func testAccTransitGatewayMulticastDomain_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayMulticastDomainConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTransitGatewayMulticastDomainConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), @@ -104,7 +104,7 @@ func testAccTransitGatewayMulticastDomain_tags(t *testing.T) { ), }, { - Config: testAccTransitGatewayMulticastDomainConfigTags1(rName, "key2", "value2"), + Config: testAccTransitGatewayMulticastDomainConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), @@ -126,7 +126,7 @@ func testAccTransitGatewayMulticastDomain_igmpv2Support(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastDomainIGMPv2SupportConfig(rName), + Config: testAccTransitGatewayMulticastDomainConfig_igmpv2Support(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastDomainExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "auto_accept_shared_associations", "enable"), @@ -192,7 +192,7 @@ func testAccCheckTransitGatewayMulticastDomainDestroy(s *terraform.State) error return nil } -func testAccTransitGatewayMulticastDomainConfig(rName string) string { +func testAccTransitGatewayMulticastDomainConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { multicast_support = "enable" @@ -208,7 +208,7 @@ resource "aws_ec2_transit_gateway_multicast_domain" "test" { `, rName) } -func testAccTransitGatewayMulticastDomainConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccTransitGatewayMulticastDomainConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { multicast_support = "enable" @@ -228,7 +228,7 @@ resource "aws_ec2_transit_gateway_multicast_domain" "test" { `, rName, tagKey1, tagValue1) } -func testAccTransitGatewayMulticastDomainConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTransitGatewayMulticastDomainConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { multicast_support = "enable" @@ -248,7 +248,7 @@ resource "aws_ec2_transit_gateway_multicast_domain" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccTransitGatewayMulticastDomainIGMPv2SupportConfig(rName string) string { +func testAccTransitGatewayMulticastDomainConfig_igmpv2Support(rName string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { multicast_support = "enable" diff --git a/internal/service/ec2/transitgateway_multicast_group_member_test.go b/internal/service/ec2/transitgateway_multicast_group_member_test.go index 59b717ffefb..040426d6016 100644 --- a/internal/service/ec2/transitgateway_multicast_group_member_test.go +++ b/internal/service/ec2/transitgateway_multicast_group_member_test.go @@ -26,7 +26,7 @@ func testAccTransitGatewayMulticastGroupMember_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastGroupMemberDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastGroupMemberConfig(rName), + Config: testAccTransitGatewayMulticastGroupMemberConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastGroupMemberExists(resourceName, &v), ), @@ -47,7 +47,7 @@ func testAccTransitGatewayMulticastGroupMember_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastGroupMemberDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastGroupMemberConfig(rName), + Config: testAccTransitGatewayMulticastGroupMemberConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastGroupMemberExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayMulticastGroupMember(), resourceName), @@ -71,7 +71,7 @@ func testAccTransitGatewayMulticastGroupMember_Disappears_domain(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastGroupMemberDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastGroupMemberConfig(rName), + Config: testAccTransitGatewayMulticastGroupMemberConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastGroupMemberExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayMulticastDomain(), domainResourceName), @@ -95,7 +95,7 @@ func testAccTransitGatewayMulticastGroupMember_twoMembers(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastGroupMemberDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastGroupMemberTwoMembersConfig(rName), + Config: testAccTransitGatewayMulticastGroupMemberConfig_twoMembers(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastGroupMemberExists(resource1Name, &v1), testAccCheckTransitGatewayMulticastGroupMemberExists(resource2Name, &v2), @@ -166,7 +166,7 @@ func testAccCheckTransitGatewayMulticastGroupMemberDestroy(s *terraform.State) e return nil } -func testAccTransitGatewayMulticastGroupMemberConfig(rName string) string { +func testAccTransitGatewayMulticastGroupMemberConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -234,7 +234,7 @@ resource "aws_ec2_transit_gateway_multicast_group_member" "test" { `, rName)) } -func testAccTransitGatewayMulticastGroupMemberTwoMembersConfig(rName string) string { +func testAccTransitGatewayMulticastGroupMemberConfig_twoMembers(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_multicast_group_source_test.go b/internal/service/ec2/transitgateway_multicast_group_source_test.go index 11bcc540ad8..84257a1086d 100644 --- a/internal/service/ec2/transitgateway_multicast_group_source_test.go +++ b/internal/service/ec2/transitgateway_multicast_group_source_test.go @@ -26,7 +26,7 @@ func testAccTransitGatewayMulticastGroupSource_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastGroupSourceDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastGroupSourceConfig(rName), + Config: testAccTransitGatewayMulticastGroupSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastGroupSourceExists(resourceName, &v), ), @@ -47,7 +47,7 @@ func testAccTransitGatewayMulticastGroupSource_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastGroupSourceDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastGroupSourceConfig(rName), + Config: testAccTransitGatewayMulticastGroupSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastGroupSourceExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayMulticastGroupSource(), resourceName), @@ -71,7 +71,7 @@ func testAccTransitGatewayMulticastGroupSource_Disappears_domain(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayMulticastGroupSourceDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayMulticastGroupSourceConfig(rName), + Config: testAccTransitGatewayMulticastGroupSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayMulticastGroupSourceExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayMulticastDomain(), domainResourceName), @@ -143,7 +143,7 @@ func testAccCheckTransitGatewayMulticastGroupSourceDestroy(s *terraform.State) e return nil } -func testAccTransitGatewayMulticastGroupSourceConfig(rName string) string { +func testAccTransitGatewayMulticastGroupSourceConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_peering_attachment_accepter_test.go b/internal/service/ec2/transitgateway_peering_attachment_accepter_test.go index 38f3c2fab35..ff4b3debe86 100644 --- a/internal/service/ec2/transitgateway_peering_attachment_accepter_test.go +++ b/internal/service/ec2/transitgateway_peering_attachment_accepter_test.go @@ -33,7 +33,7 @@ func testAccTransitGatewayPeeringAttachmentAccepter_basic_sameAccount(t *testing CheckDestroy: testAccCheckTransitGatewayPeeringAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_basic_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_sameAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), resource.TestCheckResourceAttrPair(resourceName, "peer_account_id", transitGatewayResourceNamePeer, "owner_id"), @@ -45,7 +45,7 @@ func testAccTransitGatewayPeeringAttachmentAccepter_basic_sameAccount(t *testing ), }, { - Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_basic_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_sameAccount(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -71,7 +71,7 @@ func testAccTransitGatewayPeeringAttachmentAccepter_Tags_sameAccount(t *testing. CheckDestroy: testAccCheckTransitGatewayPeeringAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_tags_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_tagsSameAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), resource.TestCheckResourceAttr(resourceName, "tags.%", "4"), @@ -82,7 +82,7 @@ func testAccTransitGatewayPeeringAttachmentAccepter_Tags_sameAccount(t *testing. ), }, { - Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_tagsUpdated_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_tagsUpdatedSameAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), resource.TestCheckResourceAttr(resourceName, "tags.%", "4"), @@ -93,7 +93,7 @@ func testAccTransitGatewayPeeringAttachmentAccepter_Tags_sameAccount(t *testing. ), }, { - Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_tagsUpdated_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_tagsUpdatedSameAccount(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -122,7 +122,7 @@ func testAccTransitGatewayPeeringAttachmentAccepter_basic_differentAccount(t *te CheckDestroy: testAccCheckTransitGatewayPeeringAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_basic_differentAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_differentAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), resource.TestCheckResourceAttrPair(resourceName, "peer_account_id", transitGatewayResourceNamePeer, "owner_id"), @@ -134,7 +134,7 @@ func testAccTransitGatewayPeeringAttachmentAccepter_basic_differentAccount(t *te ), }, { - Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_basic_differentAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentAccepterConfig_differentAccount(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -172,7 +172,7 @@ resource "aws_ec2_transit_gateway_peering_attachment" "test" { `, rName) } -func testAccTransitGatewayPeeringAttachmentAccepterConfig_basic_sameAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentAccepterConfig_sameAccount(rName string) string { return acctest.ConfigCompose( acctest.ConfigAlternateRegionProvider(), testAccTransitGatewayPeeringAttachmentAccepterBaseConfig(rName), @@ -183,7 +183,7 @@ resource "aws_ec2_transit_gateway_peering_attachment_accepter" "test" { `) } -func testAccTransitGatewayPeeringAttachmentAccepterConfig_tags_sameAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentAccepterConfig_tagsSameAccount(rName string) string { return acctest.ConfigCompose( acctest.ConfigAlternateRegionProvider(), testAccTransitGatewayPeeringAttachmentAccepterBaseConfig(rName), @@ -200,7 +200,7 @@ resource "aws_ec2_transit_gateway_peering_attachment_accepter" "test" { `, rName)) } -func testAccTransitGatewayPeeringAttachmentAccepterConfig_tagsUpdated_sameAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentAccepterConfig_tagsUpdatedSameAccount(rName string) string { return acctest.ConfigCompose( acctest.ConfigAlternateRegionProvider(), testAccTransitGatewayPeeringAttachmentAccepterBaseConfig(rName), @@ -229,7 +229,7 @@ provider "awsalternate" { `, os.Getenv(conns.EnvVarAlternateAccessKeyId), os.Getenv(conns.EnvVarAlternateProfile), acctest.AlternateRegion(), os.Getenv(conns.EnvVarAlternateSecretAccessKey)) } -func testAccTransitGatewayPeeringAttachmentAccepterConfig_basic_differentAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentAccepterConfig_differentAccount(rName string) string { return acctest.ConfigCompose( testAccAlternateAccountAlternateRegionProviderConfig(), testAccTransitGatewayPeeringAttachmentAccepterBaseConfig(rName), diff --git a/internal/service/ec2/transitgateway_peering_attachment_data_source_test.go b/internal/service/ec2/transitgateway_peering_attachment_data_source_test.go index 7dc5ff5bb31..9d741cd2e49 100644 --- a/internal/service/ec2/transitgateway_peering_attachment_data_source_test.go +++ b/internal/service/ec2/transitgateway_peering_attachment_data_source_test.go @@ -27,7 +27,7 @@ func testAccTransitGatewayPeeringAttachmentDataSource_Filter_sameAccount(t *test CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentFilterDataSourceConfig_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentDataSourceConfig_filterSameAccount(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "peer_account_id", dataSourceName, "peer_account_id"), resource.TestCheckResourceAttrPair(resourceName, "peer_region", dataSourceName, "peer_region"), @@ -59,7 +59,7 @@ func testAccTransitGatewayPeeringAttachmentDataSource_Filter_differentAccount(t CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentFilterDataSourceConfig_differentAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentDataSourceConfig_filterDifferentAccount(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "peer_region", acctest.Region()), resource.TestCheckResourceAttrPair(transitGatewayResourceName, "owner_id", dataSourceName, "peer_account_id"), @@ -88,7 +88,7 @@ func testAccTransitGatewayPeeringAttachmentDataSource_ID_sameAccount(t *testing. CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentIDDataSourceConfig_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentDataSourceConfig_iDSameAccount(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "peer_account_id", dataSourceName, "peer_account_id"), resource.TestCheckResourceAttrPair(resourceName, "peer_region", dataSourceName, "peer_region"), @@ -120,7 +120,7 @@ func testAccTransitGatewayPeeringAttachmentDataSource_ID_differentAccount(t *tes CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentIDDataSourceConfig_differentAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentDataSourceConfig_iDDifferentAccount(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "peer_region", acctest.Region()), resource.TestCheckResourceAttrPair(transitGatewayResourceName, "owner_id", dataSourceName, "peer_account_id"), @@ -149,7 +149,7 @@ func testAccTransitGatewayPeeringAttachmentDataSource_Tags(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentTagsDataSourceConfig_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentDataSourceConfig_tagsSameAccount(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "peer_account_id", dataSourceName, "peer_account_id"), resource.TestCheckResourceAttrPair(resourceName, "peer_region", dataSourceName, "peer_region"), @@ -162,9 +162,9 @@ func testAccTransitGatewayPeeringAttachmentDataSource_Tags(t *testing.T) { }) } -func testAccTransitGatewayPeeringAttachmentFilterDataSourceConfig_sameAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentDataSourceConfig_filterSameAccount(rName string) string { return acctest.ConfigCompose( - testAccTransitGatewayPeeringAttachmentBasicConfig_sameAccount(rName), + testAccTransitGatewayPeeringAttachmentConfig_sameAccount(rName), ` data "aws_ec2_transit_gateway_peering_attachment" "test" { filter { @@ -175,9 +175,9 @@ data "aws_ec2_transit_gateway_peering_attachment" "test" { `) } -func testAccTransitGatewayPeeringAttachmentIDDataSourceConfig_sameAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentDataSourceConfig_iDSameAccount(rName string) string { return acctest.ConfigCompose( - testAccTransitGatewayPeeringAttachmentBasicConfig_sameAccount(rName), + testAccTransitGatewayPeeringAttachmentConfig_sameAccount(rName), ` data "aws_ec2_transit_gateway_peering_attachment" "test" { id = aws_ec2_transit_gateway_peering_attachment.test.id @@ -185,9 +185,9 @@ data "aws_ec2_transit_gateway_peering_attachment" "test" { `) } -func testAccTransitGatewayPeeringAttachmentTagsDataSourceConfig_sameAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentDataSourceConfig_tagsSameAccount(rName string) string { return acctest.ConfigCompose( - testAccTransitGatewayPeeringAttachmentTags1Config_sameAccount(rName, "Name", rName), + testAccTransitGatewayPeeringAttachmentConfig_tags1SameAccount(rName, "Name", rName), ` data "aws_ec2_transit_gateway_peering_attachment" "test" { tags = { @@ -197,9 +197,9 @@ data "aws_ec2_transit_gateway_peering_attachment" "test" { `) } -func testAccTransitGatewayPeeringAttachmentFilterDataSourceConfig_differentAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentDataSourceConfig_filterDifferentAccount(rName string) string { return acctest.ConfigCompose( - testAccTransitGatewayPeeringAttachmentBasicConfig_differentAccount(rName), + testAccTransitGatewayPeeringAttachmentConfig_differentAccount(rName), ` data "aws_ec2_transit_gateway_peering_attachment" "test" { provider = "awsalternate" @@ -212,9 +212,9 @@ data "aws_ec2_transit_gateway_peering_attachment" "test" { `) } -func testAccTransitGatewayPeeringAttachmentIDDataSourceConfig_differentAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentDataSourceConfig_iDDifferentAccount(rName string) string { return acctest.ConfigCompose( - testAccTransitGatewayPeeringAttachmentBasicConfig_differentAccount(rName), + testAccTransitGatewayPeeringAttachmentConfig_differentAccount(rName), ` data "aws_ec2_transit_gateway_peering_attachment" "test" { provider = "awsalternate" diff --git a/internal/service/ec2/transitgateway_peering_attachment_test.go b/internal/service/ec2/transitgateway_peering_attachment_test.go index 7c3f7ee3f68..1f2297c9117 100644 --- a/internal/service/ec2/transitgateway_peering_attachment_test.go +++ b/internal/service/ec2/transitgateway_peering_attachment_test.go @@ -35,7 +35,7 @@ func testAccTransitGatewayPeeringAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayPeeringAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentBasicConfig_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentConfig_sameAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), acctest.CheckResourceAttrAccountID(resourceName, "peer_account_id"), @@ -46,7 +46,7 @@ func testAccTransitGatewayPeeringAttachment_basic(t *testing.T) { ), }, { - Config: testAccTransitGatewayPeeringAttachmentBasicConfig_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentConfig_sameAccount(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -72,7 +72,7 @@ func testAccTransitGatewayPeeringAttachment_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayPeeringAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentBasicConfig_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentConfig_sameAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), testAccCheckTransitGatewayPeeringAttachmentDisappears(&transitGatewayPeeringAttachment), @@ -100,7 +100,7 @@ func testAccTransitGatewayPeeringAttachment_Tags_sameAccount(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayPeeringAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentTags1Config_sameAccount(rName, "key1", "value1"), + Config: testAccTransitGatewayPeeringAttachmentConfig_tags1SameAccount(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -109,13 +109,13 @@ func testAccTransitGatewayPeeringAttachment_Tags_sameAccount(t *testing.T) { ), }, { - Config: testAccTransitGatewayPeeringAttachmentTags1Config_sameAccount(rName, "key1", "value1"), + Config: testAccTransitGatewayPeeringAttachmentConfig_tags1SameAccount(rName, "key1", "value1"), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, { - Config: testAccTransitGatewayPeeringAttachmentTags2Config_sameAccount(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTransitGatewayPeeringAttachmentConfig_tags2SameAccount(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -125,7 +125,7 @@ func testAccTransitGatewayPeeringAttachment_Tags_sameAccount(t *testing.T) { ), }, { - Config: testAccTransitGatewayPeeringAttachmentBasicConfig_sameAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentConfig_sameAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -155,7 +155,7 @@ func testAccTransitGatewayPeeringAttachment_differentAccount(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayPeeringAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPeeringAttachmentBasicConfig_differentAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentConfig_differentAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayPeeringAttachmentExists(resourceName, &transitGatewayPeeringAttachment), // Test that the peer account ID != the primary (request) account ID @@ -172,7 +172,7 @@ func testAccTransitGatewayPeeringAttachment_differentAccount(t *testing.T) { ), }, { - Config: testAccTransitGatewayPeeringAttachmentBasicConfig_differentAccount(rName), + Config: testAccTransitGatewayPeeringAttachmentConfig_differentAccount(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -286,7 +286,7 @@ func testAccTransitGatewayPeeringAttachmentConfig_differentAccount_base(rName st return testAccAlternateAccountAlternateRegionProviderConfig() + testAccTransitGatewayPeeringAttachmentConfig_base(rName) } -func testAccTransitGatewayPeeringAttachmentBasicConfig_sameAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentConfig_sameAccount(rName string) string { return testAccTransitGatewayPeeringAttachmentConfig_sameAccount_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_peering_attachment" "test" { peer_region = %[1]q @@ -296,7 +296,7 @@ resource "aws_ec2_transit_gateway_peering_attachment" "test" { `, acctest.AlternateRegion()) } -func testAccTransitGatewayPeeringAttachmentBasicConfig_differentAccount(rName string) string { +func testAccTransitGatewayPeeringAttachmentConfig_differentAccount(rName string) string { return testAccTransitGatewayPeeringAttachmentConfig_differentAccount_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_peering_attachment" "test" { peer_account_id = aws_ec2_transit_gateway.peer.owner_id @@ -307,7 +307,7 @@ resource "aws_ec2_transit_gateway_peering_attachment" "test" { `, acctest.AlternateRegion()) } -func testAccTransitGatewayPeeringAttachmentTags1Config_sameAccount(rName, tagKey1, tagValue1 string) string { +func testAccTransitGatewayPeeringAttachmentConfig_tags1SameAccount(rName, tagKey1, tagValue1 string) string { return testAccTransitGatewayPeeringAttachmentConfig_sameAccount_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_peering_attachment" "test" { peer_region = %[1]q @@ -323,7 +323,7 @@ resource "aws_ec2_transit_gateway_peering_attachment" "test" { `, acctest.AlternateRegion(), rName, tagKey1, tagValue1) } -func testAccTransitGatewayPeeringAttachmentTags2Config_sameAccount(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTransitGatewayPeeringAttachmentConfig_tags2SameAccount(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccTransitGatewayPeeringAttachmentConfig_sameAccount_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_peering_attachment" "test" { peer_region = %[1]q diff --git a/internal/service/ec2/transitgateway_prefix_list_reference_test.go b/internal/service/ec2/transitgateway_prefix_list_reference_test.go index 5c8346ddc60..196f93f7020 100644 --- a/internal/service/ec2/transitgateway_prefix_list_reference_test.go +++ b/internal/service/ec2/transitgateway_prefix_list_reference_test.go @@ -31,7 +31,7 @@ func testAccTransitGatewayPrefixListReference_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayPrefixListReferenceDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPrefixListReferenceConfig_Blackhole(rName), + Config: testAccTransitGatewayPrefixListReferenceConfig_blackhole(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccTransitGatewayPrefixListReferenceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "blackhole", "true"), @@ -65,7 +65,7 @@ func testAccTransitGatewayPrefixListReference_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayPrefixListReferenceDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPrefixListReferenceConfig_Blackhole(rName), + Config: testAccTransitGatewayPrefixListReferenceConfig_blackhole(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccTransitGatewayPrefixListReferenceExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayPrefixListReference(), resourceName), @@ -92,7 +92,7 @@ func testAccTransitGatewayPrefixListReference_disappears_TransitGateway(t *testi CheckDestroy: testAccCheckTransitGatewayPrefixListReferenceDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPrefixListReferenceConfig_Blackhole(rName), + Config: testAccTransitGatewayPrefixListReferenceConfig_blackhole(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccTransitGatewayPrefixListReferenceExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGateway(), transitGatewayResourceName), @@ -120,7 +120,7 @@ func testAccTransitGatewayPrefixListReference_TransitGatewayAttachmentID(t *test CheckDestroy: testAccCheckTransitGatewayPrefixListReferenceDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayPrefixListReferenceConfig_TransitGatewayAttachmentID(rName, 0), + Config: testAccTransitGatewayPrefixListReferenceConfig_attachmentID(rName, 0), Check: resource.ComposeAggregateTestCheckFunc( testAccTransitGatewayPrefixListReferenceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "blackhole", "false"), @@ -133,7 +133,7 @@ func testAccTransitGatewayPrefixListReference_TransitGatewayAttachmentID(t *test ImportStateVerify: true, }, { - Config: testAccTransitGatewayPrefixListReferenceConfig_TransitGatewayAttachmentID(rName, 1), + Config: testAccTransitGatewayPrefixListReferenceConfig_attachmentID(rName, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccTransitGatewayPrefixListReferenceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "blackhole", "false"), @@ -203,7 +203,7 @@ func testAccTransitGatewayPrefixListReferenceExists(n string) resource.TestCheck } } -func testAccTransitGatewayPrefixListReferenceConfig_Blackhole(rName string) string { +func testAccTransitGatewayPrefixListReferenceConfig_blackhole(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { address_family = "IPv4" @@ -221,7 +221,7 @@ resource "aws_ec2_transit_gateway_prefix_list_reference" "test" { `, rName) } -func testAccTransitGatewayPrefixListReferenceConfig_TransitGatewayAttachmentID(rName string, index int) string { +func testAccTransitGatewayPrefixListReferenceConfig_attachmentID(rName string, index int) string { return fmt.Sprintf(` variable "index" { default = %[2]d diff --git a/internal/service/ec2/transitgateway_route_table_association_test.go b/internal/service/ec2/transitgateway_route_table_association_test.go index 6c20c635710..c4ac7f0381d 100644 --- a/internal/service/ec2/transitgateway_route_table_association_test.go +++ b/internal/service/ec2/transitgateway_route_table_association_test.go @@ -26,7 +26,7 @@ func testAccTransitGatewayRouteTableAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteTableAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTableAssociationConfig(), + Config: testAccTransitGatewayRouteTableAssociationConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteTableAssociationExists(resourceName, &transitGatewayRouteTablePropagtion1), resource.TestCheckResourceAttrSet(resourceName, "resource_id"), @@ -113,7 +113,7 @@ func testAccCheckTransitGatewayRouteTableAssociationDestroy(s *terraform.State) return nil } -func testAccTransitGatewayRouteTableAssociationConfig() string { +func testAccTransitGatewayRouteTableAssociationConfig_basic() string { return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_route_table_data_source_test.go b/internal/service/ec2/transitgateway_route_table_data_source_test.go index 993edbd2e39..0c5ce00fba3 100644 --- a/internal/service/ec2/transitgateway_route_table_data_source_test.go +++ b/internal/service/ec2/transitgateway_route_table_data_source_test.go @@ -19,7 +19,7 @@ func testAccTransitGatewayRouteTableDataSource_Filter(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTableFilterDataSourceConfig(), + Config: testAccTransitGatewayRouteTableDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "default_association_route_table", dataSourceName, "default_association_route_table"), resource.TestCheckResourceAttrPair(resourceName, "default_propagation_route_table", dataSourceName, "default_propagation_route_table"), @@ -43,7 +43,7 @@ func testAccTransitGatewayRouteTableDataSource_ID(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTableIDDataSourceConfig(), + Config: testAccTransitGatewayRouteTableDataSourceConfig_iD(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "default_association_route_table", dataSourceName, "default_association_route_table"), resource.TestCheckResourceAttrPair(resourceName, "default_propagation_route_table", dataSourceName, "default_propagation_route_table"), @@ -56,7 +56,7 @@ func testAccTransitGatewayRouteTableDataSource_ID(t *testing.T) { }) } -func testAccTransitGatewayRouteTableFilterDataSourceConfig() string { +func testAccTransitGatewayRouteTableDataSourceConfig_filter() string { return ` resource "aws_ec2_transit_gateway" "test" {} @@ -73,7 +73,7 @@ data "aws_ec2_transit_gateway_route_table" "test" { ` } -func testAccTransitGatewayRouteTableIDDataSourceConfig() string { +func testAccTransitGatewayRouteTableDataSourceConfig_iD() string { return ` resource "aws_ec2_transit_gateway" "test" {} diff --git a/internal/service/ec2/transitgateway_route_table_propagation_test.go b/internal/service/ec2/transitgateway_route_table_propagation_test.go index dd185e143e7..a1a9d922c22 100644 --- a/internal/service/ec2/transitgateway_route_table_propagation_test.go +++ b/internal/service/ec2/transitgateway_route_table_propagation_test.go @@ -27,7 +27,7 @@ func testAccTransitGatewayRouteTablePropagation_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteTablePropagationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTablePropagationConfig(), + Config: testAccTransitGatewayRouteTablePropagationConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteTablePropagationExists(resourceName, &transitGatewayRouteTablePropagtion1), resource.TestCheckResourceAttrSet(resourceName, "resource_id"), @@ -118,7 +118,7 @@ func testAccCheckTransitGatewayRouteTablePropagationDestroy(s *terraform.State) return nil } -func testAccTransitGatewayRouteTablePropagationConfig() string { +func testAccTransitGatewayRouteTablePropagationConfig_basic() string { return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_route_table_test.go b/internal/service/ec2/transitgateway_route_table_test.go index ef81a7e992f..ce0da56565e 100644 --- a/internal/service/ec2/transitgateway_route_table_test.go +++ b/internal/service/ec2/transitgateway_route_table_test.go @@ -28,7 +28,7 @@ func testAccTransitGatewayRouteTable_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTableConfig(), + Config: testAccTransitGatewayRouteTableConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteTableExists(resourceName, &transitGatewayRouteTable1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`transit-gateway-route-table/tgw-rtb-.+`)), @@ -58,7 +58,7 @@ func testAccTransitGatewayRouteTable_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTableConfig(), + Config: testAccTransitGatewayRouteTableConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteTableExists(resourceName, &transitGatewayRouteTable1), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayRouteTable(), resourceName), @@ -82,7 +82,7 @@ func testAccTransitGatewayRouteTable_disappears_TransitGateway(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTableConfig(), + Config: testAccTransitGatewayRouteTableConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway1), testAccCheckTransitGatewayRouteTableExists(resourceName, &transitGatewayRouteTable1), @@ -105,7 +105,7 @@ func testAccTransitGatewayRouteTable_Tags(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTableTags1Config("key1", "value1"), + Config: testAccTransitGatewayRouteTableConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteTableExists(resourceName, &transitGatewayRouteTable1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -118,7 +118,7 @@ func testAccTransitGatewayRouteTable_Tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayRouteTableTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccTransitGatewayRouteTableConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteTableExists(resourceName, &transitGatewayRouteTable2), testAccCheckTransitGatewayRouteTableNotRecreated(&transitGatewayRouteTable1, &transitGatewayRouteTable2), @@ -128,7 +128,7 @@ func testAccTransitGatewayRouteTable_Tags(t *testing.T) { ), }, { - Config: testAccTransitGatewayRouteTableTags1Config("key2", "value2"), + Config: testAccTransitGatewayRouteTableConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteTableExists(resourceName, &transitGatewayRouteTable3), testAccCheckTransitGatewayRouteTableNotRecreated(&transitGatewayRouteTable2, &transitGatewayRouteTable3), @@ -213,7 +213,7 @@ func testAccCheckTransitGatewayRouteTableNotRecreated(i, j *ec2.TransitGatewayRo } } -func testAccTransitGatewayRouteTableConfig() string { +func testAccTransitGatewayRouteTableConfig_basic() string { return ` resource "aws_ec2_transit_gateway" "test" {} @@ -223,7 +223,7 @@ resource "aws_ec2_transit_gateway_route_table" "test" { ` } -func testAccTransitGatewayRouteTableTags1Config(tagKey1, tagValue1 string) string { +func testAccTransitGatewayRouteTableConfig_tags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" {} @@ -237,7 +237,7 @@ resource "aws_ec2_transit_gateway_route_table" "test" { `, tagKey1, tagValue1) } -func testAccTransitGatewayRouteTableTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTransitGatewayRouteTableConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" {} diff --git a/internal/service/ec2/transitgateway_route_tables_data_source_test.go b/internal/service/ec2/transitgateway_route_tables_data_source_test.go index 25685aacdde..ecd173be5b5 100644 --- a/internal/service/ec2/transitgateway_route_tables_data_source_test.go +++ b/internal/service/ec2/transitgateway_route_tables_data_source_test.go @@ -20,7 +20,7 @@ func testAccTransitGatewayRouteTablesDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTablesDataSourceConfig(rName), + Config: testAccTransitGatewayRouteTablesDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "ids.#", "0"), ), @@ -39,7 +39,7 @@ func testAccTransitGatewayRouteTablesDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTablesTransitGatewayFilterDataSource(rName), + Config: testAccTransitGatewayRouteTablesDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "2"), ), @@ -58,7 +58,7 @@ func testAccTransitGatewayRouteTablesDataSource_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTablesTransitGatewayTagsDataSource(rName), + Config: testAccTransitGatewayRouteTablesDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), ), @@ -77,7 +77,7 @@ func testAccTransitGatewayRouteTablesDataSource_empty(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteTablesTransitGatewayEmptyDataSource(rName), + Config: testAccTransitGatewayRouteTablesDataSourceConfig_empty(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "0"), ), @@ -86,7 +86,7 @@ func testAccTransitGatewayRouteTablesDataSource_empty(t *testing.T) { }) } -func testAccTransitGatewayRouteTablesDataSourceConfig(rName string) string { +func testAccTransitGatewayRouteTablesDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { tags = { @@ -108,7 +108,7 @@ data "aws_ec2_transit_gateway_route_tables" "test" { `, rName) } -func testAccTransitGatewayRouteTablesTransitGatewayFilterDataSource(rName string) string { +func testAccTransitGatewayRouteTablesDataSourceConfig_filter(rName string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { tags = { @@ -135,7 +135,7 @@ data "aws_ec2_transit_gateway_route_tables" "test" { `, rName) } -func testAccTransitGatewayRouteTablesTransitGatewayTagsDataSource(rName string) string { +func testAccTransitGatewayRouteTablesDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { tags = { @@ -161,7 +161,7 @@ data "aws_ec2_transit_gateway_route_tables" "test" { `, rName) } -func testAccTransitGatewayRouteTablesTransitGatewayEmptyDataSource(rName string) string { +func testAccTransitGatewayRouteTablesDataSourceConfig_empty(rName string) string { return fmt.Sprintf(` data "aws_ec2_transit_gateway_route_tables" "test" { tags = { diff --git a/internal/service/ec2/transitgateway_route_test.go b/internal/service/ec2/transitgateway_route_test.go index 2836122b47c..c623af68eef 100644 --- a/internal/service/ec2/transitgateway_route_test.go +++ b/internal/service/ec2/transitgateway_route_test.go @@ -28,7 +28,7 @@ func testAccTransitGatewayRoute_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteDestinationCIDRBlockConfig(rName), + Config: testAccTransitGatewayRouteConfig_destinationCIDRBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", "0.0.0.0/0"), @@ -60,7 +60,7 @@ func testAccTransitGatewayRoute_basic_ipv6(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteDestinationCIDRBlockConfig(rName), + Config: testAccTransitGatewayRouteConfig_destinationCIDRBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", "2001:db8::/56"), @@ -91,7 +91,7 @@ func testAccTransitGatewayRoute_blackhole(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteDestinationCIDRBlockConfig(rName), + Config: testAccTransitGatewayRouteConfig_destinationCIDRBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", "10.1.0.0/16"), @@ -121,7 +121,7 @@ func testAccTransitGatewayRoute_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteDestinationCIDRBlockConfig(rName), + Config: testAccTransitGatewayRouteConfig_destinationCIDRBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayRoute(), resourceName), @@ -145,7 +145,7 @@ func testAccTransitGatewayRoute_disappears_TransitGatewayAttachment(t *testing.T CheckDestroy: testAccCheckTransitGatewayRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRouteDestinationCIDRBlockConfig(rName), + Config: testAccTransitGatewayRouteConfig_destinationCIDRBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRouteExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayVPCAttachment(), transitGatewayVpcAttachmentResourceName), @@ -217,7 +217,7 @@ func testAccCheckTransitGatewayRouteDestroy(s *terraform.State) error { return nil } -func testAccTransitGatewayRouteDestinationCIDRBlockConfig(rName string) string { +func testAccTransitGatewayRouteConfig_destinationCIDRBlock(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_test.go b/internal/service/ec2/transitgateway_test.go index 3fe193619a1..4285e37eee8 100644 --- a/internal/service/ec2/transitgateway_test.go +++ b/internal/service/ec2/transitgateway_test.go @@ -152,7 +152,7 @@ func testAccTransitGateway_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConfig(), + Config: testAccTransitGatewayConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "amazon_side_asn", "64512"), @@ -190,7 +190,7 @@ func testAccTransitGateway_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConfig(), + Config: testAccTransitGatewayConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGateway(), resourceName), @@ -212,7 +212,7 @@ func testAccTransitGateway_AmazonSideASN(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayAmazonSideASNConfig(64513), + Config: testAccTransitGatewayConfig_amazonSideASN(64513), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "amazon_side_asn", "64513"), @@ -224,7 +224,7 @@ func testAccTransitGateway_AmazonSideASN(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayAmazonSideASNConfig(64514), + Config: testAccTransitGatewayConfig_amazonSideASN(64514), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway2), testAccCheckTransitGatewayRecreated(&transitGateway1, &transitGateway2), @@ -246,7 +246,7 @@ func testAccTransitGateway_AutoAcceptSharedAttachments(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayAutoAcceptSharedAttachmentsConfig(ec2.AutoAcceptSharedAttachmentsValueEnable), + Config: testAccTransitGatewayConfig_autoAcceptSharedAttachments(ec2.AutoAcceptSharedAttachmentsValueEnable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "auto_accept_shared_attachments", ec2.AutoAcceptSharedAttachmentsValueEnable), @@ -258,7 +258,7 @@ func testAccTransitGateway_AutoAcceptSharedAttachments(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayAutoAcceptSharedAttachmentsConfig(ec2.AutoAcceptSharedAttachmentsValueDisable), + Config: testAccTransitGatewayConfig_autoAcceptSharedAttachments(ec2.AutoAcceptSharedAttachmentsValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway2), testAccCheckTransitGatewayNotRecreated(&transitGateway1, &transitGateway2), @@ -328,7 +328,7 @@ func testAccTransitGateway_DefaultRouteTableAssociationAndPropagationDisabled(t CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayDefaultRouteTableAssociationAndPropagationDisabledConfig(), + Config: testAccTransitGatewayConfig_defaultRouteTableAssociationAndPropagationDisabled(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "default_route_table_association", ec2.DefaultRouteTableAssociationValueDisable), @@ -355,7 +355,7 @@ func testAccTransitGateway_DefaultRouteTableAssociation(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayDefaultRouteTableAssociationConfig(ec2.DefaultRouteTableAssociationValueDisable), + Config: testAccTransitGatewayConfig_defaultRouteTableAssociation(ec2.DefaultRouteTableAssociationValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "default_route_table_association", ec2.DefaultRouteTableAssociationValueDisable), @@ -367,7 +367,7 @@ func testAccTransitGateway_DefaultRouteTableAssociation(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayDefaultRouteTableAssociationConfig(ec2.DefaultRouteTableAssociationValueEnable), + Config: testAccTransitGatewayConfig_defaultRouteTableAssociation(ec2.DefaultRouteTableAssociationValueEnable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway2), testAccCheckTransitGatewayRecreated(&transitGateway1, &transitGateway2), @@ -375,7 +375,7 @@ func testAccTransitGateway_DefaultRouteTableAssociation(t *testing.T) { ), }, { - Config: testAccTransitGatewayDefaultRouteTableAssociationConfig(ec2.DefaultRouteTableAssociationValueDisable), + Config: testAccTransitGatewayConfig_defaultRouteTableAssociation(ec2.DefaultRouteTableAssociationValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway3), testAccCheckTransitGatewayNotRecreated(&transitGateway2, &transitGateway3), @@ -397,7 +397,7 @@ func testAccTransitGateway_DefaultRouteTablePropagation(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayDefaultRouteTablePropagationConfig(ec2.DefaultRouteTablePropagationValueDisable), + Config: testAccTransitGatewayConfig_defaultRouteTablePropagation(ec2.DefaultRouteTablePropagationValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "default_route_table_propagation", ec2.DefaultRouteTablePropagationValueDisable), @@ -409,7 +409,7 @@ func testAccTransitGateway_DefaultRouteTablePropagation(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayDefaultRouteTablePropagationConfig(ec2.DefaultRouteTablePropagationValueEnable), + Config: testAccTransitGatewayConfig_defaultRouteTablePropagation(ec2.DefaultRouteTablePropagationValueEnable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway2), testAccCheckTransitGatewayRecreated(&transitGateway1, &transitGateway2), @@ -417,7 +417,7 @@ func testAccTransitGateway_DefaultRouteTablePropagation(t *testing.T) { ), }, { - Config: testAccTransitGatewayDefaultRouteTablePropagationConfig(ec2.DefaultRouteTablePropagationValueDisable), + Config: testAccTransitGatewayConfig_defaultRouteTablePropagation(ec2.DefaultRouteTablePropagationValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway3), testAccCheckTransitGatewayNotRecreated(&transitGateway2, &transitGateway3), @@ -439,7 +439,7 @@ func testAccTransitGateway_DNSSupport(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayDNSSupportConfig(ec2.DnsSupportValueDisable), + Config: testAccTransitGatewayConfig_dnsSupport(ec2.DnsSupportValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "dns_support", ec2.DnsSupportValueDisable), @@ -451,7 +451,7 @@ func testAccTransitGateway_DNSSupport(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayDNSSupportConfig(ec2.DnsSupportValueEnable), + Config: testAccTransitGatewayConfig_dnsSupport(ec2.DnsSupportValueEnable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway2), testAccCheckTransitGatewayNotRecreated(&transitGateway1, &transitGateway2), @@ -473,7 +473,7 @@ func testAccTransitGateway_VPNECMPSupport(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPNECMPSupportConfig(ec2.VpnEcmpSupportValueDisable), + Config: testAccTransitGatewayConfig_vpnECMPSupport(ec2.VpnEcmpSupportValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "vpn_ecmp_support", ec2.VpnEcmpSupportValueDisable), @@ -485,7 +485,7 @@ func testAccTransitGateway_VPNECMPSupport(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayVPNECMPSupportConfig(ec2.VpnEcmpSupportValueEnable), + Config: testAccTransitGatewayConfig_vpnECMPSupport(ec2.VpnEcmpSupportValueEnable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway2), testAccCheckTransitGatewayNotRecreated(&transitGateway1, &transitGateway2), @@ -507,7 +507,7 @@ func testAccTransitGateway_Description(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayDescriptionConfig("description1"), + Config: testAccTransitGatewayConfig_description("description1"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -519,7 +519,7 @@ func testAccTransitGateway_Description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayDescriptionConfig("description2"), + Config: testAccTransitGatewayConfig_description("description2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway2), testAccCheckTransitGatewayNotRecreated(&transitGateway1, &transitGateway2), @@ -541,7 +541,7 @@ func testAccTransitGateway_Tags(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayTags1Config("key1", "value1"), + Config: testAccTransitGatewayConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -554,7 +554,7 @@ func testAccTransitGateway_Tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccTransitGatewayConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway2), testAccCheckTransitGatewayNotRecreated(&transitGateway1, &transitGateway2), @@ -564,7 +564,7 @@ func testAccTransitGateway_Tags(t *testing.T) { ), }, { - Config: testAccTransitGatewayTags1Config("key2", "value2"), + Config: testAccTransitGatewayConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(resourceName, &transitGateway3), testAccCheckTransitGatewayNotRecreated(&transitGateway2, &transitGateway3), @@ -777,13 +777,13 @@ func testAccPreCheckTransitGateway(t *testing.T) { } } -func testAccTransitGatewayConfig() string { +func testAccTransitGatewayConfig_basic() string { return ` resource "aws_ec2_transit_gateway" "test" {} ` } -func testAccTransitGatewayAmazonSideASNConfig(amazonSideASN int) string { +func testAccTransitGatewayConfig_amazonSideASN(amazonSideASN int) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { amazon_side_asn = %d @@ -791,7 +791,7 @@ resource "aws_ec2_transit_gateway" "test" { `, amazonSideASN) } -func testAccTransitGatewayAutoAcceptSharedAttachmentsConfig(autoAcceptSharedAttachments string) string { +func testAccTransitGatewayConfig_autoAcceptSharedAttachments(autoAcceptSharedAttachments string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { auto_accept_shared_attachments = %q @@ -799,7 +799,7 @@ resource "aws_ec2_transit_gateway" "test" { `, autoAcceptSharedAttachments) } -func testAccTransitGatewayDefaultRouteTableAssociationAndPropagationDisabledConfig() string { +func testAccTransitGatewayConfig_defaultRouteTableAssociationAndPropagationDisabled() string { return ` resource "aws_ec2_transit_gateway" "test" { default_route_table_association = "disable" @@ -808,7 +808,7 @@ resource "aws_ec2_transit_gateway" "test" { ` } -func testAccTransitGatewayDefaultRouteTableAssociationConfig(defaultRouteTableAssociation string) string { +func testAccTransitGatewayConfig_defaultRouteTableAssociation(defaultRouteTableAssociation string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { default_route_table_association = %q @@ -816,7 +816,7 @@ resource "aws_ec2_transit_gateway" "test" { `, defaultRouteTableAssociation) } -func testAccTransitGatewayDefaultRouteTablePropagationConfig(defaultRouteTablePropagation string) string { +func testAccTransitGatewayConfig_defaultRouteTablePropagation(defaultRouteTablePropagation string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { default_route_table_propagation = %q @@ -824,7 +824,7 @@ resource "aws_ec2_transit_gateway" "test" { `, defaultRouteTablePropagation) } -func testAccTransitGatewayDNSSupportConfig(dnsSupport string) string { +func testAccTransitGatewayConfig_dnsSupport(dnsSupport string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { dns_support = %q @@ -832,7 +832,7 @@ resource "aws_ec2_transit_gateway" "test" { `, dnsSupport) } -func testAccTransitGatewayVPNECMPSupportConfig(vpnEcmpSupport string) string { +func testAccTransitGatewayConfig_vpnECMPSupport(vpnEcmpSupport string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { vpn_ecmp_support = %q @@ -840,7 +840,7 @@ resource "aws_ec2_transit_gateway" "test" { `, vpnEcmpSupport) } -func testAccTransitGatewayDescriptionConfig(description string) string { +func testAccTransitGatewayConfig_description(description string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { description = %q @@ -848,7 +848,7 @@ resource "aws_ec2_transit_gateway" "test" { `, description) } -func testAccTransitGatewayTags1Config(tagKey1, tagValue1 string) string { +func testAccTransitGatewayConfig_tags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { tags = { @@ -858,7 +858,7 @@ resource "aws_ec2_transit_gateway" "test" { `, tagKey1, tagValue1) } -func testAccTransitGatewayTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTransitGatewayConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { tags = { diff --git a/internal/service/ec2/transitgateway_vpc_attachment_data_source_test.go b/internal/service/ec2/transitgateway_vpc_attachment_data_source_test.go index 46330c6307a..3d8fb1bdfdc 100644 --- a/internal/service/ec2/transitgateway_vpc_attachment_data_source_test.go +++ b/internal/service/ec2/transitgateway_vpc_attachment_data_source_test.go @@ -19,7 +19,7 @@ func testAccTransitGatewayVPCAttachmentDataSource_Filter(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentFilterDataSourceConfig(), + Config: testAccTransitGatewayVPCAttachmentDataSourceConfig_filter(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "appliance_mode_support", dataSourceName, "appliance_mode_support"), resource.TestCheckResourceAttrPair(resourceName, "dns_support", dataSourceName, "dns_support"), @@ -46,7 +46,7 @@ func testAccTransitGatewayVPCAttachmentDataSource_ID(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentIDDataSourceConfig(), + Config: testAccTransitGatewayVPCAttachmentDataSourceConfig_iD(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "appliance_mode_support", dataSourceName, "appliance_mode_support"), resource.TestCheckResourceAttrPair(resourceName, "dns_support", dataSourceName, "dns_support"), @@ -62,7 +62,7 @@ func testAccTransitGatewayVPCAttachmentDataSource_ID(t *testing.T) { }) } -func testAccTransitGatewayVPCAttachmentFilterDataSourceConfig() string { +func testAccTransitGatewayVPCAttachmentDataSourceConfig_filter() string { return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -99,7 +99,7 @@ data "aws_ec2_transit_gateway_vpc_attachment" "test" { ` } -func testAccTransitGatewayVPCAttachmentIDDataSourceConfig() string { +func testAccTransitGatewayVPCAttachmentDataSourceConfig_iD() string { return acctest.ConfigAvailableAZsNoOptInDefaultExclude() + ` # IncorrectState: Transit Gateway is not available in availability zone usw2-az4 diff --git a/internal/service/ec2/transitgateway_vpc_attachment_test.go b/internal/service/ec2/transitgateway_vpc_attachment_test.go index 57b31b60e3f..68a0dd88a3c 100644 --- a/internal/service/ec2/transitgateway_vpc_attachment_test.go +++ b/internal/service/ec2/transitgateway_vpc_attachment_test.go @@ -31,7 +31,7 @@ func testAccTransitGatewayVPCAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentConfig(), + Config: testAccTransitGatewayVPCAttachmentConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), resource.TestCheckResourceAttr(resourceName, "dns_support", ec2.DnsSupportValueEnable), @@ -65,7 +65,7 @@ func testAccTransitGatewayVPCAttachment_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentConfig(), + Config: testAccTransitGatewayVPCAttachmentConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), testAccCheckTransitGatewayVPCAttachmentDisappears(&transitGatewayVpcAttachment1), @@ -87,15 +87,15 @@ func testAccTransitGatewayVPCAttachment_ApplianceModeSupport(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentApplianceModeSupportConfig("false"), + Config: testAccTransitGatewayVPCAttachmentConfig_applianceModeSupport("false"), ExpectError: regexp.MustCompile(`expected appliance_mode_support to be one of`), }, { - Config: testAccTransitGatewayVPCAttachmentApplianceModeSupportConfig("true"), + Config: testAccTransitGatewayVPCAttachmentConfig_applianceModeSupport("true"), ExpectError: regexp.MustCompile(`expected appliance_mode_support to be one of`), }, { - Config: testAccTransitGatewayVPCAttachmentApplianceModeSupportConfig(ec2.ApplianceModeSupportValueDisable), + Config: testAccTransitGatewayVPCAttachmentConfig_applianceModeSupport(ec2.ApplianceModeSupportValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), resource.TestCheckResourceAttr(resourceName, "appliance_mode_support", ec2.ApplianceModeSupportValueDisable), @@ -107,7 +107,7 @@ func testAccTransitGatewayVPCAttachment_ApplianceModeSupport(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayVPCAttachmentApplianceModeSupportConfig(ec2.ApplianceModeSupportValueEnable), + Config: testAccTransitGatewayVPCAttachmentConfig_applianceModeSupport(ec2.ApplianceModeSupportValueEnable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment2), testAccCheckTransitGatewayVPCAttachmentNotRecreated(&transitGatewayVpcAttachment1, &transitGatewayVpcAttachment2), @@ -129,7 +129,7 @@ func testAccTransitGatewayVPCAttachment_DNSSupport(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentDNSSupportConfig(ec2.DnsSupportValueDisable), + Config: testAccTransitGatewayVPCAttachmentConfig_dnsSupport(ec2.DnsSupportValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), resource.TestCheckResourceAttr(resourceName, "dns_support", ec2.DnsSupportValueDisable), @@ -141,7 +141,7 @@ func testAccTransitGatewayVPCAttachment_DNSSupport(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayVPCAttachmentDNSSupportConfig(ec2.DnsSupportValueEnable), + Config: testAccTransitGatewayVPCAttachmentConfig_dnsSupport(ec2.DnsSupportValueEnable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment2), testAccCheckTransitGatewayVPCAttachmentNotRecreated(&transitGatewayVpcAttachment1, &transitGatewayVpcAttachment2), @@ -164,7 +164,7 @@ func testAccTransitGatewayVPCAttachment_IPv6Support(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentIPv6SupportConfig(rName, ec2.Ipv6SupportValueEnable), + Config: testAccTransitGatewayVPCAttachmentConfig_ipv6Support(rName, ec2.Ipv6SupportValueEnable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), resource.TestCheckResourceAttr(resourceName, "ipv6_support", ec2.Ipv6SupportValueEnable), @@ -176,7 +176,7 @@ func testAccTransitGatewayVPCAttachment_IPv6Support(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayVPCAttachmentIPv6SupportConfig(rName, ec2.Ipv6SupportValueDisable), + Config: testAccTransitGatewayVPCAttachmentConfig_ipv6Support(rName, ec2.Ipv6SupportValueDisable), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment2), testAccCheckTransitGatewayVPCAttachmentNotRecreated(&transitGatewayVpcAttachment1, &transitGatewayVpcAttachment2), @@ -204,13 +204,13 @@ func testAccTransitGatewayVPCAttachment_SharedTransitGateway(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentSharedTransitGatewayConfig(rName), + Config: testAccTransitGatewayVPCAttachmentConfig_sharedTransitGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), ), }, { - Config: testAccTransitGatewayVPCAttachmentSharedTransitGatewayConfig(rName), + Config: testAccTransitGatewayVPCAttachmentConfig_sharedTransitGateway(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -230,7 +230,7 @@ func testAccTransitGatewayVPCAttachment_SubnetIDs(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentSubnetIds2Config(), + Config: testAccTransitGatewayVPCAttachmentConfig_subnetIds2(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), @@ -242,7 +242,7 @@ func testAccTransitGatewayVPCAttachment_SubnetIDs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayVPCAttachmentSubnetIds1Config(), + Config: testAccTransitGatewayVPCAttachmentConfig_subnetIds1(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment2), testAccCheckTransitGatewayVPCAttachmentNotRecreated(&transitGatewayVpcAttachment1, &transitGatewayVpcAttachment2), @@ -250,7 +250,7 @@ func testAccTransitGatewayVPCAttachment_SubnetIDs(t *testing.T) { ), }, { - Config: testAccTransitGatewayVPCAttachmentSubnetIds2Config(), + Config: testAccTransitGatewayVPCAttachmentConfig_subnetIds2(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment3), testAccCheckTransitGatewayVPCAttachmentNotRecreated(&transitGatewayVpcAttachment2, &transitGatewayVpcAttachment3), @@ -272,7 +272,7 @@ func testAccTransitGatewayVPCAttachment_Tags(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentTags1Config("key1", "value1"), + Config: testAccTransitGatewayVPCAttachmentConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -285,7 +285,7 @@ func testAccTransitGatewayVPCAttachment_Tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTransitGatewayVPCAttachmentTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccTransitGatewayVPCAttachmentConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment2), testAccCheckTransitGatewayVPCAttachmentNotRecreated(&transitGatewayVpcAttachment1, &transitGatewayVpcAttachment2), @@ -295,7 +295,7 @@ func testAccTransitGatewayVPCAttachment_Tags(t *testing.T) { ), }, { - Config: testAccTransitGatewayVPCAttachmentTags1Config("key2", "value2"), + Config: testAccTransitGatewayVPCAttachmentConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment3), testAccCheckTransitGatewayVPCAttachmentNotRecreated(&transitGatewayVpcAttachment2, &transitGatewayVpcAttachment3), @@ -320,7 +320,7 @@ func testAccTransitGatewayVPCAttachment_TransitGatewayDefaultRouteTableAssociati CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTableAssociationAndPropagationDisabledConfig(), + Config: testAccTransitGatewayVPCAttachmentConfig_defaultRouteTableAssociationAndPropagationDisabled(), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway1), testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), @@ -352,7 +352,7 @@ func testAccTransitGatewayVPCAttachment_TransitGatewayDefaultRouteTableAssociati CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTableAssociationConfig(false), + Config: testAccTransitGatewayVPCAttachmentConfig_defaultRouteTableAssociation(false), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway1), testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), @@ -366,7 +366,7 @@ func testAccTransitGatewayVPCAttachment_TransitGatewayDefaultRouteTableAssociati ImportStateVerify: true, }, { - Config: testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTableAssociationConfig(true), + Config: testAccTransitGatewayVPCAttachmentConfig_defaultRouteTableAssociation(true), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway2), testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment2), @@ -376,7 +376,7 @@ func testAccTransitGatewayVPCAttachment_TransitGatewayDefaultRouteTableAssociati ), }, { - Config: testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTableAssociationConfig(false), + Config: testAccTransitGatewayVPCAttachmentConfig_defaultRouteTableAssociation(false), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway3), testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment3), @@ -402,7 +402,7 @@ func testAccTransitGatewayVPCAttachment_TransitGatewayDefaultRouteTablePropagati CheckDestroy: testAccCheckTransitGatewayVPCAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTablePropagationConfig(false), + Config: testAccTransitGatewayVPCAttachmentConfig_defaultRouteTablePropagation(false), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway1), testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment1), @@ -416,7 +416,7 @@ func testAccTransitGatewayVPCAttachment_TransitGatewayDefaultRouteTablePropagati ImportStateVerify: true, }, { - Config: testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTablePropagationConfig(true), + Config: testAccTransitGatewayVPCAttachmentConfig_defaultRouteTablePropagation(true), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway2), testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment2), @@ -426,7 +426,7 @@ func testAccTransitGatewayVPCAttachment_TransitGatewayDefaultRouteTablePropagati ), }, { - Config: testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTablePropagationConfig(false), + Config: testAccTransitGatewayVPCAttachmentConfig_defaultRouteTablePropagation(false), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayExists(transitGatewayResourceName, &transitGateway3), testAccCheckTransitGatewayVPCAttachmentExists(resourceName, &transitGatewayVpcAttachment3), @@ -546,7 +546,7 @@ func testAccPreCheckTransitGatewayVPCAttachment(t *testing.T) { } } -func testAccTransitGatewayVPCAttachmentConfig() string { +func testAccTransitGatewayVPCAttachmentConfig_basic() string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -576,7 +576,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `) } -func testAccTransitGatewayVPCAttachmentApplianceModeSupportConfig(appModeSupport string) string { +func testAccTransitGatewayVPCAttachmentConfig_applianceModeSupport(appModeSupport string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -608,7 +608,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `, appModeSupport)) } -func testAccTransitGatewayVPCAttachmentDNSSupportConfig(dnsSupport string) string { +func testAccTransitGatewayVPCAttachmentConfig_dnsSupport(dnsSupport string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -640,7 +640,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `, dnsSupport)) } -func testAccTransitGatewayVPCAttachmentIPv6SupportConfig(rName, ipv6Support string) string { +func testAccTransitGatewayVPCAttachmentConfig_ipv6Support(rName, ipv6Support string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { assign_generated_ipv6_cidr_block = true @@ -681,7 +681,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `, rName, ipv6Support)) } -func testAccTransitGatewayVPCAttachmentSharedTransitGatewayConfig(rName string) string { +func testAccTransitGatewayVPCAttachmentConfig_sharedTransitGateway(rName string) string { return acctest.ConfigCompose( acctest.ConfigAlternateAccountProvider(), acctest.ConfigAvailableAZsNoOptInDefaultExclude(), @@ -740,7 +740,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `, rName)) } -func testAccTransitGatewayVPCAttachmentSubnetIds1Config() string { +func testAccTransitGatewayVPCAttachmentConfig_subnetIds1() string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -772,7 +772,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `) } -func testAccTransitGatewayVPCAttachmentSubnetIds2Config() string { +func testAccTransitGatewayVPCAttachmentConfig_subnetIds2() string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -804,7 +804,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `) } -func testAccTransitGatewayVPCAttachmentTags1Config(tagKey1, tagValue1 string) string { +func testAccTransitGatewayVPCAttachmentConfig_tags1(tagKey1, tagValue1 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -838,7 +838,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `, tagKey1, tagValue1)) } -func testAccTransitGatewayVPCAttachmentTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTransitGatewayVPCAttachmentConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -873,7 +873,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTableAssociationAndPropagationDisabledConfig() string { +func testAccTransitGatewayVPCAttachmentConfig_defaultRouteTableAssociationAndPropagationDisabled() string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -908,7 +908,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `) } -func testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTableAssociationConfig(transitGatewayDefaultRouteTableAssociation bool) string { +func testAccTransitGatewayVPCAttachmentConfig_defaultRouteTableAssociation(transitGatewayDefaultRouteTableAssociation bool) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -940,7 +940,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { `, transitGatewayDefaultRouteTableAssociation)) } -func testAccTransitGatewayVPCAttachmentTransitGatewayDefaultRouteTablePropagationConfig(transitGatewayDefaultRouteTablePropagation bool) string { +func testAccTransitGatewayVPCAttachmentConfig_defaultRouteTablePropagation(transitGatewayDefaultRouteTablePropagation bool) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_vpc_attachments_data_source_test.go b/internal/service/ec2/transitgateway_vpc_attachments_data_source_test.go index aea5d091f14..c3756c623b7 100644 --- a/internal/service/ec2/transitgateway_vpc_attachments_data_source_test.go +++ b/internal/service/ec2/transitgateway_vpc_attachments_data_source_test.go @@ -19,7 +19,7 @@ func testAccTransitGatewayVPCAttachmentsDataSource_Filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPCAttachmentsDataSourceConfig(rName), + Config: testAccTransitGatewayVPCAttachmentsDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_ec2_transit_gateway_vpc_attachments.by_attachment_id", "ids.#", "1"), resource.TestCheckResourceAttr("data.aws_ec2_transit_gateway_vpc_attachments.by_gateway_id", "ids.#", "2"), @@ -29,7 +29,7 @@ func testAccTransitGatewayVPCAttachmentsDataSource_Filter(t *testing.T) { }) } -func testAccTransitGatewayVPCAttachmentsDataSourceConfig(rName string) string { +func testAccTransitGatewayVPCAttachmentsDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/transitgateway_vpn_attachment_data_source_test.go b/internal/service/ec2/transitgateway_vpn_attachment_data_source_test.go index 6ba80348462..848493b1882 100644 --- a/internal/service/ec2/transitgateway_vpn_attachment_data_source_test.go +++ b/internal/service/ec2/transitgateway_vpn_attachment_data_source_test.go @@ -26,7 +26,7 @@ func testAccTransitGatewayVPNAttachmentDataSource_idAndVPNConnectionID(t *testin CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPNAttachmentDataSourceConfig_idAndVPNConnectionID2(rBgpAsn), + Config: testAccTransitGatewayVPNAttachmentDataSourceConfig_idAndConnectionID2(rBgpAsn), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "tags.%", "0"), resource.TestCheckResourceAttrPair(dataSourceName, "transit_gateway_id", transitGatewayResourceName, "id"), @@ -53,7 +53,7 @@ func testAccTransitGatewayVPNAttachmentDataSource_filter(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayVPNAttachmentFilterDataSourceConfig(rBgpAsn), + Config: testAccTransitGatewayVPNAttachmentDataSourceConfig_filter(rBgpAsn), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "tags.%", "0"), resource.TestCheckResourceAttrPair(dataSourceName, "transit_gateway_id", transitGatewayResourceName, "id"), @@ -94,7 +94,7 @@ resource "aws_vpn_connection" "test" { `, rBgpAsn) } -func testAccTransitGatewayVPNAttachmentDataSourceConfig_idAndVPNConnectionID2(rBgpAsn int) string { +func testAccTransitGatewayVPNAttachmentDataSourceConfig_idAndConnectionID2(rBgpAsn int) string { return testAccTransitGatewayVPNAttachmentBaseDataSourceConfig(rBgpAsn) + ` data "aws_ec2_transit_gateway_vpn_attachment" "test" { transit_gateway_id = aws_ec2_transit_gateway.test.id @@ -103,7 +103,7 @@ data "aws_ec2_transit_gateway_vpn_attachment" "test" { ` } -func testAccTransitGatewayVPNAttachmentFilterDataSourceConfig(rBgpAsn int) string { +func testAccTransitGatewayVPNAttachmentDataSourceConfig_filter(rBgpAsn int) string { return testAccTransitGatewayVPNAttachmentBaseDataSourceConfig(rBgpAsn) + ` data "aws_ec2_transit_gateway_vpn_attachment" "test" { filter { diff --git a/internal/service/ec2/vpc_data_source_test.go b/internal/service/ec2/vpc_data_source_test.go index e7e14d8cfa1..11426a56a76 100644 --- a/internal/service/ec2/vpc_data_source_test.go +++ b/internal/service/ec2/vpc_data_source_test.go @@ -28,7 +28,7 @@ func TestAccVPCDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCDataSourceConfig(rName, cidr), + Config: testAccVPCDataSourceConfig_basic(rName, cidr), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(ds1ResourceName, "arn", vpcResourceName, "arn"), resource.TestCheckResourceAttr(ds1ResourceName, "cidr_block", cidr), @@ -72,7 +72,7 @@ func TestAccVPCDataSource_CIDRBlockAssociations_multiple(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCCIDRBlockAssociationsMultipleDataSourceConfig(rName), + Config: testAccVPCDataSourceConfig_cidrBlockAssociationsMultiple(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "cidr_block_associations.#", "2"), ), @@ -81,7 +81,7 @@ func TestAccVPCDataSource_CIDRBlockAssociations_multiple(t *testing.T) { }) } -func testAccVPCDataSourceConfig(rName, cidr string) string { +func testAccVPCDataSourceConfig_basic(rName, cidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = %[2]q @@ -116,7 +116,7 @@ data "aws_vpc" "by_filter" { `, rName, cidr) } -func testAccVPCCIDRBlockAssociationsMultipleDataSourceConfig(rName string) string { +func testAccVPCDataSourceConfig_cidrBlockAssociationsMultiple(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/vpc_default_network_acl_test.go b/internal/service/ec2/vpc_default_network_acl_test.go index 4e1a2af2fe1..9a315ef646e 100644 --- a/internal/service/ec2/vpc_default_network_acl_test.go +++ b/internal/service/ec2/vpc_default_network_acl_test.go @@ -28,7 +28,7 @@ func TestAccVPCDefaultNetworkACL_basic(t *testing.T) { CheckDestroy: testAccCheckDefaultNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultNetworkACLConfig(rName), + Config: testAccVPCDefaultNetworkACLConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`network-acl/acl-.+`)), @@ -61,7 +61,7 @@ func TestAccVPCDefaultNetworkACL_basicIPv6VPC(t *testing.T) { CheckDestroy: testAccCheckDefaultNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultNetworkACLIPv6Config(rName), + Config: testAccVPCDefaultNetworkACLConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -89,7 +89,7 @@ func TestAccVPCDefaultNetworkACL_tags(t *testing.T) { CheckDestroy: testAccCheckDefaultNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultNetworkACLTags1Config(rName, "key1", "value1"), + Config: testAccVPCDefaultNetworkACLConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -102,7 +102,7 @@ func TestAccVPCDefaultNetworkACL_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDefaultNetworkACLTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCDefaultNetworkACLConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -111,7 +111,7 @@ func TestAccVPCDefaultNetworkACL_tags(t *testing.T) { ), }, { - Config: testAccDefaultNetworkACLTags1Config(rName, "key2", "value2"), + Config: testAccVPCDefaultNetworkACLConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -134,7 +134,7 @@ func TestAccVPCDefaultNetworkACL_Deny_ingress(t *testing.T) { CheckDestroy: testAccCheckDefaultNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultNetworkACLDenyIngressConfig(rName), + Config: testAccVPCDefaultNetworkACLConfig_denyIngress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -170,7 +170,7 @@ func TestAccVPCDefaultNetworkACL_withIPv6Ingress(t *testing.T) { CheckDestroy: testAccCheckDefaultNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultNetworkACLIncludingIPv6RuleConfig(rName), + Config: testAccVPCDefaultNetworkACLConfig_includingIPv6Rule(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -206,7 +206,7 @@ func TestAccVPCDefaultNetworkACL_subnetRemoval(t *testing.T) { CheckDestroy: testAccCheckDefaultNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultNetworkACLSubnetsConfig(rName), + Config: testAccVPCDefaultNetworkACLConfig_subnets(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), @@ -223,7 +223,7 @@ func TestAccVPCDefaultNetworkACL_subnetRemoval(t *testing.T) { // but have not been reassigned. The result is that the Subnets are still // there, and we have a non-empty plan { - Config: testAccDefaultNetworkACLSubnetsRemoveConfig(rName), + Config: testAccVPCDefaultNetworkACLConfig_subnetsRemove(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), ), @@ -250,7 +250,7 @@ func TestAccVPCDefaultNetworkACL_subnetReassign(t *testing.T) { CheckDestroy: testAccCheckDefaultNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultNetworkACLSubnetsConfig(rName), + Config: testAccVPCDefaultNetworkACLConfig_subnets(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), @@ -276,7 +276,7 @@ func TestAccVPCDefaultNetworkACL_subnetReassign(t *testing.T) { // update occurs first, and the former's READ will correctly read zero // subnets { - Config: testAccDefaultNetworkACLSubnetsMoveConfig(rName), + Config: testAccVPCDefaultNetworkACLConfig_subnetsMove(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), @@ -325,7 +325,7 @@ func testAccCheckDefaultNetworkACLExists(n string, v *ec2.NetworkAcl) resource.T } } -func testAccDefaultNetworkACLConfig(rName string) string { +func testAccVPCDefaultNetworkACLConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -341,7 +341,7 @@ resource "aws_default_network_acl" "test" { `, rName) } -func testAccDefaultNetworkACLTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccVPCDefaultNetworkACLConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -361,7 +361,7 @@ resource "aws_default_network_acl" "test" { `, rName, tagKey1, tagValue1) } -func testAccDefaultNetworkACLTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCDefaultNetworkACLConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -382,7 +382,7 @@ resource "aws_default_network_acl" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccDefaultNetworkACLIncludingIPv6RuleConfig(rName string) string { +func testAccVPCDefaultNetworkACLConfig_includingIPv6Rule(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -407,7 +407,7 @@ resource "aws_default_network_acl" "test" { `, rName) } -func testAccDefaultNetworkACLDenyIngressConfig(rName string) string { +func testAccVPCDefaultNetworkACLConfig_denyIngress(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -462,7 +462,7 @@ resource "aws_subnet" "test2" { `, rName) } -func testAccDefaultNetworkACLSubnetsConfig(rName string) string { +func testAccVPCDefaultNetworkACLConfig_subnets(rName string) string { return acctest.ConfigCompose(testAccDefaultNetworkACLSubnetsBaseConfig(rName), fmt.Sprintf(` resource "aws_network_acl" "test" { vpc_id = aws_vpc.test.id @@ -480,7 +480,7 @@ resource "aws_default_network_acl" "test" { `, rName)) } -func testAccDefaultNetworkACLSubnetsRemoveConfig(rName string) string { +func testAccVPCDefaultNetworkACLConfig_subnetsRemove(rName string) string { return acctest.ConfigCompose(testAccDefaultNetworkACLSubnetsBaseConfig(rName), fmt.Sprintf(` resource "aws_network_acl" "test" { vpc_id = aws_vpc.test.id @@ -498,7 +498,7 @@ resource "aws_default_network_acl" "test" { `, rName)) } -func testAccDefaultNetworkACLSubnetsMoveConfig(rName string) string { +func testAccVPCDefaultNetworkACLConfig_subnetsMove(rName string) string { return acctest.ConfigCompose(testAccDefaultNetworkACLSubnetsBaseConfig(rName), fmt.Sprintf(` resource "aws_network_acl" "test" { vpc_id = aws_vpc.test.id @@ -518,7 +518,7 @@ resource "aws_default_network_acl" "test" { `, rName)) } -func testAccDefaultNetworkACLIPv6Config(rName string) string { +func testAccVPCDefaultNetworkACLConfig_ipv6(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_default_route_table_test.go b/internal/service/ec2/vpc_default_route_table_test.go index 36e033d2ac0..6e08c529288 100644 --- a/internal/service/ec2/vpc_default_route_table_test.go +++ b/internal/service/ec2/vpc_default_route_table_test.go @@ -31,16 +31,16 @@ func TestAccVPCDefaultRouteTable_basic(t *testing.T) { Steps: []resource.TestStep{ // Verify non-existent Route Table ID behavior { - Config: testAccDefaultRouteTableConfigDefaultRouteTableId("rtb-00000000"), + Config: testAccVPCDefaultRouteTableConfig_id("rtb-00000000"), ExpectError: regexp.MustCompile(`EC2 Default Route Table \(rtb-00000000\): couldn't find resource`), }, // Verify invalid Route Table ID behavior { - Config: testAccDefaultRouteTableConfigDefaultRouteTableId("vpc-00000000"), + Config: testAccVPCDefaultRouteTableConfig_id("vpc-00000000"), ExpectError: regexp.MustCompile(`EC2 Default Route Table \(vpc-00000000\): couldn't find resource`), }, { - Config: testAccDefaultRouteTableConfigBasic(rName), + Config: testAccVPCDefaultRouteTableConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`route-table/.+$`)), @@ -75,7 +75,7 @@ func TestAccVPCDefaultRouteTable_Disappears_vpc(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfigBasic(rName), + Config: testAccVPCDefaultRouteTableConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), acctest.CheckVPCExists(vpcResourceName, &vpc), @@ -101,7 +101,7 @@ func TestAccVPCDefaultRouteTable_Route_mode(t *testing.T) { CheckDestroy: testAccCheckDefaultRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfig_ipv4InternetGateway(rName, destinationCidr), + Config: testAccVPCDefaultRouteTableConfig_ipv4InternetGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -121,7 +121,7 @@ func TestAccVPCDefaultRouteTable_Route_mode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDefaultRouteTableConfigNoRouteBlock(rName), + Config: testAccVPCDefaultRouteTableConfig_noBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -137,7 +137,7 @@ func TestAccVPCDefaultRouteTable_Route_mode(t *testing.T) { ), }, { - Config: testAccDefaultRouteTableConfigRouteBlocksExplicitZero(rName), + Config: testAccVPCDefaultRouteTableConfig_blocksExplicitZero(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), @@ -171,7 +171,7 @@ func TestAccVPCDefaultRouteTable_swap(t *testing.T) { CheckDestroy: testAccCheckDefaultRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfig_ipv4InternetGateway(rName, destinationCidr1), + Config: testAccVPCDefaultRouteTableConfig_ipv4InternetGateway(rName, destinationCidr1), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -197,7 +197,7 @@ func TestAccVPCDefaultRouteTable_swap(t *testing.T) { // this case) a diff as the table now needs to be updated to match the // config { - Config: testAccDefaultRouteTableConfigSwap(rName, destinationCidr1, destinationCidr2), + Config: testAccVPCDefaultRouteTableConfig_swap(rName, destinationCidr1, destinationCidr2), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -207,7 +207,7 @@ func TestAccVPCDefaultRouteTable_swap(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: testAccDefaultRouteTableConfigSwap(rName, destinationCidr1, destinationCidr2), + Config: testAccVPCDefaultRouteTableConfig_swap(rName, destinationCidr1, destinationCidr2), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -241,7 +241,7 @@ func TestAccVPCDefaultRouteTable_ipv4ToTransitGateway(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfig_ipv4TransitGateway(rName, destinationCidr), + Config: testAccVPCDefaultRouteTableConfig_ipv4TransitGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -277,7 +277,7 @@ func TestAccVPCDefaultRouteTable_ipv4ToVPCEndpoint(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfig_ipv4VPCEndpoint(rName, destinationCidr), + Config: testAccVPCDefaultRouteTableConfig_ipv4Endpoint(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -295,7 +295,7 @@ func TestAccVPCDefaultRouteTable_ipv4ToVPCEndpoint(t *testing.T) { // VPC Endpoints will not delete unless the route is removed prior, otherwise will error: // InvalidParameter: Endpoint must be removed from route table before deletion { - Config: testAccDefaultRouteTableConfig_ipv4VPCEndpointNoRoute(rName), + Config: testAccVPCDefaultRouteTableConfig_ipv4EndpointNo(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), ), @@ -318,7 +318,7 @@ func TestAccVPCDefaultRouteTable_vpcEndpointAssociation(t *testing.T) { CheckDestroy: testAccCheckDefaultRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfig_vpcEndpointAssociation(rName, destinationCidr), + Config: testAccVPCDefaultRouteTableConfig_endpointAssociation(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -348,7 +348,7 @@ func TestAccVPCDefaultRouteTable_tags(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfigTags1(rName, "key1", "value1"), + Config: testAccVPCDefaultRouteTableConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -356,7 +356,7 @@ func TestAccVPCDefaultRouteTable_tags(t *testing.T) { ), }, { - Config: testAccDefaultRouteTableConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCDefaultRouteTableConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -365,7 +365,7 @@ func TestAccVPCDefaultRouteTable_tags(t *testing.T) { ), }, { - Config: testAccDefaultRouteTableConfigTags1(rName, "key2", "value2"), + Config: testAccVPCDefaultRouteTableConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -391,14 +391,14 @@ func TestAccVPCDefaultRouteTable_conditionalCIDRBlock(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfig_conditionalIPv4v6(rName, destinationCidr, destinationIpv6Cidr, false), + Config: testAccVPCDefaultRouteTableConfig_conditionalIPv4v6(rName, destinationCidr, destinationIpv6Cidr, false), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableRoute(resourceName, "cidr_block", destinationCidr, "gateway_id", igwResourceName, "id"), ), }, { - Config: testAccDefaultRouteTableConfig_conditionalIPv4v6(rName, destinationCidr, destinationIpv6Cidr, true), + Config: testAccVPCDefaultRouteTableConfig_conditionalIPv4v6(rName, destinationCidr, destinationIpv6Cidr, true), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableRoute(resourceName, "ipv6_cidr_block", destinationIpv6Cidr, "gateway_id", igwResourceName, "id"), @@ -428,7 +428,7 @@ func TestAccVPCDefaultRouteTable_prefixListToInternetGateway(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfigPrefixListInternetGateway(rName), + Config: testAccVPCDefaultRouteTableConfig_prefixListInternetGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -446,7 +446,7 @@ func TestAccVPCDefaultRouteTable_prefixListToInternetGateway(t *testing.T) { // Managed prefix lists will not delete unless the route is removed prior, otherwise will error: // "unexpected state 'delete-failed', wanted target 'delete-complete'" { - Config: testAccDefaultRouteTableConfigPrefixListInternetGatewayNoRoute(rName), + Config: testAccVPCDefaultRouteTableConfig_prefixListInternetGatewayNo(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), ), @@ -472,7 +472,7 @@ func TestAccVPCDefaultRouteTable_revokeExistingRules(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultRouteTableConfigRevokeExistingRulesCustomRouteTable(rName), + Config: testAccVPCDefaultRouteTableConfig_revokeExistingRulesCustom(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(rtResourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -485,7 +485,7 @@ func TestAccVPCDefaultRouteTable_revokeExistingRules(t *testing.T) { ), }, { - Config: testAccDefaultRouteTableConfigRevokeExistingRulesCustomRouteTableToMain(rName), + Config: testAccVPCDefaultRouteTableConfig_revokeExistingRulesCustomToMain(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(rtResourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -498,7 +498,7 @@ func TestAccVPCDefaultRouteTable_revokeExistingRules(t *testing.T) { ), }, { - Config: testAccDefaultRouteTableConfigRevokeExistingRulesDefaultRouteTableOverlaysCustomRouteTable(rName), + Config: testAccVPCDefaultRouteTableConfig_revokeExistingRulesOverlaysCustom(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -551,7 +551,7 @@ func testAccDefaultRouteTableImportStateIdFunc(resourceName string) resource.Imp } } -func testAccDefaultRouteTableConfigDefaultRouteTableId(defaultRouteTableId string) string { +func testAccVPCDefaultRouteTableConfig_id(defaultRouteTableId string) string { return fmt.Sprintf(` resource "aws_default_route_table" "test" { default_route_table_id = %[1]q @@ -559,7 +559,7 @@ resource "aws_default_route_table" "test" { `, defaultRouteTableId) } -func testAccDefaultRouteTableConfigBasic(rName string) string { +func testAccVPCDefaultRouteTableConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -575,7 +575,7 @@ resource "aws_default_route_table" "test" { `, rName) } -func testAccDefaultRouteTableConfig_ipv4InternetGateway(rName, destinationCidr string) string { +func testAccVPCDefaultRouteTableConfig_ipv4InternetGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -609,7 +609,7 @@ resource "aws_internet_gateway" "test" { `, rName, destinationCidr) } -func testAccDefaultRouteTableConfigNoRouteBlock(rName string) string { +func testAccVPCDefaultRouteTableConfig_noBlock(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -637,7 +637,7 @@ resource "aws_internet_gateway" "test" { }`, rName) } -func testAccDefaultRouteTableConfigRouteBlocksExplicitZero(rName string) string { +func testAccVPCDefaultRouteTableConfig_blocksExplicitZero(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -667,7 +667,7 @@ resource "aws_internet_gateway" "test" { }`, rName) } -func testAccDefaultRouteTableConfigSwap(rName, destinationCidr1, destinationCidr2 string) string { +func testAccVPCDefaultRouteTableConfig_swap(rName, destinationCidr1, destinationCidr2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -719,7 +719,7 @@ resource "aws_main_route_table_association" "test" { `, rName, destinationCidr1, destinationCidr2) } -func testAccDefaultRouteTableConfig_ipv4TransitGateway(rName, destinationCidr string) string { +func testAccVPCDefaultRouteTableConfig_ipv4TransitGateway(rName, destinationCidr string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -770,7 +770,7 @@ resource "aws_default_route_table" "test" { `, rName, destinationCidr)) } -func testAccDefaultRouteTableConfig_ipv4VPCEndpoint(rName, destinationCidr string) string { +func testAccVPCDefaultRouteTableConfig_ipv4Endpoint(rName, destinationCidr string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -848,7 +848,7 @@ resource "aws_default_route_table" "test" { `, rName, destinationCidr)) } -func testAccDefaultRouteTableConfig_ipv4VPCEndpointNoRoute(rName string) string { +func testAccVPCDefaultRouteTableConfig_ipv4EndpointNo(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -926,7 +926,7 @@ resource "aws_default_route_table" "test" { `, rName)) } -func testAccDefaultRouteTableConfig_vpcEndpointAssociation(rName, destinationCidr string) string { +func testAccVPCDefaultRouteTableConfig_endpointAssociation(rName, destinationCidr string) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -971,7 +971,7 @@ resource "aws_default_route_table" "test" { `, rName, destinationCidr) } -func testAccDefaultRouteTableConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccVPCDefaultRouteTableConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -991,7 +991,7 @@ resource "aws_default_route_table" "test" { `, rName, tagKey1, tagValue1) } -func testAccDefaultRouteTableConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCDefaultRouteTableConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1012,7 +1012,7 @@ resource "aws_default_route_table" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccDefaultRouteTableConfig_conditionalIPv4v6(rName, destinationCidr, destinationIpv6Cidr string, ipv6Route bool) string { +func testAccVPCDefaultRouteTableConfig_conditionalIPv4v6(rName, destinationCidr, destinationIpv6Cidr string, ipv6Route bool) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1054,7 +1054,7 @@ resource "aws_default_route_table" "test" { `, rName, destinationCidr, destinationIpv6Cidr, ipv6Route) } -func testAccDefaultRouteTableConfigPrefixListInternetGateway(rName string) string { +func testAccVPCDefaultRouteTableConfig_prefixListInternetGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1093,7 +1093,7 @@ resource "aws_default_route_table" "test" { `, rName) } -func testAccDefaultRouteTableConfigPrefixListInternetGatewayNoRoute(rName string) string { +func testAccVPCDefaultRouteTableConfig_prefixListInternetGatewayNo(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1132,7 +1132,7 @@ resource "aws_default_route_table" "test" { `, rName) } -func testAccDefaultRouteTableConfigRevokeExistingRulesCustomRouteTable(rName string) string { +func testAccVPCDefaultRouteTableConfig_revokeExistingRulesCustom(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1180,9 +1180,9 @@ resource "aws_route_table" "test" { `, rName) } -func testAccDefaultRouteTableConfigRevokeExistingRulesCustomRouteTableToMain(rName string) string { +func testAccVPCDefaultRouteTableConfig_revokeExistingRulesCustomToMain(rName string) string { return acctest.ConfigCompose( - testAccDefaultRouteTableConfigRevokeExistingRulesCustomRouteTable(rName), + testAccVPCDefaultRouteTableConfig_revokeExistingRulesCustom(rName), ` resource "aws_main_route_table_association" "test" { vpc_id = aws_vpc.test.id @@ -1191,9 +1191,9 @@ resource "aws_main_route_table_association" "test" { `) } -func testAccDefaultRouteTableConfigRevokeExistingRulesDefaultRouteTableOverlaysCustomRouteTable(rName string) string { +func testAccVPCDefaultRouteTableConfig_revokeExistingRulesOverlaysCustom(rName string) string { return acctest.ConfigCompose( - testAccDefaultRouteTableConfigRevokeExistingRulesCustomRouteTableToMain(rName), + testAccVPCDefaultRouteTableConfig_revokeExistingRulesCustomToMain(rName), fmt.Sprintf(` resource "aws_internet_gateway" "test" { vpc_id = aws_vpc.test.id diff --git a/internal/service/ec2/vpc_default_security_group_test.go b/internal/service/ec2/vpc_default_security_group_test.go index b1b653783a1..95d76b35cbc 100644 --- a/internal/service/ec2/vpc_default_security_group_test.go +++ b/internal/service/ec2/vpc_default_security_group_test.go @@ -25,7 +25,7 @@ func TestAccVPCDefaultSecurityGroup_VPC_basic(t *testing.T) { CheckDestroy: testAccCheckDefaultSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultSecurityGroupConfig_VPC, + Config: testAccVPCDefaultSecurityGroupConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckDefaultSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "default"), @@ -54,7 +54,7 @@ func TestAccVPCDefaultSecurityGroup_VPC_basic(t *testing.T) { ), }, { - Config: testAccDefaultSecurityGroupConfig_VPC, + Config: testAccVPCDefaultSecurityGroupConfig_basic, PlanOnly: true, }, { @@ -78,7 +78,7 @@ func TestAccVPCDefaultSecurityGroup_VPC_empty(t *testing.T) { CheckDestroy: testAccCheckDefaultSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultSecurityGroupConfig_VPC_empty, + Config: testAccVPCDefaultSecurityGroupConfig_empty, Check: resource.ComposeTestCheckFunc( testAccCheckDefaultSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), @@ -106,7 +106,7 @@ func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { CheckDestroy: testAccCheckDefaultSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultSecurityGroupConfig_Classic(), + Config: testAccVPCDefaultSecurityGroupConfig_classic(), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultSecurityGroupClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "default"), @@ -128,11 +128,11 @@ func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { ), }, { - Config: testAccDefaultSecurityGroupConfig_Classic(), + Config: testAccVPCDefaultSecurityGroupConfig_classic(), PlanOnly: true, }, { - Config: testAccDefaultSecurityGroupConfig_Classic(), + Config: testAccVPCDefaultSecurityGroupConfig_classic(), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -158,7 +158,7 @@ func TestAccVPCDefaultSecurityGroup_Classic_empty(t *testing.T) { CheckDestroy: testAccCheckDefaultSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultSecurityGroupConfig_Classic_empty(), + Config: testAccVPCDefaultSecurityGroupConfig_classicEmpty(), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultSecurityGroupClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), @@ -234,7 +234,7 @@ func testAccCheckDefaultSecurityGroupARNClassic(resourceName string, group *ec2. } } -const testAccDefaultSecurityGroupConfig_VPC = ` +const testAccVPCDefaultSecurityGroupConfig_basic = ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -266,7 +266,7 @@ resource "aws_default_security_group" "test" { } ` -const testAccDefaultSecurityGroupConfig_VPC_empty = ` +const testAccVPCDefaultSecurityGroupConfig_empty = ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -280,7 +280,7 @@ resource "aws_default_security_group" "test" { } ` -func testAccDefaultSecurityGroupConfig_Classic() string { +func testAccVPCDefaultSecurityGroupConfig_classic() string { return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), ` @@ -299,7 +299,7 @@ resource "aws_default_security_group" "test" { `) } -func testAccDefaultSecurityGroupConfig_Classic_empty() string { +func testAccVPCDefaultSecurityGroupConfig_classicEmpty() string { return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), ` diff --git a/internal/service/ec2/vpc_default_subnet_test.go b/internal/service/ec2/vpc_default_subnet_test.go index 51663496d1d..307e576ab00 100644 --- a/internal/service/ec2/vpc_default_subnet_test.go +++ b/internal/service/ec2/vpc_default_subnet_test.go @@ -88,7 +88,7 @@ func testAccDefaultSubnet_Existing_basic(t *testing.T) { CheckDestroy: testAccCheckDefaultSubnetDestroyExists, Steps: []resource.TestStep{ { - Config: testAccDefaultSubnetConfig(), + Config: testAccVPCDefaultSubnetConfig_basic(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -132,7 +132,7 @@ func testAccDefaultSubnet_Existing_forceDestroy(t *testing.T) { CheckDestroy: testAccCheckDefaultSubnetDestroyNotFound, Steps: []resource.TestStep{ { - Config: testAccDefaultSubnetForceDestroyConfig(), + Config: testAccVPCDefaultSubnetConfig_forceDestroy(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "existing_default_subnet", "true"), @@ -158,7 +158,7 @@ func testAccDefaultSubnet_Existing_ipv6(t *testing.T) { CheckDestroy: testAccCheckDefaultSubnetDestroyNotFound, Steps: []resource.TestStep{ { - Config: testAccDefaultSubnetIPv6Config(), + Config: testAccVPCDefaultSubnetConfig_ipv6(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -203,7 +203,7 @@ func testAccDefaultSubnet_Existing_privateDNSNameOptionsOnLaunch(t *testing.T) { CheckDestroy: testAccCheckDefaultSubnetDestroyExists, Steps: []resource.TestStep{ { - Config: testAccDefaultSubnetConfig_privateDNSNameOptionsOnLaunch(rName), + Config: testAccVPCDefaultSubnetConfig_privateDNSNameOptionsOnLaunch(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -248,7 +248,7 @@ func testAccDefaultSubnet_NotFound_basic(t *testing.T) { CheckDestroy: testAccCheckDefaultSubnetDestroyExists, Steps: []resource.TestStep{ { - Config: testAccDefaultSubnetNotFoundConfig(), + Config: testAccVPCDefaultSubnetConfig_notFound(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -292,7 +292,7 @@ func testAccDefaultSubnet_NotFound_ipv6Native(t *testing.T) { CheckDestroy: testAccCheckDefaultSubnetDestroyNotFound, Steps: []resource.TestStep{ { - Config: testAccDefaultSubnetIPv6NativeConfig(), + Config: testAccVPCDefaultSubnetConfig_ipv6Native(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -429,7 +429,7 @@ data "aws_subnet" "test" { } ` -func testAccDefaultSubnetConfig() string { +func testAccVPCDefaultSubnetConfig_basic() string { return acctest.ConfigCompose(testAccDefaultSubnetConfigBaseExisting, ` resource "aws_default_subnet" "test" { availability_zone = data.aws_subnet.test.availability_zone @@ -437,7 +437,7 @@ resource "aws_default_subnet" "test" { `) } -func testAccDefaultSubnetNotFoundConfig() string { +func testAccVPCDefaultSubnetConfig_notFound() string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` resource "aws_default_subnet" "test" { availability_zone = data.aws_availability_zones.available.names[0] @@ -445,7 +445,7 @@ resource "aws_default_subnet" "test" { `) } -func testAccDefaultSubnetForceDestroyConfig() string { +func testAccVPCDefaultSubnetConfig_forceDestroy() string { return acctest.ConfigCompose(testAccDefaultSubnetConfigBaseExisting, ` resource "aws_default_subnet" "test" { availability_zone = data.aws_subnet.test.availability_zone @@ -454,7 +454,7 @@ resource "aws_default_subnet" "test" { `) } -func testAccDefaultSubnetIPv6Config() string { +func testAccVPCDefaultSubnetConfig_ipv6() string { return acctest.ConfigCompose(testAccDefaultSubnetConfigBaseExisting, ` resource "aws_default_vpc" "test" { assign_generated_ipv6_cidr_block = true @@ -477,7 +477,7 @@ resource "aws_default_subnet" "test" { `) } -func testAccDefaultSubnetIPv6NativeConfig() string { +func testAccVPCDefaultSubnetConfig_ipv6Native() string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), ` resource "aws_default_vpc" "test" { assign_generated_ipv6_cidr_block = true @@ -500,7 +500,7 @@ resource "aws_default_subnet" "test" { `) } -func testAccDefaultSubnetConfig_privateDNSNameOptionsOnLaunch(rName string) string { +func testAccVPCDefaultSubnetConfig_privateDNSNameOptionsOnLaunch(rName string) string { return acctest.ConfigCompose(testAccDefaultSubnetConfigBaseExisting, fmt.Sprintf(` resource "aws_default_subnet" "test" { availability_zone = data.aws_subnet.test.availability_zone diff --git a/internal/service/ec2/vpc_default_vpc_dhcp_options.go b/internal/service/ec2/vpc_default_vpc_dhcp_options.go index 3667144ba53..a4b7b8a3f41 100644 --- a/internal/service/ec2/vpc_default_vpc_dhcp_options.go +++ b/internal/service/ec2/vpc_default_vpc_dhcp_options.go @@ -2,112 +2,102 @@ package ec2 import ( "fmt" - "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/verify" ) func ResourceDefaultVPCDHCPOptions() *schema.Resource { - // reuse aws_vpc_dhcp_options schema, and methods for READ, UPDATE - dvpc := ResourceVPCDHCPOptions() - dvpc.Create = resourceDefaultVPCDHCPOptionsCreate - dvpc.Delete = resourceDefaultVPCDHCPOptionsDelete - - // domain_name is a computed value for Default Default DHCP Options Sets - dvpc.Schema["domain_name"] = &schema.Schema{ - Type: schema.TypeString, - Computed: true, - } - // domain_name_servers is a computed value for Default Default DHCP Options Sets - dvpc.Schema["domain_name_servers"] = &schema.Schema{ - Type: schema.TypeString, - Computed: true, - } - // ntp_servers is a computed value for Default Default DHCP Options Sets - dvpc.Schema["ntp_servers"] = &schema.Schema{ - Type: schema.TypeString, - Computed: true, - } + //lintignore:R011 + return &schema.Resource{ + Create: resourceDefaultVPCDHCPOptionsCreate, + Read: resourceVPCDHCPOptionsRead, + Update: resourceVPCDHCPOptionsUpdate, + Delete: schema.Noop, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, - dvpc.Schema["owner_id"] = &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Optional: true, + CustomizeDiff: verify.SetTagsDiff, + + // Keep in sync with aws_vpc_dhcp_options' schema with the following changes: + // - domain_name is Computed-only + // - domain_name_servers is Computed-only and is TypeString + // - netbios_name_servers is Computed-only and is TypeString + // - netbios_node_type is Computed-only + // - ntp_servers is Computed-only and is TypeString + // - owner_id is Optional/Computed + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "domain_name": { + Type: schema.TypeString, + Computed: true, + }, + "domain_name_servers": { + Type: schema.TypeString, + Computed: true, + }, + "netbios_name_servers": { + Type: schema.TypeString, + Computed: true, + }, + "netbios_node_type": { + Type: schema.TypeString, + Computed: true, + }, + "ntp_servers": { + Type: schema.TypeString, + Computed: true, + }, + "owner_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, } - - return dvpc } func resourceDefaultVPCDHCPOptionsCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - filters := []*ec2.Filter{ - { - Name: aws.String("key"), - Values: aws.StringSlice([]string{"domain-name"}), - }, - { - Name: aws.String("value"), - Values: aws.StringSlice([]string{RegionalPrivateDNSSuffix(meta.(*conns.AWSClient).Region)}), - }, - { - Name: aws.String("key"), - Values: aws.StringSlice([]string{"domain-name-servers"}), - }, - { - Name: aws.String("value"), - Values: aws.StringSlice([]string{"AmazonProvidedDNS"}), - }, - } - - if v, ok := d.GetOk("owner_id"); ok { - filter := &ec2.Filter{ - Name: aws.String("owner-id"), - Values: aws.StringSlice([]string{v.(string)}), - } + input := &ec2.DescribeDhcpOptionsInput{} - filters = append(filters, filter) - } + input.Filters = append(input.Filters, + NewFilter("key", []string{"domain-name"}), + NewFilter("value", []string{RegionalPrivateDNSSuffix(meta.(*conns.AWSClient).Region)}), + NewFilter("key", []string{"domain-name-servers"}), + NewFilter("value", []string{"AmazonProvidedDNS"}), + ) - req := &ec2.DescribeDhcpOptionsInput{ - Filters: filters, + if v, ok := d.GetOk("owner_id"); ok { + input.Filters = append(input.Filters, BuildAttributeFilterList(map[string]string{ + "owner-id": v.(string), + })...) } - var dhcpOptions []*ec2.DhcpOptions - err := conn.DescribeDhcpOptionsPages(req, func(page *ec2.DescribeDhcpOptionsOutput, lastPage bool) bool { - dhcpOptions = append(dhcpOptions, page.DhcpOptions...) - return !lastPage - }) + dhcpOptions, err := FindDHCPOptions(conn, input) if err != nil { - return fmt.Errorf("Error describing DHCP options: %s", err) + return fmt.Errorf("reading EC2 Default DHCP Options Set: %w", err) } - if len(dhcpOptions) == 0 { - return fmt.Errorf("Default DHCP Options Set not found") - } - - if len(dhcpOptions) > 1 { - return fmt.Errorf("Multiple default DHCP Options Sets found") - } - - if dhcpOptions[0] == nil { - return fmt.Errorf("Default DHCP Options Set is empty") - } - d.SetId(aws.StringValue(dhcpOptions[0].DhcpOptionsId)) + d.SetId(aws.StringValue(dhcpOptions.DhcpOptionsId)) return resourceVPCDHCPOptionsUpdate(d, meta) } -func resourceDefaultVPCDHCPOptionsDelete(d *schema.ResourceData, meta interface{}) error { - log.Printf("[WARN] Cannot destroy Default DHCP Options Set. Terraform will remove this resource from the state file, however resources may remain.") - return nil -} - func RegionalPrivateDNSSuffix(region string) string { if region == endpoints.UsEast1RegionID { return "ec2.internal" diff --git a/internal/service/ec2/vpc_default_vpc_dhcp_options_test.go b/internal/service/ec2/vpc_default_vpc_dhcp_options_test.go index 18609a71e85..b61223f2899 100644 --- a/internal/service/ec2/vpc_default_vpc_dhcp_options_test.go +++ b/internal/service/ec2/vpc_default_vpc_dhcp_options_test.go @@ -6,69 +6,110 @@ import ( "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" ) -func TestAccVPCDefaultVPCDHCPOptions_basic(t *testing.T) { +func TestAccVPCDefaultVPCDHCPOptions_serial(t *testing.T) { + testCases := map[string]func(t *testing.T){ + "basic": testAccDefaultVPCDHCPOptions_basic, + "owner": testAccDefaultVPCDHCPOptions_owner, + "v4.20.0_regression": testAccDefaultVPCDHCPOptions_v420Regression, + } + + for name, tc := range testCases { + tc := tc + t.Run(name, func(t *testing.T) { + tc(t) + }) + } +} + +func testAccDefaultVPCDHCPOptions_basic(t *testing.T) { var d ec2.DhcpOptions resourceName := "aws_default_vpc_dhcp_options.test" - resource.ParallelTest(t, resource.TestCase{ + resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDefaultVPCDHCPOptionsDestroy, + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { - Config: testAccDefaultVPCDHCPOptionsBasicConfig, + Config: testAccVPCDefaultVPCDHCPOptionsConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckDHCPOptionsExists(resourceName, &d), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`dhcp-options/dopt-.+`)), resource.TestCheckResourceAttr(resourceName, "domain_name", tfec2.RegionalPrivateDNSSuffix(acctest.Region())), resource.TestCheckResourceAttr(resourceName, "domain_name_servers", "AmazonProvidedDNS"), + acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.Name", "Default DHCP Option Set"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), ), }, }, }) } -func TestAccVPCDefaultVPCDHCPOptions_owner(t *testing.T) { +func testAccDefaultVPCDHCPOptions_owner(t *testing.T) { var d ec2.DhcpOptions resourceName := "aws_default_vpc_dhcp_options.test" - resource.ParallelTest(t, resource.TestCase{ + resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDefaultVPCDHCPOptionsDestroy, + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { - Config: testAccDefaultVPCDHCPOptionsOwnerConfig, + Config: testAccVPCDefaultVPCDHCPOptionsConfig_owner, Check: resource.ComposeTestCheckFunc( testAccCheckDHCPOptionsExists(resourceName, &d), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`dhcp-options/dopt-.+`)), resource.TestCheckResourceAttr(resourceName, "domain_name", tfec2.RegionalPrivateDNSSuffix(acctest.Region())), resource.TestCheckResourceAttr(resourceName, "domain_name_servers", "AmazonProvidedDNS"), + acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.Name", "Default DHCP Option Set"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), ), }, }, }) } -func testAccCheckDefaultVPCDHCPOptionsDestroy(s *terraform.State) error { - // We expect DHCP Options Set to still exist - return nil +// https://github.com/hashicorp/terraform-provider-aws/issues/25561. +// Don't forget to unset TF_CLI_CONFIG_FILE. +func testAccDefaultVPCDHCPOptions_v420Regression(t *testing.T) { + var d ec2.DhcpOptions + resourceName := "aws_default_vpc_dhcp_options.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + CheckDestroy: acctest.CheckDestroyNoop, + Steps: []resource.TestStep{ + { + ExternalProviders: map[string]resource.ExternalProvider{ + "aws": { + Source: "hashicorp/aws", + VersionConstraint: "4.19.0", + }, + }, + Config: testAccVPCDefaultVPCDHCPOptionsConfig_basic, + Check: resource.ComposeTestCheckFunc( + testAccCheckDHCPOptionsExists(resourceName, &d), + ), + }, + { + ProviderFactories: acctest.ProviderFactories, + Config: testAccVPCDefaultVPCDHCPOptionsConfig_basic, + PlanOnly: true, + }, + }, + }) } -const testAccDefaultVPCDHCPOptionsBasicConfig = ` +const testAccVPCDefaultVPCDHCPOptionsConfig_basic = ` resource "aws_default_vpc_dhcp_options" "test" { tags = { Name = "Default DHCP Option Set" @@ -76,7 +117,7 @@ resource "aws_default_vpc_dhcp_options" "test" { } ` -const testAccDefaultVPCDHCPOptionsOwnerConfig = ` +const testAccVPCDefaultVPCDHCPOptionsConfig_owner = ` data "aws_caller_identity" "current" {} resource "aws_default_vpc_dhcp_options" "test" { diff --git a/internal/service/ec2/vpc_default_vpc_test.go b/internal/service/ec2/vpc_default_vpc_test.go index 063ed719ca5..4df3924eeb0 100644 --- a/internal/service/ec2/vpc_default_vpc_test.go +++ b/internal/service/ec2/vpc_default_vpc_test.go @@ -93,7 +93,7 @@ func testAccDefaultVPC_Existing_basic(t *testing.T) { CheckDestroy: testAccCheckDefaultVPCDestroyExists, Steps: []resource.TestStep{ { - Config: testAccDefaultVPCConfig, + Config: testAccVPCDefaultVPCConfig_basic, Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckVPCExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -140,7 +140,7 @@ func testAccDefaultVPC_Existing_assignGeneratedIPv6CIDRBlock(t *testing.T) { CheckDestroy: testAccCheckDefaultVPCDestroyExists, Steps: []resource.TestStep{ { - Config: testAccDefaultVPCAssignGeneratedIPv6CIDRBlockConfig(rName), + Config: testAccVPCDefaultVPCConfig_assignGeneratedIPv6CIDRBlock(rName), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckVPCExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -187,7 +187,7 @@ func testAccDefaultVPC_Existing_forceDestroy(t *testing.T) { CheckDestroy: testAccCheckDefaultVPCDestroyNotFound, Steps: []resource.TestStep{ { - Config: testAccDefaultVPCForceDestroyConfig, + Config: testAccVPCDefaultVPCConfig_forceDestroy, Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckVPCExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "existing_default_vpc", "true"), @@ -214,7 +214,7 @@ func testAccDefaultVPC_NotFound_basic(t *testing.T) { CheckDestroy: testAccCheckDefaultVPCDestroyExists, Steps: []resource.TestStep{ { - Config: testAccDefaultVPCConfig, + Config: testAccVPCDefaultVPCConfig_basic, Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckVPCExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -261,7 +261,7 @@ func testAccDefaultVPC_NotFound_assignGeneratedIPv6CIDRBlock(t *testing.T) { CheckDestroy: testAccCheckDefaultVPCDestroyExists, Steps: []resource.TestStep{ { - Config: testAccDefaultVPCAssignGeneratedIPv6CIDRBlockConfig(rName), + Config: testAccVPCDefaultVPCConfig_assignGeneratedIPv6CIDRBlock(rName), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckVPCExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -308,7 +308,7 @@ func testAccDefaultVPC_NotFound_forceDestroy(t *testing.T) { CheckDestroy: testAccCheckDefaultVPCDestroyNotFound, Steps: []resource.TestStep{ { - Config: testAccDefaultVPCForceDestroyConfig, + Config: testAccVPCDefaultVPCConfig_forceDestroy, Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckVPCExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "existing_default_vpc", "false"), @@ -437,17 +437,17 @@ func testAccEmptyDefaultVPC(vpcID string) error { return nil } -const testAccDefaultVPCConfig = ` +const testAccVPCDefaultVPCConfig_basic = ` resource "aws_default_vpc" "test" {} ` -const testAccDefaultVPCForceDestroyConfig = ` +const testAccVPCDefaultVPCConfig_forceDestroy = ` resource "aws_default_vpc" "test" { force_destroy = true } ` -func testAccDefaultVPCAssignGeneratedIPv6CIDRBlockConfig(rName string) string { +func testAccVPCDefaultVPCConfig_assignGeneratedIPv6CIDRBlock(rName string) string { return fmt.Sprintf(` resource "aws_default_vpc" "test" { assign_generated_ipv6_cidr_block = true diff --git a/internal/service/ec2/vpc_dhcp_options.go b/internal/service/ec2/vpc_dhcp_options.go index b80403f11c0..02b0b383898 100644 --- a/internal/service/ec2/vpc_dhcp_options.go +++ b/internal/service/ec2/vpc_dhcp_options.go @@ -26,38 +26,45 @@ func ResourceVPCDHCPOptions() *schema.Resource { State: schema.ImportStatePassthrough, }, + // Keep in sync with aws_default_vpc_dhcp_options' schema. + // See notes in vpc_default_vpc_dhcp_options.go. Schema: map[string]*schema.Schema{ "arn": { Type: schema.TypeString, Computed: true, }, "domain_name": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, + Type: schema.TypeString, + Optional: true, + ForceNew: true, + AtLeastOneOf: []string{"domain_name", "domain_name_servers", "netbios_name_servers", "netbios_node_type", "ntp_servers"}, }, "domain_name_servers": { - Type: schema.TypeList, - Optional: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + AtLeastOneOf: []string{"domain_name", "domain_name_servers", "netbios_name_servers", "netbios_node_type", "ntp_servers"}, }, "netbios_name_servers": { - Type: schema.TypeList, - Optional: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + AtLeastOneOf: []string{"domain_name", "domain_name_servers", "netbios_name_servers", "netbios_node_type", "ntp_servers"}, }, "netbios_node_type": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, + Type: schema.TypeString, + Optional: true, + ForceNew: true, + AtLeastOneOf: []string{"domain_name", "domain_name_servers", "netbios_name_servers", "netbios_node_type", "ntp_servers"}, }, "ntp_servers": { - Type: schema.TypeList, - Optional: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + AtLeastOneOf: []string{"domain_name", "domain_name_servers", "netbios_name_servers", "netbios_node_type", "ntp_servers"}, }, "owner_id": { Type: schema.TypeString, @@ -246,6 +253,10 @@ func newDHCPOptionsMap(tfToApi map[string]string) *dhcpOptionsMap { // dhcpConfigurationsToResourceData sets Terraform ResourceData from a list of AWS API DHCP configurations. func (m *dhcpOptionsMap) dhcpConfigurationsToResourceData(dhcpConfigurations []*ec2.DhcpConfiguration, d *schema.ResourceData) error { + for v := range m.tfToApi { + d.Set(v, nil) + } + for _, dhcpConfiguration := range dhcpConfigurations { apiName := aws.StringValue(dhcpConfiguration.Key) if tfName, ok := m.apiToTf[apiName]; ok { diff --git a/internal/service/ec2/vpc_dhcp_options_association_test.go b/internal/service/ec2/vpc_dhcp_options_association_test.go index e0a1d1b6395..7b50df750a9 100644 --- a/internal/service/ec2/vpc_dhcp_options_association_test.go +++ b/internal/service/ec2/vpc_dhcp_options_association_test.go @@ -25,7 +25,7 @@ func TestAccVPCDHCPOptionsAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckVPCDHCPOptionsAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCDHCPOptionsAssociationConfig(rName), + Config: testAccVPCDHCPOptionsAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCDHCPOptionsAssociationExist(resourceName), ), @@ -51,7 +51,7 @@ func TestAccVPCDHCPOptionsAssociation_Disappears_vpc(t *testing.T) { CheckDestroy: testAccCheckVPCDHCPOptionsAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCDHCPOptionsAssociationConfig(rName), + Config: testAccVPCDHCPOptionsAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCDHCPOptionsAssociationExist(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPC(), "aws_vpc.test"), @@ -73,7 +73,7 @@ func TestAccVPCDHCPOptionsAssociation_Disappears_dhcp(t *testing.T) { CheckDestroy: testAccCheckVPCDHCPOptionsAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCDHCPOptionsAssociationConfig(rName), + Config: testAccVPCDHCPOptionsAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCDHCPOptionsAssociationExist(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPCDHCPOptions(), "aws_vpc_dhcp_options.test"), @@ -95,7 +95,7 @@ func TestAccVPCDHCPOptionsAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckVPCDHCPOptionsAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCDHCPOptionsAssociationConfig(rName), + Config: testAccVPCDHCPOptionsAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCDHCPOptionsAssociationExist(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPCDHCPOptionsAssociation(), resourceName), @@ -117,7 +117,7 @@ func TestAccVPCDHCPOptionsAssociation_default(t *testing.T) { CheckDestroy: testAccCheckVPCDHCPOptionsAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCDHCPOptionsAssociationDefaultConfig(rName), + Config: testAccVPCDHCPOptionsAssociationConfig_default(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCDHCPOptionsAssociationExist(resourceName), ), @@ -202,7 +202,7 @@ func testAccCheckVPCDHCPOptionsAssociationExist(n string) resource.TestCheckFunc } } -func testAccVPCDHCPOptionsAssociationConfig(rName string) string { +func testAccVPCDHCPOptionsAssociationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -231,7 +231,7 @@ resource "aws_vpc_dhcp_options_association" "test" { `, rName) } -func testAccVPCDHCPOptionsAssociationDefaultConfig(rName string) string { +func testAccVPCDHCPOptionsAssociationConfig_default(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_dhcp_options_data_source_test.go b/internal/service/ec2/vpc_dhcp_options_data_source_test.go index 1a59920593f..eedeb53616e 100644 --- a/internal/service/ec2/vpc_dhcp_options_data_source_test.go +++ b/internal/service/ec2/vpc_dhcp_options_data_source_test.go @@ -21,11 +21,11 @@ func TestAccVPCDHCPOptionsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCDHCPOptionsDataSourceConfig_Missing, + Config: testAccVPCDHCPOptionsDataSourceConfig_missing, ExpectError: regexp.MustCompile(`no matching EC2 DHCP Options Set found`), }, { - Config: testAccVPCDHCPOptionsDataSourceConfig_dhcpOptionsID, + Config: testAccVPCDHCPOptionsDataSourceConfig_id, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "dhcp_options_id", resourceName, "id"), resource.TestCheckResourceAttrPair(datasourceName, "domain_name", resourceName, "domain_name"), @@ -58,7 +58,7 @@ func TestAccVPCDHCPOptionsDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCDHCPOptionsDataSourceConfig_Filter(rInt, 1), + Config: testAccVPCDHCPOptionsDataSourceConfig_filter(rInt, 1), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "dhcp_options_id", resourceName, "id"), resource.TestCheckResourceAttrPair(datasourceName, "domain_name", resourceName, "domain_name"), @@ -76,7 +76,7 @@ func TestAccVPCDHCPOptionsDataSource_filter(t *testing.T) { ), }, { - Config: testAccVPCDHCPOptionsDataSourceConfig_Filter(rInt, 2), + Config: testAccVPCDHCPOptionsDataSourceConfig_filter(rInt, 2), ExpectError: regexp.MustCompile(`multiple EC2 DHCP Options Sets matched`), }, { @@ -84,19 +84,19 @@ func TestAccVPCDHCPOptionsDataSource_filter(t *testing.T) { // test case with resources in the state and an erroneous config, and // thus the automatic destroy step will fail. This ensures we end with // both an empty state and a valid config. - Config: `/* this config intentionally left blank */`, + Config: testAccVPCDHCPOptionsDataSourceConfig_blank(), }, }, }) } -const testAccVPCDHCPOptionsDataSourceConfig_Missing = ` +const testAccVPCDHCPOptionsDataSourceConfig_missing = ` data "aws_vpc_dhcp_options" "test" { dhcp_options_id = "does-not-exist" } ` -const testAccVPCDHCPOptionsDataSourceConfig_dhcpOptionsID = ` +const testAccVPCDHCPOptionsDataSourceConfig_id = ` resource "aws_vpc_dhcp_options" "incorrect" { domain_name = "tf-acc-test-incorrect.example.com" } @@ -118,7 +118,7 @@ data "aws_vpc_dhcp_options" "test" { } ` -func testAccVPCDHCPOptionsDataSourceConfig_Filter(rInt, count int) string { +func testAccVPCDHCPOptionsDataSourceConfig_filter(rInt, count int) string { return fmt.Sprintf(` resource "aws_vpc_dhcp_options" "incorrect" { domain_name = "tf-acc-test-incorrect.example.com" @@ -151,3 +151,7 @@ data "aws_vpc_dhcp_options" "test" { } `, rInt, count) } + +func testAccVPCDHCPOptionsDataSourceConfig_blank() string { + return `/* this config intentionally left blank */` +} diff --git a/internal/service/ec2/vpc_dhcp_options_test.go b/internal/service/ec2/vpc_dhcp_options_test.go index 7003a5474b9..614eb462039 100644 --- a/internal/service/ec2/vpc_dhcp_options_test.go +++ b/internal/service/ec2/vpc_dhcp_options_test.go @@ -18,7 +18,6 @@ import ( func TestAccVPCDHCPOptions_basic(t *testing.T) { var d ec2.DhcpOptions resourceName := "aws_vpc_dhcp_options.test" - rName := sdkacctest.RandString(5) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -27,18 +26,57 @@ func TestAccVPCDHCPOptions_basic(t *testing.T) { CheckDestroy: testAccCheckDHCPOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDHCPOptionsConfig(rName), + Config: testAccVPCDHCPOptionsConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckDHCPOptionsExists(resourceName, &d), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`dhcp-options/dopt-.+`)), - resource.TestCheckResourceAttr(resourceName, "domain_name", fmt.Sprintf("service.%s", rName)), + resource.TestCheckResourceAttr(resourceName, "domain_name", ""), + resource.TestCheckResourceAttr(resourceName, "domain_name_servers.#", "0"), + resource.TestCheckResourceAttr(resourceName, "netbios_name_servers.#", "0"), + resource.TestCheckResourceAttr(resourceName, "netbios_node_type", "1"), + resource.TestCheckResourceAttr(resourceName, "ntp_servers.#", "0"), + acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccVPCDHCPOptions_full(t *testing.T) { + var d ec2.DhcpOptions + resourceName := "aws_vpc_dhcp_options.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + domainName := acctest.RandomDomainName() + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckDHCPOptionsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCDHCPOptionsConfig_full(rName, domainName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckDHCPOptionsExists(resourceName, &d), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`dhcp-options/dopt-.+`)), + resource.TestCheckResourceAttr(resourceName, "domain_name", domainName), + resource.TestCheckResourceAttr(resourceName, "domain_name_servers.#", "2"), resource.TestCheckResourceAttr(resourceName, "domain_name_servers.0", "127.0.0.1"), resource.TestCheckResourceAttr(resourceName, "domain_name_servers.1", "10.0.0.2"), - resource.TestCheckResourceAttr(resourceName, "ntp_servers.0", "127.0.0.1"), + resource.TestCheckResourceAttr(resourceName, "netbios_name_servers.#", "1"), resource.TestCheckResourceAttr(resourceName, "netbios_name_servers.0", "127.0.0.1"), resource.TestCheckResourceAttr(resourceName, "netbios_node_type", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "ntp_servers.#", "1"), + resource.TestCheckResourceAttr(resourceName, "ntp_servers.0", "127.0.0.1"), acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), ), }, { @@ -53,7 +91,6 @@ func TestAccVPCDHCPOptions_basic(t *testing.T) { func TestAccVPCDHCPOptions_tags(t *testing.T) { var d ec2.DhcpOptions resourceName := "aws_vpc_dhcp_options.test" - rName := sdkacctest.RandString(5) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -62,7 +99,7 @@ func TestAccVPCDHCPOptions_tags(t *testing.T) { CheckDestroy: testAccCheckDHCPOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDHCPOptionsConfigTags1(rName, "key1", "value1"), + Config: testAccVPCDHCPOptionsConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDHCPOptionsExists(resourceName, &d), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -75,7 +112,7 @@ func TestAccVPCDHCPOptions_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDHCPOptionsConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCDHCPOptionsConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDHCPOptionsExists(resourceName, &d), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -84,7 +121,7 @@ func TestAccVPCDHCPOptions_tags(t *testing.T) { ), }, { - Config: testAccDHCPOptionsConfigTags1(rName, "key2", "value2"), + Config: testAccVPCDHCPOptionsConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDHCPOptionsExists(resourceName, &d), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -98,7 +135,6 @@ func TestAccVPCDHCPOptions_tags(t *testing.T) { func TestAccVPCDHCPOptions_disappears(t *testing.T) { var d ec2.DhcpOptions resourceName := "aws_vpc_dhcp_options.test" - rName := sdkacctest.RandString(5) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -107,7 +143,7 @@ func TestAccVPCDHCPOptions_disappears(t *testing.T) { CheckDestroy: testAccCheckDHCPOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDHCPOptionsConfig(rName), + Config: testAccVPCDHCPOptionsConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckDHCPOptionsExists(resourceName, &d), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPCDHCPOptions(), resourceName), @@ -167,47 +203,49 @@ func testAccCheckDHCPOptionsExists(n string, v *ec2.DhcpOptions) resource.TestCh } } -func testAccDHCPOptionsConfig(rName string) string { +const testAccVPCDHCPOptionsConfig_basic = ` +resource "aws_vpc_dhcp_options" "test" { + netbios_node_type = 1 +} +` + +func testAccVPCDHCPOptionsConfig_full(rName, domainName string) string { return fmt.Sprintf(` resource "aws_vpc_dhcp_options" "test" { - domain_name = "service.%[1]s" + domain_name = %[2]q domain_name_servers = ["127.0.0.1", "10.0.0.2"] ntp_servers = ["127.0.0.1"] netbios_name_servers = ["127.0.0.1"] - netbios_node_type = 2 + netbios_node_type = "2" + + tags = { + Name = %[1]q + } } -`, rName) +`, rName, domainName) } -func testAccDHCPOptionsConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccVPCDHCPOptionsConfig_tags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc_dhcp_options" "test" { - domain_name = "service.%[1]s" - domain_name_servers = ["127.0.0.1", "10.0.0.2"] - ntp_servers = ["127.0.0.1"] - netbios_name_servers = ["127.0.0.1"] - netbios_node_type = 2 + netbios_node_type = 2 tags = { - %[2]q = %[3]q + %[1]q = %[2]q } } -`, rName, tagKey1, tagValue1) +`, tagKey1, tagValue1) } -func testAccDHCPOptionsConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCDHCPOptionsConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc_dhcp_options" "test" { - domain_name = "service.%[1]s" - domain_name_servers = ["127.0.0.1", "10.0.0.2"] - ntp_servers = ["127.0.0.1"] - netbios_name_servers = ["127.0.0.1"] - netbios_node_type = 2 + netbios_node_type = 2 tags = { - %[2]q = %[3]q - %[4]q = %[5]q + %[1]q = %[2]q + %[3]q = %[4]q } } -`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +`, tagKey1, tagValue1, tagKey2, tagValue2) } diff --git a/internal/service/ec2/vpc_egress_only_internet_gateway_test.go b/internal/service/ec2/vpc_egress_only_internet_gateway_test.go index 4c5adc55f7a..687ccd2024b 100644 --- a/internal/service/ec2/vpc_egress_only_internet_gateway_test.go +++ b/internal/service/ec2/vpc_egress_only_internet_gateway_test.go @@ -26,7 +26,7 @@ func TestAccVPCEgressOnlyInternetGateway_basic(t *testing.T) { CheckDestroy: testAccCheckEgressOnlyInternetGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccEgressOnlyInternetGatewayConfig(rName), + Config: testAccVPCEgressOnlyInternetGatewayConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckEgressOnlyInternetGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -53,7 +53,7 @@ func TestAccVPCEgressOnlyInternetGateway_tags(t *testing.T) { CheckDestroy: testAccCheckEgressOnlyInternetGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccEgressOnlyInternetGatewayTags1Config(rName, "key1", "value1"), + Config: testAccVPCEgressOnlyInternetGatewayConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckEgressOnlyInternetGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -66,7 +66,7 @@ func TestAccVPCEgressOnlyInternetGateway_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEgressOnlyInternetGatewayTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCEgressOnlyInternetGatewayConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEgressOnlyInternetGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -75,7 +75,7 @@ func TestAccVPCEgressOnlyInternetGateway_tags(t *testing.T) { ), }, { - Config: testAccEgressOnlyInternetGatewayTags1Config(rName, "key2", "value2"), + Config: testAccVPCEgressOnlyInternetGatewayConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEgressOnlyInternetGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -135,7 +135,7 @@ func testAccCheckEgressOnlyInternetGatewayExists(n string, v *ec2.EgressOnlyInte } } -func testAccEgressOnlyInternetGatewayConfig(rName string) string { +func testAccVPCEgressOnlyInternetGatewayConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -152,7 +152,7 @@ resource "aws_egress_only_internet_gateway" "test" { `, rName) } -func testAccEgressOnlyInternetGatewayTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccVPCEgressOnlyInternetGatewayConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -172,7 +172,7 @@ resource "aws_egress_only_internet_gateway" "test" { `, rName, tagKey1, tagValue1) } -func testAccEgressOnlyInternetGatewayTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCEgressOnlyInternetGatewayConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_endpoint.go b/internal/service/ec2/vpc_endpoint.go index bc03d302e04..4a7f3dd7af2 100644 --- a/internal/service/ec2/vpc_endpoint.go +++ b/internal/service/ec2/vpc_endpoint.go @@ -31,6 +31,7 @@ func ResourceVPCEndpoint() *schema.Resource { Read: resourceVPCEndpointRead, Update: resourceVPCEndpointUpdate, Delete: resourceVPCEndpointDelete, + Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, @@ -65,11 +66,32 @@ func ResourceVPCEndpoint() *schema.Resource { }, }, }, + "dns_options": { + Type: schema.TypeList, + Optional: true, + Computed: true, + DiffSuppressFunc: verify.SuppressMissingOptionalConfigurationBlock, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "dns_record_ip_type": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice(ec2.DnsRecordIpType_Values(), false), + }, + }, + }, + }, + "ip_address_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice(ec2.IpAddressType_Values(), false), + }, "network_interface_ids": { Type: schema.TypeSet, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "owner_id": { Type: schema.TypeString, @@ -104,14 +126,12 @@ func ResourceVPCEndpoint() *schema.Resource { Optional: true, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "security_group_ids": { Type: schema.TypeSet, Optional: true, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "service_name": { Type: schema.TypeString, @@ -127,7 +147,6 @@ func ResourceVPCEndpoint() *schema.Resource { Optional: true, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), @@ -160,33 +179,53 @@ func resourceVPCEndpointCreate(d *schema.ResourceData, meta interface{}) error { defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) - req := &ec2.CreateVpcEndpointInput{ - VpcId: aws.String(d.Get("vpc_id").(string)), - VpcEndpointType: aws.String(d.Get("vpc_endpoint_type").(string)), - ServiceName: aws.String(d.Get("service_name").(string)), + serviceName := d.Get("service_name").(string) + input := &ec2.CreateVpcEndpointInput{ PrivateDnsEnabled: aws.Bool(d.Get("private_dns_enabled").(bool)), - TagSpecifications: tagSpecificationsFromKeyValueTags(tags, "vpc-endpoint"), + ServiceName: aws.String(serviceName), + TagSpecifications: tagSpecificationsFromKeyValueTags(tags, ec2.ResourceTypeVpcEndpoint), + VpcEndpointType: aws.String(d.Get("vpc_endpoint_type").(string)), + VpcId: aws.String(d.Get("vpc_id").(string)), + } + + if v, ok := d.GetOk("dns_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.DnsOptions = expandDNSOptionsSpecification(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("ip_address_type"); ok { + input.IpAddressType = aws.String(v.(string)) } if v, ok := d.GetOk("policy"); ok { policy, err := structure.NormalizeJsonString(v) + if err != nil { - return fmt.Errorf("policy contains an invalid JSON: %s", err) + return fmt.Errorf("policy contains invalid JSON: %w", err) } - req.PolicyDocument = aws.String(policy) + + input.PolicyDocument = aws.String(policy) } - setVPCEndpointCreateList(d, "route_table_ids", &req.RouteTableIds) - setVPCEndpointCreateList(d, "subnet_ids", &req.SubnetIds) - setVPCEndpointCreateList(d, "security_group_ids", &req.SecurityGroupIds) + if v, ok := d.GetOk("route_table_ids"); ok && v.(*schema.Set).Len() > 0 { + input.RouteTableIds = flex.ExpandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("security_group_ids"); ok && v.(*schema.Set).Len() > 0 { + input.SecurityGroupIds = flex.ExpandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("subnet_ids"); ok && v.(*schema.Set).Len() > 0 { + input.SubnetIds = flex.ExpandStringSet(v.(*schema.Set)) + } + + log.Printf("[DEBUG] Creating EC2 VPC Endpoint: %s", input) + output, err := conn.CreateVpcEndpoint(input) - log.Printf("[DEBUG] Creating VPC Endpoint: %#v", req) - resp, err := conn.CreateVpcEndpoint(req) if err != nil { - return fmt.Errorf("Error creating VPC Endpoint: %s", err) + return fmt.Errorf("creating EC2 VPC Endpoint (%s): %w", serviceName, err) } - vpce := resp.VpcEndpoint + vpce := output.VpcEndpoint d.SetId(aws.StringValue(vpce.VpcEndpointId)) if d.Get("auto_accept").(bool) && aws.StringValue(vpce.State) == vpcEndpointStatePendingAcceptance { @@ -195,10 +234,8 @@ func resourceVPCEndpointCreate(d *schema.ResourceData, meta interface{}) error { } } - _, err = WaitVPCEndpointAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) - - if err != nil { - return fmt.Errorf("error waiting for VPC Endpoint (%s) to become available: %w", d.Id(), err) + if _, err = WaitVPCEndpointAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return fmt.Errorf("waiting for EC2 VPC Endpoint (%s) create: %w", d.Id(), err) } return resourceVPCEndpointRead(d, meta) @@ -228,45 +265,48 @@ func resourceVPCEndpointRead(d *schema.ResourceData, meta interface{}) error { AccountID: aws.StringValue(vpce.OwnerId), Resource: fmt.Sprintf("vpc-endpoint/%s", d.Id()), }.String() - d.Set("arn", arn) - serviceName := aws.StringValue(vpce.ServiceName) + + d.Set("arn", arn) + if err := d.Set("dns_entry", flattenDNSEntries(vpce.DnsEntries)); err != nil { + return fmt.Errorf("setting dns_entry: %w", err) + } + if vpce.DnsOptions != nil { + if err := d.Set("dns_options", []interface{}{flattenDNSOptions(vpce.DnsOptions)}); err != nil { + return fmt.Errorf("setting dns_options: %w", err) + } + } else { + d.Set("dns_options", nil) + } + d.Set("ip_address_type", vpce.IpAddressType) + d.Set("network_interface_ids", aws.StringValueSlice(vpce.NetworkInterfaceIds)) + d.Set("owner_id", vpce.OwnerId) + d.Set("private_dns_enabled", vpce.PrivateDnsEnabled) + d.Set("requester_managed", vpce.RequesterManaged) + d.Set("route_table_ids", aws.StringValueSlice(vpce.RouteTableIds)) + d.Set("security_group_ids", flattenSecurityGroupIdentifiers(vpce.Groups)) d.Set("service_name", serviceName) d.Set("state", vpce.State) + d.Set("subnet_ids", aws.StringValueSlice(vpce.SubnetIds)) + // VPC endpoints don't have types in GovCloud, so set type to default if empty + if v := aws.StringValue(vpce.VpcEndpointType); v == "" { + d.Set("vpc_endpoint_type", ec2.VpcEndpointTypeGateway) + } else { + d.Set("vpc_endpoint_type", v) + } d.Set("vpc_id", vpce.VpcId) - respPl, err := conn.DescribePrefixLists(&ec2.DescribePrefixListsInput{ - Filters: BuildAttributeFilterList(map[string]string{ - "prefix-list-name": serviceName, - }), - }) - if err != nil { - return fmt.Errorf("error reading Prefix List (%s): %s", serviceName, err) - } - if respPl == nil || len(respPl.PrefixLists) == 0 { - d.Set("cidr_blocks", []interface{}{}) - } else if len(respPl.PrefixLists) > 1 { - return fmt.Errorf("multiple prefix lists associated with the service name '%s'. Unexpected", serviceName) + if pl, err := FindPrefixListByName(conn, serviceName); err != nil { + if tfresource.NotFound(err) { + d.Set("cidr_blocks", nil) + } else { + return fmt.Errorf("reading EC2 Prefix List (%s): %w", serviceName, err) + } } else { - pl := respPl.PrefixLists[0] - + d.Set("cidr_blocks", aws.StringValueSlice(pl.Cidrs)) d.Set("prefix_list_id", pl.PrefixListId) - err = d.Set("cidr_blocks", flex.FlattenStringList(pl.Cidrs)) - if err != nil { - return fmt.Errorf("error setting cidr_blocks: %s", err) - } } - err = d.Set("dns_entry", flattenVPCEndpointDNSEntries(vpce.DnsEntries)) - if err != nil { - return fmt.Errorf("error setting dns_entry: %s", err) - } - err = d.Set("network_interface_ids", flex.FlattenStringSet(vpce.NetworkInterfaceIds)) - if err != nil { - return fmt.Errorf("error setting network_interface_ids: %s", err) - } - d.Set("owner_id", vpce.OwnerId) - policyToSet, err := verify.SecondJSONUnlessEquivalent(d.Get("policy").(string), aws.StringValue(vpce.PolicyDocument)) if err != nil { @@ -281,36 +321,15 @@ func resourceVPCEndpointRead(d *schema.ResourceData, meta interface{}) error { d.Set("policy", policyToSet) - d.Set("private_dns_enabled", vpce.PrivateDnsEnabled) - err = d.Set("route_table_ids", flex.FlattenStringSet(vpce.RouteTableIds)) - if err != nil { - return fmt.Errorf("error setting route_table_ids: %s", err) - } - d.Set("requester_managed", vpce.RequesterManaged) - err = d.Set("security_group_ids", flattenVPCEndpointSecurityGroupIds(vpce.Groups)) - if err != nil { - return fmt.Errorf("error setting security_group_ids: %s", err) - } - err = d.Set("subnet_ids", flex.FlattenStringSet(vpce.SubnetIds)) - if err != nil { - return fmt.Errorf("error setting subnet_ids: %s", err) - } - // VPC endpoints don't have types in GovCloud, so set type to default if empty - if vpceType := aws.StringValue(vpce.VpcEndpointType); vpceType == "" { - d.Set("vpc_endpoint_type", ec2.VpcEndpointTypeGateway) - } else { - d.Set("vpc_endpoint_type", vpceType) - } - tags := KeyValueTags(vpce.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -325,52 +344,64 @@ func resourceVPCEndpointUpdate(d *schema.ResourceData, meta interface{}) error { } } - if d.HasChanges("policy", "route_table_ids", "subnet_ids", "security_group_ids", "private_dns_enabled") { - req := &ec2.ModifyVpcEndpointInput{ + if d.HasChanges("dns_options", "ip_address_type", "policy", "private_dns_enabled", "security_group_ids", "route_table_ids", "subnet_ids") { + input := &ec2.ModifyVpcEndpointInput{ VpcEndpointId: aws.String(d.Id()), } + if d.HasChange("dns_options") { + if v, ok := d.GetOk("dns_options"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.DnsOptions = expandDNSOptionsSpecification(v.([]interface{})[0].(map[string]interface{})) + } + } + + if d.HasChange("ip_address_type") { + input.IpAddressType = aws.String(d.Get("ip_address_type").(string)) + } + + if d.HasChange("private_dns_enabled") { + input.PrivateDnsEnabled = aws.Bool(d.Get("private_dns_enabled").(bool)) + } + + input.AddRouteTableIds, input.RemoveRouteTableIds = flattenAddAndRemoveStringLists(d, "route_table_ids") + input.AddSecurityGroupIds, input.RemoveSecurityGroupIds = flattenAddAndRemoveStringLists(d, "security_group_ids") + input.AddSubnetIds, input.RemoveSubnetIds = flattenAddAndRemoveStringLists(d, "subnet_ids") + if d.HasChange("policy") { o, n := d.GetChange("policy") if equivalent, err := awspolicy.PoliciesAreEquivalent(o.(string), n.(string)); err != nil || !equivalent { policy, err := structure.NormalizeJsonString(d.Get("policy")) + if err != nil { - return fmt.Errorf("policy contains an invalid JSON: %s", err) + return fmt.Errorf("policy contains invalid JSON: %w", err) } if policy == "" { - req.ResetPolicy = aws.Bool(true) + input.ResetPolicy = aws.Bool(true) } else { - req.PolicyDocument = aws.String(policy) + input.PolicyDocument = aws.String(policy) } } } - setVPCEndpointUpdateLists(d, "route_table_ids", &req.AddRouteTableIds, &req.RemoveRouteTableIds) - setVPCEndpointUpdateLists(d, "subnet_ids", &req.AddSubnetIds, &req.RemoveSubnetIds) - setVPCEndpointUpdateLists(d, "security_group_ids", &req.AddSecurityGroupIds, &req.RemoveSecurityGroupIds) - - if d.HasChange("private_dns_enabled") { - req.PrivateDnsEnabled = aws.Bool(d.Get("private_dns_enabled").(bool)) - } + log.Printf("[DEBUG] Updating EC2 VPC Endpoint: %s", input) + _, err := conn.ModifyVpcEndpoint(input) - log.Printf("[DEBUG] Updating VPC Endpoint: %#v", req) - if _, err := conn.ModifyVpcEndpoint(req); err != nil { - return fmt.Errorf("Error updating VPC Endpoint: %s", err) + if err != nil { + return fmt.Errorf("updating EC2 VPC Endpoint (%s): %w", d.Id(), err) } - _, err := WaitVPCEndpointAvailable(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)) - - if err != nil { - return fmt.Errorf("error waiting for VPC Endpoint (%s) to become available: %w", d.Id(), err) + if _, err := WaitVPCEndpointAvailable(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for EC2 VPC Endpoint (%s) update: %w", d.Id(), err) } } if d.HasChange("tags_all") { o, n := d.GetChange("tags_all") + if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating tags: %s", err) + return fmt.Errorf("updating tags: %w", err) } } @@ -380,11 +411,10 @@ func resourceVPCEndpointUpdate(d *schema.ResourceData, meta interface{}) error { func resourceVPCEndpointDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - input := &ec2.DeleteVpcEndpointsInput{ + log.Printf("[DEBUG] Deleting EC2 VPC Endpoint: %s", d.Id()) + output, err := conn.DeleteVpcEndpoints(&ec2.DeleteVpcEndpointsInput{ VpcEndpointIds: aws.StringSlice([]string{d.Id()}), - } - - output, err := conn.DeleteVpcEndpoints(input) + }) if err == nil && output != nil { err = UnsuccessfulItemsError(output.Unsuccessful) @@ -395,100 +425,142 @@ func resourceVPCEndpointDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting EC2 VPC Endpoint (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 VPC Endpoint (%s): %w", d.Id(), err) } - _, err = WaitVPCEndpointDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)) - - if err != nil { - return fmt.Errorf("error waiting for EC2 VPC Endpoint (%s) to delete: %w", d.Id(), err) + if _, err = WaitVPCEndpointDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + return fmt.Errorf("waiting for EC2 VPC Endpoint (%s) delete: %w", d.Id(), err) } return nil } -func vpcEndpointAccept(conn *ec2.EC2, vpceId, svcName string, timeout time.Duration) error { - describeSvcReq := &ec2.DescribeVpcEndpointServiceConfigurationsInput{} - describeSvcReq.Filters = BuildAttributeFilterList( - map[string]string{ - "service-name": svcName, - }, - ) +func vpcEndpointAccept(conn *ec2.EC2, vpceID, serviceName string, timeout time.Duration) error { + serviceConfiguration, err := FindVPCEndpointServiceConfigurationByServiceName(conn, serviceName) - describeSvcResp, err := conn.DescribeVpcEndpointServiceConfigurations(describeSvcReq) if err != nil { - return fmt.Errorf("error reading VPC Endpoint Service (%s): %s", svcName, err) - } - if describeSvcResp == nil || len(describeSvcResp.ServiceConfigurations) == 0 { - return fmt.Errorf("No matching VPC Endpoint Service found") + return fmt.Errorf("reading EC2 VPC Endpoint Service Configuration (%s): %w", serviceName, err) } - acceptEpReq := &ec2.AcceptVpcEndpointConnectionsInput{ - ServiceId: describeSvcResp.ServiceConfigurations[0].ServiceId, - VpcEndpointIds: aws.StringSlice([]string{vpceId}), + input := &ec2.AcceptVpcEndpointConnectionsInput{ + ServiceId: serviceConfiguration.ServiceId, + VpcEndpointIds: aws.StringSlice([]string{vpceID}), } - log.Printf("[DEBUG] Accepting VPC Endpoint connection: %#v", acceptEpReq) - _, err = conn.AcceptVpcEndpointConnections(acceptEpReq) + log.Printf("[DEBUG] Accepting EC2 VPC Endpoint connection: %s", input) + _, err = conn.AcceptVpcEndpointConnections(input) + if err != nil { - return fmt.Errorf("error accepting VPC Endpoint (%s) connection: %s", vpceId, err) + return fmt.Errorf("accepting EC2 VPC Endpoint (%s) connection: %w", vpceID, err) } - _, err = WaitVPCEndpointAccepted(conn, vpceId, timeout) - - if err != nil { - return fmt.Errorf("error waiting for VPC Endpoint (%s) to be accepted: %w", vpceId, err) + if _, err = WaitVPCEndpointAccepted(conn, vpceID, timeout); err != nil { + return fmt.Errorf("waiting for EC2 VPC Endpoint (%s) acceptance: %w", vpceID, err) } return nil } -func setVPCEndpointCreateList(d *schema.ResourceData, key string, c *[]*string) { - if v, ok := d.GetOk(key); ok { - list := v.(*schema.Set) - if list.Len() > 0 { - *c = flex.ExpandStringSet(list) - } +func expandDNSOptionsSpecification(tfMap map[string]interface{}) *ec2.DnsOptionsSpecification { + if tfMap == nil { + return nil + } + + apiObject := &ec2.DnsOptionsSpecification{} + + if v, ok := tfMap["dns_record_ip_type"].(string); ok && v != "" { + apiObject.DnsRecordIpType = aws.String(v) } + + return apiObject } -func setVPCEndpointUpdateLists(d *schema.ResourceData, key string, a, r *[]*string) { - if d.HasChange(key) { - o, n := d.GetChange(key) - os := o.(*schema.Set) - ns := n.(*schema.Set) +func flattenDNSEntry(apiObject *ec2.DnsEntry) map[string]interface{} { + if apiObject == nil { + return nil + } - add := flex.ExpandStringSet(ns.Difference(os)) - if len(add) > 0 { - *a = add - } + tfMap := map[string]interface{}{} - remove := flex.ExpandStringSet(os.Difference(ns)) - if len(remove) > 0 { - *r = remove + if v := apiObject.DnsName; v != nil { + tfMap["dns_name"] = aws.StringValue(v) + } + + if v := apiObject.HostedZoneId; v != nil { + tfMap["hosted_zone_id"] = aws.StringValue(v) + } + + return tfMap +} + +func flattenDNSEntries(apiObjects []*ec2.DnsEntry) []interface{} { + if len(apiObjects) == 0 { + return nil + } + + var tfList []interface{} + + for _, apiObject := range apiObjects { + if apiObject == nil { + continue } + + tfList = append(tfList, flattenDNSEntry(apiObject)) + } + + return tfList +} + +func flattenDNSOptions(apiObject *ec2.DnsOptions) map[string]interface{} { + if apiObject == nil { + return nil } + + tfMap := map[string]interface{}{} + + if v := apiObject.DnsRecordIpType; v != nil { + tfMap["dns_record_ip_type"] = aws.StringValue(v) + } + + return tfMap } -func flattenVPCEndpointDNSEntries(dnsEntries []*ec2.DnsEntry) []interface{} { - vDnsEntries := []interface{}{} +func flattenSecurityGroupIdentifiers(apiObjects []*ec2.SecurityGroupIdentifier) []string { + if len(apiObjects) == 0 { + return nil + } - for _, dnsEntry := range dnsEntries { - vDnsEntries = append(vDnsEntries, map[string]interface{}{ - "dns_name": aws.StringValue(dnsEntry.DnsName), - "hosted_zone_id": aws.StringValue(dnsEntry.HostedZoneId), - }) + var tfList []string + + for _, apiObject := range apiObjects { + if apiObject == nil { + continue + } + + tfList = append(tfList, aws.StringValue(apiObject.GroupId)) } - return vDnsEntries + return tfList } -func flattenVPCEndpointSecurityGroupIds(groups []*ec2.SecurityGroupIdentifier) *schema.Set { - vSecurityGroupIds := []interface{}{} +func flattenAddAndRemoveStringLists(d *schema.ResourceData, key string) ([]*string, []*string) { + if !d.HasChange(key) { + return nil, nil + } + + var add, del []*string + + o, n := d.GetChange(key) + os := o.(*schema.Set) + ns := n.(*schema.Set) + + if v := flex.ExpandStringSet(ns.Difference(os)); len(v) > 0 { + add = v + } - for _, group := range groups { - vSecurityGroupIds = append(vSecurityGroupIds, aws.StringValue(group.GroupId)) + if v := flex.ExpandStringSet(os.Difference(ns)); len(v) > 0 { + del = v } - return schema.NewSet(schema.HashString, vSecurityGroupIds) + return add, del } diff --git a/internal/service/ec2/vpc_endpoint_connection_accepter.go b/internal/service/ec2/vpc_endpoint_connection_accepter.go index 0f4e7a89107..52ff607eb0a 100644 --- a/internal/service/ec2/vpc_endpoint_connection_accepter.go +++ b/internal/service/ec2/vpc_endpoint_connection_accepter.go @@ -115,7 +115,7 @@ func resourceVPCEndpointConnectionAccepterDelete(d *schema.ResourceData, meta in _, err = conn.RejectVpcEndpointConnections(input) - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIdNotFound) { return nil } diff --git a/internal/service/ec2/vpc_endpoint_data_source.go b/internal/service/ec2/vpc_endpoint_data_source.go index 1c1ab2b61c8..7f60ca0528d 100644 --- a/internal/service/ec2/vpc_endpoint_data_source.go +++ b/internal/service/ec2/vpc_endpoint_data_source.go @@ -2,7 +2,6 @@ package ec2 import ( "fmt" - "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" @@ -10,8 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func DataSourceVPCEndpoint() *schema.Resource { @@ -44,17 +43,32 @@ func DataSourceVPCEndpoint() *schema.Resource { }, }, }, + "dns_options": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "dns_record_ip_type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, "filter": CustomFiltersSchema(), "id": { Type: schema.TypeString, Optional: true, Computed: true, }, + "ip_address_type": { + Type: schema.TypeString, + Computed: true, + }, "network_interface_ids": { Type: schema.TypeSet, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "owner_id": { Type: schema.TypeString, @@ -80,13 +94,11 @@ func DataSourceVPCEndpoint() *schema.Resource { Type: schema.TypeSet, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "security_group_ids": { Type: schema.TypeSet, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "service_name": { Type: schema.TypeString, @@ -102,7 +114,6 @@ func DataSourceVPCEndpoint() *schema.Resource { Type: schema.TypeSet, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "tags": tftags.TagsSchemaComputed(), "vpc_endpoint_type": { @@ -122,43 +133,37 @@ func dataSourceVPCEndpointRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - req := &ec2.DescribeVpcEndpointsInput{} + input := &ec2.DescribeVpcEndpointsInput{ + Filters: BuildAttributeFilterList( + map[string]string{ + "vpc-endpoint-state": d.Get("state").(string), + "vpc-id": d.Get("vpc_id").(string), + "service-name": d.Get("service_name").(string), + }, + ), + } - if id, ok := d.GetOk("id"); ok { - req.VpcEndpointIds = aws.StringSlice([]string{id.(string)}) + if v, ok := d.GetOk("id"); ok { + input.VpcEndpointIds = aws.StringSlice([]string{v.(string)}) } - req.Filters = BuildAttributeFilterList( - map[string]string{ - "vpc-endpoint-state": d.Get("state").(string), - "vpc-id": d.Get("vpc_id").(string), - "service-name": d.Get("service_name").(string), - }, - ) - req.Filters = append(req.Filters, BuildTagFilterList( + input.Filters = append(input.Filters, BuildTagFilterList( Tags(tftags.New(d.Get("tags").(map[string]interface{}))), )...) - req.Filters = append(req.Filters, BuildCustomFilterList( + input.Filters = append(input.Filters, BuildCustomFilterList( d.Get("filter").(*schema.Set), )...) - if len(req.Filters) == 0 { + if len(input.Filters) == 0 { // Don't send an empty filters list; the EC2 API won't accept it. - req.Filters = nil + input.Filters = nil } - log.Printf("[DEBUG] Reading VPC Endpoint: %s", req) - respVpce, err := conn.DescribeVpcEndpoints(req) + vpce, err := FindVPCEndpoint(conn, input) + if err != nil { - return fmt.Errorf("error reading VPC Endpoint: %w", err) - } - if respVpce == nil || len(respVpce.VpcEndpoints) == 0 { - return fmt.Errorf("no matching VPC Endpoint found") - } - if len(respVpce.VpcEndpoints) > 1 { - return fmt.Errorf("multiple VPC Endpoints matched; use additional constraints to reduce matches to a single VPC Endpoint") + return tfresource.SingularDataSourceFindError("EC2 VPC Endpoint", err) } - vpce := respVpce.VpcEndpoints[0] d.SetId(aws.StringValue(vpce.VpcEndpointId)) arn := arn.ARN{ @@ -168,72 +173,58 @@ func dataSourceVPCEndpointRead(d *schema.ResourceData, meta interface{}) error { AccountID: aws.StringValue(vpce.OwnerId), Resource: fmt.Sprintf("vpc-endpoint/%s", d.Id()), }.String() - d.Set("arn", arn) - serviceName := aws.StringValue(vpce.ServiceName) + + d.Set("arn", arn) + if err := d.Set("dns_entry", flattenDNSEntries(vpce.DnsEntries)); err != nil { + return fmt.Errorf("setting dns_entry: %w", err) + } + if vpce.DnsOptions != nil { + if err := d.Set("dns_options", []interface{}{flattenDNSOptions(vpce.DnsOptions)}); err != nil { + return fmt.Errorf("setting dns_options: %w", err) + } + } else { + d.Set("dns_options", nil) + } + d.Set("ip_address_type", vpce.IpAddressType) + d.Set("network_interface_ids", aws.StringValueSlice(vpce.NetworkInterfaceIds)) + d.Set("owner_id", vpce.OwnerId) + d.Set("private_dns_enabled", vpce.PrivateDnsEnabled) + d.Set("requester_managed", vpce.RequesterManaged) + d.Set("route_table_ids", aws.StringValueSlice(vpce.RouteTableIds)) + d.Set("security_group_ids", flattenSecurityGroupIdentifiers(vpce.Groups)) d.Set("service_name", serviceName) d.Set("state", vpce.State) + d.Set("subnet_ids", aws.StringValueSlice(vpce.SubnetIds)) + // VPC endpoints don't have types in GovCloud, so set type to default if empty + if v := aws.StringValue(vpce.VpcEndpointType); v == "" { + d.Set("vpc_endpoint_type", ec2.VpcEndpointTypeGateway) + } else { + d.Set("vpc_endpoint_type", v) + } d.Set("vpc_id", vpce.VpcId) - respPl, err := conn.DescribePrefixLists(&ec2.DescribePrefixListsInput{ - Filters: BuildAttributeFilterList(map[string]string{ - "prefix-list-name": serviceName, - }), - }) - if err != nil { - return fmt.Errorf("error reading Prefix List (%s): %w", serviceName, err) - } - if respPl == nil || len(respPl.PrefixLists) == 0 { - d.Set("cidr_blocks", []interface{}{}) - } else if len(respPl.PrefixLists) > 1 { - return fmt.Errorf("multiple prefix lists associated with the service name '%s'. Unexpected", serviceName) + if pl, err := FindPrefixListByName(conn, serviceName); err != nil { + if tfresource.NotFound(err) { + d.Set("cidr_blocks", nil) + } else { + return fmt.Errorf("reading EC2 Prefix List (%s): %w", serviceName, err) + } } else { - pl := respPl.PrefixLists[0] - + d.Set("cidr_blocks", aws.StringValueSlice(pl.Cidrs)) d.Set("prefix_list_id", pl.PrefixListId) - err = d.Set("cidr_blocks", flex.FlattenStringList(pl.Cidrs)) - if err != nil { - return fmt.Errorf("error setting cidr_blocks: %w", err) - } } - err = d.Set("dns_entry", flattenVPCEndpointDNSEntries(vpce.DnsEntries)) - if err != nil { - return fmt.Errorf("error setting dns_entry: %w", err) - } - err = d.Set("network_interface_ids", flex.FlattenStringSet(vpce.NetworkInterfaceIds)) - if err != nil { - return fmt.Errorf("error setting network_interface_ids: %w", err) - } - d.Set("owner_id", vpce.OwnerId) policy, err := structure.NormalizeJsonString(aws.StringValue(vpce.PolicyDocument)) + if err != nil { - return fmt.Errorf("policy contains an invalid JSON: %w", err) + return fmt.Errorf("policy contains invalid JSON: %w", err) } + d.Set("policy", policy) - d.Set("private_dns_enabled", vpce.PrivateDnsEnabled) - err = d.Set("route_table_ids", flex.FlattenStringSet(vpce.RouteTableIds)) - if err != nil { - return fmt.Errorf("error setting route_table_ids: %w", err) - } - d.Set("requester_managed", vpce.RequesterManaged) - err = d.Set("security_group_ids", flattenVPCEndpointSecurityGroupIds(vpce.Groups)) - if err != nil { - return fmt.Errorf("error setting security_group_ids: %w", err) - } - err = d.Set("subnet_ids", flex.FlattenStringSet(vpce.SubnetIds)) - if err != nil { - return fmt.Errorf("error setting subnet_ids: %w", err) - } - err = d.Set("tags", KeyValueTags(vpce.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) - if err != nil { - return fmt.Errorf("error setting tags: %w", err) - } - // VPC endpoints don't have types in GovCloud, so set type to default if empty - if vpceType := aws.StringValue(vpce.VpcEndpointType); vpceType == "" { - d.Set("vpc_endpoint_type", ec2.VpcEndpointTypeGateway) - } else { - d.Set("vpc_endpoint_type", vpceType) + + if err := d.Set("tags", KeyValueTags(vpce.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("setting tags: %w", err) } return nil diff --git a/internal/service/ec2/vpc_endpoint_data_source_test.go b/internal/service/ec2/vpc_endpoint_data_source_test.go index 3d2b209cf71..9d002a1ddac 100644 --- a/internal/service/ec2/vpc_endpoint_data_source_test.go +++ b/internal/service/ec2/vpc_endpoint_data_source_test.go @@ -2,7 +2,6 @@ package ec2_test import ( "fmt" - "regexp" "testing" "github.com/aws/aws-sdk-go/service/ec2" @@ -12,6 +11,7 @@ import ( ) func TestAccVPCEndpointDataSource_gatewayBasic(t *testing.T) { + resourceName := "aws_vpc_endpoint.test" datasourceName := "data.aws_vpc_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -22,19 +22,27 @@ func TestAccVPCEndpointDataSource_gatewayBasic(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCEndpointDataSourceConfig_gatewayBasic(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_type", "Gateway"), - resource.TestCheckResourceAttrSet(datasourceName, "prefix_list_id"), - resource.TestCheckResourceAttrSet(datasourceName, "cidr_blocks.#"), - resource.TestCheckResourceAttr(datasourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "security_group_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(datasourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(datasourceName, "tags.%", "0"), - acctest.CheckResourceAttrAccountID(datasourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "cidr_blocks.#", resourceName, "cidr_blocks.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_entry.#", resourceName, "dns_entry.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_options.#", resourceName, "dns_options.#"), + resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrPair(datasourceName, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(datasourceName, "network_interface_ids.#", resourceName, "network_interface_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "owner_id", resourceName, "owner_id"), + resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), + resource.TestCheckResourceAttrPair(datasourceName, "prefix_list_id", resourceName, "prefix_list_id"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_enabled", resourceName, "private_dns_enabled"), + resource.TestCheckResourceAttrPair(datasourceName, "requester_managed", resourceName, "requester_managed"), + resource.TestCheckResourceAttrPair(datasourceName, "route_table_ids.#", resourceName, "route_table_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "security_group_ids.#", resourceName, "security_group_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "service_name", resourceName, "service_name"), + resource.TestCheckResourceAttrPair(datasourceName, "state", resourceName, "state"), + resource.TestCheckResourceAttrPair(datasourceName, "subnet_ids.#", resourceName, "subnet_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_endpoint_type", resourceName, "vpc_endpoint_type"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_id", resourceName, "vpc_id"), ), }, }, @@ -42,6 +50,7 @@ func TestAccVPCEndpointDataSource_gatewayBasic(t *testing.T) { } func TestAccVPCEndpointDataSource_byID(t *testing.T) { + resourceName := "aws_vpc_endpoint.test" datasourceName := "data.aws_vpc_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -52,19 +61,27 @@ func TestAccVPCEndpointDataSource_byID(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCEndpointDataSourceConfig_byID(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_type", "Gateway"), - resource.TestCheckResourceAttrSet(datasourceName, "prefix_list_id"), - resource.TestCheckResourceAttrSet(datasourceName, "cidr_blocks.#"), - resource.TestCheckResourceAttr(datasourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "security_group_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(datasourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(datasourceName, "tags.%", "0"), - acctest.CheckResourceAttrAccountID(datasourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "cidr_blocks.#", resourceName, "cidr_blocks.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_entry.#", resourceName, "dns_entry.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_options.#", resourceName, "dns_options.#"), + resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrPair(datasourceName, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(datasourceName, "network_interface_ids.#", resourceName, "network_interface_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "owner_id", resourceName, "owner_id"), + resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), + resource.TestCheckResourceAttrPair(datasourceName, "prefix_list_id", resourceName, "prefix_list_id"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_enabled", resourceName, "private_dns_enabled"), + resource.TestCheckResourceAttrPair(datasourceName, "requester_managed", resourceName, "requester_managed"), + resource.TestCheckResourceAttrPair(datasourceName, "route_table_ids.#", resourceName, "route_table_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "security_group_ids.#", resourceName, "security_group_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "service_name", resourceName, "service_name"), + resource.TestCheckResourceAttrPair(datasourceName, "state", resourceName, "state"), + resource.TestCheckResourceAttrPair(datasourceName, "subnet_ids.#", resourceName, "subnet_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_endpoint_type", resourceName, "vpc_endpoint_type"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_id", resourceName, "vpc_id"), ), }, }, @@ -72,6 +89,7 @@ func TestAccVPCEndpointDataSource_byID(t *testing.T) { } func TestAccVPCEndpointDataSource_byFilter(t *testing.T) { + resourceName := "aws_vpc_endpoint.test" datasourceName := "data.aws_vpc_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -82,19 +100,27 @@ func TestAccVPCEndpointDataSource_byFilter(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCEndpointDataSourceConfig_byFilter(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_type", "Gateway"), - resource.TestCheckResourceAttrSet(datasourceName, "prefix_list_id"), - resource.TestCheckResourceAttrSet(datasourceName, "cidr_blocks.#"), - resource.TestCheckResourceAttr(datasourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "security_group_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(datasourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(datasourceName, "tags.%", "0"), - acctest.CheckResourceAttrAccountID(datasourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "cidr_blocks.#", resourceName, "cidr_blocks.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_entry.#", resourceName, "dns_entry.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_options.#", resourceName, "dns_options.#"), + resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrPair(datasourceName, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(datasourceName, "network_interface_ids.#", resourceName, "network_interface_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "owner_id", resourceName, "owner_id"), + resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), + resource.TestCheckResourceAttrPair(datasourceName, "prefix_list_id", resourceName, "prefix_list_id"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_enabled", resourceName, "private_dns_enabled"), + resource.TestCheckResourceAttrPair(datasourceName, "requester_managed", resourceName, "requester_managed"), + resource.TestCheckResourceAttrPair(datasourceName, "route_table_ids.#", resourceName, "route_table_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "security_group_ids.#", resourceName, "security_group_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "service_name", resourceName, "service_name"), + resource.TestCheckResourceAttrPair(datasourceName, "state", resourceName, "state"), + resource.TestCheckResourceAttrPair(datasourceName, "subnet_ids.#", resourceName, "subnet_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_endpoint_type", resourceName, "vpc_endpoint_type"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_id", resourceName, "vpc_id"), ), }, }, @@ -102,6 +128,7 @@ func TestAccVPCEndpointDataSource_byFilter(t *testing.T) { } func TestAccVPCEndpointDataSource_byTags(t *testing.T) { + resourceName := "aws_vpc_endpoint.test" datasourceName := "data.aws_vpc_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -112,19 +139,27 @@ func TestAccVPCEndpointDataSource_byTags(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCEndpointDataSourceConfig_byTags(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_type", "Gateway"), - resource.TestCheckResourceAttrSet(datasourceName, "prefix_list_id"), - resource.TestCheckResourceAttrSet(datasourceName, "cidr_blocks.#"), - resource.TestCheckResourceAttr(datasourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "security_group_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(datasourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(datasourceName, "tags.%", "3"), - acctest.CheckResourceAttrAccountID(datasourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "cidr_blocks.#", resourceName, "cidr_blocks.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_entry.#", resourceName, "dns_entry.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_options.#", resourceName, "dns_options.#"), + resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrPair(datasourceName, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(datasourceName, "network_interface_ids.#", resourceName, "network_interface_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "owner_id", resourceName, "owner_id"), + resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), + resource.TestCheckResourceAttrPair(datasourceName, "prefix_list_id", resourceName, "prefix_list_id"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_enabled", resourceName, "private_dns_enabled"), + resource.TestCheckResourceAttrPair(datasourceName, "requester_managed", resourceName, "requester_managed"), + resource.TestCheckResourceAttrPair(datasourceName, "route_table_ids.#", resourceName, "route_table_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "security_group_ids.#", resourceName, "security_group_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "service_name", resourceName, "service_name"), + resource.TestCheckResourceAttrPair(datasourceName, "state", resourceName, "state"), + resource.TestCheckResourceAttrPair(datasourceName, "subnet_ids.#", resourceName, "subnet_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_endpoint_type", resourceName, "vpc_endpoint_type"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_id", resourceName, "vpc_id"), ), }, }, @@ -132,6 +167,7 @@ func TestAccVPCEndpointDataSource_byTags(t *testing.T) { } func TestAccVPCEndpointDataSource_gatewayWithRouteTableAndTags(t *testing.T) { + resourceName := "aws_vpc_endpoint.test" datasourceName := "data.aws_vpc_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -141,21 +177,28 @@ func TestAccVPCEndpointDataSource_gatewayWithRouteTableAndTags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointDataSourceConfig_gatewayWithRouteTableAndTags(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_type", "Gateway"), - resource.TestCheckResourceAttrSet(datasourceName, "prefix_list_id"), - resource.TestCheckResourceAttrSet(datasourceName, "cidr_blocks.#"), - resource.TestCheckResourceAttr(datasourceName, "route_table_ids.#", "1"), - resource.TestCheckResourceAttr(datasourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "security_group_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(datasourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(datasourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(datasourceName, "tags.Name", rName), - acctest.CheckResourceAttrAccountID(datasourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + Config: testAccVPCEndpointDataSourceConfig_gatewayRouteTableAndTags(rName), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "cidr_blocks.#", resourceName, "cidr_blocks.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_entry.#", resourceName, "dns_entry.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_options.#", resourceName, "dns_options.#"), + resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrPair(datasourceName, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(datasourceName, "network_interface_ids.#", resourceName, "network_interface_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "owner_id", resourceName, "owner_id"), + resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), + resource.TestCheckResourceAttrPair(datasourceName, "prefix_list_id", resourceName, "prefix_list_id"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_enabled", resourceName, "private_dns_enabled"), + resource.TestCheckResourceAttrPair(datasourceName, "requester_managed", resourceName, "requester_managed"), + resource.TestCheckResourceAttrPair(datasourceName, "route_table_ids.#", resourceName, "route_table_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "security_group_ids.#", resourceName, "security_group_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "service_name", resourceName, "service_name"), + resource.TestCheckResourceAttrPair(datasourceName, "state", resourceName, "state"), + resource.TestCheckResourceAttrPair(datasourceName, "subnet_ids.#", resourceName, "subnet_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_endpoint_type", resourceName, "vpc_endpoint_type"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_id", resourceName, "vpc_id"), ), }, }, @@ -163,6 +206,7 @@ func TestAccVPCEndpointDataSource_gatewayWithRouteTableAndTags(t *testing.T) { } func TestAccVPCEndpointDataSource_interface(t *testing.T) { + resourceName := "aws_vpc_endpoint.test" datasourceName := "data.aws_vpc_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -173,20 +217,27 @@ func TestAccVPCEndpointDataSource_interface(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCEndpointDataSourceConfig_interface(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_type", "Interface"), - resource.TestCheckNoResourceAttr(datasourceName, "prefix_list_id"), - resource.TestCheckResourceAttr(datasourceName, "cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(datasourceName, "subnet_ids.#", "1"), - resource.TestCheckResourceAttr(datasourceName, "network_interface_ids.#", "1"), - resource.TestCheckResourceAttr(datasourceName, "security_group_ids.#", "1"), - resource.TestCheckResourceAttr(datasourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(datasourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(datasourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(datasourceName, "tags.Name", rName), - acctest.CheckResourceAttrAccountID(datasourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "cidr_blocks.#", resourceName, "cidr_blocks.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_entry.#", resourceName, "dns_entry.#"), + resource.TestCheckResourceAttrPair(datasourceName, "dns_options.#", resourceName, "dns_options.#"), + resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrPair(datasourceName, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(datasourceName, "network_interface_ids.#", resourceName, "network_interface_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "owner_id", resourceName, "owner_id"), + resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), + resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_enabled", resourceName, "private_dns_enabled"), + resource.TestCheckResourceAttrPair(datasourceName, "requester_managed", resourceName, "requester_managed"), + resource.TestCheckResourceAttrPair(datasourceName, "route_table_ids.#", resourceName, "route_table_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "security_group_ids.#", resourceName, "security_group_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "service_name", resourceName, "service_name"), + resource.TestCheckResourceAttrPair(datasourceName, "state", resourceName, "state"), + resource.TestCheckResourceAttrPair(datasourceName, "subnet_ids.#", resourceName, "subnet_ids.#"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_endpoint_type", resourceName, "vpc_endpoint_type"), + resource.TestCheckResourceAttrPair(datasourceName, "vpc_id", resourceName, "vpc_id"), ), }, }, @@ -208,6 +259,10 @@ data "aws_region" "current" {} resource "aws_vpc_endpoint" "test" { vpc_id = aws_vpc.test.id service_name = "com.amazonaws.${data.aws_region.current.name}.s3" + + tags = { + Name = %[1]q + } } data "aws_vpc_endpoint" "test" { @@ -233,6 +288,10 @@ data "aws_region" "current" {} resource "aws_vpc_endpoint" "test" { vpc_id = aws_vpc.test.id service_name = "com.amazonaws.${data.aws_region.current.name}.s3" + + tags = { + Name = %[1]q + } } data "aws_vpc_endpoint" "test" { @@ -256,6 +315,10 @@ data "aws_region" "current" {} resource "aws_vpc_endpoint" "test" { vpc_id = aws_vpc.test.id service_name = "com.amazonaws.${data.aws_region.current.name}.s3" + + tags = { + Name = %[1]q + } } data "aws_vpc_endpoint" "test" { @@ -284,6 +347,7 @@ resource "aws_vpc_endpoint" "test" { service_name = "com.amazonaws.${data.aws_region.current.name}.s3" tags = { + Name = %[1]q Key1 = "Value1" Key2 = "Value2" Key3 = "Value3" @@ -294,6 +358,7 @@ data "aws_vpc_endpoint" "test" { vpc_id = aws_vpc_endpoint.test.vpc_id tags = { + Name = %[1]q Key1 = "Value1" Key2 = "Value2" Key3 = "Value3" @@ -302,7 +367,7 @@ data "aws_vpc_endpoint" "test" { `, rName) } -func testAccVPCEndpointDataSourceConfig_gatewayWithRouteTableAndTags(rName string) string { +func testAccVPCEndpointDataSourceConfig_gatewayRouteTableAndTags(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -344,7 +409,7 @@ data "aws_vpc_endpoint" "test" { } func testAccVPCEndpointDataSourceConfig_interface(rName string) string { - return fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -353,15 +418,6 @@ resource "aws_vpc" "test" { } } -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - resource "aws_subnet" "test" { vpc_id = aws_vpc.test.id cidr_block = aws_vpc.test.cidr_block @@ -407,5 +463,5 @@ data "aws_vpc_endpoint" "test" { service_name = aws_vpc_endpoint.test.service_name state = "available" } -`, rName) +`, rName)) } diff --git a/internal/service/ec2/vpc_endpoint_route_table_association.go b/internal/service/ec2/vpc_endpoint_route_table_association.go index 9c0aaa3594b..f7c2d88dd32 100644 --- a/internal/service/ec2/vpc_endpoint_route_table_association.go +++ b/internal/service/ec2/vpc_endpoint_route_table_association.go @@ -107,7 +107,7 @@ func resourceVPCEndpointRouteTableAssociationDelete(d *schema.ResourceData, meta log.Printf("[DEBUG] Deleting VPC Endpoint Route Table Association: %s", id) _, err := conn.ModifyVpcEndpoint(input) - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIDNotFound) || tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIdNotFound) || tfawserr.ErrCodeEquals(err, errCodeInvalidParameter) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIdNotFound) || tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIdNotFound) || tfawserr.ErrCodeEquals(err, errCodeInvalidParameter) { return nil } diff --git a/internal/service/ec2/vpc_endpoint_security_group_association.go b/internal/service/ec2/vpc_endpoint_security_group_association.go index 93aededc84c..9ae8db53c46 100644 --- a/internal/service/ec2/vpc_endpoint_security_group_association.go +++ b/internal/service/ec2/vpc_endpoint_security_group_association.go @@ -183,7 +183,7 @@ func deleteVPCEndpointSecurityGroupAssociation(conn *ec2.EC2, vpcEndpointID, sec log.Printf("[DEBUG] Deleting VPC Endpoint Security Group Association: %s", input) _, err := conn.ModifyVpcEndpoint(input) - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIDNotFound, errCodeInvalidGroupNotFound, errCodeInvalidParameter) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIdNotFound, errCodeInvalidGroupNotFound, errCodeInvalidParameter) { return nil } diff --git a/internal/service/ec2/vpc_endpoint_security_group_association_test.go b/internal/service/ec2/vpc_endpoint_security_group_association_test.go index 819fc0e913f..6a3c296cf1c 100644 --- a/internal/service/ec2/vpc_endpoint_security_group_association_test.go +++ b/internal/service/ec2/vpc_endpoint_security_group_association_test.go @@ -97,7 +97,7 @@ func TestAccVPCEndpointSecurityGroupAssociation_replaceDefaultAssociation(t *tes CheckDestroy: testAccCheckVPCEndpointSecurityGroupAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointSecurityGroupAssociationConfig_replaceDefaultAssociation(rName), + Config: testAccVPCEndpointSecurityGroupAssociationConfig_replaceDefault(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointSecurityGroupAssociationExists(resourceName, &v), testAccCheckVPCEndpointSecurityGroupAssociationNumAssociations(&v, 1), @@ -230,7 +230,7 @@ resource "aws_vpc_endpoint_security_group_association" "test" { `) } -func testAccVPCEndpointSecurityGroupAssociationConfig_replaceDefaultAssociation(rName string) string { +func testAccVPCEndpointSecurityGroupAssociationConfig_replaceDefault(rName string) string { return acctest.ConfigCompose( testAccVPCEndpointSecurityGroupAssociationConfig_base(rName), ` diff --git a/internal/service/ec2/vpc_endpoint_service.go b/internal/service/ec2/vpc_endpoint_service.go index 5e38bebacaa..1c987bb4ff3 100644 --- a/internal/service/ec2/vpc_endpoint_service.go +++ b/internal/service/ec2/vpc_endpoint_service.go @@ -1,7 +1,6 @@ package ec2 import ( - "errors" "fmt" "log" "time" @@ -10,11 +9,12 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -24,6 +24,7 @@ func ResourceVPCEndpointService() *schema.Resource { Read: resourceVPCEndpointServiceRead, Update: resourceVPCEndpointServiceUpdate, Delete: resourceVPCEndpointServiceDelete, + Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, @@ -38,7 +39,6 @@ func ResourceVPCEndpointService() *schema.Resource { Optional: true, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "arn": { Type: schema.TypeString, @@ -48,13 +48,11 @@ func ResourceVPCEndpointService() *schema.Resource { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, Computed: true, - Set: schema.HashString, }, "base_endpoint_dns_names": { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, Computed: true, - Set: schema.HashString, }, "gateway_load_balancer_arns": { Type: schema.TypeSet, @@ -64,7 +62,6 @@ func ResourceVPCEndpointService() *schema.Resource { Type: schema.TypeString, ValidateFunc: verify.ValidARN, }, - Set: schema.HashString, }, "manages_vpc_endpoints": { Type: schema.TypeBool, @@ -78,7 +75,6 @@ func ResourceVPCEndpointService() *schema.Resource { Type: schema.TypeString, ValidateFunc: verify.ValidARN, }, - Set: schema.HashString, }, "private_dns_name": { Type: schema.TypeString, @@ -121,10 +117,25 @@ func ResourceVPCEndpointService() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "supported_ip_address_types": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(ec2.ServiceConnectivityType_Values(), false), + }, + }, "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(10 * time.Minute), + Update: schema.DefaultTimeout(10 * time.Minute), + Delete: schema.DefaultTimeout(10 * time.Minute), + }, + CustomizeDiff: verify.SetTagsDiff, } } @@ -134,46 +145,48 @@ func resourceVPCEndpointServiceCreate(d *schema.ResourceData, meta interface{}) defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) - req := &ec2.CreateVpcEndpointServiceConfigurationInput{ + input := &ec2.CreateVpcEndpointServiceConfigurationInput{ AcceptanceRequired: aws.Bool(d.Get("acceptance_required").(bool)), - TagSpecifications: tagSpecificationsFromKeyValueTags(tags, "vpc-endpoint-service"), + TagSpecifications: tagSpecificationsFromKeyValueTags(tags, ec2.ResourceTypeVpcEndpointService), } - if v, ok := d.GetOk("private_dns_name"); ok { - req.PrivateDnsName = aws.String(v.(string)) + + if v, ok := d.GetOk("gateway_load_balancer_arns"); ok && v.(*schema.Set).Len() > 0 { + input.GatewayLoadBalancerArns = flex.ExpandStringSet(v.(*schema.Set)) } - if v, ok := d.GetOk("gateway_load_balancer_arns"); ok { - if v, ok := v.(*schema.Set); ok && v.Len() > 0 { - req.GatewayLoadBalancerArns = flex.ExpandStringSet(v) - } + if v, ok := d.GetOk("network_load_balancer_arns"); ok && v.(*schema.Set).Len() > 0 { + input.NetworkLoadBalancerArns = flex.ExpandStringSet(v.(*schema.Set)) } - if v, ok := d.GetOk("network_load_balancer_arns"); ok { - if v, ok := v.(*schema.Set); ok && v.Len() > 0 { - req.NetworkLoadBalancerArns = flex.ExpandStringSet(v) - } + if v, ok := d.GetOk("private_dns_name"); ok { + input.PrivateDnsName = aws.String(v.(string)) + } + + if v, ok := d.GetOk("supported_ip_address_types"); ok && v.(*schema.Set).Len() > 0 { + input.SupportedIpAddressTypes = flex.ExpandStringSet(v.(*schema.Set)) } - log.Printf("[DEBUG] Creating VPC Endpoint Service configuration: %#v", req) - resp, err := conn.CreateVpcEndpointServiceConfiguration(req) + log.Printf("[DEBUG] Creating EC2 VPC Endpoint Service: %s", input) + output, err := conn.CreateVpcEndpointServiceConfiguration(input) + if err != nil { - return fmt.Errorf("Error creating VPC Endpoint Service configuration: %s", err.Error()) + return fmt.Errorf("creating EC2 VPC Endpoint Service: %w", err) } - d.SetId(aws.StringValue(resp.ServiceConfiguration.ServiceId)) + d.SetId(aws.StringValue(output.ServiceConfiguration.ServiceId)) - if err := vpcEndpointServiceWaitUntilAvailable(d, conn); err != nil { - return err + if _, err := WaitVPCEndpointServiceAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return fmt.Errorf("waiting for EC2 VPC Endpoint Service (%s) create: %w", d.Id(), err) } if v, ok := d.GetOk("allowed_principals"); ok && v.(*schema.Set).Len() > 0 { - modifyPermReq := &ec2.ModifyVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(d.Id()), + input := &ec2.ModifyVpcEndpointServicePermissionsInput{ AddAllowedPrincipals: flex.ExpandStringSet(v.(*schema.Set)), + ServiceId: aws.String(d.Id()), } - log.Printf("[DEBUG] Adding VPC Endpoint Service permissions: %#v", modifyPermReq) - if _, err := conn.ModifyVpcEndpointServicePermissions(modifyPermReq); err != nil { - return fmt.Errorf("error adding VPC Endpoint Service permissions: %s", err.Error()) + + if _, err := conn.ModifyVpcEndpointServicePermissions(input); err != nil { + return fmt.Errorf("modifying EC2 VPC Endpoint Service (%s) permissions: %w", d.Id(), err) } } @@ -185,22 +198,19 @@ func resourceVPCEndpointServiceRead(d *schema.ResourceData, meta interface{}) er defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - svcCfgRaw, state, err := vpcEndpointServiceStateRefresh(conn, d.Id())() - if err != nil && state != ec2.ServiceStateFailed { - return fmt.Errorf("error reading VPC Endpoint Service (%s): %s", d.Id(), err.Error()) - } + svcCfg, err := FindVPCEndpointServiceConfigurationByID(conn, d.Id()) - terminalStates := map[string]bool{ - ec2.ServiceStateDeleted: true, - ec2.ServiceStateDeleting: true, - ec2.ServiceStateFailed: true, - } - if _, ok := terminalStates[state]; ok { - log.Printf("[WARN] VPC Endpoint Service (%s) not found, removing from state", d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] EC2 VPC Endpoint Service %s not found, removing from state", d.Id()) d.SetId("") return nil } + if err != nil { + return fmt.Errorf("reading EC2 VPC Endpoint Service (%s): %w", d.Id(), err) + } + + d.Set("acceptance_required", svcCfg.AcceptanceRequired) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, Service: ec2.ServiceName, @@ -209,137 +219,93 @@ func resourceVPCEndpointServiceRead(d *schema.ResourceData, meta interface{}) er Resource: fmt.Sprintf("vpc-endpoint-service/%s", d.Id()), }.String() d.Set("arn", arn) - - svcCfg := svcCfgRaw.(*ec2.ServiceConfiguration) - d.Set("acceptance_required", svcCfg.AcceptanceRequired) - err = d.Set("availability_zones", flex.FlattenStringSet(svcCfg.AvailabilityZones)) - if err != nil { - return fmt.Errorf("error setting availability_zones: %s", err) - } - err = d.Set("base_endpoint_dns_names", flex.FlattenStringSet(svcCfg.BaseEndpointDnsNames)) - if err != nil { - return fmt.Errorf("error setting base_endpoint_dns_names: %s", err) - } - - if err := d.Set("gateway_load_balancer_arns", flex.FlattenStringSet(svcCfg.GatewayLoadBalancerArns)); err != nil { - return fmt.Errorf("error setting gateway_load_balancer_arns: %w", err) - } - + d.Set("availability_zones", aws.StringValueSlice(svcCfg.AvailabilityZones)) + d.Set("base_endpoint_dns_names", aws.StringValueSlice(svcCfg.BaseEndpointDnsNames)) + d.Set("gateway_load_balancer_arns", aws.StringValueSlice(svcCfg.GatewayLoadBalancerArns)) d.Set("manages_vpc_endpoints", svcCfg.ManagesVpcEndpoints) - - if err := d.Set("network_load_balancer_arns", flex.FlattenStringSet(svcCfg.NetworkLoadBalancerArns)); err != nil { - return fmt.Errorf("error setting network_load_balancer_arns: %w", err) - } - + d.Set("network_load_balancer_arns", aws.StringValueSlice(svcCfg.NetworkLoadBalancerArns)) d.Set("private_dns_name", svcCfg.PrivateDnsName) + // The EC2 API can return a XML structure with no elements. + if tfMap := flattenPrivateDNSNameConfiguration(svcCfg.PrivateDnsNameConfiguration); len(tfMap) > 0 { + if err := d.Set("private_dns_name_configuration", []interface{}{tfMap}); err != nil { + return fmt.Errorf("setting private_dns_name_configuration: %w", err) + } + } else { + d.Set("private_dns_name_configuration", nil) + } d.Set("service_name", svcCfg.ServiceName) - d.Set("service_type", svcCfg.ServiceType[0].ServiceType) + if len(svcCfg.ServiceType) > 0 { + d.Set("service_type", svcCfg.ServiceType[0].ServiceType) + } else { + d.Set("service_type", nil) + } d.Set("state", svcCfg.ServiceState) + d.Set("supported_ip_address_types", aws.StringValueSlice(svcCfg.SupportedIpAddressTypes)) tags := KeyValueTags(svcCfg.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } - resp, err := conn.DescribeVpcEndpointServicePermissions(&ec2.DescribeVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(d.Id()), - }) - if err != nil { - return fmt.Errorf("error reading VPC Endpoint Service permissions (%s): %s", d.Id(), err.Error()) - } + allowedPrincipals, err := FindVPCEndpointServicePermissionsByID(conn, d.Id()) - err = d.Set("allowed_principals", flattenVPCEndpointServiceAllowedPrincipals(resp.AllowedPrincipals)) if err != nil { - return fmt.Errorf("error setting allowed_principals: %s", err) + return fmt.Errorf("reading EC2 VPC Endpoint Service (%s) permissions: %w", d.Id(), err) } - err = d.Set("private_dns_name_configuration", flattenPrivateDNSNameConfiguration(svcCfg.PrivateDnsNameConfiguration)) - if err != nil { - return fmt.Errorf("error setting private_dns_name_configuration: %w", err) - } + d.Set("allowed_principals", flattenAllowedPrincipals(allowedPrincipals)) return nil } -func flattenPrivateDNSNameConfiguration(privateDnsNameConfiguration *ec2.PrivateDnsNameConfiguration) []interface{} { - if privateDnsNameConfiguration == nil { - return nil - } - tfMap := map[string]interface{}{} - - if v := privateDnsNameConfiguration.Name; v != nil { - tfMap["name"] = aws.StringValue(v) - } - - if v := privateDnsNameConfiguration.State; v != nil { - tfMap["state"] = aws.StringValue(v) - } - - if v := privateDnsNameConfiguration.Type; v != nil { - tfMap["type"] = aws.StringValue(v) - } - - if v := privateDnsNameConfiguration.Value; v != nil { - tfMap["value"] = aws.StringValue(v) - } - - // The EC2 API can return a XML structure with no elements - if len(tfMap) == 0 { - return nil - } - - return []interface{}{tfMap} -} - func resourceVPCEndpointServiceUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - if d.HasChanges("acceptance_required", "gateway_load_balancer_arns", "network_load_balancer_arns", "private_dns_name") { - modifyCfgReq := &ec2.ModifyVpcEndpointServiceConfigurationInput{ + if d.HasChanges("acceptance_required", "gateway_load_balancer_arns", "network_load_balancer_arns", "private_dns_name", "supported_ip_address_types") { + input := &ec2.ModifyVpcEndpointServiceConfigurationInput{ ServiceId: aws.String(d.Id()), } - if d.HasChange("private_dns_name") { - modifyCfgReq.PrivateDnsName = aws.String(d.Get("private_dns_name").(string)) + if d.HasChange("acceptance_required") { + input.AcceptanceRequired = aws.Bool(d.Get("acceptance_required").(bool)) } - if d.HasChange("acceptance_required") { - modifyCfgReq.AcceptanceRequired = aws.Bool(d.Get("acceptance_required").(bool)) + input.AddGatewayLoadBalancerArns, input.RemoveGatewayLoadBalancerArns = flattenAddAndRemoveStringLists(d, "gateway_load_balancer_arns") + input.AddNetworkLoadBalancerArns, input.RemoveNetworkLoadBalancerArns = flattenAddAndRemoveStringLists(d, "network_load_balancer_arns") + + if d.HasChange("private_dns_name") { + input.PrivateDnsName = aws.String(d.Get("private_dns_name").(string)) } - setVPCEndpointServiceUpdateLists(d, "gateway_load_balancer_arns", - &modifyCfgReq.AddGatewayLoadBalancerArns, &modifyCfgReq.RemoveGatewayLoadBalancerArns) + input.AddSupportedIpAddressTypes, input.RemoveSupportedIpAddressTypes = flattenAddAndRemoveStringLists(d, "supported_ip_address_types") - setVPCEndpointServiceUpdateLists(d, "network_load_balancer_arns", - &modifyCfgReq.AddNetworkLoadBalancerArns, &modifyCfgReq.RemoveNetworkLoadBalancerArns) + log.Printf("[DEBUG] Updating EC2 VPC Endpoint Service: %s", input) + _, err := conn.ModifyVpcEndpointServiceConfiguration(input) - log.Printf("[DEBUG] Modifying VPC Endpoint Service configuration: %#v", modifyCfgReq) - if _, err := conn.ModifyVpcEndpointServiceConfiguration(modifyCfgReq); err != nil { - return fmt.Errorf("Error modifying VPC Endpoint Service configuration: %s", err.Error()) + if err != nil { + return fmt.Errorf("updating EC2 VPC Endpoint Service (%s): %w", d.Id(), err) } - if err := vpcEndpointServiceWaitUntilAvailable(d, conn); err != nil { - return err + if _, err := WaitVPCEndpointServiceAvailable(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for EC2 VPC Endpoint Service (%s) update: %w", d.Id(), err) } } if d.HasChange("allowed_principals") { - modifyPermReq := &ec2.ModifyVpcEndpointServicePermissionsInput{ + input := &ec2.ModifyVpcEndpointServicePermissionsInput{ ServiceId: aws.String(d.Id()), } - setVPCEndpointServiceUpdateLists(d, "allowed_principals", - &modifyPermReq.AddAllowedPrincipals, &modifyPermReq.RemoveAllowedPrincipals) + input.AddAllowedPrincipals, input.RemoveAllowedPrincipals = flattenAddAndRemoveStringLists(d, "allowed_principals") - log.Printf("[DEBUG] Modifying VPC Endpoint Service permissions: %#v", modifyPermReq) - if _, err := conn.ModifyVpcEndpointServicePermissions(modifyPermReq); err != nil { - return fmt.Errorf("Error modifying VPC Endpoint Service permissions: %s", err.Error()) + if _, err := conn.ModifyVpcEndpointServicePermissions(input); err != nil { + return fmt.Errorf("modifying EC2 VPC Endpoint Service (%s) permissions: %w", d.Id(), err) } } @@ -347,7 +313,7 @@ func resourceVPCEndpointServiceUpdate(d *schema.ResourceData, meta interface{}) o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating EC2 VPC Endpoint Service (%s) tags: %s", d.Id(), err) + return fmt.Errorf("updating EC2 VPC Endpoint Service (%s) tags: %s", d.Id(), err) } } @@ -357,116 +323,78 @@ func resourceVPCEndpointServiceUpdate(d *schema.ResourceData, meta interface{}) func resourceVPCEndpointServiceDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - input := &ec2.DeleteVpcEndpointServiceConfigurationsInput{ + log.Printf("[INFO] Deleting EC2 VPC Endpoint Service: %s", d.Id()) + output, err := conn.DeleteVpcEndpointServiceConfigurations(&ec2.DeleteVpcEndpointServiceConfigurationsInput{ ServiceIds: aws.StringSlice([]string{d.Id()}), - } + }) - output, err := conn.DeleteVpcEndpointServiceConfigurations(input) + if err == nil && output != nil { + err = UnsuccessfulItemsError(output.Unsuccessful) + } - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIdNotFound) { return nil } if err != nil { - return fmt.Errorf("error deleting EC2 VPC Endpoint Service (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 VPC Endpoint Service (%s): %w", d.Id(), err) } - if output != nil && len(output.Unsuccessful) > 0 { - err := UnsuccessfulItemsError(output.Unsuccessful) - - if err != nil { - return fmt.Errorf("error deleting EC2 VPC Endpoint Service (%s): %w", d.Id(), err) - } + if _, err := WaitVPCEndpointServiceDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + return fmt.Errorf("waiting for EC2 VPC Endpoint Service (%s) delete: %w", d.Id(), err) } - if err := waitForVPCEndpointServiceDeletion(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for EC2 VPC Endpoint Service (%s) to delete: %w", d.Id(), err) + return nil +} + +func flattenAllowedPrincipal(apiObject *ec2.AllowedPrincipal) *string { + if apiObject == nil { + return nil } - return nil + return apiObject.Principal } -func vpcEndpointServiceStateRefresh(conn *ec2.EC2, svcId string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - log.Printf("[DEBUG] Reading VPC Endpoint Service Configuration: %s", svcId) - resp, err := conn.DescribeVpcEndpointServiceConfigurations(&ec2.DescribeVpcEndpointServiceConfigurationsInput{ - ServiceIds: aws.StringSlice([]string{svcId}), - }) - if err != nil { - if tfawserr.ErrCodeEquals(err, "InvalidVpcEndpointServiceId.NotFound") { - return false, ec2.ServiceStateDeleted, nil - } +func flattenAllowedPrincipals(apiObjects []*ec2.AllowedPrincipal) []*string { + if len(apiObjects) == 0 { + return nil + } - return nil, "", err - } + var tfList []*string - svcCfg := resp.ServiceConfigurations[0] - state := aws.StringValue(svcCfg.ServiceState) - // No use in retrying if the endpoint service is in a failed state. - if state == ec2.ServiceStateFailed { - return nil, state, errors.New("VPC Endpoint Service is in a failed state") + for _, apiObject := range apiObjects { + if apiObject == nil { + continue } - return svcCfg, state, nil - } -} -func vpcEndpointServiceWaitUntilAvailable(d *schema.ResourceData, conn *ec2.EC2) error { - stateConf := &resource.StateChangeConf{ - Pending: []string{ec2.ServiceStatePending}, - Target: []string{ec2.ServiceStateAvailable}, - Refresh: vpcEndpointServiceStateRefresh(conn, d.Id()), - Timeout: 10 * time.Minute, - Delay: 5 * time.Second, - MinTimeout: 5 * time.Second, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for VPC Endpoint Service %s to become available: %s", d.Id(), err.Error()) + tfList = append(tfList, flattenAllowedPrincipal(apiObject)) } - return nil + return tfList } -func waitForVPCEndpointServiceDeletion(conn *ec2.EC2, serviceID string) error { - stateConf := &resource.StateChangeConf{ - Pending: []string{ec2.ServiceStateAvailable, ec2.ServiceStateDeleting}, - Target: []string{ec2.ServiceStateDeleted}, - Refresh: vpcEndpointServiceStateRefresh(conn, serviceID), - Timeout: 10 * time.Minute, - Delay: 5 * time.Second, - MinTimeout: 5 * time.Second, +func flattenPrivateDNSNameConfiguration(apiObject *ec2.PrivateDnsNameConfiguration) map[string]interface{} { + if apiObject == nil { + return nil } - _, err := stateConf.WaitForState() - - return err -} - -func setVPCEndpointServiceUpdateLists(d *schema.ResourceData, key string, a, r *[]*string) { - if d.HasChange(key) { - o, n := d.GetChange(key) - os := o.(*schema.Set) - ns := n.(*schema.Set) + tfMap := map[string]interface{}{} - add := flex.ExpandStringSet(ns.Difference(os)) - if len(add) > 0 { - *a = add - } + if v := apiObject.Name; v != nil { + tfMap["name"] = aws.StringValue(v) + } - remove := flex.ExpandStringSet(os.Difference(ns)) - if len(remove) > 0 { - *r = remove - } + if v := apiObject.State; v != nil { + tfMap["state"] = aws.StringValue(v) } -} -func flattenVPCEndpointServiceAllowedPrincipals(allowedPrincipals []*ec2.AllowedPrincipal) *schema.Set { - vPrincipals := []interface{}{} + if v := apiObject.Type; v != nil { + tfMap["type"] = aws.StringValue(v) + } - for _, allowedPrincipal := range allowedPrincipals { - if allowedPrincipal.Principal != nil { - vPrincipals = append(vPrincipals, aws.StringValue(allowedPrincipal.Principal)) - } + if v := apiObject.Value; v != nil { + tfMap["value"] = aws.StringValue(v) } - return schema.NewSet(schema.HashString, vPrincipals) + return tfMap } diff --git a/internal/service/ec2/vpc_endpoint_service_allowed_principal.go b/internal/service/ec2/vpc_endpoint_service_allowed_principal.go index f82f4bf1bea..4de0daa7821 100644 --- a/internal/service/ec2/vpc_endpoint_service_allowed_principal.go +++ b/internal/service/ec2/vpc_endpoint_service_allowed_principal.go @@ -10,6 +10,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" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func ResourceVPCEndpointServiceAllowedPrincipal() *schema.Resource { @@ -19,12 +20,12 @@ func ResourceVPCEndpointServiceAllowedPrincipal() *schema.Resource { Delete: resourceVPCEndpointServiceAllowedPrincipalDelete, Schema: map[string]*schema.Schema{ - "vpc_endpoint_service_id": { + "principal_arn": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "principal_arn": { + "vpc_endpoint_service_id": { Type: schema.TypeString, Required: true, ForceNew: true, @@ -36,23 +37,19 @@ func ResourceVPCEndpointServiceAllowedPrincipal() *schema.Resource { func resourceVPCEndpointServiceAllowedPrincipalCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - svcId := d.Get("vpc_endpoint_service_id").(string) - arn := d.Get("principal_arn").(string) - - _, err := findResourceVPCEndpointServiceAllowedPrincipals(conn, svcId) - if err != nil { - return err - } + serviceID := d.Get("vpc_endpoint_service_id").(string) + principalARN := d.Get("principal_arn").(string) - _, err = conn.ModifyVpcEndpointServicePermissions(&ec2.ModifyVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(svcId), - AddAllowedPrincipals: aws.StringSlice([]string{arn}), + _, err := conn.ModifyVpcEndpointServicePermissions(&ec2.ModifyVpcEndpointServicePermissionsInput{ + AddAllowedPrincipals: aws.StringSlice([]string{principalARN}), + ServiceId: aws.String(serviceID), }) + if err != nil { - return fmt.Errorf("Error creating VPC Endpoint Service allowed principal: %s", err.Error()) + return fmt.Errorf("modifying EC2 VPC Endpoint Service (%s) permissions: %w", serviceID, err) } - d.SetId(vpcEndpointServiceIdPrincipalARNHash(svcId, arn)) + d.SetId(fmt.Sprintf("a-%s%d", serviceID, create.StringHashcode(principalARN))) return resourceVPCEndpointServiceAllowedPrincipalRead(d, meta) } @@ -60,66 +57,42 @@ func resourceVPCEndpointServiceAllowedPrincipalCreate(d *schema.ResourceData, me func resourceVPCEndpointServiceAllowedPrincipalRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - svcId := d.Get("vpc_endpoint_service_id").(string) - arn := d.Get("principal_arn").(string) - - principals, err := findResourceVPCEndpointServiceAllowedPrincipals(conn, svcId) - if err != nil { - if tfawserr.ErrCodeEquals(err, "InvalidVpcEndpointServiceId.NotFound") { - log.Printf("[WARN]VPC Endpoint Service (%s) not found, removing VPC Endpoint Service allowed principal (%s) from state", svcId, d.Id()) - d.SetId("") - return nil - } + serviceID := d.Get("vpc_endpoint_service_id").(string) + principalARN := d.Get("principal_arn").(string) - return err - } + err := FindVPCEndpointServicePermissionExists(conn, serviceID, principalARN) - found := false - for _, principal := range principals { - if aws.StringValue(principal.Principal) == arn { - found = true - break - } - } - if !found { - log.Printf("[WARN] VPC Endpoint Service allowed principal (%s) not found, removing from state", d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] EC2 VPC Endpoint Service Allowed Principal %s not found, removing from state", d.Id()) d.SetId("") return nil } + if err != nil { + return fmt.Errorf("reading EC2 VPC Endpoint Service (%s) Allowed Principal (%s): %w", serviceID, principalARN, err) + } + return nil } func resourceVPCEndpointServiceAllowedPrincipalDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - svcId := d.Get("vpc_endpoint_service_id").(string) - arn := d.Get("principal_arn").(string) + serviceID := d.Get("vpc_endpoint_service_id").(string) + principalARN := d.Get("principal_arn").(string) _, err := conn.ModifyVpcEndpointServicePermissions(&ec2.ModifyVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(svcId), - RemoveAllowedPrincipals: aws.StringSlice([]string{arn}), + RemoveAllowedPrincipals: aws.StringSlice([]string{principalARN}), + ServiceId: aws.String(serviceID), }) - if err != nil { - if !tfawserr.ErrCodeEquals(err, "InvalidVpcEndpointServiceId.NotFound") { - return fmt.Errorf("Error deleting VPC Endpoint Service allowed principal: %s", err.Error()) - } - } - return nil -} + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIdNotFound) { + return nil + } -func findResourceVPCEndpointServiceAllowedPrincipals(conn *ec2.EC2, id string) ([]*ec2.AllowedPrincipal, error) { - resp, err := conn.DescribeVpcEndpointServicePermissions(&ec2.DescribeVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(id), - }) if err != nil { - return nil, err + return fmt.Errorf("modifying EC2 VPC Endpoint Service (%s) permissions: %w", serviceID, err) } - return resp.AllowedPrincipals, nil -} - -func vpcEndpointServiceIdPrincipalARNHash(svcId, arn string) string { - return fmt.Sprintf("a-%s%d", svcId, create.StringHashcode(arn)) + return nil } diff --git a/internal/service/ec2/vpc_endpoint_service_allowed_principal_test.go b/internal/service/ec2/vpc_endpoint_service_allowed_principal_test.go index a6934db58f7..3b26c860b0d 100644 --- a/internal/service/ec2/vpc_endpoint_service_allowed_principal_test.go +++ b/internal/service/ec2/vpc_endpoint_service_allowed_principal_test.go @@ -4,18 +4,19 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func TestAccVPCEndpointServiceAllowedPrincipal_basic(t *testing.T) { - lbName := fmt.Sprintf("testAccNLB-basic-%s", sdkacctest.RandString(10)) + resourceName := "aws_vpc_endpoint_service_allowed_principal.test" + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -24,9 +25,9 @@ func TestAccVPCEndpointServiceAllowedPrincipal_basic(t *testing.T) { CheckDestroy: testAccCheckVPCEndpointServiceAllowedPrincipalDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceAllowedPrincipalConfig_basic(lbName), + Config: testAccVPCEndpointServiceAllowedPrincipalConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckVPCEndpointServiceAllowedPrincipalExists("aws_vpc_endpoint_service_allowed_principal.foo"), + testAccCheckVPCEndpointServiceAllowedPrincipalExists(resourceName), ), }, }, @@ -41,26 +42,17 @@ func testAccCheckVPCEndpointServiceAllowedPrincipalDestroy(s *terraform.State) e continue } - // Try to find the resource - resp, err := conn.DescribeVpcEndpointServicePermissions(&ec2.DescribeVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(rs.Primary.Attributes["vpc_endpoint_service_id"]), - }) - if err != nil { - // Verify the error is what we want - ec2err, ok := err.(awserr.Error) - if !ok { - return err - } - if ec2err.Code() != "InvalidVpcEndpointServiceId.NotFound" { - return err - } - return nil + err := tfec2.FindVPCEndpointServicePermissionExists(conn, rs.Primary.Attributes["vpc_endpoint_service_id"], rs.Primary.Attributes["principal_arn"]) + + if tfresource.NotFound(err) { + continue } - if len(resp.AllowedPrincipals) > 0 { - return fmt.Errorf( - "VCP Endpoint Service %s has allowed principals", rs.Primary.Attributes["vpc_endpoint_service_id"]) + if err != nil { + return err } + + return fmt.Errorf("EC2 VPC Endpoint Service Allowed Principal %s still exists", rs.Primary.ID) } return nil @@ -74,91 +66,36 @@ func testAccCheckVPCEndpointServiceAllowedPrincipalExists(n string) resource.Tes } if rs.Primary.ID == "" { - return fmt.Errorf("No VPC Endpoint Service ID is set") + return fmt.Errorf("No EC2 VPC Endpoint Service Allowed Principal ID is set") } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - resp, err := conn.DescribeVpcEndpointServicePermissions(&ec2.DescribeVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(rs.Primary.Attributes["vpc_endpoint_service_id"]), - }) - if err != nil { - return err - } - - for _, principal := range resp.AllowedPrincipals { - if aws.StringValue(principal.Principal) == rs.Primary.Attributes["principal_arn"] { - return nil - } - } - - return fmt.Errorf("VPC Endpoint Service allowed principal not found") + return tfec2.FindVPCEndpointServicePermissionExists(conn, rs.Primary.Attributes["vpc_endpoint_service_id"], rs.Primary.Attributes["principal_arn"]) } } -func testAccVPCEndpointServiceAllowedPrincipalConfig_basic(lbName string) string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf( - ` -resource "aws_vpc" "nlb_test" { - cidr_block = "10.0.0.0/16" - - tags = { - Name = "terraform-testacc-vpc-endpoint-service-allowed-principal" - } -} - -resource "aws_lb" "nlb_test_1" { - name = "%s" - - subnets = [ - aws_subnet.nlb_test_1.id, - aws_subnet.nlb_test_2.id, - ] - - load_balancer_type = "network" - internal = true - idle_timeout = 60 - enable_deletion_protection = false - - tags = { - Name = "testAccVpcEndpointServiceBasicConfig_nlb1" - } -} - -resource "aws_subnet" "nlb_test_1" { - vpc_id = aws_vpc.nlb_test.id - cidr_block = "10.0.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] +func testAccVPCEndpointServiceAllowedPrincipalConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_networkLoadBalancerBase(rName, 1), fmt.Sprintf(` +data "aws_caller_identity" "current" {} - tags = { - Name = "tf-acc-vpc-endpoint-service-allowed-principal-1" - } +data "aws_iam_session_context" "current" { + arn = data.aws_caller_identity.current.arn } -resource "aws_subnet" "nlb_test_2" { - vpc_id = aws_vpc.nlb_test.id - cidr_block = "10.0.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] +resource "aws_vpc_endpoint_service" "test" { + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn tags = { - Name = "tf-acc-vpc-endpoint-service-allowed-principal-2" + Name = %[1]q } } -data "aws_caller_identity" "current" {} - -resource "aws_vpc_endpoint_service" "foo" { - acceptance_required = false - - network_load_balancer_arns = [ - aws_lb.nlb_test_1.id, - ] -} - -resource "aws_vpc_endpoint_service_allowed_principal" "foo" { - vpc_endpoint_service_id = aws_vpc_endpoint_service.foo.id +resource "aws_vpc_endpoint_service_allowed_principal" "test" { + vpc_endpoint_service_id = aws_vpc_endpoint_service.test.id - principal_arn = data.aws_caller_identity.current.arn + principal_arn = data.aws_iam_session_context.current.issuer_arn } -`, lbName)) +`, rName)) } diff --git a/internal/service/ec2/vpc_endpoint_service_data_source.go b/internal/service/ec2/vpc_endpoint_service_data_source.go index 1f29b50cfa6..c331c86682b 100644 --- a/internal/service/ec2/vpc_endpoint_service_data_source.go +++ b/internal/service/ec2/vpc_endpoint_service_data_source.go @@ -2,7 +2,6 @@ package ec2 import ( "fmt" - "log" "strconv" "github.com/aws/aws-sdk-go/aws" @@ -12,7 +11,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" - "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" ) @@ -33,14 +31,13 @@ func DataSourceVPCEndpointService() *schema.Resource { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, Computed: true, - Set: schema.HashString, }, "base_endpoint_dns_names": { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, Computed: true, - Set: schema.HashString, }, + "filter": CustomFiltersSchema(), "manages_vpc_endpoints": { Type: schema.TypeBool, Computed: true, @@ -74,12 +71,16 @@ func DataSourceVPCEndpointService() *schema.Resource { Computed: true, ValidateFunc: validation.StringInSlice(ec2.ServiceType_Values(), false), }, + "supported_ip_address_types": { + Type: schema.TypeSet, + Elem: &schema.Schema{Type: schema.TypeString}, + Computed: true, + }, "tags": tftags.TagsSchemaComputed(), "vpc_endpoint_policy_supported": { Type: schema.TypeBool, Computed: true, }, - "filter": DataSourceFiltersSchema(), }, } } @@ -88,54 +89,56 @@ func dataSourceVPCEndpointServiceRead(d *schema.ResourceData, meta interface{}) conn := meta.(*conns.AWSClient).EC2Conn ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - filters, filtersOk := d.GetOk("filter") - tags, tagsOk := d.GetOk("tags") + input := &ec2.DescribeVpcEndpointServicesInput{ + Filters: BuildAttributeFilterList( + map[string]string{ + "service-type": d.Get("service_type").(string), + }, + ), + } var serviceName string - serviceNameOk := false + if v, ok := d.GetOk("service_name"); ok { serviceName = v.(string) - serviceNameOk = true } else if v, ok := d.GetOk("service"); ok { serviceName = fmt.Sprintf("com.amazonaws.%s.%s", meta.(*conns.AWSClient).Region, v.(string)) - serviceNameOk = true } - req := &ec2.DescribeVpcEndpointServicesInput{} - if filtersOk { - req.Filters = BuildFiltersDataSource(filters.(*schema.Set)) - } - if serviceNameOk { - req.ServiceNames = aws.StringSlice([]string{serviceName}) + if serviceName != "" { + input.ServiceNames = aws.StringSlice([]string{serviceName}) } - if v, ok := d.GetOk("service_type"); ok { - req.Filters = append(req.Filters, &ec2.Filter{ - Name: aws.String("service-type"), - Values: aws.StringSlice([]string{v.(string)}), - }) + if v, ok := d.GetOk("tags"); ok { + input.Filters = append(input.Filters, BuildTagFilterList( + Tags(tftags.New(v.(map[string]interface{}))), + )...) } - if tagsOk { - req.Filters = append(req.Filters, tagFiltersFromMap(tags.(map[string]interface{}))...) + input.Filters = append(input.Filters, BuildCustomFilterList( + d.Get("filter").(*schema.Set), + )...) + + if len(input.Filters) == 0 { + // Don't send an empty filters list; the EC2 API won't accept it. + input.Filters = nil } - log.Printf("[DEBUG] Reading VPC Endpoint Service: %s", req) - resp, err := conn.DescribeVpcEndpointServices(req) + serviceDetails, serviceNames, err := FindVPCEndpointServices(conn, input) + if err != nil { - return fmt.Errorf("error reading VPC Endpoint Service (%s): %w", serviceName, err) + return fmt.Errorf("reading EC2 VPC Endpoint Services: %w", err) } - if resp == nil || (len(resp.ServiceNames) == 0 && len(resp.ServiceDetails) == 0) { - return fmt.Errorf("no matching VPC Endpoint Service found") + if len(serviceDetails) == 0 && len(serviceNames) == 0 { + return fmt.Errorf("no matching EC2 VPC Endpoint Service found") } // Note: AWS Commercial now returns a response with `ServiceNames` and // `ServiceDetails`, but GovCloud responses only include `ServiceNames` - if len(resp.ServiceDetails) == 0 { + if len(serviceDetails) == 0 { // GovCloud doesn't respect the filter. - names := aws.StringValueSlice(resp.ServiceNames) - for _, name := range names { + for _, name := range serviceNames { if name == serviceName { d.SetId(strconv.Itoa(create.StringHashcode(name))) d.Set("service_name", name) @@ -143,48 +146,49 @@ func dataSourceVPCEndpointServiceRead(d *schema.ResourceData, meta interface{}) } } - return fmt.Errorf("no matching VPC Endpoint Service found") + return fmt.Errorf("no matching EC2 VPC Endpoint Service found") } - if len(resp.ServiceDetails) > 1 { - return fmt.Errorf("multiple VPC Endpoint Services matched; use additional constraints to reduce matches to a single VPC Endpoint Service") + if len(serviceDetails) > 1 { + return fmt.Errorf("multiple EC2 VPC Endpoint Services matched; use additional constraints to reduce matches to a single EC2 VPC Endpoint Service") } - sd := resp.ServiceDetails[0] - serviceId := aws.StringValue(sd.ServiceId) + sd := serviceDetails[0] + serviceID := aws.StringValue(sd.ServiceId) serviceName = aws.StringValue(sd.ServiceName) d.SetId(strconv.Itoa(create.StringHashcode(serviceName))) + d.Set("acceptance_required", sd.AcceptanceRequired) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, Service: ec2.ServiceName, Region: meta.(*conns.AWSClient).Region, AccountID: meta.(*conns.AWSClient).AccountID, - Resource: fmt.Sprintf("vpc-endpoint-service/%s", serviceId), + Resource: fmt.Sprintf("vpc-endpoint-service/%s", serviceID), }.String() d.Set("arn", arn) - d.Set("acceptance_required", sd.AcceptanceRequired) - err = d.Set("availability_zones", flex.FlattenStringSet(sd.AvailabilityZones)) - if err != nil { - return fmt.Errorf("error setting availability_zones: %w", err) - } - err = d.Set("base_endpoint_dns_names", flex.FlattenStringSet(sd.BaseEndpointDnsNames)) - if err != nil { - return fmt.Errorf("error setting base_endpoint_dns_names: %w", err) - } + d.Set("availability_zones", aws.StringValueSlice(sd.AvailabilityZones)) + d.Set("base_endpoint_dns_names", aws.StringValueSlice(sd.BaseEndpointDnsNames)) d.Set("manages_vpc_endpoints", sd.ManagesVpcEndpoints) d.Set("owner", sd.Owner) d.Set("private_dns_name", sd.PrivateDnsName) - d.Set("service_id", serviceId) + d.Set("service_id", serviceID) d.Set("service_name", serviceName) - d.Set("service_type", sd.ServiceType[0].ServiceType) + if len(sd.ServiceType) > 0 { + d.Set("service_type", sd.ServiceType[0].ServiceType) + } else { + d.Set("service_type", nil) + } + d.Set("supported_ip_address_types", aws.StringValueSlice(sd.SupportedIpAddressTypes)) + d.Set("vpc_endpoint_policy_supported", sd.VpcEndpointPolicySupported) + err = d.Set("tags", KeyValueTags(sd.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) + if err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } - d.Set("vpc_endpoint_policy_supported", sd.VpcEndpointPolicySupported) return nil } diff --git a/internal/service/ec2/vpc_endpoint_service_data_source_test.go b/internal/service/ec2/vpc_endpoint_service_data_source_test.go index 2e5d45caa9c..a284420f426 100644 --- a/internal/service/ec2/vpc_endpoint_service_data_source_test.go +++ b/internal/service/ec2/vpc_endpoint_service_data_source_test.go @@ -21,19 +21,20 @@ func TestAccVPCEndpointServiceDataSource_gateway(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceGatewayDataSourceConfig, + Config: testAccVPCEndpointServiceDataSourceConfig_gateway, Check: resource.ComposeTestCheckFunc( - testAccCheckResourceAttrRegionalReverseDNSService(datasourceName, "service_name", "dynamodb"), resource.TestCheckResourceAttr(datasourceName, "acceptance_required", "false"), - resource.TestCheckResourceAttrPair(datasourceName, "availability_zones.#", "data.aws_availability_zones.available", "names.#"), + acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), + acctest.CheckResourceAttrGreaterThanValue(datasourceName, "availability_zones.#", "0"), resource.TestCheckResourceAttr(datasourceName, "base_endpoint_dns_names.#", "1"), resource.TestCheckResourceAttr(datasourceName, "manages_vpc_endpoints", "false"), resource.TestCheckResourceAttr(datasourceName, "owner", "amazon"), resource.TestCheckResourceAttr(datasourceName, "private_dns_name", ""), + testAccCheckResourceAttrRegionalReverseDNSService(datasourceName, "service_name", "dynamodb"), resource.TestCheckResourceAttr(datasourceName, "service_type", "Gateway"), - resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_policy_supported", "true"), + acctest.CheckResourceAttrGreaterThanValue(datasourceName, "supported_ip_address_types.#", "0"), resource.TestCheckResourceAttr(datasourceName, "tags.%", "0"), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), + resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_policy_supported", "true"), ), }, }, @@ -49,18 +50,20 @@ func TestAccVPCEndpointServiceDataSource_interface(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceInterfaceDataSourceConfig, + Config: testAccVPCEndpointServiceDataSourceConfig_interface, Check: resource.ComposeTestCheckFunc( - testAccCheckResourceAttrRegionalReverseDNSService(datasourceName, "service_name", "ec2"), resource.TestCheckResourceAttr(datasourceName, "acceptance_required", "false"), + acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), + acctest.CheckResourceAttrGreaterThanValue(datasourceName, "availability_zones.#", "0"), resource.TestCheckResourceAttr(datasourceName, "base_endpoint_dns_names.#", "1"), resource.TestCheckResourceAttr(datasourceName, "manages_vpc_endpoints", "false"), resource.TestCheckResourceAttr(datasourceName, "owner", "amazon"), acctest.CheckResourceAttrRegionalHostnameService(datasourceName, "private_dns_name", "ec2"), + testAccCheckResourceAttrRegionalReverseDNSService(datasourceName, "service_name", "ec2"), resource.TestCheckResourceAttr(datasourceName, "service_type", "Interface"), - resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_policy_supported", "true"), + acctest.CheckResourceAttrGreaterThanValue(datasourceName, "supported_ip_address_types.#", "0"), resource.TestCheckResourceAttr(datasourceName, "tags.%", "0"), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), + resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_policy_supported", "true"), ), }, }, @@ -68,8 +71,9 @@ func TestAccVPCEndpointServiceDataSource_interface(t *testing.T) { } func TestAccVPCEndpointServiceDataSource_custom(t *testing.T) { + resourceName := "aws_vpc_endpoint_service.test" datasourceName := "data.aws_vpc_endpoint_service.test" - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -77,17 +81,19 @@ func TestAccVPCEndpointServiceDataSource_custom(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceCustomDataSourceConfig(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(datasourceName, "acceptance_required", "true"), - resource.TestCheckResourceAttr(datasourceName, "availability_zones.#", "2"), - resource.TestCheckResourceAttr(datasourceName, "manages_vpc_endpoints", "false"), + Config: testAccVPCEndpointServiceDataSourceConfig_custom(rName), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "acceptance_required", resourceName, "acceptance_required"), + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "availability_zones.#", resourceName, "availability_zones.#"), + resource.TestCheckResourceAttrPair(datasourceName, "base_endpoint_dns_names.#", resourceName, "base_endpoint_dns_names.#"), + resource.TestCheckResourceAttrPair(datasourceName, "manages_vpc_endpoints", resourceName, "manages_vpc_endpoints"), acctest.CheckResourceAttrAccountID(datasourceName, "owner"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_name", resourceName, "private_dns_name"), resource.TestCheckResourceAttr(datasourceName, "service_type", "Interface"), + resource.TestCheckResourceAttrPair(datasourceName, "supported_ip_address_types.#", resourceName, "supported_ip_address_types.#"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_policy_supported", "false"), - resource.TestCheckResourceAttr(datasourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(datasourceName, "tags.Name", rName), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), ), }, }, @@ -95,8 +101,9 @@ func TestAccVPCEndpointServiceDataSource_custom(t *testing.T) { } func TestAccVPCEndpointServiceDataSource_Custom_filter(t *testing.T) { + resourceName := "aws_vpc_endpoint_service.test" datasourceName := "data.aws_vpc_endpoint_service.test" - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -104,17 +111,19 @@ func TestAccVPCEndpointServiceDataSource_Custom_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceCustomFilterDataSourceConfig(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(datasourceName, "acceptance_required", "true"), - resource.TestCheckResourceAttr(datasourceName, "availability_zones.#", "2"), - resource.TestCheckResourceAttr(datasourceName, "manages_vpc_endpoints", "false"), + Config: testAccVPCEndpointServiceDataSourceConfig_customFilter(rName), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "acceptance_required", resourceName, "acceptance_required"), + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "availability_zones.#", resourceName, "availability_zones.#"), + resource.TestCheckResourceAttrPair(datasourceName, "base_endpoint_dns_names.#", resourceName, "base_endpoint_dns_names.#"), + resource.TestCheckResourceAttrPair(datasourceName, "manages_vpc_endpoints", resourceName, "manages_vpc_endpoints"), acctest.CheckResourceAttrAccountID(datasourceName, "owner"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_name", resourceName, "private_dns_name"), resource.TestCheckResourceAttr(datasourceName, "service_type", "Interface"), + resource.TestCheckResourceAttrPair(datasourceName, "supported_ip_address_types.#", resourceName, "supported_ip_address_types.#"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_policy_supported", "false"), - resource.TestCheckResourceAttr(datasourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(datasourceName, "tags.Name", rName), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), ), }, }, @@ -122,8 +131,9 @@ func TestAccVPCEndpointServiceDataSource_Custom_filter(t *testing.T) { } func TestAccVPCEndpointServiceDataSource_CustomFilter_tags(t *testing.T) { + resourceName := "aws_vpc_endpoint_service.test" datasourceName := "data.aws_vpc_endpoint_service.test" - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -131,17 +141,19 @@ func TestAccVPCEndpointServiceDataSource_CustomFilter_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceCustomFilterTagsDataSourceConfig(rName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(datasourceName, "acceptance_required", "true"), - resource.TestCheckResourceAttr(datasourceName, "availability_zones.#", "2"), - resource.TestCheckResourceAttr(datasourceName, "manages_vpc_endpoints", "false"), + Config: testAccVPCEndpointServiceDataSourceConfig_customFilterTags(rName), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "acceptance_required", resourceName, "acceptance_required"), + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "availability_zones.#", resourceName, "availability_zones.#"), + resource.TestCheckResourceAttrPair(datasourceName, "base_endpoint_dns_names.#", resourceName, "base_endpoint_dns_names.#"), + resource.TestCheckResourceAttrPair(datasourceName, "manages_vpc_endpoints", resourceName, "manages_vpc_endpoints"), acctest.CheckResourceAttrAccountID(datasourceName, "owner"), + resource.TestCheckResourceAttrPair(datasourceName, "private_dns_name", resourceName, "private_dns_name"), resource.TestCheckResourceAttr(datasourceName, "service_type", "Interface"), + resource.TestCheckResourceAttrPair(datasourceName, "supported_ip_address_types.#", resourceName, "supported_ip_address_types.#"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), resource.TestCheckResourceAttr(datasourceName, "vpc_endpoint_policy_supported", "false"), - resource.TestCheckResourceAttr(datasourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(datasourceName, "tags.Name", rName), - acctest.MatchResourceAttrRegionalARN(datasourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), ), }, }, @@ -157,7 +169,7 @@ func TestAccVPCEndpointServiceDataSource_ServiceType_gateway(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceDataSourceConfig_ServiceType("s3", "Gateway"), + Config: testAccVPCEndpointServiceDataSourceConfig_type("s3", "Gateway"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceAttrRegionalReverseDNSService(datasourceName, "service_name", "s3"), resource.TestCheckResourceAttr(datasourceName, "service_type", "Gateway"), @@ -176,7 +188,7 @@ func TestAccVPCEndpointServiceDataSource_ServiceType_interface(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceDataSourceConfig_ServiceType("ec2", "Interface"), + Config: testAccVPCEndpointServiceDataSourceConfig_type("ec2", "Interface"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceAttrRegionalReverseDNSService(datasourceName, "service_name", "ec2"), resource.TestCheckResourceAttr(datasourceName, "service_type", "Interface"), @@ -197,21 +209,19 @@ func testAccCheckResourceAttrRegionalReverseDNSService(resourceName, attributeNa } } -const testAccVPCEndpointServiceGatewayDataSourceConfig = ` -data "aws_availability_zones" "available" {} - +const testAccVPCEndpointServiceDataSourceConfig_gateway = ` data "aws_vpc_endpoint_service" "test" { service = "dynamodb" } ` -const testAccVPCEndpointServiceInterfaceDataSourceConfig = ` +const testAccVPCEndpointServiceDataSourceConfig_interface = ` data "aws_vpc_endpoint_service" "test" { service = "ec2" } ` -func testAccVPCEndpointServiceDataSourceConfig_ServiceType(service string, serviceType string) string { +func testAccVPCEndpointServiceDataSourceConfig_type(service string, serviceType string) string { return fmt.Sprintf(` data "aws_vpc_endpoint_service" "test" { service = %[1]q @@ -220,102 +230,44 @@ data "aws_vpc_endpoint_service" "test" { `, service, serviceType) } -func testAccVPCEndpointServiceCustomBaseDataSourceConfig(rName string) string { - return fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.0.0.0/16" - - tags = { - Name = %[1]q - } -} - -resource "aws_lb" "test" { - name = %[1]q - - subnets = [ - aws_subnet.test1.id, - aws_subnet.test2.id, - ] - - load_balancer_type = "network" - internal = true - idle_timeout = 60 - enable_deletion_protection = false - - tags = { - Name = %[1]q - } -} - -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - -resource "aws_subnet" "test1" { - vpc_id = aws_vpc.test.id - cidr_block = "10.0.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] - - tags = { - Name = %[1]q - } -} - -resource "aws_subnet" "test2" { - vpc_id = aws_vpc.test.id - cidr_block = "10.0.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] - - tags = { - Name = %[1]q - } -} - +func testAccVPCEndpointServiceDataSourceConfig_customBase(rName string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_networkLoadBalancerBase(rName, 1), fmt.Sprintf(` resource "aws_vpc_endpoint_service" "test" { - acceptance_required = true - - network_load_balancer_arns = [ - aws_lb.test.id, - ] + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn tags = { Name = %[1]q } } -`, rName) +`, rName)) } -func testAccVPCEndpointServiceCustomDataSourceConfig(rName string) string { - return testAccVPCEndpointServiceCustomBaseDataSourceConfig(rName) + ` +func testAccVPCEndpointServiceDataSourceConfig_custom(rName string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceDataSourceConfig_customBase(rName), ` data "aws_vpc_endpoint_service" "test" { service_name = aws_vpc_endpoint_service.test.service_name } -` +`) } -func testAccVPCEndpointServiceCustomFilterDataSourceConfig(rName string) string { - return testAccVPCEndpointServiceCustomBaseDataSourceConfig(rName) + ` +func testAccVPCEndpointServiceDataSourceConfig_customFilter(rName string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceDataSourceConfig_customBase(rName), ` data "aws_vpc_endpoint_service" "test" { filter { name = "service-name" values = [aws_vpc_endpoint_service.test.service_name] } } -` +`) } -func testAccVPCEndpointServiceCustomFilterTagsDataSourceConfig(rName string) string { - return testAccVPCEndpointServiceCustomBaseDataSourceConfig(rName) + ` +func testAccVPCEndpointServiceDataSourceConfig_customFilterTags(rName string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceDataSourceConfig_customBase(rName), ` data "aws_vpc_endpoint_service" "test" { tags = { Name = aws_vpc_endpoint_service.test.tags["Name"] } } -` +`) } diff --git a/internal/service/ec2/vpc_endpoint_service_test.go b/internal/service/ec2/vpc_endpoint_service_test.go index ab1066a998d..d509127c98a 100644 --- a/internal/service/ec2/vpc_endpoint_service_test.go +++ b/internal/service/ec2/vpc_endpoint_service_test.go @@ -5,22 +5,20 @@ import ( "regexp" "testing" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func TestAccVPCEndpointService_basic(t *testing.T) { var svcCfg ec2.ServiceConfiguration resourceName := "aws_vpc_endpoint_service.test" - rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -29,16 +27,24 @@ func TestAccVPCEndpointService_basic(t *testing.T) { CheckDestroy: testAccCheckVPCEndpointServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceConfig_networkLoadBalancerARNs(rName1, rName2), - Check: resource.ComposeTestCheckFunc( + Config: testAccVPCEndpointServiceConfig_basic(rName), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), resource.TestCheckResourceAttr(resourceName, "acceptance_required", "false"), - resource.TestCheckResourceAttr(resourceName, "network_load_balancer_arns.#", "1"), resource.TestCheckResourceAttr(resourceName, "allowed_principals.#", "0"), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), + acctest.CheckResourceAttrGreaterThanValue(resourceName, "availability_zones.#", "0"), + acctest.CheckResourceAttrGreaterThanValue(resourceName, "base_endpoint_dns_names.#", "0"), + resource.TestCheckResourceAttr(resourceName, "gateway_load_balancer_arns.#", "0"), resource.TestCheckResourceAttr(resourceName, "manages_vpc_endpoints", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "network_load_balancer_arns.#", "1"), + resource.TestCheckResourceAttr(resourceName, "private_dns_name", ""), resource.TestCheckResourceAttr(resourceName, "private_dns_name_configuration.#", "0"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), + resource.TestCheckResourceAttrSet(resourceName, "service_name"), + resource.TestCheckResourceAttr(resourceName, "service_type", "Interface"), + resource.TestCheckResourceAttr(resourceName, "supported_ip_address_types.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "supported_ip_address_types.*", "ipv4"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -50,11 +56,10 @@ func TestAccVPCEndpointService_basic(t *testing.T) { }) } -func TestAccVPCEndpointService_allowedPrincipals(t *testing.T) { +func TestAccVPCEndpointService_disappears(t *testing.T) { var svcCfg ec2.ServiceConfiguration resourceName := "aws_vpc_endpoint_service.test" - rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -63,16 +68,34 @@ func TestAccVPCEndpointService_allowedPrincipals(t *testing.T) { CheckDestroy: testAccCheckVPCEndpointServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceConfig_allowedPrincipals(rName1, rName2), + Config: testAccVPCEndpointServiceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), + acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPCEndpointService(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccVPCEndpointService_tags(t *testing.T) { + var svcCfg ec2.ServiceConfiguration + resourceName := "aws_vpc_endpoint_service.test" + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckVPCEndpointServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCEndpointServiceConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - resource.TestCheckResourceAttr(resourceName, "acceptance_required", "false"), - resource.TestCheckResourceAttr(resourceName, "network_load_balancer_arns.#", "1"), - resource.TestCheckResourceAttr(resourceName, "allowed_principals.#", "1"), - resource.TestCheckResourceAttr(resourceName, "manages_vpc_endpoints", "false"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", rName1), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { @@ -81,25 +104,30 @@ func TestAccVPCEndpointService_allowedPrincipals(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPCEndpointServiceConfig_allowedPrincipalsUpdated(rName1, rName2), + Config: testAccVPCEndpointServiceConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccVPCEndpointServiceConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - resource.TestCheckResourceAttr(resourceName, "acceptance_required", "true"), - resource.TestCheckResourceAttr(resourceName, "network_load_balancer_arns.#", "2"), - resource.TestCheckResourceAttr(resourceName, "allowed_principals.#", "0"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", rName1), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, }, }) } -func TestAccVPCEndpointService_disappears(t *testing.T) { +func TestAccVPCEndpointService_networkLoadBalancerARNs(t *testing.T) { var svcCfg ec2.ServiceConfiguration resourceName := "aws_vpc_endpoint_service.test" - rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -108,33 +136,45 @@ func TestAccVPCEndpointService_disappears(t *testing.T) { CheckDestroy: testAccCheckVPCEndpointServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceConfig_networkLoadBalancerARNs(rName1, rName2), + Config: testAccVPCEndpointServiceConfig_networkLoadBalancerARNs(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPCEndpointService(), resourceName), + resource.TestCheckResourceAttr(resourceName, "network_load_balancer_arns.#", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccVPCEndpointServiceConfig_networkLoadBalancerARNs(rName, 2), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), + resource.TestCheckResourceAttr(resourceName, "network_load_balancer_arns.#", "2"), ), - ExpectNonEmptyPlan: true, }, }, }) } -func TestAccVPCEndpointService_gatewayLoadBalancerARNs(t *testing.T) { +func TestAccVPCEndpointService_supportedIPAddressTypes(t *testing.T) { var svcCfg ec2.ServiceConfiguration resourceName := "aws_vpc_endpoint_service.test" rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckELBv2GatewayLoadBalancer(t) }, + PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckVPCEndpointServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceConfig_gatewayLoadBalancerARNs(rName, 1), + Config: testAccVPCEndpointServiceConfig_supportedIPAddressTypesIPv4(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - resource.TestCheckResourceAttr(resourceName, "gateway_load_balancer_arns.#", "1"), + resource.TestCheckResourceAttr(resourceName, "supported_ip_address_types.#", "1"), + resource.TestCheckTypeSetElemAttr(resourceName, "supported_ip_address_types.*", "ipv4"), ), }, { @@ -143,21 +183,22 @@ func TestAccVPCEndpointService_gatewayLoadBalancerARNs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPCEndpointServiceConfig_gatewayLoadBalancerARNs(rName, 2), + Config: testAccVPCEndpointServiceConfig_supportedIPAddressTypesIPv4AndIPv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - resource.TestCheckResourceAttr(resourceName, "gateway_load_balancer_arns.#", "2"), + resource.TestCheckResourceAttr(resourceName, "supported_ip_address_types.#", "2"), + resource.TestCheckTypeSetElemAttr(resourceName, "supported_ip_address_types.*", "ipv4"), + resource.TestCheckTypeSetElemAttr(resourceName, "supported_ip_address_types.*", "ipv6"), ), }, }, }) } -func TestAccVPCEndpointService_tags(t *testing.T) { +func TestAccVPCEndpointService_allowedPrincipals(t *testing.T) { var svcCfg ec2.ServiceConfiguration resourceName := "aws_vpc_endpoint_service.test" - rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -166,11 +207,10 @@ func TestAccVPCEndpointService_tags(t *testing.T) { CheckDestroy: testAccCheckVPCEndpointServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceConfig_tags1(rName1, rName2, "key1", "value1"), + Config: testAccVPCEndpointServiceConfig_allowedPrincipals(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + resource.TestCheckResourceAttr(resourceName, "allowed_principals.#", "1"), ), }, { @@ -179,31 +219,63 @@ func TestAccVPCEndpointService_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPCEndpointServiceConfig_tags2(rName1, rName2, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCEndpointServiceConfig_allowedPrincipals(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + resource.TestCheckResourceAttr(resourceName, "allowed_principals.#", "0"), ), }, { - Config: testAccVPCEndpointServiceConfig_tags1(rName1, rName2, "key2", "value2"), + Config: testAccVPCEndpointServiceConfig_allowedPrincipals(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + resource.TestCheckResourceAttr(resourceName, "allowed_principals.#", "1"), ), }, }, }) } -func TestAccVPCEndpointService_PrivateDNS_name(t *testing.T) { +func TestAccVPCEndpointService_gatewayLoadBalancerARNs(t *testing.T) { var svcCfg ec2.ServiceConfiguration resourceName := "aws_vpc_endpoint_service.test" - rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckELBv2GatewayLoadBalancer(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckVPCEndpointServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCEndpointServiceConfig_gatewayLoadBalancerARNs(rName, 1), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), + resource.TestCheckResourceAttr(resourceName, "gateway_load_balancer_arns.#", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccVPCEndpointServiceConfig_gatewayLoadBalancerARNs(rName, 2), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), + resource.TestCheckResourceAttr(resourceName, "gateway_load_balancer_arns.#", "2"), + ), + }, + }, + }) +} + +func TestAccVPCEndpointService_privateDNSName(t *testing.T) { + var svcCfg ec2.ServiceConfiguration + resourceName := "aws_vpc_endpoint_service.test" + rName := sdkacctest.RandomWithPrefix("tfacctest") // 32 character limit + domainName1 := acctest.RandomSubdomain() + domainName2 := acctest.RandomSubdomain() resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -212,10 +284,10 @@ func TestAccVPCEndpointService_PrivateDNS_name(t *testing.T) { CheckDestroy: testAccCheckVPCEndpointServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointServiceConfig_privateDNSName(rName1, rName2, "example.com"), + Config: testAccVPCEndpointServiceConfig_privateDNSName(rName, domainName1), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - resource.TestCheckResourceAttr(resourceName, "private_dns_name", "example.com"), + resource.TestCheckResourceAttr(resourceName, "private_dns_name", domainName1), resource.TestCheckResourceAttr(resourceName, "private_dns_name_configuration.#", "1"), resource.TestCheckResourceAttr(resourceName, "private_dns_name_configuration.0.type", "TXT"), ), @@ -226,10 +298,10 @@ func TestAccVPCEndpointService_PrivateDNS_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPCEndpointServiceConfig_privateDNSName(rName1, rName2, "changed.example.com"), + Config: testAccVPCEndpointServiceConfig_privateDNSName(rName, domainName2), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointServiceExists(resourceName, &svcCfg), - resource.TestCheckResourceAttr(resourceName, "private_dns_name", "changed.example.com"), + resource.TestCheckResourceAttr(resourceName, "private_dns_name", domainName2), resource.TestCheckResourceAttr(resourceName, "private_dns_name_configuration.#", "1"), resource.TestCheckResourceAttr(resourceName, "private_dns_name_configuration.0.type", "TXT"), ), @@ -246,27 +318,23 @@ func testAccCheckVPCEndpointServiceDestroy(s *terraform.State) error { continue } - resp, err := conn.DescribeVpcEndpointServiceConfigurations(&ec2.DescribeVpcEndpointServiceConfigurationsInput{ - ServiceIds: []*string{aws.String(rs.Primary.ID)}, - }) + _, err := tfec2.FindVPCEndpointServiceConfigurationByID(conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + if err != nil { - // Verify the error is what we want - if tfawserr.ErrCodeEquals(err, "InvalidVpcEndpointServiceId.NotFound") { - continue - } return err } - if len(resp.ServiceConfigurations) > 0 { - return fmt.Errorf("VPC Endpoint Services still exist.") - } - return err + return fmt.Errorf("EC2 VPC Endpoint Service %s still exists", rs.Primary.ID) } return nil } -func testAccCheckVPCEndpointServiceExists(n string, svcCfg *ec2.ServiceConfiguration) resource.TestCheckFunc { +func testAccCheckVPCEndpointServiceExists(n string, v *ec2.ServiceConfiguration) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -274,29 +342,25 @@ func testAccCheckVPCEndpointServiceExists(n string, svcCfg *ec2.ServiceConfigura } if rs.Primary.ID == "" { - return fmt.Errorf("No VPC Endpoint Service ID is set") + return fmt.Errorf("No EC2 VPC Endpoint Service ID is set") } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - resp, err := conn.DescribeVpcEndpointServiceConfigurations(&ec2.DescribeVpcEndpointServiceConfigurationsInput{ - ServiceIds: []*string{aws.String(rs.Primary.ID)}, - }) + output, err := tfec2.FindVPCEndpointServiceConfigurationByID(conn, rs.Primary.ID) + if err != nil { return err } - if len(resp.ServiceConfigurations) == 0 { - return fmt.Errorf("VPC Endpoint Service not found") - } - *svcCfg = *resp.ServiceConfigurations[0] + *v = *output return nil } } -func testAccVPCEndpointServiceConfig_base(rName1, rName2 string) string { - return fmt.Sprintf(` +func testAccVPCEndpointServiceConfig_networkLoadBalancerBase(rName string, count int) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -305,84 +369,96 @@ resource "aws_vpc" "test" { } } -resource "aws_lb" "test1" { - name = %[1]q - - subnets = [ - aws_subnet.test1.id, - aws_subnet.test2.id, - ] +resource "aws_subnet" "test" { + count = 2 - load_balancer_type = "network" - internal = true - idle_timeout = 60 - enable_deletion_protection = false + vpc_id = aws_vpc.test.id + cidr_block = cidrsubnet(aws_vpc.test.cidr_block, 8, count.index) + availability_zone = data.aws_availability_zones.available.names[count.index] tags = { Name = %[1]q } } -resource "aws_lb" "test2" { - name = %[2]q +resource "aws_lb" "test" { + count = %[2]d + + load_balancer_type = "network" + name = "%[1]s-${count.index}" - subnets = [ - aws_subnet.test1.id, - aws_subnet.test2.id, - ] + subnets = aws_subnet.test[*].id - load_balancer_type = "network" internal = true idle_timeout = 60 enable_deletion_protection = false tags = { - Name = %[2]q + Name = %[1]q } } +`, rName, count)) +} -data "aws_availability_zones" "available" { - state = "available" +func testAccVPCEndpointServiceConfig_supportedIPAddressTypesBase(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + assign_generated_ipv6_cidr_block = true - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] + tags = { + Name = %[1]q } } -resource "aws_subnet" "test1" { +resource "aws_subnet" "test" { + count = 2 + vpc_id = aws_vpc.test.id - cidr_block = "10.0.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] + cidr_block = cidrsubnet(aws_vpc.test.cidr_block, 8, count.index) + availability_zone = data.aws_availability_zones.available.names[count.index] + ipv6_cidr_block = cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, count.index) tags = { Name = %[1]q } } -resource "aws_subnet" "test2" { - vpc_id = aws_vpc.test.id - cidr_block = "10.0.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] +resource "aws_lb" "test" { + load_balancer_type = "network" + name = %[1]q + + subnets = aws_subnet.test[*].id + + internal = true + idle_timeout = 60 + enable_deletion_protection = false + + ip_address_type = "dualstack" tags = { Name = %[1]q } } +`, rName)) +} -data "aws_caller_identity" "current" {} -`, rName1, rName2) +func testAccVPCEndpointServiceConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_networkLoadBalancerBase(rName, 1), ` +resource "aws_vpc_endpoint_service" "test" { + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn +} +`) } func testAccVPCEndpointServiceConfig_gatewayLoadBalancerARNs(rName string, count int) string { - return acctest.ConfigCompose( - acctest.ConfigAvailableAZsNoOptIn(), - fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.10.0/25" tags = { - Name = "tf-acc-test-load-balancer" + Name = %[1]q } } @@ -392,7 +468,7 @@ resource "aws_subnet" "test" { vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-test-load-balancer" + Name = %[1]q } } @@ -410,77 +486,81 @@ resource "aws_lb" "test" { resource "aws_vpc_endpoint_service" "test" { acceptance_required = false gateway_load_balancer_arns = aws_lb.test[*].arn + + tags = { + Name = %[1]q + } } `, rName, count)) } -func testAccVPCEndpointServiceConfig_networkLoadBalancerARNs(rName1, rName2 string) string { - return acctest.ConfigCompose( - testAccVPCEndpointServiceConfig_base(rName1, rName2), - ` +func testAccVPCEndpointServiceConfig_networkLoadBalancerARNs(rName string, count int) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_networkLoadBalancerBase(rName, count), fmt.Sprintf(` resource "aws_vpc_endpoint_service" "test" { - acceptance_required = false + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn - network_load_balancer_arns = [ - aws_lb.test1.arn, - ] + tags = { + Name = %[1]q + } } -`) +`, rName)) } -func testAccVPCEndpointServiceConfig_allowedPrincipals(rName1, rName2 string) string { - return acctest.ConfigCompose( - testAccVPCEndpointServiceConfig_base(rName1, rName2), - fmt.Sprintf(` +func testAccVPCEndpointServiceConfig_supportedIPAddressTypesIPv4(rName string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_supportedIPAddressTypesBase(rName), fmt.Sprintf(` resource "aws_vpc_endpoint_service" "test" { - acceptance_required = false + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn + supported_ip_address_types = ["ipv4"] - network_load_balancer_arns = [ - aws_lb.test1.arn, - ] + tags = { + Name = %[1]q + } +} +`, rName)) +} - allowed_principals = [ - data.aws_caller_identity.current.arn, - ] +func testAccVPCEndpointServiceConfig_supportedIPAddressTypesIPv4AndIPv6(rName string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_supportedIPAddressTypesBase(rName), fmt.Sprintf(` +resource "aws_vpc_endpoint_service" "test" { + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn + supported_ip_address_types = ["ipv4", "ipv6"] tags = { Name = %[1]q } } -`, rName1)) +`, rName)) } -func testAccVPCEndpointServiceConfig_allowedPrincipalsUpdated(rName1, rName2 string) string { - return acctest.ConfigCompose( - testAccVPCEndpointServiceConfig_base(rName1, rName2), - fmt.Sprintf(` -resource "aws_vpc_endpoint_service" "test" { - acceptance_required = true +func testAccVPCEndpointServiceConfig_allowedPrincipals(rName string, count int) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_networkLoadBalancerBase(rName, 1), fmt.Sprintf(` +data "aws_caller_identity" "current" {} + +data "aws_iam_session_context" "current" { + arn = data.aws_caller_identity.current.arn +} - network_load_balancer_arns = [ - aws_lb.test1.arn, - aws_lb.test2.arn, - ] +resource "aws_vpc_endpoint_service" "test" { + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn - allowed_principals = [] + allowed_principals = (%[2]d == 0 ? [] : [data.aws_iam_session_context.current.issuer_arn]) tags = { Name = %[1]q } } -`, rName1)) +`, rName, count)) } -func testAccVPCEndpointServiceConfig_tags1(rName1, rName2, tagKey1, tagValue1 string) string { - return acctest.ConfigCompose( - testAccVPCEndpointServiceConfig_base(rName1, rName2), - fmt.Sprintf(` +func testAccVPCEndpointServiceConfig_tags1(rName, tagKey1, tagValue1 string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_networkLoadBalancerBase(rName, 1), fmt.Sprintf(` resource "aws_vpc_endpoint_service" "test" { - acceptance_required = false - - network_load_balancer_arns = [ - aws_lb.test1.arn, - ] + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn tags = { %[1]q = %[2]q @@ -489,16 +569,11 @@ resource "aws_vpc_endpoint_service" "test" { `, tagKey1, tagValue1)) } -func testAccVPCEndpointServiceConfig_tags2(rName1, rName2, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return acctest.ConfigCompose( - testAccVPCEndpointServiceConfig_base(rName1, rName2), - fmt.Sprintf(` +func testAccVPCEndpointServiceConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_networkLoadBalancerBase(rName, 1), fmt.Sprintf(` resource "aws_vpc_endpoint_service" "test" { - acceptance_required = false - - network_load_balancer_arns = [ - aws_lb.test1.arn, - ] + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn tags = { %[1]q = %[2]q @@ -508,17 +583,16 @@ resource "aws_vpc_endpoint_service" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccVPCEndpointServiceConfig_privateDNSName(rName1, rName2, dnsName string) string { - return acctest.ConfigCompose( - testAccVPCEndpointServiceConfig_base(rName1, rName2), - fmt.Sprintf(` +func testAccVPCEndpointServiceConfig_privateDNSName(rName, dnsName string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_networkLoadBalancerBase(rName, 1), fmt.Sprintf(` resource "aws_vpc_endpoint_service" "test" { - acceptance_required = false - private_dns_name = "%s" + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn + private_dns_name = %[2]q - network_load_balancer_arns = [ - aws_lb.test1.arn, - ] + tags = { + Name = %[1]q + } } -`, dnsName)) +`, rName, dnsName)) } diff --git a/internal/service/ec2/vpc_endpoint_subnet_association.go b/internal/service/ec2/vpc_endpoint_subnet_association.go index 793eea6ef27..f28e4631310 100644 --- a/internal/service/ec2/vpc_endpoint_subnet_association.go +++ b/internal/service/ec2/vpc_endpoint_subnet_association.go @@ -131,7 +131,7 @@ func resourceVPCEndpointSubnetAssociationDelete(d *schema.ResourceData, meta int log.Printf("[DEBUG] Deleting VPC Endpoint Subnet Association: %s", id) _, err := conn.ModifyVpcEndpoint(input) - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIDNotFound) || tfawserr.ErrCodeEquals(err, errCodeInvalidSubnetIdNotFound) || tfawserr.ErrCodeEquals(err, errCodeInvalidParameter) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIdNotFound) || tfawserr.ErrCodeEquals(err, errCodeInvalidSubnetIdNotFound) || tfawserr.ErrCodeEquals(err, errCodeInvalidParameter) { return nil } diff --git a/internal/service/ec2/vpc_endpoint_test.go b/internal/service/ec2/vpc_endpoint_test.go index c87596225b7..abd3cc5c21b 100644 --- a/internal/service/ec2/vpc_endpoint_test.go +++ b/internal/service/ec2/vpc_endpoint_test.go @@ -3,8 +3,6 @@ package ec2_test import ( "fmt" "regexp" - "strconv" - "strings" "testing" "github.com/aws/aws-sdk-go/service/ec2" @@ -30,19 +28,118 @@ func TestAccVPCEndpoint_gatewayBasic(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCEndpointConfig_gatewayBasic(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVPCEndpointExists(resourceName, &endpoint), - testAccCheckVPCEndpointPrefixListAvailable(resourceName), - resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Gateway"), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + acctest.CheckResourceAttrGreaterThanValue(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "dns_entry.#", "0"), + resource.TestCheckResourceAttr(resourceName, "dns_options.#", "0"), + resource.TestCheckResourceAttr(resourceName, "ip_address_type", ""), + resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), + acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttrSet(resourceName, "policy"), + resource.TestCheckResourceAttrSet(resourceName, "prefix_list_id"), + resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), + resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "0"), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Gateway"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccVPCEndpoint_interfaceBasic(t *testing.T) { + var endpoint ec2.VpcEndpoint + resourceName := "aws_vpc_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckVPCEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCEndpointConfig_interfaceBasic(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckVPCEndpointExists(resourceName, &endpoint), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "dns_entry.#", "0"), + resource.TestCheckResourceAttr(resourceName, "dns_options.#", "1"), + resource.TestCheckResourceAttr(resourceName, "dns_options.0.dns_record_ip_type", "ipv4"), + resource.TestCheckResourceAttr(resourceName, "ip_address_type", "ipv4"), resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "0"), + acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttrSet(resourceName, "policy"), + resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), + resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), + resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), // Default SG. + resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Interface"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccVPCEndpoint_disappears(t *testing.T) { + var endpoint ec2.VpcEndpoint + resourceName := "aws_vpc_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckVPCEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCEndpointConfig_gatewayBasic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointExists(resourceName, &endpoint), + acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPCEndpoint(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccVPCEndpoint_tags(t *testing.T) { + var endpoint ec2.VpcEndpoint + resourceName := "aws_vpc_endpoint.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckVPCEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCEndpointConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointExists(resourceName, &endpoint), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { @@ -50,15 +147,30 @@ func TestAccVPCEndpoint_gatewayBasic(t *testing.T) { ImportState: true, ImportStateVerify: true, }, + { + Config: testAccVPCEndpointConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointExists(resourceName, &endpoint), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccVPCEndpointConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointExists(resourceName, &endpoint), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, }, }) } func TestAccVPCEndpoint_gatewayWithRouteTableAndPolicy(t *testing.T) { var endpoint ec2.VpcEndpoint - var routeTable ec2.RouteTable resourceName := "aws_vpc_endpoint.test" - routeTableResourceName := "aws_route_table.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ @@ -68,41 +180,19 @@ func TestAccVPCEndpoint_gatewayWithRouteTableAndPolicy(t *testing.T) { CheckDestroy: testAccCheckVPCEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointConfig_gatewayWithRouteTableAndPolicy(rName), + Config: testAccVPCEndpointConfig_gatewayRouteTableAndPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointExists(resourceName, &endpoint), - testAccCheckRouteTableExists(routeTableResourceName, &routeTable), - testAccCheckVPCEndpointPrefixListAvailable(resourceName), - resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Gateway"), + resource.TestCheckResourceAttrSet(resourceName, "policy"), resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "1"), - resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { - Config: testAccVPCEndpointConfig_gatewayWithRouteTableAndPolicyModified(rName), + Config: testAccVPCEndpointConfig_gatewayRouteTableAndPolicyModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointExists(resourceName, &endpoint), - testAccCheckRouteTableExists(routeTableResourceName, &routeTable), - testAccCheckVPCEndpointPrefixListAvailable(resourceName), - resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Gateway"), + resource.TestCheckResourceAttrSet(resourceName, "policy"), resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { @@ -207,7 +297,7 @@ func TestAccVPCEndpoint_ignoreEquivalent(t *testing.T) { }) } -func TestAccVPCEndpoint_interfaceBasic(t *testing.T) { +func TestAccVPCEndpoint_ipAddressType(t *testing.T) { var endpoint ec2.VpcEndpoint resourceName := "aws_vpc_endpoint.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -219,27 +309,28 @@ func TestAccVPCEndpoint_interfaceBasic(t *testing.T) { CheckDestroy: testAccCheckVPCEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointConfig_interfaceBasic(rName), + Config: testAccVPCEndpointConfig_ipAddressType(rName, "ipv4"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointExists(resourceName, &endpoint), - resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), - resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Interface"), - resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), - resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + resource.TestCheckResourceAttr(resourceName, "dns_options.#", "1"), + resource.TestCheckResourceAttr(resourceName, "dns_options.0.dns_record_ip_type", "ipv4"), + resource.TestCheckResourceAttr(resourceName, "ip_address_type", "ipv4"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"auto_accept"}, + }, + { + Config: testAccVPCEndpointConfig_ipAddressType(rName, "dualstack"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVPCEndpointExists(resourceName, &endpoint), + resource.TestCheckResourceAttr(resourceName, "dns_options.#", "1"), + resource.TestCheckResourceAttr(resourceName, "dns_options.0.dns_record_ip_type", "dualstack"), + resource.TestCheckResourceAttr(resourceName, "ip_address_type", "dualstack"), + ), }, }, }) @@ -257,41 +348,21 @@ func TestAccVPCEndpoint_interfaceWithSubnetAndSecurityGroup(t *testing.T) { CheckDestroy: testAccCheckVPCEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCEndpointConfig_interfaceWithSubnet(rName), + Config: testAccVPCEndpointConfig_interfaceSubnet(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointExists(resourceName, &endpoint), - resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), - resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Interface"), - resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "1"), resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "1"), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "2"), - resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "1"), ), }, { - Config: testAccVPCEndpointConfig_interfaceWithSubnetModified(rName), + Config: testAccVPCEndpointConfig_interfaceSubnetModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointExists(resourceName, &endpoint), - resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), - resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Interface"), - resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "3"), resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "1"), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), - resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "3"), ), }, { @@ -318,20 +389,7 @@ func TestAccVPCEndpoint_interfaceNonAWSServiceAcceptOnCreate(t *testing.T) { // Config: testAccVPCEndpointConfig_interfaceNonAWSService(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointExists(resourceName, &endpoint), - resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), - resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Interface"), - resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), - resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), resource.TestCheckResourceAttr(resourceName, "state", "available"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { @@ -359,40 +417,14 @@ func TestAccVPCEndpoint_interfaceNonAWSServiceAcceptOnUpdate(t *testing.T) { // Config: testAccVPCEndpointConfig_interfaceNonAWSService(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointExists(resourceName, &endpoint), - resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), - resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Interface"), - resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), - resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), resource.TestCheckResourceAttr(resourceName, "state", "pendingAcceptance"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { Config: testAccVPCEndpointConfig_interfaceNonAWSService(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckVPCEndpointExists(resourceName, &endpoint), - resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), - resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Interface"), - resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), - resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), resource.TestCheckResourceAttr(resourceName, "state", "available"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), - acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { @@ -405,74 +437,6 @@ func TestAccVPCEndpoint_interfaceNonAWSServiceAcceptOnUpdate(t *testing.T) { // }) } -func TestAccVPCEndpoint_disappears(t *testing.T) { - var endpoint ec2.VpcEndpoint - resourceName := "aws_vpc_endpoint.test" - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckVPCEndpointDestroy, - Steps: []resource.TestStep{ - { - Config: testAccVPCEndpointConfig_gatewayBasic(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckVPCEndpointExists(resourceName, &endpoint), - acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPCEndpoint(), resourceName), - ), - ExpectNonEmptyPlan: true, - }, - }, - }) -} - -func TestAccVPCEndpoint_tags(t *testing.T) { - var endpoint ec2.VpcEndpoint - resourceName := "aws_vpc_endpoint.test" - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckVPCEndpointDestroy, - Steps: []resource.TestStep{ - { - Config: testAccVPCEndpointConfig_tags1(rName, "key1", "value1"), - Check: resource.ComposeTestCheckFunc( - testAccCheckVPCEndpointExists(resourceName, &endpoint), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccVPCEndpointConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), - Check: resource.ComposeTestCheckFunc( - testAccCheckVPCEndpointExists(resourceName, &endpoint), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), - ), - }, - { - Config: testAccVPCEndpointConfig_tags1(rName, "key2", "value2"), - Check: resource.ComposeTestCheckFunc( - testAccCheckVPCEndpointExists(resourceName, &endpoint), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), - ), - }, - }, - }) -} - func TestAccVPCEndpoint_VPCEndpointType_gatewayLoadBalancer(t *testing.T) { var endpoint ec2.VpcEndpoint vpcEndpointServiceResourceName := "aws_vpc_endpoint_service.test" @@ -523,7 +487,7 @@ func testAccCheckVPCEndpointDestroy(s *terraform.State) error { return nil } -func testAccCheckVPCEndpointExists(n string, endpoint *ec2.VpcEndpoint) resource.TestCheckFunc { +func testAccCheckVPCEndpointExists(n string, v *ec2.VpcEndpoint) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -531,49 +495,18 @@ func testAccCheckVPCEndpointExists(n string, endpoint *ec2.VpcEndpoint) resource } if rs.Primary.ID == "" { - return fmt.Errorf("No VPC Endpoint ID is set") + return fmt.Errorf("No EC2 VPC Endpoint ID is set") } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - out, err := tfec2.FindVPCEndpointByID(conn, rs.Primary.ID) + output, err := tfec2.FindVPCEndpointByID(conn, rs.Primary.ID) if err != nil { return err } - *endpoint = *out - - return nil - } -} - -func testAccCheckVPCEndpointPrefixListAvailable(n string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - prefixListID := rs.Primary.Attributes["prefix_list_id"] - if prefixListID == "" { - return fmt.Errorf("Prefix list ID not available") - } - if !strings.HasPrefix(prefixListID, "pl") { - return fmt.Errorf("Prefix list ID does not appear to be a valid value: '%s'", prefixListID) - } - - var ( - cidrBlockSize int - err error - ) - - if cidrBlockSize, err = strconv.Atoi(rs.Primary.Attributes["cidr_blocks.#"]); err != nil { - return err - } - if cidrBlockSize < 1 { - return fmt.Errorf("cidr_blocks seem suspiciously low: %d", cidrBlockSize) - } + *v = *output return nil } @@ -598,7 +531,7 @@ resource "aws_vpc_endpoint" "test" { `, rName) } -func testAccVPCEndpointConfig_gatewayWithRouteTableAndPolicy(rName string) string { +func testAccVPCEndpointConfig_gatewayRouteTableAndPolicy(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -664,7 +597,7 @@ resource "aws_route_table_association" "test" { `, rName) } -func testAccVPCEndpointConfig_gatewayWithRouteTableAndPolicyModified(rName string) string { +func testAccVPCEndpointConfig_gatewayRouteTableAndPolicyModified(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -746,6 +679,33 @@ resource "aws_vpc_endpoint" "test" { `, rName) } +func testAccVPCEndpointConfig_ipAddressType(rName, addressType string) string { + return acctest.ConfigCompose(testAccVPCEndpointServiceConfig_supportedIPAddressTypesBase(rName), fmt.Sprintf(` +resource "aws_vpc_endpoint_service" "test" { + acceptance_required = false + network_load_balancer_arns = aws_lb.test[*].arn + supported_ip_address_types = ["ipv4", "ipv6"] + + tags = { + Name = %[1]q + } +} + +resource "aws_vpc_endpoint" "test" { + vpc_id = aws_vpc.test.id + service_name = aws_vpc_endpoint_service.test.service_name + vpc_endpoint_type = "Interface" + private_dns_enabled = false + auto_accept = true + ip_address_type = %[2]q + + dns_options { + dns_record_ip_type = %[2]q + } +} +`, rName, addressType)) +} + func testAccVPCEndpointConfig_gatewayPolicy(rName, policy string) string { return fmt.Sprintf(` data "aws_vpc_endpoint_service" "test" { @@ -812,7 +772,7 @@ resource "aws_security_group" "test" { `, rName)) } -func testAccVPCEndpointConfig_interfaceWithSubnet(rName string) string { +func testAccVPCEndpointConfig_interfaceSubnet(rName string) string { return acctest.ConfigCompose( testAccVPCEndpointConfig_vpcBase(rName), fmt.Sprintf(` @@ -838,7 +798,7 @@ resource "aws_vpc_endpoint" "test" { `, rName)) } -func testAccVPCEndpointConfig_interfaceWithSubnetModified(rName string) string { +func testAccVPCEndpointConfig_interfaceSubnetModified(rName string) string { return acctest.ConfigCompose( testAccVPCEndpointConfig_vpcBase(rName), fmt.Sprintf(` @@ -965,11 +925,13 @@ resource "aws_vpc_endpoint" "test" { } func testAccVPCEndpointConfig_gatewayLoadBalancer(rName string) string { - return acctest.ConfigCompose( - acctest.ConfigAvailableAZsNoOptIn(), - fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` data "aws_caller_identity" "current" {} +data "aws_iam_session_context" "current" { + arn = data.aws_caller_identity.current.arn +} + resource "aws_vpc" "test" { cidr_block = "10.10.10.0/25" @@ -1003,7 +965,7 @@ resource "aws_lb" "test" { resource "aws_vpc_endpoint_service" "test" { acceptance_required = false - allowed_principals = [data.aws_caller_identity.current.arn] + allowed_principals = [data.aws_iam_session_context.current.issuer_arn] gateway_load_balancer_arns = [aws_lb.test.arn] tags = { diff --git a/internal/service/ec2/vpc_flow_log_test.go b/internal/service/ec2/vpc_flow_log_test.go index 6b9980f095f..5fbf474b223 100644 --- a/internal/service/ec2/vpc_flow_log_test.go +++ b/internal/service/ec2/vpc_flow_log_test.go @@ -30,7 +30,7 @@ func TestAccVPCFlowLog_vpcID(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_VPCID(rName), + Config: testAccVPCFlowLogConfig_id(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-flow-log/fl-.+`)), @@ -49,7 +49,7 @@ func TestAccVPCFlowLog_vpcID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFlowLogConfig_LogDestinationType_CloudWatchLogs(rName), + Config: testAccVPCFlowLogConfig_destinationTypeCloudWatchLogs(rName), ExpectNonEmptyPlan: false, }, }, @@ -69,7 +69,7 @@ func TestAccVPCFlowLog_logFormat(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_LogFormat(rName), + Config: testAccVPCFlowLogConfig_format(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttr(resourceName, "log_format", logFormat), @@ -81,7 +81,7 @@ func TestAccVPCFlowLog_logFormat(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFlowLogConfig_LogDestinationType_CloudWatchLogs(rName), + Config: testAccVPCFlowLogConfig_destinationTypeCloudWatchLogs(rName), ExpectNonEmptyPlan: false, }, }, @@ -103,7 +103,7 @@ func TestAccVPCFlowLog_subnetID(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_SubnetID(rName), + Config: testAccVPCFlowLogConfig_subnetID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttrPair(resourceName, "iam_role_arn", iamRoleResourceName, "arn"), @@ -137,7 +137,7 @@ func TestAccVPCFlowLog_LogDestinationType_cloudWatchLogs(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_LogDestinationType_CloudWatchLogs(rName), + Config: testAccVPCFlowLogConfig_destinationTypeCloudWatchLogs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), // We automatically trim :* from ARNs if present @@ -168,7 +168,7 @@ func TestAccVPCFlowLog_LogDestinationType_s3(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_LogDestinationType_S3(rName), + Config: testAccVPCFlowLogConfig_destinationTypeS3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttrPair(resourceName, "log_destination", s3ResourceName, "arn"), @@ -195,7 +195,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3_invalid(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_LogDestinationType_S3_Invalid(rName), + Config: testAccVPCFlowLogConfig_destinationTypeS3Invalid(rName), ExpectError: regexp.MustCompile(`(Access Denied for LogDestination|does not exist)`), }, }, @@ -215,7 +215,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DO_plainText(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_LogDestinationType_S3_DO_PlainText(rName), + Config: testAccVPCFlowLogConfig_destinationTypeS3DOPlainText(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttrPair(resourceName, "log_destination", s3ResourceName, "arn"), @@ -246,7 +246,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DOPlainText_hiveCompatible(t *testing CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_LogDestinationType_S3_DO_PlainText_HiveCompatible_PerHour(rName), + Config: testAccVPCFlowLogConfig_destinationTypeS3DOPlainTextHiveCompatiblePerHour(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttrPair(resourceName, "log_destination", s3ResourceName, "arn"), @@ -279,7 +279,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DO_parquet(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_LogDestinationType_S3_DO_Parquet(rName), + Config: testAccVPCFlowLogConfig_destinationTypeS3DOParquet(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttrPair(resourceName, "log_destination", s3ResourceName, "arn"), @@ -310,7 +310,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DOParquet_hiveCompatible(t *testing.T CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_LogDestinationType_S3_DO_Parquet_HiveCompatible(rName), + Config: testAccVPCFlowLogConfig_destinationTypeS3DOParquetHiveCompatible(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttrPair(resourceName, "log_destination", s3ResourceName, "arn"), @@ -342,7 +342,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DOParquetHiveCompatible_perHour(t *te CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_LogDestinationType_S3_DO_Parquet_HiveCompatible_PerHour(rName), + Config: testAccVPCFlowLogConfig_destinationTypeS3DOParquetHiveCompatiblePerHour(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttrPair(resourceName, "log_destination", s3ResourceName, "arn"), @@ -374,7 +374,7 @@ func TestAccVPCFlowLog_LogDestinationType_maxAggregationInterval(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_MaxAggregationInterval(rName), + Config: testAccVPCFlowLogConfig_maxAggregationInterval(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttr(resourceName, "max_aggregation_interval", "60"), @@ -401,7 +401,7 @@ func TestAccVPCFlowLog_tags(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfigTags1(rName, "key1", "value1"), + Config: testAccVPCFlowLogConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -414,7 +414,7 @@ func TestAccVPCFlowLog_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFlowLogConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCFlowLogConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -423,7 +423,7 @@ func TestAccVPCFlowLog_tags(t *testing.T) { ), }, { - Config: testAccFlowLogConfigTags1(rName, "key2", "value2"), + Config: testAccVPCFlowLogConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -446,7 +446,7 @@ func TestAccVPCFlowLog_disappears(t *testing.T) { CheckDestroy: testAccCheckFlowLogDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowLogConfig_VPCID(rName), + Config: testAccVPCFlowLogConfig_id(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowLogExists(resourceName, &flowLog), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceFlowLog(), resourceName), @@ -518,7 +518,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccFlowLogConfig_LogDestinationType_CloudWatchLogs(rName string) string { +func testAccVPCFlowLogConfig_destinationTypeCloudWatchLogs(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` data "aws_partition" "current" {} @@ -559,7 +559,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfig_LogDestinationType_S3(rName string) string { +func testAccVPCFlowLogConfig_destinationTypeS3(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -575,7 +575,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfig_LogDestinationType_S3_Invalid(rName string) string { +func testAccVPCFlowLogConfig_destinationTypeS3Invalid(rName string) string { return testAccFlowLogConfigBase(rName) + ` data "aws_partition" "current" {} @@ -588,7 +588,7 @@ resource "aws_flow_log" "test" { ` } -func testAccFlowLogConfig_LogDestinationType_S3_DO_PlainText(rName string) string { +func testAccVPCFlowLogConfig_destinationTypeS3DOPlainText(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -607,7 +607,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfig_LogDestinationType_S3_DO_PlainText_HiveCompatible_PerHour(rName string) string { +func testAccVPCFlowLogConfig_destinationTypeS3DOPlainTextHiveCompatiblePerHour(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -628,7 +628,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfig_LogDestinationType_S3_DO_Parquet(rName string) string { +func testAccVPCFlowLogConfig_destinationTypeS3DOParquet(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -647,7 +647,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfig_LogDestinationType_S3_DO_Parquet_HiveCompatible(rName string) string { +func testAccVPCFlowLogConfig_destinationTypeS3DOParquetHiveCompatible(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -667,7 +667,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfig_LogDestinationType_S3_DO_Parquet_HiveCompatible_PerHour(rName string) string { +func testAccVPCFlowLogConfig_destinationTypeS3DOParquetHiveCompatiblePerHour(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -688,7 +688,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfig_SubnetID(rName string) string { +func testAccVPCFlowLogConfig_subnetID(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` resource "aws_subnet" "test" { cidr_block = "10.0.1.0/24" @@ -737,7 +737,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfig_VPCID(rName string) string { +func testAccVPCFlowLogConfig_id(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` data "aws_partition" "current" {} @@ -777,7 +777,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfig_LogFormat(rName string) string { +func testAccVPCFlowLogConfig_format(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` data "aws_partition" "current" {} @@ -823,7 +823,7 @@ resource "aws_flow_log" "test" { `, rName) } -func testAccFlowLogConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccVPCFlowLogConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` data "aws_partition" "current" {} @@ -867,7 +867,7 @@ resource "aws_flow_log" "test" { `, rName, tagKey1, tagValue1) } -func testAccFlowLogConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCFlowLogConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` data "aws_partition" "current" {} @@ -912,7 +912,7 @@ resource "aws_flow_log" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccFlowLogConfig_MaxAggregationInterval(rName string) string { +func testAccVPCFlowLogConfig_maxAggregationInterval(rName string) string { return testAccFlowLogConfigBase(rName) + fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/ec2/vpc_internet_gateway_attachment_test.go b/internal/service/ec2/vpc_internet_gateway_attachment_test.go index 2902ee37510..96ebeb97843 100644 --- a/internal/service/ec2/vpc_internet_gateway_attachment_test.go +++ b/internal/service/ec2/vpc_internet_gateway_attachment_test.go @@ -28,7 +28,7 @@ func TestAccVPCInternetGatewayAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckInternetGatewayAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccInternetGatewayAttachmentAttachmentConfig(rName), + Config: testAccVPCInternetGatewayAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInternetGatewayAttachmentExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "internet_gateway_id", igwResourceName, "id"), @@ -56,7 +56,7 @@ func TestAccVPCInternetGatewayAttachment_disappears(t *testing.T) { CheckDestroy: testAccCheckInternetGatewayAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccInternetGatewayAttachmentAttachmentConfig(rName), + Config: testAccVPCInternetGatewayAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInternetGatewayAttachmentExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceInternetGatewayAttachment(), resourceName), @@ -128,7 +128,7 @@ func testAccCheckInternetGatewayAttachmentExists(n string, v *ec2.InternetGatewa } } -func testAccInternetGatewayAttachmentAttachmentConfig(rName string) string { +func testAccVPCInternetGatewayAttachmentConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_internet_gateway_data_source_test.go b/internal/service/ec2/vpc_internet_gateway_data_source_test.go index 87ea53abb0a..fc61c8d9d77 100644 --- a/internal/service/ec2/vpc_internet_gateway_data_source_test.go +++ b/internal/service/ec2/vpc_internet_gateway_data_source_test.go @@ -24,7 +24,7 @@ func TestAccVPCInternetGatewayDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInternetGatewayDataSourceConfig(rName), + Config: testAccVPCInternetGatewayDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(ds1ResourceName, "internet_gateway_id", igwResourceName, "id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "owner_id", igwResourceName, "owner_id"), @@ -44,7 +44,7 @@ func TestAccVPCInternetGatewayDataSource_basic(t *testing.T) { }) } -func testAccInternetGatewayDataSourceConfig(rName string) string { +func testAccVPCInternetGatewayDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" diff --git a/internal/service/ec2/vpc_internet_gateway_test.go b/internal/service/ec2/vpc_internet_gateway_test.go index 7f3e428674d..cd22fb6c5c2 100644 --- a/internal/service/ec2/vpc_internet_gateway_test.go +++ b/internal/service/ec2/vpc_internet_gateway_test.go @@ -26,7 +26,7 @@ func TestAccVPCInternetGateway_basic(t *testing.T) { CheckDestroy: testAccCheckInternetGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccInternetGatewayBasicConfig, + Config: testAccVPCInternetGatewayConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckInternetGatewayExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`internet-gateway/igw-.+`)), @@ -55,7 +55,7 @@ func TestAccVPCInternetGateway_disappears(t *testing.T) { CheckDestroy: testAccCheckInternetGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccInternetGatewayBasicConfig, + Config: testAccVPCInternetGatewayConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckInternetGatewayExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceInternetGateway(), resourceName), @@ -80,7 +80,7 @@ func TestAccVPCInternetGateway_Attachment(t *testing.T) { CheckDestroy: testAccCheckInternetGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccInternetGatewayAttachmentConfig(rName), + Config: testAccVPCInternetGatewayConfig_attachment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInternetGatewayExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "vpc_id", vpc1ResourceName, "id"), @@ -92,7 +92,7 @@ func TestAccVPCInternetGateway_Attachment(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccInternetGatewayAttachmentUpdatedConfig(rName), + Config: testAccVPCInternetGatewayConfig_attachmentUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInternetGatewayExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "vpc_id", vpc2ResourceName, "id"), @@ -114,7 +114,7 @@ func TestAccVPCInternetGateway_Tags(t *testing.T) { CheckDestroy: testAccCheckInternetGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccInternetGatewayTags1Config(rName, "key1", "value1"), + Config: testAccVPCInternetGatewayConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckInternetGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -127,7 +127,7 @@ func TestAccVPCInternetGateway_Tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccInternetGatewayTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCInternetGatewayConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckInternetGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -136,7 +136,7 @@ func TestAccVPCInternetGateway_Tags(t *testing.T) { ), }, { - Config: testAccInternetGatewayTags1Config(rName, "key2", "value2"), + Config: testAccVPCInternetGatewayConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckInternetGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -196,11 +196,11 @@ func testAccCheckInternetGatewayExists(n string, v *ec2.InternetGateway) resourc } } -const testAccInternetGatewayBasicConfig = ` +const testAccVPCInternetGatewayConfig_basic = ` resource "aws_internet_gateway" "test" {} ` -func testAccInternetGatewayAttachmentConfig(rName string) string { +func testAccVPCInternetGatewayConfig_attachment(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "10.1.0.0/16" @@ -228,7 +228,7 @@ resource "aws_internet_gateway" "test" { `, rName) } -func testAccInternetGatewayAttachmentUpdatedConfig(rName string) string { +func testAccVPCInternetGatewayConfig_attachmentUpdated(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "10.1.0.0/16" @@ -256,7 +256,7 @@ resource "aws_internet_gateway" "test" { `, rName) } -func testAccInternetGatewayTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccVPCInternetGatewayConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_internet_gateway" "test" { tags = { @@ -266,7 +266,7 @@ resource "aws_internet_gateway" "test" { `, rName, tagKey1, tagValue1) } -func testAccInternetGatewayTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCInternetGatewayConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_internet_gateway" "test" { tags = { diff --git a/internal/service/ec2/vpc_ipv4_cidr_block_association_test.go b/internal/service/ec2/vpc_ipv4_cidr_block_association_test.go index 606c49e986a..0787efa64ca 100644 --- a/internal/service/ec2/vpc_ipv4_cidr_block_association_test.go +++ b/internal/service/ec2/vpc_ipv4_cidr_block_association_test.go @@ -29,7 +29,7 @@ func TestAccVPCIPv4CIDRBlockAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckVPCIPv4CIDRBlockAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCIPv4CIDRBlockAssociationConfig(rName), + Config: testAccVPCIPv4CIDRBlockAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCIPv4CIDRBlockAssociationExists(resource1Name, &associationSecondary), testAccCheckAdditionalVPCIPv4CIDRBlock(&associationSecondary, "172.2.0.0/16"), @@ -64,7 +64,7 @@ func TestAccVPCIPv4CIDRBlockAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckVPCIPv4CIDRBlockAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCIPv4CIDRBlockAssociationConfig(rName), + Config: testAccVPCIPv4CIDRBlockAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCIPv4CIDRBlockAssociationExists(resource1Name, &associationSecondary), testAccCheckVPCIPv4CIDRBlockAssociationExists(resource2Name, &associationTertiary), @@ -117,7 +117,7 @@ func TestAccVPCIPv4CIDRBlockAssociation_ipamBasicExplicitCIDR(t *testing.T) { CheckDestroy: testAccCheckVPCIPv4CIDRBlockAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCIPv4CIDRBlockAssociationConfig_ipamExplicitCIDR(rName, cidr), + Config: testAccVPCIPv4CIDRBlockAssociationConfig_ipamExplicit(rName, cidr), Check: resource.ComposeTestCheckFunc( testAccCheckVPCIPv4CIDRBlockAssociationExists("aws_vpc_ipv4_cidr_block_association.secondary_cidr", &associationSecondary), testAccCheckAdditionalVPCIPv4CIDRBlock(&associationSecondary, cidr)), @@ -196,7 +196,7 @@ func testAccCheckVPCIPv4CIDRBlockAssociationExists(n string, v *ec2.VpcCidrBlock } } -func testAccVPCIPv4CIDRBlockAssociationConfig(rName string) string { +func testAccVPCIPv4CIDRBlockAssociationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -238,7 +238,7 @@ resource "aws_vpc_ipv4_cidr_block_association" "secondary_cidr" { `, rName, netmaskLength)) } -func testAccVPCIPv4CIDRBlockAssociationConfig_ipamExplicitCIDR(rName, cidr string) string { +func testAccVPCIPv4CIDRBlockAssociationConfig_ipamExplicit(rName, cidr string) string { return acctest.ConfigCompose(testAccIPAMIPv4Config_base(rName), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/vpc_main_route_table_association_test.go b/internal/service/ec2/vpc_main_route_table_association_test.go index 32a62b5c335..0aa1133a053 100644 --- a/internal/service/ec2/vpc_main_route_table_association_test.go +++ b/internal/service/ec2/vpc_main_route_table_association_test.go @@ -26,13 +26,13 @@ func TestAccVPCMainRouteTableAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckMainRouteTableAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccMainRouteTableAssociationConfig(rName), + Config: testAccVPCMainRouteTableAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMainRouteTableAssociationExists(resourceName, &rta), ), }, { - Config: testAccMainRouteTableAssociationConfigUpdated(rName), + Config: testAccVPCMainRouteTableAssociationConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMainRouteTableAssociationExists(resourceName, &rta), ), @@ -119,7 +119,7 @@ resource "aws_internet_gateway" "test" { `, rName) } -func testAccMainRouteTableAssociationConfig(rName string) string { +func testAccVPCMainRouteTableAssociationConfig_basic(rName string) string { return acctest.ConfigCompose(testAccMainRouteTableAssociationConfigBaseVPC(rName), fmt.Sprintf(` resource "aws_route_table" "test" { vpc_id = aws_vpc.test.id @@ -141,7 +141,7 @@ resource "aws_main_route_table_association" "test" { `, rName)) } -func testAccMainRouteTableAssociationConfigUpdated(rName string) string { +func testAccVPCMainRouteTableAssociationConfig_updated(rName string) string { return acctest.ConfigCompose(testAccMainRouteTableAssociationConfigBaseVPC(rName), fmt.Sprintf(` # Need to keep the old route table around when we update the # main_route_table_association, otherwise Terraform will try to destroy the diff --git a/internal/service/ec2/vpc_managed_prefix_list_data_source_test.go b/internal/service/ec2/vpc_managed_prefix_list_data_source_test.go index 8e701ca1a08..7ebe61bd280 100644 --- a/internal/service/ec2/vpc_managed_prefix_list_data_source_test.go +++ b/internal/service/ec2/vpc_managed_prefix_list_data_source_test.go @@ -51,7 +51,7 @@ func TestAccVPCManagedPrefixListDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListDataSourceConfig_basic, + Config: testAccVPCManagedPrefixListDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( testAccManagedPrefixListGetIdByNameDataSource(prefixListName, &prefixListId, &prefixListArn), @@ -76,7 +76,7 @@ func TestAccVPCManagedPrefixListDataSource_basic(t *testing.T) { }) } -const testAccManagedPrefixListDataSourceConfig_basic = ` +const testAccVPCManagedPrefixListDataSourceConfig_basic = ` data "aws_region" "current" {} data "aws_ec2_managed_prefix_list" "s3_by_name" { @@ -106,7 +106,7 @@ func TestAccVPCManagedPrefixListDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListDataSourceConfig_filter, + Config: testAccVPCManagedPrefixListDataSourceConfig_filter, Check: resource.ComposeTestCheckFunc( testAccManagedPrefixListGetIdByNameDataSource(prefixListName, &prefixListId, &prefixListArn), resource.TestCheckResourceAttrPtr(resourceByName, "id", &prefixListId), @@ -133,7 +133,7 @@ func TestAccVPCManagedPrefixListDataSource_filter(t *testing.T) { }) } -const testAccManagedPrefixListDataSourceConfig_filter = ` +const testAccVPCManagedPrefixListDataSourceConfig_filter = ` data "aws_region" "current" {} data "aws_ec2_managed_prefix_list" "s3_by_name" { @@ -158,13 +158,13 @@ func TestAccVPCManagedPrefixListDataSource_matchesTooMany(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPrefixListDataSourceConfig_matchesTooMany, + Config: testAccVPCManagedPrefixListDataSourceConfig_matchesTooMany, ExpectError: regexp.MustCompile(`more than 1 prefix list matched the given criteria`), }, }, }) } -const testAccPrefixListDataSourceConfig_matchesTooMany = ` +const testAccVPCManagedPrefixListDataSourceConfig_matchesTooMany = ` data "aws_ec2_managed_prefix_list" "test" {} ` diff --git a/internal/service/ec2/vpc_managed_prefix_list_entry.go b/internal/service/ec2/vpc_managed_prefix_list_entry.go index 0f7b9391061..20f7653963b 100644 --- a/internal/service/ec2/vpc_managed_prefix_list_entry.go +++ b/internal/service/ec2/vpc_managed_prefix_list_entry.go @@ -51,34 +51,40 @@ func resourceManagedPrefixListEntryCreate(d *schema.ResourceData, meta interface plID := d.Get("prefix_list_id").(string) id := ManagedPrefixListEntryCreateID(plID, cidr) - pl, err := FindManagedPrefixListByID(conn, plID) - - if err != nil { - return fmt.Errorf("error reading EC2 Managed Prefix List (%s): %w", plID, err) - } - addPrefixListEntry := &ec2.AddPrefixListEntry{Cidr: aws.String(cidr)} if v, ok := d.GetOk("description"); ok { addPrefixListEntry.Description = aws.String(v.(string)) } - input := &ec2.ModifyManagedPrefixListInput{ - AddEntries: []*ec2.AddPrefixListEntry{addPrefixListEntry}, - CurrentVersion: pl.Version, - PrefixListId: aws.String(plID), - } + _, err := tfresource.RetryWhenAWSErrCodeEquals(d.Timeout(schema.TimeoutCreate), func() (interface{}, error) { + mutexKey := fmt.Sprintf("vpc-managed-prefix-list-%s", plID) + conns.GlobalMutexKV.Lock(mutexKey) + defer conns.GlobalMutexKV.Unlock(mutexKey) + + pl, err := FindManagedPrefixListByID(conn, plID) + + if err != nil { + return nil, fmt.Errorf("error reading VPC Managed Prefix List (%s): %w", plID, err) + } - _, err = conn.ModifyManagedPrefixList(input) + input := &ec2.ModifyManagedPrefixListInput{ + AddEntries: []*ec2.AddPrefixListEntry{addPrefixListEntry}, + CurrentVersion: pl.Version, + PrefixListId: aws.String(plID), + } + + return conn.ModifyManagedPrefixList(input) + }, "IncorrectState", "PrefixListVersionMismatch") if err != nil { - return fmt.Errorf("error creating EC2 Managed Prefix List Entry (%s): %w", id, err) + return fmt.Errorf("error creating VPC Managed Prefix List Entry (%s): %w", id, err) } d.SetId(id) if _, err := WaitManagedPrefixListModified(conn, plID); err != nil { - return fmt.Errorf("error waiting for EC2 Managed Prefix List Entry (%s) create: %w", d.Id(), err) + return fmt.Errorf("error waiting for VPC Managed Prefix List Entry (%s) create: %w", d.Id(), err) } return resourceManagedPrefixListEntryRead(d, meta) @@ -98,13 +104,13 @@ func resourceManagedPrefixListEntryRead(d *schema.ResourceData, meta interface{} }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] EC2 Managed Prefix List Entry (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] VPC Managed Prefix List Entry (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("error reading EC2 Managed Prefix List Entry (%s): %w", d.Id(), err) + return fmt.Errorf("error reading VPC Managed Prefix List Entry (%s): %w", d.Id(), err) } entry := outputRaw.(*ec2.PrefixListEntry) @@ -121,31 +127,37 @@ func resourceManagedPrefixListEntryDelete(d *schema.ResourceData, meta interface plID, cidr, err := ManagedPrefixListEntryParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("error parsing VPC Managed Prefix List Entry ID (%s): %w", d.Id(), err) } - pl, err := FindManagedPrefixListByID(conn, plID) + _, err = tfresource.RetryWhenAWSErrCodeEquals(d.Timeout(schema.TimeoutCreate), func() (interface{}, error) { + mutexKey := fmt.Sprintf("vpc-managed-prefix-list-%s", plID) + conns.GlobalMutexKV.Lock(mutexKey) + defer conns.GlobalMutexKV.Unlock(mutexKey) - if err != nil { - return fmt.Errorf("error reading EC2 Managed Prefix List (%s): %w", plID, err) - } + pl, err := FindManagedPrefixListByID(conn, plID) - input := &ec2.ModifyManagedPrefixListInput{ - CurrentVersion: pl.Version, - PrefixListId: aws.String(plID), - RemoveEntries: []*ec2.RemovePrefixListEntry{{Cidr: aws.String(cidr)}}, - } + if err != nil { + return nil, fmt.Errorf("error reading VPC Managed Prefix List (%s): %w", plID, err) + } + + input := &ec2.ModifyManagedPrefixListInput{ + CurrentVersion: pl.Version, + PrefixListId: aws.String(plID), + RemoveEntries: []*ec2.RemovePrefixListEntry{{Cidr: aws.String(cidr)}}, + } - _, err = conn.ModifyManagedPrefixList(input) + return conn.ModifyManagedPrefixList(input) + }, "IncorrectState", "PrefixListVersionMismatch") if err != nil { - return fmt.Errorf("error deleting EC2 Managed Prefix List Entry (%s): %w", d.Id(), err) + return fmt.Errorf("error deleting VPC Managed Prefix List Entry (%s): %w", d.Id(), err) } _, err = WaitManagedPrefixListModified(conn, plID) if err != nil { - return fmt.Errorf("error waiting for EC2 Managed Prefix List Entry (%s) delete: %w", d.Id(), err) + return fmt.Errorf("error waiting for VPC Managed Prefix List Entry (%s) delete: %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpc_managed_prefix_list_entry_test.go b/internal/service/ec2/vpc_managed_prefix_list_entry_test.go index 81f7bf97eea..362760956dd 100644 --- a/internal/service/ec2/vpc_managed_prefix_list_entry_test.go +++ b/internal/service/ec2/vpc_managed_prefix_list_entry_test.go @@ -28,7 +28,7 @@ func TestAccVPCManagedPrefixListEntry_ipv4(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListEntryDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListEntryIPv4Config(rName), + Config: testAccVPCManagedPrefixListEntryConfig_ipv4(rName), Check: resource.ComposeTestCheckFunc( testAccCheckManagedPrefixListEntryExists(resourceName, &entry), resource.TestCheckResourceAttrPair(resourceName, "prefix_list_id", plResourceName, "id"), @@ -46,6 +46,34 @@ func TestAccVPCManagedPrefixListEntry_ipv4(t *testing.T) { }) } +func TestAccVPCManagedPrefixListEntry_ipv4Multiple(t *testing.T) { + var entry ec2.PrefixListEntry + resourceName1 := "aws_ec2_managed_prefix_list_entry.test1" + resourceName2 := "aws_ec2_managed_prefix_list_entry.test2" + resourceName3 := "aws_ec2_managed_prefix_list_entry.test3" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckManagedPrefixList(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckManagedPrefixListEntryDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCManagedPrefixListEntryConfig_ipv4Multiple(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckManagedPrefixListEntryExists(resourceName1, &entry), + testAccCheckManagedPrefixListEntryExists(resourceName2, &entry), + testAccCheckManagedPrefixListEntryExists(resourceName3, &entry), + resource.TestCheckResourceAttr(resourceName1, "cidr", "10.0.0.0/24"), + resource.TestCheckResourceAttr(resourceName2, "cidr", "10.0.1.0/24"), + resource.TestCheckResourceAttr(resourceName3, "cidr", "10.0.2.0/24"), + ), + }, + }, + }) +} + func TestAccVPCManagedPrefixListEntry_ipv6(t *testing.T) { var entry ec2.PrefixListEntry resourceName := "aws_ec2_managed_prefix_list_entry.test" @@ -59,7 +87,7 @@ func TestAccVPCManagedPrefixListEntry_ipv6(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListEntryDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListEntryIPv6Config(rName), + Config: testAccVPCManagedPrefixListEntryConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckManagedPrefixListEntryExists(resourceName, &entry), resource.TestCheckResourceAttrPair(resourceName, "prefix_list_id", plResourceName, "id"), @@ -87,7 +115,7 @@ func TestAccVPCManagedPrefixListEntry_expectInvalidTypeError(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListEntryDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListEntryExpectInvalidType(rName), + Config: testAccVPCManagedPrefixListEntryConfig_expectInvalidType(rName), ExpectError: regexp.MustCompile(`invalid CIDR address: ::/244`), }, }, @@ -104,11 +132,11 @@ func TestAccVPCManagedPrefixListEntry_expectInvalidCIDR(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListEntryDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListEntryInvalidIPv4CIDR(rName), + Config: testAccVPCManagedPrefixListEntryConfig_invalidIPv4CIDR(rName), ExpectError: regexp.MustCompile("invalid CIDR address: 1.2.3.4/33"), }, { - Config: testAccManagedPrefixListEntryInvalidIPv6CIDR(rName), + Config: testAccVPCManagedPrefixListEntryConfig_invalidIPv6CIDR(rName), ExpectError: regexp.MustCompile("invalid CIDR address: ::/244"), }, }, @@ -128,7 +156,7 @@ func TestAccVPCManagedPrefixListEntry_description(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListEntryDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListEntryDescriptionConfig(rName), + Config: testAccVPCManagedPrefixListEntryConfig_description(rName), Check: resource.ComposeTestCheckFunc( testAccCheckManagedPrefixListEntryExists(resourceName, &entry), resource.TestCheckResourceAttrPair(resourceName, "prefix_list_id", plResourceName, "id"), @@ -158,7 +186,7 @@ func TestAccVPCManagedPrefixListEntry_disappears(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListEntryDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListEntryIPv4Config(rName), + Config: testAccVPCManagedPrefixListEntryConfig_ipv4(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckManagedPrefixListEntryExists(resourceName, &entry), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceManagedPrefixListEntry(), resourceName), @@ -244,7 +272,7 @@ func testAccManagedPrefixListEntryImportStateIdFunc(resourceName string) resourc } } -func testAccManagedPrefixListEntryIPv4Config(rName string) string { +func testAccVPCManagedPrefixListEntryConfig_ipv4(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { name = %[1]q @@ -259,7 +287,35 @@ resource "aws_ec2_managed_prefix_list_entry" "test" { `, rName) } -func testAccManagedPrefixListEntryIPv6Config(rName string) string { +func testAccVPCManagedPrefixListEntryConfig_ipv4Multiple(rName string) string { + return fmt.Sprintf(` +resource "aws_ec2_managed_prefix_list" "test" { + name = %[1]q + address_family = "IPv4" + max_entries = 5 +} + +resource "aws_ec2_managed_prefix_list_entry" "test1" { + cidr = "10.0.0.0/24" + description = "description 1" + prefix_list_id = aws_ec2_managed_prefix_list.test.id +} + +resource "aws_ec2_managed_prefix_list_entry" "test2" { + cidr = "10.0.1.0/24" + description = "description 2" + prefix_list_id = aws_ec2_managed_prefix_list.test.id +} + +resource "aws_ec2_managed_prefix_list_entry" "test3" { + cidr = "10.0.2.0/24" + description = "description 3" + prefix_list_id = aws_ec2_managed_prefix_list.test.id +} +`, rName) +} + +func testAccVPCManagedPrefixListEntryConfig_ipv6(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { name = %[1]q @@ -274,7 +330,7 @@ resource "aws_ec2_managed_prefix_list_entry" "test" { `, rName) } -func testAccManagedPrefixListEntryDescriptionConfig(rName string) string { +func testAccVPCManagedPrefixListEntryConfig_description(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { name = %[1]q @@ -290,7 +346,7 @@ resource "aws_ec2_managed_prefix_list_entry" "test" { `, rName) } -func testAccManagedPrefixListEntryExpectInvalidType(rName string) string { +func testAccVPCManagedPrefixListEntryConfig_expectInvalidType(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { name = %[1]q @@ -305,7 +361,7 @@ resource "aws_ec2_managed_prefix_list_entry" "test" { `, rName) } -func testAccManagedPrefixListEntryInvalidIPv4CIDR(rName string) string { +func testAccVPCManagedPrefixListEntryConfig_invalidIPv4CIDR(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { name = %[1]q @@ -320,7 +376,7 @@ resource "aws_ec2_managed_prefix_list_entry" "test" { `, rName) } -func testAccManagedPrefixListEntryInvalidIPv6CIDR(rName string) string { +func testAccVPCManagedPrefixListEntryConfig_invalidIPv6CIDR(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { name = %[1]q diff --git a/internal/service/ec2/vpc_managed_prefix_list_test.go b/internal/service/ec2/vpc_managed_prefix_list_test.go index 003a2edf40f..4aad229f6a8 100644 --- a/internal/service/ec2/vpc_managed_prefix_list_test.go +++ b/internal/service/ec2/vpc_managed_prefix_list_test.go @@ -26,7 +26,7 @@ func TestAccVPCManagedPrefixList_basic(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListConfig_Name(rName), + Config: testAccVPCManagedPrefixListConfig_name(rName), ResourceName: resourceName, Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), @@ -46,7 +46,7 @@ func TestAccVPCManagedPrefixList_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccManagedPrefixListUpdatedConfig(rName), + Config: testAccVPCManagedPrefixListConfig_updated(rName), ResourceName: resourceName, Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), @@ -68,7 +68,7 @@ func TestAccVPCManagedPrefixList_disappears(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListConfig_Name(rName), + Config: testAccVPCManagedPrefixListConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceManagedPrefixList(), resourceName), @@ -90,7 +90,7 @@ func TestAccVPCManagedPrefixList_AddressFamily_ipv6(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListConfig_AddressFamily(rName, "IPv6"), + Config: testAccVPCManagedPrefixListConfig_addressFamily(rName, "IPv6"), ResourceName: resourceName, Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), @@ -117,7 +117,7 @@ func TestAccVPCManagedPrefixList_Entry_cidr(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListConfig_Entry_CIDR1(rName), + Config: testAccVPCManagedPrefixListConfig_entryCIDR1(rName), ResourceName: resourceName, Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), @@ -139,7 +139,7 @@ func TestAccVPCManagedPrefixList_Entry_cidr(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccManagedPrefixListConfig_Entry_CIDR2(rName), + Config: testAccVPCManagedPrefixListConfig_entryCIDR2(rName), ResourceName: resourceName, Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), @@ -175,7 +175,7 @@ func TestAccVPCManagedPrefixList_Entry_description(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListConfig_Entry_Description(rName, "description1"), + Config: testAccVPCManagedPrefixListConfig_entryDescription(rName, "description1"), ResourceName: resourceName, Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), @@ -197,7 +197,7 @@ func TestAccVPCManagedPrefixList_Entry_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccManagedPrefixListConfig_Entry_Description(rName, "description2"), + Config: testAccVPCManagedPrefixListConfig_entryDescription(rName, "description2"), ResourceName: resourceName, Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), @@ -229,7 +229,7 @@ func TestAccVPCManagedPrefixList_name(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListConfig_Name(rName1), + Config: testAccVPCManagedPrefixListConfig_name(rName1), ResourceName: resourceName, Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), @@ -243,7 +243,7 @@ func TestAccVPCManagedPrefixList_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccManagedPrefixListConfig_Name(rName2), + Config: testAccVPCManagedPrefixListConfig_name(rName2), ResourceName: resourceName, Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), @@ -266,7 +266,7 @@ func TestAccVPCManagedPrefixList_tags(t *testing.T) { CheckDestroy: testAccCheckManagedPrefixListDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedPrefixListConfig_Tags1(rName, "key1", "value1"), + Config: testAccVPCManagedPrefixListConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -280,7 +280,7 @@ func TestAccVPCManagedPrefixList_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccManagedPrefixListConfig_Tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCManagedPrefixListConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -290,7 +290,7 @@ func TestAccVPCManagedPrefixList_tags(t *testing.T) { ), }, { - Config: testAccManagedPrefixListConfig_Tags1(rName, "key2", "value2"), + Config: testAccVPCManagedPrefixListConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccManagedPrefixListExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -365,7 +365,7 @@ func testAccPreCheckManagedPrefixList(t *testing.T) { } } -func testAccManagedPrefixListConfig_AddressFamily(rName string, addressFamily string) string { +func testAccVPCManagedPrefixListConfig_addressFamily(rName string, addressFamily string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { address_family = %[2]q @@ -375,7 +375,7 @@ resource "aws_ec2_managed_prefix_list" "test" { `, rName, addressFamily) } -func testAccManagedPrefixListConfig_Entry_CIDR1(rName string) string { +func testAccVPCManagedPrefixListConfig_entryCIDR1(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { address_family = "IPv4" @@ -395,7 +395,7 @@ resource "aws_ec2_managed_prefix_list" "test" { `, rName) } -func testAccManagedPrefixListConfig_Entry_CIDR2(rName string) string { +func testAccVPCManagedPrefixListConfig_entryCIDR2(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { address_family = "IPv4" @@ -415,7 +415,7 @@ resource "aws_ec2_managed_prefix_list" "test" { `, rName) } -func testAccManagedPrefixListConfig_Entry_Description(rName string, description string) string { +func testAccVPCManagedPrefixListConfig_entryDescription(rName string, description string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { address_family = "IPv4" @@ -435,7 +435,7 @@ resource "aws_ec2_managed_prefix_list" "test" { `, rName, description) } -func testAccManagedPrefixListConfig_Name(rName string) string { +func testAccVPCManagedPrefixListConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { address_family = "IPv4" @@ -445,7 +445,7 @@ resource "aws_ec2_managed_prefix_list" "test" { `, rName) } -func testAccManagedPrefixListUpdatedConfig(rName string) string { +func testAccVPCManagedPrefixListConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { address_family = "IPv4" @@ -455,7 +455,7 @@ resource "aws_ec2_managed_prefix_list" "test" { `, rName) } -func testAccManagedPrefixListConfig_Tags1(rName string, tagKey1 string, tagValue1 string) string { +func testAccVPCManagedPrefixListConfig_tags1(rName string, tagKey1 string, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { name = %[1]q @@ -469,7 +469,7 @@ resource "aws_ec2_managed_prefix_list" "test" { `, rName, tagKey1, tagValue1) } -func testAccManagedPrefixListConfig_Tags2(rName string, tagKey1 string, tagValue1 string, tagKey2 string, tagValue2 string) string { +func testAccVPCManagedPrefixListConfig_tags2(rName string, tagKey1 string, tagValue1 string, tagKey2 string, tagValue2 string) string { return fmt.Sprintf(` resource "aws_ec2_managed_prefix_list" "test" { name = %[1]q diff --git a/internal/service/ec2/vpc_nat_gateway_data_source_test.go b/internal/service/ec2/vpc_nat_gateway_data_source_test.go index 8fd0837f152..10268da11ce 100644 --- a/internal/service/ec2/vpc_nat_gateway_data_source_test.go +++ b/internal/service/ec2/vpc_nat_gateway_data_source_test.go @@ -23,7 +23,7 @@ func TestAccVPCNATGatewayDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccNATGatewayDataSourceConfig(rName), + Config: testAccVPCNATGatewayDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceNameById, "connectivity_type", resourceName, "connectivity_type"), resource.TestCheckResourceAttrPair(dataSourceNameById, "id", resourceName, "id"), @@ -42,7 +42,7 @@ func TestAccVPCNATGatewayDataSource_basic(t *testing.T) { }) } -func testAccNATGatewayDataSourceConfig(rName string) string { +func testAccVPCNATGatewayDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.5.0.0/16" diff --git a/internal/service/ec2/vpc_nat_gateway_test.go b/internal/service/ec2/vpc_nat_gateway_test.go index a34b2eb7c0e..3369c8a7353 100644 --- a/internal/service/ec2/vpc_nat_gateway_test.go +++ b/internal/service/ec2/vpc_nat_gateway_test.go @@ -26,7 +26,7 @@ func TestAccVPCNATGateway_basic(t *testing.T) { CheckDestroy: testAccCheckNATGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccNATGatewayConfig(rName), + Config: testAccVPCNATGatewayConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNATGatewayExists(resourceName, &natGateway), resource.TestCheckResourceAttrSet(resourceName, "allocation_id"), @@ -58,7 +58,7 @@ func TestAccVPCNATGateway_disappears(t *testing.T) { CheckDestroy: testAccCheckNATGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccNATGatewayConfig(rName), + Config: testAccVPCNATGatewayConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNATGatewayExists(resourceName, &natGateway), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNATGateway(), resourceName), @@ -81,7 +81,7 @@ func TestAccVPCNATGateway_ConnectivityType_private(t *testing.T) { CheckDestroy: testAccCheckNATGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccNATGatewayConfigConnectivityType(rName, "private"), + Config: testAccVPCNATGatewayConfig_connectivityType(rName, "private"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNATGatewayExists(resourceName, &natGateway), resource.TestCheckResourceAttr(resourceName, "allocation_id", ""), @@ -114,7 +114,7 @@ func TestAccVPCNATGateway_tags(t *testing.T) { CheckDestroy: testAccCheckNATGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccNATGatewayConfigTags1(rName, "key1", "value1"), + Config: testAccVPCNATGatewayConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckNATGatewayExists(resourceName, &natGateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -127,7 +127,7 @@ func TestAccVPCNATGateway_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNATGatewayConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCNATGatewayConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNATGatewayExists(resourceName, &natGateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -136,7 +136,7 @@ func TestAccVPCNATGateway_tags(t *testing.T) { ), }, { - Config: testAccNATGatewayConfigTags1(rName, "key2", "value2"), + Config: testAccVPCNATGatewayConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNATGatewayExists(resourceName, &natGateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -244,7 +244,7 @@ resource "aws_eip" "test" { `, rName) } -func testAccNATGatewayConfig(rName string) string { +func testAccVPCNATGatewayConfig_basic(rName string) string { return acctest.ConfigCompose(testAccNATGatewayConfigBase(rName), ` resource "aws_nat_gateway" "test" { allocation_id = aws_eip.test.id @@ -255,7 +255,7 @@ resource "aws_nat_gateway" "test" { `) } -func testAccNATGatewayConfigConnectivityType(rName, connectivityType string) string { +func testAccVPCNATGatewayConfig_connectivityType(rName, connectivityType string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -285,7 +285,7 @@ resource "aws_nat_gateway" "test" { `, rName, connectivityType) } -func testAccNATGatewayConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccVPCNATGatewayConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccNATGatewayConfigBase(rName), fmt.Sprintf(` resource "aws_nat_gateway" "test" { allocation_id = aws_eip.test.id @@ -300,7 +300,7 @@ resource "aws_nat_gateway" "test" { `, tagKey1, tagValue1)) } -func testAccNATGatewayConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCNATGatewayConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccNATGatewayConfigBase(rName), fmt.Sprintf(` resource "aws_nat_gateway" "test" { allocation_id = aws_eip.test.id diff --git a/internal/service/ec2/vpc_nat_gateways_data_source_test.go b/internal/service/ec2/vpc_nat_gateways_data_source_test.go index d119667aaa2..45998f5d832 100644 --- a/internal/service/ec2/vpc_nat_gateways_data_source_test.go +++ b/internal/service/ec2/vpc_nat_gateways_data_source_test.go @@ -19,7 +19,7 @@ func TestAccVPCNATGatewaysDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccNATGatewaysDataSourceConfig(rName), + Config: testAccVPCNATGatewaysDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_nat_gateways.by_vpc_id", "ids.#", "2"), resource.TestCheckResourceAttr("data.aws_nat_gateways.by_tags", "ids.#", "1"), @@ -31,7 +31,7 @@ func TestAccVPCNATGatewaysDataSource_basic(t *testing.T) { }) } -func testAccNATGatewaysDataSourceConfig(rName string) string { +func testAccVPCNATGatewaysDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "172.5.0.0/16" diff --git a/internal/service/ec2/vpc_network_acl_association_test.go b/internal/service/ec2/vpc_network_acl_association_test.go index f281bb4ee4c..3697c78080c 100644 --- a/internal/service/ec2/vpc_network_acl_association_test.go +++ b/internal/service/ec2/vpc_network_acl_association_test.go @@ -28,7 +28,7 @@ func TestAccVPCNetworkACLAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckNetworkACLAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLAssociationConfig(rName), + Config: testAccVPCNetworkACLAssociationConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLAssociationExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "network_acl_id", naclResourceName, "id"), @@ -56,7 +56,7 @@ func TestAccVPCNetworkACLAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckNetworkACLAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLAssociationConfig(rName), + Config: testAccVPCNetworkACLAssociationConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLAssociationExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNetworkACLAssociation(), resourceName), @@ -80,7 +80,7 @@ func TestAccVPCNetworkACLAssociation_disappears_NACL(t *testing.T) { CheckDestroy: testAccCheckNetworkACLAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLAssociationConfig(rName), + Config: testAccVPCNetworkACLAssociationConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLAssociationExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNetworkACL(), naclResourceName), @@ -104,7 +104,7 @@ func TestAccVPCNetworkACLAssociation_disappears_Subnet(t *testing.T) { CheckDestroy: testAccCheckNetworkACLAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLAssociationConfig(rName), + Config: testAccVPCNetworkACLAssociationConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLAssociationExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSubnet(), subnetResourceName), @@ -131,7 +131,7 @@ func TestAccVPCNetworkACLAssociation_twoAssociations(t *testing.T) { CheckDestroy: testAccCheckNetworkACLAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLAssociationTwoAssociationsConfig(rName), + Config: testAccVPCNetworkACLAssociationConfig_twoAssociations(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLAssociationExists(resource1Name, &v1), testAccCheckNetworkACLAssociationExists(resource1Name, &v2), @@ -168,7 +168,7 @@ func TestAccVPCNetworkACLAssociation_associateWithDefaultNACL(t *testing.T) { CheckDestroy: testAccCheckNetworkACLAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLAssociationDefaultNACLConfig(rName), + Config: testAccVPCNetworkACLAssociationConfig_default(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLAssociationExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "subnet_id", subnetResourceName, "id"), @@ -231,7 +231,7 @@ func testAccCheckNetworkACLAssociationExists(n string, v *ec2.NetworkAclAssociat } } -func testAccNetworkACLAssociationConfig(rName string) string { +func testAccVPCNetworkACLAssociationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -266,7 +266,7 @@ resource "aws_network_acl_association" "test" { `, rName) } -func testAccNetworkACLAssociationTwoAssociationsConfig(rName string) string { +func testAccVPCNetworkACLAssociationConfig_twoAssociations(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -316,7 +316,7 @@ resource "aws_network_acl_association" "test2" { `, rName) } -func testAccNetworkACLAssociationDefaultNACLConfig(rName string) string { +func testAccVPCNetworkACLAssociationConfig_default(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_network_acl_rule_test.go b/internal/service/ec2/vpc_network_acl_rule_test.go index 18f5bf3599e..6b80e6ff5d7 100644 --- a/internal/service/ec2/vpc_network_acl_rule_test.go +++ b/internal/service/ec2/vpc_network_acl_rule_test.go @@ -30,7 +30,7 @@ func TestAccVPCNetworkACLRule_basic(t *testing.T) { CheckDestroy: testAccCheckNetworkACLRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLRuleConfig(rName), + Config: testAccVPCNetworkACLRuleConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLRuleExists(resource1Name), testAccCheckNetworkACLRuleExists(resource2Name), @@ -97,7 +97,7 @@ func TestAccVPCNetworkACLRule_disappears(t *testing.T) { CheckDestroy: testAccCheckNetworkACLRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLRuleConfig(rName), + Config: testAccVPCNetworkACLRuleConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLRuleExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNetworkACLRule(), resourceName), @@ -119,7 +119,7 @@ func TestAccVPCNetworkACLRule_Disappears_networkACL(t *testing.T) { CheckDestroy: testAccCheckNetworkACLRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLRuleConfig(rName), + Config: testAccVPCNetworkACLRuleConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLRuleExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNetworkACL(), "aws_network_acl.test"), @@ -141,7 +141,7 @@ func TestAccVPCNetworkACLRule_Disappears_ingressEgressSameNumber(t *testing.T) { CheckDestroy: testAccCheckNetworkACLRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLRuleIngressEgressSameNumberMissingConfig(rName), + Config: testAccVPCNetworkACLRuleConfig_ingressEgressSameNumberMissing(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLRuleExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNetworkACLRule(), resourceName), @@ -163,7 +163,7 @@ func TestAccVPCNetworkACLRule_ipv6(t *testing.T) { CheckDestroy: testAccCheckNetworkACLRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLRuleIPv6Config(rName), + Config: testAccVPCNetworkACLRuleConfig_ipv6(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cidr_block", ""), @@ -197,7 +197,7 @@ func TestAccVPCNetworkACLRule_ipv6ICMP(t *testing.T) { CheckDestroy: testAccCheckNetworkACLRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLRuleIPv6ICMPConfig(rName), + Config: testAccVPCNetworkACLRuleConfig_ipv6ICMP(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cidr_block", ""), @@ -234,7 +234,7 @@ func TestAccVPCNetworkACLRule_ipv6VPCAssignGeneratedIPv6CIDRBlockUpdate(t *testi CheckDestroy: testAccCheckNetworkACLRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLRuleConfig_ipv6VPCNotAssignGeneratedIPv6CIDRBlockUpdate(rName), + Config: testAccVPCNetworkACLRuleConfig_ipv6NotAssignGeneratedIPv6CIDRBlockUpdate(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(vpcResourceName, &v), resource.TestCheckResourceAttr(vpcResourceName, "assign_generated_ipv6_cidr_block", "false"), @@ -242,7 +242,7 @@ func TestAccVPCNetworkACLRule_ipv6VPCAssignGeneratedIPv6CIDRBlockUpdate(t *testi ), }, { - Config: testAccNetworkACLRuleConfig_ipv6VPCAssignGeneratedIPv6CIDRBlockUpdate(rName), + Config: testAccVPCNetworkACLRuleConfig_ipv6AssignGeneratedIPv6CIDRBlockUpdate(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(vpcResourceName, &v), testAccCheckNetworkACLRuleExists(resourceName), @@ -271,7 +271,7 @@ func TestAccVPCNetworkACLRule_allProtocol(t *testing.T) { CheckDestroy: testAccCheckNetworkACLRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLRuleAllProtocolConfig(rName), + Config: testAccVPCNetworkACLRuleConfig_allProtocol(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cidr_block", "0.0.0.0/0"), @@ -285,7 +285,7 @@ func TestAccVPCNetworkACLRule_allProtocol(t *testing.T) { ), }, { - Config: testAccNetworkACLRuleAllProtocolNoRealUpdateConfig(rName), + Config: testAccVPCNetworkACLRuleConfig_allProtocolNoRealUpdate(rName), PlanOnly: true, }, }, @@ -303,7 +303,7 @@ func TestAccVPCNetworkACLRule_tcpProtocol(t *testing.T) { CheckDestroy: testAccCheckNetworkACLRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLRuleTCPProtocolConfig(rName), + Config: testAccVPCNetworkACLRuleConfig_tcpProtocol(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cidr_block", "0.0.0.0/0"), @@ -317,7 +317,7 @@ func TestAccVPCNetworkACLRule_tcpProtocol(t *testing.T) { ), }, { - Config: testAccNetworkACLRuleTCPProtocolNoRealUpdateConfig(rName), + Config: testAccVPCNetworkACLRuleConfig_tcpProtocolNoRealUpdate(rName), PlanOnly: true, }, }, @@ -398,7 +398,7 @@ func testAccCheckNetworkACLRuleExists(n string) resource.TestCheckFunc { } } -func testAccNetworkACLRuleConfig(rName string) string { +func testAccVPCNetworkACLRuleConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.3.0.0/16" @@ -449,7 +449,7 @@ resource "aws_network_acl_rule" "test3" { `, rName) } -func testAccNetworkACLRuleAllProtocolNoRealUpdateConfig(rName string) string { +func testAccVPCNetworkACLRuleConfig_allProtocolNoRealUpdate(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.3.0.0/16" @@ -480,7 +480,7 @@ resource "aws_network_acl_rule" "test" { `, rName) } -func testAccNetworkACLRuleTCPProtocolNoRealUpdateConfig(rName string) string { +func testAccVPCNetworkACLRuleConfig_tcpProtocolNoRealUpdate(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.3.0.0/16" @@ -511,7 +511,7 @@ resource "aws_network_acl_rule" "test" { `, rName) } -func testAccNetworkACLRuleAllProtocolConfig(rName string) string { +func testAccVPCNetworkACLRuleConfig_allProtocol(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.3.0.0/16" @@ -542,7 +542,7 @@ resource "aws_network_acl_rule" "test" { `, rName) } -func testAccNetworkACLRuleTCPProtocolConfig(rName string) string { +func testAccVPCNetworkACLRuleConfig_tcpProtocol(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.3.0.0/16" @@ -573,7 +573,7 @@ resource "aws_network_acl_rule" "test" { `, rName) } -func testAccNetworkACLRuleIPv6Config(rName string) string { +func testAccVPCNetworkACLRuleConfig_ipv6(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.3.0.0/16" @@ -604,7 +604,7 @@ resource "aws_network_acl_rule" "test" { `, rName) } -func testAccNetworkACLRuleIngressEgressSameNumberMissingConfig(rName string) string { +func testAccVPCNetworkACLRuleConfig_ingressEgressSameNumberMissing(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.3.0.0/16" @@ -646,7 +646,7 @@ resource "aws_network_acl_rule" "test2" { `, rName) } -func testAccNetworkACLRuleIPv6ICMPConfig(rName string) string { +func testAccVPCNetworkACLRuleConfig_ipv6ICMP(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.3.0.0/16" @@ -676,7 +676,7 @@ resource "aws_network_acl_rule" "test" { `, rName, rName) } -func testAccNetworkACLRuleConfig_ipv6VPCAssignGeneratedIPv6CIDRBlockUpdate(rName string) string { +func testAccVPCNetworkACLRuleConfig_ipv6AssignGeneratedIPv6CIDRBlockUpdate(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { assign_generated_ipv6_cidr_block = true @@ -707,7 +707,7 @@ resource "aws_network_acl_rule" "test" { `, rName) } -func testAccNetworkACLRuleConfig_ipv6VPCNotAssignGeneratedIPv6CIDRBlockUpdate(rName string) string { +func testAccVPCNetworkACLRuleConfig_ipv6NotAssignGeneratedIPv6CIDRBlockUpdate(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { assign_generated_ipv6_cidr_block = false diff --git a/internal/service/ec2/vpc_network_acl_test.go b/internal/service/ec2/vpc_network_acl_test.go index 0743a65e71f..0bc501eec45 100644 --- a/internal/service/ec2/vpc_network_acl_test.go +++ b/internal/service/ec2/vpc_network_acl_test.go @@ -28,7 +28,7 @@ func TestAccVPCNetworkACL_basic(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLConfig(rName), + Config: testAccVPCNetworkACLConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`network-acl/acl-.+`)), @@ -61,7 +61,7 @@ func TestAccVPCNetworkACL_disappears(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLConfig(rName), + Config: testAccVPCNetworkACLConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNetworkACL(), resourceName), @@ -84,7 +84,7 @@ func TestAccVPCNetworkACL_tags(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLTags1Config(rName, "key1", "value1"), + Config: testAccVPCNetworkACLConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -97,7 +97,7 @@ func TestAccVPCNetworkACL_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkACLTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCNetworkACLConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -106,7 +106,7 @@ func TestAccVPCNetworkACL_tags(t *testing.T) { ), }, { - Config: testAccNetworkACLTags1Config(rName, "key2", "value2"), + Config: testAccVPCNetworkACLConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -129,7 +129,7 @@ func TestAccVPCNetworkACL_Egress_mode(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLEgressModeBlocksConfig(rName), + Config: testAccVPCNetworkACLConfig_egressModeBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), @@ -141,7 +141,7 @@ func TestAccVPCNetworkACL_Egress_mode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkACLEgressModeNoBlocksConfig(rName), + Config: testAccVPCNetworkACLConfig_egressModeNoBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), @@ -153,7 +153,7 @@ func TestAccVPCNetworkACL_Egress_mode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkACLEgressModeZeroedConfig(rName), + Config: testAccVPCNetworkACLConfig_egressModeZeroed(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -180,7 +180,7 @@ func TestAccVPCNetworkACL_Ingress_mode(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLIngressModeBlocksConfig(rName), + Config: testAccVPCNetworkACLConfig_ingressModeBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), @@ -192,7 +192,7 @@ func TestAccVPCNetworkACL_Ingress_mode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkACLIngressModeNoBlocksConfig(rName), + Config: testAccVPCNetworkACLConfig_ingressModeNoBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), @@ -204,7 +204,7 @@ func TestAccVPCNetworkACL_Ingress_mode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkACLIngressModeZeroedConfig(rName), + Config: testAccVPCNetworkACLConfig_ingressModeZeroed(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), @@ -231,7 +231,7 @@ func TestAccVPCNetworkACL_egressAndIngressRules(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLEgressNIngressConfig(rName), + Config: testAccVPCNetworkACLConfig_egressNIngress(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ @@ -273,7 +273,7 @@ func TestAccVPCNetworkACL_OnlyIngressRules_basic(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLIngressConfig(rName), + Config: testAccVPCNetworkACLConfig_ingress(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ @@ -307,7 +307,7 @@ func TestAccVPCNetworkACL_OnlyIngressRules_update(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLIngressConfig(resourceName), + Config: testAccVPCNetworkACLConfig_ingress(resourceName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), @@ -331,7 +331,7 @@ func TestAccVPCNetworkACL_OnlyIngressRules_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkACLIngressChangeConfig(rName), + Config: testAccVPCNetworkACLConfig_ingressChange(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), @@ -361,7 +361,7 @@ func TestAccVPCNetworkACL_caseSensitivityNoChanges(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLCaseSensitiveConfig(rName), + Config: testAccVPCNetworkACLConfig_caseSensitive(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), ), @@ -387,7 +387,7 @@ func TestAccVPCNetworkACL_onlyEgressRules(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLEgressConfig(rName), + Config: testAccVPCNetworkACLConfig_egress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), ), @@ -413,7 +413,7 @@ func TestAccVPCNetworkACL_subnetChange(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLSubnetConfig(rName), + Config: testAccVPCNetworkACLConfig_subnet(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "1"), @@ -426,7 +426,7 @@ func TestAccVPCNetworkACL_subnetChange(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkACLSubnetChangeConfig(rName), + Config: testAccVPCNetworkACLConfig_subnetChange(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "1"), @@ -450,7 +450,7 @@ func TestAccVPCNetworkACL_subnets(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLSubnet_SubnetIDs(rName), + Config: testAccVPCNetworkACLConfig_subnetSubnetIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), @@ -464,7 +464,7 @@ func TestAccVPCNetworkACL_subnets(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkACLSubnet_SubnetIDsUpdate(rName), + Config: testAccVPCNetworkACLConfig_subnetSubnetIDsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "3"), @@ -489,7 +489,7 @@ func TestAccVPCNetworkACL_subnetsDelete(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLSubnet_SubnetIDs(resourceName), + Config: testAccVPCNetworkACLConfig_subnetSubnetIDs(resourceName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), @@ -503,7 +503,7 @@ func TestAccVPCNetworkACL_subnetsDelete(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkACLSubnet_SubnetIDsDeleteOne(rName), + Config: testAccVPCNetworkACLConfig_subnetSubnetIDsDeleteOne(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "1"), @@ -526,7 +526,7 @@ func TestAccVPCNetworkACL_ipv6Rules(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLIPv6Config(rName), + Config: testAccVPCNetworkACLConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -562,7 +562,7 @@ func TestAccVPCNetworkACL_ipv6ICMPRules(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLIPv6ICMPConfig(rName), + Config: testAccVPCNetworkACLConfig_ipv6ICMP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), ), @@ -583,7 +583,7 @@ func TestAccVPCNetworkACL_ipv6VPCRules(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLIPv6VPCConfig(rName), + Config: testAccVPCNetworkACLConfig_ipv6VPC(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), @@ -613,7 +613,7 @@ func TestAccVPCNetworkACL_espProtocol(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLEsp(rName), + Config: testAccVPCNetworkACLConfig_esp(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkACLExists(resourceName, &v), ), @@ -676,7 +676,7 @@ func testAccCheckNetworkACLExists(n string, v *ec2.NetworkAcl) resource.TestChec } } -func testAccNetworkACLConfig(rName string) string { +func testAccVPCNetworkACLConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -692,7 +692,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLIPv6ICMPConfig(rName string) string { +func testAccVPCNetworkACLConfig_ipv6ICMP(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -723,7 +723,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLIPv6Config(rName string) string { +func testAccVPCNetworkACLConfig_ipv6(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -764,7 +764,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLIPv6VPCConfig(rName string) string { +func testAccVPCNetworkACLConfig_ipv6VPC(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -794,7 +794,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLIngressConfig(rName string) string { +func testAccVPCNetworkACLConfig_ingress(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -844,7 +844,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLCaseSensitiveConfig(rName string) string { +func testAccVPCNetworkACLConfig_caseSensitive(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -885,7 +885,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLIngressChangeConfig(rName string) string { +func testAccVPCNetworkACLConfig_ingressChange(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -926,7 +926,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLEgressConfig(rName string) string { +func testAccVPCNetworkACLConfig_egress(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.2.0.0/16" @@ -992,7 +992,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLEgressNIngressConfig(rName string) string { +func testAccVPCNetworkACLConfig_egressNIngress(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.3.0.0/16" @@ -1040,7 +1040,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLSubnetConfig(rName string) string { +func testAccVPCNetworkACLConfig_subnet(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1090,7 +1090,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLSubnetChangeConfig(rName string) string { +func testAccVPCNetworkACLConfig_subnetChange(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1131,7 +1131,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLSubnet_SubnetIDs(rName string) string { +func testAccVPCNetworkACLConfig_subnetSubnetIDs(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1170,7 +1170,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLSubnet_SubnetIDsUpdate(rName string) string { +func testAccVPCNetworkACLConfig_subnetSubnetIDsUpdate(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1231,7 +1231,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLSubnet_SubnetIDsDeleteOne(rName string) string { +func testAccVPCNetworkACLConfig_subnetSubnetIDsDeleteOne(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1261,7 +1261,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLEsp(rName string) string { +func testAccVPCNetworkACLConfig_esp(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1290,7 +1290,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLEgressModeBlocksConfig(rName string) string { +func testAccVPCNetworkACLConfig_egressModeBlocks(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1328,7 +1328,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLEgressModeNoBlocksConfig(rName string) string { +func testAccVPCNetworkACLConfig_egressModeNoBlocks(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1348,7 +1348,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLEgressModeZeroedConfig(rName string) string { +func testAccVPCNetworkACLConfig_egressModeZeroed(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1370,7 +1370,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLIngressModeBlocksConfig(rName string) string { +func testAccVPCNetworkACLConfig_ingressModeBlocks(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1408,7 +1408,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLIngressModeNoBlocksConfig(rName string) string { +func testAccVPCNetworkACLConfig_ingressModeNoBlocks(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1428,7 +1428,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLIngressModeZeroedConfig(rName string) string { +func testAccVPCNetworkACLConfig_ingressModeZeroed(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1450,7 +1450,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccVPCNetworkACLConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1470,7 +1470,7 @@ resource "aws_network_acl" "test" { `, rName, tagKey1, tagValue1) } -func testAccNetworkACLTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCNetworkACLConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_network_acls_data_source_test.go b/internal/service/ec2/vpc_network_acls_data_source_test.go index a18661a5081..0f9fca56d25 100644 --- a/internal/service/ec2/vpc_network_acls_data_source_test.go +++ b/internal/service/ec2/vpc_network_acls_data_source_test.go @@ -21,7 +21,7 @@ func TestAccVPCNetworkACLsDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLsDataSourceConfig_basic(rName), + Config: testAccVPCNetworkACLsDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "ids.#", "1"), ), @@ -41,7 +41,7 @@ func TestAccVPCNetworkACLsDataSource_filter(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLsDataSourceConfig_Filter(rName), + Config: testAccVPCNetworkACLsDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), ), @@ -61,7 +61,7 @@ func TestAccVPCNetworkACLsDataSource_tags(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLsDataSourceConfig_Tags(rName), + Config: testAccVPCNetworkACLsDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "2"), ), @@ -81,7 +81,7 @@ func TestAccVPCNetworkACLsDataSource_vpcID(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLsDataSourceConfig_VPCID(rName), + Config: testAccVPCNetworkACLsDataSourceConfig_id(rName), Check: resource.ComposeTestCheckFunc( // The VPC will have a default network ACL resource.TestCheckResourceAttr(dataSourceName, "ids.#", "3"), @@ -102,7 +102,7 @@ func TestAccVPCNetworkACLsDataSource_empty(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkACLsDataSourceConfig_Empty(rName), + Config: testAccVPCNetworkACLsDataSourceConfig_empty(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "0"), ), @@ -133,7 +133,7 @@ resource "aws_network_acl" "test" { `, rName) } -func testAccNetworkACLsDataSourceConfig_basic(rName string) string { +func testAccVPCNetworkACLsDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(testAccNetworkACLsDataSourceConfig_Base(rName), ` data "aws_network_acls" "test" { depends_on = [aws_network_acl.test[0], aws_network_acl.test[1]] @@ -141,7 +141,7 @@ data "aws_network_acls" "test" { `) } -func testAccNetworkACLsDataSourceConfig_Filter(rName string) string { +func testAccVPCNetworkACLsDataSourceConfig_filter(rName string) string { return acctest.ConfigCompose(testAccNetworkACLsDataSourceConfig_Base(rName), ` data "aws_network_acls" "test" { filter { @@ -154,7 +154,7 @@ data "aws_network_acls" "test" { `) } -func testAccNetworkACLsDataSourceConfig_Tags(rName string) string { +func testAccVPCNetworkACLsDataSourceConfig_tags(rName string) string { return acctest.ConfigCompose(testAccNetworkACLsDataSourceConfig_Base(rName), ` data "aws_network_acls" "test" { tags = { @@ -166,7 +166,7 @@ data "aws_network_acls" "test" { `) } -func testAccNetworkACLsDataSourceConfig_VPCID(rName string) string { +func testAccVPCNetworkACLsDataSourceConfig_id(rName string) string { return acctest.ConfigCompose(testAccNetworkACLsDataSourceConfig_Base(rName), ` data "aws_network_acls" "test" { vpc_id = aws_network_acl.test[0].vpc_id @@ -176,7 +176,7 @@ data "aws_network_acls" "test" { `) } -func testAccNetworkACLsDataSourceConfig_Empty(rName string) string { +func testAccVPCNetworkACLsDataSourceConfig_empty(rName string) string { return fmt.Sprintf(` data "aws_network_acls" "test" { tags = { diff --git a/internal/service/ec2/vpc_network_insights_path_test.go b/internal/service/ec2/vpc_network_insights_path_test.go index 3ee0fad79cf..189bdb7ac7e 100644 --- a/internal/service/ec2/vpc_network_insights_path_test.go +++ b/internal/service/ec2/vpc_network_insights_path_test.go @@ -26,7 +26,7 @@ func TestAccVPCNetworkInsightsPath_basic(t *testing.T) { CheckDestroy: testAccCheckNetworkInsightsPathDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInsightsPathConfig_basic(rName, "tcp"), + Config: testAccVPCNetworkInsightsPathConfig_basic(rName, "tcp"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`network-insights-path/.+$`)), @@ -59,7 +59,7 @@ func TestAccVPCNetworkInsightsPath_disappears(t *testing.T) { CheckDestroy: testAccCheckNetworkInsightsPathDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInsightsPathConfig_basic(rName, "udp"), + Config: testAccVPCNetworkInsightsPathConfig_basic(rName, "udp"), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNetworkInsightsPath(), resourceName), @@ -81,7 +81,7 @@ func TestAccVPCNetworkInsightsPath_tags(t *testing.T) { CheckDestroy: testAccCheckNetworkInsightsPathDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInsightsPathConfig_tags1(rName, "key1", "value1"), + Config: testAccVPCNetworkInsightsPathConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -94,7 +94,7 @@ func TestAccVPCNetworkInsightsPath_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkInsightsPathConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCNetworkInsightsPathConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -103,7 +103,7 @@ func TestAccVPCNetworkInsightsPath_tags(t *testing.T) { ), }, { - Config: testAccNetworkInsightsPathConfig_tags1(rName, "key2", "value2"), + Config: testAccVPCNetworkInsightsPathConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -125,7 +125,7 @@ func TestAccVPCNetworkInsightsPath_sourceIP(t *testing.T) { CheckDestroy: testAccCheckNetworkInsightsPathDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInsightsPathConfig_sourceIP(rName, "1.1.1.1"), + Config: testAccVPCNetworkInsightsPathConfig_sourceIP(rName, "1.1.1.1"), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), resource.TestCheckResourceAttr(resourceName, "source_ip", "1.1.1.1"), @@ -137,7 +137,7 @@ func TestAccVPCNetworkInsightsPath_sourceIP(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkInsightsPathConfig_sourceIP(rName, "8.8.8.8"), + Config: testAccVPCNetworkInsightsPathConfig_sourceIP(rName, "8.8.8.8"), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), resource.TestCheckResourceAttr(resourceName, "source_ip", "8.8.8.8"), @@ -158,7 +158,7 @@ func TestAccVPCNetworkInsightsPath_destinationIP(t *testing.T) { CheckDestroy: testAccCheckNetworkInsightsPathDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInsightsPathConfig_destinationIP(rName, "1.1.1.1"), + Config: testAccVPCNetworkInsightsPathConfig_destinationIP(rName, "1.1.1.1"), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), resource.TestCheckResourceAttr(resourceName, "destination_ip", "1.1.1.1"), @@ -170,7 +170,7 @@ func TestAccVPCNetworkInsightsPath_destinationIP(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkInsightsPathConfig_destinationIP(rName, "8.8.8.8"), + Config: testAccVPCNetworkInsightsPathConfig_destinationIP(rName, "8.8.8.8"), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), resource.TestCheckResourceAttr(resourceName, "destination_ip", "8.8.8.8"), @@ -191,7 +191,7 @@ func TestAccVPCNetworkInsightsPath_destinationPort(t *testing.T) { CheckDestroy: testAccCheckNetworkInsightsPathDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInsightsPathConfig_destinationPort(rName, 80), + Config: testAccVPCNetworkInsightsPathConfig_destinationPort(rName, 80), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), resource.TestCheckResourceAttr(resourceName, "destination_port", "80"), @@ -203,7 +203,7 @@ func TestAccVPCNetworkInsightsPath_destinationPort(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNetworkInsightsPathConfig_destinationPort(rName, 443), + Config: testAccVPCNetworkInsightsPathConfig_destinationPort(rName, 443), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInsightsPathExists(resourceName), resource.TestCheckResourceAttr(resourceName, "destination_port", "443"), @@ -260,7 +260,7 @@ func testAccCheckNetworkInsightsPathDestroy(s *terraform.State) error { return nil } -func testAccNetworkInsightsPathConfig_basic(rName, protocol string) string { +func testAccVPCNetworkInsightsPathConfig_basic(rName, protocol string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -303,7 +303,7 @@ resource "aws_ec2_network_insights_path" "test" { `, rName, protocol) } -func testAccNetworkInsightsPathConfig_tags1(rName, tagKey1, tagValue1 string) string { +func testAccVPCNetworkInsightsPathConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -350,7 +350,7 @@ resource "aws_ec2_network_insights_path" "test" { `, rName, tagKey1, tagValue1) } -func testAccNetworkInsightsPathConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCNetworkInsightsPathConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -398,7 +398,7 @@ resource "aws_ec2_network_insights_path" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccNetworkInsightsPathConfig_sourceIP(rName, sourceIP string) string { +func testAccVPCNetworkInsightsPathConfig_sourceIP(rName, sourceIP string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -446,7 +446,7 @@ resource "aws_ec2_network_insights_path" "test" { `, rName, sourceIP) } -func testAccNetworkInsightsPathConfig_destinationIP(rName, destinationIP string) string { +func testAccVPCNetworkInsightsPathConfig_destinationIP(rName, destinationIP string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -494,7 +494,7 @@ resource "aws_ec2_network_insights_path" "test" { `, rName, destinationIP) } -func testAccNetworkInsightsPathConfig_destinationPort(rName string, destinationPort int) string { +func testAccVPCNetworkInsightsPathConfig_destinationPort(rName string, destinationPort int) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/vpc_network_interface_attachment_test.go b/internal/service/ec2/vpc_network_interface_attachment_test.go index 0b86460325a..0d369d01ad1 100644 --- a/internal/service/ec2/vpc_network_interface_attachment_test.go +++ b/internal/service/ec2/vpc_network_interface_attachment_test.go @@ -22,7 +22,7 @@ func TestAccVPCNetworkInterfaceAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfaceAttachmentConfig(rName), + Config: testAccVPCNetworkInterfaceAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists("aws_network_interface.test", &conf), resource.TestCheckResourceAttrSet(resourceName, "attachment_id"), @@ -36,9 +36,9 @@ func TestAccVPCNetworkInterfaceAttachment_basic(t *testing.T) { }) } -func testAccNetworkInterfaceAttachmentConfig(rName string) string { +func testAccVPCNetworkInterfaceAttachmentConfig_basic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` diff --git a/internal/service/ec2/vpc_network_interface_data_source_test.go b/internal/service/ec2/vpc_network_interface_data_source_test.go index ade2526ce32..ceb2a29ccb3 100644 --- a/internal/service/ec2/vpc_network_interface_data_source_test.go +++ b/internal/service/ec2/vpc_network_interface_data_source_test.go @@ -21,7 +21,7 @@ func TestAccVPCNetworkInterfaceDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfaceBasicDataSourceConfig(rName), + Config: testAccVPCNetworkInterfaceDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "private_ips.#", "1"), resource.TestCheckResourceAttr(datasourceName, "security_groups.#", "1"), @@ -51,7 +51,7 @@ func TestAccVPCNetworkInterfaceDataSource_filters(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfaceFiltersDataSourceConfig(rName), + Config: testAccVPCNetworkInterfaceDataSourceConfig_filters(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "private_ips.#", "1"), resource.TestCheckResourceAttr(datasourceName, "security_groups.#", "1"), @@ -76,7 +76,7 @@ func TestAccVPCNetworkInterfaceDataSource_carrierIPAssociation(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfaceCarrierIPAssociationDataSourceConfig(rName), + Config: testAccVPCNetworkInterfaceDataSourceConfig_carrierIPAssociation(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "association.#", "1"), resource.TestCheckResourceAttrPair(datasourceName, "association.0.allocation_id", eipResourceName, "id"), @@ -124,7 +124,7 @@ func TestAccVPCNetworkInterfaceDataSource_publicIPAssociation(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfacePublicIPAssociationDataSourceConfig(rName), + Config: testAccVPCNetworkInterfaceDataSourceConfig_publicIPAssociation(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "association.#", "1"), resource.TestCheckResourceAttrPair(datasourceName, "association.0.allocation_id", eipResourceName, "id"), @@ -170,7 +170,7 @@ func TestAccVPCNetworkInterfaceDataSource_attachment(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfaceAttachmentDataSourceConfig(rName), + Config: testAccVPCNetworkInterfaceDataSourceConfig_attachment(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "association.#", "0"), resource.TestCheckResourceAttr(datasourceName, "attachment.#", "1"), @@ -240,7 +240,7 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccNetworkInterfaceBasicDataSourceConfig(rName string) string { +func testAccVPCNetworkInterfaceDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( testAccNetworkInterfaceBaseDataSourceConfig(rName), ` @@ -250,7 +250,7 @@ data "aws_network_interface" "test" { `) } -func testAccNetworkInterfaceCarrierIPAssociationDataSourceConfig(rName string) string { +func testAccVPCNetworkInterfaceDataSourceConfig_carrierIPAssociation(rName string) string { return acctest.ConfigCompose( testAccAvailableAZsWavelengthZonesDefaultExcludeConfig(), fmt.Sprintf(` @@ -323,7 +323,7 @@ data "aws_network_interface" "test" { `, rName)) } -func testAccNetworkInterfacePublicIPAssociationDataSourceConfig(rName string) string { +func testAccVPCNetworkInterfaceDataSourceConfig_publicIPAssociation(rName string) string { return acctest.ConfigCompose( testAccNetworkInterfaceBaseDataSourceConfig(rName), fmt.Sprintf(` @@ -354,7 +354,7 @@ data "aws_network_interface" "test" { `, rName)) } -func testAccNetworkInterfaceFiltersDataSourceConfig(rName string) string { +func testAccVPCNetworkInterfaceDataSourceConfig_filters(rName string) string { return acctest.ConfigCompose( testAccNetworkInterfaceBaseDataSourceConfig(rName), ` @@ -367,10 +367,10 @@ data "aws_network_interface" "test" { `) } -func testAccNetworkInterfaceAttachmentDataSourceConfig(rName string) string { +func testAccVPCNetworkInterfaceDataSourceConfig_attachment(rName string) string { return acctest.ConfigCompose( testAccNetworkInterfaceBaseDataSourceConfig(rName), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { diff --git a/internal/service/ec2/vpc_network_interface_sg_attachment_test.go b/internal/service/ec2/vpc_network_interface_sg_attachment_test.go index 41c640f861d..de4dd6f593d 100644 --- a/internal/service/ec2/vpc_network_interface_sg_attachment_test.go +++ b/internal/service/ec2/vpc_network_interface_sg_attachment_test.go @@ -27,7 +27,7 @@ func TestAccVPCNetworkInterfaceSgAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckNetworkInterfaceSGAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfaceSGAttachmentConfig(rName), + Config: testAccVPCNetworkInterfaceSGAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInterfaceSGAttachmentExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "network_interface_id", networkInterfaceResourceName, "id"), @@ -49,7 +49,7 @@ func TestAccVPCNetworkInterfaceSgAttachment_disappears(t *testing.T) { CheckDestroy: testAccCheckNetworkInterfaceSGAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfaceSGAttachmentConfig(rName), + Config: testAccVPCNetworkInterfaceSGAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInterfaceSGAttachmentExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNetworkInterfaceSGAttachment(), resourceName), @@ -73,7 +73,7 @@ func TestAccVPCNetworkInterfaceSgAttachment_instance(t *testing.T) { CheckDestroy: testAccCheckNetworkInterfaceSGAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfaceSGAttachmentViaInstanceConfig(rName), + Config: testAccVPCNetworkInterfaceSGAttachmentConfig_viaInstance(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInterfaceSGAttachmentExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "network_interface_id", instanceResourceName, "primary_network_interface_id"), @@ -103,7 +103,7 @@ func TestAccVPCNetworkInterfaceSgAttachment_multiple(t *testing.T) { CheckDestroy: testAccCheckNetworkInterfaceSGAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfaceSGAttachmentMultipleConfig(rName), + Config: testAccVPCNetworkInterfaceSGAttachmentConfig_multiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNetworkInterfaceSGAttachmentExists(resourceName1), resource.TestCheckResourceAttrPair(resourceName1, "network_interface_id", networkInterfaceResourceName, "id"), @@ -170,7 +170,7 @@ func testAccCheckNetworkInterfaceSGAttachmentDestroy(s *terraform.State) error { return nil } -func testAccNetworkInterfaceSGAttachmentConfig(rName string) string { +func testAccVPCNetworkInterfaceSGAttachmentConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" @@ -213,9 +213,9 @@ resource "aws_network_interface_sg_attachment" "test" { `, rName) } -func testAccNetworkInterfaceSGAttachmentViaInstanceConfig(rName string) string { +func testAccVPCNetworkInterfaceSGAttachmentConfig_viaInstance(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -264,7 +264,7 @@ resource "aws_network_interface_sg_attachment" "test" { `, rName)) } -func testAccNetworkInterfaceSGAttachmentMultipleConfig(rName string) string { +func testAccVPCNetworkInterfaceSGAttachmentConfig_multiple(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" diff --git a/internal/service/ec2/vpc_network_interface_test.go b/internal/service/ec2/vpc_network_interface_test.go index cf73c00ce63..cad19660258 100644 --- a/internal/service/ec2/vpc_network_interface_test.go +++ b/internal/service/ec2/vpc_network_interface_test.go @@ -33,7 +33,7 @@ func TestAccVPCNetworkInterface_basic(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`network-interface/.+$`)), @@ -76,7 +76,7 @@ func TestAccVPCNetworkInterface_ipv6(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIIPV6Config(rName), + Config: testAccVPCNetworkInterfaceConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", "1"), @@ -90,7 +90,7 @@ func TestAccVPCNetworkInterface_ipv6(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIIPV6MultipleConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_ipv6Multiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", "2"), @@ -98,7 +98,7 @@ func TestAccVPCNetworkInterface_ipv6(t *testing.T) { ), }, { - Config: testAccENIIPV6Config(rName), + Config: testAccVPCNetworkInterfaceConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", "1"), @@ -121,7 +121,7 @@ func TestAccVPCNetworkInterface_tags(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENITags1Config(rName, "key1", "value1"), + Config: testAccVPCNetworkInterfaceConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -135,7 +135,7 @@ func TestAccVPCNetworkInterface_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENITags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCNetworkInterfaceConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -144,7 +144,7 @@ func TestAccVPCNetworkInterface_tags(t *testing.T) { ), }, { - Config: testAccENITags1Config(rName, "key2", "value2"), + Config: testAccVPCNetworkInterfaceConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -167,7 +167,7 @@ func TestAccVPCNetworkInterface_ipv6Count(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIIPV6CountConfig(rName, 1), + Config: testAccVPCNetworkInterfaceConfig_ipv6Count(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", "1"), @@ -180,21 +180,21 @@ func TestAccVPCNetworkInterface_ipv6Count(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIIPV6CountConfig(rName, 2), + Config: testAccVPCNetworkInterfaceConfig_ipv6Count(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", "2"), ), }, { - Config: testAccENIIPV6CountConfig(rName, 0), + Config: testAccVPCNetworkInterfaceConfig_ipv6Count(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", "0"), ), }, { - Config: testAccENIIPV6CountConfig(rName, 1), + Config: testAccVPCNetworkInterfaceConfig_ipv6Count(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", "1"), @@ -216,7 +216,7 @@ func TestAccVPCNetworkInterface_disappears(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceNetworkInterface(), resourceName), @@ -241,7 +241,7 @@ func TestAccVPCNetworkInterface_description(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIDescriptionConfig(rName, "description 1"), + Config: testAccVPCNetworkInterfaceConfig_description(rName, "description 1"), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "attachment.#", "0"), @@ -270,7 +270,7 @@ func TestAccVPCNetworkInterface_description(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIDescriptionConfig(rName, "description 2"), + Config: testAccVPCNetworkInterfaceConfig_description(rName, "description 2"), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "attachment.#", "0"), @@ -312,7 +312,7 @@ func TestAccVPCNetworkInterface_attachment(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIAttachmentConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_attachment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "attachment.#", "1"), @@ -346,7 +346,7 @@ func TestAccVPCNetworkInterface_ignoreExternalAttachment(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIExternalAttachmentConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_externalAttachment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), testAccCheckENIMakeExternalAttachment("aws_instance.test", &conf), @@ -374,7 +374,7 @@ func TestAccVPCNetworkInterface_sourceDestCheck(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENISourceDestCheckConfig(rName, false), + Config: testAccVPCNetworkInterfaceConfig_sourceDestCheck(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "source_dest_check", "false"), @@ -387,14 +387,14 @@ func TestAccVPCNetworkInterface_sourceDestCheck(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENISourceDestCheckConfig(rName, true), + Config: testAccVPCNetworkInterfaceConfig_sourceDestCheck(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "source_dest_check", "true"), ), }, { - Config: testAccENISourceDestCheckConfig(rName, false), + Config: testAccVPCNetworkInterfaceConfig_sourceDestCheck(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "source_dest_check", "false"), @@ -416,7 +416,7 @@ func TestAccVPCNetworkInterface_privateIPsCount(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIPrivateIPsCountConfig(rName, 1), + Config: testAccVPCNetworkInterfaceConfig_privateIPsCount(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "private_ips_count", "1"), @@ -429,7 +429,7 @@ func TestAccVPCNetworkInterface_privateIPsCount(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIPrivateIPsCountConfig(rName, 2), + Config: testAccVPCNetworkInterfaceConfig_privateIPsCount(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "private_ips_count", "2"), @@ -442,7 +442,7 @@ func TestAccVPCNetworkInterface_privateIPsCount(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIPrivateIPsCountConfig(rName, 0), + Config: testAccVPCNetworkInterfaceConfig_privateIPsCount(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "private_ips_count", "0"), @@ -455,7 +455,7 @@ func TestAccVPCNetworkInterface_privateIPsCount(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIPrivateIPsCountConfig(rName, 1), + Config: testAccVPCNetworkInterfaceConfig_privateIPsCount(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "private_ips_count", "1"), @@ -483,7 +483,7 @@ func TestAccVPCNetworkInterface_ENIInterfaceType_efa(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIInterfaceTypeConfig(rName, "efa"), + Config: testAccVPCNetworkInterfaceConfig_type(rName, "efa"), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "interface_type", "efa"), @@ -511,7 +511,7 @@ func TestAccVPCNetworkInterface_ENI_ipv4Prefix(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIIPV4PrefixConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_ipv4Prefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", "1"), @@ -525,7 +525,7 @@ func TestAccVPCNetworkInterface_ENI_ipv4Prefix(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIIPV4PrefixMultipleConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", "2"), @@ -533,7 +533,7 @@ func TestAccVPCNetworkInterface_ENI_ipv4Prefix(t *testing.T) { ), }, { - Config: testAccENIIPV4PrefixConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_ipv4Prefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", "1"), @@ -556,7 +556,7 @@ func TestAccVPCNetworkInterface_ENI_ipv4PrefixCount(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIIPV4PrefixCountConfig(rName, 1), + Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixCount(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", "1"), @@ -569,21 +569,21 @@ func TestAccVPCNetworkInterface_ENI_ipv4PrefixCount(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIIPV4PrefixCountConfig(rName, 2), + Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixCount(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", "2"), ), }, { - Config: testAccENIIPV4PrefixCountConfig(rName, 0), + Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixCount(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", "0"), ), }, { - Config: testAccENIIPV4PrefixCountConfig(rName, 1), + Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixCount(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", "1"), @@ -605,7 +605,7 @@ func TestAccVPCNetworkInterface_ENI_ipv6Prefix(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIIPV6PrefixConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_ipv6Prefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", "1"), @@ -619,7 +619,7 @@ func TestAccVPCNetworkInterface_ENI_ipv6Prefix(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIIPV6PrefixMultipleConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", "2"), @@ -627,7 +627,7 @@ func TestAccVPCNetworkInterface_ENI_ipv6Prefix(t *testing.T) { ), }, { - Config: testAccENIIPV6PrefixConfig(rName), + Config: testAccVPCNetworkInterfaceConfig_ipv6Prefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", "1"), @@ -650,7 +650,7 @@ func TestAccVPCNetworkInterface_ENI_ipv6PrefixCount(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { - Config: testAccENIIPV6PrefixCountConfig(rName, 1), + Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixCount(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", "1"), @@ -663,21 +663,21 @@ func TestAccVPCNetworkInterface_ENI_ipv6PrefixCount(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { - Config: testAccENIIPV6PrefixCountConfig(rName, 2), + Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixCount(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", "2"), ), }, { - Config: testAccENIIPV6PrefixCountConfig(rName, 0), + Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixCount(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", "0"), ), }, { - Config: testAccENIIPV6PrefixCountConfig(rName, 1), + Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixCount(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", "1"), @@ -699,7 +699,7 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { // Configuration with three private_ips - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.44", "172.16.10.59", "172.16.10.123"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.44", "172.16.10.59", "172.16.10.123"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.59", "172.16.10.123"}, &networkInterface), @@ -713,7 +713,7 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { // Change order of private_ips - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.44", "172.16.10.59"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.44", "172.16.10.59"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.59", "172.16.10.123"}, &networkInterface), @@ -722,7 +722,7 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { ), }, { // Add secondaries to private_ips - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.12", "172.16.10.44", "172.16.10.59"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.12", "172.16.10.44", "172.16.10.59"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.12", "172.16.10.59", "172.16.10.123"}, &networkInterface), @@ -731,7 +731,7 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { ), }, { // Remove secondary to private_ips - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.44", "172.16.10.59"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.44", "172.16.10.59"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.59", "172.16.10.123"}, &networkInterface), @@ -740,7 +740,7 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { ), }, { // Remove primary - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.59", "172.16.10.57"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.59", "172.16.10.57"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.57", "172.16.10.59", "172.16.10.123"}, &networkInterface), @@ -749,7 +749,7 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { ), }, { // Use count to add IPs - Config: testAccENIConfig_privateIPSetCount(rName, 4), + Config: testAccVPCNetworkInterfaceConfig_privateIPSetCount(rName, 4), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same @@ -757,7 +757,7 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { ), }, { // Change list, retain primary - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.44", "172.16.10.57"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.44", "172.16.10.57"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.57"}, &networkInterface), @@ -766,7 +766,7 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { ), }, { // New list - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.17"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17"}, &networkInterface), @@ -794,7 +794,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { CheckDestroy: testAccCheckENIDestroy, Steps: []resource.TestStep{ { // Build a set incrementally in order - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.17"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17"}, &networkInterface), @@ -808,7 +808,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ImportStateVerifyIgnore: []string{"private_ip_list_enabled", "ipv6_address_list_enabled"}, }, { // Add to set - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.17", "172.16.10.45"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17", "172.16.10.45"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17", "172.16.10.45"}, &networkInterface), @@ -817,7 +817,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Add to set - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.17", "172.16.10.45", "172.16.10.89"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17", "172.16.10.45", "172.16.10.89"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17", "172.16.10.45", "172.16.10.89"}, &networkInterface), @@ -826,7 +826,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Add to set - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}, &networkInterface), @@ -835,7 +835,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Change from set to list using same order - Config: testAccENIConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}, &networkInterface), @@ -844,7 +844,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Change order of private_ip_list - Config: testAccENIConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.122"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.122"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.122"}, &networkInterface), @@ -853,7 +853,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Remove secondaries from end - Config: testAccENIConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.45"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.45"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.45"}, &networkInterface), @@ -862,7 +862,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Add secondaries to end - Config: testAccENIConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.123"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.123"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.123"}, &networkInterface), @@ -871,7 +871,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Add secondaries to middle - Config: testAccENIConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.77", "172.16.10.45", "172.16.10.123"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.77", "172.16.10.45", "172.16.10.123"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.77", "172.16.10.45", "172.16.10.123"}, &networkInterface), @@ -880,7 +880,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Remove secondaries from middle - Config: testAccENIConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.123"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.123"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.123"}, &networkInterface), @@ -889,7 +889,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Use count to add IPs - Config: testAccENIConfig_privateIPSetCount(rName, 4), + Config: testAccVPCNetworkInterfaceConfig_privateIPSetCount(rName, 4), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same @@ -897,7 +897,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Change to specific list - forces new - Config: testAccENIConfig_privateIPList(rName, []string{"172.16.10.59", "172.16.10.123", "172.16.10.38"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.59", "172.16.10.123", "172.16.10.38"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.59", "172.16.10.123", "172.16.10.38"}, &networkInterface), @@ -906,7 +906,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Change first of private_ip_list - forces new - Config: testAccENIConfig_privateIPList(rName, []string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}, &networkInterface), @@ -915,7 +915,7 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { ), }, { // Change from list to set using same set - Config: testAccENIConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}), + Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}), Check: resource.ComposeTestCheckFunc( testAccCheckENIExists(resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}, &networkInterface), @@ -1162,7 +1162,7 @@ resource "aws_security_group" "test" { `, rName)) } -func testAccENIConfig(rName string) string { +func testAccVPCNetworkInterfaceConfig_basic(rName string) string { return acctest.ConfigCompose(testAccENIIPV4BaseConfig(rName), ` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1170,7 +1170,7 @@ resource "aws_network_interface" "test" { `) } -func testAccENIIPV6Config(rName string) string { +func testAccVPCNetworkInterfaceConfig_ipv6(rName string) string { return acctest.ConfigCompose(testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1185,7 +1185,7 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccENIIPV6MultipleConfig(rName string) string { +func testAccVPCNetworkInterfaceConfig_ipv6Multiple(rName string) string { return acctest.ConfigCompose(testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1200,7 +1200,7 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccENIIPV6CountConfig(rName string, ipv6Count int) string { +func testAccVPCNetworkInterfaceConfig_ipv6Count(rName string, ipv6Count int) string { return acctest.ConfigCompose(testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1215,7 +1215,7 @@ resource "aws_network_interface" "test" { `, rName, ipv6Count)) } -func testAccENIDescriptionConfig(rName, description string) string { +func testAccVPCNetworkInterfaceConfig_description(rName, description string) string { return acctest.ConfigCompose(testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1230,7 +1230,7 @@ resource "aws_network_interface" "test" { `, rName, description)) } -func testAccENISourceDestCheckConfig(rName string, sourceDestCheck bool) string { +func testAccVPCNetworkInterfaceConfig_sourceDestCheck(rName string, sourceDestCheck bool) string { return acctest.ConfigCompose(testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1244,9 +1244,9 @@ resource "aws_network_interface" "test" { `, rName, sourceDestCheck)) } -func testAccENIAttachmentConfig(rName string) string { +func testAccVPCNetworkInterfaceConfig_attachment(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` @@ -1289,9 +1289,9 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccENIExternalAttachmentConfig(rName string) string { +func testAccVPCNetworkInterfaceConfig_externalAttachment(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.AvailableEC2InstanceTypeForRegion("t3.micro", "t2.micro"), testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` @@ -1329,7 +1329,7 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccENIPrivateIPsCountConfig(rName string, privateIpsCount int) string { +func testAccVPCNetworkInterfaceConfig_privateIPsCount(rName string, privateIpsCount int) string { return acctest.ConfigCompose(testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { private_ips_count = %[2]d @@ -1342,7 +1342,7 @@ resource "aws_network_interface" "test" { `, rName, privateIpsCount)) } -func testAccENITags1Config(rName, tagKey1, tagValue1 string) string { +func testAccVPCNetworkInterfaceConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1356,7 +1356,7 @@ resource "aws_network_interface" "test" { `, tagKey1, tagValue1)) } -func testAccENITags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCNetworkInterfaceConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1371,7 +1371,7 @@ resource "aws_network_interface" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccENIInterfaceTypeConfig(rName, interfaceType string) string { +func testAccVPCNetworkInterfaceConfig_type(rName, interfaceType string) string { return acctest.ConfigCompose(testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1386,7 +1386,7 @@ resource "aws_network_interface" "test" { `, rName, interfaceType)) } -func testAccENIIPV4PrefixConfig(rName string) string { +func testAccVPCNetworkInterfaceConfig_ipv4Prefix(rName string) string { return acctest.ConfigCompose(testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1400,7 +1400,7 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccENIIPV4PrefixMultipleConfig(rName string) string { +func testAccVPCNetworkInterfaceConfig_ipv4PrefixMultiple(rName string) string { return acctest.ConfigCompose(testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1414,7 +1414,7 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccENIIPV4PrefixCountConfig(rName string, ipv4PrefixCount int) string { +func testAccVPCNetworkInterfaceConfig_ipv4PrefixCount(rName string, ipv4PrefixCount int) string { return acctest.ConfigCompose(testAccENIIPV4BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1428,7 +1428,7 @@ resource "aws_network_interface" "test" { `, rName, ipv4PrefixCount)) } -func testAccENIIPV6PrefixConfig(rName string) string { +func testAccVPCNetworkInterfaceConfig_ipv6Prefix(rName string) string { return acctest.ConfigCompose(testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1443,7 +1443,7 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccENIIPV6PrefixMultipleConfig(rName string) string { +func testAccVPCNetworkInterfaceConfig_ipv6PrefixMultiple(rName string) string { return acctest.ConfigCompose(testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1458,7 +1458,7 @@ resource "aws_network_interface" "test" { `, rName)) } -func testAccENIIPV6PrefixCountConfig(rName string, ipv6PrefixCount int) string { +func testAccVPCNetworkInterfaceConfig_ipv6PrefixCount(rName string, ipv6PrefixCount int) string { return acctest.ConfigCompose(testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` resource "aws_network_interface" "test" { subnet_id = aws_subnet.test.id @@ -1473,7 +1473,7 @@ resource "aws_network_interface" "test" { `, rName, ipv6PrefixCount)) } -func testAccENIConfig_privateIPSet(rName string, privateIPs []string) string { +func testAccVPCNetworkInterfaceConfig_privateIPSet(rName string, privateIPs []string) string { return acctest.ConfigCompose( testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` @@ -1485,7 +1485,7 @@ resource "aws_network_interface" "test" { `, strings.Join(privateIPs, `", "`))) } -func testAccENIConfig_privateIPSetCount(rName string, count int) string { +func testAccVPCNetworkInterfaceConfig_privateIPSetCount(rName string, count int) string { return acctest.ConfigCompose( testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` @@ -1497,7 +1497,7 @@ resource "aws_network_interface" "test" { `, count)) } -func testAccENIConfig_privateIPList(rName string, privateIPs []string) string { +func testAccVPCNetworkInterfaceConfig_privateIPList(rName string, privateIPs []string) string { return acctest.ConfigCompose( testAccENIIPV6BaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/ec2/vpc_network_interfaces_data_source_test.go b/internal/service/ec2/vpc_network_interfaces_data_source_test.go index 3ec06cbfef7..679af82e480 100644 --- a/internal/service/ec2/vpc_network_interfaces_data_source_test.go +++ b/internal/service/ec2/vpc_network_interfaces_data_source_test.go @@ -20,7 +20,7 @@ func TestAccVPCNetworkInterfacesDataSource_filter(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfacesDataSourceConfig_Filter(rName), + Config: testAccVPCNetworkInterfacesDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_network_interfaces.test", "ids.#", "2"), ), @@ -39,7 +39,7 @@ func TestAccVPCNetworkInterfacesDataSource_tags(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfacesDataSourceConfig_Tags(rName), + Config: testAccVPCNetworkInterfacesDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_network_interfaces.test", "ids.#", "1"), ), @@ -58,7 +58,7 @@ func TestAccVPCNetworkInterfacesDataSource_empty(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccNetworkInterfacesDataSourceConfig_Empty(rName), + Config: testAccVPCNetworkInterfacesDataSourceConfig_empty(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_network_interfaces.test", "ids.#", "0"), ), @@ -104,7 +104,7 @@ resource "aws_network_interface" "test2" { `, rName) } -func testAccNetworkInterfacesDataSourceConfig_Filter(rName string) string { +func testAccVPCNetworkInterfacesDataSourceConfig_filter(rName string) string { return acctest.ConfigCompose(testAccNetworkInterfacesDataSourceConfig_Base(rName), ` data "aws_network_interfaces" "test" { filter { @@ -115,7 +115,7 @@ data "aws_network_interfaces" "test" { `) } -func testAccNetworkInterfacesDataSourceConfig_Tags(rName string) string { +func testAccVPCNetworkInterfacesDataSourceConfig_tags(rName string) string { return acctest.ConfigCompose(testAccNetworkInterfacesDataSourceConfig_Base(rName), ` data "aws_network_interfaces" "test" { tags = { @@ -125,7 +125,7 @@ data "aws_network_interfaces" "test" { `) } -func testAccNetworkInterfacesDataSourceConfig_Empty(rName string) string { +func testAccVPCNetworkInterfacesDataSourceConfig_empty(rName string) string { return fmt.Sprintf(` data "aws_network_interfaces" "test" { tags = { diff --git a/internal/service/ec2/vpc_peering_connection_accepter_test.go b/internal/service/ec2/vpc_peering_connection_accepter_test.go index 92c2488b80d..5a67400a58d 100644 --- a/internal/service/ec2/vpc_peering_connection_accepter_test.go +++ b/internal/service/ec2/vpc_peering_connection_accepter_test.go @@ -27,7 +27,7 @@ func TestAccVPCPeeringConnectionAccepter_sameRegionSameAccount(t *testing.T) { CheckDestroy: testAccVPCPeeringConnectionAccepterDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionAccepterSameRegionSameAccountConfig(rName), + Config: testAccVPCPeeringConnectionAccepterConfig_sameRegionSameAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists(resourceNameAccepter, &v), // The aws_vpc_peering_connection documentation says: @@ -55,7 +55,7 @@ func TestAccVPCPeeringConnectionAccepter_sameRegionSameAccount(t *testing.T) { ), }, { - Config: testAccVPCPeeringConnectionAccepterSameRegionSameAccountConfig(rName), + Config: testAccVPCPeeringConnectionAccepterConfig_sameRegionSameAccount(rName), ResourceName: resourceNameAccepter, ImportState: true, ImportStateVerify: true, @@ -84,7 +84,7 @@ func TestAccVPCPeeringConnectionAccepter_differentRegionSameAccount(t *testing.T CheckDestroy: testAccVPCPeeringConnectionAccepterDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionAccepterDifferentRegionSameAccountConfig(rName), + Config: testAccVPCPeeringConnectionAccepterConfig_differentRegionSameAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists(resourceNameConnection, &vMain), testAccCheckVPCPeeringConnectionExistsWithProvider(resourceNameAccepter, &vPeer, acctest.RegionProviderFunc(acctest.AlternateRegion(), &providers)), @@ -100,7 +100,7 @@ func TestAccVPCPeeringConnectionAccepter_differentRegionSameAccount(t *testing.T ), }, { - Config: testAccVPCPeeringConnectionAccepterDifferentRegionSameAccountConfig(rName), + Config: testAccVPCPeeringConnectionAccepterConfig_differentRegionSameAccount(rName), ResourceName: resourceNameAccepter, ImportState: true, ImportStateVerify: true, @@ -129,7 +129,7 @@ func TestAccVPCPeeringConnectionAccepter_sameRegionDifferentAccount(t *testing.T CheckDestroy: testAccVPCPeeringConnectionAccepterDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionAccepterSameRegionDifferentAccountConfig(rName), + Config: testAccVPCPeeringConnectionAccepterConfig_sameRegionDifferentAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists(resourceNameConnection, &v), resource.TestCheckResourceAttrPair(resourceNameConnection, "vpc_id", resourceNameMainVpc, "id"), @@ -167,7 +167,7 @@ func TestAccVPCPeeringConnectionAccepter_differentRegionDifferentAccount(t *test CheckDestroy: testAccVPCPeeringConnectionAccepterDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionAccepterDifferentRegionDifferentAccountConfig(rName), + Config: testAccVPCPeeringConnectionAccepterConfig_differentRegionDifferentAccount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists(resourceNameConnection, &v), resource.TestCheckResourceAttrPair(resourceNameConnection, "vpc_id", resourceNameMainVpc, "id"), @@ -190,7 +190,7 @@ func testAccVPCPeeringConnectionAccepterDestroy(s *terraform.State) error { return nil } -func testAccVPCPeeringConnectionAccepterSameRegionSameAccountConfig(rName string) string { +func testAccVPCPeeringConnectionAccepterConfig_sameRegionSameAccount(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" @@ -231,7 +231,7 @@ resource "aws_vpc_peering_connection_accepter" "peer" { `, rName) } -func testAccVPCPeeringConnectionAccepterDifferentRegionSameAccountConfig(rName string) string { +func testAccVPCPeeringConnectionAccepterConfig_differentRegionSameAccount(rName string) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" @@ -277,7 +277,7 @@ resource "aws_vpc_peering_connection_accepter" "peer" { `, rName, acctest.AlternateRegion())) } -func testAccVPCPeeringConnectionAccepterSameRegionDifferentAccountConfig(rName string) string { +func testAccVPCPeeringConnectionAccepterConfig_sameRegionDifferentAccount(rName string) string { return acctest.ConfigCompose(acctest.ConfigAlternateAccountProvider(), fmt.Sprintf(` resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" @@ -328,7 +328,7 @@ resource "aws_vpc_peering_connection_accepter" "peer" { `, rName, acctest.Region())) } -func testAccVPCPeeringConnectionAccepterDifferentRegionDifferentAccountConfig(rName string) string { +func testAccVPCPeeringConnectionAccepterConfig_differentRegionDifferentAccount(rName string) string { return acctest.ConfigCompose(testAccAlternateAccountAlternateRegionProviderConfig(), fmt.Sprintf(` resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/vpc_peering_connection_data_source_test.go b/internal/service/ec2/vpc_peering_connection_data_source_test.go index e1fcc30c46a..4a6727797c6 100644 --- a/internal/service/ec2/vpc_peering_connection_data_source_test.go +++ b/internal/service/ec2/vpc_peering_connection_data_source_test.go @@ -22,7 +22,7 @@ func TestAccVPCPeeringConnectionDataSource_cidrBlock(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionDataSourceCIDRBlockConfig(rName), + Config: testAccVPCPeeringConnectionDataSourceConfig_cidrBlock(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "cidr_block", requesterVpcResourceName, "cidr_block"), @@ -45,7 +45,7 @@ func TestAccVPCPeeringConnectionDataSource_id(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionDataSourceIDConfig(rName), + Config: testAccVPCPeeringConnectionDataSourceConfig_id(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), // resource.TestCheckResourceAttrPair(dataSourceName, "cidr_block", resourceName, "cidr_block"), // not in resource @@ -84,7 +84,7 @@ func TestAccVPCPeeringConnectionDataSource_peerCIDRBlock(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionDataSourcePeerCIDRBlockConfig(rName), + Config: testAccVPCPeeringConnectionDataSourceConfig_peerCIDRBlock(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "peer_cidr_block", accepterVpcResourceName, "cidr_block"), @@ -105,7 +105,7 @@ func TestAccVPCPeeringConnectionDataSource_peerVPCID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionDataSourcePeerVPCIDConfig(rName), + Config: testAccVPCPeeringConnectionDataSourceConfig_peerID(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "peer_vpc_id", resourceName, "peer_vpc_id"), @@ -126,7 +126,7 @@ func TestAccVPCPeeringConnectionDataSource_vpcID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionDataSourceVPCIDConfig(rName), + Config: testAccVPCPeeringConnectionDataSourceConfig_vpcID(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceName, "vpc_id", resourceName, "vpc_id"), @@ -136,7 +136,7 @@ func TestAccVPCPeeringConnectionDataSource_vpcID(t *testing.T) { }) } -func testAccVPCPeeringConnectionDataSourceCIDRBlockConfig(rName string) string { +func testAccVPCPeeringConnectionDataSourceConfig_cidrBlock(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "requester" { cidr_block = "10.250.0.0/16" # CIDR must be different than other tests @@ -176,7 +176,7 @@ data "aws_vpc_peering_connection" "test" { `, rName) } -func testAccVPCPeeringConnectionDataSourceIDConfig(rName string) string { +func testAccVPCPeeringConnectionDataSourceConfig_id(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "requester" { cidr_block = "10.1.0.0/16" @@ -210,7 +210,7 @@ data "aws_vpc_peering_connection" "test" { `, rName) } -func testAccVPCPeeringConnectionDataSourcePeerCIDRBlockConfig(rName string) string { +func testAccVPCPeeringConnectionDataSourceConfig_peerCIDRBlock(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "requester" { cidr_block = "10.252.0.0/16" # CIDR must be different than other tests @@ -250,7 +250,7 @@ data "aws_vpc_peering_connection" "test" { `, rName) } -func testAccVPCPeeringConnectionDataSourcePeerVPCIDConfig(rName string) string { +func testAccVPCPeeringConnectionDataSourceConfig_peerID(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "requester" { cidr_block = "10.1.0.0/16" @@ -284,7 +284,7 @@ data "aws_vpc_peering_connection" "test" { `, rName) } -func testAccVPCPeeringConnectionDataSourceVPCIDConfig(rName string) string { +func testAccVPCPeeringConnectionDataSourceConfig_vpcID(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "requester" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_peering_connection_options_test.go b/internal/service/ec2/vpc_peering_connection_options_test.go index eeb05df6382..27991cd5c68 100644 --- a/internal/service/ec2/vpc_peering_connection_options_test.go +++ b/internal/service/ec2/vpc_peering_connection_options_test.go @@ -28,7 +28,7 @@ func TestAccVPCPeeringConnectionOptions_basic(t *testing.T) { CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionOptionsSameRegionSameAccountConfig(rName, true, true), + Config: testAccVPCPeeringConnectionOptionsConfig_sameRegionSameAccount(rName, true, true), Check: resource.ComposeTestCheckFunc( // Requester's view: resource.TestCheckResourceAttr(resourceName, "requester.#", "1"), @@ -66,7 +66,7 @@ func TestAccVPCPeeringConnectionOptions_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPCPeeringConnectionOptionsSameRegionSameAccountConfig(rName, false, false), + Config: testAccVPCPeeringConnectionOptionsConfig_sameRegionSameAccount(rName, false, false), Check: resource.ComposeTestCheckFunc( // Requester's view: resource.TestCheckResourceAttr( @@ -122,7 +122,7 @@ func TestAccVPCPeeringConnectionOptions_differentRegionSameAccount(t *testing.T) CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionOptionsDifferentRegionSameAccountConfig(rName, true, true), + Config: testAccVPCPeeringConnectionOptionsConfig_differentRegionSameAccount(rName, true, true), Check: resource.ComposeTestCheckFunc( // Requester's view: resource.TestCheckResourceAttr(resourceName, "requester.#", "1"), @@ -156,13 +156,13 @@ func TestAccVPCPeeringConnectionOptions_differentRegionSameAccount(t *testing.T) ), }, { - Config: testAccVPCPeeringConnectionOptionsDifferentRegionSameAccountConfig(rName, true, true), + Config: testAccVPCPeeringConnectionOptionsConfig_differentRegionSameAccount(rName, true, true), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, { - Config: testAccVPCPeeringConnectionOptionsDifferentRegionSameAccountConfig(rName, false, false), + Config: testAccVPCPeeringConnectionOptionsConfig_differentRegionSameAccount(rName, false, false), Check: resource.ComposeTestCheckFunc( // Requester's view: resource.TestCheckResourceAttr( @@ -218,7 +218,7 @@ func TestAccVPCPeeringConnectionOptions_sameRegionDifferentAccount(t *testing.T) CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionOptionsSameRegionDifferentAccountConfig(rName), + Config: testAccVPCPeeringConnectionOptionsConfig_sameRegionDifferentAccount(rName), Check: resource.ComposeTestCheckFunc( // Requester's view: resource.TestCheckResourceAttr(resourceName, "requester.#", "1"), @@ -242,7 +242,7 @@ func TestAccVPCPeeringConnectionOptions_sameRegionDifferentAccount(t *testing.T) ), }, { - Config: testAccVPCPeeringConnectionOptionsSameRegionDifferentAccountConfig(rName), + Config: testAccVPCPeeringConnectionOptionsConfig_sameRegionDifferentAccount(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -287,7 +287,7 @@ func testAccCheckVPCPeeringConnectionOptionsWithProvider(n, block string, option } } -func testAccVPCPeeringConnectionOptionsSameRegionSameAccountConfig(rName string, accepterDnsResolution, requesterRemoteClassicLink bool) string { +func testAccVPCPeeringConnectionOptionsConfig_sameRegionSameAccount(rName string, accepterDnsResolution, requesterRemoteClassicLink bool) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -331,7 +331,7 @@ resource "aws_vpc_peering_connection_options" "test" { `, rName, accepterDnsResolution, requesterRemoteClassicLink) } -func testAccVPCPeeringConnectionOptionsDifferentRegionSameAccountConfig(rName string, dnsResolution, dnsResolutionPeer bool) string { +func testAccVPCPeeringConnectionOptionsConfig_differentRegionSameAccount(rName string, dnsResolution, dnsResolutionPeer bool) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -401,7 +401,7 @@ resource "aws_vpc_peering_connection_options" "peer" { `, rName, acctest.AlternateRegion(), dnsResolution, dnsResolutionPeer)) } -func testAccVPCPeeringConnectionOptionsSameRegionDifferentAccountConfig(rName string) string { +func testAccVPCPeeringConnectionOptionsConfig_sameRegionDifferentAccount(rName string) string { return acctest.ConfigCompose(acctest.ConfigAlternateAccountProvider(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/vpc_peering_connection_test.go b/internal/service/ec2/vpc_peering_connection_test.go index f9f253fe62c..c1e840185b1 100644 --- a/internal/service/ec2/vpc_peering_connection_test.go +++ b/internal/service/ec2/vpc_peering_connection_test.go @@ -30,7 +30,7 @@ func TestAccVPCPeeringConnection_basic(t *testing.T) { CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionConfig(rName), + Config: testAccVPCPeeringConnectionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -60,7 +60,7 @@ func TestAccVPCPeeringConnection_disappears(t *testing.T) { CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionConfig(rName), + Config: testAccVPCPeeringConnectionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPCPeeringConnection(), resourceName), @@ -83,7 +83,7 @@ func TestAccVPCPeeringConnection_tags(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionConfigTags1(rName, "key1", "value1"), + Config: testAccVPCPeeringConnectionConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -99,7 +99,7 @@ func TestAccVPCPeeringConnection_tags(t *testing.T) { }, }, { - Config: testAccVPCPeeringConnectionConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCPeeringConnectionConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -108,7 +108,7 @@ func TestAccVPCPeeringConnection_tags(t *testing.T) { ), }, { - Config: testAccVPCPeeringConnectionConfigTags1(rName, "key2", "value2"), + Config: testAccVPCPeeringConnectionConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -146,7 +146,7 @@ func TestAccVPCPeeringConnection_options(t *testing.T) { CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionAccepterRequesterOptionsConfig(rName), + Config: testAccVPCPeeringConnectionConfig_accepterRequesterOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists( resourceName, @@ -207,7 +207,7 @@ func TestAccVPCPeeringConnection_options(t *testing.T) { }, }, { - Config: testAccVPCPeeringConnectionAccepterRequesterOptionsConfig(rName), + Config: testAccVPCPeeringConnectionConfig_accepterRequesterOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists( resourceName, @@ -271,7 +271,7 @@ func TestAccVPCPeeringConnection_failedState(t *testing.T) { CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionFailedStateConfig(rName), + Config: testAccVPCPeeringConnectionConfig_failedState(rName), ExpectError: regexp.MustCompile(`unexpected state 'failed'`), }, }, @@ -292,7 +292,7 @@ func TestAccVPCPeeringConnection_peerRegionAutoAccept(t *testing.T) { CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionAlternateRegionAutoAcceptConfig(rName, true), + Config: testAccVPCPeeringConnectionConfig_alternateRegionAutoAccept(rName, true), ExpectError: regexp.MustCompile("`peer_region` cannot be set whilst `auto_accept` is `true` when creating an EC2 VPC Peering Connection"), }, }, @@ -315,7 +315,7 @@ func TestAccVPCPeeringConnection_region(t *testing.T) { CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionAlternateRegionAutoAcceptConfig(rName, false), + Config: testAccVPCPeeringConnectionConfig_alternateRegionAutoAccept(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists( resourceName, @@ -345,7 +345,7 @@ func TestAccVPCPeeringConnection_accept(t *testing.T) { CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionAutoAcceptConfig(rName, false), + Config: testAccVPCPeeringConnectionConfig_autoAccept(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists( resourceName, @@ -359,7 +359,7 @@ func TestAccVPCPeeringConnection_accept(t *testing.T) { ), }, { - Config: testAccVPCPeeringConnectionAutoAcceptConfig(rName, true), + Config: testAccVPCPeeringConnectionConfig_autoAccept(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists( resourceName, @@ -374,7 +374,7 @@ func TestAccVPCPeeringConnection_accept(t *testing.T) { }, // Tests that changing 'auto_accept' back to false keeps the connection active. { - Config: testAccVPCPeeringConnectionAutoAcceptConfig(rName, false), + Config: testAccVPCPeeringConnectionConfig_autoAccept(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckVPCPeeringConnectionExists( resourceName, @@ -410,7 +410,7 @@ func TestAccVPCPeeringConnection_optionsNoAutoAccept(t *testing.T) { CheckDestroy: testAccCheckVPCPeeringConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionAccepterRequesterOptionsNoAutoAcceptConfig(rName), + Config: testAccVPCPeeringConnectionConfig_accepterRequesterOptionsNoAutoAccept(rName), ExpectError: regexp.MustCompile(`is not active`), }, }, @@ -470,7 +470,7 @@ func testAccCheckVPCPeeringConnectionExistsWithProvider(n string, v *ec2.VpcPeer } } -func testAccVPCPeeringConnectionConfig(rName string) string { +func testAccVPCPeeringConnectionConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -496,7 +496,7 @@ resource "aws_vpc_peering_connection" "test" { `, rName) } -func testAccVPCPeeringConnectionConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccVPCPeeringConnectionConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -525,7 +525,7 @@ resource "aws_vpc_peering_connection" "test" { `, rName, tagKey1, tagValue1) } -func testAccVPCPeeringConnectionConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCPeeringConnectionConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -556,7 +556,7 @@ resource "aws_vpc_peering_connection" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccVPCPeeringConnectionAccepterRequesterOptionsConfig(rName string) string { +func testAccVPCPeeringConnectionConfig_accepterRequesterOptions(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -596,7 +596,7 @@ resource "aws_vpc_peering_connection" "test" { `, rName) } -func testAccVPCPeeringConnectionFailedStateConfig(rName string) string { +func testAccVPCPeeringConnectionConfig_failedState(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -625,7 +625,7 @@ resource "aws_vpc_peering_connection" "test" { `, rName) } -func testAccVPCPeeringConnectionAlternateRegionAutoAcceptConfig(rName string, autoAccept bool) string { +func testAccVPCPeeringConnectionConfig_alternateRegionAutoAccept(rName string, autoAccept bool) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -658,7 +658,7 @@ resource "aws_vpc_peering_connection" "test" { `, rName, autoAccept, acctest.AlternateRegion())) } -func testAccVPCPeeringConnectionAutoAcceptConfig(rName string, autoAccept bool) string { +func testAccVPCPeeringConnectionConfig_autoAccept(rName string, autoAccept bool) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -688,7 +688,7 @@ resource "aws_vpc_peering_connection" "test" { `, rName, autoAccept) } -func testAccVPCPeeringConnectionAccepterRequesterOptionsNoAutoAcceptConfig(rName string) string { +func testAccVPCPeeringConnectionConfig_accepterRequesterOptionsNoAutoAccept(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/vpc_peering_connections_data_source_test.go b/internal/service/ec2/vpc_peering_connections_data_source_test.go index 82911350614..f80b16ad93c 100644 --- a/internal/service/ec2/vpc_peering_connections_data_source_test.go +++ b/internal/service/ec2/vpc_peering_connections_data_source_test.go @@ -19,7 +19,7 @@ func TestAccVPCPeeringConnectionsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionsDataSourceConfig(rName), + Config: testAccVPCPeeringConnectionsDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_vpc_peering_connections.test_by_filters", "ids.#", "2"), ), @@ -37,7 +37,7 @@ func TestAccVPCPeeringConnectionsDataSource_NoMatches(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCPeeringConnectionsDataSourceConfig_NoMatches(rName), + Config: testAccVPCPeeringConnectionsDataSourceConfig_noMatches(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_vpc_peering_connections.test", "ids.#", "0"), ), @@ -46,7 +46,7 @@ func TestAccVPCPeeringConnectionsDataSource_NoMatches(t *testing.T) { }) } -func testAccVPCPeeringConnectionsDataSourceConfig(rName string) string { +func testAccVPCPeeringConnectionsDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "10.1.0.0/16" @@ -101,7 +101,7 @@ data "aws_vpc_peering_connections" "test_by_filters" { `, rName) } -func testAccVPCPeeringConnectionsDataSourceConfig_NoMatches(rName string) string { +func testAccVPCPeeringConnectionsDataSourceConfig_noMatches(rName string) string { return fmt.Sprintf(` data "aws_vpc_peering_connections" "test" { tags = { diff --git a/internal/service/ec2/vpc_prefix_list_data_source.go b/internal/service/ec2/vpc_prefix_list_data_source.go index c51198769a8..7becf31eb53 100644 --- a/internal/service/ec2/vpc_prefix_list_data_source.go +++ b/internal/service/ec2/vpc_prefix_list_data_source.go @@ -1,13 +1,11 @@ package ec2 import ( - "fmt" - "log" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func DataSourcePrefixList() *schema.Resource { @@ -15,21 +13,21 @@ func DataSourcePrefixList() *schema.Resource { Read: dataSourcePrefixListRead, Schema: map[string]*schema.Schema{ - "prefix_list_id": { - Type: schema.TypeString, - Optional: true, + "cidr_blocks": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, + "filter": CustomFiltersSchema(), "name": { Type: schema.TypeString, Optional: true, Computed: true, }, - "cidr_blocks": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, + "prefix_list_id": { + Type: schema.TypeString, + Optional: true, }, - "filter": DataSourceFiltersSchema(), }, } } @@ -37,36 +35,31 @@ func DataSourcePrefixList() *schema.Resource { func dataSourcePrefixListRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - filters, filtersOk := d.GetOk("filter") + input := &ec2.DescribePrefixListsInput{} - req := &ec2.DescribePrefixListsInput{} - if filtersOk { - req.Filters = BuildFiltersDataSource(filters.(*schema.Set)) + if v, ok := d.GetOk("name"); ok { + input.Filters = append(input.Filters, BuildAttributeFilterList(map[string]string{ + "prefix-list-name": v.(string), + })...) } - if prefixListID := d.Get("prefix_list_id"); prefixListID != "" { - req.PrefixListIds = aws.StringSlice([]string{prefixListID.(string)}) - } - if prefixListName := d.Get("name"); prefixListName.(string) != "" { - req.Filters = append(req.Filters, &ec2.Filter{ - Name: aws.String("prefix-list-name"), - Values: aws.StringSlice([]string{prefixListName.(string)}), - }) + + if v, ok := d.GetOk("prefix_list_id"); ok { + input.PrefixListIds = aws.StringSlice([]string{v.(string)}) } - log.Printf("[DEBUG] Reading Prefix List: %s", req) - resp, err := conn.DescribePrefixLists(req) + input.Filters = append(input.Filters, BuildCustomFilterList( + d.Get("filter").(*schema.Set), + )...) + + pl, err := FindPrefixList(conn, input) + if err != nil { - return err - } - if resp == nil || len(resp.PrefixLists) == 0 { - return fmt.Errorf("no matching prefix list found; the prefix list ID or name may be invalid or not exist in the current region") + return tfresource.SingularDataSourceFindError("EC2 Prefix List", err) } - pl := resp.PrefixLists[0] - d.SetId(aws.StringValue(pl.PrefixListId)) - d.Set("name", pl.PrefixListName) d.Set("cidr_blocks", aws.StringValueSlice(pl.Cidrs)) + d.Set("name", pl.PrefixListName) return nil } diff --git a/internal/service/ec2/vpc_prefix_list_data_source_test.go b/internal/service/ec2/vpc_prefix_list_data_source_test.go index 80f3fc5231a..32510ad23a6 100644 --- a/internal/service/ec2/vpc_prefix_list_data_source_test.go +++ b/internal/service/ec2/vpc_prefix_list_data_source_test.go @@ -1,31 +1,30 @@ package ec2_test import ( - "fmt" "regexp" - "strconv" "testing" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" - "github.com/hashicorp/terraform-provider-aws/internal/conns" - tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" ) func TestAccVPCPrefixListDataSource_basic(t *testing.T) { + ds1Name := "data.aws_prefix_list.s3_by_id" + ds2Name := "data.aws_prefix_list.s3_by_name" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPrefixListDataSourceConfig, + Config: testAccVPCPrefixListDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( - testAccPrefixListCheckDataSource("data.aws_prefix_list.s3_by_id"), - testAccPrefixListCheckDataSource("data.aws_prefix_list.s3_by_name"), + acctest.CheckResourceAttrGreaterThanValue(ds1Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttrSet(ds1Name, "name"), + acctest.CheckResourceAttrGreaterThanValue(ds2Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttrSet(ds2Name, "name"), ), }, }, @@ -33,16 +32,21 @@ func TestAccVPCPrefixListDataSource_basic(t *testing.T) { } func TestAccVPCPrefixListDataSource_filter(t *testing.T) { + ds1Name := "data.aws_prefix_list.s3_by_id" + ds2Name := "data.aws_prefix_list.s3_by_name" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPrefixListFilterDataSourceConfig, + Config: testAccVPCPrefixListDataSourceConfig_filter, Check: resource.ComposeTestCheckFunc( - testAccPrefixListCheckDataSource("data.aws_prefix_list.s3_by_id"), - testAccPrefixListCheckDataSource("data.aws_prefix_list.s3_by_name"), + acctest.CheckResourceAttrGreaterThanValue(ds1Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttrSet(ds1Name, "name"), + acctest.CheckResourceAttrGreaterThanValue(ds2Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttrSet(ds2Name, "name"), ), }, }, @@ -56,71 +60,14 @@ func TestAccVPCPrefixListDataSource_nameDoesNotOverrideFilter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPrefixListDataSourceConfig_nameDoesNotOverrideFilter, - ExpectError: regexp.MustCompile(`no matching prefix list found`), + Config: testAccVPCPrefixListDataSourceConfig_nameDoesNotOverrideFilter, + ExpectError: regexp.MustCompile(`no matching EC2 Prefix List found`), }, }, }) } -func testAccPrefixListCheckDataSource(name string) resource.TestCheckFunc { - getPrefixListId := func(name string) (string, error) { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - - input := ec2.DescribePrefixListsInput{ - Filters: tfec2.BuildAttributeFilterList(map[string]string{ - "prefix-list-name": name, - }), - } - - output, err := conn.DescribePrefixLists(&input) - if err != nil { - return "", err - } - - if len(output.PrefixLists) != 1 { - return "", fmt.Errorf("prefix list %s not found", name) - } - - return aws.StringValue(output.PrefixLists[0].PrefixListId), nil - } - - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("root module has no resource called %s", name) - } - - attr := rs.Primary.Attributes - - region := acctest.Region() - prefixListName := fmt.Sprintf("com.amazonaws.%s.s3", region) - prefixListId, err := getPrefixListId(prefixListName) - if err != nil { - return err - } - - if attr["name"] != prefixListName { - return fmt.Errorf("bad name %s", attr["name"]) - } - if attr["id"] != prefixListId { - return fmt.Errorf("bad id %s", attr["id"]) - } - - var cidrBlockSize int - - if cidrBlockSize, err = strconv.Atoi(attr["cidr_blocks.#"]); err != nil { - return err - } - if cidrBlockSize < 1 { - return fmt.Errorf("cidr_blocks seem suspiciously low: %d", cidrBlockSize) - } - - return nil - } -} - -const testAccPrefixListDataSourceConfig = ` +const testAccVPCPrefixListDataSourceConfig_basic = ` data "aws_region" "current" {} data "aws_prefix_list" "s3_by_id" { @@ -132,7 +79,7 @@ data "aws_prefix_list" "s3_by_name" { } ` -const testAccPrefixListFilterDataSourceConfig = ` +const testAccVPCPrefixListDataSourceConfig_filter = ` data "aws_region" "current" {} data "aws_prefix_list" "s3_by_name" { @@ -150,7 +97,7 @@ data "aws_prefix_list" "s3_by_id" { } ` -const testAccPrefixListDataSourceConfig_nameDoesNotOverrideFilter = ` +const testAccVPCPrefixListDataSourceConfig_nameDoesNotOverrideFilter = ` data "aws_region" "current" {} data "aws_prefix_list" "test" { diff --git a/internal/service/ec2/vpc_route_data_source_test.go b/internal/service/ec2/vpc_route_data_source_test.go index 9fa1acd111c..8a45df2497f 100644 --- a/internal/service/ec2/vpc_route_data_source_test.go +++ b/internal/service/ec2/vpc_route_data_source_test.go @@ -26,7 +26,7 @@ func TestAccVPCRouteDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRouteBasicDataSourceConfig(rName), + Config: testAccVPCRouteDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( // By destination CIDR. resource.TestCheckResourceAttrPair(datasource1Name, "destination_cidr_block", instanceRouteResourceName, "destination_cidr_block"), @@ -58,7 +58,7 @@ func TestAccVPCRouteDataSource_transitGatewayID(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4TransitGatewayDataSourceConfig(rName), + Config: testAccVPCRouteDataSourceConfig_ipv4TransitGateway(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "destination_cidr_block", dataSourceName, "destination_cidr_block"), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", dataSourceName, "route_table_id"), @@ -81,7 +81,7 @@ func TestAccVPCRouteDataSource_ipv6DestinationCIDR(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6EgressOnlyInternetGatewayDataSourceConfig(rName), + Config: testAccVPCRouteDataSourceConfig_ipv6EgressOnlyInternetGateway(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "destination_ipv6_cidr_block", dataSourceName, "destination_ipv6_cidr_block"), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", dataSourceName, "route_table_id"), @@ -103,7 +103,7 @@ func TestAccVPCRouteDataSource_localGatewayID(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4LocalGatewayDataSourceConfig(rName), + Config: testAccVPCRouteDataSourceConfig_ipv4LocalGateway(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "destination_cidr_block", dataSourceName, "destination_cidr_block"), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", dataSourceName, "route_table_id"), @@ -126,7 +126,7 @@ func TestAccVPCRouteDataSource_carrierGatewayID(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4CarrierGatewayDataSourceConfig(rName), + Config: testAccVPCRouteDataSourceConfig_ipv4CarrierGateway(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "destination_cidr_block", dataSourceName, "destination_cidr_block"), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", dataSourceName, "route_table_id"), @@ -149,7 +149,7 @@ func TestAccVPCRouteDataSource_destinationPrefixListID(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListNatGatewayDataSourceConfig(rName), + Config: testAccVPCRouteDataSourceConfig_prefixListNATGateway(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "destination_prefix_list_id", dataSourceName, "destination_prefix_list_id"), resource.TestCheckResourceAttrPair(resourceName, "nat_gateway_id", dataSourceName, "nat_gateway_id"), @@ -174,7 +174,7 @@ func TestAccVPCRouteDataSource_gatewayVPCEndpoint(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteGatewayVPCEndpointNoDataSourceDataSourceConfig(rName), + Config: testAccVPCRouteDataSourceConfig_gatewayEndpointNo(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(rtResourceName, &routeTable), testAccCheckVPCEndpointExists(vpceResourceName, &vpce), @@ -182,16 +182,16 @@ func TestAccVPCRouteDataSource_gatewayVPCEndpoint(t *testing.T) { ), }, { - Config: testAccRouteGatewayVPCEndpointWithDataSourceDataSourceConfig(rName), + Config: testAccVPCRouteDataSourceConfig_gatewayEndpoint(rName), ExpectError: regexp.MustCompile(`No routes matching supplied arguments found in Route Table`), }, }, }) } -func testAccRouteBasicDataSourceConfig(rName string) string { +func testAccVPCRouteDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptInDefaultExclude(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), fmt.Sprintf(` @@ -272,7 +272,7 @@ data "aws_route" "by_destination_cidr_block" { `, rName)) } -func testAccRouteIPv4TransitGatewayDataSourceConfig(rName string) string { +func testAccVPCRouteDataSourceConfig_ipv4TransitGateway(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` @@ -323,7 +323,7 @@ data "aws_route" "test" { `, rName)) } -func testAccRouteIPv6EgressOnlyInternetGatewayDataSourceConfig(rName string) string { +func testAccVPCRouteDataSourceConfig_ipv6EgressOnlyInternetGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -362,7 +362,7 @@ data "aws_route" "test" { `, rName) } -func testAccRouteIPv4LocalGatewayDataSourceConfig(rName string) string { +func testAccVPCRouteDataSourceConfig_ipv4LocalGateway(rName string) string { return fmt.Sprintf(` data "aws_ec2_local_gateways" "all" {} @@ -416,7 +416,7 @@ data "aws_route" "by_local_gateway_id" { `, rName) } -func testAccRouteIPv4CarrierGatewayDataSourceConfig(rName string) string { +func testAccVPCRouteDataSourceConfig_ipv4CarrierGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -455,7 +455,7 @@ data "aws_route" "test" { `, rName) } -func testAccRoutePrefixListNatGatewayDataSourceConfig(rName string) string { +func testAccVPCRouteDataSourceConfig_prefixListNATGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -531,7 +531,7 @@ data "aws_route" "test" { `, rName) } -func testAccRouteGatewayVPCEndpointNoDataSourceDataSourceConfig(rName string) string { +func testAccVPCRouteDataSourceConfig_gatewayEndpointNo(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -559,8 +559,8 @@ resource "aws_route_table" "test" { `, rName) } -func testAccRouteGatewayVPCEndpointWithDataSourceDataSourceConfig(rName string) string { - return acctest.ConfigCompose(testAccRouteGatewayVPCEndpointNoDataSourceDataSourceConfig(rName), ` +func testAccVPCRouteDataSourceConfig_gatewayEndpoint(rName string) string { + return acctest.ConfigCompose(testAccVPCRouteDataSourceConfig_gatewayEndpointNo(rName), ` data "aws_prefix_list" "test" { name = aws_vpc_endpoint.test.service_name } diff --git a/internal/service/ec2/vpc_route_table_association_test.go b/internal/service/ec2/vpc_route_table_association_test.go index 35e2561e111..badefe1e435 100644 --- a/internal/service/ec2/vpc_route_table_association_test.go +++ b/internal/service/ec2/vpc_route_table_association_test.go @@ -28,7 +28,7 @@ func TestAccVPCRouteTableAssociation_Subnet_basic(t *testing.T) { CheckDestroy: testAccCheckRouteTableAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableAssociationConfigSubnet(rName), + Config: testAccVPCRouteTableAssociationConfig_subnet(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableAssociationExists(resourceName, &rta), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", resourceNameRouteTable, "id"), @@ -60,7 +60,7 @@ func TestAccVPCRouteTableAssociation_Subnet_changeRouteTable(t *testing.T) { CheckDestroy: testAccCheckRouteTableAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableAssociationConfigSubnet(rName), + Config: testAccVPCRouteTableAssociationConfig_subnet(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableAssociationExists(resourceName, &rta), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", resourceNameRouteTable1, "id"), @@ -68,7 +68,7 @@ func TestAccVPCRouteTableAssociation_Subnet_changeRouteTable(t *testing.T) { ), }, { - Config: testAccRouteTableAssociationConfigSubnetChangeRouteTable(rName), + Config: testAccVPCRouteTableAssociationConfig_subnetChange(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableAssociationExists(resourceName, &rta), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", resourceNameRouteTable2, "id"), @@ -93,7 +93,7 @@ func TestAccVPCRouteTableAssociation_Gateway_basic(t *testing.T) { CheckDestroy: testAccCheckRouteTableAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableAssociationConfigGateway(rName), + Config: testAccVPCRouteTableAssociationConfig_gateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableAssociationExists(resourceName, &rta), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", resourceNameRouteTable, "id"), @@ -125,7 +125,7 @@ func TestAccVPCRouteTableAssociation_Gateway_changeRouteTable(t *testing.T) { CheckDestroy: testAccCheckRouteTableAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableAssociationConfigGateway(rName), + Config: testAccVPCRouteTableAssociationConfig_gateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableAssociationExists(resourceName, &rta), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", resourceNameRouteTable1, "id"), @@ -133,7 +133,7 @@ func TestAccVPCRouteTableAssociation_Gateway_changeRouteTable(t *testing.T) { ), }, { - Config: testAccRouteTableAssociationConfigGatewayChangeRouteTable(rName), + Config: testAccVPCRouteTableAssociationConfig_gatewayChange(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableAssociationExists(resourceName, &rta), resource.TestCheckResourceAttrPair(resourceName, "route_table_id", resourceNameRouteTable2, "id"), @@ -156,7 +156,7 @@ func TestAccVPCRouteTableAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckRouteTableAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableAssociationConfigSubnet(rName), + Config: testAccVPCRouteTableAssociationConfig_subnet(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableAssociationExists(resourceName, &rta), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceRouteTableAssociation(), resourceName), @@ -261,7 +261,7 @@ resource "aws_internet_gateway" "test" { `, rName) } -func testAccRouteTableAssociationConfigSubnet(rName string) string { +func testAccVPCRouteTableAssociationConfig_subnet(rName string) string { return acctest.ConfigCompose(testAccRouteTableAssociationConfigBaseVPC(rName), fmt.Sprintf(` resource "aws_route_table" "test" { vpc_id = aws_vpc.test.id @@ -283,7 +283,7 @@ resource "aws_route_table_association" "test" { `, rName)) } -func testAccRouteTableAssociationConfigSubnetChangeRouteTable(rName string) string { +func testAccVPCRouteTableAssociationConfig_subnetChange(rName string) string { return acctest.ConfigCompose(testAccRouteTableAssociationConfigBaseVPC(rName), fmt.Sprintf(` resource "aws_route_table" "test2" { vpc_id = aws_vpc.test.id @@ -305,7 +305,7 @@ resource "aws_route_table_association" "test" { `, rName)) } -func testAccRouteTableAssociationConfigGateway(rName string) string { +func testAccVPCRouteTableAssociationConfig_gateway(rName string) string { return acctest.ConfigCompose(testAccRouteTableAssociationConfigBaseVPC(rName), fmt.Sprintf(` resource "aws_route_table" "test" { vpc_id = aws_vpc.test.id @@ -335,7 +335,7 @@ resource "aws_route_table_association" "test" { `, rName)) } -func testAccRouteTableAssociationConfigGatewayChangeRouteTable(rName string) string { +func testAccVPCRouteTableAssociationConfig_gatewayChange(rName string) string { return acctest.ConfigCompose(testAccRouteTableAssociationConfigBaseVPC(rName), fmt.Sprintf(` resource "aws_route_table" "test2" { vpc_id = aws_vpc.test.id diff --git a/internal/service/ec2/vpc_route_table_data_source_test.go b/internal/service/ec2/vpc_route_table_data_source_test.go index cadfc4a6dae..177a67e0494 100644 --- a/internal/service/ec2/vpc_route_table_data_source_test.go +++ b/internal/service/ec2/vpc_route_table_data_source_test.go @@ -30,7 +30,7 @@ func TestAccVPCRouteTableDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRouteTableBasicDataSourceConfig(rName), + Config: testAccVPCRouteTableDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( // By tags. acctest.MatchResourceAttrRegionalARN(datasource1Name, "arn", "ec2", regexp.MustCompile(`route-table/.+$`)), @@ -108,7 +108,7 @@ func TestAccVPCRouteTableDataSource_main(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRouteTableMainDataSourceConfig(rName), + Config: testAccVPCRouteTableDataSourceConfig_main(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(datasourceName, "id"), resource.TestCheckResourceAttrSet(datasourceName, "vpc_id"), @@ -165,7 +165,7 @@ func testAccCheckListHasSomeElementAttrPair(nameFirst string, resourceAttr strin } } -func testAccRouteTableBasicDataSourceConfig(rName string) string { +func testAccVPCRouteTableDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" @@ -247,7 +247,7 @@ data "aws_route_table" "by_id" { `, rName) } -func testAccRouteTableMainDataSourceConfig(rName string) string { +func testAccVPCRouteTableDataSourceConfig_main(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" diff --git a/internal/service/ec2/vpc_route_table_test.go b/internal/service/ec2/vpc_route_table_test.go index 11c3b0eff10..1afb5b0973d 100644 --- a/internal/service/ec2/vpc_route_table_test.go +++ b/internal/service/ec2/vpc_route_table_test.go @@ -29,7 +29,7 @@ func TestAccVPCRouteTable_basic(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableBasicConfig(rName), + Config: testAccVPCRouteTableConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), @@ -61,7 +61,7 @@ func TestAccVPCRouteTable_disappears(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableBasicConfig(rName), + Config: testAccVPCRouteTableConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceRouteTable(), resourceName), @@ -84,7 +84,7 @@ func TestAccVPCRouteTable_Disappears_subnetAssociation(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableSubnetAssociationConfig(rName), + Config: testAccVPCRouteTableConfig_subnetAssociation(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceRouteTable(), resourceName), @@ -110,7 +110,7 @@ func TestAccVPCRouteTable_ipv4ToInternetGateway(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableIPv4InternetGatewayConfig(rName, destinationCidr1, destinationCidr2), + Config: testAccVPCRouteTableConfig_ipv4InternetGateway(rName, destinationCidr1, destinationCidr2), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -125,7 +125,7 @@ func TestAccVPCRouteTable_ipv4ToInternetGateway(t *testing.T) { ), }, { - Config: testAccRouteTableIPv4InternetGatewayConfig(rName, destinationCidr2, destinationCidr2), + Config: testAccVPCRouteTableConfig_ipv4InternetGateway(rName, destinationCidr1, destinationCidr2), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -133,7 +133,7 @@ func TestAccVPCRouteTable_ipv4ToInternetGateway(t *testing.T) { acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), resource.TestCheckResourceAttr(resourceName, "propagating_vgws.#", "0"), resource.TestCheckResourceAttr(resourceName, "route.#", "2"), - testAccCheckRouteTableRoute(resourceName, "cidr_block", destinationCidr2, "gateway_id", igwResourceName, "id"), + testAccCheckRouteTableRoute(resourceName, "cidr_block", destinationCidr1, "gateway_id", igwResourceName, "id"), testAccCheckRouteTableRoute(resourceName, "cidr_block", destinationCidr2, "gateway_id", igwResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), @@ -161,7 +161,7 @@ func TestAccVPCRouteTable_ipv4ToInstance(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableIPv4InstanceConfig(rName, destinationCidr), + Config: testAccVPCRouteTableConfig_ipv4Instance(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -196,7 +196,7 @@ func TestAccVPCRouteTable_ipv6ToEgressOnlyInternetGateway(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableIPv6EgressOnlyInternetGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteTableConfig_ipv6EgressOnlyInternetGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -216,7 +216,7 @@ func TestAccVPCRouteTable_ipv6ToEgressOnlyInternetGateway(t *testing.T) { }, { // Verify that expanded form of the destination CIDR causes no diff. - Config: testAccRouteTableIPv6EgressOnlyInternetGatewayConfig(rName, "::0/0"), + Config: testAccVPCRouteTableConfig_ipv6EgressOnlyInternetGateway(rName, "::0/0"), PlanOnly: true, }, }, @@ -235,7 +235,7 @@ func TestAccVPCRouteTable_tags(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableTags1Config(rName, "key1", "value1"), + Config: testAccVPCRouteTableConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -248,7 +248,7 @@ func TestAccVPCRouteTable_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRouteTableTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCRouteTableConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -257,7 +257,7 @@ func TestAccVPCRouteTable_tags(t *testing.T) { ), }, { - Config: testAccRouteTableTags1Config(rName, "key2", "value2"), + Config: testAccVPCRouteTableConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -282,7 +282,7 @@ func TestAccVPCRouteTable_requireRouteDestination(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableConfigNoDestination(rName), + Config: testAccVPCRouteTableConfig_noDestination(rName), ExpectError: regexp.MustCompile("error creating route: one of `cidr_block"), }, }, @@ -299,7 +299,7 @@ func TestAccVPCRouteTable_requireRouteTarget(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableConfigNoTarget(rName), + Config: testAccVPCRouteTableConfig_noTarget(rName), ExpectError: regexp.MustCompile(`error creating route: one of .*\begress_only_gateway_id\b`), }, }, @@ -321,7 +321,7 @@ func TestAccVPCRouteTable_Route_mode(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableIPv4InternetGatewayConfig(rName, destinationCidr1, destinationCidr2), + Config: testAccVPCRouteTableConfig_ipv4InternetGateway(rName, destinationCidr1, destinationCidr2), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -341,7 +341,7 @@ func TestAccVPCRouteTable_Route_mode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRouteTableRouteModeNoBlocksConfig(rName), + Config: testAccVPCRouteTableConfig_modeNoBlocks(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -361,7 +361,7 @@ func TestAccVPCRouteTable_Route_mode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRouteTableRouteModeZeroedConfig(rName), + Config: testAccVPCRouteTableConfig_modeZeroed(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), @@ -400,7 +400,7 @@ func TestAccVPCRouteTable_ipv4ToTransitGateway(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableIPv4TransitGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteTableConfig_ipv4TransitGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -440,7 +440,7 @@ func TestAccVPCRouteTable_ipv4ToVPCEndpoint(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableRouteIPv4VPCEndpointIDConfig(rName, destinationCidr), + Config: testAccVPCRouteTableConfig_ipv4EndpointID(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -476,7 +476,7 @@ func TestAccVPCRouteTable_ipv4ToCarrierGateway(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableIPv4CarrierGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteTableConfig_ipv4CarrierGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -512,7 +512,7 @@ func TestAccVPCRouteTable_ipv4ToLocalGateway(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableRouteIPv4LocalGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteTableConfig_ipv4LocalGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -548,7 +548,7 @@ func TestAccVPCRouteTable_ipv4ToVPCPeeringConnection(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableIPv4VPCPeeringConnectionConfig(rName, destinationCidr), + Config: testAccVPCRouteTableConfig_ipv4PeeringConnection(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -584,7 +584,7 @@ func TestAccVPCRouteTable_vgwRoutePropagation(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableConfig_vgwRoutePropagation(rName, vgwResourceName1), + Config: testAccVPCRouteTableConfig_vgwPropagation(rName, vgwResourceName1), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), @@ -598,7 +598,7 @@ func TestAccVPCRouteTable_vgwRoutePropagation(t *testing.T) { ), }, { - Config: testAccRouteTableConfig_vgwRoutePropagation(rName, vgwResourceName2), + Config: testAccVPCRouteTableConfig_vgwPropagation(rName, vgwResourceName2), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), @@ -635,14 +635,14 @@ func TestAccVPCRouteTable_conditionalCIDRBlock(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr, false), + Config: testAccVPCRouteTableConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr, false), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableRoute(resourceName, "cidr_block", destinationCidr, "gateway_id", igwResourceName, "id"), ), }, { - Config: testAccRouteTableConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr, true), + Config: testAccVPCRouteTableConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr, true), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableRoute(resourceName, "ipv6_cidr_block", destinationIpv6Cidr, "gateway_id", igwResourceName, "id"), @@ -671,7 +671,7 @@ func TestAccVPCRouteTable_ipv4ToNatGateway(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableIPv4NatGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteTableConfig_ipv4NATGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -707,7 +707,7 @@ func TestAccVPCRouteTable_IPv6ToNetworkInterface_unattached(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableIPv6NetworkInterfaceUnattachedConfig(rName, destinationCidr), + Config: testAccVPCRouteTableConfig_ipv6NetworkInterfaceUnattached(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -745,7 +745,7 @@ func TestAccVPCRouteTable_IPv4ToNetworkInterfaces_unattached(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableBasicConfig(rName), + Config: testAccVPCRouteTableConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), @@ -757,7 +757,7 @@ func TestAccVPCRouteTable_IPv4ToNetworkInterfaces_unattached(t *testing.T) { ), }, { - Config: testAccRouteTableIPv4TwoNetworkInterfacesUnattachedConfig(rName, destinationCidr1, destinationCidr2), + Config: testAccVPCRouteTableConfig_ipv4TwoNetworkInterfacesUnattached(rName, destinationCidr1, destinationCidr2), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -777,7 +777,7 @@ func TestAccVPCRouteTable_IPv4ToNetworkInterfaces_unattached(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRouteTableIPv4TwoNetworkInterfacesUnattachedConfig(rName, destinationCidr2, destinationCidr1), + Config: testAccVPCRouteTableConfig_ipv4TwoNetworkInterfacesUnattached(rName, destinationCidr2, destinationCidr1), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -792,7 +792,7 @@ func TestAccVPCRouteTable_IPv4ToNetworkInterfaces_unattached(t *testing.T) { ), }, { - Config: testAccRouteTableRouteModeZeroedConfig(rName), + Config: testAccVPCRouteTableConfig_modeZeroed(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), @@ -820,7 +820,7 @@ func TestAccVPCRouteTable_vpcMultipleCIDRs(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableVPCMultipleCIDRsConfig(rName), + Config: testAccVPCRouteTableConfig_multipleCIDRs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -853,7 +853,7 @@ func TestAccVPCRouteTable_vpcClassicLink(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableVPCClassicLinkConfig(rName), + Config: testAccVPCRouteTableConfig_classicLink(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -888,7 +888,7 @@ func TestAccVPCRouteTable_gatewayVPCEndpoint(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableGatewayVPCEndpointConfig(rName), + Config: testAccVPCRouteTableConfig_gatewayEndpoint(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckVPCEndpointExists(vpceResourceName, &vpce), @@ -931,7 +931,7 @@ func TestAccVPCRouteTable_multipleRoutes(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTableMultipleRoutesConfig(rName, + Config: testAccVPCRouteTableConfig_multiples(rName, "cidr_block", destinationCidr1, "gateway_id", igwResourceName, "ipv6_cidr_block", destinationCidr3, "egress_only_gateway_id", eoigwResourceName), Check: resource.ComposeTestCheckFunc( @@ -948,7 +948,7 @@ func TestAccVPCRouteTable_multipleRoutes(t *testing.T) { ), }, { - Config: testAccRouteTableMultipleRoutesConfig(rName, + Config: testAccVPCRouteTableConfig_multiples(rName, "cidr_block", destinationCidr1, "vpc_peering_connection_id", pcxResourceName, "ipv6_cidr_block", destinationCidr3, "egress_only_gateway_id", eoigwResourceName), Check: resource.ComposeTestCheckFunc( @@ -965,7 +965,7 @@ func TestAccVPCRouteTable_multipleRoutes(t *testing.T) { ), }, { - Config: testAccRouteTableMultipleRoutesConfig(rName, + Config: testAccVPCRouteTableConfig_multiples(rName, "ipv6_cidr_block", destinationCidr3, "vpc_peering_connection_id", pcxResourceName, "cidr_block", destinationCidr2, "gateway_id", igwResourceName), Check: resource.ComposeTestCheckFunc( @@ -1004,7 +1004,7 @@ func TestAccVPCRouteTable_prefixListToInternetGateway(t *testing.T) { CheckDestroy: testAccCheckRouteTableDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTablePrefixListInternetGatewayConfig(rName), + Config: testAccVPCRouteTableConfig_prefixListInternetGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -1178,7 +1178,7 @@ func testAccCheckRouteTableWaitForVPCEndpointRoute(routeTable *ec2.RouteTable, v } } -func testAccRouteTableBasicConfig(rName string) string { +func testAccVPCRouteTableConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1194,7 +1194,7 @@ resource "aws_route_table" "test" { `, rName) } -func testAccRouteTableSubnetAssociationConfig(rName string) string { +func testAccVPCRouteTableConfig_subnetAssociation(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1229,7 +1229,7 @@ resource "aws_route_table_association" "test" { `, rName)) } -func testAccRouteTableIPv4InternetGatewayConfig(rName, destinationCidr1, destinationCidr2 string) string { +func testAccVPCRouteTableConfig_ipv4InternetGateway(rName, destinationCidr1, destinationCidr2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1267,7 +1267,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr1, destinationCidr2) } -func testAccRouteTableIPv6EgressOnlyInternetGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteTableConfig_ipv6EgressOnlyInternetGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1301,7 +1301,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr) } -func testAccRouteTableIPv4InstanceConfig(rName, destinationCidr string) string { +func testAccVPCRouteTableConfig_ipv4Instance(rName, destinationCidr string) string { return acctest.ConfigCompose( testAccLatestAmazonNatInstanceAMIConfig(), acctest.ConfigAvailableAZsNoOptIn(), @@ -1337,7 +1337,7 @@ resource "aws_instance" "test" { `, rName, destinationCidr)) } -func testAccRouteTableTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccVPCRouteTableConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1357,7 +1357,7 @@ resource "aws_route_table" "test" { `, rName, tagKey1, tagValue1) } -func testAccRouteTableTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCRouteTableConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1378,7 +1378,7 @@ resource "aws_route_table" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccRouteTableIPv4VPCPeeringConnectionConfig(rName, destinationCidr string) string { +func testAccVPCRouteTableConfig_ipv4PeeringConnection(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1421,7 +1421,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr) } -func testAccRouteTableConfig_vgwRoutePropagation(rName, vgwResourceName string) string { +func testAccVPCRouteTableConfig_vgwPropagation(rName, vgwResourceName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1460,11 +1460,11 @@ resource "aws_route_table" "test" { `, rName, vgwResourceName) } -func testAccRouteTableConfigNoDestination(rName string) string { +func testAccVPCRouteTableConfig_noDestination(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1496,7 +1496,7 @@ resource "aws_instance" "test" { `, rName)) } -func testAccRouteTableConfigNoTarget(rName string) string { +func testAccVPCRouteTableConfig_noTarget(rName string) string { return fmt.Sprintf(` resource "aws_route_table" "test" { vpc_id = aws_vpc.test.id @@ -1520,7 +1520,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccRouteTableRouteModeNoBlocksConfig(rName string) string { +func testAccVPCRouteTableConfig_modeNoBlocks(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1548,7 +1548,7 @@ resource "aws_route_table" "test" { `, rName) } -func testAccRouteTableRouteModeZeroedConfig(rName string) string { +func testAccVPCRouteTableConfig_modeZeroed(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1578,7 +1578,7 @@ resource "aws_route_table" "test" { `, rName) } -func testAccRouteTableIPv4TransitGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteTableConfig_ipv4TransitGateway(rName, destinationCidr string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1629,7 +1629,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr)) } -func testAccRouteTableRouteIPv4VPCEndpointIDConfig(rName, destinationCidr string) string { +func testAccVPCRouteTableConfig_ipv4EndpointID(rName, destinationCidr string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1698,7 +1698,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr)) } -func testAccRouteTableIPv4CarrierGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteTableConfig_ipv4CarrierGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1731,7 +1731,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr) } -func testAccRouteTableRouteIPv4LocalGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteTableConfig_ipv4LocalGateway(rName, destinationCidr string) string { return fmt.Sprintf(` data "aws_ec2_local_gateways" "all" {} @@ -1788,7 +1788,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr) } -func testAccRouteTableConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr string, ipv6Route bool) string { +func testAccVPCRouteTableConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr string, ipv6Route bool) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1830,7 +1830,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr, destinationIpv6Cidr, ipv6Route) } -func testAccRouteTableIPv4NatGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteTableConfig_ipv4NATGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1893,7 +1893,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr) } -func testAccRouteTableIPv6NetworkInterfaceUnattachedConfig(rName, destinationCidr string) string { +func testAccVPCRouteTableConfig_ipv6NetworkInterfaceUnattached(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1937,7 +1937,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr) } -func testAccRouteTableIPv4TwoNetworkInterfacesUnattachedConfig(rName, destinationCidr1, destinationCidr2 string) string { +func testAccVPCRouteTableConfig_ipv4TwoNetworkInterfacesUnattached(rName, destinationCidr1, destinationCidr2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1992,7 +1992,7 @@ resource "aws_route_table" "test" { `, rName, destinationCidr1, destinationCidr2) } -func testAccRouteTableVPCMultipleCIDRsConfig(rName string) string { +func testAccVPCRouteTableConfig_multipleCIDRs(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2017,7 +2017,7 @@ resource "aws_route_table" "test" { `, rName) } -func testAccRouteTableVPCClassicLinkConfig(rName string) string { +func testAccVPCRouteTableConfig_classicLink(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2038,7 +2038,7 @@ resource "aws_route_table" "test" { `, rName) } -func testAccRouteTableGatewayVPCEndpointConfig(rName string) string { +func testAccVPCRouteTableConfig_gatewayEndpoint(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2066,7 +2066,7 @@ resource "aws_vpc_endpoint" "test" { `, rName) } -func testAccRouteTableMultipleRoutesConfig(rName, +func testAccVPCRouteTableConfig_multiples(rName, destinationAttr1, destinationValue1, targetAttribute1, targetValue1, destinationAttr2, destinationValue2, targetAttribute2, targetValue2 string) string { return acctest.ConfigCompose( @@ -2202,7 +2202,7 @@ data "aws_ami" "amzn-ami-nat-instance" { ` } -func testAccRouteTablePrefixListInternetGatewayConfig(rName string) string { +func testAccVPCRouteTableConfig_prefixListInternetGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_route_tables_data_source_test.go b/internal/service/ec2/vpc_route_tables_data_source_test.go index 04d769976e2..5c98ff1184c 100644 --- a/internal/service/ec2/vpc_route_tables_data_source_test.go +++ b/internal/service/ec2/vpc_route_tables_data_source_test.go @@ -20,7 +20,7 @@ func TestAccVPCRouteTablesDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteTablesDataSourceConfig(rName), + Config: testAccVPCRouteTablesDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr("data.aws_route_tables.by_vpc_id", "ids.#", "2"), // Add the default route table. resource.TestCheckResourceAttr("data.aws_route_tables.by_tags", "ids.#", "2"), @@ -32,7 +32,7 @@ func TestAccVPCRouteTablesDataSource_basic(t *testing.T) { }) } -func testAccRouteTablesDataSourceConfig(rName string) string { +func testAccVPCRouteTablesDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "172.16.0.0/16" diff --git a/internal/service/ec2/vpc_route_test.go b/internal/service/ec2/vpc_route_test.go index 3b5ad08925b..221b169316a 100644 --- a/internal/service/ec2/vpc_route_test.go +++ b/internal/service/ec2/vpc_route_test.go @@ -32,7 +32,7 @@ func TestAccVPCRoute_basic(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4InternetGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4InternetGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(rtResourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 2), @@ -79,7 +79,7 @@ func TestAccVPCRoute_disappears(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4InternetGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4InternetGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceRoute(), resourceName), @@ -104,7 +104,7 @@ func TestAccVPCRoute_Disappears_routeTable(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4InternetGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4InternetGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceRouteTable(), rtResourceName), @@ -129,7 +129,7 @@ func TestAccVPCRoute_ipv6ToEgressOnlyInternetGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6EgressOnlyInternetGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv6EgressOnlyInternetGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -159,7 +159,7 @@ func TestAccVPCRoute_ipv6ToEgressOnlyInternetGateway(t *testing.T) { }, { // Verify that expanded form of the destination CIDR causes no diff. - Config: testAccRouteIPv6EgressOnlyInternetGatewayConfig(rName, "::0/0"), + Config: testAccVPCRouteConfig_ipv6EgressOnlyInternetGateway(rName, "::0/0"), PlanOnly: true, }, }, @@ -180,7 +180,7 @@ func TestAccVPCRoute_ipv6ToInternetGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6InternetGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv6InternetGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -226,7 +226,7 @@ func TestAccVPCRoute_ipv6ToInstance(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6InstanceConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv6Instance(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -272,7 +272,7 @@ func TestAccVPCRoute_IPv6ToNetworkInterface_unattached(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6NetworkInterfaceUnattachedConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv6NetworkInterfaceUnattached(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -318,7 +318,7 @@ func TestAccVPCRoute_ipv6ToVPCPeeringConnection(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6VPCPeeringConnectionConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv6PeeringConnection(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -364,7 +364,7 @@ func TestAccVPCRoute_ipv6ToVPNGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6VPNGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv6VPNGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -410,7 +410,7 @@ func TestAccVPCRoute_ipv4ToVPNGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4VPNGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4VPNGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -456,7 +456,7 @@ func TestAccVPCRoute_ipv4ToInstance(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4InstanceConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4Instance(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -502,7 +502,7 @@ func TestAccVPCRoute_IPv4ToNetworkInterface_unattached(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4NetworkInterfaceUnattachedConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4NetworkInterfaceUnattached(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -549,7 +549,7 @@ func TestAccVPCRoute_IPv4ToNetworkInterface_attached(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4NetworkInterfaceAttachedConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4NetworkInterfaceAttached(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -597,7 +597,7 @@ func TestAccVPCRoute_IPv4ToNetworkInterface_twoAttachments(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4NetworkInterfaceTwoAttachmentsConfig(rName, destinationCidr, eni1ResourceName), + Config: testAccVPCRouteConfig_ipv4NetworkInterfaceTwoAttachments(rName, destinationCidr, eni1ResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -620,7 +620,7 @@ func TestAccVPCRoute_IPv4ToNetworkInterface_twoAttachments(t *testing.T) { ), }, { - Config: testAccRouteIPv4NetworkInterfaceTwoAttachmentsConfig(rName, destinationCidr, eni2ResourceName), + Config: testAccVPCRouteConfig_ipv4NetworkInterfaceTwoAttachments(rName, destinationCidr, eni2ResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -666,7 +666,7 @@ func TestAccVPCRoute_ipv4ToVPCPeeringConnection(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4VPCPeeringConnectionConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4PeeringConnection(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -712,7 +712,7 @@ func TestAccVPCRoute_ipv4ToNatGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4NatGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4NATGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -758,7 +758,7 @@ func TestAccVPCRoute_ipv6ToNatGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6NatGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv6NATGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -804,7 +804,7 @@ func TestAccVPCRoute_doesNotCrashWithVPCEndpoint(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteWithVPCEndpointConfig(rName), + Config: testAccVPCRouteConfig_endpoint(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(rtResourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 3), @@ -839,7 +839,7 @@ func TestAccVPCRoute_ipv4ToTransitGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4TransitGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4TransitGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -889,7 +889,7 @@ func TestAccVPCRoute_ipv6ToTransitGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6TransitGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv6TransitGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -935,7 +935,7 @@ func TestAccVPCRoute_ipv4ToCarrierGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4CarrierGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_ipv4CarrierGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttrPair(resourceName, "carrier_gateway_id", cgwResourceName, "id"), @@ -981,7 +981,7 @@ func TestAccVPCRoute_ipv4ToLocalGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteResourceIPv4LocalGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_resourceIPv4LocalGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1027,7 +1027,7 @@ func TestAccVPCRoute_ipv6ToLocalGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteResourceIPv6LocalGatewayConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_resourceIPv6LocalGateway(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1073,7 +1073,7 @@ func TestAccVPCRoute_conditionalCIDRBlock(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr, false), + Config: testAccVPCRouteConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr, false), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", destinationCidr), @@ -1081,7 +1081,7 @@ func TestAccVPCRoute_conditionalCIDRBlock(t *testing.T) { ), }, { - Config: testAccRouteConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr, true), + Config: testAccVPCRouteConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr, true), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", ""), @@ -1123,7 +1123,7 @@ func TestAccVPCRoute_IPv4Update_target(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4FlexiTargetConfig(rName, destinationCidr, "instance_id", instanceResourceName), + Config: testAccVPCRouteConfig_ipv4FlexiTarget(rName, destinationCidr, "instance_id", instanceResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1146,7 +1146,7 @@ func TestAccVPCRoute_IPv4Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv4FlexiTargetConfig(rName, destinationCidr, "gateway_id", vgwResourceName), + Config: testAccVPCRouteConfig_ipv4FlexiTarget(rName, destinationCidr, "gateway_id", vgwResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1169,7 +1169,7 @@ func TestAccVPCRoute_IPv4Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv4FlexiTargetConfig(rName, destinationCidr, "gateway_id", igwResourceName), + Config: testAccVPCRouteConfig_ipv4FlexiTarget(rName, destinationCidr, "gateway_id", igwResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1192,7 +1192,7 @@ func TestAccVPCRoute_IPv4Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv4FlexiTargetConfig(rName, destinationCidr, "nat_gateway_id", ngwResourceName), + Config: testAccVPCRouteConfig_ipv4FlexiTarget(rName, destinationCidr, "nat_gateway_id", ngwResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1215,7 +1215,7 @@ func TestAccVPCRoute_IPv4Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv4FlexiTargetConfig(rName, destinationCidr, "network_interface_id", eniResourceName), + Config: testAccVPCRouteConfig_ipv4FlexiTarget(rName, destinationCidr, "network_interface_id", eniResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1239,7 +1239,7 @@ func TestAccVPCRoute_IPv4Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv4FlexiTargetConfig(rName, destinationCidr, "transit_gateway_id", tgwResourceName), + Config: testAccVPCRouteConfig_ipv4FlexiTarget(rName, destinationCidr, "transit_gateway_id", tgwResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1262,7 +1262,7 @@ func TestAccVPCRoute_IPv4Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv4FlexiTargetConfig(rName, destinationCidr, "vpc_endpoint_id", vpcEndpointResourceName), + Config: testAccVPCRouteConfig_ipv4FlexiTarget(rName, destinationCidr, "vpc_endpoint_id", vpcEndpointResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1285,7 +1285,7 @@ func TestAccVPCRoute_IPv4Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv4FlexiTargetConfig(rName, destinationCidr, "vpc_peering_connection_id", pcxResourceName), + Config: testAccVPCRouteConfig_ipv4FlexiTarget(rName, destinationCidr, "vpc_peering_connection_id", pcxResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1340,7 +1340,7 @@ func TestAccVPCRoute_IPv6Update_target(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv6FlexiTargetConfig(rName, destinationCidr, "instance_id", instanceResourceName), + Config: testAccVPCRouteConfig_ipv6FlexiTarget(rName, destinationCidr, "instance_id", instanceResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1363,7 +1363,7 @@ func TestAccVPCRoute_IPv6Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv6FlexiTargetConfig(rName, destinationCidr, "gateway_id", vgwResourceName), + Config: testAccVPCRouteConfig_ipv6FlexiTarget(rName, destinationCidr, "gateway_id", vgwResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1386,7 +1386,7 @@ func TestAccVPCRoute_IPv6Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv6FlexiTargetConfig(rName, destinationCidr, "gateway_id", igwResourceName), + Config: testAccVPCRouteConfig_ipv6FlexiTarget(rName, destinationCidr, "gateway_id", igwResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1409,7 +1409,7 @@ func TestAccVPCRoute_IPv6Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv6FlexiTargetConfig(rName, destinationCidr, "egress_only_gateway_id", eoigwResourceName), + Config: testAccVPCRouteConfig_ipv6FlexiTarget(rName, destinationCidr, "egress_only_gateway_id", eoigwResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1432,7 +1432,7 @@ func TestAccVPCRoute_IPv6Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv6FlexiTargetConfig(rName, destinationCidr, "network_interface_id", eniResourceName), + Config: testAccVPCRouteConfig_ipv6FlexiTarget(rName, destinationCidr, "network_interface_id", eniResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1455,7 +1455,7 @@ func TestAccVPCRoute_IPv6Update_target(t *testing.T) { ), }, { - Config: testAccRouteIPv6FlexiTargetConfig(rName, destinationCidr, "vpc_peering_connection_id", pcxResourceName), + Config: testAccVPCRouteConfig_ipv6FlexiTarget(rName, destinationCidr, "vpc_peering_connection_id", pcxResourceName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1505,7 +1505,7 @@ func TestAccVPCRoute_ipv4ToVPCEndpoint(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteResourceIPv4VPCEndpointConfig(rName, destinationCidr), + Config: testAccVPCRouteConfig_resourceIPv4Endpoint(rName, destinationCidr), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1553,7 +1553,7 @@ func TestAccVPCRoute_localRoute(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRouteIPv4NoRouteConfig(rName), + Config: testAccVPCRouteConfig_ipv4NoRoute(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(vpcResourceName, &vpc), testAccCheckRouteTableExists(rtResourceName, &routeTable), @@ -1561,7 +1561,7 @@ func TestAccVPCRoute_localRoute(t *testing.T) { ), }, { - Config: testAccRouteIPv4LocalRouteConfig(rName), + Config: testAccVPCRouteConfig_ipv4Local(rName), ResourceName: resourceName, ImportState: true, ImportStateIdFunc: func(rt *ec2.RouteTable, v *ec2.Vpc) resource.ImportStateIdFunc { @@ -1591,7 +1591,7 @@ func TestAccVPCRoute_prefixListToInternetGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListInternetGatewayConfig(rName), + Config: testAccVPCRouteConfig_prefixListInternetGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1637,7 +1637,7 @@ func TestAccVPCRoute_prefixListToVPNGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListVPNGatewayConfig(rName), + Config: testAccVPCRouteConfig_prefixListVPNGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1683,7 +1683,7 @@ func TestAccVPCRoute_prefixListToInstance(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListInstanceConfig(rName), + Config: testAccVPCRouteConfig_prefixListInstance(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1729,7 +1729,7 @@ func TestAccVPCRoute_PrefixListToNetworkInterface_unattached(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListNetworkInterfaceUnattachedConfig(rName), + Config: testAccVPCRouteConfig_prefixListNetworkInterfaceUnattached(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1776,7 +1776,7 @@ func TestAccVPCRoute_PrefixListToNetworkInterface_attached(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListNetworkInterfaceAttachedConfig(rName), + Config: testAccVPCRouteConfig_prefixListNetworkInterfaceAttached(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1822,7 +1822,7 @@ func TestAccVPCRoute_prefixListToVPCPeeringConnection(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListVPCPeeringConnectionConfig(rName), + Config: testAccVPCRouteConfig_prefixListPeeringConnection(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1868,7 +1868,7 @@ func TestAccVPCRoute_prefixListToNatGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListNatGatewayConfig(rName), + Config: testAccVPCRouteConfig_prefixListNATGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1918,7 +1918,7 @@ func TestAccVPCRoute_prefixListToTransitGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListTransitGatewayConfig(rName), + Config: testAccVPCRouteConfig_prefixListTransitGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -1968,7 +1968,7 @@ func TestAccVPCRoute_prefixListToCarrierGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListCarrierGatewayConfig(rName), + Config: testAccVPCRouteConfig_prefixListCarrierGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttrPair(resourceName, "carrier_gateway_id", cgwResourceName, "id"), @@ -2018,7 +2018,7 @@ func TestAccVPCRoute_prefixListToLocalGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListLocalGatewayConfig(rName), + Config: testAccVPCRouteConfig_prefixListLocalGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -2064,7 +2064,7 @@ func TestAccVPCRoute_prefixListToEgressOnlyInternetGateway(t *testing.T) { CheckDestroy: testAccCheckRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutePrefixListEgressOnlyInternetGatewayConfig(rName), + Config: testAccVPCRouteConfig_prefixListEgressOnlyInternetGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteExists(resourceName, &route), resource.TestCheckResourceAttr(resourceName, "carrier_gateway_id", ""), @@ -2179,7 +2179,7 @@ func testAccRouteImportStateIdFunc(resourceName string) resource.ImportStateIdFu } } -func testAccRouteIPv4InternetGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv4InternetGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2213,7 +2213,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteIPv6InternetGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv6InternetGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2256,7 +2256,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteIPv6NetworkInterfaceUnattachedConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv6NetworkInterfaceUnattached(rName, destinationCidr string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2304,7 +2304,7 @@ resource "aws_route" "test" { `, rName, destinationCidr)) } -func testAccRouteIPv6InstanceConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv6Instance(rName, destinationCidr string) string { return acctest.ConfigCompose( testAccLatestAmazonNatInstanceAMIConfig(), acctest.ConfigAvailableAZsNoOptIn(), @@ -2358,7 +2358,7 @@ resource "aws_route" "test" { `, rName, destinationCidr)) } -func testAccRouteIPv6VPCPeeringConnectionConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv6PeeringConnection(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2404,7 +2404,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteIPv6EgressOnlyInternetGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv6EgressOnlyInternetGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2439,7 +2439,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteWithVPCEndpointConfig(rName string) string { +func testAccVPCRouteConfig_endpoint(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2484,7 +2484,7 @@ resource "aws_vpc_endpoint" "test" { `, rName) } -func testAccRouteIPv4TransitGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv4TransitGateway(rName, destinationCidr string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` @@ -2538,7 +2538,7 @@ resource "aws_route" "test" { `, rName, destinationCidr)) } -func testAccRouteIPv6TransitGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv6TransitGateway(rName, destinationCidr string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2593,7 +2593,7 @@ resource "aws_route" "test" { `, rName, destinationCidr)) } -func testAccRouteConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr string, ipv6Route bool) string { +func testAccVPCRouteConfig_conditionalIPv4IPv6(rName, destinationCidr, destinationIpv6Cidr string, ipv6Route bool) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2636,7 +2636,7 @@ resource "aws_route" "test" { `, rName, destinationCidr, destinationIpv6Cidr, ipv6Route) } -func testAccRouteIPv4InstanceConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv4Instance(rName, destinationCidr string) string { return acctest.ConfigCompose( testAccLatestAmazonNatInstanceAMIConfig(), acctest.ConfigAvailableAZsNoOptIn(), @@ -2686,7 +2686,7 @@ resource "aws_route" "test" { `, rName, destinationCidr)) } -func testAccRouteIPv4NetworkInterfaceUnattachedConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv4NetworkInterfaceUnattached(rName, destinationCidr string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2732,7 +2732,7 @@ resource "aws_route" "test" { `, rName, destinationCidr)) } -func testAccRouteResourceIPv4LocalGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_resourceIPv4LocalGateway(rName, destinationCidr string) string { return fmt.Sprintf(` data "aws_ec2_local_gateways" "all" {} @@ -2781,7 +2781,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteResourceIPv6LocalGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_resourceIPv6LocalGateway(rName, destinationCidr string) string { return fmt.Sprintf(` data "aws_ec2_local_gateways" "all" {} @@ -2831,7 +2831,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteIPv4NetworkInterfaceAttachedConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv4NetworkInterfaceAttached(rName, destinationCidr string) string { return acctest.ConfigCompose( testAccLatestAmazonNatInstanceAMIConfig(), acctest.ConfigAvailableAZsNoOptIn(), @@ -2896,7 +2896,7 @@ resource "aws_route" "test" { `, rName, destinationCidr)) } -func testAccRouteIPv4NetworkInterfaceTwoAttachmentsConfig(rName, destinationCidr, targetResourceName string) string { +func testAccVPCRouteConfig_ipv4NetworkInterfaceTwoAttachments(rName, destinationCidr, targetResourceName string) string { return acctest.ConfigCompose( testAccLatestAmazonNatInstanceAMIConfig(), acctest.ConfigAvailableAZsNoOptIn(), @@ -2974,7 +2974,7 @@ resource "aws_route" "test" { `, rName, destinationCidr, targetResourceName)) } -func testAccRouteIPv4VPCPeeringConnectionConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv4PeeringConnection(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3018,7 +3018,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteIPv4NatGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv4NATGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3082,7 +3082,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteIPv6NatGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv6NATGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3131,7 +3131,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteIPv4VPNGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv4VPNGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3165,7 +3165,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteIPv6VPNGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv6VPNGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3200,7 +3200,7 @@ resource "aws_route" "test" { `, rName, destinationCidr) } -func testAccRouteResourceIPv4VPCEndpointConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_resourceIPv4Endpoint(rName, destinationCidr string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -3270,9 +3270,9 @@ resource "aws_route" "test" { `, rName, destinationCidr)) } -func testAccRouteIPv4FlexiTargetConfig(rName, destinationCidr, targetAttribute, targetValue string) string { +func testAccVPCRouteConfig_ipv4FlexiTarget(rName, destinationCidr, targetAttribute, targetValue string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptInDefaultExclude(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), fmt.Sprintf(` @@ -3445,9 +3445,9 @@ resource "aws_route" "test" { `, rName, destinationCidr, targetAttribute, targetValue)) } -func testAccRouteIPv6FlexiTargetConfig(rName, destinationCidr, targetAttribute, targetValue string) string { +func testAccVPCRouteConfig_ipv6FlexiTarget(rName, destinationCidr, targetAttribute, targetValue string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), acctest.ConfigAvailableAZsNoOptIn(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), fmt.Sprintf(` @@ -3566,7 +3566,7 @@ resource "aws_route" "test" { `, rName, destinationCidr, targetAttribute, targetValue)) } -func testAccRouteIPv4NoRouteConfig(rName string) string { +func testAccVPCRouteConfig_ipv4NoRoute(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3586,9 +3586,9 @@ resource "aws_route_table" "test" { `, rName) } -func testAccRouteIPv4LocalRouteConfig(rName string) string { +func testAccVPCRouteConfig_ipv4Local(rName string) string { return acctest.ConfigCompose( - testAccRouteIPv4NoRouteConfig(rName), + testAccVPCRouteConfig_ipv4NoRoute(rName), ` resource "aws_route" "test" { route_table_id = aws_route_table.test.id @@ -3598,7 +3598,7 @@ resource "aws_route" "test" { `) } -func testAccRoutePrefixListInternetGatewayConfig(rName string) string { +func testAccVPCRouteConfig_prefixListInternetGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3638,7 +3638,7 @@ resource "aws_route" "test" { `, rName) } -func testAccRoutePrefixListVPNGatewayConfig(rName string) string { +func testAccVPCRouteConfig_prefixListVPNGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3678,7 +3678,7 @@ resource "aws_route" "test" { `, rName) } -func testAccRoutePrefixListInstanceConfig(rName string) string { +func testAccVPCRouteConfig_prefixListInstance(rName string) string { return acctest.ConfigCompose( testAccLatestAmazonNatInstanceAMIConfig(), acctest.ConfigAvailableAZsNoOptIn(), @@ -3734,7 +3734,7 @@ resource "aws_route" "test" { `, rName)) } -func testAccRoutePrefixListNetworkInterfaceUnattachedConfig(rName string) string { +func testAccVPCRouteConfig_prefixListNetworkInterfaceUnattached(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -3786,7 +3786,7 @@ resource "aws_route" "test" { `, rName)) } -func testAccRoutePrefixListNetworkInterfaceAttachedConfig(rName string) string { +func testAccVPCRouteConfig_prefixListNetworkInterfaceAttached(rName string) string { return acctest.ConfigCompose( testAccLatestAmazonNatInstanceAMIConfig(), acctest.ConfigAvailableAZsNoOptIn(), @@ -3857,7 +3857,7 @@ resource "aws_route" "test" { `, rName)) } -func testAccRoutePrefixListVPCPeeringConnectionConfig(rName string) string { +func testAccVPCRouteConfig_prefixListPeeringConnection(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3907,7 +3907,7 @@ resource "aws_route" "test" { `, rName) } -func testAccRoutePrefixListNatGatewayConfig(rName string) string { +func testAccVPCRouteConfig_prefixListNATGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3977,7 +3977,7 @@ resource "aws_route" "test" { `, rName) } -func testAccRoutePrefixListTransitGatewayConfig(rName string) string { +func testAccVPCRouteConfig_prefixListTransitGateway(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` @@ -4037,7 +4037,7 @@ resource "aws_route" "test" { `, rName)) } -func testAccRoutePrefixListCarrierGatewayConfig(rName string) string { +func testAccVPCRouteConfig_prefixListCarrierGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -4077,7 +4077,7 @@ resource "aws_route" "test" { `, rName) } -func testAccRoutePrefixListLocalGatewayConfig(rName string) string { +func testAccVPCRouteConfig_prefixListLocalGateway(rName string) string { return fmt.Sprintf(` data "aws_ec2_local_gateways" "all" {} @@ -4132,7 +4132,7 @@ resource "aws_route" "test" { `, rName) } -func testAccRoutePrefixListEgressOnlyInternetGatewayConfig(rName string) string { +func testAccVPCRouteConfig_prefixListEgressOnlyInternetGateway(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -4173,7 +4173,7 @@ resource "aws_route" "test" { `, rName) } -func testAccRouteIPv4CarrierGatewayConfig(rName, destinationCidr string) string { +func testAccVPCRouteConfig_ipv4CarrierGateway(rName, destinationCidr string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_security_group_data_source_test.go b/internal/service/ec2/vpc_security_group_data_source_test.go index a767cf352c7..7b239a54a1a 100644 --- a/internal/service/ec2/vpc_security_group_data_source_test.go +++ b/internal/service/ec2/vpc_security_group_data_source_test.go @@ -20,7 +20,7 @@ func TestAccVPCSecurityGroupDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupDataSourceConfig(rInt), + Config: testAccVPCSecurityGroupDataSourceConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccSecurityGroupCheckDataSource("data.aws_security_group.by_id"), resource.TestCheckResourceAttr("data.aws_security_group.by_id", "description", "sg description"), @@ -104,7 +104,7 @@ func testAccSecurityGroupCheckDefaultDataSource(name string) resource.TestCheckF } } -func testAccSecurityGroupDataSourceConfig(rInt int) string { +func testAccVPCSecurityGroupDataSourceConfig_basic(rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index c6d623e065b..939286c4faa 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -139,7 +139,7 @@ func TestAccVPCSecurityGroupRule_Ingress_vpc(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleIngressConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_ingress(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), @@ -172,7 +172,7 @@ func TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRule_Ingress_Source_with_AccountID(rInt), + Config: testAccVPCSecurityGroupRuleConfig_ingressSourceAccountID(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), resource.TestCheckResourceAttrPair( @@ -218,7 +218,7 @@ func TestAccVPCSecurityGroupRule_Ingress_protocol(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleIngress_protocolConfig, + Config: testAccVPCSecurityGroupRuleConfig_ingressProtocol, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), @@ -249,7 +249,7 @@ func TestAccVPCSecurityGroupRule_Ingress_icmpv6(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleIngress_icmpv6Config, + Config: testAccVPCSecurityGroupRuleConfig_ingressIcmpv6, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists(sgResourceName, &group), resource.TestCheckResourceAttr(resourceName, "from_port", "-1"), @@ -301,7 +301,7 @@ func TestAccVPCSecurityGroupRule_Ingress_ipv6(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleIngress_ipv6Config, + Config: testAccVPCSecurityGroupRuleConfig_ingressIPv6, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testRuleCount, @@ -343,7 +343,7 @@ func TestAccVPCSecurityGroupRule_Ingress_classic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleIngressClassicConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_ingressClassic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), @@ -393,7 +393,7 @@ func TestAccVPCSecurityGroupRule_multiIngress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleMultiIngressConfig, + Config: testAccVPCSecurityGroupRuleConfig_multiIngress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testMultiRuleCount, @@ -420,7 +420,7 @@ func TestAccVPCSecurityGroupRule_egress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleEgressConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_egress(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), @@ -446,7 +446,7 @@ func TestAccVPCSecurityGroupRule_selfReference(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleSelfReferenceConfig, + Config: testAccVPCSecurityGroupRuleConfig_selfReference, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), ), @@ -470,7 +470,7 @@ func TestAccVPCSecurityGroupRule_expectInvalidTypeError(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleExpectInvalidType(rInt), + Config: testAccVPCSecurityGroupRuleConfig_expectInvalidType(rInt), ExpectError: regexp.MustCompile(`expected type to be one of \[ingress egress\]`), }, }, @@ -486,11 +486,11 @@ func TestAccVPCSecurityGroupRule_expectInvalidCIDR(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleInvalidIPv4CIDR(rInt), + Config: testAccVPCSecurityGroupRuleConfig_invalidIPv4CIDR(rInt), ExpectError: regexp.MustCompile("invalid CIDR address: 1.2.3.4/33"), }, { - Config: testAccSecurityGroupRuleInvalidIPv6CIDR(rInt), + Config: testAccVPCSecurityGroupRuleConfig_invalidIPv6CIDR(rInt), ExpectError: regexp.MustCompile("invalid CIDR address: ::/244"), }, }, @@ -529,7 +529,7 @@ func TestAccVPCSecurityGroupRule_PartialMatching_basic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRulePartialMatchingConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_partialMatching(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress", &group, &p, "ingress"), @@ -592,7 +592,7 @@ func TestAccVPCSecurityGroupRule_PartialMatching_source(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRulePartialMatching_SourceConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_partialMatchingSource(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleExists("aws_security_group.nat", &nat), @@ -620,7 +620,7 @@ func TestAccVPCSecurityGroupRule_issue5310(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleIssue5310, + Config: testAccVPCSecurityGroupRuleConfig_issue5310, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.issue_5310", &group), ), @@ -645,7 +645,7 @@ func TestAccVPCSecurityGroupRule_race(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleRace, + Config: testAccVPCSecurityGroupRuleConfig_race, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.race", &group), ), @@ -665,7 +665,7 @@ func TestAccVPCSecurityGroupRule_selfSource(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleSelfInSource(rInt), + Config: testAccVPCSecurityGroupRuleConfig_selfInSource(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), ), @@ -723,7 +723,7 @@ func TestAccVPCSecurityGroupRule_prefixListEgress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRulePrefixListEgressConfig, + Config: testAccVPCSecurityGroupRuleConfig_prefixListEgress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.egress", &group), // lookup info on the VPC Endpoint created, to populate the expected @@ -754,7 +754,7 @@ func TestAccVPCSecurityGroupRule_ingressDescription(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleIngressDescriptionConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_ingressDescription(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), @@ -782,7 +782,7 @@ func TestAccVPCSecurityGroupRule_egressDescription(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleEgressDescriptionConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_egressDescription(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), @@ -810,7 +810,7 @@ func TestAccVPCSecurityGroupRule_IngressDescription_updates(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleIngressDescriptionConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_ingressDescription(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), @@ -819,7 +819,7 @@ func TestAccVPCSecurityGroupRule_IngressDescription_updates(t *testing.T) { }, { - Config: testAccSecurityGroupRuleIngress_updateDescriptionConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_ingressUpdateDescription(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), @@ -847,7 +847,7 @@ func TestAccVPCSecurityGroupRule_EgressDescription_updates(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleEgressDescriptionConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_egressDescription(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), @@ -856,7 +856,7 @@ func TestAccVPCSecurityGroupRule_EgressDescription_updates(t *testing.T) { }, { - Config: testAccSecurityGroupRuleEgress_updateDescriptionConfig(rInt), + Config: testAccVPCSecurityGroupRuleConfig_egressUpdateDescription(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), @@ -900,7 +900,7 @@ func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleDescriptionAllPortsConfig(rName, "description1"), + Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPorts(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule1, "ingress"), @@ -917,7 +917,7 @@ func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSecurityGroupRuleDescriptionAllPortsConfig(rName, "description2"), + Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPorts(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule2, "ingress"), @@ -958,7 +958,7 @@ func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleDescriptionAllPortsNonZeroPortsConfig(rName, "description1"), + Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPortsNonZeroPorts(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule1, "ingress"), @@ -975,7 +975,7 @@ func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) ImportStateVerify: true, }, { - Config: testAccSecurityGroupRuleDescriptionAllPortsNonZeroPortsConfig(rName, "description2"), + Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPortsNonZeroPorts(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule2, "ingress"), @@ -1020,7 +1020,7 @@ func TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash(t *testi CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleMultipleRuleSearchingAllProtocolCrashConfig(rName), + Config: testAccVPCSecurityGroupRuleConfig_multipleSearchingAllProtocolCrash(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName1, &group, &rule1, "ingress"), @@ -1125,7 +1125,7 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleMultiDescription(rInt, "ingress"), + Config: testAccVPCSecurityGroupRuleConfig_multidescription(rInt, "ingress"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.worker", &group), testAccCheckSecurityGroupRuleExists("aws_security_group.nat", &nat), @@ -1161,7 +1161,7 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSecurityGroupRuleMultiDescription(rInt, "egress"), + Config: testAccVPCSecurityGroupRuleConfig_multidescription(rInt, "egress"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupRuleExists("aws_security_group.worker", &group), testAccCheckSecurityGroupRuleExists("aws_security_group.nat", &nat), @@ -1441,7 +1441,7 @@ func testAccSecurityGroupRuleImportGetAttrs(attrs map[string]string, key string) return &values, nil } -func testAccSecurityGroupRuleIngressConfig(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_ingress(rInt int) string { return fmt.Sprintf(` resource "aws_security_group" "web" { name = "terraform_test_%d" @@ -1464,7 +1464,7 @@ resource "aws_security_group_rule" "ingress_1" { `, rInt) } -const testAccSecurityGroupRuleIngress_icmpv6Config = ` +const testAccVPCSecurityGroupRuleConfig_ingressIcmpv6 = ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" } @@ -1483,7 +1483,7 @@ resource "aws_security_group_rule" "test" { } ` -const testAccSecurityGroupRuleIngress_ipv6Config = ` +const testAccVPCSecurityGroupRuleConfig_ingressIPv6 = ` resource "aws_vpc" "tftest" { cidr_block = "10.0.0.0/16" @@ -1511,7 +1511,7 @@ resource "aws_security_group_rule" "ingress_1" { } ` -const testAccSecurityGroupRuleIngress_protocolConfig = ` +const testAccVPCSecurityGroupRuleConfig_ingressProtocol = ` resource "aws_vpc" "tftest" { cidr_block = "10.0.0.0/16" @@ -1539,7 +1539,7 @@ resource "aws_security_group_rule" "ingress_1" { } ` -const testAccSecurityGroupRuleIssue5310 = ` +const testAccVPCSecurityGroupRuleConfig_issue5310 = ` resource "aws_security_group" "issue_5310" { name = "terraform-test-issue_5310" description = "SG for test of issue 5310" @@ -1555,7 +1555,7 @@ resource "aws_security_group_rule" "issue_5310" { } ` -func testAccSecurityGroupRuleIngressClassicConfig(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_ingressClassic(rInt int) string { return fmt.Sprintf(` resource "aws_security_group" "web" { name = "terraform_test_%d" @@ -1578,7 +1578,7 @@ resource "aws_security_group_rule" "ingress_1" { `, rInt) } -func testAccSecurityGroupRuleEgressConfig(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_egress(rInt int) string { return fmt.Sprintf(` resource "aws_security_group" "web" { name = "terraform_test_%d" @@ -1601,7 +1601,7 @@ resource "aws_security_group_rule" "egress_1" { `, rInt) } -const testAccSecurityGroupRuleMultiIngressConfig = ` +const testAccVPCSecurityGroupRuleConfig_multiIngress = ` resource "aws_security_group" "web" { name = "terraform_acceptance_test_example_2" description = "Used in the terraform acceptance tests" @@ -1633,7 +1633,7 @@ resource "aws_security_group_rule" "ingress_2" { } ` -func testAccSecurityGroupRuleMultiDescription(rInt int, rType string) string { +func testAccVPCSecurityGroupRuleConfig_multidescription(rInt int, rType string) string { var b bytes.Buffer b.WriteString(fmt.Sprintf(` resource "aws_vpc" "tf_sgrule_description_test" { @@ -1716,7 +1716,7 @@ resource "aws_security_group_rule" "rule_4" { } // check for GH-1985 regression -const testAccSecurityGroupRuleSelfReferenceConfig = ` +const testAccVPCSecurityGroupRuleConfig_selfReference = ` resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" @@ -1744,7 +1744,7 @@ resource "aws_security_group_rule" "self" { } ` -func testAccSecurityGroupRulePartialMatchingConfig(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_partialMatching(rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" @@ -1805,7 +1805,7 @@ resource "aws_security_group_rule" "nat_ingress" { `, rInt, rInt) } -func testAccSecurityGroupRulePartialMatching_SourceConfig(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_partialMatchingSource(rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" @@ -1855,7 +1855,7 @@ resource "aws_security_group_rule" "other_ingress" { `, rInt, rInt) } -const testAccSecurityGroupRulePrefixListEgressConfig = ` +const testAccVPCSecurityGroupRuleConfig_prefixListEgress = ` resource "aws_vpc" "tf_sg_prefix_list_egress_test" { cidr_block = "10.0.0.0/16" @@ -1907,7 +1907,7 @@ resource "aws_security_group_rule" "egress_1" { } ` -func testAccSecurityGroupRuleIngressDescriptionConfig(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_ingressDescription(rInt int) string { return fmt.Sprintf(` resource "aws_security_group" "web" { name = "terraform_test_%d" @@ -1931,7 +1931,7 @@ resource "aws_security_group_rule" "ingress_1" { `, rInt) } -func testAccSecurityGroupRuleIngress_updateDescriptionConfig(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_ingressUpdateDescription(rInt int) string { return fmt.Sprintf(` resource "aws_security_group" "web" { name = "terraform_test_%d" @@ -1955,7 +1955,7 @@ resource "aws_security_group_rule" "ingress_1" { `, rInt) } -func testAccSecurityGroupRuleEgressDescriptionConfig(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_egressDescription(rInt int) string { return fmt.Sprintf(` resource "aws_security_group" "web" { name = "terraform_test_%d" @@ -1979,7 +1979,7 @@ resource "aws_security_group_rule" "egress_1" { `, rInt) } -func testAccSecurityGroupRuleEgress_updateDescriptionConfig(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_egressUpdateDescription(rInt int) string { return fmt.Sprintf(` resource "aws_security_group" "web" { name = "terraform_test_%d" @@ -2003,7 +2003,7 @@ resource "aws_security_group_rule" "egress_1" { `, rInt) } -func testAccSecurityGroupRuleDescriptionAllPortsConfig(rName, description string) string { +func testAccVPCSecurityGroupRuleConfig_descriptionAllPorts(rName, description string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %q @@ -2025,7 +2025,7 @@ resource "aws_security_group_rule" "test" { `, rName, description) } -func testAccSecurityGroupRuleDescriptionAllPortsNonZeroPortsConfig(rName, description string) string { +func testAccVPCSecurityGroupRuleConfig_descriptionAllPortsNonZeroPorts(rName, description string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %q @@ -2047,7 +2047,7 @@ resource "aws_security_group_rule" "test" { `, rName, description) } -func testAccSecurityGroupRuleMultipleRuleSearchingAllProtocolCrashConfig(rName string) string { +func testAccVPCSecurityGroupRuleConfig_multipleSearchingAllProtocolCrash(rName string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %q @@ -2077,7 +2077,7 @@ resource "aws_security_group_rule" "test2" { `, rName) } -var testAccSecurityGroupRuleRace = func() string { +var testAccVPCSecurityGroupRuleConfig_race = func() string { var b bytes.Buffer iterations := 50 b.WriteString(fmt.Sprintf(` @@ -2118,7 +2118,7 @@ resource "aws_security_group_rule" "egress%d" { return b.String() }() -func testAccSecurityGroupRuleSelfInSource(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_selfInSource(rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -2145,7 +2145,7 @@ resource "aws_security_group_rule" "allow_self" { `, rInt) } -func testAccSecurityGroupRule_Ingress_Source_with_AccountID(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_ingressSourceAccountID(rInt int) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -2175,7 +2175,7 @@ resource "aws_security_group_rule" "allow_self" { `, rInt) } -func testAccSecurityGroupRuleExpectInvalidType(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_expectInvalidType(rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -2202,7 +2202,7 @@ resource "aws_security_group_rule" "allow_self" { `, rInt) } -func testAccSecurityGroupRuleInvalidIPv4CIDR(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_invalidIPv4CIDR(rInt int) string { return fmt.Sprintf(` resource "aws_security_group" "foo" { name = "testing-failure-%d" @@ -2219,7 +2219,7 @@ resource "aws_security_group_rule" "ing" { `, rInt) } -func testAccSecurityGroupRuleInvalidIPv6CIDR(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_invalidIPv6CIDR(rInt int) string { return fmt.Sprintf(` resource "aws_security_group" "foo" { name = "testing-failure-%d" diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index be90caf03c7..c1272834738 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -507,7 +507,7 @@ func TestAccVPCSecurityGroup_allowAll(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_allowAll, + Config: testAccVPCSecurityGroupConfig_allowAll, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -533,7 +533,7 @@ func TestAccVPCSecurityGroup_sourceSecurityGroup(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_sourceSecurityGroup, + Config: testAccVPCSecurityGroupConfig_source, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -559,7 +559,7 @@ func TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_IPRangeAndSecurityGroupWithSameRules, + Config: testAccVPCSecurityGroupConfig_ipRangeSGSameRules, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -585,7 +585,7 @@ func TestAccVPCSecurityGroup_ipRangesWithSameRules(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_IPRangesWithSameRules, + Config: testAccVPCSecurityGroupConfig_ipRangesSameRules, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -611,7 +611,7 @@ func TestAccVPCSecurityGroup_basic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig, + Config: testAccVPCSecurityGroupConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupAttributes(&group), @@ -654,7 +654,7 @@ func TestAccVPCSecurityGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig, + Config: testAccVPCSecurityGroupConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSecurityGroup(), resourceName), @@ -676,7 +676,7 @@ func TestAccVPCSecurityGroup_egressMode(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupEgressModeBlocksConfig(), + Config: testAccVPCSecurityGroupConfig_egressModeBlocks(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup1), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), @@ -689,14 +689,14 @@ func TestAccVPCSecurityGroup_egressMode(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupEgressModeNoBlocksConfig(), + Config: testAccVPCSecurityGroupConfig_egressModeNoBlocks(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup2), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), ), }, { - Config: testAccSecurityGroupEgressModeZeroedConfig(), + Config: testAccVPCSecurityGroupConfig_egressModeZeroed(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup3), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -717,7 +717,7 @@ func TestAccVPCSecurityGroup_ingressMode(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIngressModeBlocksConfig(), + Config: testAccVPCSecurityGroupConfig_ingressModeBlocks(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup1), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), @@ -730,14 +730,14 @@ func TestAccVPCSecurityGroup_ingressMode(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupIngressModeNoBlocksConfig(), + Config: testAccVPCSecurityGroupConfig_ingressModeNoBlocks(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup2), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), ), }, { - Config: testAccSecurityGroupIngressModeZeroedConfig(), + Config: testAccVPCSecurityGroupConfig_ingressModeZeroed(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup3), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), @@ -759,7 +759,7 @@ func TestAccVPCSecurityGroup_ruleGathering(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_ruleGathering(sgName), + Config: testAccVPCSecurityGroupConfig_ruleGathering(sgName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", sgName), @@ -873,7 +873,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { // create the configuration with 2 security groups, then create a // dependency cycle such that they cannot be deleted { - Config: testAccSecurityGroupConfig_revoke_base, + Config: testAccVPCSecurityGroupConfig_revokeBase, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -890,13 +890,13 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { // groups removed. Terraform tries to destroy them but cannot. Expect a // DependencyViolation error { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved, ExpectError: regexp.MustCompile("DependencyViolation"), }, // Restore the config (a no-op plan) but also remove the dependencies // between the groups with testRemoveCycle { - Config: testAccSecurityGroupConfig_revoke_base, + Config: testAccVPCSecurityGroupConfig_revokeBase, // ExpectError: regexp.MustCompile("DependencyViolation"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), @@ -906,7 +906,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { }, // Again try to apply the config with the sgs removed; it should work { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved, }, //// // now test with revoke_rules_on_delete @@ -916,7 +916,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { // configuration, each Security Group has `revoke_rules_on_delete` // specified, and should delete with no issue { - Config: testAccSecurityGroupConfig_revoke_true, + Config: testAccVPCSecurityGroupConfig_revokeTrue, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -926,7 +926,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { // Again try to apply the config with the sgs removed; it should work, // because we've told the SGs to forcefully revoke their rules first { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved, }, }, }) @@ -955,7 +955,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { // Groups are configured to explicitly not revoke rules on delete, // `revoke_rules_on_delete = false` { - Config: testAccSecurityGroupConfig_revoke_false, + Config: testAccVPCSecurityGroupConfig_revokeFalse, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -973,13 +973,13 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { // Terraform tries to destroy them but cannot. Expect a // DependencyViolation error { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved, ExpectError: regexp.MustCompile("DependencyViolation"), }, // Restore the config (a no-op plan) but also remove the dependencies // between the groups with testRemoveCycle { - Config: testAccSecurityGroupConfig_revoke_false, + Config: testAccVPCSecurityGroupConfig_revokeFalse, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -988,7 +988,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { }, // Again try to apply the config with the sgs removed; it should work { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved, }, }, }) @@ -1005,7 +1005,7 @@ func TestAccVPCSecurityGroup_ipv6(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIPv6Config, + Config: testAccVPCSecurityGroupConfig_ipv6, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), @@ -1057,7 +1057,7 @@ func TestAccVPCSecurityGroup_Name_generated(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_generatedName, + Config: testAccVPCSecurityGroupConfig_generatedName, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -1086,7 +1086,7 @@ func TestAccVPCSecurityGroup_Name_terraformPrefix(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNameConfig("terraform-test"), + Config: testAccVPCSecurityGroupConfig_name("terraform-test"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "terraform-test"), @@ -1114,7 +1114,7 @@ func TestAccVPCSecurityGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNamePrefixConfig("tf-acc-test-prefix-"), + Config: testAccVPCSecurityGroupConfig_namePrefix("tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), @@ -1143,7 +1143,7 @@ func TestAccVPCSecurityGroup_NamePrefix_terraformPrefix(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNamePrefixConfig("terraform-test"), + Config: testAccVPCSecurityGroupConfig_namePrefix("terraform-test"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "terraform-test"), @@ -1192,7 +1192,7 @@ func TestAccVPCSecurityGroup_name_change(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupAndInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNameConfigChange("terraform-test"), + Config: testAccVPCSecurityGroupConfig_nameChange("terraform-test"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(sgResourceName, &group), testAccCheckInstanceExists(instanceResourceName, &instance), @@ -1201,7 +1201,7 @@ func TestAccVPCSecurityGroup_name_change(t *testing.T) { ), }, { - Config: testAccSecurityGroupNameConfigChange("terraform-test-2"), + Config: testAccVPCSecurityGroupConfig_nameChange("terraform-test-2"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(sgResourceName, &group), testAccCheckInstanceExists(instanceResourceName, &instance), @@ -1238,7 +1238,7 @@ func TestAccVPCSecurityGroup_self(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupSelfConfig, + Config: testAccVPCSecurityGroupConfig_self, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), @@ -1273,7 +1273,7 @@ func TestAccVPCSecurityGroup_vpc(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupVPCConfig, + Config: testAccVPCSecurityGroupConfig_vpc, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupAttributes(&group), @@ -1317,7 +1317,7 @@ func TestAccVPCSecurityGroup_vpcNegOneIngress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupVPCNegOneIngressConfig, + Config: testAccVPCSecurityGroupConfig_negOneIngress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupAttributesNegOneProtocol(&group), @@ -1354,7 +1354,7 @@ func TestAccVPCSecurityGroup_vpcProtoNumIngress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupVPCProtoNumIngressConfig, + Config: testAccVPCSecurityGroupConfig_protoNumIngress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), @@ -1390,7 +1390,7 @@ func TestAccVPCSecurityGroup_multiIngress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupMultiIngressConfig, + Config: testAccVPCSecurityGroupConfig_multiIngress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -1416,7 +1416,7 @@ func TestAccVPCSecurityGroup_change(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig, + Config: testAccVPCSecurityGroupConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -1428,7 +1428,7 @@ func TestAccVPCSecurityGroup_change(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupChangeConfig, + Config: testAccVPCSecurityGroupConfig_change, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupAttributesChanged(&group), @@ -1449,7 +1449,7 @@ func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleDescriptionConfig("Egress description", "Ingress description"), + Config: testAccVPCSecurityGroupConfig_ruleDescription("Egress description", "Ingress description"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1487,7 +1487,7 @@ func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { }, // Change just the rule descriptions. { - Config: testAccSecurityGroupRuleDescriptionConfig("New egress description", "New ingress description"), + Config: testAccVPCSecurityGroupConfig_ruleDescription("New egress description", "New ingress description"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1519,7 +1519,7 @@ func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { }, // Remove just the rule descriptions. { - Config: testAccSecurityGroupEmptyRuleDescriptionConfig, + Config: testAccVPCSecurityGroupConfig_emptyRuleDescription, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1561,7 +1561,7 @@ func TestAccVPCSecurityGroup_defaultEgressVPC(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupDefaultEgressConfig, + Config: testAccVPCSecurityGroupConfig_defaultEgress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExistsWithoutDefault(resourceName), ), @@ -1588,13 +1588,13 @@ func TestAccVPCSecurityGroup_defaultEgressClassic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupClassicDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupClassicConfig(rName), + Config: testAccVPCSecurityGroupConfig_classic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupClassicExists(resourceName, &group), ), }, { - Config: testAccSecurityGroupClassicConfig(rName), + Config: testAccVPCSecurityGroupConfig_classic(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1616,7 +1616,7 @@ func TestAccVPCSecurityGroup_drift(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_drift(), + Config: testAccVPCSecurityGroupConfig_drift(), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), @@ -1670,7 +1670,7 @@ func TestAccVPCSecurityGroup_driftComplex(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_drift_complex(), + Config: testAccVPCSecurityGroupConfig_driftComplex(), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), @@ -1745,19 +1745,19 @@ func TestAccVPCSecurityGroup_invalidCIDRBlock(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupInvalidIngressCIDR, + Config: testAccVPCSecurityGroupConfig_invalidIngressCIDR, ExpectError: regexp.MustCompile("invalid CIDR address: 1.2.3.4/33"), }, { - Config: testAccSecurityGroupInvalidEgressCIDR, + Config: testAccVPCSecurityGroupConfig_invalidEgressCIDR, ExpectError: regexp.MustCompile("invalid CIDR address: 1.2.3.4/33"), }, { - Config: testAccSecurityGroupInvalidIPv6IngressCIDR, + Config: testAccVPCSecurityGroupConfig_invalidIPv6IngressCIDR, ExpectError: regexp.MustCompile("invalid CIDR address: ::/244"), }, { - Config: testAccSecurityGroupInvalidIPv6EgressCIDR, + Config: testAccVPCSecurityGroupConfig_invalidIPv6EgressCIDR, ExpectError: regexp.MustCompile("invalid CIDR address: ::/244"), }, }, @@ -1776,7 +1776,7 @@ func TestAccVPCSecurityGroup_tags(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupTags1Config(rName, "key1", "value1"), + Config: testAccVPCSecurityGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1790,7 +1790,7 @@ func TestAccVPCSecurityGroup_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCSecurityGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1799,7 +1799,7 @@ func TestAccVPCSecurityGroup_tags(t *testing.T) { ), }, { - Config: testAccSecurityGroupTags1Config(rName, "key2", "value2"), + Config: testAccVPCSecurityGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1821,7 +1821,7 @@ func TestAccVPCSecurityGroup_cidrAndGroups(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupCombindCIDRandGroups, + Config: testAccVPCSecurityGroupConfig_combinedCIDRAndGroups, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), // testAccCheckSecurityGroupAttributes(&group), @@ -1848,7 +1848,7 @@ func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_ingressWithCIDRAndSGs, + Config: testAccVPCSecurityGroupConfig_ingressCIDRAndSGs, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupSGandCIDRAttributes(&group), @@ -1901,7 +1901,7 @@ func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupClassicDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_ingressWithCIDRAndSGs_classic(rName), + Config: testAccVPCSecurityGroupConfig_ingressCIDRAndSGsClassic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -1920,7 +1920,7 @@ func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { ), }, { - Config: testAccSecurityGroupConfig_ingressWithCIDRAndSGs_classic(rName), + Config: testAccVPCSecurityGroupConfig_ingressCIDRAndSGsClassic(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1941,7 +1941,7 @@ func TestAccVPCSecurityGroup_egressWithPrefixList(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupPrefixListEgressConfig, + Config: testAccVPCSecurityGroupConfig_prefixListEgress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupEgressPrefixListAttributes(&group), @@ -1969,7 +1969,7 @@ func TestAccVPCSecurityGroup_ingressWithPrefixList(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupPrefixListIngressConfig, + Config: testAccVPCSecurityGroupConfig_prefixListIngress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupIngressPrefixListAttributes(&group), @@ -1997,7 +1997,7 @@ func TestAccVPCSecurityGroup_ipv4AndIPv6Egress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_ipv4andIPv6Egress, + Config: testAccVPCSecurityGroupConfig_ipv4andIPv6Egress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), @@ -2527,7 +2527,7 @@ func TestAccVPCSecurityGroup_failWithDiffMismatch(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_failWithDiffMismatch, + Config: testAccVPCSecurityGroupConfig_failDiffMismatch, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -2553,7 +2553,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2562,7 +2562,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { }, // append a rule to step over the limit { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2574,7 +2574,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2600,7 +2600,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, 1), @@ -2608,7 +2608,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { }, // append a rule to step over the limit { - Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(0, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2636,7 +2636,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, 1), @@ -2661,7 +2661,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2669,7 +2669,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { }, // prepend a rule to step over the limit { - Config: testAccSecurityGroupRuleLimitConfig(1, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_ruleLimit(1, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2681,7 +2681,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2706,7 +2706,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2714,7 +2714,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { }, // add a rule to step over the limit with entirely new rules { - Config: testAccSecurityGroupRuleLimitConfig(100, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_ruleLimit(100, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2726,7 +2726,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2749,19 +2749,19 @@ func TestAccVPCSecurityGroup_rulesDropOnError(t *testing.T) { Steps: []resource.TestStep{ // Create a valid security group with some rules and make sure it exists { - Config: testAccSecurityGroupConfig_rulesDropOnError_Init, + Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorInit, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), }, // Add a bad rule to trigger API error { - Config: testAccSecurityGroupConfig_rulesDropOnError_AddBadRule, + Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorAddBadRule, ExpectError: regexp.MustCompile("InvalidGroupId.Malformed"), }, // All originally added rules must survive. This will return non-empty plan if anything changed. { - Config: testAccSecurityGroupConfig_rulesDropOnError_Init, + Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorInit, PlanOnly: true, }, }, @@ -2797,7 +2797,7 @@ func testSecurityGroupRuleCount(id string, expectedIngressCount, expectedEgressC return nil } -func testAccSecurityGroupRuleLimitConfig(egressStartIndex, egressRulesCount int) string { +func testAccVPCSecurityGroupConfig_ruleLimit(egressStartIndex, egressRulesCount int) string { var egressRules strings.Builder for i := egressStartIndex; i < egressRulesCount+egressStartIndex; i++ { fmt.Fprintf(&egressRules, ` @@ -2834,7 +2834,7 @@ resource "aws_security_group" "test" { `, egressRules.String()) } -func testAccSecurityGroupCIDRBlockRuleLimitConfig(egressStartIndex, egressRulesCount int) string { +func testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(egressStartIndex, egressRulesCount int) string { var cidrBlocks strings.Builder for i := egressStartIndex; i < egressRulesCount+egressStartIndex; i++ { fmt.Fprintf(&cidrBlocks, ` @@ -2873,7 +2873,7 @@ resource "aws_security_group" "test" { `, cidrBlocks.String()) } -const testAccSecurityGroupEmptyRuleDescriptionConfig = ` +const testAccVPCSecurityGroupConfig_emptyRuleDescription = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -2909,7 +2909,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupIPv6Config = ` +const testAccVPCSecurityGroupConfig_ipv6 = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -2943,7 +2943,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupConfig = ` +const testAccVPCSecurityGroupConfig_basic = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -2966,7 +2966,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupConfig_revoke_base_removed = ` +const testAccVPCSecurityGroupConfig_revokeBaseRemoved = ` resource "aws_vpc" "sg-race-revoke" { cidr_block = "10.1.0.0/16" @@ -2976,7 +2976,7 @@ resource "aws_vpc" "sg-race-revoke" { } ` -const testAccSecurityGroupConfig_revoke_base = ` +const testAccVPCSecurityGroupConfig_revokeBase = ` resource "aws_vpc" "sg-race-revoke" { cidr_block = "10.1.0.0/16" @@ -3006,7 +3006,7 @@ resource "aws_security_group" "secondary" { } ` -const testAccSecurityGroupConfig_revoke_false = ` +const testAccVPCSecurityGroupConfig_revokeFalse = ` resource "aws_vpc" "sg-race-revoke" { cidr_block = "10.1.0.0/16" @@ -3040,7 +3040,7 @@ resource "aws_security_group" "secondary" { } ` -const testAccSecurityGroupConfig_revoke_true = ` +const testAccVPCSecurityGroupConfig_revokeTrue = ` resource "aws_vpc" "sg-race-revoke" { cidr_block = "10.1.0.0/16" @@ -3074,7 +3074,7 @@ resource "aws_security_group" "secondary" { } ` -const testAccSecurityGroupChangeConfig = ` +const testAccVPCSecurityGroupConfig_change = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3111,7 +3111,7 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupRuleDescriptionConfig(egressDescription, ingressDescription string) string { +func testAccVPCSecurityGroupConfig_ruleDescription(egressDescription, ingressDescription string) string { return fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3149,7 +3149,7 @@ resource "aws_security_group" "test" { `, ingressDescription, egressDescription) } -const testAccSecurityGroupSelfConfig = ` +const testAccVPCSecurityGroupConfig_self = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3179,7 +3179,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupVPCConfig = ` +const testAccVPCSecurityGroupConfig_vpc = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3209,7 +3209,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupVPCNegOneIngressConfig = ` +const testAccVPCSecurityGroupConfig_negOneIngress = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3232,7 +3232,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupVPCProtoNumIngressConfig = ` +const testAccVPCSecurityGroupConfig_protoNumIngress = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3255,7 +3255,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupMultiIngressConfig = ` +const testAccVPCSecurityGroupConfig_multiIngress = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3319,7 +3319,7 @@ resource "aws_security_group" "test2" { } ` -func testAccSecurityGroupTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccVPCSecurityGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3341,7 +3341,7 @@ resource "aws_security_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccSecurityGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCSecurityGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3364,7 +3364,7 @@ resource "aws_security_group" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -const testAccSecurityGroupConfig_generatedName = ` +const testAccVPCSecurityGroupConfig_generatedName = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3382,7 +3382,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupDefaultEgressConfig = ` +const testAccVPCSecurityGroupConfig_defaultEgress = ` resource "aws_vpc" "tf_sg_egress_test" { cidr_block = "10.0.0.0/16" @@ -3405,7 +3405,7 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupClassicConfig(rName string) string { +func testAccVPCSecurityGroupConfig_classic(rName string) string { return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` @@ -3416,7 +3416,7 @@ resource "aws_security_group" "test" { `, rName)) } -func testAccSecurityGroupNameConfig(name string) string { +func testAccVPCSecurityGroupConfig_name(name string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -3433,7 +3433,7 @@ resource "aws_security_group" "test" { `, name) } -func testAccSecurityGroupNamePrefixConfig(namePrefix string) string { +func testAccVPCSecurityGroupConfig_namePrefix(namePrefix string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -3450,7 +3450,7 @@ resource "aws_security_group" "test" { `, namePrefix) } -func testAccSecurityGroupConfig_drift() string { +func testAccVPCSecurityGroupConfig_drift() string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = "tf_acc_%d" @@ -3477,7 +3477,7 @@ resource "aws_security_group" "test" { `, sdkacctest.RandInt()) } -func testAccSecurityGroupConfig_drift_complex() string { +func testAccVPCSecurityGroupConfig_driftComplex() string { return fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3547,7 +3547,7 @@ resource "aws_security_group" "test" { `, sdkacctest.RandInt(), sdkacctest.RandInt()) } -const testAccSecurityGroupInvalidIngressCIDR = ` +const testAccVPCSecurityGroupConfig_invalidIngressCIDR = ` resource "aws_security_group" "test" { name = "testing-foo" description = "foo-testing" @@ -3561,7 +3561,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupInvalidEgressCIDR = ` +const testAccVPCSecurityGroupConfig_invalidEgressCIDR = ` resource "aws_security_group" "test" { name = "testing-foo" description = "foo-testing" @@ -3575,7 +3575,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupInvalidIPv6IngressCIDR = ` +const testAccVPCSecurityGroupConfig_invalidIPv6IngressCIDR = ` resource "aws_security_group" "test" { name = "testing-foo" description = "foo-testing" @@ -3589,7 +3589,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupInvalidIPv6EgressCIDR = ` +const testAccVPCSecurityGroupConfig_invalidIPv6EgressCIDR = ` resource "aws_security_group" "test" { name = "testing-foo" description = "foo-testing" @@ -3603,7 +3603,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupCombindCIDRandGroups = ` +const testAccVPCSecurityGroupConfig_combinedCIDRAndGroups = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3662,7 +3662,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupConfig_ingressWithCIDRAndSGs = ` +const testAccVPCSecurityGroupConfig_ingressCIDRAndSGs = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3717,7 +3717,7 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupConfig_ingressWithCIDRAndSGs_classic(rName string) string { +func testAccVPCSecurityGroupConfig_ingressCIDRAndSGsClassic(rName string) string { return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` @@ -3761,7 +3761,7 @@ resource "aws_security_group" "test" { // fails to apply in one pass with the error "diffs didn't match during apply" // GH-2027 -const testAccSecurityGroupConfig_failWithDiffMismatch = ` +const testAccVPCSecurityGroupConfig_failDiffMismatch = ` resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" @@ -3806,7 +3806,7 @@ resource "aws_security_group" "nat" { } ` -const testAccSecurityGroupConfig_allowAll = ` +const testAccVPCSecurityGroupConfig_allowAll = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3842,7 +3842,7 @@ resource "aws_security_group_rule" "allow_all-1" { } ` -const testAccSecurityGroupConfig_sourceSecurityGroup = ` +const testAccVPCSecurityGroupConfig_source = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3887,7 +3887,7 @@ resource "aws_security_group_rule" "allow_test3" { } ` -const testAccSecurityGroupConfig_IPRangeAndSecurityGroupWithSameRules = ` +const testAccVPCSecurityGroupConfig_ipRangeSGSameRules = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3937,7 +3937,7 @@ resource "aws_security_group_rule" "allow_ipv6_cidr_block" { } ` -const testAccSecurityGroupConfig_IPRangesWithSameRules = ` +const testAccVPCSecurityGroupConfig_ipRangesSameRules = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3972,7 +3972,7 @@ resource "aws_security_group_rule" "allow_ipv6_cidr_block" { } ` -const testAccSecurityGroupConfig_ipv4andIPv6Egress = ` +const testAccVPCSecurityGroupConfig_ipv4andIPv6Egress = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" assign_generated_ipv6_cidr_block = true @@ -4003,7 +4003,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupPrefixListEgressConfig = ` +const testAccVPCSecurityGroupConfig_prefixListEgress = ` data "aws_region" "current" {} resource "aws_vpc" "tf_sg_prefix_list_egress_test" { @@ -4053,7 +4053,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupPrefixListIngressConfig = ` +const testAccVPCSecurityGroupConfig_prefixListIngress = ` data "aws_region" "current" {} resource "aws_vpc" "tf_sg_prefix_list_ingress_test" { @@ -4103,7 +4103,7 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupConfig_ruleGathering(sgName string) string { +func testAccVPCSecurityGroupConfig_ruleGathering(sgName string) string { return fmt.Sprintf(` variable "name" { default = "%s" @@ -4228,7 +4228,7 @@ resource "aws_security_group" "test" { `, sgName) } -const testAccSecurityGroupConfig_rulesDropOnError_Init = ` +const testAccVPCSecurityGroupConfig_rulesDropOnErrorInit = ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -4268,7 +4268,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupConfig_rulesDropOnError_AddBadRule = ` +const testAccVPCSecurityGroupConfig_rulesDropOnErrorAddBadRule = ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -4309,7 +4309,7 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupEgressModeBlocksConfig() string { +func testAccVPCSecurityGroupConfig_egressModeBlocks() string { return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4343,7 +4343,7 @@ resource "aws_security_group" "test" { ` } -func testAccSecurityGroupEgressModeNoBlocksConfig() string { +func testAccVPCSecurityGroupConfig_egressModeNoBlocks() string { return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4363,7 +4363,7 @@ resource "aws_security_group" "test" { ` } -func testAccSecurityGroupEgressModeZeroedConfig() string { +func testAccVPCSecurityGroupConfig_egressModeZeroed() string { return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4385,7 +4385,7 @@ resource "aws_security_group" "test" { ` } -func testAccSecurityGroupIngressModeBlocksConfig() string { +func testAccVPCSecurityGroupConfig_ingressModeBlocks() string { return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4419,7 +4419,7 @@ resource "aws_security_group" "test" { ` } -func testAccSecurityGroupIngressModeNoBlocksConfig() string { +func testAccVPCSecurityGroupConfig_ingressModeNoBlocks() string { return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4439,7 +4439,7 @@ resource "aws_security_group" "test" { ` } -func testAccSecurityGroupIngressModeZeroedConfig() string { +func testAccVPCSecurityGroupConfig_ingressModeZeroed() string { return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4461,10 +4461,10 @@ resource "aws_security_group" "test" { ` } -func testAccSecurityGroupNameConfigChange(sgName string) string { +func testAccVPCSecurityGroupConfig_nameChange(sgName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/vpc_security_groups_data_source_test.go b/internal/service/ec2/vpc_security_groups_data_source_test.go index 289b4c51879..5cbe0606387 100644 --- a/internal/service/ec2/vpc_security_groups_data_source_test.go +++ b/internal/service/ec2/vpc_security_groups_data_source_test.go @@ -20,7 +20,7 @@ func TestAccVPCSecurityGroupsDataSource_tag(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupsDataSourceConfig_tag(rName), + Config: testAccVPCSecurityGroupsDataSourceConfig_tag(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "arns.#", "3"), resource.TestCheckResourceAttr(dataSourceName, "ids.#", "3"), @@ -41,7 +41,7 @@ func TestAccVPCSecurityGroupsDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupsDataSourceConfig_filter(rName), + Config: testAccVPCSecurityGroupsDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "arns.#", "1"), resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), @@ -62,7 +62,7 @@ func TestAccVPCSecurityGroupsDataSource_empty(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupsDataSourceConfig_empty(rName), + Config: testAccVPCSecurityGroupsDataSourceConfig_empty(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "arns.#", "0"), resource.TestCheckResourceAttr(dataSourceName, "ids.#", "0"), @@ -73,7 +73,7 @@ func TestAccVPCSecurityGroupsDataSource_empty(t *testing.T) { }) } -func testAccSecurityGroupsDataSourceConfig_tag(rName string) string { +func testAccVPCSecurityGroupsDataSourceConfig_tag(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" @@ -103,7 +103,7 @@ data "aws_security_groups" "test" { `, rName) } -func testAccSecurityGroupsDataSourceConfig_filter(rName string) string { +func testAccVPCSecurityGroupsDataSourceConfig_filter(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" @@ -136,7 +136,7 @@ data "aws_security_groups" "test" { `, rName) } -func testAccSecurityGroupsDataSourceConfig_empty(rName string) string { +func testAccVPCSecurityGroupsDataSourceConfig_empty(rName string) string { return fmt.Sprintf(` data "aws_security_groups" "test" { tags = { diff --git a/internal/service/ec2/vpc_subnet.go b/internal/service/ec2/vpc_subnet.go index e52c0c58eba..c3f4ea964f3 100644 --- a/internal/service/ec2/vpc_subnet.go +++ b/internal/service/ec2/vpc_subnet.go @@ -38,7 +38,7 @@ func ResourceSubnet() *schema.Resource { MigrateState: SubnetMigrateState, // Keep in sync with aws_default_subnet's schema. - // See notes in default_subnet.go. + // See notes in vpc_default_subnet.go. Schema: map[string]*schema.Schema{ "arn": { Type: schema.TypeString, diff --git a/internal/service/ec2/vpc_subnet_cidr_reservation_test.go b/internal/service/ec2/vpc_subnet_cidr_reservation_test.go index 73213d18513..83163de0384 100644 --- a/internal/service/ec2/vpc_subnet_cidr_reservation_test.go +++ b/internal/service/ec2/vpc_subnet_cidr_reservation_test.go @@ -26,7 +26,7 @@ func TestAccVPCSubnetCIDRReservation_basic(t *testing.T) { CheckDestroy: testAccCheckSubnetCIDRReservationDestroy, Steps: []resource.TestStep{ { - Config: testSubnetCIDRReservationConfig_ipv4(rName), + Config: testAccVPCSubnetCIDRReservationConfig_testIPv4(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetCIDRReservationExists(resourceName, &res), resource.TestCheckResourceAttr(resourceName, "cidr_block", "10.1.1.16/28"), @@ -57,7 +57,7 @@ func TestAccVPCSubnetCIDRReservation_ipv6(t *testing.T) { CheckDestroy: testAccCheckSubnetCIDRReservationDestroy, Steps: []resource.TestStep{ { - Config: testSubnetCIDRReservationConfig_ipv6(rName), + Config: testAccVPCSubnetCIDRReservationConfig_testIPv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetCIDRReservationExists(resourceName, &res), resource.TestCheckResourceAttr(resourceName, "reservation_type", "explicit"), @@ -86,7 +86,7 @@ func TestAccVPCSubnetCIDRReservation_disappears(t *testing.T) { CheckDestroy: testAccCheckSubnetCIDRReservationDestroy, Steps: []resource.TestStep{ { - Config: testSubnetCIDRReservationConfig_ipv4(rName), + Config: testAccVPCSubnetCIDRReservationConfig_testIPv4(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetCIDRReservationExists(resourceName, &res), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSubnetCIDRReservation(), resourceName), @@ -157,7 +157,7 @@ func testAccSubnetCIDRReservationImportStateIdFunc(resourceName string) resource } } -func testSubnetCIDRReservationConfig_ipv4(rName string) string { +func testAccVPCSubnetCIDRReservationConfig_testIPv4(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -185,7 +185,7 @@ resource "aws_ec2_subnet_cidr_reservation" "test" { `, rName) } -func testSubnetCIDRReservationConfig_ipv6(rName string) string { +func testAccVPCSubnetCIDRReservationConfig_testIPv6(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpc_subnet_data_source_test.go b/internal/service/ec2/vpc_subnet_data_source_test.go index 449c6f7b4ec..9320573b278 100644 --- a/internal/service/ec2/vpc_subnet_data_source_test.go +++ b/internal/service/ec2/vpc_subnet_data_source_test.go @@ -31,7 +31,7 @@ func TestAccVPCSubnetDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetDataSourceConfig(rName, rInt), + Config: testAccVPCSubnetDataSourceConfig_basic(rName, rInt), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(ds1ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "owner_id", snResourceName, "owner_id"), @@ -147,10 +147,10 @@ func TestAccVPCSubnetDataSource_ipv6ByIPv6Filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSubnetIPv6DataSourceConfig(rName, rInt), + Config: testAccVPCSubnetDataSourceConfig_ipv6(rName, rInt), }, { - Config: testAccSubnetIPv6WithDataSourceFilterDataSourceConfig(rName, rInt), + Config: testAccVPCSubnetDataSourceConfig_ipv6Filter(rName, rInt), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block_association_id"), resource.TestCheckResourceAttrSet("data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block"), @@ -170,10 +170,10 @@ func TestAccVPCSubnetDataSource_ipv6ByIPv6CIDRBlock(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSubnetIPv6DataSourceConfig(rName, rInt), + Config: testAccVPCSubnetDataSourceConfig_ipv6(rName, rInt), }, { - Config: testAccSubnetIPv6WithDataSourceIPv6CIDRBlockDataSourceConfig(rName, rInt), + Config: testAccVPCSubnetDataSourceConfig_ipv6IPv6CIDRBlock(rName, rInt), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block_association_id"), ), @@ -182,7 +182,7 @@ func TestAccVPCSubnetDataSource_ipv6ByIPv6CIDRBlock(t *testing.T) { }) } -func testAccSubnetDataSourceConfig(rName string, rInt int) string { +func testAccVPCSubnetDataSourceConfig_basic(rName string, rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -246,7 +246,7 @@ data "aws_subnet" "by_az_id" { `, rName, rInt) } -func testAccSubnetIPv6DataSourceConfig(rName string, rInt int) string { +func testAccVPCSubnetDataSourceConfig_ipv6(rName string, rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -279,7 +279,7 @@ resource "aws_subnet" "test" { `, rName, rInt) } -func testAccSubnetIPv6WithDataSourceFilterDataSourceConfig(rName string, rInt int) string { +func testAccVPCSubnetDataSourceConfig_ipv6Filter(rName string, rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -319,7 +319,7 @@ data "aws_subnet" "by_ipv6_cidr" { `, rName, rInt) } -func testAccSubnetIPv6WithDataSourceIPv6CIDRBlockDataSourceConfig(rName string, rInt int) string { +func testAccVPCSubnetDataSourceConfig_ipv6IPv6CIDRBlock(rName string, rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" diff --git a/internal/service/ec2/vpc_subnet_ids_data_source_test.go b/internal/service/ec2/vpc_subnet_ids_data_source_test.go index 9f1e7de50ec..0ea4c1c66fa 100644 --- a/internal/service/ec2/vpc_subnet_ids_data_source_test.go +++ b/internal/service/ec2/vpc_subnet_ids_data_source_test.go @@ -21,10 +21,10 @@ func TestAccVPCSubnetIDsDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetIDsDataSourceConfig(rName, rInt), + Config: testAccVPCSubnetIDsDataSourceConfig_basic(rName, rInt), }, { - Config: testAccSubnetIDsWithDataSourceDataSourceConfig(rName, rInt), + Config: testAccVPCSubnetIDsDataSourceConfig_dataSource(rName, rInt), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_subnet_ids.selected", "ids.#", "3"), resource.TestCheckResourceAttr("data.aws_subnet_ids.private", "ids.#", "2"), @@ -45,7 +45,7 @@ func TestAccVPCSubnetIDsDataSource_filter(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetIDsDataSource_filter(rName, rInt), + Config: testAccVPCSubnetIdsDataSourceConfig_filter(rName, rInt), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_subnet_ids.test", "ids.#", "2"), ), @@ -54,7 +54,7 @@ func TestAccVPCSubnetIDsDataSource_filter(t *testing.T) { }) } -func testAccSubnetIDsWithDataSourceDataSourceConfig(rName string, rInt int) string { +func testAccVPCSubnetIDsDataSourceConfig_dataSource(rName string, rInt int) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.%[2]d.0.0/16" @@ -111,7 +111,7 @@ data "aws_subnet_ids" "private" { `, rName, rInt)) } -func testAccSubnetIDsDataSourceConfig(rName string, rInt int) string { +func testAccVPCSubnetIDsDataSourceConfig_basic(rName string, rInt int) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.%[2]d.0.0/16" @@ -156,7 +156,7 @@ resource "aws_subnet" "test_private_b" { `, rName, rInt)) } -func testAccSubnetIDsDataSource_filter(rName string, rInt int) string { +func testAccVPCSubnetIdsDataSourceConfig_filter(rName string, rInt int) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.%[2]d.0.0/16" diff --git a/internal/service/ec2/vpc_subnet_test.go b/internal/service/ec2/vpc_subnet_test.go index 7c1f597104d..b48b69039de 100644 --- a/internal/service/ec2/vpc_subnet_test.go +++ b/internal/service/ec2/vpc_subnet_test.go @@ -29,7 +29,7 @@ func TestAccVPCSubnet_basic(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig(rName), + Config: testAccVPCSubnetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`subnet/subnet-.+`)), @@ -71,7 +71,7 @@ func TestAccVPCSubnet_tags(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetTagsConfig1(rName, "key1", "value1"), + Config: testAccVPCSubnetConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -84,7 +84,7 @@ func TestAccVPCSubnet_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetTagsConfig2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCSubnetConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -93,7 +93,7 @@ func TestAccVPCSubnet_tags(t *testing.T) { ), }, { - Config: testAccSubnetTagsConfig1(rName, "key2", "value2"), + Config: testAccVPCSubnetConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -118,7 +118,7 @@ func TestAccVPCSubnet_DefaultTags_providerOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "providervalue1"), - testAccSubnetConfig(rName), + testAccVPCSubnetConfig_basic(rName), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -135,7 +135,7 @@ func TestAccVPCSubnet_DefaultTags_providerOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags2("providerkey1", "providervalue1", "providerkey2", "providervalue2"), - testAccSubnetConfig(rName), + testAccVPCSubnetConfig_basic(rName), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -148,7 +148,7 @@ func TestAccVPCSubnet_DefaultTags_providerOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "value1"), - testAccSubnetConfig(rName), + testAccVPCSubnetConfig_basic(rName), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -174,7 +174,7 @@ func TestAccVPCSubnet_DefaultTags_updateToProviderOnly(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetTagsConfig1(rName, "key1", "value1"), + Config: testAccVPCSubnetConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -186,7 +186,7 @@ func TestAccVPCSubnet_DefaultTags_updateToProviderOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("key1", "value1"), - testAccSubnetConfig(rName), + testAccVPCSubnetConfig_basic(rName), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -219,7 +219,7 @@ func TestAccVPCSubnet_DefaultTags_updateToResourceOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("key1", "value1"), - testAccSubnetConfig(rName), + testAccVPCSubnetConfig_basic(rName), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -229,7 +229,7 @@ func TestAccVPCSubnet_DefaultTags_updateToResourceOnly(t *testing.T) { ), }, { - Config: testAccSubnetTagsConfig1(rName, "key1", "value1"), + Config: testAccVPCSubnetConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -262,7 +262,7 @@ func TestAccVPCSubnet_DefaultTagsProviderAndResource_nonOverlappingTag(t *testin { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "providervalue1"), - testAccSubnetTagsConfig1(rName, "resourcekey1", "resourcevalue1"), + testAccVPCSubnetConfig_tags1(rName, "resourcekey1", "resourcevalue1"), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -281,7 +281,7 @@ func TestAccVPCSubnet_DefaultTagsProviderAndResource_nonOverlappingTag(t *testin { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "providervalue1"), - testAccSubnetTagsConfig2(rName, "resourcekey1", "resourcevalue1", "resourcekey2", "resourcevalue2"), + testAccVPCSubnetConfig_tags2(rName, "resourcekey1", "resourcevalue1", "resourcekey2", "resourcevalue2"), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -297,7 +297,7 @@ func TestAccVPCSubnet_DefaultTagsProviderAndResource_nonOverlappingTag(t *testin { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey2", "providervalue2"), - testAccSubnetTagsConfig1(rName, "resourcekey3", "resourcevalue3"), + testAccVPCSubnetConfig_tags1(rName, "resourcekey3", "resourcevalue3"), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -327,7 +327,7 @@ func TestAccVPCSubnet_DefaultTagsProviderAndResource_overlappingTag(t *testing.T { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("overlapkey1", "providervalue1"), - testAccSubnetTagsConfig1(rName, "overlapkey1", "resourcevalue1"), + testAccVPCSubnetConfig_tags1(rName, "overlapkey1", "resourcevalue1"), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -344,7 +344,7 @@ func TestAccVPCSubnet_DefaultTagsProviderAndResource_overlappingTag(t *testing.T { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags2("overlapkey1", "providervalue1", "overlapkey2", "providervalue2"), - testAccSubnetTagsConfig2(rName, "overlapkey1", "resourcevalue1", "overlapkey2", "resourcevalue2"), + testAccVPCSubnetConfig_tags2(rName, "overlapkey1", "resourcevalue1", "overlapkey2", "resourcevalue2"), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -359,7 +359,7 @@ func TestAccVPCSubnet_DefaultTagsProviderAndResource_overlappingTag(t *testing.T { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("overlapkey1", "providervalue1"), - testAccSubnetTagsConfig1(rName, "overlapkey1", "resourcevalue2"), + testAccVPCSubnetConfig_tags1(rName, "overlapkey1", "resourcevalue2"), ), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), @@ -386,7 +386,7 @@ func TestAccVPCSubnet_DefaultTagsProviderAndResource_duplicateTag(t *testing.T) { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("overlapkey", "overlapvalue"), - testAccSubnetTagsConfig1(rName, "overlapkey", "overlapvalue"), + testAccVPCSubnetConfig_tags1(rName, "overlapkey", "overlapvalue"), ), PlanOnly: true, ExpectError: regexp.MustCompile(`"tags" are identical to those in the "default_tags" configuration block`), @@ -408,7 +408,7 @@ func TestAccVPCSubnet_defaultAndIgnoreTags(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetTagsConfig1(rName, "key1", "value1"), + Config: testAccVPCSubnetConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), testAccCheckSubnetUpdateTags(&subnet, nil, map[string]string{"defaultkey1": "defaultvalue1"}), @@ -418,14 +418,14 @@ func TestAccVPCSubnet_defaultAndIgnoreTags(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultAndIgnoreTagsKeyPrefixes1("defaultkey1", "defaultvalue1", "defaultkey"), - testAccSubnetTagsConfig1(rName, "key1", "value1"), + testAccVPCSubnetConfig_tags1(rName, "key1", "value1"), ), PlanOnly: true, }, { Config: acctest.ConfigCompose( acctest.ConfigDefaultAndIgnoreTagsKeys1("defaultkey1", "defaultvalue1"), - testAccSubnetTagsConfig1(rName, "key1", "value1"), + testAccVPCSubnetConfig_tags1(rName, "key1", "value1"), ), PlanOnly: true, }, @@ -450,7 +450,7 @@ func TestAccVPCSubnet_updateTagsKnownAtApply(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig_tagsComputedFromVPCDataSource1("key1", "value1"), + Config: testAccVPCSubnetConfig_tagsComputedFromDataSource1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -458,7 +458,7 @@ func TestAccVPCSubnet_updateTagsKnownAtApply(t *testing.T) { ), }, { - Config: testAccSubnetConfig_tagsComputedFromVPCDataSource2("key1", "value1", "key2", "value2"), + Config: testAccVPCSubnetConfig_tagsComputedFromDataSource2("key1", "value1", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -487,7 +487,7 @@ func TestAccVPCSubnet_ignoreTags(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig(rName), + Config: testAccVPCSubnetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), testAccCheckSubnetUpdateTags(&subnet, nil, map[string]string{"ignorekey1": "ignorevalue1"}), @@ -495,11 +495,11 @@ func TestAccVPCSubnet_ignoreTags(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: acctest.ConfigCompose(acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey"), testAccSubnetConfig(rName)), + Config: acctest.ConfigCompose(acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey"), testAccVPCSubnetConfig_basic(rName)), PlanOnly: true, }, { - Config: acctest.ConfigCompose(acctest.ConfigIgnoreTagsKeys("ignorekey1"), testAccSubnetConfig(rName)), + Config: acctest.ConfigCompose(acctest.ConfigIgnoreTagsKeys("ignorekey1"), testAccVPCSubnetConfig_basic(rName)), PlanOnly: true, }, }, @@ -518,7 +518,7 @@ func TestAccVPCSubnet_ipv6(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig_ipv6(rName), + Config: testAccVPCSubnetConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &before), testAccCheckSubnetIPv6BeforeUpdate(&before), @@ -530,14 +530,14 @@ func TestAccVPCSubnet_ipv6(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetConfig_ipv6UpdateAssignv6OnCreation(rName), + Config: testAccVPCSubnetConfig_ipv6UpdateAssignv6OnCreation(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &after), testAccCheckSubnetIPv6AfterUpdate(&after), ), }, { - Config: testAccSubnetConfig_ipv6UpdateV6CIDR(rName), + Config: testAccVPCSubnetConfig_ipv6UpdateV6CIDR(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &after), testAccCheckSubnetNotRecreated(t, &before, &after), @@ -559,7 +559,7 @@ func TestAccVPCSubnet_enableIPv6(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig_prev6(rName), + Config: testAccVPCSubnetConfig_prev6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_block", ""), @@ -572,7 +572,7 @@ func TestAccVPCSubnet_enableIPv6(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetConfig_ipv6(rName), + Config: testAccVPCSubnetConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttrSet(resourceName, "ipv6_cidr_block"), @@ -580,7 +580,7 @@ func TestAccVPCSubnet_enableIPv6(t *testing.T) { ), }, { - Config: testAccSubnetConfig_prev6(rName), + Config: testAccVPCSubnetConfig_prev6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_block", ""), @@ -603,7 +603,7 @@ func TestAccVPCSubnet_availabilityZoneID(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfigAvailabilityZoneId(rName), + Config: testAccVPCSubnetConfig_availabilityZoneID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "availability_zone"), @@ -631,7 +631,7 @@ func TestAccVPCSubnet_disappears(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig(rName), + Config: testAccVPCSubnetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSubnet(), resourceName), @@ -655,7 +655,7 @@ func TestAccVPCSubnet_customerOwnedIPv4Pool(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig_customerOwnedv4Pool(rName), + Config: testAccVPCSubnetConfig_customerOwnedv4Pool(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttrPair(resourceName, "customer_owned_ipv4_pool", coipDataSourceName, "pool_id"), @@ -682,7 +682,7 @@ func TestAccVPCSubnet_mapCustomerOwnedIPOnLaunch(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig_mapCustomerOwnedOnLaunch(rName, true), + Config: testAccVPCSubnetConfig_mapCustomerOwnedOnLaunch(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "map_customer_owned_ip_on_launch", "true"), @@ -709,7 +709,7 @@ func TestAccVPCSubnet_mapPublicIPOnLaunch(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig_mapPublicOnLaunch(rName, true), + Config: testAccVPCSubnetConfig_mapPublicOnLaunch(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "map_public_ip_on_launch", "true"), @@ -721,14 +721,14 @@ func TestAccVPCSubnet_mapPublicIPOnLaunch(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetConfig_mapPublicOnLaunch(rName, false), + Config: testAccVPCSubnetConfig_mapPublicOnLaunch(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "map_public_ip_on_launch", "false"), ), }, { - Config: testAccSubnetConfig_mapPublicOnLaunch(rName, true), + Config: testAccVPCSubnetConfig_mapPublicOnLaunch(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "map_public_ip_on_launch", "true"), @@ -751,7 +751,7 @@ func TestAccVPCSubnet_outpost(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfigOutpost(rName), + Config: testAccVPCSubnetConfig_outpost(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "outpost_arn", outpostDataSourceName, "arn"), @@ -778,7 +778,7 @@ func TestAccVPCSubnet_enableDNS64(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig_enableDNS64(rName, true), + Config: testAccVPCSubnetConfig_enableDNS64(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "enable_dns64", "true"), @@ -790,14 +790,14 @@ func TestAccVPCSubnet_enableDNS64(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetConfig_enableDNS64(rName, false), + Config: testAccVPCSubnetConfig_enableDNS64(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "enable_dns64", "false"), ), }, { - Config: testAccSubnetConfig_enableDNS64(rName, true), + Config: testAccVPCSubnetConfig_enableDNS64(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "enable_dns64", "true"), @@ -819,7 +819,7 @@ func TestAccVPCSubnet_privateDNSNameOptionsOnLaunch(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfig_privateDNSNameOptionsOnLaunch(rName, true, true, "resource-name"), + Config: testAccVPCSubnetConfig_privateDNSNameOptionsOnLaunch(rName, true, true, "resource-name"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "enable_resource_name_dns_aaaa_record_on_launch", "true"), @@ -833,7 +833,7 @@ func TestAccVPCSubnet_privateDNSNameOptionsOnLaunch(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetConfig_privateDNSNameOptionsOnLaunch(rName, false, true, "ip-name"), + Config: testAccVPCSubnetConfig_privateDNSNameOptionsOnLaunch(rName, false, true, "ip-name"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "enable_resource_name_dns_aaaa_record_on_launch", "false"), @@ -842,7 +842,7 @@ func TestAccVPCSubnet_privateDNSNameOptionsOnLaunch(t *testing.T) { ), }, { - Config: testAccSubnetConfig_privateDNSNameOptionsOnLaunch(rName, true, false, "resource-name"), + Config: testAccVPCSubnetConfig_privateDNSNameOptionsOnLaunch(rName, true, false, "resource-name"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &subnet), resource.TestCheckResourceAttr(resourceName, "enable_resource_name_dns_aaaa_record_on_launch", "true"), @@ -866,7 +866,7 @@ func TestAccVPCSubnet_ipv6Native(t *testing.T) { CheckDestroy: testAccCheckSubnetDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetConfigIPv6Native(rName), + Config: testAccVPCSubnetConfig_ipv6Native(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "cidr_block", ""), @@ -974,7 +974,7 @@ func testAccCheckSubnetUpdateTags(subnet *ec2.Subnet, oldTags, newTags map[strin } } -func testAccSubnetConfig(rName string) string { +func testAccVPCSubnetConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -991,7 +991,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccSubnetTagsConfig1(rName, tagKey1, tagValue1 string) string { +func testAccVPCSubnetConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1012,7 +1012,7 @@ resource "aws_subnet" "test" { `, rName, tagKey1, tagValue1) } -func testAccSubnetTagsConfig2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCSubnetConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1051,7 +1051,7 @@ resource "aws_subnet" "test" { } ` -func testAccSubnetConfig_tagsComputedFromVPCDataSource1(tagKey1, tagValue1 string) string { +func testAccVPCSubnetConfig_tagsComputedFromDataSource1(tagKey1, tagValue1 string) string { return acctest.ConfigCompose( testAccSubnetComputedTagsBaseConfig, fmt.Sprintf(` @@ -1063,7 +1063,7 @@ locals { `, tagKey1, tagValue1)) } -func testAccSubnetConfig_tagsComputedFromVPCDataSource2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCSubnetConfig_tagsComputedFromDataSource2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( testAccSubnetComputedTagsBaseConfig, fmt.Sprintf(` @@ -1076,7 +1076,7 @@ locals { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccSubnetConfig_prev6(rName string) string { +func testAccVPCSubnetConfig_prev6(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.0.0/16" @@ -1098,7 +1098,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccSubnetConfig_ipv6(rName string) string { +func testAccVPCSubnetConfig_ipv6(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.0.0/16" @@ -1122,7 +1122,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccSubnetConfig_ipv6UpdateAssignv6OnCreation(rName string) string { +func testAccVPCSubnetConfig_ipv6UpdateAssignv6OnCreation(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.0.0/16" @@ -1146,7 +1146,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccSubnetConfig_ipv6UpdateV6CIDR(rName string) string { +func testAccVPCSubnetConfig_ipv6UpdateV6CIDR(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.0.0/16" @@ -1170,7 +1170,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccSubnetConfigAvailabilityZoneId(rName string) string { +func testAccVPCSubnetConfig_availabilityZoneID(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1192,7 +1192,7 @@ resource "aws_subnet" "test" { `, rName)) } -func testAccSubnetConfig_customerOwnedv4Pool(rName string) string { +func testAccVPCSubnetConfig_customerOwnedv4Pool(rName string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -1245,7 +1245,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccSubnetConfig_mapCustomerOwnedOnLaunch(rName string, mapCustomerOwnedIpOnLaunch bool) string { +func testAccVPCSubnetConfig_mapCustomerOwnedOnLaunch(rName string, mapCustomerOwnedIpOnLaunch bool) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -1298,7 +1298,7 @@ resource "aws_subnet" "test" { `, rName, mapCustomerOwnedIpOnLaunch) } -func testAccSubnetConfig_mapPublicOnLaunch(rName string, mapPublicIpOnLaunch bool) string { +func testAccVPCSubnetConfig_mapPublicOnLaunch(rName string, mapPublicIpOnLaunch bool) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1320,7 +1320,7 @@ resource "aws_subnet" "test" { `, rName, mapPublicIpOnLaunch) } -func testAccSubnetConfig_enableDNS64(rName string, enableDns64 bool) string { +func testAccVPCSubnetConfig_enableDNS64(rName string, enableDns64 bool) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.0.0/16" @@ -1345,7 +1345,7 @@ resource "aws_subnet" "test" { `, rName, enableDns64) } -func testAccSubnetConfig_privateDNSNameOptionsOnLaunch(rName string, enableDnsAAAA, enableDnsA bool, hostnameType string) string { +func testAccVPCSubnetConfig_privateDNSNameOptionsOnLaunch(rName string, enableDnsAAAA, enableDnsA bool, hostnameType string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.0.0/16" @@ -1373,7 +1373,7 @@ resource "aws_subnet" "test" { `, rName, enableDnsAAAA, enableDnsA, hostnameType) } -func testAccSubnetConfigIPv6Native(rName string) string { +func testAccVPCSubnetConfig_ipv6Native(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.0.0/16" @@ -1399,7 +1399,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccSubnetConfigOutpost(rName string) string { +func testAccVPCSubnetConfig_outpost(rName string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/ec2/vpc_subnets_data_source_test.go b/internal/service/ec2/vpc_subnets_data_source_test.go index e7e653ff2fe..9a35ac384d5 100644 --- a/internal/service/ec2/vpc_subnets_data_source_test.go +++ b/internal/service/ec2/vpc_subnets_data_source_test.go @@ -19,10 +19,10 @@ func TestAccVPCSubnetsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSubnetsDataSourceConfig(rName), + Config: testAccVPCSubnetsDataSourceConfig_basic(rName), }, { - Config: testAccSubnetsWithDataSourceDataSourceConfig(rName), + Config: testAccVPCSubnetsDataSourceConfig_dataSource(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_subnets.selected", "ids.#", "4"), resource.TestCheckResourceAttr("data.aws_subnets.private", "ids.#", "2"), @@ -43,7 +43,7 @@ func TestAccVPCSubnetsDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSubnetsDataSource_filter(rName), + Config: testAccVPCSubnetsDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_subnets.test", "ids.#", "2"), ), @@ -52,7 +52,7 @@ func TestAccVPCSubnetsDataSource_filter(t *testing.T) { }) } -func testAccSubnetsDataSourceConfig(rName string) string { +func testAccVPCSubnetsDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" @@ -108,8 +108,8 @@ resource "aws_subnet" "test_private_b" { `, rName)) } -func testAccSubnetsWithDataSourceDataSourceConfig(rName string) string { - return acctest.ConfigCompose(testAccSubnetsDataSourceConfig(rName), ` +func testAccVPCSubnetsDataSourceConfig_dataSource(rName string) string { + return acctest.ConfigCompose(testAccVPCSubnetsDataSourceConfig_basic(rName), ` data "aws_subnets" "selected" { filter { name = "vpc-id" @@ -144,7 +144,7 @@ data "aws_subnets" "none" { `) } -func testAccSubnetsDataSource_filter(rName string) string { +func testAccVPCSubnetsDataSourceConfig_filter(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" diff --git a/internal/service/ec2/vpc_test.go b/internal/service/ec2/vpc_test.go index ed254186a5b..faff46fa3ce 100644 --- a/internal/service/ec2/vpc_test.go +++ b/internal/service/ec2/vpc_test.go @@ -98,7 +98,7 @@ func TestAccVPC_tags(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCTags1Config("key1", "value1"), + Config: testAccVPCConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -111,7 +111,7 @@ func TestAccVPC_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPCTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccVPCConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -120,7 +120,7 @@ func TestAccVPC_tags(t *testing.T) { ), }, { - Config: testAccVPCTags1Config("key2", "value2"), + Config: testAccVPCConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -200,7 +200,7 @@ func TestAccVPC_DefaultTags_updateToProviderOnly(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCTags1Config("key1", "value1"), + Config: testAccVPCConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -254,7 +254,7 @@ func TestAccVPC_DefaultTags_updateToResourceOnly(t *testing.T) { ), }, { - Config: testAccVPCTags1Config("key1", "value1"), + Config: testAccVPCConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -286,7 +286,7 @@ func TestAccVPC_DefaultTagsProviderAndResource_nonOverlappingTag(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "providervalue1"), - testAccVPCTags1Config("resourcekey1", "resourcevalue1"), + testAccVPCConfig_tags1("resourcekey1", "resourcevalue1"), ), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), @@ -305,7 +305,7 @@ func TestAccVPC_DefaultTagsProviderAndResource_nonOverlappingTag(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "providervalue1"), - testAccVPCTags2Config("resourcekey1", "resourcevalue1", "resourcekey2", "resourcevalue2"), + testAccVPCConfig_tags2("resourcekey1", "resourcevalue1", "resourcekey2", "resourcevalue2"), ), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), @@ -321,7 +321,7 @@ func TestAccVPC_DefaultTagsProviderAndResource_nonOverlappingTag(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey2", "providervalue2"), - testAccVPCTags1Config("resourcekey3", "resourcevalue3"), + testAccVPCConfig_tags1("resourcekey3", "resourcevalue3"), ), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), @@ -350,7 +350,7 @@ func TestAccVPC_DefaultTagsProviderAndResource_overlappingTag(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("overlapkey1", "providervalue1"), - testAccVPCTags1Config("overlapkey1", "resourcevalue1"), + testAccVPCConfig_tags1("overlapkey1", "resourcevalue1"), ), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), @@ -367,7 +367,7 @@ func TestAccVPC_DefaultTagsProviderAndResource_overlappingTag(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags2("overlapkey1", "providervalue1", "overlapkey2", "providervalue2"), - testAccVPCTags2Config("overlapkey1", "resourcevalue1", "overlapkey2", "resourcevalue2"), + testAccVPCConfig_tags2("overlapkey1", "resourcevalue1", "overlapkey2", "resourcevalue2"), ), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), @@ -382,7 +382,7 @@ func TestAccVPC_DefaultTagsProviderAndResource_overlappingTag(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("overlapkey1", "providervalue1"), - testAccVPCTags1Config("overlapkey1", "resourcevalue2"), + testAccVPCConfig_tags1("overlapkey1", "resourcevalue2"), ), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), @@ -408,7 +408,7 @@ func TestAccVPC_DefaultTagsProviderAndResource_duplicateTag(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("overlapkey", "overlapvalue"), - testAccVPCTags1Config("overlapkey", "overlapvalue"), + testAccVPCConfig_tags1("overlapkey", "overlapvalue"), ), PlanOnly: true, ExpectError: regexp.MustCompile(`"tags" are identical to those in the "default_tags" configuration block`), @@ -435,7 +435,7 @@ func TestAccVPC_DynamicResourceTagsMergedWithLocals_ignoreChanges(t *testing.T) CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCWithIgnoreChangesConfig_DynamicTagsMergedWithLocals("localkey", "localvalue"), + Config: testAccVPCConfig_ignoreChangesDynamicTagsMergedLocals("localkey", "localvalue"), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -453,7 +453,7 @@ func TestAccVPC_DynamicResourceTagsMergedWithLocals_ignoreChanges(t *testing.T) ExpectNonEmptyPlan: true, }, { - Config: testAccVPCWithIgnoreChangesConfig_DynamicTagsMergedWithLocals("localkey", "localvalue"), + Config: testAccVPCConfig_ignoreChangesDynamicTagsMergedLocals("localkey", "localvalue"), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -491,7 +491,7 @@ func TestAccVPC_DynamicResourceTags_ignoreChanges(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCWithIgnoreChangesConfig_DynamicTags, + Config: testAccVPCConfig_ignoreChangesDynamicTags, Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -507,7 +507,7 @@ func TestAccVPC_DynamicResourceTags_ignoreChanges(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: testAccVPCWithIgnoreChangesConfig_DynamicTags, + Config: testAccVPCConfig_ignoreChangesDynamicTags, Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -537,7 +537,7 @@ func TestAccVPC_defaultAndIgnoreTags(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCTags1Config("key1", "value1"), + Config: testAccVPCConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), testAccCheckVPCUpdateTags(&vpc, nil, map[string]string{"defaultkey1": "defaultvalue1"}), @@ -547,14 +547,14 @@ func TestAccVPC_defaultAndIgnoreTags(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultAndIgnoreTagsKeyPrefixes1("defaultkey1", "defaultvalue1", "defaultkey"), - testAccVPCTags1Config("key1", "value1"), + testAccVPCConfig_tags1("key1", "value1"), ), PlanOnly: true, }, { Config: acctest.ConfigCompose( acctest.ConfigDefaultAndIgnoreTagsKeys1("defaultkey1", "defaultvalue1"), - testAccVPCTags1Config("key1", "value1"), + testAccVPCConfig_tags1("key1", "value1"), ), PlanOnly: true, }, @@ -574,7 +574,7 @@ func TestAccVPC_ignoreTags(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCTags1Config("key1", "value1"), + Config: testAccVPCConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), testAccCheckVPCUpdateTags(&vpc, nil, map[string]string{"ignorekey1": "ignorevalue1"}), @@ -582,11 +582,11 @@ func TestAccVPC_ignoreTags(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey") + testAccVPCTags1Config("key1", "value1"), + Config: acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey") + testAccVPCConfig_tags1("key1", "value1"), PlanOnly: true, }, { - Config: acctest.ConfigIgnoreTagsKeys("ignorekey1") + testAccVPCTags1Config("key1", "value1"), + Config: acctest.ConfigIgnoreTagsKeys("ignorekey1") + testAccVPCConfig_tags1("key1", "value1"), PlanOnly: true, }, }, @@ -840,7 +840,7 @@ func TestAccVPC_assignGeneratedIPv6CIDRBlockWithNetworkBorderGroup(t *testing.T) CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCConfig_assignGeneratedIPv6CIDRBlockWithOptionalNetworkBorderGroup(rName, true), + Config: testAccVPCConfig_assignGeneratedIPv6CIDRBlockOptionalNetworkBorderGroup(rName, true), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "assign_generated_ipv6_cidr_block", "true"), @@ -857,7 +857,7 @@ func TestAccVPC_assignGeneratedIPv6CIDRBlockWithNetworkBorderGroup(t *testing.T) ImportStateVerify: true, }, { - Config: testAccVPCConfig_assignGeneratedIPv6CIDRBlockWithOptionalNetworkBorderGroup(rName, false), + Config: testAccVPCConfig_assignGeneratedIPv6CIDRBlockOptionalNetworkBorderGroup(rName, false), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "assign_generated_ipv6_cidr_block", "true"), @@ -888,7 +888,7 @@ func TestAccVPC_IPAMIPv4BasicNetmask(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccIPAMIPv4(rName, 28), + Config: testAccVPCConfig_ipamIPv4(rName, 28), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), testAccCheckVPCCIDRPrefix(&vpc, "28"), @@ -915,7 +915,7 @@ func TestAccVPC_IPAMIPv4BasicExplicitCIDR(t *testing.T) { CheckDestroy: testAccCheckVPCDestroy, Steps: []resource.TestStep{ { - Config: testAccIPAMIPv4Config_explicitCIDR(rName, cidr), + Config: testAccVPCConfig_ipamIPv4ExplicitCIDR(rName, cidr), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "cidr_block", cidr), @@ -993,7 +993,7 @@ resource "aws_vpc" "test" { } ` -func testAccVPCTags1Config(tagKey1, tagValue1 string) string { +func testAccVPCConfig_tags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1005,7 +1005,7 @@ resource "aws_vpc" "test" { `, tagKey1, tagValue1) } -func testAccVPCTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1018,7 +1018,7 @@ resource "aws_vpc" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccVPCWithIgnoreChangesConfig_DynamicTagsMergedWithLocals(localTagKey1, localTagValue1 string) string { +func testAccVPCConfig_ignoreChangesDynamicTagsMergedLocals(localTagKey1, localTagValue1 string) string { return fmt.Sprintf(` locals { tags = { @@ -1043,7 +1043,7 @@ resource "aws_vpc" "test" { `, localTagKey1, localTagValue1) } -const testAccVPCWithIgnoreChangesConfig_DynamicTags = ` +const testAccVPCConfig_ignoreChangesDynamicTags = ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -1073,7 +1073,7 @@ resource "aws_vpc" "test" { `, rName, assignGeneratedIpv6CidrBlock) } -func testAccVPCConfig_assignGeneratedIPv6CIDRBlockWithOptionalNetworkBorderGroup(rName string, localZoneNetworkBorderGroup bool) string { +func testAccVPCConfig_assignGeneratedIPv6CIDRBlockOptionalNetworkBorderGroup(rName string, localZoneNetworkBorderGroup bool) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -1230,7 +1230,7 @@ resource "aws_vpc_ipam_pool_cidr" "test" { `, rName) } -func testAccIPAMIPv4(rName string, netmaskLength int) string { +func testAccVPCConfig_ipamIPv4(rName string, netmaskLength int) string { return acctest.ConfigCompose(testAccIPAMIPv4Config_base(rName), fmt.Sprintf(` resource "aws_vpc" "test" { ipv4_ipam_pool_id = aws_vpc_ipam_pool.test.id @@ -1245,7 +1245,7 @@ resource "aws_vpc" "test" { `, rName, netmaskLength)) } -func testAccIPAMIPv4Config_explicitCIDR(rName, cidr string) string { +func testAccVPCConfig_ipamIPv4ExplicitCIDR(rName, cidr string) string { return acctest.ConfigCompose(testAccIPAMIPv4Config_base(rName), fmt.Sprintf(` resource "aws_vpc" "test" { ipv4_ipam_pool_id = aws_vpc_ipam_pool.test.id diff --git a/internal/service/ec2/vpc_traffic_mirror_filter_rule_test.go b/internal/service/ec2/vpc_traffic_mirror_filter_rule_test.go index 3bbf5264599..c246e93d44f 100644 --- a/internal/service/ec2/vpc_traffic_mirror_filter_rule_test.go +++ b/internal/service/ec2/vpc_traffic_mirror_filter_rule_test.go @@ -41,7 +41,7 @@ func TestAccVPCTrafficMirrorFilterRule_basic(t *testing.T) { Steps: []resource.TestStep{ //create { - Config: testAccTrafficMirrorFilterRuleConfig_basic(dstCidr, srcCidr, action, direction, ruleNum), + Config: testAccVPCTrafficMirrorFilterRuleConfig_basic(dstCidr, srcCidr, action, direction, ruleNum), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterRuleExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", ec2.ServiceName, regexp.MustCompile(`traffic-mirror-filter-rule/tmfr-.+`)), @@ -59,7 +59,7 @@ func TestAccVPCTrafficMirrorFilterRule_basic(t *testing.T) { }, // Add all optionals { - Config: testAccTrafficMirrorFilterRuleConfig_full(dstCidr, srcCidr, action, direction, description, ruleNum, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo, protocol), + Config: testAccVPCTrafficMirrorFilterRuleConfig_full(dstCidr, srcCidr, action, direction, description, ruleNum, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo, protocol), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterRuleExists(resourceName), resource.TestMatchResourceAttr(resourceName, "traffic_mirror_filter_id", regexp.MustCompile("tmf-.*")), @@ -80,7 +80,7 @@ func TestAccVPCTrafficMirrorFilterRule_basic(t *testing.T) { }, // remove optionals { - Config: testAccTrafficMirrorFilterRuleConfig_basic(dstCidr, srcCidr, action, direction, ruleNum), + Config: testAccVPCTrafficMirrorFilterRuleConfig_basic(dstCidr, srcCidr, action, direction, ruleNum), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterRuleExists(resourceName), resource.TestMatchResourceAttr(resourceName, "traffic_mirror_filter_id", regexp.MustCompile("tmf-.*")), @@ -123,7 +123,7 @@ func TestAccVPCTrafficMirrorFilterRule_disappears(t *testing.T) { CheckDestroy: testAccCheckTrafficMirrorFilterRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTrafficMirrorFilterRuleConfig_basic(dstCidr, srcCidr, action, direction, ruleNum), + Config: testAccVPCTrafficMirrorFilterRuleConfig_basic(dstCidr, srcCidr, action, direction, ruleNum), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterRuleExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTrafficMirrorFilterRule(), resourceName), @@ -183,7 +183,7 @@ func testAccCheckTrafficMirrorFilterRuleExists(name string) resource.TestCheckFu } } -func testAccTrafficMirrorFilterRuleConfig_basic(dstCidr, srcCidr, action, dir string, num int) string { +func testAccVPCTrafficMirrorFilterRuleConfig_basic(dstCidr, srcCidr, action, dir string, num int) string { return fmt.Sprintf(` resource "aws_ec2_traffic_mirror_filter" "test" { } @@ -199,7 +199,7 @@ resource "aws_ec2_traffic_mirror_filter_rule" "test" { `, dstCidr, action, num, srcCidr, dir) } -func testAccTrafficMirrorFilterRuleConfig_full(dstCidr, srcCidr, action, dir, description string, ruleNum, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo, protocol int) string { +func testAccVPCTrafficMirrorFilterRuleConfig_full(dstCidr, srcCidr, action, dir, description string, ruleNum, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo, protocol int) string { return fmt.Sprintf(` resource "aws_ec2_traffic_mirror_filter" "test" {} diff --git a/internal/service/ec2/vpc_traffic_mirror_filter_test.go b/internal/service/ec2/vpc_traffic_mirror_filter_test.go index 30c6e5e6884..c20c531d32e 100644 --- a/internal/service/ec2/vpc_traffic_mirror_filter_test.go +++ b/internal/service/ec2/vpc_traffic_mirror_filter_test.go @@ -31,7 +31,7 @@ func TestAccVPCTrafficMirrorFilter_basic(t *testing.T) { Steps: []resource.TestStep{ //create { - Config: testAccTrafficMirrorFilterConfig(description), + Config: testAccVPCTrafficMirrorFilterConfig_basic(description), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`traffic-mirror-filter/tmf-.+`)), @@ -42,7 +42,7 @@ func TestAccVPCTrafficMirrorFilter_basic(t *testing.T) { }, // Test Disable DNS service { - Config: testAccTrafficMirrorFilterConfigWithoutDNS(description), + Config: testAccVPCTrafficMirrorFilterConfig_noDNS(description), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterExists(resourceName, &v), resource.TestCheckNoResourceAttr(resourceName, "network_services"), @@ -50,7 +50,7 @@ func TestAccVPCTrafficMirrorFilter_basic(t *testing.T) { }, // Test Enable DNS service { - Config: testAccTrafficMirrorFilterConfig(description), + Config: testAccVPCTrafficMirrorFilterConfig_basic(description), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", description), @@ -80,7 +80,7 @@ func TestAccVPCTrafficMirrorFilter_tags(t *testing.T) { CheckDestroy: testAccCheckTrafficMirrorFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccTrafficMirrorFilterConfigTags1("key1", "value1"), + Config: testAccVPCTrafficMirrorFilterConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -93,7 +93,7 @@ func TestAccVPCTrafficMirrorFilter_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTrafficMirrorFilterConfigTags2("key1", "value1updated", "key2", "value2"), + Config: testAccVPCTrafficMirrorFilterConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -102,7 +102,7 @@ func TestAccVPCTrafficMirrorFilter_tags(t *testing.T) { ), }, { - Config: testAccTrafficMirrorFilterConfigTags1("key2", "value2"), + Config: testAccVPCTrafficMirrorFilterConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -128,7 +128,7 @@ func TestAccVPCTrafficMirrorFilter_disappears(t *testing.T) { CheckDestroy: testAccCheckTrafficMirrorFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccTrafficMirrorFilterConfig(description), + Config: testAccVPCTrafficMirrorFilterConfig_basic(description), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorFilterExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTrafficMirrorFilter(), resourceName), @@ -170,7 +170,7 @@ func testAccCheckTrafficMirrorFilterExists(name string, traffic *ec2.TrafficMirr } } -func testAccTrafficMirrorFilterConfig(description string) string { +func testAccVPCTrafficMirrorFilterConfig_basic(description string) string { return fmt.Sprintf(` resource "aws_ec2_traffic_mirror_filter" "test" { description = "%s" @@ -180,7 +180,7 @@ resource "aws_ec2_traffic_mirror_filter" "test" { `, description) } -func testAccTrafficMirrorFilterConfigWithoutDNS(description string) string { +func testAccVPCTrafficMirrorFilterConfig_noDNS(description string) string { return fmt.Sprintf(` resource "aws_ec2_traffic_mirror_filter" "test" { description = "%s" @@ -188,7 +188,7 @@ resource "aws_ec2_traffic_mirror_filter" "test" { `, description) } -func testAccTrafficMirrorFilterConfigTags1(tagKey1, tagValue1 string) string { +func testAccVPCTrafficMirrorFilterConfig_tags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ec2_traffic_mirror_filter" "test" { tags = { @@ -198,7 +198,7 @@ resource "aws_ec2_traffic_mirror_filter" "test" { `, tagKey1, tagValue1) } -func testAccTrafficMirrorFilterConfigTags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCTrafficMirrorFilterConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_ec2_traffic_mirror_filter" "test" { tags = { diff --git a/internal/service/ec2/vpc_traffic_mirror_session_test.go b/internal/service/ec2/vpc_traffic_mirror_session_test.go index d78900936ae..82c300990a2 100644 --- a/internal/service/ec2/vpc_traffic_mirror_session_test.go +++ b/internal/service/ec2/vpc_traffic_mirror_session_test.go @@ -37,7 +37,7 @@ func TestAccVPCTrafficMirrorSession_basic(t *testing.T) { Steps: []resource.TestStep{ //create { - Config: testAccTrafficMirrorSessionConfig(rName, session), + Config: testAccVPCTrafficMirrorSessionConfig_basic(rName, session), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorSessionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -51,7 +51,7 @@ func TestAccVPCTrafficMirrorSession_basic(t *testing.T) { }, // update of description, packet length and VNI { - Config: testAccTrafficMirrorSessionConfigWithOptionals(description, rName, session, pLen, vni), + Config: testAccVPCTrafficMirrorSessionConfig_optionals(description, rName, session, pLen, vni), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorSessionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", description), @@ -62,7 +62,7 @@ func TestAccVPCTrafficMirrorSession_basic(t *testing.T) { }, // removal of description, packet length and VNI { - Config: testAccTrafficMirrorSessionConfig(rName, session), + Config: testAccVPCTrafficMirrorSessionConfig_basic(rName, session), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorSessionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -97,7 +97,7 @@ func TestAccVPCTrafficMirrorSession_tags(t *testing.T) { CheckDestroy: testAccCheckTrafficMirrorSessionDestroy, Steps: []resource.TestStep{ { - Config: testAccTrafficMirrorSessionConfigTags1(rName, "key1", "value1", session), + Config: testAccVPCTrafficMirrorSessionConfig_tags1(rName, "key1", "value1", session), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorSessionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -110,7 +110,7 @@ func TestAccVPCTrafficMirrorSession_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTrafficMirrorSessionConfigTags2(rName, "key1", "value1updated", "key2", "value2", session), + Config: testAccVPCTrafficMirrorSessionConfig_tags2(rName, "key1", "value1updated", "key2", "value2", session), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorSessionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -119,7 +119,7 @@ func TestAccVPCTrafficMirrorSession_tags(t *testing.T) { ), }, { - Config: testAccTrafficMirrorSessionConfigTags1(rName, "key2", "value2", session), + Config: testAccVPCTrafficMirrorSessionConfig_tags1(rName, "key2", "value2", session), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorSessionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -146,7 +146,7 @@ func TestAccVPCTrafficMirrorSession_disappears(t *testing.T) { CheckDestroy: testAccCheckTrafficMirrorSessionDestroy, Steps: []resource.TestStep{ { - Config: testAccTrafficMirrorSessionConfig(rName, session), + Config: testAccVPCTrafficMirrorSessionConfig_basic(rName, session), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorSessionExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTrafficMirrorSession(), resourceName), @@ -189,7 +189,7 @@ func testAccCheckTrafficMirrorSessionExists(name string, session *ec2.TrafficMir } func testAccTrafficMirrorSessionConfigBase(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` data "aws_availability_zones" "azs" { state = "available" @@ -260,7 +260,7 @@ resource "aws_ec2_traffic_mirror_target" "target" { `, rName)) } -func testAccTrafficMirrorSessionConfig(rName string, session int) string { +func testAccVPCTrafficMirrorSessionConfig_basic(rName string, session int) string { return acctest.ConfigCompose(testAccTrafficMirrorSessionConfigBase(rName), fmt.Sprintf(` resource "aws_ec2_traffic_mirror_session" "test" { traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id @@ -271,7 +271,7 @@ resource "aws_ec2_traffic_mirror_session" "test" { `, session)) } -func testAccTrafficMirrorSessionConfigTags1(rName, tagKey1, tagValue1 string, session int) string { +func testAccVPCTrafficMirrorSessionConfig_tags1(rName, tagKey1, tagValue1 string, session int) string { return acctest.ConfigCompose(testAccTrafficMirrorSessionConfigBase(rName), fmt.Sprintf(` resource "aws_ec2_traffic_mirror_session" "test" { traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id @@ -286,7 +286,7 @@ resource "aws_ec2_traffic_mirror_session" "test" { `, tagKey1, tagValue1, session)) } -func testAccTrafficMirrorSessionConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string, session int) string { +func testAccVPCTrafficMirrorSessionConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string, session int) string { return acctest.ConfigCompose(testAccTrafficMirrorSessionConfigBase(rName), fmt.Sprintf(` resource "aws_ec2_traffic_mirror_session" "test" { traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id @@ -302,7 +302,7 @@ resource "aws_ec2_traffic_mirror_session" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2, session)) } -func testAccTrafficMirrorSessionConfigWithOptionals(description string, rName string, session, pLen, vni int) string { +func testAccVPCTrafficMirrorSessionConfig_optionals(description string, rName string, session, pLen, vni int) string { return acctest.ConfigCompose(testAccTrafficMirrorSessionConfigBase(rName), fmt.Sprintf(` resource "aws_ec2_traffic_mirror_session" "test" { description = "%s" diff --git a/internal/service/ec2/vpc_traffic_mirror_target_test.go b/internal/service/ec2/vpc_traffic_mirror_target_test.go index 7d35f208e3b..d350e0eaebd 100644 --- a/internal/service/ec2/vpc_traffic_mirror_target_test.go +++ b/internal/service/ec2/vpc_traffic_mirror_target_test.go @@ -32,7 +32,7 @@ func TestAccVPCTrafficMirrorTarget_nlb(t *testing.T) { CheckDestroy: testAccCheckTrafficMirrorTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTrafficMirrorTargetConfigNlb(rName, description), + Config: testAccVPCTrafficMirrorTargetConfig_nlb(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorTargetExists(resourceName, &v), acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), @@ -67,7 +67,7 @@ func TestAccVPCTrafficMirrorTarget_eni(t *testing.T) { CheckDestroy: testAccCheckTrafficMirrorTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTrafficMirrorTargetConfigEni(rName, description), + Config: testAccVPCTrafficMirrorTargetConfig_eni(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", description), @@ -100,7 +100,7 @@ func TestAccVPCTrafficMirrorTarget_tags(t *testing.T) { CheckDestroy: testAccCheckTrafficMirrorTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTrafficMirrorTargetConfigTags1(rName, description, "key1", "value1"), + Config: testAccVPCTrafficMirrorTargetConfig_tags1(rName, description, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -113,7 +113,7 @@ func TestAccVPCTrafficMirrorTarget_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTrafficMirrorTargetConfigTags2(rName, description, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCTrafficMirrorTargetConfig_tags2(rName, description, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -122,7 +122,7 @@ func TestAccVPCTrafficMirrorTarget_tags(t *testing.T) { ), }, { - Config: testAccTrafficMirrorTargetConfigTags1(rName, description, "key2", "value2"), + Config: testAccVPCTrafficMirrorTargetConfig_tags1(rName, description, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -149,7 +149,7 @@ func TestAccVPCTrafficMirrorTarget_disappears(t *testing.T) { CheckDestroy: testAccCheckTrafficMirrorTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTrafficMirrorTargetConfigNlb(rName, description), + Config: testAccVPCTrafficMirrorTargetConfig_nlb(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficMirrorTargetExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTrafficMirrorTarget(), resourceName), @@ -232,7 +232,7 @@ resource "aws_subnet" "sub2" { `, rName) } -func testAccTrafficMirrorTargetConfigNlb(rName, description string) string { +func testAccVPCTrafficMirrorTargetConfig_nlb(rName, description string) string { return acctest.ConfigCompose(testAccTrafficMirrorTargetConfigBase(rName), fmt.Sprintf(` resource "aws_lb" "lb" { name = %[1]q @@ -255,10 +255,10 @@ resource "aws_ec2_traffic_mirror_target" "test" { `, rName, description)) } -func testAccTrafficMirrorTargetConfigEni(rName, description string) string { +func testAccVPCTrafficMirrorTargetConfig_eni(rName, description string) string { return acctest.ConfigCompose( testAccTrafficMirrorTargetConfigBase(rName), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "src" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -277,7 +277,7 @@ resource "aws_ec2_traffic_mirror_target" "test" { `, rName, description)) } -func testAccTrafficMirrorTargetConfigTags1(rName, description, tagKey1, tagValue1 string) string { +func testAccVPCTrafficMirrorTargetConfig_tags1(rName, description, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccTrafficMirrorTargetConfigBase(rName), fmt.Sprintf(` resource "aws_lb" "lb" { name = %[1]q @@ -304,7 +304,7 @@ resource "aws_ec2_traffic_mirror_target" "test" { `, rName, description, tagKey1, tagValue1)) } -func testAccTrafficMirrorTargetConfigTags2(rName, description, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCTrafficMirrorTargetConfig_tags2(rName, description, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccTrafficMirrorTargetConfigBase(rName), fmt.Sprintf(` resource "aws_lb" "lb" { name = %[1]q diff --git a/internal/service/ec2/vpc_vpcs_data_source_test.go b/internal/service/ec2/vpc_vpcs_data_source_test.go index 4a432f568d6..9bac54fb15b 100644 --- a/internal/service/ec2/vpc_vpcs_data_source_test.go +++ b/internal/service/ec2/vpc_vpcs_data_source_test.go @@ -19,7 +19,7 @@ func TestAccVPCsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCsDataSourceConfig(rName), + Config: testAccVPCVPCsDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue("data.aws_vpcs.test", "ids.#", "0"), ), @@ -37,7 +37,7 @@ func TestAccVPCsDataSource_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCsDataSourceConfig_tags(rName), + Config: testAccVPCVPCsDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_vpcs.test", "ids.#", "1"), ), @@ -55,7 +55,7 @@ func TestAccVPCsDataSource_filters(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCsDataSourceConfig_filters(rName), + Config: testAccVPCVPCsDataSourceConfig_filters(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue("data.aws_vpcs.test", "ids.#", "0"), ), @@ -73,7 +73,7 @@ func TestAccVPCsDataSource_empty(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCsDataSourceConfig_empty(rName), + Config: testAccVPCVPCsDataSourceConfig_empty(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_vpcs.test", "ids.#", "0"), ), @@ -82,7 +82,7 @@ func TestAccVPCsDataSource_empty(t *testing.T) { }) } -func testAccVPCsDataSourceConfig(rName string) string { +func testAccVPCVPCsDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/24" @@ -96,7 +96,7 @@ data "aws_vpcs" "test" {} `, rName) } -func testAccVPCsDataSourceConfig_tags(rName string) string { +func testAccVPCVPCsDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/24" @@ -116,7 +116,7 @@ data "aws_vpcs" "test" { `, rName) } -func testAccVPCsDataSourceConfig_filters(rName string) string { +func testAccVPCVPCsDataSourceConfig_filters(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "192.168.0.0/25" @@ -135,7 +135,7 @@ data "aws_vpcs" "test" { `, rName) } -func testAccVPCsDataSourceConfig_empty(rName string) string { +func testAccVPCVPCsDataSourceConfig_empty(rName string) string { return fmt.Sprintf(` data "aws_vpcs" "test" { tags = { diff --git a/internal/service/ec2/vpnclient_authorization_rule.go b/internal/service/ec2/vpnclient_authorization_rule.go index 402b8b6379a..93c7356de68 100644 --- a/internal/service/ec2/vpnclient_authorization_rule.go +++ b/internal/service/ec2/vpnclient_authorization_rule.go @@ -157,7 +157,7 @@ func resourceClientVPNAuthorizationRuleDelete(d *schema.ResourceData, meta inter log.Printf("[DEBUG] Deleting EC2 Client VPN Authorization Rule: %s", d.Id()) _, err = conn.RevokeClientVpnIngress(input) - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIDNotFound, errCodeInvalidClientVPNAuthorizationRuleNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound, errCodeInvalidClientVPNAuthorizationRuleNotFound) { return nil } diff --git a/internal/service/ec2/vpnclient_endpoint.go b/internal/service/ec2/vpnclient_endpoint.go index b38f33268ba..4394da1e2e5 100644 --- a/internal/service/ec2/vpnclient_endpoint.go +++ b/internal/service/ec2/vpnclient_endpoint.go @@ -470,7 +470,7 @@ func resourceClientVPNEndpointDelete(d *schema.ResourceData, meta interface{}) e ClientVpnEndpointId: aws.String(d.Id()), }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { return nil } diff --git a/internal/service/ec2/vpnclient_endpoint_data_source_test.go b/internal/service/ec2/vpnclient_endpoint_data_source_test.go index e90b9e825ee..bd9cdd72774 100644 --- a/internal/service/ec2/vpnclient_endpoint_data_source_test.go +++ b/internal/service/ec2/vpnclient_endpoint_data_source_test.go @@ -23,7 +23,7 @@ func testAccClientVPNEndpointDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckClientVPNEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointDataSourceConfig_basic(rName), + Config: testAccClientVPNEndpointDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasource1Name, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasource1Name, "authentication_options.#", resourceName, "authentication_options.#"), @@ -90,7 +90,7 @@ func testAccClientVPNEndpointDataSource_basic(t *testing.T) { }) } -func testAccEndpointDataSourceConfig_basic(rName string) string { +func testAccClientVPNEndpointDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(testAccClientVPNEndpointConfig_basic(rName), ` data "aws_ec2_client_vpn_endpoint" "by_id" { client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.test.id diff --git a/internal/service/ec2/vpnclient_endpoint_test.go b/internal/service/ec2/vpnclient_endpoint_test.go index 1068d23198c..ce236d00d7e 100644 --- a/internal/service/ec2/vpnclient_endpoint_test.go +++ b/internal/service/ec2/vpnclient_endpoint_test.go @@ -329,7 +329,7 @@ func testAccClientVPNEndpoint_federatedAuthWithSelfServiceProvider(t *testing.T) CheckDestroy: testAccCheckClientVPNEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccClientVPNEndpointConfig_federatedAuthAndSelfServiceSamlProvider(rName, idpEntityID), + Config: testAccClientVPNEndpointConfig_federatedAuthAndSelfServiceSAMLProvider(rName, idpEntityID), Check: resource.ComposeTestCheckFunc( testAccCheckClientVPNEndpointExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "authentication_options.#", "1"), @@ -1135,7 +1135,7 @@ resource "aws_ec2_client_vpn_endpoint" "test" { `, rName, idpEntityID)) } -func testAccClientVPNEndpointConfig_federatedAuthAndSelfServiceSamlProvider(rName, idpEntityID string) string { +func testAccClientVPNEndpointConfig_federatedAuthAndSelfServiceSAMLProvider(rName, idpEntityID string) string { return acctest.ConfigCompose(testAccClientVPNEndpointConfig_acmCertificateBase("test"), fmt.Sprintf(` resource "aws_iam_saml_provider" "test1" { name = %[1]q diff --git a/internal/service/ec2/vpnclient_network_association.go b/internal/service/ec2/vpnclient_network_association.go index 3d3c1413c70..0f02b33d558 100644 --- a/internal/service/ec2/vpnclient_network_association.go +++ b/internal/service/ec2/vpnclient_network_association.go @@ -165,7 +165,7 @@ func resourceClientVPNNetworkAssociationDelete(d *schema.ResourceData, meta inte AssociationId: aws.String(d.Id()), }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNAssociationIDNotFound, errCodeInvalidClientVPNEndpointIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNAssociationIdNotFound, errCodeInvalidClientVPNEndpointIdNotFound) { return nil } diff --git a/internal/service/ec2/vpnclient_route.go b/internal/service/ec2/vpnclient_route.go index 94d8405a0d4..5105d14c9e9 100644 --- a/internal/service/ec2/vpnclient_route.go +++ b/internal/service/ec2/vpnclient_route.go @@ -144,7 +144,7 @@ func resourceClientVPNRouteDelete(d *schema.ResourceData, meta interface{}) erro TargetVpcSubnetId: aws.String(targetSubnetID), }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIDNotFound, errCodeInvalidClientVPNRouteNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound, errCodeInvalidClientVPNRouteNotFound) { return nil } diff --git a/internal/service/ec2/vpnsite_connection.go b/internal/service/ec2/vpnsite_connection.go index 43523fb357c..81f6dd9139a 100644 --- a/internal/service/ec2/vpnsite_connection.go +++ b/internal/service/ec2/vpnsite_connection.go @@ -1,6 +1,7 @@ package ec2 import ( + "context" "encoding/xml" "fmt" "log" @@ -14,6 +15,7 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "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" @@ -74,6 +76,12 @@ func ResourceVPNConnection() *schema.Resource { ValidateFunc: validation.IsCIDRNetwork(0, 128), RequiredWith: []string{"transit_gateway_id"}, }, + "outside_ip_address_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice(outsideIPAddressType_Values(), false), + }, "remote_ipv4_network_cidr": { Type: schema.TypeString, Optional: true, @@ -124,6 +132,10 @@ func ResourceVPNConnection() *schema.Resource { Optional: true, ExactlyOneOf: []string{"transit_gateway_id", "vpn_gateway_id"}, }, + "transport_transit_gateway_attachment_id": { + Type: schema.TypeString, + Optional: true, + }, "tunnel_inside_ip_version": { Type: schema.TypeString, Optional: true, @@ -536,7 +548,10 @@ func ResourceVPNConnection() *schema.Resource { }, }, - CustomizeDiff: verify.SetTagsDiff, + CustomizeDiff: customdiff.Sequence( + customizeDiffValidateOutsideIPAddressType, + verify.SetTagsDiff, + ), } } @@ -692,9 +707,11 @@ func resourceVPNConnectionRead(d *schema.ResourceData, meta interface{}) error { d.Set("enable_acceleration", v.EnableAcceleration) d.Set("local_ipv4_network_cidr", v.LocalIpv4NetworkCidr) d.Set("local_ipv6_network_cidr", v.LocalIpv6NetworkCidr) + d.Set("outside_ip_address_type", v.OutsideIpAddressType) d.Set("remote_ipv4_network_cidr", v.RemoteIpv4NetworkCidr) d.Set("remote_ipv6_network_cidr", v.RemoteIpv6NetworkCidr) d.Set("static_routes_only", v.StaticRoutesOnly) + d.Set("transport_transit_gateway_attachment_id", v.TransportTransitGatewayAttachmentId) d.Set("tunnel_inside_ip_version", v.TunnelInsideIpVersion) for i, prefix := range []string{"tunnel1_", "tunnel2_"} { @@ -706,9 +723,11 @@ func resourceVPNConnectionRead(d *schema.ResourceData, meta interface{}) error { d.Set("enable_acceleration", nil) d.Set("local_ipv4_network_cidr", nil) d.Set("local_ipv6_network_cidr", nil) + d.Set("outside_ip_address_type", nil) d.Set("remote_ipv4_network_cidr", nil) d.Set("remote_ipv6_network_cidr", nil) d.Set("static_routes_only", nil) + d.Set("transport_transit_gateway_attachment_id", nil) d.Set("tunnel_inside_ip_version", nil) } @@ -882,6 +901,10 @@ func expandVPNConnectionOptionsSpecification(d *schema.ResourceData) *ec2.VpnCon apiObject.EnableAcceleration = aws.Bool(v.(bool)) } + if v, ok := d.GetOk("outside_ip_address_type"); ok { + apiObject.OutsideIpAddressType = aws.String(v.(string)) + } + if v := d.Get("tunnel_inside_ip_version").(string); v == ec2.TunnelInsideIpVersionIpv6 { if v, ok := d.GetOk("local_ipv6_network_cidr"); ok { apiObject.LocalIpv6NetworkCidr = aws.String(v.(string)) @@ -908,6 +931,10 @@ func expandVPNConnectionOptionsSpecification(d *schema.ResourceData) *ec2.VpnCon apiObject.StaticRoutesOnly = aws.Bool(v.(bool)) } + if v, ok := d.GetOk("transport_transit_gateway_attachment_id"); ok { + apiObject.TransportTransitGatewayAttachmentId = aws.String(v.(string)) + } + apiObject.TunnelOptions = []*ec2.VpnTunnelOptionsSpecification{ expandVPNTunnelOptionsSpecification(d, "tunnel1_"), expandVPNTunnelOptionsSpecification(d, "tunnel2_"), @@ -1492,3 +1519,15 @@ func validVPNConnectionTunnelInsideIPv6CIDR() schema.SchemaValidateFunc { validation.StringMatch(regexp.MustCompile(`^fd00:`), "must be within fd00::/8"), ) } + +// customizeDiffValidateOutsideIPAddressType validates that if provided `outside_ip_address_type` is `PrivateIpv4` then `transport_transit_gateway_attachment_id` must be provided +func customizeDiffValidateOutsideIPAddressType(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { + if v, ok := diff.GetOk("outside_ip_address_type"); !ok || v.(string) == OutsideIPAddressTypePublicIPv4 { + return nil + } + + if v, ok := diff.GetOk("transport_transit_gateway_attachment_id"); !ok || v.(string) != "" { + return nil + } + return fmt.Errorf("`transport_transit_gateway_attachment_id` must be provided if `outside_ip_address_type` is `PrivateIpv4`") +} diff --git a/internal/service/ec2/vpnsite_connection_route_test.go b/internal/service/ec2/vpnsite_connection_route_test.go index 2cca83bd880..f527339623f 100644 --- a/internal/service/ec2/vpnsite_connection_route_test.go +++ b/internal/service/ec2/vpnsite_connection_route_test.go @@ -26,7 +26,7 @@ func TestAccSiteVPNConnectionRoute_basic(t *testing.T) { CheckDestroy: testAccVPNConnectionRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionRouteConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionRouteConfig_basic(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionRouteExists(resourceName), ), @@ -47,7 +47,7 @@ func TestAccSiteVPNConnectionRoute_disappears(t *testing.T) { CheckDestroy: testAccVPNConnectionRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionRouteConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionRouteConfig_basic(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionRouteExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPNConnectionRoute(), resourceName), @@ -117,7 +117,7 @@ func testAccVPNConnectionRouteExists(n string) resource.TestCheckFunc { } } -func testAccVPNConnectionRouteConfig(rName string, rBgpAsn int) string { +func testAccSiteVPNConnectionRouteConfig_basic(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { diff --git a/internal/service/ec2/vpnsite_connection_test.go b/internal/service/ec2/vpnsite_connection_test.go index 0efb30f0885..e6c382ec873 100644 --- a/internal/service/ec2/vpnsite_connection_test.go +++ b/internal/service/ec2/vpnsite_connection_test.go @@ -159,7 +159,7 @@ func TestAccSiteVPNConnection_basic(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_basic(rName, rBgpAsn), Check: resource.ComposeAggregateTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpn-connection/vpn-.+`)), @@ -169,6 +169,7 @@ func TestAccSiteVPNConnection_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "enable_acceleration", "false"), resource.TestCheckResourceAttr(resourceName, "local_ipv4_network_cidr", "0.0.0.0/0"), resource.TestCheckResourceAttr(resourceName, "local_ipv6_network_cidr", ""), + resource.TestCheckResourceAttr(resourceName, "outside_ip_address_type", "PublicIpv4"), resource.TestCheckResourceAttr(resourceName, "remote_ipv4_network_cidr", "0.0.0.0/0"), resource.TestCheckResourceAttr(resourceName, "remote_ipv6_network_cidr", ""), resource.TestCheckResourceAttr(resourceName, "routes.#", "0"), @@ -248,7 +249,7 @@ func TestAccSiteVPNConnection_transitGatewayID(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionTransitGatewayConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_transitGateway(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestMatchResourceAttr(resourceName, "transit_gateway_attachment_id", regexp.MustCompile(`tgw-attach-.+`)), @@ -277,7 +278,7 @@ func TestAccSiteVPNConnection_tunnel1InsideCIDR(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionTunnel1InsideCIDRConfig(rName, rBgpAsn, "169.254.8.0/30", "169.254.9.0/30"), + Config: testAccSiteVPNConnectionConfig_tunnel1InsideCIDR(rName, rBgpAsn, "169.254.8.0/30", "169.254.9.0/30"), Check: resource.ComposeAggregateTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "tunnel1_inside_cidr", "169.254.8.0/30"), @@ -306,7 +307,7 @@ func TestAccSiteVPNConnection_tunnel1InsideIPv6CIDR(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionTunnel1InsideIPv6CIDRConfig(rName, rBgpAsn, "fd00:2001:db8:2:2d1:81ff:fe41:d200/126", "fd00:2001:db8:2:2d1:81ff:fe41:d204/126"), + Config: testAccSiteVPNConnectionConfig_tunnel1InsideIPv6CIDR(rName, rBgpAsn, "fd00:2001:db8:2:2d1:81ff:fe41:d200/126", "fd00:2001:db8:2:2d1:81ff:fe41:d204/126"), Check: resource.ComposeAggregateTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "tunnel1_inside_ipv6_cidr", "fd00:2001:db8:2:2d1:81ff:fe41:d200/126"), @@ -335,7 +336,7 @@ func TestAccSiteVPNConnection_tunnel1PreSharedKey(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionTunnel1PresharedKeyConfig(rName, rBgpAsn, "tunnel1presharedkey", "tunnel2presharedkey"), + Config: testAccSiteVPNConnectionConfig_tunnel1PresharedKey(rName, rBgpAsn, "tunnel1presharedkey", "tunnel2presharedkey"), Check: resource.ComposeAggregateTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "tunnel1_preshared_key", "tunnel1presharedkey"), @@ -405,63 +406,63 @@ func TestAccSiteVPNConnection_tunnelOptions(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "not-a-cidr"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "not-a-cidr"), ExpectError: regexp.MustCompile(`invalid CIDR address: not-a-cidr`), }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "169.254.254.0/31"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "169.254.254.0/31"), ExpectError: regexp.MustCompile(`expected "\w+" to contain a network Value with between 30 and 30 significant bits`), }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "172.16.0.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "172.16.0.0/30"), ExpectError: regexp.MustCompile(`must be within 169.254.0.0/16`), }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "169.254.0.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "169.254.0.0/30"), ExpectError: badCidrRangeErr, }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "169.254.1.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "169.254.1.0/30"), ExpectError: badCidrRangeErr, }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "169.254.2.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "169.254.2.0/30"), ExpectError: badCidrRangeErr, }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "169.254.3.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "169.254.3.0/30"), ExpectError: badCidrRangeErr, }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "169.254.4.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "169.254.4.0/30"), ExpectError: badCidrRangeErr, }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "169.254.5.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "169.254.5.0/30"), ExpectError: badCidrRangeErr, }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "12345678", "169.254.169.252/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "12345678", "169.254.169.252/30"), ExpectError: badCidrRangeErr, }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "1234567", "169.254.254.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "1234567", "169.254.254.0/30"), ExpectError: regexp.MustCompile(`expected length of \w+ to be in the range \(8 - 64\)`), }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, sdkacctest.RandStringFromCharSet(65, sdkacctest.CharSetAlpha), "169.254.254.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, sdkacctest.RandStringFromCharSet(65, sdkacctest.CharSetAlpha), "169.254.254.0/30"), ExpectError: regexp.MustCompile(`expected length of \w+ to be in the range \(8 - 64\)`), }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "01234567", "169.254.254.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "01234567", "169.254.254.0/30"), ExpectError: regexp.MustCompile(`cannot start with zero character`), }, { - Config: testAccVPNConnectionSingleTunnelOptionsConfig(rName, rBgpAsn, "1234567!", "169.254.254.0/30"), + Config: testAccSiteVPNConnectionConfig_singleTunnelOptions(rName, rBgpAsn, "1234567!", "169.254.254.0/30"), ExpectError: regexp.MustCompile(`can only contain alphanumeric, period and underscore characters`), }, { - Config: testAccVPNConnectionTunnelOptionsConfig(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1, tunnel2), + Config: testAccSiteVPNConnectionConfig_tunnelOptions(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1, tunnel2), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "static_routes_only", "false"), @@ -543,7 +544,7 @@ func TestAccSiteVPNConnection_tunnelOptionsLesser(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionTunnelOptionsConfig(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1, tunnel2), + Config: testAccSiteVPNConnectionConfig_tunnelOptions(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1, tunnel2), Check: resource.ComposeAggregateTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn1), resource.TestCheckResourceAttrSet(resourceName, "tunnel1_address"), @@ -649,7 +650,7 @@ func TestAccSiteVPNConnection_tunnelOptionsLesser(t *testing.T) { }, // Update just tunnel1. { - Config: testAccVPNConnectionTunnelOptionsConfig(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1Updated, tunnel2), + Config: testAccSiteVPNConnectionConfig_tunnelOptions(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1Updated, tunnel2), Check: resource.ComposeAggregateTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn2), testAccCheckVPNConnectionNotRecreated(&vpn1, &vpn2), @@ -756,7 +757,7 @@ func TestAccSiteVPNConnection_tunnelOptionsLesser(t *testing.T) { }, // Update just tunnel2. { - Config: testAccVPNConnectionTunnelOptionsConfig(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1Updated, tunnel2Updated), + Config: testAccSiteVPNConnectionConfig_tunnelOptions(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1Updated, tunnel2Updated), Check: resource.ComposeAggregateTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn3), testAccCheckVPNConnectionNotRecreated(&vpn2, &vpn3), @@ -863,7 +864,7 @@ func TestAccSiteVPNConnection_tunnelOptionsLesser(t *testing.T) { }, // Update tunnel1 and tunnel2. { - Config: testAccVPNConnectionTunnelOptionsConfig(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1, tunnel2), + Config: testAccSiteVPNConnectionConfig_tunnelOptions(rName, rBgpAsn, "192.168.1.1/32", "192.168.1.2/32", tunnel1, tunnel2), Check: resource.ComposeAggregateTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn4), testAccCheckVPNConnectionNotRecreated(&vpn3, &vpn4), @@ -971,7 +972,7 @@ func TestAccSiteVPNConnection_tunnelOptionsLesser(t *testing.T) { // Test resetting to defaults. // [local|remote]_ipv[4|6]_network_cidr, tunnel[1|2]_inside_[ipv6_]cidr and tunnel[1|2]_preshared_key are Computed so no diffs will be detected. { - Config: testAccVPNConnectionConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_basic(rName, rBgpAsn), Check: resource.ComposeAggregateTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn5), testAccCheckVPNConnectionNotRecreated(&vpn4, &vpn5), @@ -984,13 +985,10 @@ func TestAccSiteVPNConnection_tunnelOptionsLesser(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tunnel1_ike_versions.#", "0"), resource.TestCheckResourceAttr(resourceName, "tunnel1_inside_cidr", "169.254.8.0/30"), resource.TestCheckResourceAttr(resourceName, "tunnel1_inside_ipv6_cidr", ""), - resource.TestCheckNoResourceAttr(resourceName, "tunnel1_phase1_dh_group_numbers"), - resource.TestCheckNoResourceAttr(resourceName, "tunnel1_phase1_encryption_algorithms"), - resource.TestCheckNoResourceAttr(resourceName, "tunnel1_phase1_integrity_algorithms"), - resource.TestCheckResourceAttr(resourceName, "tunnel1_phase1_lifetime_seconds", "28800"), resource.TestCheckResourceAttr(resourceName, "tunnel1_phase1_dh_group_numbers.#", "0"), resource.TestCheckResourceAttr(resourceName, "tunnel1_phase1_encryption_algorithms.#", "0"), resource.TestCheckResourceAttr(resourceName, "tunnel1_phase1_integrity_algorithms.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tunnel1_phase1_lifetime_seconds", "28800"), resource.TestCheckResourceAttr(resourceName, "tunnel1_phase2_dh_group_numbers.#", "0"), resource.TestCheckResourceAttr(resourceName, "tunnel1_phase2_encryption_algorithms.#", "0"), resource.TestCheckResourceAttr(resourceName, "tunnel1_phase2_integrity_algorithms.#", "0"), @@ -1045,7 +1043,7 @@ func TestAccSiteVPNConnection_staticRoutes(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionWithStaticRoutesConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_staticRoutes(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "static_routes_only", "true"), @@ -1060,6 +1058,62 @@ func TestAccSiteVPNConnection_staticRoutes(t *testing.T) { }) } +func TestAccSiteVPNConnection_outsideAddressTypePrivate(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rBgpAsn := sdkacctest.RandIntRange(64512, 65534) + resourceName := "aws_vpn_connection.test" + var vpn ec2.VpnConnection + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccVPNConnectionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSiteVPNConnectionConfig_outsideAddressTypePrivate(rName, rBgpAsn), + Check: resource.ComposeTestCheckFunc( + testAccVPNConnectionExists(resourceName, &vpn), + resource.TestCheckResourceAttr(resourceName, "outside_ip_address_type", "PrivateIpv4"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccSiteVPNConnection_outsideAddressTypePublic(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rBgpAsn := sdkacctest.RandIntRange(64512, 65534) + resourceName := "aws_vpn_connection.test" + var vpn ec2.VpnConnection + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccVPNConnectionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSiteVPNConnectionConfig_outsideAddressTypePublic(rName, rBgpAsn), + Check: resource.ComposeTestCheckFunc( + testAccVPNConnectionExists(resourceName, &vpn), + resource.TestCheckResourceAttr(resourceName, "outside_ip_address_type", "PublicIpv4"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestAccSiteVPNConnection_enableAcceleration(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) rBgpAsn := sdkacctest.RandIntRange(64512, 65534) @@ -1073,7 +1127,7 @@ func TestAccSiteVPNConnection_enableAcceleration(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionEnableAccelerationConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_enableAcceleration(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "enable_acceleration", "true"), @@ -1101,7 +1155,7 @@ func TestAccSiteVPNConnection_ipv6(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionIPv6Config(rName, rBgpAsn, "fd00:2001:db8:2:2d1:81ff:fe41:d201/128", "fd00:2001:db8:2:2d1:81ff:fe41:d202/128", "fd00:2001:db8:2:2d1:81ff:fe41:d200/126", "fd00:2001:db8:2:2d1:81ff:fe41:d204/126"), + Config: testAccSiteVPNConnectionConfig_ipv6(rName, rBgpAsn, "fd00:2001:db8:2:2d1:81ff:fe41:d201/128", "fd00:2001:db8:2:2d1:81ff:fe41:d202/128", "fd00:2001:db8:2:2d1:81ff:fe41:d200/126", "fd00:2001:db8:2:2d1:81ff:fe41:d204/126"), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), ), @@ -1128,7 +1182,7 @@ func TestAccSiteVPNConnection_tags(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionTags1Config(rName, rBgpAsn, "key1", "value1"), + Config: testAccSiteVPNConnectionConfig_tags1(rName, rBgpAsn, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1141,7 +1195,7 @@ func TestAccSiteVPNConnection_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNConnectionTags2Config(rName, rBgpAsn, "key1", "value1updated", "key2", "value2"), + Config: testAccSiteVPNConnectionConfig_tags2(rName, rBgpAsn, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1150,7 +1204,7 @@ func TestAccSiteVPNConnection_tags(t *testing.T) { ), }, { - Config: testAccVPNConnectionTags1Config(rName, rBgpAsn, "key2", "value2"), + Config: testAccSiteVPNConnectionConfig_tags1(rName, rBgpAsn, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1174,7 +1228,7 @@ func TestAccSiteVPNConnection_specifyIPv4(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionLocalRemoteIPv4CIDRsConfig(rName, rBgpAsn, "10.111.0.0/16", "10.222.33.0/24"), + Config: testAccSiteVPNConnectionConfig_localRemoteIPv4CIDRs(rName, rBgpAsn, "10.111.0.0/16", "10.222.33.0/24"), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "local_ipv4_network_cidr", "10.111.0.0/16"), @@ -1187,7 +1241,7 @@ func TestAccSiteVPNConnection_specifyIPv4(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNConnectionLocalRemoteIPv4CIDRsConfig(rName, rBgpAsn, "10.112.0.0/16", "10.222.32.0/24"), + Config: testAccSiteVPNConnectionConfig_localRemoteIPv4CIDRs(rName, rBgpAsn, "10.112.0.0/16", "10.222.32.0/24"), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "local_ipv4_network_cidr", "10.112.0.0/16"), @@ -1211,7 +1265,7 @@ func TestAccSiteVPNConnection_specifyIPv6(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionIPv6Config(rName, rBgpAsn, "1111:2222:3333:4444::/64", "5555:6666:7777::/48", "fd00:2001:db8:2:2d1:81ff:fe41:d200/126", "fd00:2001:db8:2:2d1:81ff:fe41:d204/126"), + Config: testAccSiteVPNConnectionConfig_ipv6(rName, rBgpAsn, "1111:2222:3333:4444::/64", "5555:6666:7777::/48", "fd00:2001:db8:2:2d1:81ff:fe41:d200/126", "fd00:2001:db8:2:2d1:81ff:fe41:d204/126"), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "local_ipv6_network_cidr", "1111:2222:3333:4444::/64"), @@ -1235,7 +1289,7 @@ func TestAccSiteVPNConnection_disappears(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_basic(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPNConnection(), resourceName), @@ -1260,7 +1314,7 @@ func TestAccSiteVPNConnection_updateCustomerGatewayID(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionCustomerGatewayIDConfig(rName, rBgpAsn1, rBgpAsn2), + Config: testAccSiteVPNConnectionConfig_customerGatewayID(rName, rBgpAsn1, rBgpAsn2), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn1), resource.TestCheckResourceAttrPair(resourceName, "customer_gateway_id", "aws_customer_gateway.test1", "id"), @@ -1272,7 +1326,7 @@ func TestAccSiteVPNConnection_updateCustomerGatewayID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNConnectionCustomerGatewayIDUpdatedConfig(rName, rBgpAsn1, rBgpAsn2), + Config: testAccSiteVPNConnectionConfig_customerGatewayIDUpdated(rName, rBgpAsn1, rBgpAsn2), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn2), testAccCheckVPNConnectionNotRecreated(&vpn1, &vpn2), @@ -1296,7 +1350,7 @@ func TestAccSiteVPNConnection_updateVPNGatewayID(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionVPNGatewayIDConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_vpnGatewayID(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn1), resource.TestCheckResourceAttrPair(resourceName, "vpn_gateway_id", "aws_vpn_gateway.test1", "id"), @@ -1308,7 +1362,7 @@ func TestAccSiteVPNConnection_updateVPNGatewayID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNConnectionVPNGatewayIDUpdatedConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_vpnGatewayIDUpdated(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn2), testAccCheckVPNConnectionNotRecreated(&vpn1, &vpn2), @@ -1332,7 +1386,7 @@ func TestAccSiteVPNConnection_updateTransitGatewayID(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionTransitGatewayIDConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_transitGatewayID(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn1), resource.TestCheckResourceAttrSet(resourceName, "transit_gateway_attachment_id"), @@ -1345,7 +1399,7 @@ func TestAccSiteVPNConnection_updateTransitGatewayID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNConnectionTransitGatewayIDUpdatedConfig(rName, rBgpAsn), + Config: testAccSiteVPNConnectionConfig_transitGatewayIDUpdated(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn2), testAccCheckVPNConnectionNotRecreated(&vpn1, &vpn2), @@ -1370,7 +1424,7 @@ func TestAccSiteVPNConnection_vpnGatewayIDToTransitGatewayID(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionTransitGatewayIDOrVPNGatewayIDConfig(rName, rBgpAsn, false), + Config: testAccSiteVPNConnectionConfig_transitGatewayIDOrVPNGatewayID(rName, rBgpAsn, false), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn1), resource.TestCheckResourceAttr(resourceName, "transit_gateway_id", ""), @@ -1383,7 +1437,7 @@ func TestAccSiteVPNConnection_vpnGatewayIDToTransitGatewayID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNConnectionTransitGatewayIDOrVPNGatewayIDConfig(rName, rBgpAsn, true), + Config: testAccSiteVPNConnectionConfig_transitGatewayIDOrVPNGatewayID(rName, rBgpAsn, true), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn2), testAccCheckVPNConnectionNotRecreated(&vpn1, &vpn2), @@ -1408,7 +1462,7 @@ func TestAccSiteVPNConnection_transitGatewayIDToVPNGatewayID(t *testing.T) { CheckDestroy: testAccVPNConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNConnectionTransitGatewayIDOrVPNGatewayIDConfig(rName, rBgpAsn, true), + Config: testAccSiteVPNConnectionConfig_transitGatewayIDOrVPNGatewayID(rName, rBgpAsn, true), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn1), resource.TestCheckResourceAttrPair(resourceName, "transit_gateway_id", "aws_ec2_transit_gateway.test", "id"), @@ -1421,7 +1475,7 @@ func TestAccSiteVPNConnection_transitGatewayIDToVPNGatewayID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNConnectionTransitGatewayIDOrVPNGatewayIDConfig(rName, rBgpAsn, false), + Config: testAccSiteVPNConnectionConfig_transitGatewayIDOrVPNGatewayID(rName, rBgpAsn, false), Check: resource.ComposeTestCheckFunc( testAccVPNConnectionExists(resourceName, &vpn2), testAccCheckVPNConnectionNotRecreated(&vpn1, &vpn2), @@ -1492,7 +1546,7 @@ func testAccCheckVPNConnectionNotRecreated(before, after *ec2.VpnConnection) res } } -func testAccVPNConnectionConfig(rName string, rBgpAsn int) string { +func testAccSiteVPNConnectionConfig_basic(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -1518,7 +1572,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn) } -func testAccVPNConnectionCustomerGatewayIDConfig(rName string, rBgpAsn1, rBgpAsn2 int) string { +func testAccSiteVPNConnectionConfig_customerGatewayID(rName string, rBgpAsn1, rBgpAsn2 int) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -1554,7 +1608,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn1, rBgpAsn2) } -func testAccVPNConnectionCustomerGatewayIDUpdatedConfig(rName string, rBgpAsn1, rBgpAsn2 int) string { +func testAccSiteVPNConnectionConfig_customerGatewayIDUpdated(rName string, rBgpAsn1, rBgpAsn2 int) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -1590,7 +1644,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn1, rBgpAsn2) } -func testAccVPNConnectionVPNGatewayIDConfig(rName string, rBgpAsn int) string { +func testAccSiteVPNConnectionConfig_vpnGatewayID(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test1" { tags = { @@ -1622,7 +1676,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn) } -func testAccVPNConnectionVPNGatewayIDUpdatedConfig(rName string, rBgpAsn int) string { +func testAccSiteVPNConnectionConfig_vpnGatewayIDUpdated(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test1" { tags = { @@ -1654,7 +1708,95 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn) } -func testAccVPNConnectionWithStaticRoutesConfig(rName string, rBgpAsn int) string { +func testAccSiteVPNConnectionConfig_outsideAddressTypePrivate(rName string, rBgpAsn int) string { + return fmt.Sprintf(` +resource "aws_dx_gateway" "test" { + name = %[1]q + amazon_side_asn = "64521" +} + +resource "aws_ec2_transit_gateway" "test" { + amazon_side_asn = "64522" + description = %[1]q + transit_gateway_cidr_blocks = [ + "10.0.0.0/24", + ] +} + +resource "aws_customer_gateway" "test" { + bgp_asn = 64523 + ip_address = "10.0.0.1" + type = "ipsec.1" + + tags = { + Name = %[1]q + } +} + +resource "aws_dx_gateway_association" "test" { + dx_gateway_id = aws_dx_gateway.test.id + associated_gateway_id = aws_ec2_transit_gateway.test.id + + allowed_prefixes = [ + "10.0.0.0/8", + ] +} + +data "aws_ec2_transit_gateway_dx_gateway_attachment" "test" { + transit_gateway_id = aws_ec2_transit_gateway.test.id + dx_gateway_id = aws_dx_gateway.test.id + + depends_on = [ + aws_dx_gateway_association.test + ] +} + +resource "aws_vpn_connection" "test" { + customer_gateway_id = aws_customer_gateway.test.id + outside_ip_address_type = "PrivateIpv4" + transit_gateway_id = aws_ec2_transit_gateway.test.id + transport_transit_gateway_attachment_id = data.aws_ec2_transit_gateway_dx_gateway_attachment.test.id + type = "ipsec.1" + + tags = { + Name = %[1]q + } +} +`, rName, rBgpAsn) +} + +func testAccSiteVPNConnectionConfig_outsideAddressTypePublic(rName string, rBgpAsn int) string { + return fmt.Sprintf(` +resource "aws_vpn_gateway" "test" { + tags = { + Name = %[1]q + } +} + +resource "aws_customer_gateway" "test" { + bgp_asn = %[2]d + ip_address = "178.0.0.1" + type = "ipsec.1" + + tags = { + Name = %[1]q + } +} + +resource "aws_vpn_connection" "test" { + customer_gateway_id = aws_customer_gateway.test.id + outside_ip_address_type = "PublicIpv4" + type = "ipsec.1" + vpn_gateway_id = aws_vpn_gateway.test.id + + tags = { + Name = %[1]q + } +} +`, rName, rBgpAsn) +} + +func testAccSiteVPNConnectionConfig_staticRoutes(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -1685,7 +1827,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn) } -func testAccVPNConnectionEnableAccelerationConfig(rName string, rBgpAsn int) string { +func testAccSiteVPNConnectionConfig_enableAcceleration(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { description = %[1]q @@ -1715,7 +1857,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn) } -func testAccVPNConnectionIPv6Config(rName string, rBgpAsn int, localIpv6NetworkCidr string, remoteIpv6NetworkCidr string, tunnel1InsideIpv6Cidr string, tunnel2InsideIpv6Cidr string) string { +func testAccSiteVPNConnectionConfig_ipv6(rName string, rBgpAsn int, localIpv6NetworkCidr string, remoteIpv6NetworkCidr string, tunnel1InsideIpv6Cidr string, tunnel2InsideIpv6Cidr string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { description = %[1]q @@ -1752,7 +1894,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn, localIpv6NetworkCidr, remoteIpv6NetworkCidr, tunnel1InsideIpv6Cidr, tunnel2InsideIpv6Cidr) } -func testAccVPNConnectionSingleTunnelOptionsConfig(rName string, rBgpAsn int, psk string, tunnelCidr string) string { +func testAccSiteVPNConnectionConfig_singleTunnelOptions(rName string, rBgpAsn int, psk string, tunnelCidr string) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -1786,7 +1928,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn, tunnelCidr, psk) } -func testAccVPNConnectionTransitGatewayConfig(rName string, rBgpAsn int) string { +func testAccSiteVPNConnectionConfig_transitGateway(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { description = %[1]q @@ -1814,7 +1956,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn) } -func testAccVPNConnectionTransitGatewayIDConfig(rName string, rBgpAsn int) string { +func testAccSiteVPNConnectionConfig_transitGatewayID(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test1" { description = "%[1]s-1" @@ -1846,7 +1988,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn) } -func testAccVPNConnectionTransitGatewayIDUpdatedConfig(rName string, rBgpAsn int) string { +func testAccSiteVPNConnectionConfig_transitGatewayIDUpdated(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test1" { description = "%[1]s-1" @@ -1878,7 +2020,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn) } -func testAccVPNConnectionTunnel1InsideCIDRConfig(rName string, rBgpAsn int, tunnel1InsideCidr string, tunnel2InsideCidr string) string { +func testAccSiteVPNConnectionConfig_tunnel1InsideCIDR(rName string, rBgpAsn int, tunnel1InsideCidr string, tunnel2InsideCidr string) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -1910,7 +2052,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn, tunnel1InsideCidr, tunnel2InsideCidr) } -func testAccVPNConnectionTunnel1InsideIPv6CIDRConfig(rName string, rBgpAsn int, tunnel1InsideIpv6Cidr string, tunnel2InsideIpv6Cidr string) string { +func testAccSiteVPNConnectionConfig_tunnel1InsideIPv6CIDR(rName string, rBgpAsn int, tunnel1InsideIpv6Cidr string, tunnel2InsideIpv6Cidr string) string { return fmt.Sprintf(` resource "aws_ec2_transit_gateway" "test" { description = %[1]q @@ -1941,7 +2083,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn, tunnel1InsideIpv6Cidr, tunnel2InsideIpv6Cidr) } -func testAccVPNConnectionTunnel1PresharedKeyConfig(rName string, rBgpAsn int, tunnel1PresharedKey string, tunnel2PresharedKey string) string { +func testAccSiteVPNConnectionConfig_tunnel1PresharedKey(rName string, rBgpAsn int, tunnel1PresharedKey string, tunnel2PresharedKey string) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -1973,7 +2115,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn, tunnel1PresharedKey, tunnel2PresharedKey) } -func testAccVPNConnectionTunnelOptionsConfig( +func testAccSiteVPNConnectionConfig_tunnelOptions( rName string, rBgpAsn int, localIpv4NetworkCidr string, @@ -2087,7 +2229,7 @@ resource "aws_vpn_connection" "test" { tunnel2.startupAction) } -func testAccVPNConnectionTags1Config(rName string, rBgpAsn int, tagKey1, tagValue1 string) string { +func testAccSiteVPNConnectionConfig_tags1(rName string, rBgpAsn int, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -2118,7 +2260,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn, tagKey1, tagValue1) } -func testAccVPNConnectionTags2Config(rName string, rBgpAsn int, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSiteVPNConnectionConfig_tags2(rName string, rBgpAsn int, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -2150,7 +2292,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccVPNConnectionLocalRemoteIPv4CIDRsConfig(rName string, rBgpAsn int, localIpv4Cidr string, remoteIpv4Cidr string) string { +func testAccSiteVPNConnectionConfig_localRemoteIPv4CIDRs(rName string, rBgpAsn int, localIpv4Cidr string, remoteIpv4Cidr string) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -2184,7 +2326,7 @@ resource "aws_vpn_connection" "test" { `, rName, rBgpAsn, localIpv4Cidr, remoteIpv4Cidr) } -func testAccVPNConnectionTransitGatewayIDOrVPNGatewayIDConfig(rName string, rBgpAsn int, useTransitGateway bool) string { +func testAccSiteVPNConnectionConfig_transitGatewayIDOrVPNGatewayID(rName string, rBgpAsn int, useTransitGateway bool) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { diff --git a/internal/service/ec2/vpnsite_customer_gateway.go b/internal/service/ec2/vpnsite_customer_gateway.go index 96bed8654d9..9fdd2f2ea57 100644 --- a/internal/service/ec2/vpnsite_customer_gateway.go +++ b/internal/service/ec2/vpnsite_customer_gateway.go @@ -84,7 +84,7 @@ func resourceCustomerGatewayCreate(d *schema.ResourceData, meta interface{}) err input := &ec2.CreateCustomerGatewayInput{ BgpAsn: aws.Int64(i64BgpAsn), - PublicIp: aws.String(d.Get("ip_address").(string)), + IpAddress: aws.String(d.Get("ip_address").(string)), TagSpecifications: tagSpecificationsFromKeyValueTags(tags, ec2.ResourceTypeCustomerGateway), Type: aws.String(d.Get("type").(string)), } diff --git a/internal/service/ec2/vpnsite_customer_gateway_data_source_test.go b/internal/service/ec2/vpnsite_customer_gateway_data_source_test.go index 5b09edf0f0a..993c714a6f4 100644 --- a/internal/service/ec2/vpnsite_customer_gateway_data_source_test.go +++ b/internal/service/ec2/vpnsite_customer_gateway_data_source_test.go @@ -24,7 +24,7 @@ func TestAccSiteVPNCustomerGatewayDataSource_filter(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayFilterDataSourceConfig(rName, asn, hostOctet), + Config: testAccSiteVPNCustomerGatewayDataSourceConfig_filter(rName, asn, hostOctet), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "bgp_asn", dataSourceName, "bgp_asn"), @@ -53,7 +53,7 @@ func TestAccSiteVPNCustomerGatewayDataSource_id(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayIDDataSourceConfig(rName, asn, hostOctet), + Config: testAccSiteVPNCustomerGatewayDataSourceConfig_id(rName, asn, hostOctet), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "bgp_asn", dataSourceName, "bgp_asn"), @@ -68,7 +68,7 @@ func TestAccSiteVPNCustomerGatewayDataSource_id(t *testing.T) { }) } -func testAccCustomerGatewayFilterDataSourceConfig(rName string, asn, hostOctet int) string { +func testAccSiteVPNCustomerGatewayDataSourceConfig_filter(rName string, asn, hostOctet int) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { bgp_asn = %[2]d @@ -89,7 +89,7 @@ data "aws_customer_gateway" "test" { `, rName, asn, hostOctet) } -func testAccCustomerGatewayIDDataSourceConfig(rName string, asn, hostOctet int) string { +func testAccSiteVPNCustomerGatewayDataSourceConfig_id(rName string, asn, hostOctet int) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { bgp_asn = %[2]d diff --git a/internal/service/ec2/vpnsite_customer_gateway_test.go b/internal/service/ec2/vpnsite_customer_gateway_test.go index 4cfbce6fa6a..b440538e638 100644 --- a/internal/service/ec2/vpnsite_customer_gateway_test.go +++ b/internal/service/ec2/vpnsite_customer_gateway_test.go @@ -29,7 +29,7 @@ func TestAccSiteVPNCustomerGateway_basic(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayConfig(rBgpAsn), + Config: testAccSiteVPNCustomerGatewayConfig_basic(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayExists(resourceName, &gateway), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`customer-gateway/cgw-.+`)), @@ -61,7 +61,7 @@ func TestAccSiteVPNCustomerGateway_disappears(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayConfig(rBgpAsn), + Config: testAccSiteVPNCustomerGatewayConfig_basic(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayExists(resourceName, &gateway), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceCustomerGateway(), resourceName), @@ -72,6 +72,38 @@ func TestAccSiteVPNCustomerGateway_disappears(t *testing.T) { }) } +func TestAccSiteVPNCustomerGateway_privateIPv4(t *testing.T) { + var gateway ec2.CustomerGateway + rBgpAsn := sdkacctest.RandIntRange(64512, 65534) + resourceName := "aws_customer_gateway.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckCustomerGatewayDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSiteVPNCustomerGatewayConfig_basic(rBgpAsn), + Check: resource.ComposeTestCheckFunc( + testAccCheckCustomerGatewayExists(resourceName, &gateway), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`customer-gateway/cgw-.+`)), + resource.TestCheckResourceAttr(resourceName, "bgp_asn", strconv.Itoa(rBgpAsn)), + resource.TestCheckResourceAttr(resourceName, "certificate_arn", ""), + resource.TestCheckResourceAttr(resourceName, "device_name", ""), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "type", "ipsec.1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestAccSiteVPNCustomerGateway_tags(t *testing.T) { var gateway ec2.CustomerGateway rBgpAsn := sdkacctest.RandIntRange(64512, 65534) @@ -84,7 +116,7 @@ func TestAccSiteVPNCustomerGateway_tags(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayConfigTags1(rBgpAsn, "key1", "value1"), + Config: testAccSiteVPNCustomerGatewayConfig_tags1(rBgpAsn, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -96,7 +128,7 @@ func TestAccSiteVPNCustomerGateway_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCustomerGatewayConfigTags2(rBgpAsn, "key1", "value1updated", "key2", "value2"), + Config: testAccSiteVPNCustomerGatewayConfig_tags2(rBgpAsn, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -104,7 +136,7 @@ func TestAccSiteVPNCustomerGateway_tags(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2")), }, { - Config: testAccCustomerGatewayConfigTags1(rBgpAsn, "key2", "value2"), + Config: testAccSiteVPNCustomerGatewayConfig_tags1(rBgpAsn, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -127,7 +159,7 @@ func TestAccSiteVPNCustomerGateway_deviceName(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayConfigDeviceName(rName, rBgpAsn), + Config: testAccSiteVPNCustomerGatewayConfig_deviceName(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "device_name", "test"), @@ -155,7 +187,7 @@ func TestAccSiteVPNCustomerGateway_4ByteASN(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccSiteVPNCustomerGatewayConfig_4ByteASN(rName, rBgpAsn), + Config: testAccSiteVPNCustomerGatewayConfig_siteVPN4ByteASN(rName, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "bgp_asn", rBgpAsn), @@ -190,7 +222,7 @@ func TestAccSiteVPNCustomerGateway_certificate(t *testing.T) { Steps: []resource.TestStep{ // We need to create and activate the CAs before issuing a certificate. { - Config: testAccCustomerGatewayConfigCAs(domain), + Config: testAccSiteVPNCustomerGatewayConfig_cas(domain), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(acmRootCAResourceName, &caRoot), acctest.CheckACMPCACertificateAuthorityExists(acmSubordinateCAResourceName, &caSubordinate), @@ -199,7 +231,7 @@ func TestAccSiteVPNCustomerGateway_certificate(t *testing.T) { ), }, { - Config: testAccCustomerGatewayConfigCertificate(rName, rBgpAsn, domain), + Config: testAccSiteVPNCustomerGatewayConfig_certificate(rName, rBgpAsn, domain), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", acmCertificateResourceName, "arn"), @@ -211,7 +243,7 @@ func TestAccSiteVPNCustomerGateway_certificate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCustomerGatewayConfigCertificate(rName, rBgpAsn, domain), + Config: testAccSiteVPNCustomerGatewayConfig_certificate(rName, rBgpAsn, domain), Check: resource.ComposeTestCheckFunc( // CAs must be DISABLED for deletion. acctest.CheckACMPCACertificateAuthorityDisableCA(&caSubordinate), @@ -272,7 +304,7 @@ func testAccCheckCustomerGatewayExists(n string, v *ec2.CustomerGateway) resourc } } -func testAccCustomerGatewayConfig(rBgpAsn int) string { +func testAccSiteVPNCustomerGatewayConfig_basic(rBgpAsn int) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { bgp_asn = %[1]d @@ -282,7 +314,7 @@ resource "aws_customer_gateway" "test" { `, rBgpAsn) } -func testAccCustomerGatewayConfigTags1(rBgpAsn int, tagKey1, tagValue1 string) string { +func testAccSiteVPNCustomerGatewayConfig_tags1(rBgpAsn int, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { bgp_asn = %[1]d @@ -296,7 +328,7 @@ resource "aws_customer_gateway" "test" { `, rBgpAsn, tagKey1, tagValue1) } -func testAccCustomerGatewayConfigTags2(rBgpAsn int, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSiteVPNCustomerGatewayConfig_tags2(rBgpAsn int, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { bgp_asn = %[1]d @@ -311,7 +343,7 @@ resource "aws_customer_gateway" "test" { `, rBgpAsn, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccCustomerGatewayConfigDeviceName(rName string, rBgpAsn int) string { +func testAccSiteVPNCustomerGatewayConfig_deviceName(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { bgp_asn = %[2]d @@ -326,7 +358,7 @@ resource "aws_customer_gateway" "test" { `, rName, rBgpAsn) } -func testAccSiteVPNCustomerGatewayConfig_4ByteASN(rName, rBgpAsn string) string { +func testAccSiteVPNCustomerGatewayConfig_siteVPN4ByteASN(rName, rBgpAsn string) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { bgp_asn = %[2]q @@ -340,7 +372,7 @@ resource "aws_customer_gateway" "test" { `, rName, rBgpAsn) } -func testAccCustomerGatewayConfigCAs(domain string) string { +func testAccSiteVPNCustomerGatewayConfig_cas(domain string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "root" { permanent_deletion_time_in_days = 7 @@ -372,9 +404,9 @@ resource "aws_acmpca_certificate_authority" "test" { `, domain) } -func testAccCustomerGatewayConfigCertificate(rName string, rBgpAsn int, domain string) string { +func testAccSiteVPNCustomerGatewayConfig_certificate(rName string, rBgpAsn int, domain string) string { return acctest.ConfigCompose( - testAccCustomerGatewayConfigCAs(domain), + testAccSiteVPNCustomerGatewayConfig_cas(domain), fmt.Sprintf(` resource "aws_acm_certificate" "test" { domain_name = "test.sub.%[3]s" diff --git a/internal/service/ec2/vpnsite_gateway_attachment_test.go b/internal/service/ec2/vpnsite_gateway_attachment_test.go index bc0ce69d76c..10fab439fa8 100644 --- a/internal/service/ec2/vpnsite_gateway_attachment_test.go +++ b/internal/service/ec2/vpnsite_gateway_attachment_test.go @@ -26,7 +26,7 @@ func TestAccSiteVPNGatewayAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayAttachmentConfig_basic(rName), + Config: testAccSiteVPNGatewayAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayAttachmentExists(resourceName, &v), ), @@ -47,7 +47,7 @@ func TestAccSiteVPNGatewayAttachment_disappears(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayAttachmentConfig_basic(rName), + Config: testAccSiteVPNGatewayAttachmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayAttachmentExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPNGatewayAttachment(), resourceName), @@ -107,7 +107,7 @@ func testAccCheckVPNGatewayAttachmentDestroy(s *terraform.State) error { return nil } -func testAccVPNGatewayAttachmentConfig_basic(rName string) string { +func testAccSiteVPNGatewayAttachmentConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ec2/vpnsite_gateway_data_source_test.go b/internal/service/ec2/vpnsite_gateway_data_source_test.go index 29593e83fc3..85fd7279c16 100644 --- a/internal/service/ec2/vpnsite_gateway_data_source_test.go +++ b/internal/service/ec2/vpnsite_gateway_data_source_test.go @@ -24,7 +24,7 @@ func TestAccSiteVPNGatewayDataSource_unattached(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayUnattachedDataSourceConfig(rName), + Config: testAccSiteVPNGatewayDataSourceConfig_unattached(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceNameById, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(dataSourceNameById, "arn", resourceName, "arn"), @@ -50,7 +50,7 @@ func TestAccSiteVPNGatewayDataSource_attached(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayAttachedDataSourceConfig(rName), + Config: testAccSiteVPNGatewayDataSourceConfig_attached(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", "aws_vpn_gateway.test", "id"), resource.TestCheckResourceAttrPair(dataSourceName, "attached_vpc_id", "aws_vpc.test", "id"), @@ -61,7 +61,7 @@ func TestAccSiteVPNGatewayDataSource_attached(t *testing.T) { }) } -func testAccVPNGatewayUnattachedDataSourceConfig(rName string) string { +func testAccSiteVPNGatewayDataSourceConfig_unattached(rName string) string { return fmt.Sprintf(` resource "aws_vpn_gateway" "test" { tags = { @@ -88,7 +88,7 @@ data "aws_vpn_gateway" "test_by_amazon_side_asn" { `, rName) } -func testAccVPNGatewayAttachedDataSourceConfig(rName string) string { +func testAccSiteVPNGatewayDataSourceConfig_attached(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpnsite_gateway_route_propagation_test.go b/internal/service/ec2/vpnsite_gateway_route_propagation_test.go index 634bbd4df11..d941265b759 100644 --- a/internal/service/ec2/vpnsite_gateway_route_propagation_test.go +++ b/internal/service/ec2/vpnsite_gateway_route_propagation_test.go @@ -25,7 +25,7 @@ func TestAccSiteVPNGatewayRoutePropagation_basic(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayRoutePropagationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayRoutePropagationBasicConfig(rName), + Config: testAccSiteVPNGatewayRoutePropagationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayRoutePropagationExists(resourceName), ), @@ -45,7 +45,7 @@ func TestAccSiteVPNGatewayRoutePropagation_disappears(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayRoutePropagationDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayRoutePropagationBasicConfig(rName), + Config: testAccSiteVPNGatewayRoutePropagationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayRoutePropagationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPNGatewayRoutePropagation(), resourceName), @@ -115,7 +115,7 @@ func testAccCheckVPNGatewayRoutePropagationDestroy(s *terraform.State) error { return nil } -func testAccVPNGatewayRoutePropagationBasicConfig(rName string) string { +func testAccSiteVPNGatewayRoutePropagationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/vpnsite_gateway_test.go b/internal/service/ec2/vpnsite_gateway_test.go index 5bce3f145d4..3f2186ab699 100644 --- a/internal/service/ec2/vpnsite_gateway_test.go +++ b/internal/service/ec2/vpnsite_gateway_test.go @@ -45,7 +45,7 @@ func TestAccSiteVPNGateway_basic(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayConfig_basic(rName), + Config: testAccSiteVPNGatewayConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName, &v1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpn-gateway/vgw-.+`)), @@ -58,7 +58,7 @@ func TestAccSiteVPNGateway_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNGatewayConfig_changeVPC(rName), + Config: testAccSiteVPNGatewayConfig_changeVPC(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName, &v2), testNotEqual, @@ -81,7 +81,7 @@ func TestAccSiteVPNGateway_withAvailabilityZoneSetToState(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayConfig_az(rName), + Config: testAccSiteVPNGatewayConfig_az(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "availability_zone", azDataSourceName, "names.0"), @@ -109,7 +109,7 @@ func TestAccSiteVPNGateway_amazonSideASN(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayConfig_asn(rName), + Config: testAccSiteVPNGatewayConfig_asn(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -137,7 +137,7 @@ func TestAccSiteVPNGateway_disappears(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayConfig_basic(rName), + Config: testAccSiteVPNGatewayConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPNGateway(), resourceName), @@ -196,7 +196,7 @@ func TestAccSiteVPNGateway_reattach(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayConfig_reattach(rName), + Config: testAccSiteVPNGatewayConfig_reattach(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckVPCExists(vpcResourceName1, &vpc1), acctest.CheckVPCExists(vpcResourceName2, &vpc2), @@ -217,7 +217,7 @@ func TestAccSiteVPNGateway_reattach(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNGatewayConfig_reattachChange(rName), + Config: testAccSiteVPNGatewayConfig_reattachChange(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName1, &vgw1), testAccCheckVPNGatewayExists(resourceName2, &vgw2), @@ -226,7 +226,7 @@ func TestAccSiteVPNGateway_reattach(t *testing.T) { ), }, { - Config: testAccVPNGatewayConfig_reattach(rName), + Config: testAccSiteVPNGatewayConfig_reattach(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName1, &vgw1), testAccCheckVPNGatewayExists(resourceName2, &vgw2), @@ -250,7 +250,7 @@ func TestAccSiteVPNGateway_tags(t *testing.T) { CheckDestroy: testAccCheckVPNGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccVPNGatewayConfig_tags1(rName, "key1", "value1"), + Config: testAccSiteVPNGatewayConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -263,7 +263,7 @@ func TestAccSiteVPNGateway_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVPNGatewayConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccSiteVPNGatewayConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -272,7 +272,7 @@ func TestAccSiteVPNGateway_tags(t *testing.T) { ), }, { - Config: testAccVPNGatewayConfig_tags1(rName, "key2", "value2"), + Config: testAccSiteVPNGatewayConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVPNGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -332,7 +332,7 @@ func testAccCheckVPNGatewayExists(n string, v *ec2.VpnGateway) resource.TestChec } } -func testAccVPNGatewayConfig_basic(rName string) string { +func testAccSiteVPNGatewayConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "10.1.0.0/16" @@ -348,7 +348,7 @@ resource "aws_vpn_gateway" "test" { `, rName) } -func testAccVPNGatewayConfig_changeVPC(rName string) string { +func testAccSiteVPNGatewayConfig_changeVPC(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "10.1.0.0/16" @@ -372,7 +372,7 @@ resource "aws_vpn_gateway" "test" { `, rName) } -func testAccVPNGatewayConfig_tags1(rName, tagKey1, tagValue1 string) string { +func testAccSiteVPNGatewayConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -392,7 +392,7 @@ resource "aws_vpn_gateway" "test" { `, rName, tagKey1, tagValue1) } -func testAccVPNGatewayConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSiteVPNGatewayConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -413,7 +413,7 @@ resource "aws_vpn_gateway" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccVPNGatewayConfig_reattach(rName string) string { +func testAccSiteVPNGatewayConfig_reattach(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "10.1.0.0/16" @@ -449,7 +449,7 @@ resource "aws_vpn_gateway" "test2" { `, rName) } -func testAccVPNGatewayConfig_reattachChange(rName string) string { +func testAccSiteVPNGatewayConfig_reattachChange(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test1" { cidr_block = "10.1.0.0/16" @@ -485,7 +485,7 @@ resource "aws_vpn_gateway" "test2" { `, rName) } -func testAccVPNGatewayConfig_az(rName string) string { +func testAccSiteVPNGatewayConfig_az(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -506,7 +506,7 @@ resource "aws_vpn_gateway" "test" { `, rName)) } -func testAccVPNGatewayConfig_asn(rName string) string { +func testAccSiteVPNGatewayConfig_asn(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" diff --git a/internal/service/ec2/wait.go b/internal/service/ec2/wait.go index 44afde38c31..7e9c9c54535 100644 --- a/internal/service/ec2/wait.go +++ b/internal/service/ec2/wait.go @@ -2266,8 +2266,8 @@ func WaitVPCEndpointDeleted(conn *ec2.EC2, vpcEndpointID string, timeout time.Du stateConf := &resource.StateChangeConf{ Pending: []string{vpcEndpointStateDeleting}, Target: []string{}, - Timeout: timeout, Refresh: StatusVPCEndpointState(conn, vpcEndpointID), + Timeout: timeout, Delay: 5 * time.Second, MinTimeout: 5 * time.Second, } @@ -2281,6 +2281,44 @@ func WaitVPCEndpointDeleted(conn *ec2.EC2, vpcEndpointID string, timeout time.Du return nil, err } +func WaitVPCEndpointServiceAvailable(conn *ec2.EC2, id string, timeout time.Duration) (*ec2.ServiceConfiguration, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.ServiceStatePending}, + Target: []string{ec2.ServiceStateAvailable}, + Refresh: StatusVPCEndpointServiceStateAvailable(conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.ServiceConfiguration); ok { + return output, err + } + + return nil, err +} + +func WaitVPCEndpointServiceDeleted(conn *ec2.EC2, id string, timeout time.Duration) (*ec2.ServiceConfiguration, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.ServiceStateAvailable, ec2.ServiceStateDeleting}, + Target: []string{}, + Timeout: timeout, + Refresh: StatusVPCEndpointServiceStateDeleted(conn, id), + Delay: 5 * time.Second, + MinTimeout: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.ServiceConfiguration); ok { + return output, err + } + + return nil, err +} + func WaitVPCEndpointRouteTableAssociationDeleted(conn *ec2.EC2, vpcEndpointID, routeTableID string) error { stateConf := &resource.StateChangeConf{ Pending: []string{VPCEndpointRouteTableAssociationStatusReady}, @@ -2309,7 +2347,7 @@ func WaitVPCEndpointRouteTableAssociationReady(conn *ec2.EC2, vpcEndpointID, rou return err } -func WaitEBSSnapshotImportComplete(conn *ec2.EC2, importTaskID string) (*ec2.SnapshotTaskDetail, error) { +func WaitEBSSnapshotImportComplete(conn *ec2.EC2, importTaskID string, timeout time.Duration) (*ec2.SnapshotTaskDetail, error) { stateConf := &resource.StateChangeConf{ Pending: []string{ EBSSnapshotImportStateActive, @@ -2320,7 +2358,7 @@ func WaitEBSSnapshotImportComplete(conn *ec2.EC2, importTaskID string) (*ec2.Sna }, Target: []string{EBSSnapshotImportStateCompleted}, Refresh: StatusEBSSnapshotImport(conn, importTaskID), - Timeout: 60 * time.Minute, + Timeout: timeout, Delay: 10 * time.Second, } @@ -2354,35 +2392,26 @@ func waitVPCEndpointConnectionAccepted(conn *ec2.EC2, serviceID, vpcEndpointID s return nil, err } -func WaitEBSSnapshotTierArchive(conn *ec2.EC2, id string) (*ec2.SnapshotTierStatus, error) { +const ( + ebsSnapshotArchivedTimeout = 60 * time.Minute +) + +func waitEBSSnapshotTierArchive(conn *ec2.EC2, id string, timeout time.Duration) (*ec2.SnapshotTierStatus, error) { //nolint:unparam stateConf := &resource.StateChangeConf{ - Pending: []string{"standard"}, + Pending: []string{TargetStorageTierStandard}, Target: []string{ec2.TargetStorageTierArchive}, - Refresh: StatusSnapshotTierStatus(conn, id), - Timeout: 60 * time.Minute, + Refresh: StatusSnapshotStorageTier(conn, id), + Timeout: timeout, Delay: 10 * time.Second, } - detail, err := stateConf.WaitForState() - if err != nil { - return nil, err - } else { - return detail.(*ec2.SnapshotTierStatus), nil - } -} + outputRaw, err := stateConf.WaitForState() -// WaitVolumeAttachmentAttached waits for a VolumeAttachment to return Attached -func WaitVolumeAttachmentAttached(conn *ec2.EC2, name, volumeID, instanceID string) error { - stateConf := &resource.StateChangeConf{ - Pending: []string{ec2.VolumeAttachmentStateAttaching}, - Target: []string{ec2.VolumeAttachmentStateAttached}, - Refresh: volumeAttachmentStateRefreshFunc(conn, name, volumeID, instanceID), - Timeout: 5 * time.Minute, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } + if output, ok := outputRaw.(*ec2.SnapshotTierStatus); ok { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.StringValue(output.LastTieringOperationStatus), aws.StringValue(output.LastTieringOperationStatusDetail))) - _, err := stateConf.WaitForState() + return output, err + } - return err + return nil, err } diff --git a/internal/service/ec2/wavelength_carrier_gateway_test.go b/internal/service/ec2/wavelength_carrier_gateway_test.go index 16f65fdaa83..68c4cc88b46 100644 --- a/internal/service/ec2/wavelength_carrier_gateway_test.go +++ b/internal/service/ec2/wavelength_carrier_gateway_test.go @@ -29,7 +29,7 @@ func TestAccWavelengthCarrierGateway_basic(t *testing.T) { CheckDestroy: testAccCheckCarrierGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCarrierGatewayConfig_basic(rName), + Config: testAccWavelengthCarrierGatewayConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCarrierGatewayExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`carrier-gateway/cagw-.+`)), @@ -59,7 +59,7 @@ func TestAccWavelengthCarrierGateway_disappears(t *testing.T) { CheckDestroy: testAccCheckCarrierGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCarrierGatewayConfig_basic(rName), + Config: testAccWavelengthCarrierGatewayConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCarrierGatewayExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceCarrierGateway(), resourceName), @@ -82,7 +82,7 @@ func TestAccWavelengthCarrierGateway_tags(t *testing.T) { CheckDestroy: testAccCheckCarrierGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCarrierGatewayConfig_tags1(rName, "key1", "value1"), + Config: testAccWavelengthCarrierGatewayConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckCarrierGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -95,7 +95,7 @@ func TestAccWavelengthCarrierGateway_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCarrierGatewayConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccWavelengthCarrierGatewayConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCarrierGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -104,7 +104,7 @@ func TestAccWavelengthCarrierGateway_tags(t *testing.T) { ), }, { - Config: testAccCarrierGatewayConfig_tags1(rName, "key2", "value2"), + Config: testAccWavelengthCarrierGatewayConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCarrierGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -197,7 +197,7 @@ func testAccPreCheckWavelengthZoneAvailable(t *testing.T) { } } -func testAccCarrierGatewayConfig_basic(rName string) string { +func testAccWavelengthCarrierGatewayConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -213,7 +213,7 @@ resource "aws_ec2_carrier_gateway" "test" { `, rName) } -func testAccCarrierGatewayConfig_tags1(rName, tagKey1, tagValue1 string) string { +func testAccWavelengthCarrierGatewayConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -233,7 +233,7 @@ resource "aws_ec2_carrier_gateway" "test" { `, rName, tagKey1, tagValue1) } -func testAccCarrierGatewayConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccWavelengthCarrierGatewayConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ecr/authorization_token_data_source_test.go b/internal/service/ecr/authorization_token_data_source_test.go index 65ebee2ee1e..9e687f8ea96 100644 --- a/internal/service/ecr/authorization_token_data_source_test.go +++ b/internal/service/ecr/authorization_token_data_source_test.go @@ -21,7 +21,7 @@ func TestAccECRAuthorizationTokenDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAuthorizationTokenBasicDataSourceConfig, + Config: testAccAuthorizationTokenDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "authorization_token"), resource.TestCheckResourceAttrSet(dataSourceName, "proxy_endpoint"), @@ -32,7 +32,7 @@ func TestAccECRAuthorizationTokenDataSource_basic(t *testing.T) { ), }, { - Config: testAccCheckAuthorizationTokenRepositoryDataSourceConfig(rName), + Config: testAccAuthorizationTokenDataSourceConfig_repository(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "registry_id", "aws_ecr_repository.repo", "registry_id"), resource.TestCheckResourceAttrSet(dataSourceName, "authorization_token"), @@ -47,11 +47,11 @@ func TestAccECRAuthorizationTokenDataSource_basic(t *testing.T) { }) } -var testAccCheckAuthorizationTokenBasicDataSourceConfig = ` +var testAccAuthorizationTokenDataSourceConfig_basic = ` data "aws_ecr_authorization_token" "repo" {} ` -func testAccCheckAuthorizationTokenRepositoryDataSourceConfig(rName string) string { +func testAccAuthorizationTokenDataSourceConfig_repository(rName string) string { return fmt.Sprintf(` resource "aws_ecr_repository" "repo" { name = %q diff --git a/internal/service/ecr/image_data_source_test.go b/internal/service/ecr/image_data_source_test.go index 99eb72c1a9a..3e71991f492 100644 --- a/internal/service/ecr/image_data_source_test.go +++ b/internal/service/ecr/image_data_source_test.go @@ -22,7 +22,7 @@ func TestAccECRImageDataSource_ecrImage(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckImageDataSourceConfig(registry, repo, tag), + Config: testAccImageDataSourceConfig_basic(registry, repo, tag), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceByTag, "image_digest"), resource.TestCheckResourceAttrSet(resourceByTag, "image_pushed_at"), @@ -37,7 +37,7 @@ func TestAccECRImageDataSource_ecrImage(t *testing.T) { }) } -func testAccCheckImageDataSourceConfig(reg, repo, tag string) string { +func testAccImageDataSourceConfig_basic(reg, repo, tag string) string { return fmt.Sprintf(` data "aws_ecr_image" "by_tag" { registry_id = "%s" diff --git a/internal/service/ecr/pull_through_cache_rule_test.go b/internal/service/ecr/pull_through_cache_rule_test.go index 4c434714892..f29ca677587 100644 --- a/internal/service/ecr/pull_through_cache_rule_test.go +++ b/internal/service/ecr/pull_through_cache_rule_test.go @@ -27,7 +27,7 @@ func TestAccECRPullThroughCacheRule_basic(t *testing.T) { CheckDestroy: testAccCheckPullThroughCacheRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccPullThroughCacheRuleConfig(repositoryPrefix), + Config: testAccPullThroughCacheRuleConfig_basic(repositoryPrefix), Check: resource.ComposeTestCheckFunc( testAccCheckPullThroughCacheRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "ecr_repository_prefix", repositoryPrefix), @@ -55,7 +55,7 @@ func TestAccECRPullThroughCacheRule_disappears(t *testing.T) { CheckDestroy: testAccCheckPullThroughCacheRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccPullThroughCacheRuleConfig(repositoryPrefix), + Config: testAccPullThroughCacheRuleConfig_basic(repositoryPrefix), Check: resource.ComposeTestCheckFunc( testAccCheckPullThroughCacheRuleExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfecr.ResourcePullThroughCacheRule(), resourceName), @@ -145,7 +145,7 @@ func testAccCheckPullThroughCacheRuleRegistryID(resourceName string) resource.Te } } -func testAccPullThroughCacheRuleConfig(repositoryPrefix string) string { +func testAccPullThroughCacheRuleConfig_basic(repositoryPrefix string) string { return fmt.Sprintf(` resource "aws_ecr_pull_through_cache_rule" "test" { ecr_repository_prefix = %[1]q diff --git a/internal/service/ecr/registry_policy_test.go b/internal/service/ecr/registry_policy_test.go index 7d7029deacc..0e0a0259dc0 100644 --- a/internal/service/ecr/registry_policy_test.go +++ b/internal/service/ecr/registry_policy_test.go @@ -40,7 +40,7 @@ func testAccRegistryPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckRegistryPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryPolicy(), + Config: testAccRegistryPolicyConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryPolicyExists(resourceName, &v), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(`"ecr:ReplicateImage".+`)), @@ -53,7 +53,7 @@ func testAccRegistryPolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRegistryPolicyUpdated(), + Config: testAccRegistryPolicyConfig_updated(), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryPolicyExists(resourceName, &v), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(`"ecr:ReplicateImage".+`)), @@ -76,7 +76,7 @@ func testAccRegistryPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckRegistryPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryPolicy(), + Config: testAccRegistryPolicyConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryPolicyExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfecr.ResourceRegistryPolicy(), resourceName), @@ -134,7 +134,7 @@ func testAccCheckRegistryPolicyExists(name string, res *ecr.GetRegistryPolicyOut } } -func testAccRegistryPolicy() string { +func testAccRegistryPolicyConfig_basic() string { return ` data "aws_caller_identity" "current" {} @@ -161,7 +161,7 @@ resource "aws_ecr_registry_policy" "test" { ` } -func testAccRegistryPolicyUpdated() string { +func testAccRegistryPolicyConfig_updated() string { return ` data "aws_caller_identity" "current" {} diff --git a/internal/service/ecr/registry_scanning_configuration_test.go b/internal/service/ecr/registry_scanning_configuration_test.go index 232533dd281..fdb2c5f1b3e 100644 --- a/internal/service/ecr/registry_scanning_configuration_test.go +++ b/internal/service/ecr/registry_scanning_configuration_test.go @@ -37,7 +37,7 @@ func testAccRegistryScanningConfiguration_basic(t *testing.T) { CheckDestroy: testAccRegistryScanningConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryScanningConfigurationConfig(), + Config: testAccRegistryScanningConfigurationConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccRegistryScanningConfigurationExists(resourceName, &v), acctest.CheckResourceAttrAccountID(resourceName, "registry_id"), @@ -65,7 +65,7 @@ func testAccRegistryScanningConfiguration_update(t *testing.T) { CheckDestroy: testAccRegistryScanningConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryScanningConfigurationConfigOneRule(), + Config: testAccRegistryScanningConfigurationConfig_oneRule(), Check: resource.ComposeTestCheckFunc( testAccRegistryScanningConfigurationExists(resourceName, &v), acctest.CheckResourceAttrAccountID(resourceName, "registry_id"), @@ -86,7 +86,7 @@ func testAccRegistryScanningConfiguration_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRegistryScanningConfigurationConfigTwoRules(), + Config: testAccRegistryScanningConfigurationConfig_twoRules(), Check: resource.ComposeTestCheckFunc( testAccRegistryScanningConfigurationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "rule.#", "2"), @@ -154,7 +154,7 @@ func testAccRegistryScanningConfigurationExists(name string, v *ecr.GetRegistryS } } -func testAccRegistryScanningConfigurationConfig() string { +func testAccRegistryScanningConfigurationConfig_basic() string { return ` resource "aws_ecr_registry_scanning_configuration" "test" { scan_type = "BASIC" @@ -162,7 +162,7 @@ resource "aws_ecr_registry_scanning_configuration" "test" { ` } -func testAccRegistryScanningConfigurationConfigOneRule() string { +func testAccRegistryScanningConfigurationConfig_oneRule() string { return ` resource "aws_ecr_registry_scanning_configuration" "test" { scan_type = "BASIC" @@ -177,7 +177,7 @@ resource "aws_ecr_registry_scanning_configuration" "test" { ` } -func testAccRegistryScanningConfigurationConfigTwoRules() string { +func testAccRegistryScanningConfigurationConfig_twoRules() string { return ` resource "aws_ecr_registry_scanning_configuration" "test" { scan_type = "ENHANCED" diff --git a/internal/service/ecr/replication_configuration_test.go b/internal/service/ecr/replication_configuration_test.go index 1714135ba74..4cb1efff84f 100644 --- a/internal/service/ecr/replication_configuration_test.go +++ b/internal/service/ecr/replication_configuration_test.go @@ -36,7 +36,7 @@ func testAccReplicationConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckReplicationConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationConfiguration(acctest.AlternateRegion()), + Config: testAccReplicationConfigurationConfig_basic(acctest.AlternateRegion()), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationConfigurationExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "registry_id"), @@ -54,7 +54,7 @@ func testAccReplicationConfiguration_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccReplicationMultipleRegionConfiguration(acctest.AlternateRegion(), acctest.ThirdRegion()), + Config: testAccReplicationConfigurationConfig_multipleRegion(acctest.AlternateRegion(), acctest.ThirdRegion()), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationConfigurationExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "registry_id"), @@ -69,7 +69,7 @@ func testAccReplicationConfiguration_basic(t *testing.T) { ), }, { - Config: testAccReplicationConfiguration(acctest.AlternateRegion()), + Config: testAccReplicationConfigurationConfig_basic(acctest.AlternateRegion()), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationConfigurationExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "registry_id"), @@ -95,7 +95,7 @@ func testAccReplicationConfiguration_repositoryFilter(t *testing.T) { CheckDestroy: testAccCheckReplicationConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationConfigurationRepositoryFilter(acctest.AlternateRegion()), + Config: testAccReplicationConfigurationConfig_repositoryFilter(acctest.AlternateRegion()), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationConfigurationExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "registry_id"), @@ -113,7 +113,7 @@ func testAccReplicationConfiguration_repositoryFilter(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccReplicationConfigurationRepositoryFilterMultiple(acctest.AlternateRegion()), + Config: testAccReplicationConfigurationConfig_repositoryFilterMultiple(acctest.AlternateRegion()), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationConfigurationExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "registry_id"), @@ -127,7 +127,7 @@ func testAccReplicationConfiguration_repositoryFilter(t *testing.T) { ), }, { - Config: testAccReplicationConfigurationRepositoryFilter(acctest.AlternateRegion()), + Config: testAccReplicationConfigurationConfig_repositoryFilter(acctest.AlternateRegion()), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationConfigurationExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "registry_id"), @@ -185,7 +185,7 @@ func testAccCheckReplicationConfigurationDestroy(s *terraform.State) error { return nil } -func testAccReplicationConfiguration(region string) string { +func testAccReplicationConfigurationConfig_basic(region string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -202,7 +202,7 @@ resource "aws_ecr_replication_configuration" "test" { `, region) } -func testAccReplicationMultipleRegionConfiguration(region1, region2 string) string { +func testAccReplicationConfigurationConfig_multipleRegion(region1, region2 string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -225,7 +225,7 @@ resource "aws_ecr_replication_configuration" "test" { `, region1, region2) } -func testAccReplicationConfigurationRepositoryFilter(region string) string { +func testAccReplicationConfigurationConfig_repositoryFilter(region string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -247,7 +247,7 @@ resource "aws_ecr_replication_configuration" "test" { `, region) } -func testAccReplicationConfigurationRepositoryFilterMultiple(region string) string { +func testAccReplicationConfigurationConfig_repositoryFilterMultiple(region string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/ecr/repository.go b/internal/service/ecr/repository.go index e7bdb6b2435..1a69873ba74 100644 --- a/internal/service/ecr/repository.go +++ b/internal/service/ecr/repository.go @@ -137,7 +137,7 @@ func resourceRepositoryCreate(d *schema.ResourceData, meta interface{}) error { out, err := conn.CreateRepository(&input) // Some partitions (i.e., ISO) may not support tag-on-create - if input.Tags != nil && meta.(*conns.AWSClient).Partition != endpoints.AwsPartitionID && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && meta.(*conns.AWSClient).Partition != endpoints.AwsPartitionID && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating ECR Repository (%s) with tags: %s. Trying create without tags.", d.Get("name").(string), err) input.Tags = nil @@ -159,7 +159,7 @@ func resourceRepositoryCreate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, aws.StringValue(repository.RepositoryArn), nil, tags) // If default tags only, log and continue. Otherwise, error. - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed adding tags after create for ECR Repository (%s): %s", d.Id(), err) return resourceRepositoryRead(d, meta) } @@ -237,7 +237,7 @@ func resourceRepositoryRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, arn) // Some partitions (i.e., ISO) may not support tagging, giving error - if meta.(*conns.AWSClient).Partition != endpoints.AwsPartitionID && verify.CheckISOErrorTagsUnsupported(err) { + if meta.(*conns.AWSClient).Partition != endpoints.AwsPartitionID && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed listing tags for ECR Repository (%s): %s", d.Id(), err) return nil } @@ -327,7 +327,7 @@ func resourceRepositoryUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, arn, o, n) // Some partitions may not support tagging, giving error - if meta.(*conns.AWSClient).Partition != endpoints.AwsPartitionID && verify.CheckISOErrorTagsUnsupported(err) { + if meta.(*conns.AWSClient).Partition != endpoints.AwsPartitionID && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed updating tags for ECR Repository (%s): %s", d.Id(), err) return resourceRepositoryRead(d, meta) } diff --git a/internal/service/ecr/repository_data_source.go b/internal/service/ecr/repository_data_source.go index e7e5f50bdd2..46d059c284c 100644 --- a/internal/service/ecr/repository_data_source.go +++ b/internal/service/ecr/repository_data_source.go @@ -116,7 +116,7 @@ func dataSourceRepositoryRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, arn) // Some partitions (i.e., ISO) may not support tagging, giving error - if meta.(*conns.AWSClient).Partition != endpoints.AwsPartitionID && verify.CheckISOErrorTagsUnsupported(err) { + if meta.(*conns.AWSClient).Partition != endpoints.AwsPartitionID && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed listing tags for ECR Repository (%s): %s", d.Id(), err) return nil } diff --git a/internal/service/ecr/repository_data_source_test.go b/internal/service/ecr/repository_data_source_test.go index 29199ee4fd3..2ef981bd76f 100644 --- a/internal/service/ecr/repository_data_source_test.go +++ b/internal/service/ecr/repository_data_source_test.go @@ -22,7 +22,7 @@ func TestAccECRRepositoryDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckRepositoryDataSourceConfig(rName), + Config: testAccRepositoryDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "registry_id", dataSourceName, "registry_id"), @@ -48,7 +48,7 @@ func TestAccECRRepositoryDataSource_encryption(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckRepositoryDataSourceConfig_encryption(rName), + Config: testAccRepositoryDataSourceConfig_encryption(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "registry_id", dataSourceName, "registry_id"), @@ -86,7 +86,7 @@ data "aws_ecr_repository" "test" { } ` -func testAccCheckRepositoryDataSourceConfig(rName string) string { +func testAccRepositoryDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecr_repository" "test" { name = %q @@ -103,7 +103,7 @@ data "aws_ecr_repository" "test" { `, rName) } -func testAccCheckRepositoryDataSourceConfig_encryption(rName string) string { +func testAccRepositoryDataSourceConfig_encryption(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" {} diff --git a/internal/service/ecr/repository_policy_test.go b/internal/service/ecr/repository_policy_test.go index f16fe7cf932..f1d98980e53 100644 --- a/internal/service/ecr/repository_policy_test.go +++ b/internal/service/ecr/repository_policy_test.go @@ -27,7 +27,7 @@ func TestAccECRRepositoryPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckRepositoryPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPolicyConfig(rName), + Config: testAccRepositoryPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPolicyExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "repository", "aws_ecr_repository.test", "name"), @@ -41,7 +41,7 @@ func TestAccECRRepositoryPolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryPolicyUpdatedConfig(rName), + Config: testAccRepositoryPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPolicyExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "repository", "aws_ecr_repository.test", "name"), @@ -65,7 +65,7 @@ func TestAccECRRepositoryPolicy_IAM_basic(t *testing.T) { CheckDestroy: testAccCheckRepositoryPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPolicyIAMRoleConfig(rName), + Config: testAccRepositoryPolicyConfig_iamRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPolicyExists(resourceName), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(rName)), @@ -93,7 +93,7 @@ func TestAccECRRepositoryPolicy_IAM_principalOrder(t *testing.T) { CheckDestroy: testAccCheckRepositoryPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPolicyIAMRoleOrderJSONEncodeConfig(rName), + Config: testAccRepositoryPolicyConfig_iamRoleOrderJSONEncode(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPolicyExists(resourceName), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(rName)), @@ -101,13 +101,13 @@ func TestAccECRRepositoryPolicy_IAM_principalOrder(t *testing.T) { ), }, { - Config: testAccRepositoryPolicyIAMRoleNewOrderJSONEncodeConfig(rName), + Config: testAccRepositoryPolicyConfig_iamRoleNewOrderJSONEncode(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPolicyExists(resourceName), ), }, { - Config: testAccRepositoryPolicyIAMRoleOrderJSONEncodeConfig(rName), + Config: testAccRepositoryPolicyConfig_iamRoleOrderJSONEncode(rName), PlanOnly: true, }, }, @@ -125,7 +125,7 @@ func TestAccECRRepositoryPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckRepositoryPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPolicyConfig(rName), + Config: testAccRepositoryPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfecr.ResourceRepositoryPolicy(), resourceName), @@ -147,7 +147,7 @@ func TestAccECRRepositoryPolicy_Disappears_repository(t *testing.T) { CheckDestroy: testAccCheckRepositoryPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryPolicyConfig(rName), + Config: testAccRepositoryPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfecr.ResourceRepository(), resourceName), @@ -193,7 +193,7 @@ func testAccCheckRepositoryPolicyExists(name string) resource.TestCheckFunc { } } -func testAccRepositoryPolicyConfig(rName string) string { +func testAccRepositoryPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecr_repository" "test" { name = %[1]q @@ -215,7 +215,7 @@ resource "aws_ecr_repository_policy" "test" { `, rName) } -func testAccRepositoryPolicyUpdatedConfig(rName string) string { +func testAccRepositoryPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_ecr_repository" "test" { name = %[1]q @@ -240,11 +240,11 @@ resource "aws_ecr_repository_policy" "test" { `, rName) } -// testAccRepositoryPolicyIAMRoleConfig creates a new IAM Role and tries +// testAccRepositoryPolicyConfig_iamRole creates a new IAM Role and tries // to use it's ARN in an ECR Repository Policy. IAM changes need some time to // be propagated to other services - like ECR. So the following code should // exercise our retry logic, since we try to use the new resource instantly. -func testAccRepositoryPolicyIAMRoleConfig(rName string) string { +func testAccRepositoryPolicyConfig_iamRole(rName string) string { return fmt.Sprintf(` resource "aws_ecr_repository" "test" { name = %[1]q @@ -368,7 +368,7 @@ resource "aws_ecr_repository" "test" { `, rName) } -func testAccRepositoryPolicyIAMRoleOrderJSONEncodeConfig(rName string) string { +func testAccRepositoryPolicyConfig_iamRoleOrderJSONEncode(rName string) string { return acctest.ConfigCompose( testAccRepositoryPolicyIAMRoleOrderBaseConfig(rName), fmt.Sprintf(` @@ -396,7 +396,7 @@ resource "aws_ecr_repository_policy" "test" { `, rName)) } -func testAccRepositoryPolicyIAMRoleNewOrderJSONEncodeConfig(rName string) string { +func testAccRepositoryPolicyConfig_iamRoleNewOrderJSONEncode(rName string) string { return acctest.ConfigCompose( testAccRepositoryPolicyIAMRoleOrderBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/ecr/repository_test.go b/internal/service/ecr/repository_test.go index 91afcebffd0..d682a1efe20 100644 --- a/internal/service/ecr/repository_test.go +++ b/internal/service/ecr/repository_test.go @@ -28,7 +28,7 @@ func TestAccECRRepository_basic(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryConfig(rName), + Config: testAccRepositoryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ecr", fmt.Sprintf("repository/%s", rName)), @@ -122,7 +122,7 @@ func TestAccECRRepository_Image_scanning(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryConfig_image_scanning_configuration(rName, true), + Config: testAccRepositoryConfig_imageScanningConfiguration(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -137,13 +137,13 @@ func TestAccECRRepository_Image_scanning(t *testing.T) { }, { // Test that the removal of the non-default image_scanning_configuration causes plan changes - Config: testAccRepositoryConfig(rName), + Config: testAccRepositoryConfig_basic(rName), PlanOnly: true, ExpectNonEmptyPlan: true, }, { // Test attribute update - Config: testAccRepositoryConfig_image_scanning_configuration(rName, false), + Config: testAccRepositoryConfig_imageScanningConfiguration(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "image_scanning_configuration.#", "1"), @@ -152,7 +152,7 @@ func TestAccECRRepository_Image_scanning(t *testing.T) { }, { // Test that the removal of the default image_scanning_configuration doesn't cause any plan changes - Config: testAccRepositoryConfig(rName), + Config: testAccRepositoryConfig_basic(rName), PlanOnly: true, ExpectNonEmptyPlan: false, }, @@ -173,7 +173,7 @@ func TestAccECRRepository_Encryption_kms(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryConfig_encryption_kms_defaultkey(rName), + Config: testAccRepositoryConfig_encryptionKMSDefaultkey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "encryption_configuration.#", "1"), @@ -188,7 +188,7 @@ func TestAccECRRepository_Encryption_kms(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryConfig_encryption_kms_customkey(rName), + Config: testAccRepositoryConfig_encryptionKMSCustomkey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v2), testAccCheckRepositoryRecreated(&v1, &v2), @@ -219,13 +219,13 @@ func TestAccECRRepository_Encryption_aes256(t *testing.T) { Steps: []resource.TestStep{ { // Test that the addition of the default encryption_configuration doesn't recreation in the next step - Config: testAccRepositoryConfig(rName), + Config: testAccRepositoryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v1), ), }, { - Config: testAccRepositoryConfig_encryption_aes256(rName), + Config: testAccRepositoryConfig_encryptionAES256(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v2), testAccCheckRepositoryNotRecreated(&v1, &v2), @@ -241,7 +241,7 @@ func TestAccECRRepository_Encryption_aes256(t *testing.T) { }, { // Test that the removal of the default encryption_configuration doesn't cause any plan changes - Config: testAccRepositoryConfig(rName), + Config: testAccRepositoryConfig_basic(rName), PlanOnly: true, }, }, @@ -343,7 +343,7 @@ func testAccCheckRepositoryNotRecreated(i, j *ecr.Repository) resource.TestCheck } } -func testAccRepositoryConfig(rName string) string { +func testAccRepositoryConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecr_repository" "test" { name = %q @@ -385,7 +385,7 @@ resource "aws_ecr_repository" "test" { `, rName) } -func testAccRepositoryConfig_image_scanning_configuration(rName string, scanOnPush bool) string { +func testAccRepositoryConfig_imageScanningConfiguration(rName string, scanOnPush bool) string { return fmt.Sprintf(` resource "aws_ecr_repository" "test" { name = %q @@ -397,7 +397,7 @@ resource "aws_ecr_repository" "test" { `, rName, scanOnPush) } -func testAccRepositoryConfig_encryption_kms_defaultkey(rName string) string { +func testAccRepositoryConfig_encryptionKMSDefaultkey(rName string) string { return fmt.Sprintf(` resource "aws_ecr_repository" "test" { name = %q @@ -409,7 +409,7 @@ resource "aws_ecr_repository" "test" { `, rName) } -func testAccRepositoryConfig_encryption_kms_customkey(rName string) string { +func testAccRepositoryConfig_encryptionKMSCustomkey(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" {} @@ -424,7 +424,7 @@ resource "aws_ecr_repository" "test" { `, rName) } -func testAccRepositoryConfig_encryption_aes256(rName string) string { +func testAccRepositoryConfig_encryptionAES256(rName string) string { return fmt.Sprintf(` resource "aws_ecr_repository" "test" { name = %q diff --git a/internal/service/ecrpublic/authorization_token_data_source_test.go b/internal/service/ecrpublic/authorization_token_data_source_test.go index b0db516c6c0..9223a40d2f6 100644 --- a/internal/service/ecrpublic/authorization_token_data_source_test.go +++ b/internal/service/ecrpublic/authorization_token_data_source_test.go @@ -18,7 +18,7 @@ func TestAccECRPublicAuthorizationTokenDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAuthorizationTokenBasicDataSourceConfig, + Config: testAccAuthorizationTokenDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "authorization_token"), resource.TestCheckResourceAttrSet(dataSourceName, "expires_at"), @@ -31,6 +31,6 @@ func TestAccECRPublicAuthorizationTokenDataSource_basic(t *testing.T) { }) } -var testAccCheckAuthorizationTokenBasicDataSourceConfig = ` +var testAccAuthorizationTokenDataSourceConfig_basic = ` data "aws_ecrpublic_authorization_token" "repo" {} ` diff --git a/internal/service/ecrpublic/repository_test.go b/internal/service/ecrpublic/repository_test.go index c878d1720db..3955a9c16f9 100644 --- a/internal/service/ecrpublic/repository_test.go +++ b/internal/service/ecrpublic/repository_test.go @@ -28,7 +28,7 @@ func TestAccECRPublicRepository_basic(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryConfig(rName), + Config: testAccRepositoryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "repository_name", rName), @@ -57,7 +57,7 @@ func TestAccECRPublicRepository_CatalogData_aboutText(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryCatalogDataAboutTextConfig(rName, "about_text_1"), + Config: testAccRepositoryConfig_catalogDataAboutText(rName, "about_text_1"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.#", "1"), @@ -70,7 +70,7 @@ func TestAccECRPublicRepository_CatalogData_aboutText(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryCatalogDataAboutTextConfig(rName, "about_text_2"), + Config: testAccRepositoryConfig_catalogDataAboutText(rName, "about_text_2"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.#", "1"), @@ -93,7 +93,7 @@ func TestAccECRPublicRepository_CatalogData_architectures(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryCatalogDataArchitecturesConfig(rName, "Linux"), + Config: testAccRepositoryConfig_catalogDataArchitectures(rName, "Linux"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.0.architectures.#", "1"), @@ -106,7 +106,7 @@ func TestAccECRPublicRepository_CatalogData_architectures(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryCatalogDataArchitecturesConfig(rName, "Windows"), + Config: testAccRepositoryConfig_catalogDataArchitectures(rName, "Windows"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.0.architectures.#", "1"), @@ -129,7 +129,7 @@ func TestAccECRPublicRepository_CatalogData_description(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryCatalogDataDescriptionConfig(rName, "description 1"), + Config: testAccRepositoryConfig_catalogDataDescription(rName, "description 1"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.#", "1"), @@ -142,7 +142,7 @@ func TestAccECRPublicRepository_CatalogData_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryCatalogDataDescriptionConfig(rName, "description 2"), + Config: testAccRepositoryConfig_catalogDataDescription(rName, "description 2"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.#", "1"), @@ -165,7 +165,7 @@ func TestAccECRPublicRepository_CatalogData_operatingSystems(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryCatalogDataOperatingSystemsConfig(rName, "ARM"), + Config: testAccRepositoryConfig_catalogDataOperatingSystems(rName, "ARM"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.0.operating_systems.#", "1"), @@ -178,7 +178,7 @@ func TestAccECRPublicRepository_CatalogData_operatingSystems(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryCatalogDataOperatingSystemsConfig(rName, "x86"), + Config: testAccRepositoryConfig_catalogDataOperatingSystems(rName, "x86"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.0.operating_systems.#", "1"), @@ -201,7 +201,7 @@ func TestAccECRPublicRepository_CatalogData_usageText(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryCatalogDataUsageTextConfig(rName, "usage text 1"), + Config: testAccRepositoryConfig_catalogDataUsageText(rName, "usage text 1"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.#", "1"), @@ -214,7 +214,7 @@ func TestAccECRPublicRepository_CatalogData_usageText(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRepositoryCatalogDataUsageTextConfig(rName, "usage text 2"), + Config: testAccRepositoryConfig_catalogDataUsageText(rName, "usage text 2"), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.#", "1"), @@ -237,7 +237,7 @@ func TestAccECRPublicRepository_CatalogData_logoImageBlob(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryCatalogDataLogoImageBlobConfig(rName), + Config: testAccRepositoryConfig_catalogDataLogoImageBlob(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "catalog_data.#", "1"), @@ -266,7 +266,7 @@ func TestAccECRPublicRepository_Basic_forceDestroy(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryForceDestroyConfig(rName), + Config: testAccRepositoryConfig_forceDestroy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "repository_name", rName), @@ -296,7 +296,7 @@ func TestAccECRPublicRepository_disappears(t *testing.T) { CheckDestroy: testAccCheckRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccRepositoryConfig(rName), + Config: testAccRepositoryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRepositoryExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfecrpublic.ResourceRepository(), resourceName), @@ -368,7 +368,7 @@ func testAccCheckRepositoryDestroy(s *terraform.State) error { return nil } -func testAccRepositoryConfig(rName string) string { +func testAccRepositoryConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecrpublic_repository" "test" { repository_name = %q @@ -376,7 +376,7 @@ resource "aws_ecrpublic_repository" "test" { `, rName) } -func testAccRepositoryForceDestroyConfig(rName string) string { +func testAccRepositoryConfig_forceDestroy(rName string) string { return fmt.Sprintf(` resource "aws_ecrpublic_repository" "test" { repository_name = %q @@ -385,7 +385,7 @@ resource "aws_ecrpublic_repository" "test" { `, rName) } -func testAccRepositoryCatalogDataAboutTextConfig(rName string, aboutText string) string { +func testAccRepositoryConfig_catalogDataAboutText(rName string, aboutText string) string { return fmt.Sprintf(` resource "aws_ecrpublic_repository" "test" { repository_name = %[1]q @@ -396,7 +396,7 @@ resource "aws_ecrpublic_repository" "test" { `, rName, aboutText) } -func testAccRepositoryCatalogDataArchitecturesConfig(rName string, architecture string) string { +func testAccRepositoryConfig_catalogDataArchitectures(rName string, architecture string) string { return fmt.Sprintf(` resource "aws_ecrpublic_repository" "test" { repository_name = %[1]q @@ -407,7 +407,7 @@ resource "aws_ecrpublic_repository" "test" { `, rName, architecture) } -func testAccRepositoryCatalogDataDescriptionConfig(rName string, description string) string { +func testAccRepositoryConfig_catalogDataDescription(rName string, description string) string { return fmt.Sprintf(` resource "aws_ecrpublic_repository" "test" { repository_name = %[1]q @@ -418,7 +418,7 @@ resource "aws_ecrpublic_repository" "test" { `, rName, description) } -func testAccRepositoryCatalogDataOperatingSystemsConfig(rName string, operatingSystem string) string { +func testAccRepositoryConfig_catalogDataOperatingSystems(rName string, operatingSystem string) string { return fmt.Sprintf(` resource "aws_ecrpublic_repository" "test" { repository_name = %[1]q @@ -429,7 +429,7 @@ resource "aws_ecrpublic_repository" "test" { `, rName, operatingSystem) } -func testAccRepositoryCatalogDataUsageTextConfig(rName string, usageText string) string { +func testAccRepositoryConfig_catalogDataUsageText(rName string, usageText string) string { return fmt.Sprintf(` resource "aws_ecrpublic_repository" "test" { repository_name = %[1]q @@ -440,7 +440,7 @@ resource "aws_ecrpublic_repository" "test" { `, rName, usageText) } -func testAccRepositoryCatalogDataLogoImageBlobConfig(rName string) string { +func testAccRepositoryConfig_catalogDataLogoImageBlob(rName string) string { return fmt.Sprintf(` resource "aws_ecrpublic_repository" "test" { repository_name = %q diff --git a/internal/service/ecs/account_setting_default_test.go b/internal/service/ecs/account_setting_default_test.go index ce134e41259..e2b520437ba 100644 --- a/internal/service/ecs/account_setting_default_test.go +++ b/internal/service/ecs/account_setting_default_test.go @@ -25,7 +25,7 @@ func TestAccECSAccountSettingDefault_containerInstanceLongARNFormat(t *testing.T CheckDestroy: testAccCheckAccountSettingDefaultDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountSettingDefaultConfig(settingName), + Config: testAccAccountSettingDefaultConfig_basic(settingName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", settingName), resource.TestCheckResourceAttr(resourceName, "value", "enabled"), @@ -53,7 +53,7 @@ func TestAccECSAccountSettingDefault_serviceLongARNFormat(t *testing.T) { CheckDestroy: testAccCheckAccountSettingDefaultDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountSettingDefaultConfig(settingName), + Config: testAccAccountSettingDefaultConfig_basic(settingName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", settingName), resource.TestCheckResourceAttr(resourceName, "value", "enabled"), @@ -81,7 +81,7 @@ func TestAccECSAccountSettingDefault_taskLongARNFormat(t *testing.T) { CheckDestroy: testAccCheckAccountSettingDefaultDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountSettingDefaultConfig(settingName), + Config: testAccAccountSettingDefaultConfig_basic(settingName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", settingName), resource.TestCheckResourceAttr(resourceName, "value", "enabled"), @@ -109,7 +109,7 @@ func TestAccECSAccountSettingDefault_vpcTrunking(t *testing.T) { CheckDestroy: testAccCheckAccountSettingDefaultDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountSettingDefaultConfig(settingName), + Config: testAccAccountSettingDefaultConfig_basic(settingName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", settingName), resource.TestCheckResourceAttr(resourceName, "value", "enabled"), @@ -137,7 +137,7 @@ func TestAccECSAccountSettingDefault_containerInsights(t *testing.T) { CheckDestroy: testAccCheckAccountSettingDefaultDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountSettingDefaultConfig(settingName), + Config: testAccAccountSettingDefaultConfig_basic(settingName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", settingName), resource.TestCheckResourceAttr(resourceName, "value", "enabled"), @@ -198,7 +198,7 @@ func testAccCheckAccountSettingDefaultDestroy(s *terraform.State) error { return nil } -func testAccAccountSettingDefaultConfig(settingName string) string { +func testAccAccountSettingDefaultConfig_basic(settingName string) string { return fmt.Sprintf(` resource "aws_ecs_account_setting_default" "test" { name = %[1]q diff --git a/internal/service/ecs/capacity_provider.go b/internal/service/ecs/capacity_provider.go index f0945d968df..021ef7a9e5c 100644 --- a/internal/service/ecs/capacity_provider.go +++ b/internal/service/ecs/capacity_provider.go @@ -126,7 +126,7 @@ func resourceCapacityProviderCreate(d *schema.ResourceData, meta interface{}) er output, err := conn.CreateCapacityProvider(&input) // Some partitions (i.e., ISO) may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed creating Capacity Provider (%s) with tags: %s. Trying create without tags.", name, err) input.Tags = nil @@ -143,7 +143,7 @@ func resourceCapacityProviderCreate(d *schema.ResourceData, meta interface{}) er if input.Tags == nil && len(tags) > 0 { err := UpdateTags(conn, d.Id(), nil, tags) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // If default tags only, log and continue. Otherwise, error. log.Printf("[WARN] ECS tagging failed adding tags after create for Capacity Provider (%s): %s", d.Id(), err) return resourceCapacityProviderRead(d, meta) @@ -239,7 +239,7 @@ func resourceCapacityProviderUpdate(d *schema.ResourceData, meta interface{}) er err := UpdateTags(conn, d.Id(), o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed updating tags for Capacity Provider (%s): %s", d.Id(), err) return resourceCapacityProviderRead(d, meta) } diff --git a/internal/service/ecs/capacity_provider_test.go b/internal/service/ecs/capacity_provider_test.go index d217bc7dbc9..80312c86842 100644 --- a/internal/service/ecs/capacity_provider_test.go +++ b/internal/service/ecs/capacity_provider_test.go @@ -26,7 +26,7 @@ func TestAccECSCapacityProvider_basic(t *testing.T) { CheckDestroy: testAccCheckCapacityProviderDestroy, Steps: []resource.TestStep{ { - Config: testAccCapacityProviderConfig(rName), + Config: testAccCapacityProviderConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCapacityProviderExists(resourceName, &provider), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -64,7 +64,7 @@ func TestAccECSCapacityProvider_disappears(t *testing.T) { CheckDestroy: testAccCheckCapacityProviderDestroy, Steps: []resource.TestStep{ { - Config: testAccCapacityProviderConfig(rName), + Config: testAccCapacityProviderConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCapacityProviderExists(resourceName, &provider), acctest.CheckResourceDisappears(acctest.Provider, tfecs.ResourceCapacityProvider(), resourceName), @@ -87,7 +87,7 @@ func TestAccECSCapacityProvider_managedScaling(t *testing.T) { CheckDestroy: testAccCheckCapacityProviderDestroy, Steps: []resource.TestStep{ { - Config: testAccCapacityProviderManagedScalingConfig(rName, ecs.ManagedScalingStatusEnabled, 300, 10, 1, 50), + Config: testAccCapacityProviderConfig_managedScaling(rName, ecs.ManagedScalingStatusEnabled, 300, 10, 1, 50), Check: resource.ComposeTestCheckFunc( testAccCheckCapacityProviderExists(resourceName, &provider), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -107,7 +107,7 @@ func TestAccECSCapacityProvider_managedScaling(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCapacityProviderManagedScalingConfig(rName, ecs.ManagedScalingStatusDisabled, 400, 100, 10, 100), + Config: testAccCapacityProviderConfig_managedScaling(rName, ecs.ManagedScalingStatusDisabled, 400, 100, 10, 100), Check: resource.ComposeTestCheckFunc( testAccCheckCapacityProviderExists(resourceName, &provider), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -136,7 +136,7 @@ func TestAccECSCapacityProvider_managedScalingPartial(t *testing.T) { CheckDestroy: testAccCheckCapacityProviderDestroy, Steps: []resource.TestStep{ { - Config: testAccCapacityProviderManagedScalingPartialConfig(rName), + Config: testAccCapacityProviderConfig_managedScalingPartial(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCapacityProviderExists(resourceName, &provider), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -171,7 +171,7 @@ func TestAccECSCapacityProvider_tags(t *testing.T) { CheckDestroy: testAccCheckCapacityProviderDestroy, Steps: []resource.TestStep{ { - Config: testAccCapacityProviderTags1Config(rName, "key1", "value1"), + Config: testAccCapacityProviderConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckCapacityProviderExists(resourceName, &provider), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -185,7 +185,7 @@ func TestAccECSCapacityProvider_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCapacityProviderTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccCapacityProviderConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCapacityProviderExists(resourceName, &provider), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -194,7 +194,7 @@ func TestAccECSCapacityProvider_tags(t *testing.T) { ), }, { - Config: testAccCapacityProviderTags1Config(rName, "key2", "value2"), + Config: testAccCapacityProviderConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCapacityProviderExists(resourceName, &provider), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -303,7 +303,7 @@ resource "aws_autoscaling_group" "test" { `, rName) } -func testAccCapacityProviderConfig(rName string) string { +func testAccCapacityProviderConfig_basic(rName string) string { return testAccCapacityProviderBaseConfig(rName) + fmt.Sprintf(` resource "aws_ecs_capacity_provider" "test" { name = %q @@ -315,7 +315,7 @@ resource "aws_ecs_capacity_provider" "test" { `, rName) } -func testAccCapacityProviderManagedScalingConfig(rName, status string, warmup, max, min, cap int) string { +func testAccCapacityProviderConfig_managedScaling(rName, status string, warmup, max, min, cap int) string { return testAccCapacityProviderBaseConfig(rName) + fmt.Sprintf(` resource "aws_ecs_capacity_provider" "test" { name = %[1]q @@ -335,7 +335,7 @@ resource "aws_ecs_capacity_provider" "test" { `, rName, warmup, max, min, status, cap) } -func testAccCapacityProviderManagedScalingPartialConfig(rName string) string { +func testAccCapacityProviderConfig_managedScalingPartial(rName string) string { return testAccCapacityProviderBaseConfig(rName) + fmt.Sprintf(` resource "aws_ecs_capacity_provider" "test" { name = %[1]q @@ -352,7 +352,7 @@ resource "aws_ecs_capacity_provider" "test" { `, rName) } -func testAccCapacityProviderTags1Config(rName, tag1Key, tag1Value string) string { +func testAccCapacityProviderConfig_tags1(rName, tag1Key, tag1Value string) string { return testAccCapacityProviderBaseConfig(rName) + fmt.Sprintf(` resource "aws_ecs_capacity_provider" "test" { name = %[1]q @@ -368,7 +368,7 @@ resource "aws_ecs_capacity_provider" "test" { `, rName, tag1Key, tag1Value) } -func testAccCapacityProviderTags2Config(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccCapacityProviderConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return testAccCapacityProviderBaseConfig(rName) + fmt.Sprintf(` resource "aws_ecs_capacity_provider" "test" { name = %[1]q diff --git a/internal/service/ecs/cluster.go b/internal/service/ecs/cluster.go index ed687ecfcba..42ae59448c8 100644 --- a/internal/service/ecs/cluster.go +++ b/internal/service/ecs/cluster.go @@ -203,7 +203,7 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { out, err := retryClusterCreate(conn, input) // Some partitions (i.e., ISO) may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed creating Cluster (%s) with tags: %s. Trying create without tags.", clusterName, err) input.Tags = nil @@ -226,7 +226,7 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { if input.Tags == nil && len(tags) > 0 { err := UpdateTags(conn, d.Id(), nil, tags) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // If default tags only, log and continue. Otherwise, error. log.Printf("[WARN] ECS tagging failed adding tags after create for Cluster (%s): %s", d.Id(), err) return resourceClusterRead(d, meta) @@ -366,7 +366,7 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, d.Id(), o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed updating tags for Cluster (%s): %s", d.Id(), err) return nil } diff --git a/internal/service/ecs/cluster_capacity_providers_test.go b/internal/service/ecs/cluster_capacity_providers_test.go index 5b135136617..965af9bde0e 100644 --- a/internal/service/ecs/cluster_capacity_providers_test.go +++ b/internal/service/ecs/cluster_capacity_providers_test.go @@ -25,7 +25,7 @@ func TestAccECSClusterCapacityProviders_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCapacityProvidersConfig(rName), + Config: testAccClusterCapacityProvidersConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), resource.TestCheckResourceAttr(resourceName, "capacity_providers.#", "1"), @@ -60,7 +60,7 @@ func TestAccECSClusterCapacityProviders_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCapacityProvidersConfig(rName), + Config: testAccClusterCapacityProvidersConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), acctest.CheckResourceDisappears(acctest.Provider, tfecs.ResourceCluster(), resourceName), @@ -117,7 +117,7 @@ func TestAccECSClusterCapacityProviders_destroy(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCapacityProvidersConfig_destroy_before(rName), + Config: testAccClusterCapacityProvidersConfig_destroyBefore(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), func(s *terraform.State) error { @@ -130,7 +130,7 @@ func TestAccECSClusterCapacityProviders_destroy(t *testing.T) { ), }, { - Config: testAccClusterCapacityProvidersConfig_destroy_after(rName), + Config: testAccClusterCapacityProvidersConfig_destroyAfter(rName), }, }, }) @@ -148,7 +148,7 @@ func TestAccECSClusterCapacityProviders_Update_capacityProviders(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCapacityProvidersConfig_withCapacityProviders1(rName, "FARGATE"), + Config: testAccClusterCapacityProvidersConfig_1(rName, "FARGATE"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), resource.TestCheckResourceAttr(resourceName, "capacity_providers.#", "1"), @@ -161,7 +161,7 @@ func TestAccECSClusterCapacityProviders_Update_capacityProviders(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterCapacityProvidersConfig_withCapacityProviders2(rName, "FARGATE", "FARGATE_SPOT"), + Config: testAccClusterCapacityProvidersConfig_2(rName, "FARGATE", "FARGATE_SPOT"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), resource.TestCheckResourceAttr(resourceName, "capacity_providers.#", "2"), @@ -175,7 +175,7 @@ func TestAccECSClusterCapacityProviders_Update_capacityProviders(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterCapacityProvidersConfig_withCapacityProviders0(rName), + Config: testAccClusterCapacityProvidersConfig_0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), resource.TestCheckResourceAttr(resourceName, "capacity_providers.#", "0"), @@ -187,7 +187,7 @@ func TestAccECSClusterCapacityProviders_Update_capacityProviders(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterCapacityProvidersConfig_withCapacityProviders1(rName, "FARGATE"), + Config: testAccClusterCapacityProvidersConfig_1(rName, "FARGATE"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), resource.TestCheckResourceAttr(resourceName, "capacity_providers.#", "1"), @@ -215,7 +215,7 @@ func TestAccECSClusterCapacityProviders_Update_defaultStrategy(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCapacityProvidersConfig_withDefaultCapacityProviderStrategy1(rName), + Config: testAccClusterCapacityProvidersConfig_defaultProviderStrategy1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), resource.TestCheckResourceAttr(resourceName, "default_capacity_provider_strategy.#", "1"), @@ -232,7 +232,7 @@ func TestAccECSClusterCapacityProviders_Update_defaultStrategy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterCapacityProvidersConfig_withDefaultCapacityProviderStrategy2(rName), + Config: testAccClusterCapacityProvidersConfig_defaultProviderStrategy2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), resource.TestCheckResourceAttr(resourceName, "default_capacity_provider_strategy.#", "2"), @@ -254,7 +254,7 @@ func TestAccECSClusterCapacityProviders_Update_defaultStrategy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterCapacityProvidersConfig_withDefaultCapacityProviderStrategy3(rName), + Config: testAccClusterCapacityProvidersConfig_defaultProviderStrategy3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), resource.TestCheckResourceAttr(resourceName, "default_capacity_provider_strategy.#", "2"), @@ -276,7 +276,7 @@ func TestAccECSClusterCapacityProviders_Update_defaultStrategy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterCapacityProvidersConfig_withDefaultCapacityProviderStrategy4(rName), + Config: testAccClusterCapacityProvidersConfig_defaultProviderStrategy4(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_ecs_cluster.test", &cluster), resource.TestCheckResourceAttr(resourceName, "default_capacity_provider_strategy.#", "0"), @@ -291,7 +291,7 @@ func TestAccECSClusterCapacityProviders_Update_defaultStrategy(t *testing.T) { }) } -func testAccClusterCapacityProvidersConfig(rName string) string { +func testAccClusterCapacityProvidersConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -323,7 +323,7 @@ resource "aws_ecs_cluster_capacity_providers" "test" { `, rName) } -func testAccClusterCapacityProvidersConfig_withCapacityProviders0(rName string) string { +func testAccClusterCapacityProvidersConfig_0(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -337,7 +337,7 @@ resource "aws_ecs_cluster_capacity_providers" "test" { `, rName) } -func testAccClusterCapacityProvidersConfig_withCapacityProviders1(rName, provider1 string) string { +func testAccClusterCapacityProvidersConfig_1(rName, provider1 string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -351,7 +351,7 @@ resource "aws_ecs_cluster_capacity_providers" "test" { `, rName, provider1) } -func testAccClusterCapacityProvidersConfig_withCapacityProviders2(rName, provider1, provider2 string) string { +func testAccClusterCapacityProvidersConfig_2(rName, provider1, provider2 string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -365,7 +365,7 @@ resource "aws_ecs_cluster_capacity_providers" "test" { `, rName, provider1, provider2) } -func testAccClusterCapacityProvidersConfig_withDefaultCapacityProviderStrategy1(rName string) string { +func testAccClusterCapacityProvidersConfig_defaultProviderStrategy1(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -385,7 +385,7 @@ resource "aws_ecs_cluster_capacity_providers" "test" { `, rName) } -func testAccClusterCapacityProvidersConfig_withDefaultCapacityProviderStrategy2(rName string) string { +func testAccClusterCapacityProvidersConfig_defaultProviderStrategy2(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -410,7 +410,7 @@ resource "aws_ecs_cluster_capacity_providers" "test" { `, rName) } -func testAccClusterCapacityProvidersConfig_withDefaultCapacityProviderStrategy3(rName string) string { +func testAccClusterCapacityProvidersConfig_defaultProviderStrategy3(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -435,7 +435,7 @@ resource "aws_ecs_cluster_capacity_providers" "test" { `, rName) } -func testAccClusterCapacityProvidersConfig_withDefaultCapacityProviderStrategy4(rName string) string { +func testAccClusterCapacityProvidersConfig_defaultProviderStrategy4(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -449,7 +449,7 @@ resource "aws_ecs_cluster_capacity_providers" "test" { `, rName) } -func testAccClusterCapacityProvidersConfig_destroy_before(rName string) string { +func testAccClusterCapacityProvidersConfig_destroyBefore(rName string) string { return fmt.Sprintf(` data "aws_ami" "test" { most_recent = true @@ -609,7 +609,7 @@ resource "aws_autoscaling_group" "test" { `, rName) } -func testAccClusterCapacityProvidersConfig_destroy_after(rName string) string { +func testAccClusterCapacityProvidersConfig_destroyAfter(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ecs/cluster_data_source_test.go b/internal/service/ecs/cluster_data_source_test.go index 5dbba503b26..1a57513095b 100644 --- a/internal/service/ecs/cluster_data_source_test.go +++ b/internal/service/ecs/cluster_data_source_test.go @@ -21,7 +21,7 @@ func TestAccECSClusterDataSource_ecsCluster(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckClusterDataSourceConfig(rName), + Config: testAccClusterDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttr(dataSourceName, "pending_tasks_count", "0"), @@ -45,7 +45,7 @@ func TestAccECSClusterDataSource_ecsClusterContainerInsights(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckClusterContainerInsightsDataSourceConfig(rName), + Config: testAccClusterDataSourceConfig_containerInsights(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttr(dataSourceName, "pending_tasks_count", "0"), @@ -59,7 +59,7 @@ func TestAccECSClusterDataSource_ecsClusterContainerInsights(t *testing.T) { }) } -func testAccCheckClusterDataSourceConfig(rName string) string { +func testAccClusterDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -71,7 +71,7 @@ data "aws_ecs_cluster" "test" { `, rName) } -func testAccCheckClusterContainerInsightsDataSourceConfig(rName string) string { +func testAccClusterDataSourceConfig_containerInsights(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q diff --git a/internal/service/ecs/cluster_test.go b/internal/service/ecs/cluster_test.go index 000a88f54b4..59b30bcb323 100644 --- a/internal/service/ecs/cluster_test.go +++ b/internal/service/ecs/cluster_test.go @@ -27,7 +27,7 @@ func TestAccECSCluster_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ecs", fmt.Sprintf("cluster/%s", rName)), @@ -57,7 +57,7 @@ func TestAccECSCluster_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), acctest.CheckResourceDisappears(acctest.Provider, tfecs.ResourceCluster(), resourceName), @@ -80,7 +80,7 @@ func TestAccECSCluster_tags(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterTags1Config(rName, "key1", "value1"), + Config: testAccClusterConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -94,7 +94,7 @@ func TestAccECSCluster_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccClusterConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -103,7 +103,7 @@ func TestAccECSCluster_tags(t *testing.T) { ), }, { - Config: testAccClusterTags1Config(rName, "key2", "value2"), + Config: testAccClusterConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -127,7 +127,7 @@ func TestAccECSCluster_singleCapacityProvider(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterSingleCapacityProvider(rName, providerName), + Config: testAccClusterConfig_singleCapacityProvider(rName, providerName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), ), @@ -154,7 +154,7 @@ func TestAccECSCluster_capacityProviders(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCapacityProviders(rName), + Config: testAccClusterConfig_capacityProviders(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), ), @@ -166,7 +166,7 @@ func TestAccECSCluster_capacityProviders(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterCapacityProvidersReOrdered(rName), + Config: testAccClusterConfig_capacityProvidersReOrdered(rName), PlanOnly: true, }, }, @@ -185,7 +185,7 @@ func TestAccECSCluster_capacityProvidersUpdate(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCapacityProvidersFargate(rName), + Config: testAccClusterConfig_capacityProvidersFargate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), ), @@ -197,13 +197,13 @@ func TestAccECSCluster_capacityProvidersUpdate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterCapacityProvidersFargateSpot(rName), + Config: testAccClusterConfig_capacityProvidersFargateSpot(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), ), }, { - Config: testAccClusterCapacityProvidersFargateBoth(rName), + Config: testAccClusterConfig_capacityProvidersFargateBoth(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), ), @@ -224,7 +224,7 @@ func TestAccECSCluster_capacityProvidersNoStrategy(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCapacityProvidersFargateNoStrategy(rName), + Config: testAccClusterConfig_capacityProvidersFargateNoStrategy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), ), @@ -236,7 +236,7 @@ func TestAccECSCluster_capacityProvidersNoStrategy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterCapacityProvidersFargateSpotNoStrategy(rName), + Config: testAccClusterConfig_capacityProvidersFargateSpotNoStrategy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), ), @@ -257,14 +257,14 @@ func TestAccECSCluster_containerInsights(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ecs", fmt.Sprintf("cluster/%s", rName)), ), }, { - Config: testAccClusterContainerInsightsConfig(rName, "enabled"), + Config: testAccClusterConfig_containerInsights(rName, "enabled"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ecs", fmt.Sprintf("cluster/%s", rName)), @@ -277,7 +277,7 @@ func TestAccECSCluster_containerInsights(t *testing.T) { ), }, { - Config: testAccClusterContainerInsightsConfig(rName, "disabled"), + Config: testAccClusterConfig_containerInsights(rName, "disabled"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "setting.#", "1"), @@ -303,7 +303,7 @@ func TestAccECSCluster_configuration(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfigurationConfig(rName, true), + Config: testAccClusterConfig_configuration(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -322,7 +322,7 @@ func TestAccECSCluster_configuration(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfigurationConfig(rName, false), + Config: testAccClusterConfig_configuration(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -383,7 +383,7 @@ func testAccCheckClusterExists(resourceName string, cluster *ecs.Cluster) resour } } -func testAccClusterConfig(rName string) string { +func testAccClusterConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %q @@ -391,7 +391,7 @@ resource "aws_ecs_cluster" "test" { `, rName) } -func testAccClusterTags1Config(rName, tag1Key, tag1Value string) string { +func testAccClusterConfig_tags1(rName, tag1Key, tag1Value string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %q @@ -415,7 +415,7 @@ resource "aws_ecs_capacity_provider" "test" { `, rName) } -func testAccClusterSingleCapacityProvider(rName, providerName string) string { +func testAccClusterConfig_singleCapacityProvider(rName, providerName string) string { return testAccClusterCapacityProviderConfig(providerName) + fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -431,7 +431,7 @@ resource "aws_ecs_cluster" "test" { `, rName) } -func testAccClusterCapacityProviders(rName string) string { +func testAccClusterConfig_capacityProviders(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -452,7 +452,7 @@ resource "aws_ecs_cluster" "test" { `, rName) } -func testAccClusterCapacityProvidersReOrdered(rName string) string { +func testAccClusterConfig_capacityProvidersReOrdered(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -473,7 +473,7 @@ resource "aws_ecs_cluster" "test" { `, rName) } -func testAccClusterCapacityProvidersFargate(rName string) string { +func testAccClusterConfig_capacityProvidersFargate(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -489,7 +489,7 @@ resource "aws_ecs_cluster" "test" { `, rName) } -func testAccClusterCapacityProvidersFargateSpot(rName string) string { +func testAccClusterConfig_capacityProvidersFargateSpot(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -505,7 +505,7 @@ resource "aws_ecs_cluster" "test" { `, rName) } -func testAccClusterCapacityProvidersFargateBoth(rName string) string { +func testAccClusterConfig_capacityProvidersFargateBoth(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -521,7 +521,7 @@ resource "aws_ecs_cluster" "test" { `, rName) } -func testAccClusterCapacityProvidersFargateNoStrategy(rName string) string { +func testAccClusterConfig_capacityProvidersFargateNoStrategy(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -531,7 +531,7 @@ resource "aws_ecs_cluster" "test" { `, rName) } -func testAccClusterCapacityProvidersFargateSpotNoStrategy(rName string) string { +func testAccClusterConfig_capacityProvidersFargateSpotNoStrategy(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -541,7 +541,7 @@ resource "aws_ecs_cluster" "test" { `, rName) } -func testAccClusterTags2Config(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccClusterConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %q @@ -554,7 +554,7 @@ resource "aws_ecs_cluster" "test" { `, rName, tag1Key, tag1Value, tag2Key, tag2Value) } -func testAccClusterContainerInsightsConfig(rName, value string) string { +func testAccClusterConfig_containerInsights(rName, value string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -566,7 +566,7 @@ resource "aws_ecs_cluster" "test" { `, rName, value) } -func testAccClusterConfigurationConfig(rName string, enable bool) string { +func testAccClusterConfig_configuration(rName string, enable bool) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q diff --git a/internal/service/ecs/container_definition_data_source_test.go b/internal/service/ecs/container_definition_data_source_test.go index 0b7e02ca856..4243b852cf1 100644 --- a/internal/service/ecs/container_definition_data_source_test.go +++ b/internal/service/ecs/container_definition_data_source_test.go @@ -22,7 +22,7 @@ func TestAccECSContainerDefinitionDataSource_ecsContainerDefinition(t *testing.T ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckContainerDefinitionDataSourceConfig(clusterName, tdName, svcName), + Config: testAccContainerDefinitionDataSourceConfig_basic(clusterName, tdName, svcName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_ecs_container_definition.mongo", "image", "mongo:latest"), resource.TestCheckResourceAttr("data.aws_ecs_container_definition.mongo", "image_digest", "latest"), @@ -36,7 +36,7 @@ func TestAccECSContainerDefinitionDataSource_ecsContainerDefinition(t *testing.T }) } -func testAccCheckContainerDefinitionDataSourceConfig(clusterName, tdName, svcName string) string { +func testAccContainerDefinitionDataSourceConfig_basic(clusterName, tdName, svcName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = "%s" diff --git a/internal/service/ecs/find.go b/internal/service/ecs/find.go index 1a15d150c95..517fe0215e9 100644 --- a/internal/service/ecs/find.go +++ b/internal/service/ecs/find.go @@ -21,7 +21,7 @@ func FindCapacityProviderByARN(conn *ecs.ECS, arn string) (*ecs.CapacityProvider output, err := conn.DescribeCapacityProviders(input) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed describing Capacity Provider (%s) with tags: %s; retrying without tags", arn, err) input.Include = nil @@ -60,7 +60,7 @@ func FindClusterByNameOrARN(ctx context.Context, conn *ecs.ECS, nameOrARN string output, err := conn.DescribeClustersWithContext(ctx, input) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed describing ECS Cluster (%s) including tags: %s; retrying without tags", nameOrARN, err) input.Include = aws.StringSlice([]string{ecs.ClusterFieldConfigurations, ecs.ClusterFieldSettings}) @@ -68,7 +68,7 @@ func FindClusterByNameOrARN(ctx context.Context, conn *ecs.ECS, nameOrARN string } // Some partitions (i.e., ISO) may not support describe including configuration, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed describing ECS Cluster (%s) including configuration: %s; retrying without configuration", nameOrARN, err) input.Include = aws.StringSlice([]string{ecs.ClusterFieldSettings}) diff --git a/internal/service/ecs/service.go b/internal/service/ecs/service.go index d5d2fe9e1c5..b895ab220f4 100644 --- a/internal/service/ecs/service.go +++ b/internal/service/ecs/service.go @@ -531,7 +531,7 @@ func resourceServiceCreate(d *schema.ResourceData, meta interface{}) error { output, err := retryServiceCreate(conn, input) // Some partitions (i.e., ISO) may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed creating Service (%s) with tags: %s. Trying create without tags.", d.Get("name").(string), err) input.Tags = nil @@ -566,7 +566,7 @@ func resourceServiceCreate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, d.Id(), nil, tags) // If default tags only, log and continue. Otherwise, error. - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed adding tags after create for Service (%s): %s", d.Id(), err) return resourceServiceRead(d, meta) } @@ -594,7 +594,7 @@ func resourceServiceRead(d *schema.ResourceData, meta interface{}) error { output, err := conn.DescribeServices(&input) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed describing Service (%s) with tags: %s; retrying without tags", d.Id(), err) input.Include = nil @@ -1129,7 +1129,7 @@ func resourceServiceUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, d.Id(), o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed updating tags for Service (%s): %s", d.Id(), err) return resourceServiceRead(d, meta) } diff --git a/internal/service/ecs/service_data_source_test.go b/internal/service/ecs/service_data_source_test.go index 5948cc0dad2..09da5bfcdcb 100644 --- a/internal/service/ecs/service_data_source_test.go +++ b/internal/service/ecs/service_data_source_test.go @@ -21,7 +21,7 @@ func TestAccECSServiceDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckServiceDataSourceConfig(rName), + Config: testAccServiceDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "desired_count", dataSourceName, "desired_count"), @@ -35,7 +35,7 @@ func TestAccECSServiceDataSource_basic(t *testing.T) { }) } -func testAccCheckServiceDataSourceConfig(rName string) string { +func testAccServiceDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q diff --git a/internal/service/ecs/service_test.go b/internal/service/ecs/service_test.go index 712a9894a66..1c7e3884c7a 100644 --- a/internal/service/ecs/service_test.go +++ b/internal/service/ecs/service_test.go @@ -31,7 +31,7 @@ func TestAccECSService_basic(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceConfig(rName), + Config: testAccServiceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "service_registries.#", "0"), @@ -40,7 +40,7 @@ func TestAccECSService_basic(t *testing.T) { }, { - Config: testAccServiceModifiedConfig(rName), + Config: testAccServiceConfig_modified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "service_registries.#", "0"), @@ -64,7 +64,7 @@ func TestAccECSService_basicImport(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceFamilyAndRevisionConfig(rName), + Config: testAccServiceConfig_familyAndRevision(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), ), @@ -102,7 +102,7 @@ func TestAccECSService_disappears(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceConfig(rName), + Config: testAccServiceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), acctest.CheckResourceDisappears(acctest.Provider, tfecs.ResourceService(), resourceName), @@ -125,7 +125,7 @@ func TestAccECSService_PlacementStrategy_unnormalized(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceInterchangeablePlacementStrategyConfig(rName), + Config: testAccServiceConfig_interchangeablePlacementStrategy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), ), @@ -146,13 +146,13 @@ func TestAccECSService_CapacityProviderStrategy_basic(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceCapacityProviderStrategyConfig(rName, 1, 0, false), + Config: testAccServiceConfig_capacityProviderStrategy(rName, 1, 0, false), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), ), }, { - Config: testAccServiceCapacityProviderStrategyConfig(rName, 10, 1, false), + Config: testAccServiceConfig_capacityProviderStrategy(rName, 10, 1, false), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), ), @@ -173,13 +173,13 @@ func TestAccECSService_CapacityProviderStrategy_forceNewDeployment(t *testing.T) CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceCapacityProviderStrategyConfig(rName, 1, 0, true), + Config: testAccServiceConfig_capacityProviderStrategy(rName, 1, 0, true), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service1), ), }, { - Config: testAccServiceCapacityProviderStrategyConfig(rName, 10, 1, true), + Config: testAccServiceConfig_capacityProviderStrategy(rName, 10, 1, true), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service2), testAccCheckServiceNotRecreated(&service1, &service2), @@ -201,26 +201,26 @@ func TestAccECSService_CapacityProviderStrategy_update(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceUpdateCapacityProviderStrategyRemoveConfig(rName), + Config: testAccServiceConfig_updateCapacityProviderStrategyRemove(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service1), ), }, { - Config: testAccServiceUpdateCapacityProviderStrategyConfig(rName, 1, "FARGATE"), + Config: testAccServiceConfig_updateCapacityProviderStrategy(rName, 1, "FARGATE"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service2), ), }, { - Config: testAccServiceUpdateCapacityProviderStrategyConfig(rName, 1, "FARGATE_SPOT"), + Config: testAccServiceConfig_updateCapacityProviderStrategy(rName, 1, "FARGATE_SPOT"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service1), testAccCheckServiceNotRecreated(&service1, &service2), ), }, { - Config: testAccServiceUpdateCapacityProviderStrategyRemoveConfig(rName), + Config: testAccServiceConfig_updateCapacityProviderStrategyRemove(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service1), ), @@ -241,7 +241,7 @@ func TestAccECSService_CapacityProviderStrategy_multiple(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceMultipleCapacityProviderStrategiesConfig(rName), + Config: testAccServiceConfig_multipleCapacityProviderStrategies(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "capacity_provider_strategy.#", "2"), @@ -263,14 +263,14 @@ func TestAccECSService_familyAndRevision(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceFamilyAndRevisionConfig(rName), + Config: testAccServiceConfig_familyAndRevision(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), ), }, { - Config: testAccServiceFamilyAndRevisionModifiedConfig(rName), + Config: testAccServiceConfig_familyAndRevisionModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), ), @@ -292,7 +292,7 @@ func TestAccECSService_renamedCluster(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceRenamedClusterConfig(rName), + Config: testAccServiceConfig_renamedCluster(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttrPair(resourceName, "cluster", "aws_ecs_cluster.default", "arn"), @@ -300,7 +300,7 @@ func TestAccECSService_renamedCluster(t *testing.T) { }, { - Config: testAccServiceRenamedClusterConfig(rName), + Config: testAccServiceConfig_renamedCluster(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttrPair(resourceName, "cluster", "aws_ecs_cluster.default", "arn"), @@ -326,29 +326,29 @@ func TestAccECSService_healthCheckGracePeriodSeconds(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceHealthCheckGracePeriodSecondsConfig(rName, -1), + Config: testAccServiceConfig_healthCheckGracePeriodSeconds(rName, -1), ExpectError: regexp.MustCompile(`expected health_check_grace_period_seconds to be in the range`), }, { - Config: testAccServiceHealthCheckGracePeriodSecondsConfig(rName, math.MaxInt32+1), + Config: testAccServiceConfig_healthCheckGracePeriodSeconds(rName, math.MaxInt32+1), ExpectError: regexp.MustCompile(`expected health_check_grace_period_seconds to be in the range`), }, { - Config: testAccServiceHealthCheckGracePeriodSecondsConfig(rName, 300), + Config: testAccServiceConfig_healthCheckGracePeriodSeconds(rName, 300), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "health_check_grace_period_seconds", "300"), ), }, { - Config: testAccServiceHealthCheckGracePeriodSecondsConfig(rName, 600), + Config: testAccServiceConfig_healthCheckGracePeriodSeconds(rName, 600), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "health_check_grace_period_seconds", "600"), ), }, { - Config: testAccServiceHealthCheckGracePeriodSecondsConfig(rName, math.MaxInt32), + Config: testAccServiceConfig_healthCheckGracePeriodSeconds(rName, math.MaxInt32), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "health_check_grace_period_seconds", "2147483647"), @@ -370,7 +370,7 @@ func TestAccECSService_iamRole(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceIAMRoleConfig(rName), + Config: testAccServiceConfig_iamRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), ), @@ -391,7 +391,7 @@ func TestAccECSService_DeploymentControllerType_codeDeploy(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceDeploymentControllerTypeCodeDeployConfig(rName), + Config: testAccServiceConfig_deploymentControllerTypeCodeDeploy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "deployment_controller.#", "1"), @@ -427,7 +427,7 @@ func TestAccECSService_DeploymentControllerType_codeDeployUpdateDesiredCountAndH CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceDeploymentControllerTypeCodeDeployConfigUpdate(rName, 1, 100), + Config: testAccServiceConfig_deploymentControllerTypeCodeDeployUpdate(rName, 1, 100), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "deployment_controller.#", "1"), @@ -436,14 +436,14 @@ func TestAccECSService_DeploymentControllerType_codeDeployUpdateDesiredCountAndH ), }, { - Config: testAccServiceDeploymentControllerTypeCodeDeployConfigUpdate(rName, 2, 100), + Config: testAccServiceConfig_deploymentControllerTypeCodeDeployUpdate(rName, 2, 100), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "desired_count", "2"), ), }, { - Config: testAccServiceDeploymentControllerTypeCodeDeployConfigUpdate(rName, 2, 120), + Config: testAccServiceConfig_deploymentControllerTypeCodeDeployUpdate(rName, 2, 120), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "health_check_grace_period_seconds", "120"), @@ -465,7 +465,7 @@ func TestAccECSService_DeploymentControllerType_external(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceDeploymentControllerTypeExternalConfig(rName), + Config: testAccServiceConfig_deploymentControllerTypeExternal(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "deployment_controller.#", "1"), @@ -496,7 +496,7 @@ func TestAccECSService_DeploymentValues_basic(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceDeploymentValuesConfig(rName), + Config: testAccServiceConfig_deploymentValues(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "deployment_maximum_percent", "200"), @@ -520,7 +520,7 @@ func TestAccECSService_DeploymentValues_minZeroMaxOneHundred(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceDeploymentPercentsConfig(rName, 0, 100), + Config: testAccServiceConfig_deploymentPercents(rName, 0, 100), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "deployment_maximum_percent", "100"), @@ -543,7 +543,7 @@ func TestAccECSService_deploymentCircuitBreaker(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceDeploymentCircuitBreakerConfig(rName), + Config: testAccServiceConfig_deploymentCircuitBreaker(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "deployment_circuit_breaker.#", "1"), @@ -568,13 +568,13 @@ func TestAccECSService_loadBalancerChanges(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceLBChangesConfig(rName), + Config: testAccServiceConfig_lbChanges(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &s1), ), }, { - Config: testAccServiceLBChangesModifiedConfig(rName), + Config: testAccServiceConfig_lbChangesModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &s2), testAccCheckServiceNotRecreated(&s2, &s1), @@ -597,7 +597,7 @@ func TestAccECSService_clusterName(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceClusterNameConfig(rName), + Config: testAccServiceConfig_clusterName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "cluster", rName), @@ -619,7 +619,7 @@ func TestAccECSService_alb(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceALBConfig(rName), + Config: testAccServiceConfig_alb(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "load_balancer.#", "1"), @@ -641,7 +641,7 @@ func TestAccECSService_multipleTargetGroups(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceMultipleTargetGroupsConfig(rName), + Config: testAccServiceConfig_multipleTargetGroups(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "load_balancer.#", "2"), @@ -663,14 +663,14 @@ func TestAccECSService_forceNewDeployment(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceConfig(rName), + Config: testAccServiceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service1), resource.TestCheckResourceAttr(resourceName, "ordered_placement_strategy.#", "0"), ), }, { - Config: testAccServiceForceNewDeploymentConfig(rName), + Config: testAccServiceConfig_forceNewDeployment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service2), testAccCheckServiceNotRecreated(&service1, &service2), @@ -695,14 +695,14 @@ func TestAccECSService_PlacementStrategy_basic(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceConfig(rName), + Config: testAccServiceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service1), resource.TestCheckResourceAttr(resourceName, "ordered_placement_strategy.#", "0"), ), }, { - Config: testAccServicePlacementStrategyConfig(rName), + Config: testAccServiceConfig_placementStrategy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service2), testAccCheckServiceNotRecreated(&service1, &service2), @@ -712,7 +712,7 @@ func TestAccECSService_PlacementStrategy_basic(t *testing.T) { ), }, { - Config: testAccServiceRandomPlacementStrategyConfig(rName), + Config: testAccServiceConfig_randomPlacementStrategy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service3), testAccCheckServiceNotRecreated(&service2, &service3), @@ -722,7 +722,7 @@ func TestAccECSService_PlacementStrategy_basic(t *testing.T) { ), }, { - Config: testAccServiceMultiplacementStrategyConfig(rName), + Config: testAccServiceConfig_multiplacementStrategy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service4), testAccCheckServiceNotRecreated(&service3, &service4), @@ -748,7 +748,7 @@ func TestAccECSService_PlacementStrategy_missing(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServicePlacementStrategyTypeConfig(rName, ""), + Config: testAccServiceConfig_placementStrategyType(rName, ""), ExpectError: regexp.MustCompile(`expected ordered_placement_strategy.0.type to be one of`), }, }, @@ -767,14 +767,14 @@ func TestAccECSService_PlacementConstraints_basic(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServicePlacementConstraintConfig(rName), + Config: testAccServiceConfig_placementConstraint(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service1), resource.TestCheckResourceAttr(resourceName, "placement_constraints.#", "1"), ), }, { - Config: testAccServicePlacementConstraintEmptyExpressionConfig(rName), + Config: testAccServiceConfig_placementConstraintEmptyExpression(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service2), testAccCheckServiceNotRecreated(&service1, &service2), @@ -797,7 +797,7 @@ func TestAccECSService_PlacementConstraints_emptyExpression(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServicePlacementConstraintEmptyExpressionConfig(rName), + Config: testAccServiceConfig_placementConstraintEmptyExpression(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "placement_constraints.#", "1"), @@ -819,7 +819,7 @@ func TestAccECSService_LaunchTypeFargate_basic(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceLaunchTypeFargateConfig(rName, false), + Config: testAccServiceConfig_launchTypeFargate(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "launch_type", "FARGATE"), @@ -830,14 +830,14 @@ func TestAccECSService_LaunchTypeFargate_basic(t *testing.T) { ), }, { - Config: testAccServiceLaunchTypeFargateConfig(rName, true), + Config: testAccServiceConfig_launchTypeFargate(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "network_configuration.0.assign_public_ip", "true"), ), }, { - Config: testAccServiceLaunchTypeFargateConfig(rName, false), + Config: testAccServiceConfig_launchTypeFargate(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "network_configuration.0.assign_public_ip", "false"), @@ -859,21 +859,21 @@ func TestAccECSService_LaunchTypeFargate_platformVersion(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceLaunchTypeFargateAndPlatformVersionConfig(rName, "1.3.0"), + Config: testAccServiceConfig_launchTypeFargateAndPlatformVersion(rName, "1.3.0"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "platform_version", "1.3.0"), ), }, { - Config: testAccServiceLaunchTypeFargateAndPlatformVersionConfig(rName, "LATEST"), + Config: testAccServiceConfig_launchTypeFargateAndPlatformVersion(rName, "LATEST"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "platform_version", "LATEST"), ), }, { - Config: testAccServiceLaunchTypeFargateAndPlatformVersionConfig(rName, "1.4.0"), + Config: testAccServiceConfig_launchTypeFargateAndPlatformVersion(rName, "1.4.0"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "platform_version", "1.4.0"), @@ -896,7 +896,7 @@ func TestAccECSService_LaunchTypeFargate_waitForSteadyState(t *testing.T) { Steps: []resource.TestStep{ { // Wait for the ECS Cluster to reach a steady state w/specified count - Config: testAccServiceLaunchTypeFargateAndWaitConfig(rName, 1, true), + Config: testAccServiceConfig_launchTypeFargateAndWait(rName, 1, true), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "desired_count", "1"), @@ -928,7 +928,7 @@ func TestAccECSService_LaunchTypeFargate_updateWaitForSteadyState(t *testing.T) CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceLaunchTypeFargateNoWaitConfig(rName), + Config: testAccServiceConfig_launchTypeFargateNoWait(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "desired_count", "1"), @@ -937,7 +937,7 @@ func TestAccECSService_LaunchTypeFargate_updateWaitForSteadyState(t *testing.T) }, { // Modify desired count and wait for the ECS Cluster to reach steady state - Config: testAccServiceLaunchTypeFargateAndWaitConfig(rName, 2, true), + Config: testAccServiceConfig_launchTypeFargateAndWait(rName, 2, true), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "desired_count", "2"), @@ -946,7 +946,7 @@ func TestAccECSService_LaunchTypeFargate_updateWaitForSteadyState(t *testing.T) }, { // Modify desired count without wait - Config: testAccServiceLaunchTypeFargateAndWaitConfig(rName, 1, false), + Config: testAccServiceConfig_launchTypeFargateAndWait(rName, 1, false), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "desired_count", "1"), @@ -969,7 +969,7 @@ func TestAccECSService_LaunchTypeEC2_network(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceNetworkConfigurationConfig(rName), + Config: testAccServiceConfig_networkConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "network_configuration.0.assign_public_ip", "false"), @@ -978,7 +978,7 @@ func TestAccECSService_LaunchTypeEC2_network(t *testing.T) { ), }, { - Config: testAccServiceNetworkConfigurationModifiedConfig(rName), + Config: testAccServiceConfig_networkConfigurationModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "network_configuration.0.assign_public_ip", "false"), @@ -1002,7 +1002,7 @@ func TestAccECSService_DaemonSchedulingStrategy_basic(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceDaemonSchedulingStrategyConfig(rName), + Config: testAccServiceConfig_daemonSchedulingStrategy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "scheduling_strategy", "DAEMON"), @@ -1024,7 +1024,7 @@ func TestAccECSService_DaemonSchedulingStrategy_setDeploymentMinimum(t *testing. CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceDaemonSchedulingStrategySetDeploymentMinimumConfig(rName), + Config: testAccServiceConfig_daemonSchedulingStrategySetDeploymentMinimum(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "scheduling_strategy", "DAEMON"), @@ -1046,7 +1046,7 @@ func TestAccECSService_replicaSchedulingStrategy(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceReplicaSchedulingStrategyConfig(rName), + Config: testAccServiceConfig_replicaSchedulingStrategy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "scheduling_strategy", "REPLICA"), @@ -1068,7 +1068,7 @@ func TestAccECSService_ServiceRegistries_basic(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceServiceRegistriesConfig(rName), + Config: testAccServiceConfig_registries(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "service_registries.#", "1"), @@ -1090,7 +1090,7 @@ func TestAccECSService_ServiceRegistries_container(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceServiceRegistriesContainerConfig(rName), + Config: testAccServiceConfig_registriesContainer(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "service_registries.#", "1"), @@ -1118,14 +1118,14 @@ func TestAccECSService_ServiceRegistries_changes(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceServiceRegistriesChangesConfig(rName, serviceDiscoveryName), + Config: testAccServiceConfig_registriesChanges(rName, serviceDiscoveryName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "service_registries.#", "1"), ), }, { - Config: testAccServiceServiceRegistriesChangesConfig(rName, updatedServiceDiscoveryName), + Config: testAccServiceConfig_registriesChanges(rName, updatedServiceDiscoveryName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "service_registries.#", "1"), @@ -1147,7 +1147,7 @@ func TestAccECSService_Tags_basic(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceTags1Config(rName, "key1", "value1"), + Config: testAccServiceConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1164,7 +1164,7 @@ func TestAccECSService_Tags_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"task_definition", "wait_for_steady_state"}, }, { - Config: testAccServiceTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccServiceConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1173,7 +1173,7 @@ func TestAccECSService_Tags_basic(t *testing.T) { ), }, { - Config: testAccServiceTags1Config(rName, "key2", "value2"), + Config: testAccServiceConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1196,7 +1196,7 @@ func TestAccECSService_Tags_managed(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceManagedTagsConfig(rName), + Config: testAccServiceConfig_managedTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1219,7 +1219,7 @@ func TestAccECSService_Tags_propagate(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServicePropagateTagsConfig(rName, "SERVICE"), + Config: testAccServiceConfig_propagateTags(rName, "SERVICE"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &first), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1227,14 +1227,14 @@ func TestAccECSService_Tags_propagate(t *testing.T) { ), }, { - Config: testAccServicePropagateTagsConfig(rName, "TASK_DEFINITION"), + Config: testAccServiceConfig_propagateTags(rName, "TASK_DEFINITION"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &second), resource.TestCheckResourceAttr(resourceName, "propagate_tags", ecs.PropagateTagsTaskDefinition), ), }, { - Config: testAccServicePropagateTagsConfig(rName, "NONE"), + Config: testAccServiceConfig_propagateTags(rName, "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &third), resource.TestCheckResourceAttr(resourceName, "propagate_tags", ecs.PropagateTagsNone), @@ -1256,14 +1256,14 @@ func TestAccECSService_executeCommand(t *testing.T) { CheckDestroy: testAccCheckServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceExecuteCommandConfig(rName, true), + Config: testAccServiceConfig_executeCommand(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "enable_execute_command", "true"), ), }, { - Config: testAccServiceExecuteCommandConfig(rName, false), + Config: testAccServiceConfig_executeCommand(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "enable_execute_command", "false"), @@ -1364,7 +1364,7 @@ func testAccCheckServiceNotRecreated(i, j *ecs.Service) resource.TestCheckFunc { } } -func testAccServiceConfig(rName string) string { +func testAccServiceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -1395,7 +1395,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceModifiedConfig(rName string) string { +func testAccServiceConfig_modified(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -1426,7 +1426,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceLaunchTypeFargateNoWaitConfig(rName string) string { +func testAccServiceConfig_launchTypeFargateNoWait(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1539,7 +1539,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceLaunchTypeFargateAndWaitConfig(rName string, desiredCount int, waitForSteadyState bool) string { +func testAccServiceConfig_launchTypeFargateAndWait(rName string, desiredCount int, waitForSteadyState bool) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1655,7 +1655,7 @@ resource "aws_ecs_service" "test" { `, rName, desiredCount, waitForSteadyState) } -func testAccServiceInterchangeablePlacementStrategyConfig(rName string) string { +func testAccServiceConfig_interchangeablePlacementStrategy(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -1691,7 +1691,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceCapacityProviderStrategyConfig(rName string, weight, base int, forceNewDeployment bool) string { +func testAccServiceConfig_capacityProviderStrategy(rName string, weight, base int, forceNewDeployment bool) string { return acctest.ConfigCompose(testAccCapacityProviderBaseConfig(rName), fmt.Sprintf(` resource "aws_ecs_capacity_provider" "test" { name = %[1]q @@ -1737,7 +1737,7 @@ resource "aws_ecs_service" "test" { `, rName, weight, base, forceNewDeployment)) } -func testAccServiceUpdateCapacityProviderStrategyConfig(rName string, weight int, capacityProvider string) string { +func testAccServiceConfig_updateCapacityProviderStrategy(rName string, weight int, capacityProvider string) string { return acctest.ConfigCompose( testAccCapacityProviderBaseConfig(rName), fmt.Sprintf(` @@ -1817,7 +1817,7 @@ resource "aws_ecs_service" "test" { `, rName, weight, capacityProvider)) } -func testAccServiceUpdateCapacityProviderStrategyRemoveConfig(rName string) string { +func testAccServiceConfig_updateCapacityProviderStrategyRemove(rName string) string { return acctest.ConfigCompose( testAccCapacityProviderBaseConfig(rName), fmt.Sprintf(` @@ -1851,8 +1851,8 @@ resource "aws_ecs_service" "test" { `, rName)) } -func testAccServiceMultipleCapacityProviderStrategiesConfig(rName string) string { - return acctest.ConfigCompose(testAccClusterCapacityProviders(rName), fmt.Sprintf(` +func testAccServiceConfig_multipleCapacityProviderStrategies(rName string) string { + return acctest.ConfigCompose(testAccClusterConfig_capacityProviders(rName), fmt.Sprintf(` resource "aws_ecs_service" "test" { name = %[1]q cluster = aws_ecs_cluster.test.id @@ -1928,7 +1928,7 @@ resource "aws_vpc" "test" { `, rName)) } -func testAccServiceForceNewDeploymentConfig(rName string) string { +func testAccServiceConfig_forceNewDeployment(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -1965,7 +1965,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServicePlacementStrategyConfig(rName string) string { +func testAccServiceConfig_placementStrategy(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -2001,7 +2001,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServicePlacementStrategyTypeConfig(rName string, placementStrategyType string) string { +func testAccServiceConfig_placementStrategyType(rName string, placementStrategyType string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -2036,7 +2036,7 @@ resource "aws_ecs_service" "test" { `, rName, placementStrategyType) } -func testAccServiceRandomPlacementStrategyConfig(rName string) string { +func testAccServiceConfig_randomPlacementStrategy(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -2071,7 +2071,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceMultiplacementStrategyConfig(rName string) string { +func testAccServiceConfig_multiplacementStrategy(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -2112,7 +2112,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServicePlacementConstraintConfig(rName string) string { +func testAccServiceConfig_placementConstraint(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -2157,7 +2157,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServicePlacementConstraintEmptyExpressionConfig(rName string) string { +func testAccServiceConfig_placementConstraintEmptyExpression(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -2192,7 +2192,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceLaunchTypeFargateConfig(rName string, assignPublicIP bool) string { +func testAccServiceConfig_launchTypeFargate(rName string, assignPublicIP bool) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -2289,7 +2289,7 @@ resource "aws_ecs_service" "test" { `, rName, assignPublicIP) } -func testAccServiceLaunchTypeFargateAndPlatformVersionConfig(rName, platformVersion string) string { +func testAccServiceConfig_launchTypeFargateAndPlatformVersion(rName, platformVersion string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -2387,7 +2387,7 @@ resource "aws_ecs_service" "test" { `, rName, platformVersion) } -func testAccServiceHealthCheckGracePeriodSecondsConfig(rName string, healthCheckGracePeriodSeconds int) string { +func testAccServiceConfig_healthCheckGracePeriodSeconds(rName string, healthCheckGracePeriodSeconds int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -2531,7 +2531,7 @@ resource "aws_ecs_service" "test" { `, rName, healthCheckGracePeriodSeconds) } -func testAccServiceIAMRoleConfig(rName string) string { +func testAccServiceConfig_iamRole(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -2660,7 +2660,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceDeploymentValuesConfig(rName string) string { +func testAccServiceConfig_deploymentValues(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -2832,15 +2832,15 @@ resource "aws_ecs_service" "test" { `, rName, image, containerName, containerPort, hostPort) } -func testAccServiceLBChangesConfig(rName string) string { +func testAccServiceConfig_lbChanges(rName string) string { return testAccServiceLBChangesBaseConfig(rName, "ghost:latest", "ghost", 2368, 8080) } -func testAccServiceLBChangesModifiedConfig(rName string) string { +func testAccServiceConfig_lbChangesModified(rName string) string { return testAccServiceLBChangesBaseConfig(rName, "nginx:latest", "nginx", 80, 8080) } -func testAccServiceFamilyAndRevisionConfig(rName string) string { +func testAccServiceConfig_familyAndRevision(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -2871,7 +2871,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceFamilyAndRevisionModifiedConfig(rName string) string { +func testAccServiceConfig_familyAndRevisionModified(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -2902,7 +2902,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceRenamedClusterConfig(rName string) string { +func testAccServiceConfig_renamedCluster(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -2933,7 +2933,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceClusterNameConfig(rName string) string { +func testAccServiceConfig_clusterName(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -2964,7 +2964,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceALBConfig(rName string) string { +func testAccServiceConfig_alb(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -3107,7 +3107,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceMultipleTargetGroupsConfig(rName string) string { +func testAccServiceConfig_multipleTargetGroups(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -3324,15 +3324,15 @@ resource "aws_ecs_service" "test" { `, rName, securityGroups) } -func testAccServiceNetworkConfigurationConfig(rName string) string { +func testAccServiceConfig_networkConfiguration(rName string) string { return testAccServiceNetworkConfigurationBaseConfig(rName, "aws_security_group.allow_all_a.id, aws_security_group.allow_all_b.id") } -func testAccServiceNetworkConfigurationModifiedConfig(rName string) string { +func testAccServiceConfig_networkConfigurationModified(rName string) string { return testAccServiceNetworkConfigurationBaseConfig(rName, "aws_security_group.allow_all_a.id") } -func testAccServiceServiceRegistriesConfig(rName string) string { +func testAccServiceConfig_registries(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "test" { state = "available" @@ -3433,7 +3433,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceServiceRegistriesContainerConfig(rName string) string { +func testAccServiceConfig_registriesContainer(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "test" { state = "available" @@ -3537,7 +3537,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceServiceRegistriesChangesConfig(rName, discoveryName string) string { +func testAccServiceConfig_registriesChanges(rName, discoveryName string) string { return fmt.Sprintf(` data "aws_availability_zones" "test" { state = "available" @@ -3638,7 +3638,7 @@ resource "aws_ecs_service" "test" { `, rName, discoveryName) } -func testAccServiceDaemonSchedulingStrategyConfig(rName string) string { +func testAccServiceConfig_daemonSchedulingStrategy(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -3669,7 +3669,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceDaemonSchedulingStrategySetDeploymentMinimumConfig(rName string) string { +func testAccServiceConfig_daemonSchedulingStrategySetDeploymentMinimum(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -3701,7 +3701,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceDeploymentControllerTypeCodeDeployConfig(rName string) string { +func testAccServiceConfig_deploymentControllerTypeCodeDeploy(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -3801,7 +3801,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceDeploymentControllerTypeCodeDeployConfigUpdate(rName string, desiredReplicas, healthCheckGracePeriodSeconds int) string { +func testAccServiceConfig_deploymentControllerTypeCodeDeployUpdate(rName string, desiredReplicas, healthCheckGracePeriodSeconds int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -3959,7 +3959,7 @@ resource "aws_ecs_service" "test" { `, rName, desiredReplicas, healthCheckGracePeriodSeconds) } -func testAccServiceDeploymentControllerTypeExternalConfig(rName string) string { +func testAccServiceConfig_deploymentControllerTypeExternal(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -3977,7 +3977,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceDeploymentPercentsConfig(rName string, deploymentMinimumHealthyPercent, deploymentMaximumPercent int) string { +func testAccServiceConfig_deploymentPercents(rName string, deploymentMinimumHealthyPercent, deploymentMaximumPercent int) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -4010,7 +4010,7 @@ resource "aws_ecs_service" "test" { `, rName, deploymentMaximumPercent, deploymentMinimumHealthyPercent) } -func testAccServiceDeploymentCircuitBreakerConfig(rName string) string { +func testAccServiceConfig_deploymentCircuitBreaker(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -4046,7 +4046,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceTags1Config(rName, tag1Key, tag1Value string) string { +func testAccServiceConfig_tags1(rName, tag1Key, tag1Value string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -4081,7 +4081,7 @@ resource "aws_ecs_service" "test" { `, rName, tag1Key, tag1Value) } -func testAccServiceTags2Config(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccServiceConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -4117,7 +4117,7 @@ resource "aws_ecs_service" "test" { `, rName, tag1Key, tag1Value, tag2Key, tag2Value) } -func testAccServiceManagedTagsConfig(rName string) string { +func testAccServiceConfig_managedTags(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -4153,7 +4153,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServicePropagateTagsConfig(rName, propagate string) string { +func testAccServiceConfig_propagateTags(rName, propagate string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -4194,7 +4194,7 @@ resource "aws_ecs_service" "test" { `, rName, propagate) } -func testAccServiceReplicaSchedulingStrategyConfig(rName string) string { +func testAccServiceConfig_replicaSchedulingStrategy(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = %[1]q @@ -4226,7 +4226,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccServiceExecuteCommandConfig(rName string, enable bool) string { +func testAccServiceConfig_executeCommand(rName string, enable bool) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q diff --git a/internal/service/ecs/tag_test.go b/internal/service/ecs/tag_test.go index 5874df27b42..6fa0d2e7c51 100644 --- a/internal/service/ecs/tag_test.go +++ b/internal/service/ecs/tag_test.go @@ -24,7 +24,7 @@ func TestAccECSTag_basic(t *testing.T) { CheckDestroy: testAccCheckTagDestroy, Steps: []resource.TestStep{ { - Config: testAccTagConfig(rName, "key1", "value1"), + Config: testAccTagConfig_basic(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTagExists(resourceName), resource.TestCheckResourceAttr(resourceName, "key", "key1"), @@ -51,7 +51,7 @@ func TestAccECSTag_disappears(t *testing.T) { CheckDestroy: testAccCheckTagDestroy, Steps: []resource.TestStep{ { - Config: testAccTagConfig(rName, "key1", "value1"), + Config: testAccTagConfig_basic(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTagExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfecs.ResourceTag(), resourceName), @@ -74,7 +74,7 @@ func TestAccECSTag_ResourceARN_batchComputeEnvironment(t *testing.T) { CheckDestroy: testAccCheckTagDestroy, Steps: []resource.TestStep{ { - Config: testAccTagConfigResourceArnBatchComputeEnvironment(rName), + Config: testAccTagConfig_resourceARNBatchComputeEnvironment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTagExists(resourceName), ), @@ -99,7 +99,7 @@ func TestAccECSTag_value(t *testing.T) { CheckDestroy: testAccCheckTagDestroy, Steps: []resource.TestStep{ { - Config: testAccTagConfig(rName, "key1", "value1"), + Config: testAccTagConfig_basic(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTagExists(resourceName), resource.TestCheckResourceAttr(resourceName, "key", "key1"), @@ -112,7 +112,7 @@ func TestAccECSTag_value(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTagConfig(rName, "key1", "value1updated"), + Config: testAccTagConfig_basic(rName, "key1", "value1updated"), Check: resource.ComposeTestCheckFunc( testAccCheckTagExists(resourceName), resource.TestCheckResourceAttr(resourceName, "key", "key1"), @@ -123,7 +123,7 @@ func TestAccECSTag_value(t *testing.T) { }) } -func testAccTagConfig(rName string, key string, value string) string { +func testAccTagConfig_basic(rName string, key string, value string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -141,7 +141,7 @@ resource "aws_ecs_tag" "test" { `, rName, key, value) } -func testAccTagConfigResourceArnBatchComputeEnvironment(rName string) string { +func testAccTagConfig_resourceARNBatchComputeEnvironment(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/ecs/task_definition.go b/internal/service/ecs/task_definition.go index 8bec8f4afde..422aaee93e6 100644 --- a/internal/service/ecs/task_definition.go +++ b/internal/service/ecs/task_definition.go @@ -518,7 +518,7 @@ func resourceTaskDefinitionCreate(d *schema.ResourceData, meta interface{}) erro out, err := conn.RegisterTaskDefinition(&input) // Some partitions (i.e., ISO) may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed creating Task Definition (%s) with tags: %s. Trying create without tags.", d.Get("family").(string), err) input.Tags = nil @@ -542,7 +542,7 @@ func resourceTaskDefinitionCreate(d *schema.ResourceData, meta interface{}) erro err := UpdateTags(conn, aws.StringValue(taskDefinition.TaskDefinitionArn), nil, tags) // If default tags only, log and continue. Otherwise, error. - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed adding tags after create for Task Definition (%s): %s", d.Id(), err) return resourceTaskDefinitionRead(d, meta) } @@ -570,7 +570,7 @@ func resourceTaskDefinitionRead(d *schema.ResourceData, meta interface{}) error out, err := conn.DescribeTaskDefinition(&input) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed describing Task Definition (%s) with tags: %s; retrying without tags", d.Id(), err) input.Include = nil @@ -732,7 +732,7 @@ func resourceTaskDefinitionUpdate(d *schema.ResourceData, meta interface{}) erro err := UpdateTags(conn, d.Get("arn").(string), o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed updating tags for Task Definition (%s): %s", d.Id(), err) return nil } @@ -941,7 +941,7 @@ func expandVolumes(configured []interface{}) []*ecs.Volume { } if v, ok := data["fsx_windows_file_server_volume_configuration"].([]interface{}); ok && len(v) > 0 { - l.FsxWindowsFileServerVolumeConfiguration = expandVolumesFsxWinVolume(v) + l.FsxWindowsFileServerVolumeConfiguration = expandVolumesFSxWinVolume(v) } volumes = append(volumes, l) @@ -1020,7 +1020,7 @@ func expandVolumesEFSVolumeAuthorizationConfig(efsConfig []interface{}) *ecs.EFS return auth } -func expandVolumesFsxWinVolume(fsxWinConfig []interface{}) *ecs.FSxWindowsFileServerVolumeConfiguration { +func expandVolumesFSxWinVolume(fsxWinConfig []interface{}) *ecs.FSxWindowsFileServerVolumeConfiguration { config := fsxWinConfig[0].(map[string]interface{}) fsxVol := &ecs.FSxWindowsFileServerVolumeConfiguration{} @@ -1033,13 +1033,13 @@ func expandVolumesFsxWinVolume(fsxWinConfig []interface{}) *ecs.FSxWindowsFileSe } if v, ok := config["authorization_config"].([]interface{}); ok && len(v) > 0 { - fsxVol.AuthorizationConfig = expandVolumesFsxWinVolumeAuthorizationConfig(v) + fsxVol.AuthorizationConfig = expandVolumesFSxWinVolumeAuthorizationConfig(v) } return fsxVol } -func expandVolumesFsxWinVolumeAuthorizationConfig(config []interface{}) *ecs.FSxWindowsFileServerAuthorizationConfig { +func expandVolumesFSxWinVolumeAuthorizationConfig(config []interface{}) *ecs.FSxWindowsFileServerAuthorizationConfig { authconfig := config[0].(map[string]interface{}) auth := &ecs.FSxWindowsFileServerAuthorizationConfig{} @@ -1074,7 +1074,7 @@ func flattenVolumes(list []*ecs.Volume) []map[string]interface{} { } if volume.FsxWindowsFileServerVolumeConfiguration != nil { - l["fsx_windows_file_server_volume_configuration"] = flattenFsxWinVolumeConfiguration(volume.FsxWindowsFileServerVolumeConfiguration) + l["fsx_windows_file_server_volume_configuration"] = flattenFSxWinVolumeConfiguration(volume.FsxWindowsFileServerVolumeConfiguration) } result = append(result, l) @@ -1154,7 +1154,7 @@ func flattenEFSVolumeAuthorizationConfig(config *ecs.EFSAuthorizationConfig) []i return items } -func flattenFsxWinVolumeConfiguration(config *ecs.FSxWindowsFileServerVolumeConfiguration) []interface{} { +func flattenFSxWinVolumeConfiguration(config *ecs.FSxWindowsFileServerVolumeConfiguration) []interface{} { var items []interface{} m := make(map[string]interface{}) if config != nil { @@ -1167,7 +1167,7 @@ func flattenFsxWinVolumeConfiguration(config *ecs.FSxWindowsFileServerVolumeConf } if v := config.AuthorizationConfig; v != nil { - m["authorization_config"] = flattenFsxWinVolumeAuthorizationConfig(v) + m["authorization_config"] = flattenFSxWinVolumeAuthorizationConfig(v) } } @@ -1175,7 +1175,7 @@ func flattenFsxWinVolumeConfiguration(config *ecs.FSxWindowsFileServerVolumeConf return items } -func flattenFsxWinVolumeAuthorizationConfig(config *ecs.FSxWindowsFileServerAuthorizationConfig) []interface{} { +func flattenFSxWinVolumeAuthorizationConfig(config *ecs.FSxWindowsFileServerAuthorizationConfig) []interface{} { var items []interface{} m := make(map[string]interface{}) if config != nil { diff --git a/internal/service/ecs/task_definition_data_source_test.go b/internal/service/ecs/task_definition_data_source_test.go index 678061431e9..c2134459e6e 100644 --- a/internal/service/ecs/task_definition_data_source_test.go +++ b/internal/service/ecs/task_definition_data_source_test.go @@ -21,7 +21,7 @@ func TestAccECSTaskDefinitionDataSource_ecsTaskDefinition(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckTaskDefinitionDataSourceConfig(rName), + Config: testAccTaskDefinitionDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_ecs_task_definition.mongo", "arn"), resource.TestCheckResourceAttr(resourceName, "family", rName), @@ -35,7 +35,7 @@ func TestAccECSTaskDefinitionDataSource_ecsTaskDefinition(t *testing.T) { }) } -func testAccCheckTaskDefinitionDataSourceConfig(rName string) string { +func testAccTaskDefinitionDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "mongo_role" { name = "%[1]s" diff --git a/internal/service/ecs/task_definition_test.go b/internal/service/ecs/task_definition_test.go index be473841221..571fff2f1c7 100644 --- a/internal/service/ecs/task_definition_test.go +++ b/internal/service/ecs/task_definition_test.go @@ -39,14 +39,14 @@ func TestAccECSTaskDefinition_basic(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinition(rName), + Config: testAccTaskDefinitionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ecs", regexp.MustCompile(`task-definition/.+`)), ), }, { - Config: testAccTaskDefinitionModified(rName), + Config: testAccTaskDefinitionConfig_modified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ecs", regexp.MustCompile(`task-definition/.+`)), @@ -77,7 +77,7 @@ func TestAccECSTaskDefinition_scratchVolume(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionScratchVolume(rName), + Config: testAccTaskDefinitionConfig_scratchVolume(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), ), @@ -106,7 +106,7 @@ func TestAccECSTaskDefinition_DockerVolume_basic(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionDockerVolumes(rName), + Config: testAccTaskDefinitionConfig_dockerVolumes(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), @@ -149,7 +149,7 @@ func TestAccECSTaskDefinition_DockerVolume_minimal(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionDockerVolumesMinimalConfig(rName), + Config: testAccTaskDefinitionConfig_dockerVolumesMinimal(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), @@ -184,7 +184,7 @@ func TestAccECSTaskDefinition_runtimePlatform(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionRuntimePlatformMinimalConfig(rName), + Config: testAccTaskDefinitionConfig_runtimePlatformMinimal(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "runtime_platform.#", "1"), @@ -218,7 +218,7 @@ func TestAccECSTaskDefinition_Fargate_runtimePlatform(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccFargateTaskDefinitionRuntimePlatformMinimalConfig(rName, true, true), + Config: testAccTaskDefinitionConfig_fargateRuntimePlatformMinimal(rName, true, true), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "runtime_platform.#", "1"), @@ -252,7 +252,7 @@ func TestAccECSTaskDefinition_Fargate_runtimePlatformWithoutArch(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccFargateTaskDefinitionRuntimePlatformMinimalConfig(rName, false, true), + Config: testAccTaskDefinitionConfig_fargateRuntimePlatformMinimal(rName, false, true), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "runtime_platform.#", "1"), @@ -285,7 +285,7 @@ func TestAccECSTaskDefinition_EFSVolume_minimal(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionEFSVolumeMinimal(rName), + Config: testAccTaskDefinitionConfig_efsVolumeMinimal(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), @@ -320,7 +320,7 @@ func TestAccECSTaskDefinition_EFSVolume_basic(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionEFSVolume(rName, "/home/test"), + Config: testAccTaskDefinitionConfig_efsVolume(rName, "/home/test"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), @@ -355,7 +355,7 @@ func TestAccECSTaskDefinition_EFSVolume_transitEncryption(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionTransitEncryptionEFSVolume(rName, "ENABLED", 2999), + Config: testAccTaskDefinitionConfig_transitEncryptionEFSVolume(rName, "ENABLED", 2999), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), @@ -393,7 +393,7 @@ func TestAccECSTaskDefinition_EFSVolume_accessPoint(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionEFSAccessPoint(rName, "DISABLED"), + Config: testAccTaskDefinitionConfig_efsAccessPoint(rName, "DISABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), @@ -444,7 +444,7 @@ func TestAccECSTaskDefinition_fsxWinFileSystem(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionFSxVolume(domainName, rName), + Config: testAccTaskDefinitionConfig_fsxVolume(domainName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), @@ -483,7 +483,7 @@ func TestAccECSTaskDefinition_DockerVolume_taskScoped(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionTaskScopedDockerVolume(rName), + Config: testAccTaskDefinitionConfig_scopedDockerVolume(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), testAccCheckTaskDefinitionDockerVolumeConfigurationAutoprovisionNil(&def), @@ -516,14 +516,14 @@ func TestAccECSTaskDefinition_service(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionService(rName), + Config: testAccTaskDefinitionConfig_service(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), testAccCheckServiceExists("aws_ecs_service.test", &service), ), }, { - Config: testAccTaskDefinitionServiceModified(rName), + Config: testAccTaskDefinitionConfig_serviceModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), testAccCheckServiceExists("aws_ecs_service.test", &service), @@ -553,7 +553,7 @@ func TestAccECSTaskDefinition_taskRoleARN(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionTaskRoleARN(rName), + Config: testAccTaskDefinitionConfig_roleARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), ), @@ -582,7 +582,7 @@ func TestAccECSTaskDefinition_networkMode(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionNetworkMode(rName), + Config: testAccTaskDefinitionConfig_networkMode(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "network_mode", "bridge"), @@ -612,7 +612,7 @@ func TestAccECSTaskDefinition_ipcMode(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionIPcMode(rName), + Config: testAccTaskDefinitionConfig_ipcMode(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "ipc_mode", "host"), @@ -642,7 +642,7 @@ func TestAccECSTaskDefinition_pidMode(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionPIDMode(rName), + Config: testAccTaskDefinitionConfig_pidMode(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "pid_mode", "host"), @@ -672,7 +672,7 @@ func TestAccECSTaskDefinition_constraint(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinition_constraint(rName), + Config: testAccTaskDefinitionConfig_constraint(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "placement_constraints.#", "1"), @@ -704,13 +704,13 @@ func TestAccECSTaskDefinition_changeVolumesForcesNewResource(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinition(rName), + Config: testAccTaskDefinitionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &before), ), }, { - Config: testAccTaskDefinitionUpdatedVolume(rName), + Config: testAccTaskDefinitionConfig_updatedVolume(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &after), testAccCheckTaskDefinitionRecreated(t, &before, &after), @@ -741,7 +741,7 @@ func TestAccECSTaskDefinition_arrays(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionArrays(rName), + Config: testAccTaskDefinitionConfig_arrays(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &conf), ), @@ -770,7 +770,7 @@ func TestAccECSTaskDefinition_Fargate_basic(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionFargate(rName, `[{"protocol": "tcp", "containerPort": 8000}]`), + Config: testAccTaskDefinitionConfig_fargate(rName, `[{"protocol": "tcp", "containerPort": 8000}]`), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "requires_compatibilities.#", "1"), @@ -788,7 +788,7 @@ func TestAccECSTaskDefinition_Fargate_basic(t *testing.T) { { ExpectNonEmptyPlan: false, PlanOnly: true, - Config: testAccTaskDefinitionFargate(rName, `[{"protocol": "tcp", "containerPort": 8000, "hostPort": 8000}]`), + Config: testAccTaskDefinitionConfig_fargate(rName, `[{"protocol": "tcp", "containerPort": 8000, "hostPort": 8000}]`), }, }, }) @@ -807,7 +807,7 @@ func TestAccECSTaskDefinition_Fargate_ephemeralStorage(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionFargateEphemeralStorage(rName, `[{"protocol": "tcp", "containerPort": 8000}]`), + Config: testAccTaskDefinitionConfig_fargateEphemeralStorage(rName, `[{"protocol": "tcp", "containerPort": 8000}]`), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "requires_compatibilities.#", "1"), @@ -841,7 +841,7 @@ func TestAccECSTaskDefinition_executionRole(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionExecutionRole(rName), + Config: testAccTaskDefinitionConfig_executionRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &conf), ), @@ -871,7 +871,7 @@ func TestAccECSTaskDefinition_disappears(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinition(rName), + Config: testAccTaskDefinitionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), acctest.CheckResourceDisappears(acctest.Provider, tfecs.ResourceTaskDefinition(), resourceName), @@ -879,7 +879,7 @@ func TestAccECSTaskDefinition_disappears(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: testAccTaskDefinition(rName), + Config: testAccTaskDefinitionConfig_basic(rName), Check: resource.TestCheckResourceAttr(resourceName, "revision", "2"), // should get re-created }, }, @@ -898,7 +898,7 @@ func TestAccECSTaskDefinition_tags(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionTags1Config(rName, "key1", "value1"), + Config: testAccTaskDefinitionConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &taskDefinition), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -913,7 +913,7 @@ func TestAccECSTaskDefinition_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"skip_destroy"}, }, { - Config: testAccTaskDefinitionTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTaskDefinitionConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &taskDefinition), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -922,7 +922,7 @@ func TestAccECSTaskDefinition_tags(t *testing.T) { ), }, { - Config: testAccTaskDefinitionTags1Config(rName, "key2", "value2"), + Config: testAccTaskDefinitionConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &taskDefinition), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -955,7 +955,7 @@ func TestAccECSTaskDefinition_proxy(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionProxyConfigurationConfig(rName, containerName, proxyType, ignoredUid, ignoredGid, appPorts, proxyIngressPort, proxyEgressPort, egressIgnoredPorts, egressIgnoredIPs), + Config: testAccTaskDefinitionConfig_proxyConfiguration(rName, containerName, proxyType, ignoredUid, ignoredGid, appPorts, proxyIngressPort, proxyEgressPort, egressIgnoredPorts, egressIgnoredIPs), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &taskDefinition), testAccCheckTaskDefinitionProxyConfiguration(&taskDefinition, containerName, proxyType, ignoredUid, ignoredGid, appPorts, proxyIngressPort, proxyEgressPort, egressIgnoredPorts, egressIgnoredIPs), @@ -985,7 +985,7 @@ func TestAccECSTaskDefinition_inferenceAccelerator(t *testing.T) { CheckDestroy: testAccCheckTaskDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskDefinitionInferenceAcceleratorConfig(rName), + Config: testAccTaskDefinitionConfig_inferenceAccelerator(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "inference_accelerator.#", "1"), @@ -1002,7 +1002,7 @@ func TestAccECSTaskDefinition_inferenceAccelerator(t *testing.T) { }) } -func testAccTaskDefinitionProxyConfigurationConfig(rName string, containerName string, proxyType string, +func testAccTaskDefinitionConfig_proxyConfiguration(rName string, containerName string, proxyType string, ignoredUid string, ignoredGid string, appPorts string, proxyIngressPort string, proxyEgressPort string, egressIgnoredPorts string, egressIgnoredIPs string) string { @@ -1203,7 +1203,7 @@ func testAccCheckTaskDefinitionDockerVolumeConfigurationAutoprovisionNil(def *ec } } -func testAccTaskDefinition_constraint(rName string) string { +func testAccTaskDefinitionConfig_constraint(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1260,7 +1260,7 @@ TASK_DEFINITION `, rName)) } -func testAccTaskDefinition(rName string) string { +func testAccTaskDefinitionConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1312,7 +1312,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionUpdatedVolume(rName string) string { +func testAccTaskDefinitionConfig_updatedVolume(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1364,7 +1364,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionArrays(rName string) string { +func testAccTaskDefinitionConfig_arrays(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1475,7 +1475,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionFargate(rName, portMappings string) string { +func testAccTaskDefinitionConfig_fargate(rName, portMappings string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1501,7 +1501,7 @@ TASK_DEFINITION `, rName, portMappings) } -func testAccTaskDefinitionFargateEphemeralStorage(rName, portMappings string) string { +func testAccTaskDefinitionConfig_fargateEphemeralStorage(rName, portMappings string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1531,7 +1531,7 @@ TASK_DEFINITION `, rName, portMappings) } -func testAccTaskDefinitionExecutionRole(rName string) string { +func testAccTaskDefinitionConfig_executionRole(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -1603,7 +1603,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionScratchVolume(rName string) string { +func testAccTaskDefinitionConfig_scratchVolume(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1628,7 +1628,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionDockerVolumes(rName string) string { +func testAccTaskDefinitionConfig_dockerVolumes(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1670,7 +1670,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionDockerVolumesMinimalConfig(rName string) string { +func testAccTaskDefinitionConfig_dockerVolumesMinimal(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1699,7 +1699,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionRuntimePlatformMinimalConfig(rName string) string { +func testAccTaskDefinitionConfig_runtimePlatformMinimal(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1723,7 +1723,7 @@ TASK_DEFINITION `, rName) } -func testAccFargateTaskDefinitionRuntimePlatformMinimalConfig(rName string, architecture bool, osFamily bool) string { +func testAccTaskDefinitionConfig_fargateRuntimePlatformMinimal(rName string, architecture bool, osFamily bool) string { var arch string if architecture { @@ -1768,7 +1768,7 @@ TASK_DEFINITION `, rName, arch, os) } -func testAccTaskDefinitionTaskScopedDockerVolume(rName string) string { +func testAccTaskDefinitionConfig_scopedDockerVolume(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -1797,7 +1797,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionEFSVolumeMinimal(rName string) string { +func testAccTaskDefinitionConfig_efsVolumeMinimal(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -1830,7 +1830,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionEFSVolume(rName, rDir string) string { +func testAccTaskDefinitionConfig_efsVolume(rName, rDir string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -1864,7 +1864,7 @@ TASK_DEFINITION `, rName, rDir) } -func testAccTaskDefinitionTransitEncryptionEFSVolume(rName, tEnc string, tEncPort int) string { +func testAccTaskDefinitionConfig_transitEncryptionEFSVolume(rName, tEnc string, tEncPort int) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -1900,7 +1900,7 @@ TASK_DEFINITION `, rName, tEnc, tEncPort) } -func testAccTaskDefinitionEFSAccessPoint(rName, useIam string) string { +func testAccTaskDefinitionConfig_efsAccessPoint(rName, useIam string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -1947,7 +1947,7 @@ TASK_DEFINITION `, rName, useIam) } -func testAccTaskDefinitionTaskRoleARN(rName string) string { +func testAccTaskDefinitionConfig_roleARN(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -2017,7 +2017,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionIPcMode(rName string) string { +func testAccTaskDefinitionConfig_ipcMode(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -2090,7 +2090,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionPIDMode(rName string) string { +func testAccTaskDefinitionConfig_pidMode(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -2163,7 +2163,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionNetworkMode(rName string) string { +func testAccTaskDefinitionConfig_networkMode(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -2235,7 +2235,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionService(rName string) string { +func testAccTaskDefinitionConfig_service(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -2271,7 +2271,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionServiceModified(rName string) string { +func testAccTaskDefinitionConfig_serviceModified(rName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -2307,7 +2307,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionModified(rName string) string { +func testAccTaskDefinitionConfig_modified(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -2385,7 +2385,7 @@ var testValidTaskDefinitionInvalidCommandContainerDefinitions = ` ] ` -func testAccTaskDefinitionTags1Config(rName, tag1Key, tag1Value string) string { +func testAccTaskDefinitionConfig_tags1(rName, tag1Key, tag1Value string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -2413,7 +2413,7 @@ DEFINITION `, rName, tag1Key, tag1Value) } -func testAccTaskDefinitionTags2Config(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccTaskDefinitionConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "test" { name = %[1]q @@ -2442,7 +2442,7 @@ DEFINITION `, rName, tag1Key, tag1Value, tag2Key, tag2Value) } -func testAccTaskDefinitionInferenceAcceleratorConfig(rName string) string { +func testAccTaskDefinitionConfig_inferenceAccelerator(rName string) string { return fmt.Sprintf(` resource "aws_ecs_task_definition" "test" { family = %[1]q @@ -2484,7 +2484,7 @@ TASK_DEFINITION `, rName) } -func testAccTaskDefinitionFSxVolume(domain, rName string) string { +func testAccTaskDefinitionConfig_fsxVolume(domain, rName string) string { return acctest.ConfigCompose( testAccFSxWindowsFileSystemSubnetIds1Config(rName, domain), fmt.Sprintf(` @@ -2586,7 +2586,7 @@ func testAccTaskDefinitionImportStateIdFunc(resourceName string) resource.Import func testAccFSxWindowsFileSystemBaseConfig(rName, domain string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_directory_service_directory" "test" { edition = "Standard" diff --git a/internal/service/ecs/task_set.go b/internal/service/ecs/task_set.go index fedb0a668a4..3e4464a8e13 100644 --- a/internal/service/ecs/task_set.go +++ b/internal/service/ecs/task_set.go @@ -334,7 +334,7 @@ func resourceTaskSetCreate(d *schema.ResourceData, meta interface{}) error { output, err := retryTaskSetCreate(conn, input) // Some partitions (i.e., ISO) may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed creating Task Set with tags: %s. Trying create without tags.", err) input.Tags = nil @@ -360,7 +360,7 @@ func resourceTaskSetCreate(d *schema.ResourceData, meta interface{}) error { if input.Tags == nil && len(tags) > 0 { err := UpdateTags(conn, aws.StringValue(output.TaskSet.TaskSetArn), nil, tags) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // If default tags only, log and continue. Otherwise, error. log.Printf("[WARN] ECS tagging failed adding tags after create for Task Set (%s): %s", d.Id(), err) return resourceTaskSetRead(d, meta) @@ -401,7 +401,7 @@ func resourceTaskSetRead(d *schema.ResourceData, meta interface{}) error { } // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed describing Task Set (%s) with tags: %s; retrying without tags", d.Id(), err) input.Include = nil @@ -505,7 +505,7 @@ func resourceTaskSetUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, d.Get("arn").(string), o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ECS tagging failed updating tags for Task Set (%s): %s", d.Id(), err) return resourceTaskSetRead(d, meta) } diff --git a/internal/service/ecs/task_set_test.go b/internal/service/ecs/task_set_test.go index 6e5d0549ba6..93b5297e85e 100644 --- a/internal/service/ecs/task_set_test.go +++ b/internal/service/ecs/task_set_test.go @@ -27,7 +27,7 @@ func TestAccECSTaskSet_basic(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetBasicConfig(rName), + Config: testAccTaskSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ecs", regexp.MustCompile(fmt.Sprintf("task-set/%[1]s/%[1]s/ecs-svc/.+", rName))), @@ -60,7 +60,7 @@ func TestAccECSTaskSet_withExternalId(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetWithExternalIdConfig(rName), + Config: testAccTaskSetConfig_externalID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "service_registries.#", "0"), @@ -91,7 +91,7 @@ func TestAccECSTaskSet_withScale(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetWithScaleConfig(rName, 0.0), + Config: testAccTaskSetConfig_scale(rName, 0.0), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "scale.#", "1"), @@ -108,7 +108,7 @@ func TestAccECSTaskSet_withScale(t *testing.T) { }, }, { - Config: testAccTaskSetWithScaleConfig(rName, 100.0), + Config: testAccTaskSetConfig_scale(rName, 100.0), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "scale.#", "1"), @@ -139,7 +139,7 @@ func TestAccECSTaskSet_disappears(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetBasicConfig(rName), + Config: testAccTaskSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfecs.ResourceTaskSet(), resourceName), @@ -161,7 +161,7 @@ func TestAccECSTaskSet_withCapacityProviderStrategy(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetWithCapacityProviderStrategy(rName, 1, 0), + Config: testAccTaskSetConfig_capacityProviderStrategy(rName, 1, 0), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), ), @@ -175,7 +175,7 @@ func TestAccECSTaskSet_withCapacityProviderStrategy(t *testing.T) { }, }, { - Config: testAccTaskSetWithCapacityProviderStrategy(rName, 10, 1), + Config: testAccTaskSetConfig_capacityProviderStrategy(rName, 10, 1), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), ), @@ -203,7 +203,7 @@ func TestAccECSTaskSet_withMultipleCapacityProviderStrategies(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetWithMultipleCapacityProviderStrategies(rName), + Config: testAccTaskSetConfig_multipleCapacityProviderStrategies(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "capacity_provider_strategy.#", "2"), @@ -232,7 +232,7 @@ func TestAccECSTaskSet_withAlb(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetWithAlb(rName), + Config: testAccTaskSetConfig_alb(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "load_balancer.#", "1"), @@ -261,7 +261,7 @@ func TestAccECSTaskSet_withLaunchTypeFargate(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetWithLaunchTypeFargate(rName), + Config: testAccTaskSetConfig_launchTypeFargate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "launch_type", "FARGATE"), @@ -295,7 +295,7 @@ func TestAccECSTaskSet_withLaunchTypeFargateAndPlatformVersion(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetWithLaunchTypeFargateAndPlatformVersion(rName, "1.3.0"), + Config: testAccTaskSetConfig_launchTypeFargateAndPlatformVersion(rName, "1.3.0"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "platform_version", "1.3.0"), @@ -310,7 +310,7 @@ func TestAccECSTaskSet_withLaunchTypeFargateAndPlatformVersion(t *testing.T) { }, }, { - Config: testAccTaskSetWithLaunchTypeFargateAndPlatformVersion(rName, "1.4.0"), + Config: testAccTaskSetConfig_launchTypeFargateAndPlatformVersion(rName, "1.4.0"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "platform_version", "1.4.0"), @@ -339,7 +339,7 @@ func TestAccECSTaskSet_withServiceRegistries(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSet_withServiceRegistries(rName), + Config: testAccTaskSetConfig_serviceRegistries(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "service_registries.#", "1"), @@ -368,7 +368,7 @@ func TestAccECSTaskSet_Tags(t *testing.T) { CheckDestroy: testAccCheckTaskSetDestroy, Steps: []resource.TestStep{ { - Config: testAccTaskSetConfigTags1(rName, "key1", "value1"), + Config: testAccTaskSetConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -384,7 +384,7 @@ func TestAccECSTaskSet_Tags(t *testing.T) { }, }, { - Config: testAccTaskSetConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTaskSetConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -393,7 +393,7 @@ func TestAccECSTaskSet_Tags(t *testing.T) { ), }, { - Config: testAccTaskSetConfigTags1(rName, "key2", "value2"), + Config: testAccTaskSetConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTaskSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -440,7 +440,7 @@ resource "aws_ecs_service" "test" { `, rName) } -func testAccTaskSetBasicConfig(rName string) string { +func testAccTaskSetConfig_basic(rName string) string { return acctest.ConfigCompose( testAccTaskSetBaseConfig(rName), ` @@ -452,7 +452,7 @@ resource "aws_ecs_task_set" "test" { `) } -func testAccTaskSetWithExternalIdConfig(rName string) string { +func testAccTaskSetConfig_externalID(rName string) string { return acctest.ConfigCompose( testAccTaskSetBaseConfig(rName), ` @@ -465,7 +465,7 @@ resource "aws_ecs_task_set" "test" { `) } -func testAccTaskSetWithScaleConfig(rName string, scale float64) string { +func testAccTaskSetConfig_scale(rName string, scale float64) string { return acctest.ConfigCompose( testAccTaskSetBaseConfig(rName), fmt.Sprintf(` @@ -480,7 +480,7 @@ resource "aws_ecs_task_set" "test" { `, scale)) } -func testAccTaskSetWithCapacityProviderStrategy(rName string, weight, base int) string { +func testAccTaskSetConfig_capacityProviderStrategy(rName string, weight, base int) string { return acctest.ConfigCompose( testAccCapacityProviderBaseConfig(rName), testAccTaskSetBaseConfig(rName), @@ -505,7 +505,7 @@ resource "aws_ecs_task_set" "test" { `, rName, weight, base)) } -func testAccTaskSetWithMultipleCapacityProviderStrategies(rName string) string { +func testAccTaskSetConfig_multipleCapacityProviderStrategies(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.0.0/16" @@ -601,7 +601,7 @@ resource "aws_ecs_task_set" "test" { `, rName) } -func testAccTaskSetWithAlb(rName string) string { +func testAccTaskSetConfig_alb(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -692,7 +692,7 @@ resource "aws_ecs_task_set" "test" { `, rName)) } -func testAccTaskSetConfigTags1(rName, tag1Key, tag1Value string) string { +func testAccTaskSetConfig_tags1(rName, tag1Key, tag1Value string) string { return acctest.ConfigCompose( testAccTaskSetBaseConfig(rName), fmt.Sprintf(` @@ -707,7 +707,7 @@ resource "aws_ecs_task_set" "test" { `, tag1Key, tag1Value)) } -func testAccTaskSetConfigTags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccTaskSetConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return acctest.ConfigCompose( testAccTaskSetBaseConfig(rName), fmt.Sprintf(` @@ -723,7 +723,7 @@ resource "aws_ecs_task_set" "test" { `, tag1Key, tag1Value, tag2Key, tag2Value)) } -func testAccTaskSet_withServiceRegistries(rName string) string { +func testAccTaskSetConfig_serviceRegistries(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -817,7 +817,7 @@ resource "aws_ecs_task_set" "test" { `, rName)) } -func testAccTaskSetWithLaunchTypeFargate(rName string) string { +func testAccTaskSetConfig_launchTypeFargate(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -899,7 +899,7 @@ resource "aws_ecs_task_set" "test" { `, rName)) } -func testAccTaskSetWithLaunchTypeFargateAndPlatformVersion(rName, platformVersion string) string { +func testAccTaskSetConfig_launchTypeFargateAndPlatformVersion(rName, platformVersion string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` diff --git a/internal/service/efs/access_point_data_source_test.go b/internal/service/efs/access_point_data_source_test.go index 0ad24391e0a..165c4ef97ef 100644 --- a/internal/service/efs/access_point_data_source_test.go +++ b/internal/service/efs/access_point_data_source_test.go @@ -22,7 +22,7 @@ func TestAccEFSAccessPointDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointDataSourceConfig(rName), + Config: testAccAccessPointDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "owner_id", resourceName, "owner_id"), @@ -35,7 +35,7 @@ func TestAccEFSAccessPointDataSource_basic(t *testing.T) { }) } -func testAccAccessPointDataSourceConfig(rName string) string { +func testAccAccessPointDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = "%s" diff --git a/internal/service/efs/access_point_test.go b/internal/service/efs/access_point_test.go index 6a617c20cba..846cd22ffbf 100644 --- a/internal/service/efs/access_point_test.go +++ b/internal/service/efs/access_point_test.go @@ -29,7 +29,7 @@ func TestAccEFSAccessPoint_basic(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointConfig(rName), + Config: testAccAccessPointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &ap), resource.TestCheckResourceAttrPair(resourceName, "file_system_arn", fsResourceName, "arn"), @@ -63,7 +63,7 @@ func TestAccEFSAccessPoint_Root_directory(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointRootDirectoryConfig(rName, "/home/test"), + Config: testAccAccessPointConfig_rootDirectory(rName, "/home/test"), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &ap), resource.TestCheckResourceAttr(resourceName, "root_directory.#", "1"), @@ -92,7 +92,7 @@ func TestAccEFSAccessPoint_RootDirectoryCreation_info(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointRootDirectoryCreationInfoConfig(rName, "/home/test"), + Config: testAccAccessPointConfig_rootDirectoryCreationInfo(rName, "/home/test"), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &ap), resource.TestCheckResourceAttr(resourceName, "root_directory.#", "1"), @@ -124,7 +124,7 @@ func TestAccEFSAccessPoint_POSIX_user(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointPOSIXUserConfig(rName), + Config: testAccAccessPointConfig_posixUser(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &ap), resource.TestCheckResourceAttr(resourceName, "posix_user.#", "1"), @@ -154,7 +154,7 @@ func TestAccEFSAccessPoint_POSIXUserSecondary_gids(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointPOSIXUserSecondaryGidsConfig(rName), + Config: testAccAccessPointConfig_posixUserSecondaryGids(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &ap), resource.TestCheckResourceAttr(resourceName, "posix_user.#", "1"), @@ -183,7 +183,7 @@ func TestAccEFSAccessPoint_tags(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointTags1Config(rName, "key1", "value1"), + Config: testAccAccessPointConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &ap), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -196,7 +196,7 @@ func TestAccEFSAccessPoint_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAccessPointTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAccessPointConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &ap), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -205,7 +205,7 @@ func TestAccEFSAccessPoint_tags(t *testing.T) { ), }, { - Config: testAccAccessPointTags1Config(rName, "key2", "value2"), + Config: testAccAccessPointConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &ap), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -228,7 +228,7 @@ func TestAccEFSAccessPoint_disappears(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointConfig(rName), + Config: testAccAccessPointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &ap), acctest.CheckResourceDisappears(acctest.Provider, tfefs.ResourceAccessPoint(), resourceName), @@ -298,7 +298,7 @@ func testAccCheckAccessPointExists(resourceID string, mount *efs.AccessPointDesc } } -func testAccAccessPointConfig(rName string) string { +func testAccAccessPointConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = "%s" @@ -310,7 +310,7 @@ resource "aws_efs_access_point" "test" { `, rName) } -func testAccAccessPointRootDirectoryConfig(rName, dir string) string { +func testAccAccessPointConfig_rootDirectory(rName, dir string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -325,7 +325,7 @@ resource "aws_efs_access_point" "test" { `, rName, dir) } -func testAccAccessPointRootDirectoryCreationInfoConfig(rName, dir string) string { +func testAccAccessPointConfig_rootDirectoryCreationInfo(rName, dir string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -345,7 +345,7 @@ resource "aws_efs_access_point" "test" { `, rName, dir) } -func testAccAccessPointPOSIXUserConfig(rName string) string { +func testAccAccessPointConfig_posixUser(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = "%s" @@ -361,7 +361,7 @@ resource "aws_efs_access_point" "test" { `, rName) } -func testAccAccessPointPOSIXUserSecondaryGidsConfig(rName string) string { +func testAccAccessPointConfig_posixUserSecondaryGids(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = "%s" @@ -378,7 +378,7 @@ resource "aws_efs_access_point" "test" { `, rName) } -func testAccAccessPointTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAccessPointConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -394,7 +394,7 @@ resource "aws_efs_access_point" "test" { `, rName, tagKey1, tagValue1) } -func testAccAccessPointTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAccessPointConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q diff --git a/internal/service/efs/access_points_data_source_test.go b/internal/service/efs/access_points_data_source_test.go index b6f17ea9ee7..0d94ecd9395 100644 --- a/internal/service/efs/access_points_data_source_test.go +++ b/internal/service/efs/access_points_data_source_test.go @@ -18,7 +18,7 @@ func TestAccEFSAccessPointsDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointsDataSourceConfig(), + Config: testAccAccessPointsDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "arns.#", "1"), resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), @@ -38,7 +38,7 @@ func TestAccEFSAccessPointsDataSource_empty(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointsEmptyDataSourceConfig(), + Config: testAccAccessPointsDataSourceConfig_empty(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "arns.#", "0"), resource.TestCheckResourceAttr(dataSourceName, "ids.#", "0"), @@ -48,7 +48,7 @@ func TestAccEFSAccessPointsDataSource_empty(t *testing.T) { }) } -func testAccAccessPointsDataSourceConfig() string { +func testAccAccessPointsDataSourceConfig_basic() string { return ` resource "aws_efs_file_system" "test" {} @@ -62,7 +62,7 @@ data "aws_efs_access_points" "test" { ` } -func testAccAccessPointsEmptyDataSourceConfig() string { +func testAccAccessPointsDataSourceConfig_empty() string { return ` resource "aws_efs_file_system" "test" {} diff --git a/internal/service/efs/backup_policy_test.go b/internal/service/efs/backup_policy_test.go index b2407f3d3d7..7bff23224e7 100644 --- a/internal/service/efs/backup_policy_test.go +++ b/internal/service/efs/backup_policy_test.go @@ -27,7 +27,7 @@ func TestAccEFSBackupPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckBackupPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupPolicyConfig(rName, "ENABLED"), + Config: testAccBackupPolicyConfig_basic(rName, "ENABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckBackupPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "backup_policy.#", "1"), @@ -56,7 +56,7 @@ func TestAccEFSBackupPolicy_Disappears_fs(t *testing.T) { CheckDestroy: testAccCheckBackupPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupPolicyConfig(rName, "ENABLED"), + Config: testAccBackupPolicyConfig_basic(rName, "ENABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckBackupPolicyExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfefs.ResourceFileSystem(), fsResourceName), @@ -79,7 +79,7 @@ func TestAccEFSBackupPolicy_update(t *testing.T) { CheckDestroy: testAccCheckBackupPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupPolicyConfig(rName, "DISABLED"), + Config: testAccBackupPolicyConfig_basic(rName, "DISABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckBackupPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "backup_policy.#", "1"), @@ -92,7 +92,7 @@ func TestAccEFSBackupPolicy_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupPolicyConfig(rName, "ENABLED"), + Config: testAccBackupPolicyConfig_basic(rName, "ENABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckBackupPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "backup_policy.#", "1"), @@ -100,7 +100,7 @@ func TestAccEFSBackupPolicy_update(t *testing.T) { ), }, { - Config: testAccBackupPolicyConfig(rName, "DISABLED"), + Config: testAccBackupPolicyConfig_basic(rName, "DISABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckBackupPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "backup_policy.#", "1"), @@ -164,7 +164,7 @@ func testAccCheckBackupPolicyDestroy(s *terraform.State) error { return nil } -func testAccBackupPolicyConfig(rName, status string) string { +func testAccBackupPolicyConfig_basic(rName, status string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q diff --git a/internal/service/efs/file_system_data_source_test.go b/internal/service/efs/file_system_data_source_test.go index cf43440da90..cea85e6e9ea 100644 --- a/internal/service/efs/file_system_data_source_test.go +++ b/internal/service/efs/file_system_data_source_test.go @@ -22,7 +22,7 @@ func TestAccEFSFileSystemDataSource_id(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccFileSystemIDDataSourceConfig, + Config: testAccFileSystemDataSourceConfig_id, Check: resource.ComposeTestCheckFunc( testAccFileSystemCheckDataSource(dataSourceName, resourceName), resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), @@ -52,7 +52,7 @@ func TestAccEFSFileSystemDataSource_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccFileSystemTagsDataSourceConfig, + Config: testAccFileSystemDataSourceConfig_tags, Check: resource.ComposeTestCheckFunc( testAccFileSystemCheckDataSource(dataSourceName, resourceName), resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), @@ -82,7 +82,7 @@ func TestAccEFSFileSystemDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccFileSystemNameDataSourceConfig, + Config: testAccFileSystemDataSourceConfig_name, Check: resource.ComposeTestCheckFunc( testAccFileSystemCheckDataSource(dataSourceName, resourceName), resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), @@ -112,7 +112,7 @@ func TestAccEFSFileSystemDataSource_availabilityZone(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccFileSystemAvailabilityZoneDataSourceConfig, + Config: testAccFileSystemDataSourceConfig_availabilityZone, Check: resource.ComposeTestCheckFunc( testAccFileSystemCheckDataSource(dataSourceName, resourceName), resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone_id", resourceName, "availability_zone_id"), @@ -130,7 +130,7 @@ func TestAccEFSFileSystemDataSource_nonExistent_fileSystemID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccFileSystemIDDataSourceConfig_NonExistent, + Config: testAccFileSystemDataSourceConfig_idNonExistent, ExpectError: regexp.MustCompile(`error reading EFS FileSystem`), }, }, @@ -148,13 +148,13 @@ func TestAccEFSFileSystemDataSource_nonExistent_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccFileSystemConfig(rName), + Config: testAccFileSystemConfig_dataSourceBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), ), }, { - Config: testAccFileSystemTagsDataSourceConfig_NonExistent(rName), + Config: testAccFileSystemDataSourceConfig_tagsNonExistent(rName), ExpectError: regexp.MustCompile(`Search returned 0 results`), }, }, @@ -195,15 +195,15 @@ func testAccFileSystemCheckDataSource(dName, rName string) resource.TestCheckFun } } -const testAccFileSystemIDDataSourceConfig_NonExistent = ` +const testAccFileSystemDataSourceConfig_idNonExistent = ` data "aws_efs_file_system" "test" { file_system_id = "fs-nonexistent" } ` -func testAccFileSystemTagsDataSourceConfig_NonExistent(rName string) string { +func testAccFileSystemDataSourceConfig_tagsNonExistent(rName string) string { return acctest.ConfigCompose( - testAccFileSystemConfig(rName), + testAccFileSystemConfig_dataSourceBasic(rName), ` data "aws_efs_file_system" "test" { tags = { @@ -213,7 +213,7 @@ data "aws_efs_file_system" "test" { `) } -const testAccFileSystemNameDataSourceConfig = ` +const testAccFileSystemDataSourceConfig_name = ` resource "aws_efs_file_system" "test" {} data "aws_efs_file_system" "test" { @@ -221,7 +221,7 @@ data "aws_efs_file_system" "test" { } ` -const testAccFileSystemIDDataSourceConfig = ` +const testAccFileSystemDataSourceConfig_id = ` resource "aws_efs_file_system" "test" {} data "aws_efs_file_system" "test" { @@ -229,7 +229,7 @@ data "aws_efs_file_system" "test" { } ` -const testAccFileSystemTagsDataSourceConfig = ` +const testAccFileSystemDataSourceConfig_tags = ` resource "aws_efs_file_system" "test" { tags = { Name = "default-efs" @@ -250,7 +250,7 @@ data "aws_efs_file_system" "test" { } ` -const testAccFileSystemAvailabilityZoneDataSourceConfig = ` +const testAccFileSystemDataSourceConfig_availabilityZone = ` data "aws_availability_zones" "available" { state = "available" diff --git a/internal/service/efs/file_system_policy_test.go b/internal/service/efs/file_system_policy_test.go index 6b224d5f222..a093ca9c34d 100644 --- a/internal/service/efs/file_system_policy_test.go +++ b/internal/service/efs/file_system_policy_test.go @@ -26,7 +26,7 @@ func TestAccEFSFileSystemPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckFileSystemPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemPolicyConfig(rName), + Config: testAccFileSystemPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemPolicyExists(resourceName, &desc), resource.TestCheckResourceAttrSet(resourceName, "policy"), @@ -39,7 +39,7 @@ func TestAccEFSFileSystemPolicy_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"bypass_policy_lockout_safety_check"}, }, { - Config: testAccFileSystemPolicyUpdatedConfig(rName), + Config: testAccFileSystemPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemPolicyExists(resourceName, &desc), resource.TestCheckResourceAttrSet(resourceName, "policy"), @@ -61,7 +61,7 @@ func TestAccEFSFileSystemPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckFileSystemPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemPolicyConfig(rName), + Config: testAccFileSystemPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemPolicyExists(resourceName, &desc), acctest.CheckResourceDisappears(acctest.Provider, tfefs.ResourceFileSystemPolicy(), resourceName), @@ -84,7 +84,7 @@ func TestAccEFSFileSystemPolicy_policyBypass(t *testing.T) { CheckDestroy: testAccCheckFileSystemPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemPolicyConfig(rName), + Config: testAccFileSystemPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemPolicyExists(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "bypass_policy_lockout_safety_check", "false"), @@ -97,7 +97,7 @@ func TestAccEFSFileSystemPolicy_policyBypass(t *testing.T) { ImportStateVerifyIgnore: []string{"bypass_policy_lockout_safety_check"}, }, { - Config: testAccFileSystemPolicyBypassConfig(rName, true), + Config: testAccFileSystemPolicyConfig_bypass(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemPolicyExists(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "bypass_policy_lockout_safety_check", "true"), @@ -120,14 +120,14 @@ func TestAccEFSFileSystemPolicy_equivalentPolicies(t *testing.T) { CheckDestroy: testAccCheckFileSystemPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemPolicyFirstEquivalentConfig(rName), + Config: testAccFileSystemPolicyConfig_firstEquivalent(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemPolicyExists(resourceName, &desc), resource.TestCheckResourceAttrSet(resourceName, "policy"), ), }, { - Config: testAccFileSystemPolicySecondEquivalentConfig(rName), + Config: testAccFileSystemPolicyConfig_secondEquivalent(rName), PlanOnly: true, }, }, @@ -147,14 +147,14 @@ func TestAccEFSFileSystemPolicy_equivalentPoliciesIAMPolicyDoc(t *testing.T) { CheckDestroy: testAccCheckFileSystemPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemPolicyEquivalentIAMPolicyDocConfig(rName), + Config: testAccFileSystemPolicyConfig_equivalentIAMDoc(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemPolicyExists(resourceName, &desc), resource.TestCheckResourceAttrSet(resourceName, "policy"), ), }, { - Config: testAccFileSystemPolicyEquivalentIAMPolicyDocConfig(rName), + Config: testAccFileSystemPolicyConfig_equivalentIAMDoc(rName), PlanOnly: true, }, }, @@ -210,7 +210,7 @@ func testAccCheckFileSystemPolicyExists(n string, v *efs.DescribeFileSystemPolic } } -func testAccFileSystemPolicyConfig(rName string) string { +func testAccFileSystemPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -248,7 +248,7 @@ POLICY `, rName) } -func testAccFileSystemPolicyUpdatedConfig(rName string) string { +func testAccFileSystemPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -283,7 +283,7 @@ POLICY `, rName) } -func testAccFileSystemPolicyBypassConfig(rName string, bypass bool) string { +func testAccFileSystemPolicyConfig_bypass(rName string, bypass bool) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -323,7 +323,7 @@ POLICY `, rName, bypass) } -func testAccFileSystemPolicyFirstEquivalentConfig(rName string) string { +func testAccFileSystemPolicyConfig_firstEquivalent(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -357,7 +357,7 @@ resource "aws_efs_file_system_policy" "test" { `, rName) } -func testAccFileSystemPolicySecondEquivalentConfig(rName string) string { +func testAccFileSystemPolicyConfig_secondEquivalent(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -391,7 +391,7 @@ resource "aws_efs_file_system_policy" "test" { `, rName) } -func testAccFileSystemPolicyEquivalentIAMPolicyDocConfig(rName string) string { +func testAccFileSystemPolicyConfig_equivalentIAMDoc(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q diff --git a/internal/service/efs/file_system_test.go b/internal/service/efs/file_system_test.go index aca5e3cb727..17ae0e4a8c5 100644 --- a/internal/service/efs/file_system_test.go +++ b/internal/service/efs/file_system_test.go @@ -27,7 +27,7 @@ func TestAccEFSFileSystem_basic(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemConfig(rName), + Config: testAccFileSystemConfig_dataSourceBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elasticfilesystem", regexp.MustCompile(`file-system/fs-.+`)), @@ -52,7 +52,7 @@ func TestAccEFSFileSystem_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFileSystemWithPerformanceModeConfig, + Config: testAccFileSystemConfig_performanceMode, Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem("aws_efs_file_system.test2", &desc), resource.TestCheckResourceAttr("aws_efs_file_system.test2", "creation_token", "supercalifragilisticexpialidocious"), @@ -75,7 +75,7 @@ func TestAccEFSFileSystem_availabilityZoneName(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemAvailabilityZoneNameConfig(rName), + Config: testAccFileSystemConfig_availabilityZoneName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttrPair(resourceName, "availability_zone_id", "data.aws_availability_zones.available", "zone_ids.0"), @@ -103,7 +103,7 @@ func TestAccEFSFileSystem_tags(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemTags1Config(rName, "key1", "value1"), + Config: testAccFileSystemConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -116,7 +116,7 @@ func TestAccEFSFileSystem_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFileSystemTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccFileSystemConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -125,7 +125,7 @@ func TestAccEFSFileSystem_tags(t *testing.T) { ), }, { - Config: testAccFileSystemTags1Config(rName, "key2", "value2"), + Config: testAccFileSystemConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -133,7 +133,7 @@ func TestAccEFSFileSystem_tags(t *testing.T) { ), }, { - Config: testAccFileSystemWithMaxTagsConfig(rName), + Config: testAccFileSystemConfig_maxTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "tags.%", "50"), @@ -158,7 +158,7 @@ func TestAccEFSFileSystem_pagedTags(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemPagedTagsConfig(rInt), + Config: testAccFileSystemConfig_pagedTags(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "tags.%", "10"), @@ -186,7 +186,7 @@ func TestAccEFSFileSystem_kmsKey(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemWithKMSKeyConfig(rInt, true), + Config: testAccFileSystemConfig_kmsKey(rInt, true), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsKeyResourceName, "arn"), @@ -212,7 +212,7 @@ func TestAccEFSFileSystem_kmsWithoutEncryption(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemWithKMSKeyConfig(rInt, false), + Config: testAccFileSystemConfig_kmsKey(rInt, false), ExpectError: regexp.MustCompile(`encrypted must be set to true when kms_key_id is specified`), }, }, @@ -230,7 +230,7 @@ func TestAccEFSFileSystem_provisionedThroughputInMibps(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemConfig_ProvisionedThroughputInMibps(1.0), + Config: testAccFileSystemConfig_provisionedThroughputInMibps(1.0), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "provisioned_throughput_in_mibps", "1"), @@ -238,7 +238,7 @@ func TestAccEFSFileSystem_provisionedThroughputInMibps(t *testing.T) { ), }, { - Config: testAccFileSystemConfig_ProvisionedThroughputInMibps(2.0), + Config: testAccFileSystemConfig_provisionedThroughputInMibps(2.0), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "provisioned_throughput_in_mibps", "2"), @@ -265,7 +265,7 @@ func TestAccEFSFileSystem_throughputMode(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemConfig_ProvisionedThroughputInMibps(1.0), + Config: testAccFileSystemConfig_provisionedThroughputInMibps(1.0), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "provisioned_throughput_in_mibps", "1"), @@ -273,7 +273,7 @@ func TestAccEFSFileSystem_throughputMode(t *testing.T) { ), }, { - Config: testAccFileSystemConfig_ThroughputMode(efs.ThroughputModeBursting), + Config: testAccFileSystemConfig_throughputMode(efs.ThroughputModeBursting), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "provisioned_throughput_in_mibps", "0"), @@ -300,14 +300,14 @@ func TestAccEFSFileSystem_lifecyclePolicy(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemWithLifecyclePolicyConfig( + Config: testAccFileSystemConfig_lifecyclePolicy( "transition_to_ia", "invalid_value", ), ExpectError: regexp.MustCompile(`got invalid_value`), }, { - Config: testAccFileSystemWithLifecyclePolicyConfig( + Config: testAccFileSystemConfig_lifecyclePolicy( "transition_to_ia", efs.TransitionToIARulesAfter30Days, ), @@ -323,7 +323,7 @@ func TestAccEFSFileSystem_lifecyclePolicy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFileSystemWithLifecyclePolicyConfig( + Config: testAccFileSystemConfig_lifecyclePolicy( "transition_to_primary_storage_class", efs.TransitionToPrimaryStorageClassRulesAfter1Access, ), @@ -334,14 +334,14 @@ func TestAccEFSFileSystem_lifecyclePolicy(t *testing.T) { ), }, { - Config: testAccFileSystemRemovedLifecyclePolicyConfig, + Config: testAccFileSystemConfig_removedLifecyclePolicy, Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), resource.TestCheckResourceAttr(resourceName, "lifecycle_policy.#", "0"), ), }, { - Config: testAccFileSystemWithLifecyclePolicyMultiConfig( + Config: testAccFileSystemConfig_lifecyclePolicyMulti( "transition_to_primary_storage_class", efs.TransitionToPrimaryStorageClassRulesAfter1Access, "transition_to_ia", @@ -370,7 +370,7 @@ func TestAccEFSFileSystem_disappears(t *testing.T) { CheckDestroy: testAccCheckFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemConfig(rName), + Config: testAccFileSystemConfig_dataSourceBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystem(resourceName, &desc), acctest.CheckResourceDisappears(acctest.Provider, tfefs.ResourceFileSystem(), resourceName), @@ -430,7 +430,7 @@ func testAccCheckFileSystem(resourceID string, fDesc *efs.FileSystemDescription) } } -func testAccFileSystemConfig(rName string) string { +func testAccFileSystemConfig_dataSourceBasic(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %q @@ -438,7 +438,7 @@ resource "aws_efs_file_system" "test" { `, rName) } -func testAccFileSystemAvailabilityZoneNameConfig(rName string) string { +func testAccFileSystemConfig_availabilityZoneName(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -456,7 +456,7 @@ resource "aws_efs_file_system" "test" { `, rName) } -func testAccFileSystemTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccFileSystemConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -467,7 +467,7 @@ resource "aws_efs_file_system" "test" { `, rName, tagKey1, tagValue1) } -func testAccFileSystemTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccFileSystemConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { creation_token = %[1]q @@ -479,7 +479,7 @@ resource "aws_efs_file_system" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccFileSystemPagedTagsConfig(rInt int) string { +func testAccFileSystemConfig_pagedTags(rInt int) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { tags = { @@ -498,7 +498,7 @@ resource "aws_efs_file_system" "test" { `, rInt) } -func testAccFileSystemWithMaxTagsConfig(rName string) string { +func testAccFileSystemConfig_maxTags(rName string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { tags = { @@ -557,14 +557,14 @@ resource "aws_efs_file_system" "test" { `, rName) } -const testAccFileSystemWithPerformanceModeConfig = ` +const testAccFileSystemConfig_performanceMode = ` resource "aws_efs_file_system" "test2" { creation_token = "supercalifragilisticexpialidocious" performance_mode = "maxIO" } ` -func testAccFileSystemWithKMSKeyConfig(rInt int, enable bool) string { +func testAccFileSystemConfig_kmsKey(rInt int, enable bool) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Terraform acc test %[1]d" @@ -577,7 +577,7 @@ resource "aws_efs_file_system" "test" { `, rInt, enable) } -func testAccFileSystemConfig_ThroughputMode(throughputMode string) string { +func testAccFileSystemConfig_throughputMode(throughputMode string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { throughput_mode = %q @@ -585,7 +585,7 @@ resource "aws_efs_file_system" "test" { `, throughputMode) } -func testAccFileSystemConfig_ProvisionedThroughputInMibps(provisionedThroughputInMibps float64) string { +func testAccFileSystemConfig_provisionedThroughputInMibps(provisionedThroughputInMibps float64) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { provisioned_throughput_in_mibps = %f @@ -594,7 +594,7 @@ resource "aws_efs_file_system" "test" { `, provisionedThroughputInMibps) } -func testAccFileSystemWithLifecyclePolicyConfig(lpName, lpVal string) string { +func testAccFileSystemConfig_lifecyclePolicy(lpName, lpVal string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { lifecycle_policy { @@ -604,7 +604,7 @@ resource "aws_efs_file_system" "test" { `, lpName, lpVal) } -func testAccFileSystemWithLifecyclePolicyMultiConfig(lpName1, lpVal1, lpName2, lpVal2 string) string { +func testAccFileSystemConfig_lifecyclePolicyMulti(lpName1, lpVal1, lpName2, lpVal2 string) string { return fmt.Sprintf(` resource "aws_efs_file_system" "test" { lifecycle_policy { @@ -618,6 +618,6 @@ resource "aws_efs_file_system" "test" { `, lpName1, lpVal1, lpName2, lpVal2) } -const testAccFileSystemRemovedLifecyclePolicyConfig = ` +const testAccFileSystemConfig_removedLifecyclePolicy = ` resource "aws_efs_file_system" "test" {} ` diff --git a/internal/service/efs/find.go b/internal/service/efs/find.go index 4b3ddd8dddc..86a46612665 100644 --- a/internal/service/efs/find.go +++ b/internal/service/efs/find.go @@ -82,3 +82,32 @@ func FindFileSystemPolicyByID(conn *efs.EFS, id string) (*efs.DescribeFileSystem return output, nil } + +func FindReplicationConfigurationByID(conn *efs.EFS, id string) (*efs.ReplicationConfigurationDescription, error) { + input := &efs.DescribeReplicationConfigurationsInput{ + FileSystemId: aws.String(id), + } + + output, err := conn.DescribeReplicationConfigurations(input) + + if tfawserr.ErrCodeEquals(err, efs.ErrCodeFileSystemNotFound) || tfawserr.ErrCodeEquals(err, efs.ErrCodeReplicationNotFound) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || + len(output.Replications) == 0 || + output.Replications[0] == nil || + len(output.Replications[0].Destinations) == 0 || + output.Replications[0].Destinations[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.Replications[0], nil +} diff --git a/internal/service/efs/mount_target_data_source_test.go b/internal/service/efs/mount_target_data_source_test.go index e36850cd06b..5ebd3125b35 100644 --- a/internal/service/efs/mount_target_data_source_test.go +++ b/internal/service/efs/mount_target_data_source_test.go @@ -21,7 +21,7 @@ func TestAccEFSMountTargetDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccMountTargetByMountTargetIDConfig(rName), + Config: testAccMountTargetDataSourceConfig_byID(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "file_system_arn", resourceName, "file_system_arn"), resource.TestCheckResourceAttrPair(dataSourceName, "file_system_id", resourceName, "file_system_id"), @@ -51,7 +51,7 @@ func TestAccEFSMountTargetDataSource_byAccessPointID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccMountTargetByAccessPointIDConfig(rName), + Config: testAccMountTargetDataSourceConfig_byAccessPointID(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "file_system_arn", resourceName, "file_system_arn"), resource.TestCheckResourceAttrPair(dataSourceName, "file_system_id", resourceName, "file_system_id"), @@ -81,7 +81,7 @@ func TestAccEFSMountTargetDataSource_byFileSystemID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccMountTargetByFileSystemIDConfig(rName), + Config: testAccMountTargetDataSourceConfig_byFileSystemID(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "file_system_arn", resourceName, "file_system_arn"), resource.TestCheckResourceAttrPair(dataSourceName, "file_system_id", resourceName, "file_system_id"), @@ -135,7 +135,7 @@ resource "aws_subnet" "test" { `, rName)) } -func testAccMountTargetByMountTargetIDConfig(rName string) string { +func testAccMountTargetDataSourceConfig_byID(rName string) string { return acctest.ConfigCompose(testAccMountTargetBaseDataSourceConfig(rName), ` data "aws_efs_mount_target" "test" { mount_target_id = aws_efs_mount_target.test.id @@ -143,7 +143,7 @@ data "aws_efs_mount_target" "test" { `) } -func testAccMountTargetByAccessPointIDConfig(rName string) string { +func testAccMountTargetDataSourceConfig_byAccessPointID(rName string) string { return acctest.ConfigCompose(testAccMountTargetBaseDataSourceConfig(rName), ` resource "aws_efs_access_point" "test" { file_system_id = aws_efs_file_system.test.id @@ -155,7 +155,7 @@ data "aws_efs_mount_target" "test" { `) } -func testAccMountTargetByFileSystemIDConfig(rName string) string { +func testAccMountTargetDataSourceConfig_byFileSystemID(rName string) string { return acctest.ConfigCompose(testAccMountTargetBaseDataSourceConfig(rName), ` data "aws_efs_mount_target" "test" { file_system_id = aws_efs_file_system.test.id diff --git a/internal/service/efs/mount_target_test.go b/internal/service/efs/mount_target_test.go index 468013685e5..3e0f43a1fc3 100644 --- a/internal/service/efs/mount_target_test.go +++ b/internal/service/efs/mount_target_test.go @@ -31,7 +31,7 @@ func TestAccEFSMountTarget_basic(t *testing.T) { CheckDestroy: testAccCheckMountTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMountTargetConfig(ct), + Config: testAccMountTargetConfig_basic(ct), Check: resource.ComposeTestCheckFunc( testAccCheckMountTarget(resourceName, &mount), resource.TestCheckResourceAttrSet(resourceName, "availability_zone_id"), @@ -50,7 +50,7 @@ func TestAccEFSMountTarget_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMountTargetModifiedConfig(ct), + Config: testAccMountTargetConfig_modified(ct), Check: resource.ComposeTestCheckFunc( testAccCheckMountTarget(resourceName, &mount), testAccCheckMountTarget(resourceName2, &mount), @@ -71,10 +71,10 @@ func TestAccEFSMountTarget_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, efs.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckVpnGatewayDestroy, + CheckDestroy: testAccCheckVPNGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccMountTargetConfig(ct), + Config: testAccMountTargetConfig_basic(ct), Check: resource.ComposeTestCheckFunc( testAccCheckMountTarget(resourceName, &mount), acctest.CheckResourceDisappears(acctest.Provider, tfefs.ResourceMountTarget(), resourceName), @@ -97,7 +97,7 @@ func TestAccEFSMountTarget_ipAddress(t *testing.T) { CheckDestroy: testAccCheckMountTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMountTargetIPAddressConfig(rName, "10.0.0.100"), + Config: testAccMountTargetConfig_ipAddress(rName, "10.0.0.100"), Check: resource.ComposeTestCheckFunc( testAccCheckMountTarget(resourceName, &mount), resource.TestCheckResourceAttr(resourceName, "ip_address", "10.0.0.100"), @@ -125,7 +125,7 @@ func TestAccEFSMountTarget_IPAddress_emptyString(t *testing.T) { CheckDestroy: testAccCheckMountTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMountTargetIPAddressConfigNullIP(rName), + Config: testAccMountTargetConfig_ipAddressNullIP(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMountTarget(resourceName, &mount), resource.TestMatchResourceAttr(resourceName, "ip_address", regexp.MustCompile(`\d+\.\d+\.\d+\.\d+`)), @@ -219,7 +219,7 @@ func testAccCheckMountTarget(resourceID string, mount *efs.MountTargetDescriptio } } -func testAccMountTargetConfig(ct string) string { +func testAccMountTargetConfig_basic(ct string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -263,7 +263,7 @@ resource "aws_subnet" "test" { `, ct) } -func testAccMountTargetModifiedConfig(ct string) string { +func testAccMountTargetConfig_modified(ct string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -322,7 +322,7 @@ resource "aws_subnet" "test2" { `, ct) } -func testAccMountTargetIPAddressConfig(rName, ipAddress string) string { +func testAccMountTargetConfig_ipAddress(rName, ipAddress string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -365,7 +365,7 @@ resource "aws_efs_mount_target" "test" { `, rName, ipAddress) } -func testAccMountTargetIPAddressConfigNullIP(rName string) string { +func testAccMountTargetConfig_ipAddressNullIP(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -408,7 +408,7 @@ resource "aws_efs_mount_target" "test" { `, rName) } -func testAccCheckVpnGatewayDestroy(s *terraform.State) error { +func testAccCheckVPNGatewayDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn for _, rs := range s.RootModule().Resources { diff --git a/internal/service/efs/replication_configuration.go b/internal/service/efs/replication_configuration.go new file mode 100644 index 00000000000..1ac7d8c8739 --- /dev/null +++ b/internal/service/efs/replication_configuration.go @@ -0,0 +1,281 @@ +package efs + +import ( + "fmt" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/efs" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceReplicationConfiguration() *schema.Resource { + return &schema.Resource{ + Create: resourceReplicationConfigurationCreate, + Read: resourceReplicationConfigurationRead, + Delete: resourceReplicationConfigurationDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(10 * time.Minute), + Delete: schema.DefaultTimeout(20 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "creation_time": { + Type: schema.TypeString, + Computed: true, + }, + "destination": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "availability_zone_name": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + AtLeastOneOf: []string{"destination.0.availability_zone_name", "destination.0.region"}, + }, + "file_system_id": { + Type: schema.TypeString, + Computed: true, + }, + "kms_key_id": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "region": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: verify.ValidRegionName, + AtLeastOneOf: []string{"destination.0.availability_zone_name", "destination.0.region"}, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "original_source_file_system_arn": { + Type: schema.TypeString, + Computed: true, + }, + "source_file_system_arn": { + Type: schema.TypeString, + Computed: true, + }, + "source_file_system_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "source_file_system_region": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceReplicationConfigurationCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).EFSConn + + fsID := d.Get("source_file_system_id").(string) + input := &efs.CreateReplicationConfigurationInput{ + SourceFileSystemId: aws.String(fsID), + } + + if v, ok := d.GetOk("destination"); ok && len(v.([]interface{})) > 0 { + input.Destinations = expandDestinationsToCreate(v.([]interface{})) + } + + _, err := conn.CreateReplicationConfiguration(input) + + if err != nil { + return fmt.Errorf("creating EFS Replication Configuration (%s): %w", fsID, err) + } + + d.SetId(fsID) + + if _, err := waitReplicationConfigurationCreated(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return fmt.Errorf("waiting for EFS Replication Configuration (%s) create: %w", d.Id(), err) + } + + return resourceReplicationConfigurationRead(d, meta) +} + +func resourceReplicationConfigurationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).EFSConn + + replication, err := FindReplicationConfigurationByID(conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] EFS Replication Configuration (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("reading EFS Replication Configuration (%s): %w", d.Id(), err) + } + + destinations := flattenDestinations(replication.Destinations) + + // availability_zone_name and kms_key_id aren't returned from the AWS Read API. + if v, ok := d.GetOk("destination"); ok && len(v.([]interface{})) > 0 { + copy := func(i int, k string) { + destinations[i].(map[string]interface{})[k] = v.([]interface{})[i].(map[string]interface{})[k] + } + // Assume 1 destination. + copy(0, "availability_zone_name") + copy(0, "kms_key_id") + } + + d.Set("creation_time", aws.TimeValue(replication.CreationTime).String()) + if err := d.Set("destination", destinations); err != nil { + return fmt.Errorf("setting destination: %w", err) + } + d.Set("original_source_file_system_arn", replication.OriginalSourceFileSystemArn) + d.Set("source_file_system_arn", replication.SourceFileSystemArn) + d.Set("source_file_system_id", replication.SourceFileSystemId) + d.Set("source_file_system_region", replication.SourceFileSystemRegion) + + return nil +} + +func resourceReplicationConfigurationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).EFSConn + + // Deletion of the replication configuration must be done from the + // Region in which the destination file system is located. + destination := expandDestinationsToCreate(d.Get("destination").([]interface{}))[0] + session, err := conns.NewSessionForRegion(&conn.Config, aws.StringValue(destination.Region), meta.(*conns.AWSClient).TerraformVersion) + + if err != nil { + return fmt.Errorf("creating AWS session: %w", err) + } + + deleteConn := efs.New(session) + + log.Printf("[DEBUG] Deleting EFS Replication Configuration: %s", d.Id()) + _, err = deleteConn.DeleteReplicationConfiguration(&efs.DeleteReplicationConfigurationInput{ + SourceFileSystemId: aws.String(d.Id()), + }) + + if tfawserr.ErrCodeEquals(err, efs.ErrCodeFileSystemNotFound, efs.ErrCodeReplicationNotFound) { + return nil + } + + if err != nil { + return fmt.Errorf("deleting EFS Replication Configuration (%s): %w", d.Id(), err) + } + + if _, err := waitReplicationConfigurationDeleted(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return fmt.Errorf("waiting for EFS Replication Configuration (%s) delete: %w", d.Id(), err) + } + + return nil +} + +func expandDestinationToCreate(tfMap map[string]interface{}) *efs.DestinationToCreate { + if tfMap == nil { + return nil + } + + apiObject := &efs.DestinationToCreate{} + + if v, ok := tfMap["availability_zone_name"].(string); ok && v != "" { + apiObject.AvailabilityZoneName = aws.String(v) + } + + if v, ok := tfMap["kms_key_id"].(string); ok && v != "" { + apiObject.KmsKeyId = aws.String(v) + } + + if v, ok := tfMap["region"].(string); ok && v != "" { + apiObject.Region = aws.String(v) + } + + return apiObject +} + +func expandDestinationsToCreate(tfList []interface{}) []*efs.DestinationToCreate { + if len(tfList) == 0 { + return nil + } + + var apiObjects []*efs.DestinationToCreate + + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]interface{}) + + if !ok { + continue + } + + apiObject := expandDestinationToCreate(tfMap) + + if apiObject == nil { + continue + } + + apiObjects = append(apiObjects, apiObject) + } + + return apiObjects +} + +func flattenDestination(apiObject *efs.Destination) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.FileSystemId; v != nil { + tfMap["file_system_id"] = aws.StringValue(v) + } + + if v := apiObject.Region; v != nil { + tfMap["region"] = aws.StringValue(v) + } + + if v := apiObject.Status; v != nil { + tfMap["status"] = aws.StringValue(v) + } + + return tfMap +} + +func flattenDestinations(apiObjects []*efs.Destination) []interface{} { + if len(apiObjects) == 0 { + return nil + } + + var tfList []interface{} + + for _, apiObject := range apiObjects { + if apiObject == nil { + continue + } + + tfList = append(tfList, flattenDestination(apiObject)) + } + + return tfList +} diff --git a/internal/service/efs/replication_configuration_test.go b/internal/service/efs/replication_configuration_test.go new file mode 100644 index 00000000000..0f523e869b2 --- /dev/null +++ b/internal/service/efs/replication_configuration_test.go @@ -0,0 +1,215 @@ +package efs_test + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/efs" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfefs "github.com/hashicorp/terraform-provider-aws/internal/service/efs" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccEFSReplicationConfiguration_basic(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + resourceName := "aws_efs_replication_configuration.test" + fsResourceName := "aws_efs_file_system.test" + region := acctest.Region() + var providers []*schema.Provider + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, efs.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: acctest.CheckWithProviders(testAccCheckReplicationConfigurationDestroy, &providers), + Steps: []resource.TestStep{ + { + Config: testAccReplicationConfigurationConfig_basic(region), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckReplicationConfigurationExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "creation_time"), + resource.TestCheckResourceAttr(resourceName, "destination.#", "1"), + resource.TestMatchResourceAttr(resourceName, "destination.0.file_system_id", regexp.MustCompile(`fs-.+`)), + resource.TestCheckResourceAttr(resourceName, "destination.0.region", region), + resource.TestCheckResourceAttr(resourceName, "destination.0.status", efs.ReplicationStatusEnabled), + resource.TestCheckResourceAttrPair(resourceName, "original_source_file_system_arn", fsResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "source_file_system_arn", fsResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "source_file_system_id", fsResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "source_file_system_region", region), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccEFSReplicationConfiguration_disappears(t *testing.T) { + resourceName := "aws_efs_replication_configuration.test" + region := acctest.Region() + var providers []*schema.Provider + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckMultipleRegion(t, 2) + }, + ErrorCheck: acctest.ErrorCheck(t, efs.EndpointsID), + ProviderFactories: acctest.FactoriesAlternate(&providers), + CheckDestroy: acctest.CheckWithProviders(testAccCheckReplicationConfigurationDestroy, &providers), + Steps: []resource.TestStep{ + { + Config: testAccReplicationConfigurationConfig_basic(region), + Check: resource.ComposeTestCheckFunc( + testAccCheckReplicationConfigurationExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfefs.ResourceReplicationConfiguration(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccEFSReplicationConfiguration_allAttributes(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + resourceName := "aws_efs_replication_configuration.test" + fsResourceName := "aws_efs_file_system.test" + kmsKeyResourceName := "aws_kms_key.test" + alternateRegion := acctest.AlternateRegion() + var providers []*schema.Provider + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckMultipleRegion(t, 2) + }, + ErrorCheck: acctest.ErrorCheck(t, efs.EndpointsID), + ProviderFactories: acctest.FactoriesAlternate(&providers), + CheckDestroy: acctest.CheckWithProviders(testAccCheckReplicationConfigurationDestroy, &providers), + Steps: []resource.TestStep{ + { + Config: testAccReplicationConfigurationConfig_full(alternateRegion), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckReplicationConfigurationExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "creation_time"), + resource.TestCheckResourceAttr(resourceName, "destination.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "destination.0.availability_zone_name", "data.aws_availability_zones.available", "names.0"), + resource.TestMatchResourceAttr(resourceName, "destination.0.file_system_id", regexp.MustCompile(`fs-.+`)), + resource.TestCheckResourceAttrPair(resourceName, "destination.0.kms_key_id", kmsKeyResourceName, "key_id"), + resource.TestCheckResourceAttr(resourceName, "destination.0.region", alternateRegion), + resource.TestCheckResourceAttr(resourceName, "destination.0.status", efs.ReplicationStatusEnabled), + resource.TestCheckResourceAttrPair(resourceName, "original_source_file_system_arn", fsResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "source_file_system_arn", fsResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "source_file_system_id", fsResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "source_file_system_region", acctest.Region()), + ), + }, + }, + }) +} + +func testAccCheckReplicationConfigurationExists(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No EFS Replication Configuration ID is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).EFSConn + + _, err := tfefs.FindReplicationConfigurationByID(conn, rs.Primary.ID) + + if err != nil { + return err + } + + return nil + } +} + +func testAccCheckReplicationConfigurationDestroy(s *terraform.State, provider *schema.Provider) error { + conn := provider.Meta().(*conns.AWSClient).EFSConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_efs_replication_configuration" { + continue + } + + _, err := tfefs.FindReplicationConfigurationByID(conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("EFS Replication Configuration %s still exists", rs.Primary.ID) + } + + return nil +} + +func testAccReplicationConfigurationConfig_basic(region string) string { + return fmt.Sprintf(` +resource "aws_efs_file_system" "test" {} + +resource "aws_efs_replication_configuration" "test" { + source_file_system_id = aws_efs_file_system.test.id + + destination { + region = %[1]q + } +} +`, region) +} + +func testAccReplicationConfigurationConfig_full(region string) string { + return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` +resource "aws_kms_key" "test" { + provider = "awsalternate" +} + +data "aws_availability_zones" "available" { + provider = "awsalternate" + + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_efs_file_system" "test" {} + +resource "aws_efs_replication_configuration" "test" { + source_file_system_id = aws_efs_file_system.test.id + + destination { + availability_zone_name = data.aws_availability_zones.available.names[0] + kms_key_id = aws_kms_key.test.key_id + region = %[1]q + } +} +`, region)) +} diff --git a/internal/service/efs/status.go b/internal/service/efs/status.go index f62f5167deb..dc3cef469cb 100644 --- a/internal/service/efs/status.go +++ b/internal/service/efs/status.go @@ -61,3 +61,19 @@ func statusFileSystemLifeCycleState(conn *efs.EFS, id string) resource.StateRefr return output, aws.StringValue(output.LifeCycleState), nil } } + +func statusReplicationConfiguration(conn *efs.EFS, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindReplicationConfigurationByID(conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.StringValue(output.Destinations[0].Status), nil + } +} diff --git a/internal/service/efs/wait.go b/internal/service/efs/wait.go index 2f75cf5189e..367ca4d104b 100644 --- a/internal/service/efs/wait.go +++ b/internal/service/efs/wait.go @@ -129,3 +129,38 @@ func waitBackupPolicyEnabled(conn *efs.EFS, id string) (*efs.BackupPolicy, error return nil, err } + +func waitReplicationConfigurationCreated(conn *efs.EFS, id string, timeout time.Duration) (*efs.ReplicationConfigurationDescription, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{efs.ReplicationStatusEnabling}, + Target: []string{efs.ReplicationStatusEnabled}, + Refresh: statusReplicationConfiguration(conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*efs.ReplicationConfigurationDescription); ok { + return output, err + } + + return nil, err +} + +func waitReplicationConfigurationDeleted(conn *efs.EFS, id string, timeout time.Duration) (*efs.ReplicationConfigurationDescription, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{efs.ReplicationStatusDeleting}, + Target: []string{}, + Refresh: statusReplicationConfiguration(conn, id), + Timeout: timeout, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*efs.ReplicationConfigurationDescription); ok { + return output, err + } + + return nil, err +} diff --git a/internal/service/eks/addon_data_source_test.go b/internal/service/eks/addon_data_source_test.go index 94728297cb2..69ca9984002 100644 --- a/internal/service/eks/addon_data_source_test.go +++ b/internal/service/eks/addon_data_source_test.go @@ -27,7 +27,7 @@ func TestAccEKSAddonDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonDataSourceConfig(rName, addonName), + Config: testAccAddonDataSourceConfig_basic(rName, addonName), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, dataSourceResourceName, &addon), acctest.MatchResourceAttrRegionalARN(dataSourceResourceName, "arn", "eks", regexp.MustCompile(fmt.Sprintf("addon/%s/%s/.+$", rName, addonName))), @@ -43,7 +43,7 @@ func TestAccEKSAddonDataSource_basic(t *testing.T) { }) } -func testAccAddonDataSourceConfig(rName, addonName string) string { +func testAccAddonDataSourceConfig_basic(rName, addonName string) string { return acctest.ConfigCompose(testAccAddonBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_addon" "test" { addon_name = %[2]q diff --git a/internal/service/eks/addon_test.go b/internal/service/eks/addon_test.go index 42a5fa88555..012ff3669d1 100644 --- a/internal/service/eks/addon_test.go +++ b/internal/service/eks/addon_test.go @@ -33,7 +33,7 @@ func TestAccEKSAddon_basic(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonConfig(rName, addonName), + Config: testAccAddonConfig_basic(rName, addonName), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, addonResourceName, &addon), resource.TestCheckResourceAttr(addonResourceName, "addon_name", addonName), @@ -67,7 +67,7 @@ func TestAccEKSAddon_disappears(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonConfig(rName, addonName), + Config: testAccAddonConfig_basic(rName, addonName), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), acctest.CheckResourceDisappears(acctest.Provider, tfeks.ResourceAddon(), resourceName), @@ -93,7 +93,7 @@ func TestAccEKSAddon_Disappears_cluster(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonConfig(rName, addonName), + Config: testAccAddonConfig_basic(rName, addonName), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), acctest.CheckResourceDisappears(acctest.Provider, tfeks.ResourceCluster(), clusterResourceName), @@ -120,7 +120,7 @@ func TestAccEKSAddon_addonVersion(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonAddonVersionConfig(rName, addonName, addonVersion1), + Config: testAccAddonConfig_version(rName, addonName, addonVersion1), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon1), resource.TestCheckResourceAttr(resourceName, "addon_version", addonVersion1), @@ -133,7 +133,7 @@ func TestAccEKSAddon_addonVersion(t *testing.T) { ImportStateVerifyIgnore: []string{"resolve_conflicts"}, }, { - Config: testAccAddonAddonVersionConfig(rName, addonName, addonVersion2), + Config: testAccAddonConfig_version(rName, addonName, addonVersion2), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon2), resource.TestCheckResourceAttr(resourceName, "addon_version", addonVersion2), @@ -157,7 +157,7 @@ func TestAccEKSAddon_preserve(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonPreserveConfig(rName, addonName), + Config: testAccAddonConfig_preserve(rName, addonName), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), resource.TestCheckResourceAttr(resourceName, "preserve", "true"), @@ -187,7 +187,7 @@ func TestAccEKSAddon_resolveConflicts(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonResolveConflictsConfig(rName, addonName, eks.ResolveConflictsNone), + Config: testAccAddonConfig_resolveConflicts(rName, addonName, eks.ResolveConflictsNone), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon1), resource.TestCheckResourceAttr(resourceName, "resolve_conflicts", eks.ResolveConflictsNone), @@ -200,7 +200,7 @@ func TestAccEKSAddon_resolveConflicts(t *testing.T) { ImportStateVerifyIgnore: []string{"resolve_conflicts"}, }, { - Config: testAccAddonResolveConflictsConfig(rName, addonName, eks.ResolveConflictsOverwrite), + Config: testAccAddonConfig_resolveConflicts(rName, addonName, eks.ResolveConflictsOverwrite), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon2), resource.TestCheckResourceAttr(resourceName, "resolve_conflicts", eks.ResolveConflictsOverwrite), @@ -225,7 +225,7 @@ func TestAccEKSAddon_serviceAccountRoleARN(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonServiceAccountRoleARNConfig(rName, addonName), + Config: testAccAddonConfig_serviceAccountRoleARN(rName, addonName), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), resource.TestCheckResourceAttrPair(resourceName, "service_account_role_arn", serviceRoleResourceName, "arn"), @@ -254,7 +254,7 @@ func TestAccEKSAddon_tags(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonConfigTags1(rName, addonName, "key1", "value1"), + Config: testAccAddonConfig_tags1(rName, addonName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -267,7 +267,7 @@ func TestAccEKSAddon_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAddonConfigTags2(rName, addonName, "key1", "value1updated", "key2", "value2"), + Config: testAccAddonConfig_tags2(rName, addonName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -276,7 +276,7 @@ func TestAccEKSAddon_tags(t *testing.T) { ), }, { - Config: testAccAddonConfigTags1(rName, addonName, "key2", "value2"), + Config: testAccAddonConfig_tags1(rName, addonName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -305,7 +305,7 @@ func TestAccEKSAddon_DefaultTags_providerOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "providervalue1"), - testAccAddonConfig(rName, addonName), + testAccAddonConfig_basic(rName, addonName), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -322,7 +322,7 @@ func TestAccEKSAddon_DefaultTags_providerOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags2("providerkey1", "providervalue1", "providerkey2", "providervalue2"), - testAccAddonConfig(rName, addonName), + testAccAddonConfig_basic(rName, addonName), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -335,7 +335,7 @@ func TestAccEKSAddon_DefaultTags_providerOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "value1"), - testAccAddonConfig(rName, addonName), + testAccAddonConfig_basic(rName, addonName), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -364,7 +364,7 @@ func TestAccEKSAddon_DefaultTags_updateToProviderOnly(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonConfigTags1(rName, addonName, "key1", "value1"), + Config: testAccAddonConfig_tags1(rName, addonName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -376,7 +376,7 @@ func TestAccEKSAddon_DefaultTags_updateToProviderOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("key1", "value1"), - testAccAddonConfig(rName, addonName), + testAccAddonConfig_basic(rName, addonName), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -412,7 +412,7 @@ func TestAccEKSAddon_DefaultTags_updateToResourceOnly(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("key1", "value1"), - testAccAddonConfig(rName, addonName), + testAccAddonConfig_basic(rName, addonName), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -422,7 +422,7 @@ func TestAccEKSAddon_DefaultTags_updateToResourceOnly(t *testing.T) { ), }, { - Config: testAccAddonConfigTags1(rName, addonName, "key1", "value1"), + Config: testAccAddonConfig_tags1(rName, addonName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -458,7 +458,7 @@ func TestAccEKSAddon_DefaultTagsProviderAndResource_nonOverlappingTag(t *testing { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "providervalue1"), - testAccAddonConfigTags1(rName, addonName, "resourcekey1", "resourcevalue1"), + testAccAddonConfig_tags1(rName, addonName, "resourcekey1", "resourcevalue1"), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -477,7 +477,7 @@ func TestAccEKSAddon_DefaultTagsProviderAndResource_nonOverlappingTag(t *testing { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey1", "providervalue1"), - testAccAddonConfigTags2(rName, addonName, "resourcekey1", "resourcevalue1", "resourcekey2", "resourcevalue2"), + testAccAddonConfig_tags2(rName, addonName, "resourcekey1", "resourcevalue1", "resourcekey2", "resourcevalue2"), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -493,7 +493,7 @@ func TestAccEKSAddon_DefaultTagsProviderAndResource_nonOverlappingTag(t *testing { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("providerkey2", "providervalue2"), - testAccAddonConfigTags1(rName, addonName, "resourcekey3", "resourcevalue3"), + testAccAddonConfig_tags1(rName, addonName, "resourcekey3", "resourcevalue3"), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -526,7 +526,7 @@ func TestAccEKSAddon_DefaultTagsProviderAndResource_overlappingTag(t *testing.T) { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("overlapkey1", "providervalue1"), - testAccAddonConfigTags1(rName, addonName, "overlapkey1", "resourcevalue1"), + testAccAddonConfig_tags1(rName, addonName, "overlapkey1", "resourcevalue1"), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -543,7 +543,7 @@ func TestAccEKSAddon_DefaultTagsProviderAndResource_overlappingTag(t *testing.T) { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags2("overlapkey1", "providervalue1", "overlapkey2", "providervalue2"), - testAccAddonConfigTags2(rName, addonName, "overlapkey1", "resourcevalue1", "overlapkey2", "resourcevalue2"), + testAccAddonConfig_tags2(rName, addonName, "overlapkey1", "resourcevalue1", "overlapkey2", "resourcevalue2"), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -558,7 +558,7 @@ func TestAccEKSAddon_DefaultTagsProviderAndResource_overlappingTag(t *testing.T) { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("overlapkey1", "providervalue1"), - testAccAddonConfigTags1(rName, addonName, "overlapkey1", "resourcevalue2"), + testAccAddonConfig_tags1(rName, addonName, "overlapkey1", "resourcevalue2"), ), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), @@ -587,7 +587,7 @@ func TestAccEKSAddon_DefaultTagsProviderAndResource_duplicateTag(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("overlapkey", "overlapvalue"), - testAccAddonConfigTags1(rName, addonName, "overlapkey", "overlapvalue"), + testAccAddonConfig_tags1(rName, addonName, "overlapkey", "overlapvalue"), ), PlanOnly: true, ExpectError: regexp.MustCompile(`"tags" are identical to those in the "default_tags" configuration block`), @@ -612,7 +612,7 @@ func TestAccEKSAddon_defaultAndIgnoreTags(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonConfigTags1(rName, addonName, "key1", "value1"), + Config: testAccAddonConfig_tags1(rName, addonName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), testAccCheckAddonUpdateTags(&addon, nil, map[string]string{"defaultkey1": "defaultvalue1"}), @@ -622,14 +622,14 @@ func TestAccEKSAddon_defaultAndIgnoreTags(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultAndIgnoreTagsKeyPrefixes1("defaultkey1", "defaultvalue1", "defaultkey"), - testAccAddonConfigTags1(rName, addonName, "key1", "value1"), + testAccAddonConfig_tags1(rName, addonName, "key1", "value1"), ), PlanOnly: true, }, { Config: acctest.ConfigCompose( acctest.ConfigDefaultAndIgnoreTagsKeys1("defaultkey1", "defaultvalue1"), - testAccAddonConfigTags1(rName, addonName, "key1", "value1"), + testAccAddonConfig_tags1(rName, addonName, "key1", "value1"), ), PlanOnly: true, }, @@ -653,7 +653,7 @@ func TestAccEKSAddon_ignoreTags(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonConfigTags1(rName, addonName, "key1", "value1"), + Config: testAccAddonConfig_tags1(rName, addonName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, resourceName, &addon), testAccCheckAddonUpdateTags(&addon, nil, map[string]string{"ignorekey1": "ignorevalue1"}), @@ -663,14 +663,14 @@ func TestAccEKSAddon_ignoreTags(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey"), - testAccAddonConfigTags1(rName, addonName, "key1", "value1"), + testAccAddonConfig_tags1(rName, addonName, "key1", "value1"), ), PlanOnly: true, }, { Config: acctest.ConfigCompose( acctest.ConfigIgnoreTagsKeys("ignorekey1"), - testAccAddonConfigTags1(rName, addonName, "key1", "value1"), + testAccAddonConfig_tags1(rName, addonName, "key1", "value1"), ), PlanOnly: true, }, @@ -827,7 +827,7 @@ resource "aws_eks_cluster" "test" { `, rName)) } -func testAccAddonConfig(rName, addonName string) string { +func testAccAddonConfig_basic(rName, addonName string) string { return acctest.ConfigCompose(testAccAddonBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_addon" "test" { cluster_name = aws_eks_cluster.test.name @@ -836,7 +836,7 @@ resource "aws_eks_addon" "test" { `, rName, addonName)) } -func testAccAddonAddonVersionConfig(rName, addonName, addonVersion string) string { +func testAccAddonConfig_version(rName, addonName, addonVersion string) string { return acctest.ConfigCompose(testAccAddonBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_addon" "test" { cluster_name = aws_eks_cluster.test.name @@ -847,7 +847,7 @@ resource "aws_eks_addon" "test" { `, rName, addonName, addonVersion)) } -func testAccAddonPreserveConfig(rName, addonName string) string { +func testAccAddonConfig_preserve(rName, addonName string) string { return acctest.ConfigCompose(testAccAddonBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_addon" "test" { cluster_name = aws_eks_cluster.test.name @@ -857,7 +857,7 @@ resource "aws_eks_addon" "test" { `, rName, addonName)) } -func testAccAddonResolveConflictsConfig(rName, addonName, resolveConflicts string) string { +func testAccAddonConfig_resolveConflicts(rName, addonName, resolveConflicts string) string { return acctest.ConfigCompose(testAccAddonBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_addon" "test" { cluster_name = aws_eks_cluster.test.name @@ -867,7 +867,7 @@ resource "aws_eks_addon" "test" { `, rName, addonName, resolveConflicts)) } -func testAccAddonServiceAccountRoleARNConfig(rName, addonName string) string { +func testAccAddonConfig_serviceAccountRoleARN(rName, addonName string) string { return acctest.ConfigCompose(testAccAddonBaseConfig(rName), fmt.Sprintf(` resource "aws_iam_role" "test-service-role" { name = "test-service-role" @@ -896,7 +896,7 @@ resource "aws_eks_addon" "test" { `, rName, addonName)) } -func testAccAddonConfigTags1(rName, addonName, tagKey1, tagValue1 string) string { +func testAccAddonConfig_tags1(rName, addonName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccAddonBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_addon" "test" { cluster_name = aws_eks_cluster.test.name @@ -909,7 +909,7 @@ resource "aws_eks_addon" "test" { `, rName, addonName, tagKey1, tagValue1)) } -func testAccAddonConfigTags2(rName, addonName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAddonConfig_tags2(rName, addonName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccAddonBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_addon" "test" { cluster_name = aws_eks_cluster.test.name diff --git a/internal/service/eks/addon_version_data_source_test.go b/internal/service/eks/addon_version_data_source_test.go index 1ce95a5c9fd..6c771e5e0b7 100644 --- a/internal/service/eks/addon_version_data_source_test.go +++ b/internal/service/eks/addon_version_data_source_test.go @@ -26,7 +26,7 @@ func TestAccEKSAddonVersionDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckAddonDestroy, Steps: []resource.TestStep{ { - Config: testAccAddonVersionDataSourceConfig_Basic(rName, addonName, true), + Config: testAccAddonVersionDataSourceConfig_basic(rName, addonName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, addonDataSourceName, &addon), resource.TestCheckResourceAttrPair(versionDataSourceName, "version", addonDataSourceName, "addon_version"), @@ -35,7 +35,7 @@ func TestAccEKSAddonVersionDataSource_basic(t *testing.T) { ), }, { - Config: testAccAddonVersionDataSourceConfig_Basic(rName, addonName, false), + Config: testAccAddonVersionDataSourceConfig_basic(rName, addonName, false), Check: resource.ComposeTestCheckFunc( testAccCheckAddonExists(ctx, addonDataSourceName, &addon), resource.TestCheckResourceAttrPair(versionDataSourceName, "version", addonDataSourceName, "addon_version"), @@ -47,7 +47,7 @@ func TestAccEKSAddonVersionDataSource_basic(t *testing.T) { }) } -func testAccAddonVersionDataSourceConfig_Basic(rName, addonName string, mostRecent bool) string { +func testAccAddonVersionDataSourceConfig_basic(rName, addonName string, mostRecent bool) string { return acctest.ConfigCompose(testAccAddonBaseConfig(rName), fmt.Sprintf(` data "aws_eks_addon_version" "test" { addon_name = %[2]q diff --git a/internal/service/eks/cluster_data_source_test.go b/internal/service/eks/cluster_data_source_test.go index 4c005d0037e..c60549ea332 100644 --- a/internal/service/eks/cluster_data_source_test.go +++ b/internal/service/eks/cluster_data_source_test.go @@ -22,7 +22,7 @@ func TestAccEKSClusterDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterDataSourceConfig_Basic(rName), + Config: testAccClusterDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceResourceName, "arn"), resource.TestCheckResourceAttr(dataSourceResourceName, "certificate_authority.#", "1"), @@ -57,8 +57,8 @@ func TestAccEKSClusterDataSource_basic(t *testing.T) { }) } -func testAccClusterDataSourceConfig_Basic(rName string) string { - return acctest.ConfigCompose(testAccClusterConfig_Logging(rName, []string{"api", "audit"}), ` +func testAccClusterDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccClusterConfig_logging(rName, []string{"api", "audit"}), ` data "aws_eks_cluster" "test" { name = aws_eks_cluster.test.name } diff --git a/internal/service/eks/cluster_test.go b/internal/service/eks/cluster_test.go index df9741a6afd..d048e0d6016 100644 --- a/internal/service/eks/cluster_test.go +++ b/internal/service/eks/cluster_test.go @@ -30,7 +30,7 @@ func TestAccEKSCluster_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Required(rName), + Config: testAccClusterConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "eks", regexp.MustCompile(fmt.Sprintf("cluster/%s$", rName))), @@ -78,7 +78,7 @@ func TestAccEKSCluster_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Required(rName), + Config: testAccClusterConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), acctest.CheckResourceDisappears(acctest.Provider, tfeks.ResourceCluster(), resourceName), @@ -102,7 +102,7 @@ func TestAccEKSCluster_Encryption_create(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EncryptionConfig(rName), + Config: testAccClusterConfig_encryption(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "encryption_config.#", "1"), @@ -133,14 +133,14 @@ func TestAccEKSCluster_Encryption_update(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Required(rName), + Config: testAccClusterConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "encryption_config.#", "0"), ), }, { - Config: testAccClusterConfig_EncryptionConfig(rName), + Config: testAccClusterConfig_encryption(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -173,7 +173,7 @@ func TestAccEKSCluster_Encryption_versionUpdate(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EncryptionConfig_Version(rName, "1.19"), + Config: testAccClusterConfig_encryptionVersion(rName, "1.19"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "encryption_config.#", "1"), @@ -189,7 +189,7 @@ func TestAccEKSCluster_Encryption_versionUpdate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_EncryptionConfig_Version(rName, "1.20"), + Config: testAccClusterConfig_encryptionVersion(rName, "1.20"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -216,7 +216,7 @@ func TestAccEKSCluster_version(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Version(rName, "1.19"), + Config: testAccClusterConfig_version(rName, "1.19"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "version", "1.19"), @@ -228,7 +228,7 @@ func TestAccEKSCluster_version(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_Version(rName, "1.20"), + Config: testAccClusterConfig_version(rName, "1.20"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -251,7 +251,7 @@ func TestAccEKSCluster_logging(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Logging(rName, []string{"api"}), + Config: testAccClusterConfig_logging(rName, []string{"api"}), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "enabled_cluster_log_types.#", "1"), @@ -264,7 +264,7 @@ func TestAccEKSCluster_logging(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_Logging(rName, []string{"api", "audit"}), + Config: testAccClusterConfig_logging(rName, []string{"api", "audit"}), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -275,7 +275,7 @@ func TestAccEKSCluster_logging(t *testing.T) { }, // Disable all log types. { - Config: testAccClusterConfig_Required(rName), + Config: testAccClusterConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -298,7 +298,7 @@ func TestAccEKSCluster_tags(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterTags1Config(rName, "key1", "value1"), + Config: testAccClusterConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -311,7 +311,7 @@ func TestAccEKSCluster_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccClusterConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -320,7 +320,7 @@ func TestAccEKSCluster_tags(t *testing.T) { ), }, { - Config: testAccClusterTags1Config(rName, "key2", "value2"), + Config: testAccClusterConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -343,7 +343,7 @@ func TestAccEKSCluster_VPC_securityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_VPCConfig_SecurityGroupIDs(rName), + Config: testAccClusterConfig_vpcSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), @@ -371,7 +371,7 @@ func TestAccEKSCluster_VPC_endpointPrivateAccess(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_VPCConfig_EndpointPrivateAccess(rName, true), + Config: testAccClusterConfig_vpcEndpointPrivateAccess(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), @@ -384,7 +384,7 @@ func TestAccEKSCluster_VPC_endpointPrivateAccess(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_VPCConfig_EndpointPrivateAccess(rName, false), + Config: testAccClusterConfig_vpcEndpointPrivateAccess(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -393,7 +393,7 @@ func TestAccEKSCluster_VPC_endpointPrivateAccess(t *testing.T) { ), }, { - Config: testAccClusterConfig_VPCConfig_EndpointPrivateAccess(rName, true), + Config: testAccClusterConfig_vpcEndpointPrivateAccess(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster3), testAccCheckClusterNotRecreated(&cluster2, &cluster3), @@ -417,7 +417,7 @@ func TestAccEKSCluster_VPC_endpointPublicAccess(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_VPCConfig_EndpointPublicAccess(rName, false), + Config: testAccClusterConfig_vpcEndpointPublicAccess(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), @@ -430,7 +430,7 @@ func TestAccEKSCluster_VPC_endpointPublicAccess(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_VPCConfig_EndpointPublicAccess(rName, true), + Config: testAccClusterConfig_vpcEndpointPublicAccess(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -439,7 +439,7 @@ func TestAccEKSCluster_VPC_endpointPublicAccess(t *testing.T) { ), }, { - Config: testAccClusterConfig_VPCConfig_EndpointPublicAccess(rName, false), + Config: testAccClusterConfig_vpcEndpointPublicAccess(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster3), testAccCheckClusterNotRecreated(&cluster2, &cluster3), @@ -463,7 +463,7 @@ func TestAccEKSCluster_VPC_publicAccessCIDRs(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_VPCConfig_PublicAccessCIDRs(rName, `["1.2.3.4/32", "5.6.7.8/32"]`), + Config: testAccClusterConfig_vpcPublicAccessCIDRs(rName, `["1.2.3.4/32", "5.6.7.8/32"]`), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), @@ -476,7 +476,7 @@ func TestAccEKSCluster_VPC_publicAccessCIDRs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_VPCConfig_PublicAccessCIDRs(rName, `["4.3.2.1/32", "8.7.6.5/32"]`), + Config: testAccClusterConfig_vpcPublicAccessCIDRs(rName, `["4.3.2.1/32", "8.7.6.5/32"]`), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), @@ -499,27 +499,27 @@ func TestAccEKSCluster_Network_serviceIPv4CIDR(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_NetworkConfig_ServiceIPv4CIDR(rName, `"10.0.0.0/11"`), + Config: testAccClusterConfig_networkServiceIPv4CIDR(rName, `"10.0.0.0/11"`), ExpectError: regexp.MustCompile(`expected .* to contain a network Value with between`), }, { - Config: testAccClusterConfig_NetworkConfig_ServiceIPv4CIDR(rName, `"10.0.0.0/25"`), + Config: testAccClusterConfig_networkServiceIPv4CIDR(rName, `"10.0.0.0/25"`), ExpectError: regexp.MustCompile(`expected .* to contain a network Value with between`), }, { - Config: testAccClusterConfig_NetworkConfig_ServiceIPv4CIDR(rName, `"9.0.0.0/16"`), + Config: testAccClusterConfig_networkServiceIPv4CIDR(rName, `"9.0.0.0/16"`), ExpectError: regexp.MustCompile(`must be within`), }, { - Config: testAccClusterConfig_NetworkConfig_ServiceIPv4CIDR(rName, `"172.14.0.0/24"`), + Config: testAccClusterConfig_networkServiceIPv4CIDR(rName, `"172.14.0.0/24"`), ExpectError: regexp.MustCompile(`must be within`), }, { - Config: testAccClusterConfig_NetworkConfig_ServiceIPv4CIDR(rName, `"192.167.0.0/24"`), + Config: testAccClusterConfig_networkServiceIPv4CIDR(rName, `"192.167.0.0/24"`), ExpectError: regexp.MustCompile(`must be within`), }, { - Config: testAccClusterConfig_NetworkConfig_ServiceIPv4CIDR(rName, `"192.168.0.0/24"`), + Config: testAccClusterConfig_networkServiceIPv4CIDR(rName, `"192.168.0.0/24"`), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "kubernetes_network_config.#", "1"), @@ -532,12 +532,12 @@ func TestAccEKSCluster_Network_serviceIPv4CIDR(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_NetworkConfig_ServiceIPv4CIDR(rName, `"192.168.0.0/24"`), + Config: testAccClusterConfig_networkServiceIPv4CIDR(rName, `"192.168.0.0/24"`), PlanOnly: true, ExpectNonEmptyPlan: false, }, { - Config: testAccClusterConfig_NetworkConfig_ServiceIPv4CIDR(rName, `"192.168.1.0/24"`), + Config: testAccClusterConfig_networkServiceIPv4CIDR(rName, `"192.168.1.0/24"`), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -561,15 +561,15 @@ func TestAccEKSCluster_Network_ipFamily(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_NetworkConfig_IPFamily(rName, `"v6"`), + Config: testAccClusterConfig_networkIPFamily(rName, `"v6"`), ExpectError: regexp.MustCompile(`expected .* to be one of \[ipv4 ipv6]`), }, { - Config: testAccClusterConfig_NetworkConfig_IPFamily(rName, `"IPv4"`), + Config: testAccClusterConfig_networkIPFamily(rName, `"IPv4"`), ExpectError: regexp.MustCompile(`expected .* to be one of \[ipv4 ipv6]`), }, { - Config: testAccClusterConfig_NetworkConfig_IPFamily(rName, `"ipv6"`), + Config: testAccClusterConfig_networkIPFamily(rName, `"ipv6"`), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "kubernetes_network_config.#", "1"), @@ -582,12 +582,12 @@ func TestAccEKSCluster_Network_ipFamily(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_NetworkConfig_IPFamily(rName, `"ipv6"`), + Config: testAccClusterConfig_networkIPFamily(rName, `"ipv6"`), PlanOnly: true, ExpectNonEmptyPlan: false, }, { - Config: testAccClusterConfig_NetworkConfig_IPFamily(rName, `"ipv4"`), + Config: testAccClusterConfig_networkIPFamily(rName, `"ipv4"`), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -750,7 +750,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccClusterConfig_Required(rName string) string { +func testAccClusterConfig_required(rName string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q @@ -765,7 +765,7 @@ resource "aws_eks_cluster" "test" { `, rName)) } -func testAccClusterConfig_Version(rName, version string) string { +func testAccClusterConfig_version(rName, version string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q @@ -781,7 +781,7 @@ resource "aws_eks_cluster" "test" { `, rName, version)) } -func testAccClusterConfig_Logging(rName string, logTypes []string) string { +func testAccClusterConfig_logging(rName string, logTypes []string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q @@ -797,7 +797,7 @@ resource "aws_eks_cluster" "test" { `, rName, strings.Join(logTypes, "\", \""))) } -func testAccClusterTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccClusterConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q @@ -816,7 +816,7 @@ resource "aws_eks_cluster" "test" { `, rName, tagKey1, tagValue1)) } -func testAccClusterTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccClusterConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q @@ -836,7 +836,7 @@ resource "aws_eks_cluster" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccClusterConfig_EncryptionConfig(rName string) string { +func testAccClusterConfig_encryption(rName string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -864,7 +864,7 @@ resource "aws_eks_cluster" "test" { `, rName)) } -func testAccClusterConfig_EncryptionConfig_Version(rName, version string) string { +func testAccClusterConfig_encryptionVersion(rName, version string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -893,7 +893,7 @@ resource "aws_eks_cluster" "test" { `, rName, version)) } -func testAccClusterConfig_VPCConfig_SecurityGroupIDs(rName string) string { +func testAccClusterConfig_vpcSecurityGroupIDs(rName string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_security_group" "test" { vpc_id = aws_vpc.test.id @@ -917,7 +917,7 @@ resource "aws_eks_cluster" "test" { `, rName)) } -func testAccClusterConfig_VPCConfig_EndpointPrivateAccess(rName string, endpointPrivateAccess bool) string { +func testAccClusterConfig_vpcEndpointPrivateAccess(rName string, endpointPrivateAccess bool) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q @@ -934,7 +934,7 @@ resource "aws_eks_cluster" "test" { `, rName, endpointPrivateAccess)) } -func testAccClusterConfig_VPCConfig_EndpointPublicAccess(rName string, endpointPublicAccess bool) string { +func testAccClusterConfig_vpcEndpointPublicAccess(rName string, endpointPublicAccess bool) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q @@ -951,7 +951,7 @@ resource "aws_eks_cluster" "test" { `, rName, endpointPublicAccess)) } -func testAccClusterConfig_VPCConfig_PublicAccessCIDRs(rName string, publicAccessCidr string) string { +func testAccClusterConfig_vpcPublicAccessCIDRs(rName string, publicAccessCidr string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q @@ -969,7 +969,7 @@ resource "aws_eks_cluster" "test" { `, rName, publicAccessCidr)) } -func testAccClusterConfig_NetworkConfig_ServiceIPv4CIDR(rName string, serviceIpv4Cidr string) string { +func testAccClusterConfig_networkServiceIPv4CIDR(rName string, serviceIpv4Cidr string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q @@ -988,7 +988,7 @@ resource "aws_eks_cluster" "test" { `, rName, serviceIpv4Cidr)) } -func testAccClusterConfig_NetworkConfig_IPFamily(rName string, ipFamily string) string { +func testAccClusterConfig_networkIPFamily(rName string, ipFamily string) string { return acctest.ConfigCompose(testAccClusterConfig_Base(rName), fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q diff --git a/internal/service/eks/clusters_data_source_test.go b/internal/service/eks/clusters_data_source_test.go index b8cf8673128..7db2fecb14f 100644 --- a/internal/service/eks/clusters_data_source_test.go +++ b/internal/service/eks/clusters_data_source_test.go @@ -20,7 +20,7 @@ func TestAccEKSClustersDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClustersDataSourceConfig_Basic(rName), + Config: testAccClustersDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceResourceName, "names.#", "0"), ), @@ -29,9 +29,9 @@ func TestAccEKSClustersDataSource_basic(t *testing.T) { }) } -func testAccClustersDataSourceConfig_Basic(rName string) string { +func testAccClustersDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( - testAccClusterConfig_Required(rName), ` + testAccClusterConfig_required(rName), ` data "aws_eks_clusters" "test" { depends_on = [aws_eks_cluster.test] } diff --git a/internal/service/eks/fargate_profile_test.go b/internal/service/eks/fargate_profile_test.go index 69c5631696f..29c1ea8a518 100644 --- a/internal/service/eks/fargate_profile_test.go +++ b/internal/service/eks/fargate_profile_test.go @@ -30,7 +30,7 @@ func TestAccEKSFargateProfile_basic(t *testing.T) { CheckDestroy: testAccCheckFargateProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccFargateProfileFargateProfileNameConfig(rName), + Config: testAccFargateProfileConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFargateProfileExists(resourceName, &fargateProfile), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "eks", regexp.MustCompile(fmt.Sprintf("fargateprofile/%[1]s/%[1]s/.+", rName))), @@ -64,7 +64,7 @@ func TestAccEKSFargateProfile_disappears(t *testing.T) { CheckDestroy: testAccCheckFargateProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccFargateProfileFargateProfileNameConfig(rName), + Config: testAccFargateProfileConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFargateProfileExists(resourceName, &fargateProfile), acctest.CheckResourceDisappears(acctest.Provider, tfeks.ResourceFargateProfile(), resourceName), @@ -88,7 +88,7 @@ func TestAccEKSFargateProfile_Multi_profile(t *testing.T) { CheckDestroy: testAccCheckFargateProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccFargateProfileFargateProfileMultipleConfig(rName), + Config: testAccFargateProfileConfig_multiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFargateProfileExists(resourceName1, &fargateProfile), testAccCheckFargateProfileExists(resourceName2, &fargateProfile), @@ -110,7 +110,7 @@ func TestAccEKSFargateProfile_Selector_labels(t *testing.T) { CheckDestroy: testAccCheckFargateProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccFargateProfileSelectorLabels1Config(rName, "key1", "value1"), + Config: testAccFargateProfileConfig_selectorLabels1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFargateProfileExists(resourceName, &fargateProfile1), ), @@ -136,7 +136,7 @@ func TestAccEKSFargateProfile_tags(t *testing.T) { CheckDestroy: testAccCheckFargateProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccFargateProfileTags1Config(rName, "key1", "value1"), + Config: testAccFargateProfileConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFargateProfileExists(resourceName, &fargateProfile1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -149,7 +149,7 @@ func TestAccEKSFargateProfile_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFargateProfileTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccFargateProfileConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFargateProfileExists(resourceName, &fargateProfile2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -158,7 +158,7 @@ func TestAccEKSFargateProfile_tags(t *testing.T) { ), }, { - Config: testAccFargateProfileTags1Config(rName, "key2", "value2"), + Config: testAccFargateProfileConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFargateProfileExists(resourceName, &fargateProfile3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -459,7 +459,7 @@ resource "aws_eks_cluster" "test" { `, rName) } -func testAccFargateProfileFargateProfileNameConfig(rName string) string { +func testAccFargateProfileConfig_name(rName string) string { return testAccFargateProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_eks_fargate_profile" "test" { cluster_name = aws_eks_cluster.test.name @@ -479,7 +479,7 @@ resource "aws_eks_fargate_profile" "test" { `, rName) } -func testAccFargateProfileFargateProfileMultipleConfig(rName string) string { +func testAccFargateProfileConfig_multiple(rName string) string { return acctest.ConfigCompose( testAccFargateProfileBaseConfig(rName), fmt.Sprintf(` @@ -503,7 +503,7 @@ resource "aws_eks_fargate_profile" "test" { `, rName)) } -func testAccFargateProfileSelectorLabels1Config(rName, labelKey1, labelValue1 string) string { +func testAccFargateProfileConfig_selectorLabels1(rName, labelKey1, labelValue1 string) string { return testAccFargateProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_eks_fargate_profile" "test" { cluster_name = aws_eks_cluster.test.name @@ -526,7 +526,7 @@ resource "aws_eks_fargate_profile" "test" { `, rName, labelKey1, labelValue1) } -func testAccFargateProfileTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccFargateProfileConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccFargateProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_eks_fargate_profile" "test" { cluster_name = aws_eks_cluster.test.name @@ -550,7 +550,7 @@ resource "aws_eks_fargate_profile" "test" { `, rName, tagKey1, tagValue1) } -func testAccFargateProfileTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccFargateProfileConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccFargateProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_eks_fargate_profile" "test" { cluster_name = aws_eks_cluster.test.name diff --git a/internal/service/eks/identity_provider_config_test.go b/internal/service/eks/identity_provider_config_test.go index c4af37428a5..4cc32a40a1b 100644 --- a/internal/service/eks/identity_provider_config_test.go +++ b/internal/service/eks/identity_provider_config_test.go @@ -30,11 +30,11 @@ func TestAccEKSIdentityProviderConfig_basic(t *testing.T) { CheckDestroy: testAccCheckIdentityProviderDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccIdentityProviderIssuerURLConfig(rName, "http://example.com"), + Config: testAccIdentityProviderConfigConfig_issuerURL(rName, "http://example.com"), ExpectError: regexp.MustCompile(`expected .* to have a url with schema of: "https", got http://example.com`), }, { - Config: testAccIdentityProviderNameConfig(rName), + Config: testAccIdentityProviderConfigConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityProviderExistsConfig(ctx, resourceName, &config), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "eks", regexp.MustCompile(fmt.Sprintf("identityproviderconfig/%[1]s/oidc/%[1]s/.+", rName))), @@ -73,7 +73,7 @@ func TestAccEKSIdentityProviderConfig_disappears(t *testing.T) { CheckDestroy: testAccCheckIdentityProviderDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccIdentityProviderNameConfig(rName), + Config: testAccIdentityProviderConfigConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityProviderExistsConfig(ctx, resourceName, &config), acctest.CheckResourceDisappears(acctest.Provider, tfeks.ResourceIdentityProviderConfig(), resourceName), @@ -97,7 +97,7 @@ func TestAccEKSIdentityProviderConfig_allOIDCOptions(t *testing.T) { CheckDestroy: testAccCheckIdentityProviderDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccIdentityProviderAllOIDCOptionsConfig(rName), + Config: testAccIdentityProviderConfigConfig_allOIDCOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityProviderExistsConfig(ctx, resourceName, &config), resource.TestCheckResourceAttr(resourceName, "oidc.#", "1"), @@ -135,7 +135,7 @@ func TestAccEKSIdentityProviderConfig_tags(t *testing.T) { CheckDestroy: testAccCheckIdentityProviderDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccIdentityProviderTags1Config(rName, "key1", "value1"), + Config: testAccIdentityProviderConfigConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityProviderExistsConfig(ctx, resourceName, &config), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -148,7 +148,7 @@ func TestAccEKSIdentityProviderConfig_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccIdentityProviderTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccIdentityProviderConfigConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityProviderExistsConfig(ctx, resourceName, &config), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -157,7 +157,7 @@ func TestAccEKSIdentityProviderConfig_tags(t *testing.T) { ), }, { - Config: testAccIdentityProviderTags1Config(rName, "key2", "value2"), + Config: testAccIdentityProviderConfigConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityProviderExistsConfig(ctx, resourceName, &config), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -291,7 +291,7 @@ resource "aws_eks_cluster" "test" { `, rName)) } -func testAccIdentityProviderNameConfig(rName string) string { +func testAccIdentityProviderConfigConfig_name(rName string) string { return acctest.ConfigCompose(testAccIdentityProviderBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_identity_provider_config" "test" { cluster_name = aws_eks_cluster.test.name @@ -305,7 +305,7 @@ resource "aws_eks_identity_provider_config" "test" { `, rName)) } -func testAccIdentityProviderIssuerURLConfig(rName, issuerUrl string) string { +func testAccIdentityProviderConfigConfig_issuerURL(rName, issuerUrl string) string { return acctest.ConfigCompose(testAccIdentityProviderBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_identity_provider_config" "test" { cluster_name = aws_eks_cluster.test.name @@ -319,7 +319,7 @@ resource "aws_eks_identity_provider_config" "test" { `, rName, issuerUrl)) } -func testAccIdentityProviderAllOIDCOptionsConfig(rName string) string { +func testAccIdentityProviderConfigConfig_allOIDCOptions(rName string) string { return acctest.ConfigCompose(testAccIdentityProviderBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_identity_provider_config" "test" { cluster_name = aws_eks_cluster.test.name @@ -342,7 +342,7 @@ resource "aws_eks_identity_provider_config" "test" { `, rName)) } -func testAccIdentityProviderTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccIdentityProviderConfigConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccIdentityProviderBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_identity_provider_config" "test" { cluster_name = aws_eks_cluster.test.name @@ -360,7 +360,7 @@ resource "aws_eks_identity_provider_config" "test" { `, rName, tagKey1, tagValue1)) } -func testAccIdentityProviderTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccIdentityProviderConfigConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccIdentityProviderBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_identity_provider_config" "test" { cluster_name = aws_eks_cluster.test.name diff --git a/internal/service/eks/node_group_data_source_test.go b/internal/service/eks/node_group_data_source_test.go index 5d67b383e01..42fc08a5e84 100644 --- a/internal/service/eks/node_group_data_source_test.go +++ b/internal/service/eks/node_group_data_source_test.go @@ -23,11 +23,11 @@ func TestAccEKSNodeGroupDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupNodeGroupNameConfig(rName), + Config: testAccNodeGroupConfig_dataSourceName(rName), Check: resource.ComposeTestCheckFunc(), }, { - Config: testAccNodeGroupDataSourceConfig(rName), + Config: testAccNodeGroupDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup), resource.TestCheckResourceAttrPair(resourceName, "ami_type", dataSourceResourceName, "ami_type"), @@ -57,8 +57,8 @@ func TestAccEKSNodeGroupDataSource_basic(t *testing.T) { }) } -func testAccNodeGroupDataSourceConfig(rName string) string { - return acctest.ConfigCompose(testAccNodeGroupNodeGroupNameConfig(rName), fmt.Sprintf(` +func testAccNodeGroupDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccNodeGroupConfig_dataSourceName(rName), fmt.Sprintf(` data "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name node_group_name = %[1]q diff --git a/internal/service/eks/node_group_test.go b/internal/service/eks/node_group_test.go index 8b641815d22..9b5e9d5d347 100644 --- a/internal/service/eks/node_group_test.go +++ b/internal/service/eks/node_group_test.go @@ -36,7 +36,7 @@ func TestAccEKSNodeGroup_basic(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupNodeGroupNameConfig(rName), + Config: testAccNodeGroupConfig_dataSourceName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup), resource.TestCheckResourceAttr(resourceName, "ami_type", eks.AMITypesAl2X8664), @@ -86,7 +86,7 @@ func TestAccEKSNodeGroup_Name_generated(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupNodeGroupNameGeneratedConfig(rName), + Config: testAccNodeGroupConfig_nameGenerated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup), create.TestCheckResourceAttrNameGenerated(resourceName, "node_group_name"), @@ -114,7 +114,7 @@ func TestAccEKSNodeGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupNodeGroupNamePrefixConfig(rName, "tf-acc-test-prefix-"), + Config: testAccNodeGroupConfig_namePrefix(rName, "tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup), create.TestCheckResourceAttrNameFromPrefix(resourceName, "node_group_name", "tf-acc-test-prefix-"), @@ -142,7 +142,7 @@ func TestAccEKSNodeGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupNodeGroupNameConfig(rName), + Config: testAccNodeGroupConfig_dataSourceName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup), acctest.CheckResourceDisappears(acctest.Provider, tfeks.ResourceNodeGroup(), resourceName), @@ -165,7 +165,7 @@ func TestAccEKSNodeGroup_amiType(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupAMITypeConfig(rName, eks.AMITypesAl2X8664Gpu), + Config: testAccNodeGroupConfig_amiType(rName, eks.AMITypesAl2X8664Gpu), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "ami_type", eks.AMITypesAl2X8664Gpu), @@ -177,7 +177,7 @@ func TestAccEKSNodeGroup_amiType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupAMITypeConfig(rName, eks.AMITypesAl2Arm64), + Config: testAccNodeGroupConfig_amiType(rName, eks.AMITypesAl2Arm64), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), resource.TestCheckResourceAttr(resourceName, "ami_type", eks.AMITypesAl2Arm64), @@ -199,7 +199,7 @@ func TestAccEKSNodeGroup_CapacityType_spot(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupCapacityTypeConfig(rName, eks.CapacityTypesSpot), + Config: testAccNodeGroupConfig_capacityType(rName, eks.CapacityTypesSpot), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "capacity_type", eks.CapacityTypesSpot), @@ -226,7 +226,7 @@ func TestAccEKSNodeGroup_diskSize(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupDiskSizeConfig(rName, 21), + Config: testAccNodeGroupConfig_diskSize(rName, 21), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "disk_size", "21"), @@ -253,7 +253,7 @@ func TestAccEKSNodeGroup_forceUpdateVersion(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupForceUpdateVersionConfig(rName, "1.19"), + Config: testAccNodeGroupConfig_forceUpdateVersion(rName, "1.19"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "version", "1.19"), @@ -266,7 +266,7 @@ func TestAccEKSNodeGroup_forceUpdateVersion(t *testing.T) { ImportStateVerifyIgnore: []string{"force_update_version"}, }, { - Config: testAccNodeGroupForceUpdateVersionConfig(rName, "1.20"), + Config: testAccNodeGroupConfig_forceUpdateVersion(rName, "1.20"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "version", "1.20"), @@ -289,7 +289,7 @@ func TestAccEKSNodeGroup_InstanceTypes_multiple(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupInstanceTypesMultipleConfig(rName, instanceTypes), + Config: testAccNodeGroupConfig_instanceTypesMultiple(rName, instanceTypes), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "instance_types.#", "4"), @@ -320,7 +320,7 @@ func TestAccEKSNodeGroup_InstanceTypes_single(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupInstanceTypesSingleConfig(rName), + Config: testAccNodeGroupConfig_instanceTypesSingle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "instance_types.#", "1"), @@ -347,7 +347,7 @@ func TestAccEKSNodeGroup_labels(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupLabels1Config(rName, "key1", "value1"), + Config: testAccNodeGroupConfig_labels1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "labels.%", "1"), @@ -360,7 +360,7 @@ func TestAccEKSNodeGroup_labels(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupLabels2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccNodeGroupConfig_labels2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), resource.TestCheckResourceAttr(resourceName, "labels.%", "2"), @@ -369,7 +369,7 @@ func TestAccEKSNodeGroup_labels(t *testing.T) { ), }, { - Config: testAccNodeGroupLabels1Config(rName, "key2", "value2"), + Config: testAccNodeGroupConfig_labels1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup3), resource.TestCheckResourceAttr(resourceName, "labels.%", "1"), @@ -394,7 +394,7 @@ func TestAccEKSNodeGroup_LaunchTemplate_id(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupLaunchTemplateId1Config(rName), + Config: testAccNodeGroupConfig_launchTemplateId1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "launch_template.#", "1"), @@ -407,7 +407,7 @@ func TestAccEKSNodeGroup_LaunchTemplate_id(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupLaunchTemplateId2Config(rName), + Config: testAccNodeGroupConfig_launchTemplateId2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupRecreated(&nodeGroup1, &nodeGroup2), @@ -433,7 +433,7 @@ func TestAccEKSNodeGroup_LaunchTemplate_name(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupLaunchTemplateName1Config(rName), + Config: testAccNodeGroupConfig_launchTemplateName1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "launch_template.#", "1"), @@ -446,7 +446,7 @@ func TestAccEKSNodeGroup_LaunchTemplate_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupLaunchTemplateName2Config(rName), + Config: testAccNodeGroupConfig_launchTemplateName2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupRecreated(&nodeGroup1, &nodeGroup2), @@ -471,7 +471,7 @@ func TestAccEKSNodeGroup_LaunchTemplate_version(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupLaunchTemplateVersion1Config(rName), + Config: testAccNodeGroupConfig_launchTemplateVersion1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "launch_template.#", "1"), @@ -484,7 +484,7 @@ func TestAccEKSNodeGroup_LaunchTemplate_version(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupLaunchTemplateVersion2Config(rName), + Config: testAccNodeGroupConfig_launchTemplateVersion2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupNotRecreated(&nodeGroup1, &nodeGroup2), @@ -509,7 +509,7 @@ func TestAccEKSNodeGroup_releaseVersion(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupReleaseVersionConfig(rName, "1.17"), + Config: testAccNodeGroupConfig_releaseVersion(rName, "1.17"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttrPair(resourceName, "release_version", ssmParameterDataSourceName, "value"), @@ -521,7 +521,7 @@ func TestAccEKSNodeGroup_releaseVersion(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupReleaseVersionConfig(rName, "1.18"), + Config: testAccNodeGroupConfig_releaseVersion(rName, "1.18"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupNotRecreated(&nodeGroup1, &nodeGroup2), @@ -549,7 +549,7 @@ func TestAccEKSNodeGroup_RemoteAccess_ec2SSHKey(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupRemoteAccessEC2SSHKeyConfig(rName, publicKey), + Config: testAccNodeGroupConfig_remoteAccessEC2SSHKey(rName, publicKey), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "remote_access.#", "1"), @@ -582,7 +582,7 @@ func TestAccEKSNodeGroup_RemoteAccess_sourceSecurityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupRemoteAccessSourceSecurityGroupIds1Config(rName, publicKey), + Config: testAccNodeGroupConfig_remoteAccessSourceSecurityIds1(rName, publicKey), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "remote_access.#", "1"), @@ -610,7 +610,7 @@ func TestAccEKSNodeGroup_Scaling_desiredSize(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupScalingSizesConfig(rName, 2, 2, 1), + Config: testAccNodeGroupConfig_scalingSizes(rName, 2, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "scaling_config.#", "1"), @@ -625,7 +625,7 @@ func TestAccEKSNodeGroup_Scaling_desiredSize(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupScalingSizesConfig(rName, 1, 2, 1), + Config: testAccNodeGroupConfig_scalingSizes(rName, 1, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupNotRecreated(&nodeGroup1, &nodeGroup2), @@ -651,7 +651,7 @@ func TestAccEKSNodeGroup_Scaling_maxSize(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupScalingSizesConfig(rName, 1, 2, 1), + Config: testAccNodeGroupConfig_scalingSizes(rName, 1, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "scaling_config.#", "1"), @@ -666,7 +666,7 @@ func TestAccEKSNodeGroup_Scaling_maxSize(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupScalingSizesConfig(rName, 1, 1, 1), + Config: testAccNodeGroupConfig_scalingSizes(rName, 1, 1, 1), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupNotRecreated(&nodeGroup1, &nodeGroup2), @@ -692,7 +692,7 @@ func TestAccEKSNodeGroup_Scaling_minSize(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupScalingSizesConfig(rName, 2, 2, 2), + Config: testAccNodeGroupConfig_scalingSizes(rName, 2, 2, 2), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "scaling_config.#", "1"), @@ -707,7 +707,7 @@ func TestAccEKSNodeGroup_Scaling_minSize(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupScalingSizesConfig(rName, 2, 2, 1), + Config: testAccNodeGroupConfig_scalingSizes(rName, 2, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupNotRecreated(&nodeGroup1, &nodeGroup2), @@ -733,7 +733,7 @@ func TestAccEKSNodeGroup_ScalingZeroDesiredSize_minSize(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupScalingSizesConfig(rName, 0, 1, 0), + Config: testAccNodeGroupConfig_scalingSizes(rName, 0, 1, 0), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "scaling_config.#", "1"), @@ -748,7 +748,7 @@ func TestAccEKSNodeGroup_ScalingZeroDesiredSize_minSize(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupScalingSizesConfig(rName, 1, 2, 1), + Config: testAccNodeGroupConfig_scalingSizes(rName, 1, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupNotRecreated(&nodeGroup1, &nodeGroup2), @@ -759,7 +759,7 @@ func TestAccEKSNodeGroup_ScalingZeroDesiredSize_minSize(t *testing.T) { ), }, { - Config: testAccNodeGroupScalingSizesConfig(rName, 0, 1, 0), + Config: testAccNodeGroupConfig_scalingSizes(rName, 0, 1, 0), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "scaling_config.#", "1"), @@ -784,7 +784,7 @@ func TestAccEKSNodeGroup_tags(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupTags1Config(rName, "key1", "value1"), + Config: testAccNodeGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -797,7 +797,7 @@ func TestAccEKSNodeGroup_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccNodeGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupNotRecreated(&nodeGroup1, &nodeGroup2), @@ -807,7 +807,7 @@ func TestAccEKSNodeGroup_tags(t *testing.T) { ), }, { - Config: testAccNodeGroupTags1Config(rName, "key2", "value2"), + Config: testAccNodeGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup3), testAccCheckNodeGroupNotRecreated(&nodeGroup2, &nodeGroup3), @@ -831,7 +831,7 @@ func TestAccEKSNodeGroup_taints(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupTaints1Config(rName, "key1", "value1", "NO_SCHEDULE"), + Config: testAccNodeGroupConfig_taints1(rName, "key1", "value1", "NO_SCHEDULE"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "taint.#", "1"), @@ -848,7 +848,7 @@ func TestAccEKSNodeGroup_taints(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupTaints2Config(rName, + Config: testAccNodeGroupConfig_taints2(rName, "key1", "value1updated", "NO_EXECUTE", "key2", "value2", "NO_SCHEDULE"), Check: resource.ComposeTestCheckFunc( @@ -867,7 +867,7 @@ func TestAccEKSNodeGroup_taints(t *testing.T) { ), }, { - Config: testAccNodeGroupTaints1Config(rName, "key2", "value2", "NO_SCHEDULE"), + Config: testAccNodeGroupConfig_taints1(rName, "key2", "value2", "NO_SCHEDULE"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "taint.#", "1"), @@ -894,7 +894,7 @@ func TestAccEKSNodeGroup_update(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupUpdate1Config(rName), + Config: testAccNodeGroupConfig_update1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "update_config.#", "1"), @@ -908,7 +908,7 @@ func TestAccEKSNodeGroup_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupUpdate2Config(rName), + Config: testAccNodeGroupConfig_update2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "update_config.#", "1"), @@ -932,7 +932,7 @@ func TestAccEKSNodeGroup_version(t *testing.T) { CheckDestroy: testAccCheckNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupVersionConfig(rName, "1.19"), + Config: testAccNodeGroupConfig_version(rName, "1.19"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup1), resource.TestCheckResourceAttr(resourceName, "version", "1.19"), @@ -944,7 +944,7 @@ func TestAccEKSNodeGroup_version(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNodeGroupVersionConfig(rName, "1.20"), + Config: testAccNodeGroupConfig_version(rName, "1.20"), Check: resource.ComposeTestCheckFunc( testAccCheckNodeGroupExists(resourceName, &nodeGroup2), testAccCheckNodeGroupNotRecreated(&nodeGroup1, &nodeGroup2), @@ -1225,7 +1225,7 @@ resource "aws_eks_cluster" "test" { `, rName, version)) } -func testAccNodeGroupNodeGroupNameConfig(rName string) string { +func testAccNodeGroupConfig_dataSourceName(rName string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1248,7 +1248,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupNodeGroupNameGeneratedConfig(rName string) string { +func testAccNodeGroupConfig_nameGenerated(rName string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), ` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1270,7 +1270,7 @@ resource "aws_eks_node_group" "test" { `) } -func testAccNodeGroupNodeGroupNamePrefixConfig(rName, namePrefix string) string { +func testAccNodeGroupConfig_namePrefix(rName, namePrefix string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1293,7 +1293,7 @@ resource "aws_eks_node_group" "test" { `, namePrefix)) } -func testAccNodeGroupAMITypeConfig(rName, amiType string) string { +func testAccNodeGroupConfig_amiType(rName, amiType string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { ami_type = %[2]q @@ -1317,7 +1317,7 @@ resource "aws_eks_node_group" "test" { `, rName, amiType)) } -func testAccNodeGroupCapacityTypeConfig(rName, capacityType string) string { +func testAccNodeGroupConfig_capacityType(rName, capacityType string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { capacity_type = %[2]q @@ -1341,7 +1341,7 @@ resource "aws_eks_node_group" "test" { `, rName, capacityType)) } -func testAccNodeGroupDiskSizeConfig(rName string, diskSize int) string { +func testAccNodeGroupConfig_diskSize(rName string, diskSize int) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1365,7 +1365,7 @@ resource "aws_eks_node_group" "test" { `, rName, diskSize)) } -func testAccNodeGroupForceUpdateVersionConfig(rName, version string) string { +func testAccNodeGroupConfig_forceUpdateVersion(rName, version string) string { return acctest.ConfigCompose(testAccNodeGroupBaseVersionConfig(rName, version), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1390,7 +1390,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupInstanceTypesMultipleConfig(rName, instanceTypes string) string { +func testAccNodeGroupConfig_instanceTypesMultiple(rName, instanceTypes string) string { return acctest.ConfigCompose( testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` @@ -1418,7 +1418,7 @@ resource "aws_eks_node_group" "test" { `, instanceTypes, rName)) } -func testAccNodeGroupInstanceTypesSingleConfig(rName string) string { +func testAccNodeGroupConfig_instanceTypesSingle(rName string) string { return acctest.ConfigCompose( testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` @@ -1453,7 +1453,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupLabels1Config(rName, labelKey1, labelValue1 string) string { +func testAccNodeGroupConfig_labels1(rName, labelKey1, labelValue1 string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1480,7 +1480,7 @@ resource "aws_eks_node_group" "test" { `, rName, labelKey1, labelValue1)) } -func testAccNodeGroupLabels2Config(rName, labelKey1, labelValue1, labelKey2, labelValue2 string) string { +func testAccNodeGroupConfig_labels2(rName, labelKey1, labelValue1, labelKey2, labelValue2 string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1508,7 +1508,7 @@ resource "aws_eks_node_group" "test" { `, rName, labelKey1, labelValue1, labelKey2, labelValue2)) } -func testAccNodeGroupLaunchTemplateId1Config(rName string) string { +func testAccNodeGroupConfig_launchTemplateId1(rName string) string { return acctest.ConfigCompose( testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` @@ -1556,7 +1556,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupLaunchTemplateId2Config(rName string) string { +func testAccNodeGroupConfig_launchTemplateId2(rName string) string { return acctest.ConfigCompose( testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` @@ -1604,7 +1604,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupLaunchTemplateName1Config(rName string) string { +func testAccNodeGroupConfig_launchTemplateName1(rName string) string { return acctest.ConfigCompose( testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` @@ -1652,7 +1652,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupLaunchTemplateName2Config(rName string) string { +func testAccNodeGroupConfig_launchTemplateName2(rName string) string { return acctest.ConfigCompose( testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` @@ -1700,7 +1700,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupLaunchTemplateVersion1Config(rName string) string { +func testAccNodeGroupConfig_launchTemplateVersion1(rName string) string { return acctest.ConfigCompose( testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` @@ -1742,7 +1742,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupLaunchTemplateVersion2Config(rName string) string { +func testAccNodeGroupConfig_launchTemplateVersion2(rName string) string { return acctest.ConfigCompose( testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` @@ -1784,7 +1784,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupReleaseVersionConfig(rName string, version string) string { +func testAccNodeGroupConfig_releaseVersion(rName string, version string) string { return acctest.ConfigCompose(testAccNodeGroupBaseVersionConfig(rName, version), fmt.Sprintf(` data "aws_ssm_parameter" "test" { name = "/aws/service/eks/optimized-ami/${aws_eks_cluster.test.version}/amazon-linux-2/recommended/release_version" @@ -1813,7 +1813,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupRemoteAccessEC2SSHKeyConfig(rName, publicKey string) string { +func testAccNodeGroupConfig_remoteAccessEC2SSHKey(rName, publicKey string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_key_pair" "test" { key_name = %[1]q @@ -1845,7 +1845,7 @@ resource "aws_eks_node_group" "test" { `, rName, publicKey)) } -func testAccNodeGroupRemoteAccessSourceSecurityGroupIds1Config(rName, publicKey string) string { +func testAccNodeGroupConfig_remoteAccessSourceSecurityIds1(rName, publicKey string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_key_pair" "test" { key_name = %[1]q @@ -1878,7 +1878,7 @@ resource "aws_eks_node_group" "test" { `, rName, publicKey)) } -func testAccNodeGroupScalingSizesConfig(rName string, desiredSize, maxSize, minSize int) string { +func testAccNodeGroupConfig_scalingSizes(rName string, desiredSize, maxSize, minSize int) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1901,7 +1901,7 @@ resource "aws_eks_node_group" "test" { `, rName, desiredSize, maxSize, minSize)) } -func testAccNodeGroupTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccNodeGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1928,7 +1928,7 @@ resource "aws_eks_node_group" "test" { `, rName, tagKey1, tagValue1)) } -func testAccNodeGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccNodeGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1956,7 +1956,7 @@ resource "aws_eks_node_group" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccNodeGroupTaints1Config(rName, taintKey1, taintValue1, taintEffect1 string) string { +func testAccNodeGroupConfig_taints1(rName, taintKey1, taintValue1, taintEffect1 string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -1985,7 +1985,7 @@ resource "aws_eks_node_group" "test" { `, rName, taintKey1, taintValue1, taintEffect1)) } -func testAccNodeGroupTaints2Config(rName, taintKey1, taintValue1, taintEffect1, taintKey2, taintValue2, taintEffect2 string) string { +func testAccNodeGroupConfig_taints2(rName, taintKey1, taintValue1, taintEffect1, taintKey2, taintValue2, taintEffect2 string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -2020,7 +2020,7 @@ resource "aws_eks_node_group" "test" { `, rName, taintKey1, taintValue1, taintEffect1, taintKey2, taintValue2, taintEffect2)) } -func testAccNodeGroupUpdate1Config(rName string) string { +func testAccNodeGroupConfig_update1(rName string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -2047,7 +2047,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupUpdate2Config(rName string) string { +func testAccNodeGroupConfig_update2(rName string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name @@ -2074,7 +2074,7 @@ resource "aws_eks_node_group" "test" { `, rName)) } -func testAccNodeGroupVersionConfig(rName, version string) string { +func testAccNodeGroupConfig_version(rName, version string) string { return acctest.ConfigCompose(testAccNodeGroupBaseVersionConfig(rName, version), fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name diff --git a/internal/service/eks/node_groups_data_source_test.go b/internal/service/eks/node_groups_data_source_test.go index a25f6766f1b..8c1b8a485bb 100644 --- a/internal/service/eks/node_groups_data_source_test.go +++ b/internal/service/eks/node_groups_data_source_test.go @@ -21,11 +21,11 @@ func TestAccEKSNodeGroupsDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccNodeGroupNamesConfig(rName), + Config: testAccNodeGroupsDataSourceConfig_namesBasic(rName), Check: resource.ComposeTestCheckFunc(), }, { - Config: testAccNodeGroupNamesDataSourceConfig(rName), + Config: testAccNodeGroupsDataSourceConfig_names(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceResourceName, "cluster_name", rName), resource.TestCheckResourceAttr(dataSourceResourceName, "names.#", "2"), @@ -35,8 +35,8 @@ func TestAccEKSNodeGroupsDataSource_basic(t *testing.T) { }) } -func testAccNodeGroupNamesDataSourceConfig(rName string) string { - return acctest.ConfigCompose(testAccNodeGroupNamesConfig(rName), ` +func testAccNodeGroupsDataSourceConfig_names(rName string) string { + return acctest.ConfigCompose(testAccNodeGroupsDataSourceConfig_namesBasic(rName), ` data "aws_eks_node_groups" "test" { cluster_name = aws_eks_cluster.test.name @@ -45,7 +45,7 @@ data "aws_eks_node_groups" "test" { `) } -func testAccNodeGroupNamesConfig(rName string) string { +func testAccNodeGroupsDataSourceConfig_namesBasic(rName string) string { return acctest.ConfigCompose(testAccNodeGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_eks_node_group" "test_a" { cluster_name = aws_eks_cluster.test.name diff --git a/internal/service/elasticache/cluster.go b/internal/service/elasticache/cluster.go index 77f1cb1a10c..e05bf244538 100644 --- a/internal/service/elasticache/cluster.go +++ b/internal/service/elasticache/cluster.go @@ -13,7 +13,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elasticache" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" - gversion "github.com/hashicorp/go-version" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -436,7 +435,7 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, arn, nil, tags) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed adding tags after create for ElastiCache Cache Cluster (%s): %w", d.Id(), err) } @@ -507,7 +506,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, aws.StringValue(c.ARN)) - if err != nil && !verify.CheckISOErrorTagsUnsupported(err) { + if err != nil && !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { return fmt.Errorf("error listing tags for ElastiCache Cache Cluster (%s): %w", d.Id(), err) } @@ -535,8 +534,12 @@ func setFromCacheCluster(d *schema.ResourceData, c *elasticache.CacheCluster) er d.Set("node_type", c.CacheNodeType) d.Set("engine", c.Engine) - if err := setEngineVersionFromCacheCluster(d, c); err != nil { - return err + if aws.StringValue(c.Engine) == engineRedis { + if err := setEngineVersionRedis(d, c.EngineVersion); err != nil { + return err + } + } else { + setEngineVersionMemcached(d, c.EngineVersion) } d.Set("auto_minor_version_upgrade", strconv.FormatBool(aws.BoolValue(c.AutoMinorVersionUpgrade))) @@ -557,27 +560,6 @@ func setFromCacheCluster(d *schema.ResourceData, c *elasticache.CacheCluster) er return nil } -func setEngineVersionFromCacheCluster(d *schema.ResourceData, c *elasticache.CacheCluster) error { - engineVersion, err := gversion.NewVersion(aws.StringValue(c.EngineVersion)) - if err != nil { - return fmt.Errorf("error reading ElastiCache Cache Cluster (%s) engine version: %w", d.Id(), err) - } - if engineVersion.Segments()[0] < 6 { - d.Set("engine_version", engineVersion.String()) - } else { - // Handle major-only version number - configVersion := d.Get("engine_version").(string) - if t, _ := regexp.MatchString(`[6-9]\.x`, configVersion); t { - d.Set("engine_version", fmt.Sprintf("%d.x", engineVersion.Segments()[0])) - } else { - d.Set("engine_version", fmt.Sprintf("%d.%d", engineVersion.Segments()[0], engineVersion.Segments()[1])) - } - } - d.Set("engine_version_actual", engineVersion.String()) - - return nil -} - func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ElastiCacheConn @@ -724,7 +706,7 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { // ISO partitions may not support tagging, giving error if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed updating ElastiCache Cache Cluster (%s) tags: %w", d.Get("arn").(string), err) } @@ -802,7 +784,7 @@ func createCacheCluster(conn *elasticache.ElastiCache, input *elasticache.Create output, err := conn.CreateCacheCluster(input) // Some partitions may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating ElastiCache Cache Cluster with tags: %s. Trying create without tags.", err) input.Tags = nil diff --git a/internal/service/elasticache/cluster_data_source.go b/internal/service/elasticache/cluster_data_source.go index 3626f9513f8..b06d382aa4a 100644 --- a/internal/service/elasticache/cluster_data_source.go +++ b/internal/service/elasticache/cluster_data_source.go @@ -233,7 +233,7 @@ func dataSourceClusterRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, aws.StringValue(cluster.ARN)) - if err != nil && !verify.CheckISOErrorTagsUnsupported(err) { + if err != nil && !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { return fmt.Errorf("error listing tags for Elasticache Cluster (%s): %w", d.Id(), err) } diff --git a/internal/service/elasticache/cluster_data_source_test.go b/internal/service/elasticache/cluster_data_source_test.go index 4113d522d73..90621d9fce9 100644 --- a/internal/service/elasticache/cluster_data_source_test.go +++ b/internal/service/elasticache/cluster_data_source_test.go @@ -25,7 +25,7 @@ func TestAccElastiCacheClusterDataSource_Data_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccClusterWithDataSourceConfig(rName), + Config: testAccClusterDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone", resourceName, "availability_zone"), resource.TestCheckResourceAttrPair(dataSourceName, "cluster_address", resourceName, "cluster_address"), @@ -54,7 +54,7 @@ func TestAccElastiCacheClusterDataSource_Engine_Redis_LogDeliveryConfigurations( ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), + Config: testAccClusterConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "engine", "redis"), resource.TestCheckResourceAttr(dataSourceName, "log_delivery_configuration.0.destination", rName), @@ -71,7 +71,7 @@ func TestAccElastiCacheClusterDataSource_Engine_Redis_LogDeliveryConfigurations( }) } -func testAccClusterWithDataSourceConfig(rName string) string { +func testAccClusterDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = %[1]q diff --git a/internal/service/elasticache/cluster_test.go b/internal/service/elasticache/cluster_test.go index e05f21abd17..8a4c31d6673 100644 --- a/internal/service/elasticache/cluster_test.go +++ b/internal/service/elasticache/cluster_test.go @@ -46,7 +46,7 @@ func TestAccElastiCacheCluster_Engine_memcached(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Engine_Memcached(rName), + Config: testAccClusterConfig_engineMemcached(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "cache_nodes.0.id", "0001"), @@ -84,7 +84,7 @@ func TestAccElastiCacheCluster_Engine_redis(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Engine_Redis(rName), + Config: testAccClusterConfig_engineRedis(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "cache_nodes.0.id", "0001"), @@ -122,7 +122,7 @@ func TestAccElastiCacheCluster_Engine_redis_v5(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Engine_Redis_v5(rName), + Config: testAccClusterConfig_engineRedisV5(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -153,7 +153,7 @@ func TestAccElastiCacheCluster_Engine_None(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Engine_None(rName), + Config: testAccClusterConfig_engineNone(rName), // Verify "ExactlyOneOf" in the schema for "engine" and "replication_group_id" // throws a plan-time error when neither are configured. ExpectError: regexp.MustCompile(`Invalid combination of arguments`), @@ -175,7 +175,7 @@ func TestAccElastiCacheCluster_PortRedis_default(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_RedisDefaultPort, + Config: testAccClusterConfig_redisDefaultPort, Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_elasticache_cluster.test", &ec), resource.TestCheckResourceAttr("aws_security_group_rule.test", "to_port", "6379"), @@ -202,7 +202,7 @@ func TestAccElastiCacheCluster_ParameterGroupName_default(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_ParameterGroupName(rName, "memcached", "1.4.34", "default.memcached1.4"), + Config: testAccClusterConfig_parameterGroupName(rName, "memcached", "1.4.34", "default.memcached1.4"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "engine", "memcached"), @@ -240,7 +240,7 @@ func TestAccElastiCacheCluster_port(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Port(rName, port), + Config: testAccClusterConfig_port(rName, port), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "cache_nodes.0.id", "0001"), @@ -275,7 +275,7 @@ func TestAccElastiCacheCluster_SecurityGroup_ec2Classic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SecurityGroup_EC2Classic(rName), + Config: testAccClusterConfig_securityGroupEC2Classic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceSecurityGroupName), testAccCheckClusterEC2ClassicExists(resourceName, &ec), @@ -338,14 +338,14 @@ func TestAccElastiCacheCluster_NumCacheNodes_decrease(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_NumCacheNodes(rName, 3), + Config: testAccClusterConfig_numCacheNodes(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "num_cache_nodes", "3"), ), }, { - Config: testAccClusterConfig_NumCacheNodes(rName, 1), + Config: testAccClusterConfig_numCacheNodes(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "num_cache_nodes", "1"), @@ -371,14 +371,14 @@ func TestAccElastiCacheCluster_NumCacheNodes_increase(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_NumCacheNodes(rName, 1), + Config: testAccClusterConfig_numCacheNodes(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "num_cache_nodes", "1"), ), }, { - Config: testAccClusterConfig_NumCacheNodes(rName, 3), + Config: testAccClusterConfig_numCacheNodes(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "num_cache_nodes", "3"), @@ -404,7 +404,7 @@ func TestAccElastiCacheCluster_NumCacheNodes_increaseWithPreferredAvailabilityZo CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_NumCacheNodesWithPreferredAvailabilityZones(rName, 1), + Config: testAccClusterConfig_numCacheNodesPreferredAvailabilityZones(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "num_cache_nodes", "1"), @@ -412,7 +412,7 @@ func TestAccElastiCacheCluster_NumCacheNodes_increaseWithPreferredAvailabilityZo ), }, { - Config: testAccClusterConfig_NumCacheNodesWithPreferredAvailabilityZones(rName, 3), + Config: testAccClusterConfig_numCacheNodesPreferredAvailabilityZones(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "num_cache_nodes", "3"), @@ -439,7 +439,7 @@ func TestAccElastiCacheCluster_vpc(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInVPCConfig(rName), + Config: testAccClusterConfig_inVPC(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists("aws_elasticache_subnet_group.test", &csg), testAccCheckClusterExists("aws_elasticache_cluster.test", &ec), @@ -466,7 +466,7 @@ func TestAccElastiCacheCluster_multiAZInVPC(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterMultiAZInVPCConfig(rName), + Config: testAccClusterConfig_multiAZInVPC(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists("aws_elasticache_subnet_group.test", &csg), testAccCheckClusterExists("aws_elasticache_cluster.test", &ec), @@ -493,22 +493,22 @@ func TestAccElastiCacheCluster_AZMode_memcached(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_AZMode_Memcached(rName, "unknown"), + Config: testAccClusterConfig_azModeMemcached(rName, "unknown"), ExpectError: regexp.MustCompile(`expected az_mode to be one of .*, got unknown`), }, { - Config: testAccClusterConfig_AZMode_Memcached(rName, "cross-az"), + Config: testAccClusterConfig_azModeMemcached(rName, "cross-az"), ExpectError: regexp.MustCompile(`az_mode "cross-az" is not supported with num_cache_nodes = 1`), }, { - Config: testAccClusterConfig_AZMode_Memcached(rName, "single-az"), + Config: testAccClusterConfig_azModeMemcached(rName, "single-az"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "az_mode", "single-az"), ), }, { - Config: testAccClusterConfig_AZMode_Memcached(rName, "cross-az"), + Config: testAccClusterConfig_azModeMemcached(rName, "cross-az"), ExpectError: regexp.MustCompile(`az_mode "cross-az" is not supported with num_cache_nodes = 1`), }, }, @@ -531,15 +531,15 @@ func TestAccElastiCacheCluster_AZMode_redis(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_AZMode_Redis(rName, "unknown"), + Config: testAccClusterConfig_azModeRedis(rName, "unknown"), ExpectError: regexp.MustCompile(`expected az_mode to be one of .*, got unknown`), }, { - Config: testAccClusterConfig_AZMode_Redis(rName, "cross-az"), + Config: testAccClusterConfig_azModeRedis(rName, "cross-az"), ExpectError: regexp.MustCompile(`az_mode "cross-az" is not supported with num_cache_nodes = 1`), }, { - Config: testAccClusterConfig_AZMode_Redis(rName, "single-az"), + Config: testAccClusterConfig_azModeRedis(rName, "single-az"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "az_mode", "single-az"), @@ -565,7 +565,7 @@ func TestAccElastiCacheCluster_EngineVersion_memcached(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EngineVersion_Memcached(rName, "1.4.33"), + Config: testAccClusterConfig_engineVersionMemcached(rName, "1.4.33"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &pre), resource.TestCheckResourceAttr(resourceName, "engine_version", "1.4.33"), @@ -573,7 +573,7 @@ func TestAccElastiCacheCluster_EngineVersion_memcached(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion_Memcached(rName, "1.4.24"), + Config: testAccClusterConfig_engineVersionMemcached(rName, "1.4.24"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &mid), testAccCheckClusterRecreated(&pre, &mid), @@ -582,7 +582,7 @@ func TestAccElastiCacheCluster_EngineVersion_memcached(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion_Memcached(rName, "1.4.34"), + Config: testAccClusterConfig_engineVersionMemcached(rName, "1.4.34"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &post), testAccCheckClusterNotRecreated(&mid, &post), @@ -610,7 +610,7 @@ func TestAccElastiCacheCluster_EngineVersion_redis(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EngineVersion_Redis(rName, "3.2.6"), + Config: testAccClusterConfig_engineVersionRedis(rName, "3.2.6"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "engine_version", "3.2.6"), @@ -618,7 +618,7 @@ func TestAccElastiCacheCluster_EngineVersion_redis(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion_Redis(rName, "3.2.4"), + Config: testAccClusterConfig_engineVersionRedis(rName, "3.2.4"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v2), testAccCheckClusterRecreated(&v1, &v2), @@ -627,7 +627,7 @@ func TestAccElastiCacheCluster_EngineVersion_redis(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion_Redis(rName, "3.2.10"), + Config: testAccClusterConfig_engineVersionRedis(rName, "3.2.10"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v3), testAccCheckClusterNotRecreated(&v2, &v3), @@ -636,7 +636,7 @@ func TestAccElastiCacheCluster_EngineVersion_redis(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion_Redis(rName, "6.0"), + Config: testAccClusterConfig_engineVersionRedis(rName, "6.0"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v4), testAccCheckClusterNotRecreated(&v3, &v4), @@ -645,7 +645,7 @@ func TestAccElastiCacheCluster_EngineVersion_redis(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion_Redis(rName, "6.2"), + Config: testAccClusterConfig_engineVersionRedis(rName, "6.2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v5), testAccCheckClusterNotRecreated(&v4, &v5), @@ -654,7 +654,7 @@ func TestAccElastiCacheCluster_EngineVersion_redis(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion_Redis(rName, "5.0.6"), + Config: testAccClusterConfig_engineVersionRedis(rName, "5.0.6"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v6), testAccCheckClusterRecreated(&v5, &v6), @@ -663,7 +663,7 @@ func TestAccElastiCacheCluster_EngineVersion_redis(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion_Redis(rName, "6.x"), + Config: testAccClusterConfig_engineVersionRedis(rName, "6.x"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v7), testAccCheckClusterNotRecreated(&v6, &v7), @@ -672,7 +672,7 @@ func TestAccElastiCacheCluster_EngineVersion_redis(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion_Redis(rName, "6.0"), + Config: testAccClusterConfig_engineVersionRedis(rName, "6.0"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v8), testAccCheckClusterRecreated(&v7, &v8), @@ -700,14 +700,14 @@ func TestAccElastiCacheCluster_NodeTypeResize_memcached(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_NodeType_Memcached(rName, "cache.t3.small"), + Config: testAccClusterConfig_nodeTypeMemcached(rName, "cache.t3.small"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &pre), resource.TestCheckResourceAttr(resourceName, "node_type", "cache.t3.small"), ), }, { - Config: testAccClusterConfig_NodeType_Memcached(rName, "cache.t3.medium"), + Config: testAccClusterConfig_nodeTypeMemcached(rName, "cache.t3.medium"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &post), testAccCheckClusterRecreated(&pre, &post), @@ -734,14 +734,14 @@ func TestAccElastiCacheCluster_NodeTypeResize_redis(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_NodeType_Redis(rName, "cache.t3.small"), + Config: testAccClusterConfig_nodeTypeRedis(rName, "cache.t3.small"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &pre), resource.TestCheckResourceAttr(resourceName, "node_type", "cache.t3.small"), ), }, { - Config: testAccClusterConfig_NodeType_Redis(rName, "cache.t3.medium"), + Config: testAccClusterConfig_nodeTypeRedis(rName, "cache.t3.medium"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &post), testAccCheckClusterNotRecreated(&pre, &post), @@ -762,7 +762,7 @@ func TestAccElastiCacheCluster_NumCacheNodes_redis(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_NumCacheNodes_Redis(rName, 2), + Config: testAccClusterConfig_numCacheNodesRedis(rName, 2), ExpectError: regexp.MustCompile(`engine "redis" does not support num_cache_nodes > 1`), }, }, @@ -787,7 +787,7 @@ func TestAccElastiCacheCluster_ReplicationGroupID_availabilityZone(t *testing.T) CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_ReplicationGroupID_AvailabilityZone(rName), + Config: testAccClusterConfig_replicationGroupIDAvailabilityZone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(replicationGroupResourceName, &replicationGroup), testAccCheckClusterExists(clusterResourceName, &cluster), @@ -816,7 +816,7 @@ func TestAccElastiCacheCluster_ReplicationGroupID_singleReplica(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_ReplicationGroupID_Replica(rName, 1), + Config: testAccClusterConfig_replicationGroupIDReplica(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(replicationGroupResourceName, &replicationGroup), testAccCheckClusterExists(clusterResourceName, &cluster), @@ -849,7 +849,7 @@ func TestAccElastiCacheCluster_ReplicationGroupID_multipleReplica(t *testing.T) CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_ReplicationGroupID_Replica(rName, 2), + Config: testAccClusterConfig_replicationGroupIDReplica(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(replicationGroupResourceName, &replicationGroup), @@ -880,7 +880,7 @@ func TestAccElastiCacheCluster_Memcached_finalSnapshot(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Memcached_FinalSnapshot(rName), + Config: testAccClusterConfig_memcachedFinalSnapshot(rName), ExpectError: regexp.MustCompile(`engine "memcached" does not support final_snapshot_identifier`), }, }, @@ -903,7 +903,7 @@ func TestAccElastiCacheCluster_Redis_finalSnapshot(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Redis_FinalSnapshot(rName), + Config: testAccClusterConfig_redisFinalSnapshot(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "final_snapshot_identifier", rName), @@ -929,7 +929,7 @@ func TestAccElastiCacheCluster_Redis_autoMinorVersionUpgrade(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Redis_AutoMinorVersionUpgrade(rName, false), + Config: testAccClusterConfig_redisAutoMinorVersionUpgrade(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), @@ -944,7 +944,7 @@ func TestAccElastiCacheCluster_Redis_autoMinorVersionUpgrade(t *testing.T) { }, }, { - Config: testAccClusterConfig_Redis_AutoMinorVersionUpgrade(rName, true), + Config: testAccClusterConfig_redisAutoMinorVersionUpgrade(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "true"), @@ -970,7 +970,7 @@ func TestAccElastiCacheCluster_Engine_Redis_LogDeliveryConfigurations(t *testing CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), + Config: testAccClusterConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -991,7 +991,7 @@ func TestAccElastiCacheCluster_Engine_Redis_LogDeliveryConfigurations(t *testing ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccClusterConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), + Config: testAccClusterConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -1012,7 +1012,7 @@ func TestAccElastiCacheCluster_Engine_Redis_LogDeliveryConfigurations(t *testing ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccClusterConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), + Config: testAccClusterConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -1027,7 +1027,7 @@ func TestAccElastiCacheCluster_Engine_Redis_LogDeliveryConfigurations(t *testing ), }, { - Config: testAccClusterConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), + Config: testAccClusterConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -1042,7 +1042,7 @@ func TestAccElastiCacheCluster_Engine_Redis_LogDeliveryConfigurations(t *testing ), }, { - Config: testAccClusterConfig_Engine_Redis_LogDeliveryConfigurations(rName, false, "", "", false, "", ""), + Config: testAccClusterConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, false, "", "", false, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -1057,7 +1057,7 @@ func TestAccElastiCacheCluster_Engine_Redis_LogDeliveryConfigurations(t *testing ), }, { - Config: testAccClusterConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, false, "", ""), + Config: testAccClusterConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, false, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &ec), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -1097,7 +1097,7 @@ func TestAccElastiCacheCluster_tags(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfigTags1(rName, "key1", "value1"), + Config: testAccClusterConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1113,7 +1113,7 @@ func TestAccElastiCacheCluster_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately"}, //not in the API }, { - Config: testAccClusterConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccClusterConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1125,7 +1125,7 @@ func TestAccElastiCacheCluster_tags(t *testing.T) { ), }, { - Config: testAccClusterConfigTags1(rName, "key2", "value2"), + Config: testAccClusterConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1154,7 +1154,7 @@ func TestAccElastiCacheCluster_tagWithOtherModification(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterVersionAndTagConfig(rName, "5.0.4", "key1", "value1"), + Config: testAccClusterConfig_versionAndTag(rName, "5.0.4", "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "engine_version", "5.0.4"), @@ -1165,7 +1165,7 @@ func TestAccElastiCacheCluster_tagWithOtherModification(t *testing.T) { ), }, { - Config: testAccClusterVersionAndTagConfig(rName, "5.0.6", "key1", "value1updated"), + Config: testAccClusterConfig_versionAndTag(rName, "5.0.6", "key1", "value1updated"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "engine_version", "5.0.6"), @@ -1310,7 +1310,7 @@ func testAccCheckClusterEC2ClassicExists(n string, v *elasticache.CacheCluster) } } -func testAccClusterConfig_Engine_Memcached(rName string) string { +func testAccClusterConfig_engineMemcached(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = "%[1]s" @@ -1321,7 +1321,7 @@ resource "aws_elasticache_cluster" "test" { `, rName) } -func testAccClusterConfig_Engine_Redis(rName string) string { +func testAccClusterConfig_engineRedis(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = "%[1]s" @@ -1332,7 +1332,7 @@ resource "aws_elasticache_cluster" "test" { `, rName) } -func testAccClusterConfig_Engine_Redis_v5(rName string) string { +func testAccClusterConfig_engineRedisV5(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = "%[1]s" @@ -1344,7 +1344,7 @@ resource "aws_elasticache_cluster" "test" { `, rName) } -func testAccClusterConfig_Engine_None(rName string) string { +func testAccClusterConfig_engineNone(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = "%[1]s" @@ -1354,7 +1354,7 @@ resource "aws_elasticache_cluster" "test" { `, rName) } -func testAccClusterConfig_ParameterGroupName(rName, engine, engineVersion, parameterGroupName string) string { +func testAccClusterConfig_parameterGroupName(rName, engine, engineVersion, parameterGroupName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = %q @@ -1367,7 +1367,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, engine, engineVersion, parameterGroupName) } -func testAccClusterConfig_Port(rName string, port int) string { +func testAccClusterConfig_port(rName string, port int) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = "%s" @@ -1379,7 +1379,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, port) } -func testAccClusterConfig_SecurityGroup_EC2Classic(rName string) string { +func testAccClusterConfig_securityGroupEC2Classic(rName string) string { return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` @@ -1447,7 +1447,7 @@ resource "aws_elasticache_cluster" "test" { `, rName) } -func testAccClusterConfig_NumCacheNodes(rName string, numCacheNodes int) string { +func testAccClusterConfig_numCacheNodes(rName string, numCacheNodes int) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { apply_immediately = true @@ -1459,7 +1459,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, numCacheNodes) } -func testAccClusterConfig_NumCacheNodesWithPreferredAvailabilityZones(rName string, numCacheNodes int) string { +func testAccClusterConfig_numCacheNodesPreferredAvailabilityZones(rName string, numCacheNodes int) string { preferredAvailabilityZones := make([]string, numCacheNodes) for i := range preferredAvailabilityZones { preferredAvailabilityZones[i] = `data.aws_availability_zones.available.names[0]` @@ -1486,7 +1486,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, numCacheNodes, strings.Join(preferredAvailabilityZones, ",")) } -func testAccClusterInVPCConfig(rName string) string { +func testAccClusterConfig_inVPC(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1557,7 +1557,7 @@ resource "aws_sns_topic" "test" { `, rName) } -func testAccClusterMultiAZInVPCConfig(rName string) string { +func testAccClusterConfig_multiAZInVPC(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1635,7 +1635,7 @@ resource "aws_elasticache_cluster" "test" { `, rName) } -var testAccClusterConfig_RedisDefaultPort = ` +var testAccClusterConfig_redisDefaultPort = ` resource "aws_security_group" "test" { name = "tf-test-security-group" description = "tf-test-security-group-descr" @@ -1660,7 +1660,7 @@ resource "aws_elasticache_cluster" "test" { } ` -func testAccClusterConfig_AZMode_Memcached(rName, azMode string) string { +func testAccClusterConfig_azModeMemcached(rName, azMode string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { apply_immediately = true @@ -1674,7 +1674,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, azMode) } -func testAccClusterConfig_AZMode_Redis(rName, azMode string) string { +func testAccClusterConfig_azModeRedis(rName, azMode string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { apply_immediately = true @@ -1688,7 +1688,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, azMode) } -func testAccClusterConfig_EngineVersion_Memcached(rName, engineVersion string) string { +func testAccClusterConfig_engineVersionMemcached(rName, engineVersion string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { apply_immediately = true @@ -1702,7 +1702,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, engineVersion) } -func testAccClusterConfig_EngineVersion_Redis(rName, engineVersion string) string { +func testAccClusterConfig_engineVersionRedis(rName, engineVersion string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { apply_immediately = true @@ -1716,7 +1716,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, engineVersion) } -func testAccClusterConfig_NodeType_Memcached(rName, nodeType string) string { +func testAccClusterConfig_nodeTypeMemcached(rName, nodeType string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { apply_immediately = true @@ -1729,7 +1729,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, nodeType) } -func testAccClusterConfig_NodeType_Redis(rName, nodeType string) string { +func testAccClusterConfig_nodeTypeRedis(rName, nodeType string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { apply_immediately = true @@ -1742,7 +1742,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, nodeType) } -func testAccClusterConfig_NumCacheNodes_Redis(rName string, numCacheNodes int) string { +func testAccClusterConfig_numCacheNodesRedis(rName string, numCacheNodes int) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { apply_immediately = true @@ -1755,7 +1755,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, numCacheNodes) } -func testAccClusterConfig_ReplicationGroupID_AvailabilityZone(rName string) string { +func testAccClusterConfig_replicationGroupIDAvailabilityZone(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1786,7 +1786,7 @@ resource "aws_elasticache_cluster" "test" { `, rName) } -func testAccClusterConfig_ReplicationGroupID_Replica(rName string, count int) string { +func testAccClusterConfig_replicationGroupIDReplica(rName string, count int) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_description = "Terraform Acceptance Testing" @@ -1808,7 +1808,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, count) } -func testAccClusterConfig_Memcached_FinalSnapshot(rName string) string { +func testAccClusterConfig_memcachedFinalSnapshot(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = %[1]q @@ -1821,7 +1821,7 @@ resource "aws_elasticache_cluster" "test" { `, rName) } -func testAccClusterConfig_Redis_FinalSnapshot(rName string) string { +func testAccClusterConfig_redisFinalSnapshot(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = %[1]q @@ -1834,7 +1834,7 @@ resource "aws_elasticache_cluster" "test" { `, rName) } -func testAccClusterConfig_Redis_AutoMinorVersionUpgrade(rName string, enable bool) string { +func testAccClusterConfig_redisAutoMinorVersionUpgrade(rName string, enable bool) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { cluster_id = %[1]q @@ -1848,7 +1848,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, enable) } -func testAccClusterConfig_Engine_Redis_LogDeliveryConfigurations(rName string, slowLogDeliveryEnabled bool, slowDeliveryDestination string, slowDeliveryFormat string, engineLogDeliveryEnabled bool, engineDeliveryDestination string, engineLogDeliveryFormat string) string { +func testAccClusterConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName string, slowLogDeliveryEnabled bool, slowDeliveryDestination string, slowDeliveryFormat string, engineLogDeliveryEnabled bool, engineDeliveryDestination string, engineLogDeliveryFormat string) string { return fmt.Sprintf(` data "aws_iam_policy_document" "p" { statement { @@ -1966,7 +1966,7 @@ data "aws_elasticache_cluster" "test" { } -func testAccClusterConfigTags1(rName, tag1Key, tag1Value string) string { +func testAccClusterConfig_tags1(rName, tag1Key, tag1Value string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1983,7 +1983,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, tag1Key, tag1Value)) } -func testAccClusterConfigTags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccClusterConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2001,7 +2001,7 @@ resource "aws_elasticache_cluster" "test" { `, rName, tag1Key, tag1Value, tag2Key, tag2Value)) } -func testAccClusterVersionAndTagConfig(rName, version, tagKey1, tagValue1 string) string { +func testAccClusterConfig_versionAndTag(rName, version, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { diff --git a/internal/service/elasticache/engine_version.go b/internal/service/elasticache/engine_version.go index 841c6d256ee..7a8d79b3713 100644 --- a/internal/service/elasticache/engine_version.go +++ b/internal/service/elasticache/engine_version.go @@ -6,6 +6,7 @@ import ( "math" "regexp" + "github.com/aws/aws-sdk-go/aws" multierror "github.com/hashicorp/go-multierror" gversion "github.com/hashicorp/go-version" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -88,29 +89,39 @@ func customizeDiffEngineVersionForceNewOnDowngrade(_ context.Context, diff *sche return engineVersionForceNewOnDowngrade(diff) } -type forceNewDiffer interface { - Id() string - HasChange(key string) bool +type getChangeDiffer interface { GetChange(key string) (interface{}, interface{}) - ForceNew(key string) error } -func engineVersionForceNewOnDowngrade(diff forceNewDiffer) error { - if diff.Id() == "" || !diff.HasChange("engine_version") { - return nil - } - +func engineVersionIsDowngrade(diff getChangeDiffer) (bool, error) { o, n := diff.GetChange("engine_version") oVersion, err := normalizeEngineVersion(o.(string)) if err != nil { - return fmt.Errorf("error parsing old engine_version: %w", err) + return false, fmt.Errorf("error parsing old engine_version: %w", err) } nVersion, err := normalizeEngineVersion(n.(string)) if err != nil { - return fmt.Errorf("error parsing new engine_version: %w", err) + return false, fmt.Errorf("error parsing new engine_version: %w", err) + } + + return nVersion.LessThan(oVersion), nil +} + +type forceNewDiffer interface { + Id() string + GetChange(key string) (interface{}, interface{}) + HasChange(key string) bool + ForceNew(key string) error +} + +func engineVersionForceNewOnDowngrade(diff forceNewDiffer) error { + if diff.Id() == "" || !diff.HasChange("engine_version") { + return nil } - if nVersion.GreaterThan(oVersion) || nVersion.Equal(oVersion) { + if downgrade, err := engineVersionIsDowngrade(diff); err != nil { + return err + } else if !downgrade { return nil } @@ -130,3 +141,56 @@ func normalizeEngineVersion(version string) (*gversion.Version, error) { } return gversion.NewVersion(version) } + +func setEngineVersionMemcached(d *schema.ResourceData, version *string) { + d.Set("engine_version", version) + d.Set("engine_version_actual", version) +} + +func setEngineVersionRedis(d *schema.ResourceData, version *string) error { + engineVersion, err := gversion.NewVersion(aws.StringValue(version)) + if err != nil { + return fmt.Errorf("error reading engine version: %w", err) + } + if engineVersion.Segments()[0] < 6 { + d.Set("engine_version", engineVersion.String()) + } else { + // Handle major-only version number + configVersion := d.Get("engine_version").(string) + if t, _ := regexp.MatchString(`[6-9]\.x`, configVersion); t { + d.Set("engine_version", fmt.Sprintf("%d.x", engineVersion.Segments()[0])) + } else { + d.Set("engine_version", fmt.Sprintf("%d.%d", engineVersion.Segments()[0], engineVersion.Segments()[1])) + } + } + d.Set("engine_version_actual", engineVersion.String()) + + return nil +} + +type versionDiff [3]int + +// diffVersion returns a diff of the versions, component by component. +// Only reports the first diff, since subsequent segments are unimportant for us. +func diffVersion(n, o *gversion.Version) (result versionDiff) { + if n.String() == o.String() { + return + } + + segmentsNew := n.Segments64() + segmentsOld := o.Segments64() + + for i := 0; i < 3; i++ { + lhs := segmentsNew[i] + rhs := segmentsOld[i] + if lhs < rhs { + result[i] = -1 + break + } else if lhs > rhs { + result[i] = 1 + break + } + } + + return +} diff --git a/internal/service/elasticache/engine_version_test.go b/internal/service/elasticache/engine_version_test.go index 740031622d8..00dd5f2db96 100644 --- a/internal/service/elasticache/engine_version_test.go +++ b/internal/service/elasticache/engine_version_test.go @@ -3,7 +3,10 @@ package elasticache import ( "fmt" "math" + "regexp" "testing" + + "github.com/hashicorp/go-version" ) func TestValidMemcachedVersionString(t *testing.T) { @@ -227,26 +230,132 @@ func TestValidateClusterEngineVersion(t *testing.T) { } } -type differ struct { +type mockGetChangeDiffer struct { + old, new string +} + +func (d *mockGetChangeDiffer) GetChange(key string) (interface{}, interface{}) { + return d.old, d.new +} + +func TestCustomizeDiffEngineVersionIsDowngrade(t *testing.T) { + testcases := map[string]struct { + old, new string + expected bool + }{ + "no change": { + old: "1.2.3", + new: "1.2.3", + expected: false, + }, + + "upgrade minor versions": { + old: "1.2.3", + new: "1.3.5", + expected: false, + }, + + "upgrade major versions": { + old: "1.2.3", + new: "2.4.6", + expected: false, + }, + + // "upgrade major 6.x": { + // old: "5.0.6", + // new: "6.x", + // expectForceNew: false, + // }, + + // "upgrade major 6.digit": { + // old: "5.0.6", + // new: "6.0", + // expectForceNew: false, + // }, + + "downgrade minor versions": { + old: "1.3.5", + new: "1.2.3", + expected: true, + }, + + "downgrade major versions": { + old: "2.4.6", + new: "1.2.3", + expected: true, + }, + + "downgrade from major 6.x": { + old: "6.x", + new: "5.0.6", + expected: true, + }, + + "downgrade major 6.digit": { + old: "6.2", + new: "6.0", + expected: true, + }, + + "switch major 6.digit to 6.x": { + old: "6.2", + new: "6.x", + expected: false, + }, + + "downgrade from major 7.x to 6.x": { + old: "7.x", + new: "6.x", + expected: true, + }, + + "downgrade from major 7.digit to 6.x": { + old: "7.2", + new: "6.x", + expected: true, + }, + } + + for name, testcase := range testcases { + t.Run(name, func(t *testing.T) { + diff := &mockGetChangeDiffer{ + old: testcase.old, + new: testcase.new, + } + + actual, err := engineVersionIsDowngrade(diff) + + if err != nil { + t.Fatalf("no error expected, got %s", err) + } + + if testcase.expected != actual { + t.Errorf("expected %t, got %t", testcase.expected, actual) + } + }) + } +} + +type mockForceNewDiffer struct { id string old, new string hasChange bool // force HasChange() to return true forceNew bool } -func (d *differ) Id() string { +func (d *mockForceNewDiffer) Id() string { return d.id } -func (d *differ) HasChange(key string) bool { +func (d *mockForceNewDiffer) HasChange(key string) bool { return d.hasChange || d.old != d.new } -func (d *differ) GetChange(key string) (interface{}, interface{}) { +func (d *mockForceNewDiffer) GetChange(key string) (interface{}, interface{}) { return d.old, d.new } -func (d *differ) ForceNew(key string) error { +func (d *mockForceNewDiffer) ForceNew(key string) error { d.forceNew = true return nil @@ -346,7 +455,7 @@ func TestCustomizeDiffEngineVersionForceNewOnDowngrade(t *testing.T) { for name, testcase := range testcases { t.Run(name, func(t *testing.T) { - diff := &differ{} + diff := &mockForceNewDiffer{} if !testcase.isNew { diff.id = "some id" diff.old = testcase.old @@ -419,3 +528,184 @@ func TestNormalizeEngineVersion(t *testing.T) { }) } } + +func TestVersionDiff(t *testing.T) { + cases := []struct { + v1 string + v2 string + expected versionDiff + }{ + {"1.2.3", "1.2.3", versionDiff{0, 0, 0}}, + {"1.2.3", "1.1.7", versionDiff{0, 1, 0}}, + {"1.2.3", "1.4.5", versionDiff{0, -1, 0}}, + {"2.0.0", "1.2.3", versionDiff{1, 0, 0}}, + {"1.2.3", "2.0.0", versionDiff{-1, 0, 0}}, + {"1.2.3", "1.2.1", versionDiff{0, 0, 1}}, + {"1.2.3", "1.2.4", versionDiff{0, 0, -1}}, + } + + for _, tc := range cases { + v1, err := version.NewVersion(tc.v1) + if err != nil { + t.Fatalf("err: %s", err) + } + + v2, err := version.NewVersion(tc.v2) + if err != nil { + t.Fatalf("err: %s", err) + } + + actual := diffVersion(v1, v2) + expected := tc.expected + if actual != expected { + t.Fatalf( + "%s <=> %s\nexpected: %d\nactual: %d", + tc.v1, tc.v2, + expected, actual) + } + } +} + +type mockDiff struct { + old, new string + hasChange bool // force HasChange() to return true +} + +func (d mockDiff) HasChange() bool { + return d.hasChange || d.old != d.new +} + +func (d mockDiff) GetChange() (interface{}, interface{}) { + return d.old, d.new +} + +type mockChangesDiffer struct { + id string + values map[string]mockDiff +} + +func (d *mockChangesDiffer) Id() string { + return d.id +} + +func (d *mockChangesDiffer) HasChange(key string) bool { + return d.values[key].HasChange() +} + +func (d *mockChangesDiffer) GetChange(key string) (interface{}, interface{}) { + return d.values[key].GetChange() +} + +func TestParamGroupNameRequiresMajorVersionUpgrade(t *testing.T) { + testcases := map[string]struct { + isNew bool + paramOld, paramNew string + paramHasChange bool + versionOld, versionNew string + versionHasChange bool + expectError *regexp.Regexp + }{ + "new resource, no param group set": { + isNew: true, + paramOld: "", + paramNew: "", + }, + + "new resource, param group spurious diff": { + isNew: true, + paramOld: "", + paramNew: "", + paramHasChange: true, + }, + + "new resource, set param group, no version set": { + isNew: true, + paramOld: "old", + paramNew: "", + expectError: regexp.MustCompile(`cannot change parameter group name without upgrading major engine version`), + }, + + // new resource with version changes can only be verified at apply-time + + "update, no param group change": { + paramOld: "no-change", + paramNew: "no-change", + }, + + "update, param group spurious diff": { + paramOld: "no-change", + paramNew: "no-change", + paramHasChange: true, + }, + + "update, param group change, no version change": { + paramOld: "old", + paramNew: "new", + versionOld: "6.0", + versionNew: "6.0", + expectError: regexp.MustCompile(`cannot change parameter group name without upgrading major engine version`), + }, + + "update, param group change, version spurious diff": { + paramOld: "old", + paramNew: "new", + versionOld: "6.0", + versionNew: "6.0", + versionHasChange: true, + expectError: regexp.MustCompile(`cannot change parameter group name without upgrading major engine version`), + }, + + "update, param group change, minor version change": { + paramOld: "old", + paramNew: "new", + versionOld: "6.0", + versionNew: "6.2", + expectError: regexp.MustCompile(`cannot change parameter group name on minor engine version upgrade, upgrading from 6\.0\.[[:digit:]]+ to 6\.2\.[[:digit:]]+`), + }, + + "update, param group change, major version change": { + paramOld: "old", + paramNew: "new", + versionOld: "5.0.6", + versionNew: "6.2", + }, + } + + for name, testcase := range testcases { + t.Run(name, func(t *testing.T) { + diff := &mockChangesDiffer{ + values: map[string]mockDiff{ + "parameter_group_name": { + old: testcase.paramOld, + new: testcase.paramNew, + hasChange: testcase.paramHasChange, + }, + "engine_version": { + old: testcase.versionOld, + new: testcase.versionNew, + hasChange: testcase.versionHasChange, + }, + }, + } + if !testcase.isNew { + diff.id = "some id" + } + + err := paramGroupNameRequiresMajorVersionUpgrade(diff) + + if testcase.expectError == nil { + if err != nil { + t.Fatalf("no error expected, got %s", err) + } + } else { + if err == nil { + t.Fatalf("expected error, got none") + } + if !testcase.expectError.MatchString(err.Error()) { + t.Fatalf("unexpected error: %q", err.Error()) + } + } + + }) + } +} diff --git a/internal/service/elasticache/find.go b/internal/service/elasticache/find.go index fd1abd54986..b5190f81e6c 100644 --- a/internal/service/elasticache/find.go +++ b/internal/service/elasticache/find.go @@ -7,6 +7,7 @@ import ( "github.com/aws/aws-sdk-go/service/elasticache" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) // FindReplicationGroupByID retrieves an ElastiCache Replication Group by id. @@ -213,16 +214,38 @@ func FindUserGroupByID(conn *elasticache.ElastiCache, groupID string) (*elastica return nil, err } - switch len(out.UserGroups) { + switch count := len(out.UserGroups); count { case 0: - return nil, &resource.NotFoundError{ - Message: "empty result", - } + return nil, tfresource.NewEmptyResultError(input) case 1: return out.UserGroups[0], nil default: + return nil, tfresource.NewTooManyResultsError(count, input) + } +} + +func FindParameterGroupByName(conn *elasticache.ElastiCache, name string) (*elasticache.CacheParameterGroup, error) { + input := elasticache.DescribeCacheParameterGroupsInput{ + CacheParameterGroupName: aws.String(name), + } + out, err := conn.DescribeCacheParameterGroups(&input) + + if tfawserr.ErrCodeEquals(err, elasticache.ErrCodeCacheParameterGroupNotFoundFault) { return nil, &resource.NotFoundError{ - Message: "too many results", + LastError: err, + LastRequest: input, } } + if err != nil { + return nil, err + } + + switch count := len(out.CacheParameterGroups); count { + case 0: + return nil, tfresource.NewEmptyResultError(input) + case 1: + return out.CacheParameterGroups[0], nil + default: + return nil, tfresource.NewTooManyResultsError(count, input) + } } diff --git a/internal/service/elasticache/global_replication_group.go b/internal/service/elasticache/global_replication_group.go index aab6e8acf3d..991e6a86566 100644 --- a/internal/service/elasticache/global_replication_group.go +++ b/internal/service/elasticache/global_replication_group.go @@ -1,6 +1,8 @@ package elasticache import ( + "context" + "errors" "fmt" "log" "regexp" @@ -9,6 +11,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elasticache" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + gversion "github.com/hashicorp/go-version" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -68,11 +72,22 @@ func ResourceGlobalReplicationGroup() *schema.Resource { Type: schema.TypeString, Computed: true, }, - // Leaving space for `engine_version` for creation and updating. - // `engine_version` cannot be used for returning the version because, starting with Redis 6, - // version configuration is major-version-only: `engine_version = "6.x"` or major-minor-version-only: `engine_version = "6.2"`, - // while `engine_version_actual` will be the full version e.g. `6.0.5` - // See also https://github.com/hashicorp/terraform-provider-aws/issues/15625 + "engine_version": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validRedisVersionString, + DiffSuppressFunc: func(_, old, new string, _ *schema.ResourceData) bool { + if t, _ := regexp.MatchString(`[6-9]\.x`, new); t && old != "" { + oldVersion, err := gversion.NewVersion(old) + if err != nil { + return false + } + return oldVersion.Segments()[0] >= 6 + } + return false + }, + }, "engine_version_actual": { Type: schema.TypeString, Computed: true, @@ -114,6 +129,10 @@ func ResourceGlobalReplicationGroup() *schema.Resource { // }, // }, // }, + "parameter_group_name": { + Type: schema.TypeString, + Optional: true, + }, "primary_replication_group_id": { Type: schema.TypeString, Required: true, @@ -125,10 +144,15 @@ func ResourceGlobalReplicationGroup() *schema.Resource { Computed: true, }, }, + + CustomizeDiff: customdiff.Sequence( + customizeDiffGlobalReplicationGroupEngineVersionErrorOnDowngrade, + customizeDiffGlobalReplicationGroupParamGroupNameRequiresMajorVersionUpgrade, + ), } } -func descriptionDiffSuppress(_, old, new string, d *schema.ResourceData) bool { +func descriptionDiffSuppress(_, old, new string, _ *schema.ResourceData) bool { if (old == EmptyDescription && new == "") || (old == "" && new == EmptyDescription) { return true } @@ -143,6 +167,66 @@ func descriptionStateFunc(v interface{}) string { return s } +func customizeDiffGlobalReplicationGroupEngineVersionErrorOnDowngrade(_ context.Context, diff *schema.ResourceDiff, _ interface{}) error { + if diff.Id() == "" || !diff.HasChange("engine_version") { + return nil + } + + if downgrade, err := engineVersionIsDowngrade(diff); err != nil { + return err + } else if !downgrade { + return nil + } + + return fmt.Errorf(`Downgrading Elasticache Global Replication Group (%s) engine version requires replacement +of the Global Replication Group and all Replication Group members. The AWS provider cannot handle this internally. + +Please use the "-replace" option on the terraform plan and apply commands (see https://www.terraform.io/cli/commands/plan#replace-address).`, diff.Id()) +} + +type changesDiffer interface { + Id() string + GetChange(key string) (interface{}, interface{}) + HasChange(key string) bool +} + +func customizeDiffGlobalReplicationGroupParamGroupNameRequiresMajorVersionUpgrade(_ context.Context, diff *schema.ResourceDiff, _ interface{}) error { + return paramGroupNameRequiresMajorVersionUpgrade(diff) +} + +// parameter_group_name can only be set when doing a major update, +// but we also should allow it to stay set afterwards +func paramGroupNameRequiresMajorVersionUpgrade(diff changesDiffer) error { + o, n := diff.GetChange("parameter_group_name") + if o.(string) == n.(string) { + return nil + } + + if diff.Id() == "" { + if !diff.HasChange("engine_version") { + return errors.New("cannot change parameter group name without upgrading major engine version") + } + } + + // cannot check for major version upgrade at plan time for new resource + if diff.Id() != "" { + o, n := diff.GetChange("engine_version") + + newVersion, _ := normalizeEngineVersion(n.(string)) + oldVersion, _ := gversion.NewVersion(o.(string)) + + vDiff := diffVersion(newVersion, oldVersion) + if vDiff[0] == 0 && vDiff[1] == 0 { + return errors.New("cannot change parameter group name without upgrading major engine version") + } + if vDiff[0] != 1 { + return fmt.Errorf("cannot change parameter group name on minor engine version upgrade, upgrading from %s to %s", oldVersion.String(), newVersion.String()) + } + } + + return nil +} + func resourceGlobalReplicationGroupCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ElastiCacheConn @@ -160,12 +244,51 @@ func resourceGlobalReplicationGroupCreate(d *schema.ResourceData, meta interface return fmt.Errorf("error creating ElastiCache Global Replication Group: %w", err) } + if output == nil || output.GlobalReplicationGroup == nil { + return errors.New("error creating ElastiCache Global Replication Group: empty result") + } + d.SetId(aws.StringValue(output.GlobalReplicationGroup.GlobalReplicationGroupId)) - if _, err := WaitGlobalReplicationGroupAvailable(conn, d.Id(), GlobalReplicationGroupDefaultCreatedTimeout); err != nil { + globalReplicationGroup, err := WaitGlobalReplicationGroupAvailable(conn, d.Id(), GlobalReplicationGroupDefaultCreatedTimeout) + if err != nil { return fmt.Errorf("error waiting for ElastiCache Global Replication Group (%s) creation: %w", d.Id(), err) } + if v, ok := d.GetOk("engine_version"); ok { + requestedVersion, _ := normalizeEngineVersion(v.(string)) + + engineVersion, err := gversion.NewVersion(aws.StringValue(globalReplicationGroup.EngineVersion)) + if err != nil { + return fmt.Errorf("error updating ElastiCache Global Replication Group (%s) engine version on creation: error reading engine version: %w", d.Id(), err) + } + + diff := diffVersion(requestedVersion, engineVersion) + + if diff[0] == -1 || diff[1] == -1 { // Ignore patch version downgrade + return fmt.Errorf("error updating ElastiCache Global Replication Group (%s) engine version on creation: cannot downgrade version when creating, is %s, want %s", d.Id(), engineVersion.String(), requestedVersion.String()) + } + + p := d.Get("parameter_group_name").(string) + + if diff[0] == 1 { + err := updateGlobalReplicationGroup(conn, d.Id(), globalReplicationGroupEngineVersionMajorUpdater(v.(string), p)) + if err != nil { + return fmt.Errorf("error updating ElastiCache Global Replication Group (%s) engine version on creation: %w", d.Id(), err) + } + } else if diff[1] == 1 { + if p != "" { + return fmt.Errorf("cannot change parameter group name on minor engine version upgrade, upgrading from %s to %s", engineVersion.String(), requestedVersion.String()) + } + if t, _ := regexp.MatchString(`[6-9]\.x`, v.(string)); !t { + err := updateGlobalReplicationGroup(conn, d.Id(), globalReplicationGroupEngineVersionMinorUpdater(v.(string))) + if err != nil { + return fmt.Errorf("error updating ElastiCache Global Replication Group (%s) engine version on creation: %w", d.Id(), err) + } + } + } + } + return resourceGlobalReplicationGroupRead(d, meta) } @@ -194,25 +317,50 @@ func resourceGlobalReplicationGroupRead(d *schema.ResourceData, meta interface{} d.Set("cache_node_type", globalReplicationGroup.CacheNodeType) d.Set("cluster_enabled", globalReplicationGroup.ClusterEnabled) d.Set("engine", globalReplicationGroup.Engine) - d.Set("engine_version_actual", globalReplicationGroup.EngineVersion) d.Set("global_replication_group_description", globalReplicationGroup.GlobalReplicationGroupDescription) d.Set("global_replication_group_id", globalReplicationGroup.GlobalReplicationGroupId) d.Set("transit_encryption_enabled", globalReplicationGroup.TransitEncryptionEnabled) + err = setEngineVersionRedis(d, globalReplicationGroup.EngineVersion) + if err != nil { + return fmt.Errorf("error reading ElastiCache Replication Group: %w", err) + } + d.Set("primary_replication_group_id", flattenGlobalReplicationGroupPrimaryGroupID(globalReplicationGroup.Members)) return nil } +type globalReplicationGroupUpdater func(input *elasticache.ModifyGlobalReplicationGroupInput) + func resourceGlobalReplicationGroupUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ElastiCacheConn + if d.HasChange("engine_version") { + o, n := d.GetChange("engine_version") + + newVersion, _ := normalizeEngineVersion(n.(string)) + oldVersion, _ := gversion.NewVersion(o.(string)) + + diff := diffVersion(newVersion, oldVersion) + if diff[0] == 1 { + p := d.Get("parameter_group_name").(string) + err := updateGlobalReplicationGroup(conn, d.Id(), globalReplicationGroupEngineVersionMajorUpdater(n.(string), p)) + if err != nil { + return fmt.Errorf("error updating ElastiCache Global Replication Group (%s): %w", d.Id(), err) + } + } else if diff[1] == 1 { + err := updateGlobalReplicationGroup(conn, d.Id(), globalReplicationGroupEngineVersionMinorUpdater(n.(string))) + if err != nil { + return fmt.Errorf("error updating ElastiCache Global Replication Group (%s): %w", d.Id(), err) + } + } + } + // Only one field can be changed per request updaters := map[string]globalReplicationGroupUpdater{} - if !d.IsNewResource() { - updaters["global_replication_group_description"] = func(input *elasticache.ModifyGlobalReplicationGroupInput) { - input.GlobalReplicationGroupDescription = aws.String(d.Get("global_replication_group_description").(string)) - } + updaters["global_replication_group_description"] = func(input *elasticache.ModifyGlobalReplicationGroupInput) { + input.GlobalReplicationGroupDescription = aws.String(d.Get("global_replication_group_description").(string)) } for k, f := range updaters { @@ -226,7 +374,18 @@ func resourceGlobalReplicationGroupUpdate(d *schema.ResourceData, meta interface return resourceGlobalReplicationGroupRead(d, meta) } -type globalReplicationGroupUpdater func(input *elasticache.ModifyGlobalReplicationGroupInput) +func globalReplicationGroupEngineVersionMinorUpdater(version string) globalReplicationGroupUpdater { + return func(input *elasticache.ModifyGlobalReplicationGroupInput) { + input.EngineVersion = aws.String(version) + } +} + +func globalReplicationGroupEngineVersionMajorUpdater(version, paramGroupName string) globalReplicationGroupUpdater { + return func(input *elasticache.ModifyGlobalReplicationGroupInput) { + input.EngineVersion = aws.String(version) + input.CacheParameterGroupName = aws.String(paramGroupName) + } +} func updateGlobalReplicationGroup(conn *elasticache.ElastiCache, id string, f globalReplicationGroupUpdater) error { input := &elasticache.ModifyGlobalReplicationGroupInput{ diff --git a/internal/service/elasticache/global_replication_group_test.go b/internal/service/elasticache/global_replication_group_test.go index 020fbf2a594..9827027c033 100644 --- a/internal/service/elasticache/global_replication_group_test.go +++ b/internal/service/elasticache/global_replication_group_test.go @@ -25,6 +25,7 @@ func TestAccElastiCacheGlobalReplicationGroup_basic(t *testing.T) { var globalReplicationGroup elasticache.GlobalReplicationGroup var primaryReplicationGroup elasticache.ReplicationGroup + var pg elasticache.CacheParameterGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -32,6 +33,525 @@ func TestAccElastiCacheGlobalReplicationGroup_basic(t *testing.T) { resourceName := "aws_elasticache_global_replication_group.test" primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupDestroy, + testAccCheckGlobalReplicationGroupMemberParameterGroupDestroy(&pg), + ), + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_basic(rName, primaryReplicationGroupId), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + testAccCheckReplicationGroupExists(primaryReplicationGroupResourceName, &primaryReplicationGroup), + testAccCheckReplicationGroupParameterGroup(&primaryReplicationGroup, &pg), + acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "elasticache", regexp.MustCompile(`globalreplicationgroup:`+tfelasticache.GlobalReplicationGroupRegionPrefixFormat+rName)), + resource.TestCheckResourceAttrPair(resourceName, "at_rest_encryption_enabled", primaryReplicationGroupResourceName, "at_rest_encryption_enabled"), + resource.TestCheckResourceAttr(resourceName, "auth_token_enabled", "false"), + resource.TestCheckResourceAttrPair(resourceName, "cache_node_type", primaryReplicationGroupResourceName, "node_type"), + resource.TestCheckResourceAttrPair(resourceName, "cluster_enabled", primaryReplicationGroupResourceName, "cluster_enabled"), + resource.TestCheckResourceAttrPair(resourceName, "engine", primaryReplicationGroupResourceName, "engine"), + resource.TestCheckResourceAttrPair(resourceName, "engine_version_actual", primaryReplicationGroupResourceName, "engine_version_actual"), + resource.TestCheckResourceAttr(resourceName, "global_replication_group_id_suffix", rName), + resource.TestMatchResourceAttr(resourceName, "global_replication_group_id", regexp.MustCompile(tfelasticache.GlobalReplicationGroupRegionPrefixFormat+rName)), + resource.TestCheckResourceAttr(resourceName, "global_replication_group_description", tfelasticache.EmptyDescription), + resource.TestCheckResourceAttr(resourceName, "primary_replication_group_id", primaryReplicationGroupId), + resource.TestCheckResourceAttr(resourceName, "transit_encryption_enabled", "false"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_description(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + description1 := sdkacctest.RandString(10) + description2 := sdkacctest.RandString(10) + resourceName := "aws_elasticache_global_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_description(rName, primaryReplicationGroupId, description1), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestCheckResourceAttr(resourceName, "global_replication_group_description", description1), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccGlobalReplicationGroupConfig_description(rName, primaryReplicationGroupId, description2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestCheckResourceAttr(resourceName, "global_replication_group_description", description2), + ), + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_disappears(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_basic(rName, primaryReplicationGroupId), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + acctest.CheckResourceDisappears(acctest.Provider, tfelasticache.ResourceGlobalReplicationGroup(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_multipleSecondaries(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var providers []*schema.Provider + var globalReplcationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckMultipleRegion(t, 3) + }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 3), + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_multipleSecondaries(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplcationGroup), + ), + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_ReplaceSecondary_differentRegion(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var providers []*schema.Provider + var globalReplcationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckMultipleRegion(t, 3) + }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 3), + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_replaceSecondaryDifferentRegionSetup(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplcationGroup), + ), + }, + { + Config: testAccGlobalReplicationGroupConfig_replaceSecondaryDifferentRegionMove(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplcationGroup), + ), + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_clusterMode(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + var primaryReplicationGroup elasticache.ReplicationGroup + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_clusterMode(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + testAccCheckReplicationGroupExists(primaryReplicationGroupResourceName, &primaryReplicationGroup), + resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnCreate_NoChange_v6(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "6.2", "6.2"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnCreate_NoChange_v6x(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "6.2", "6.x"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"engine_version"}, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnCreate_NoChange_v5(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "5.0.6", "5.0.6"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestCheckResourceAttr(resourceName, "engine_version_actual", "5.0.6"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnCreate_MinorUpgrade(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + var rg elasticache.ReplicationGroup + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "6.0", "6.2"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + testAccCheckReplicationGroupExists(primaryReplicationGroupResourceName, &rg), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + testAccMatchReplicationGroupActualVersion(&rg, regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnCreate_MinorUpgrade_6x(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + var rg elasticache.ReplicationGroup + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "6.0", "6.x"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + testAccCheckReplicationGroupExists(primaryReplicationGroupResourceName, &rg), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.0\.[[:digit:]]+$`)), + testAccMatchReplicationGroupActualVersion(&rg, regexp.MustCompile(`^6\.0\.[[:digit:]]+$`)), + ), + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnCreate_MajorUpgrade(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + var rg elasticache.ReplicationGroup + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersionParam(rName, primaryReplicationGroupId, "5.0.6", "6.2", "default.redis6.x"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + testAccCheckReplicationGroupExists(primaryReplicationGroupResourceName, &rg), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + testAccMatchReplicationGroupActualVersion(&rg, regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"parameter_group_name"}, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnCreate_MajorUpgrade_6x(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + var rg elasticache.ReplicationGroup + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersionParam(rName, primaryReplicationGroupId, "5.0.6", "6.2", "default.redis6.x"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + testAccCheckReplicationGroupExists(primaryReplicationGroupResourceName, &rg), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + testAccMatchReplicationGroupActualVersion(&rg, regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"parameter_group_name"}, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnCreate_MinorDowngrade(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "6.2", "6.0"), + ExpectError: regexp.MustCompile(`cannot downgrade version when creating, is 6.2.[[:digit:]]+, want 6.0.[[:digit:]]+`), + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetParameterGroupOnCreate_NoVersion(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_param(rName, primaryReplicationGroupId, "6.2", "default.redis6.x"), + ExpectError: regexp.MustCompile(`cannot change parameter group name without upgrading major engine version`), + PlanOnly: true, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetParameterGroupOnCreate_MinorUpgrade(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersionParam(rName, primaryReplicationGroupId, "6.0", "6.2", "default.redis6.x"), + ExpectError: regexp.MustCompile(`cannot change parameter group name on minor engine version upgrade, upgrading from 6\.0\.[[:digit:]]+ to 6\.2\.[[:digit:]]+`), + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnUpdate_MinorUpgrade(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), @@ -39,34 +559,25 @@ func TestAccElastiCacheGlobalReplicationGroup_basic(t *testing.T) { CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalReplicationGroupConfig_basic(rName, primaryReplicationGroupId), - Check: resource.ComposeTestCheckFunc( + Config: testAccGlobalReplicationGroupConfig_engineVersionInherit(rName, primaryReplicationGroupId, "6.0"), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), - testAccCheckReplicationGroupExists(primaryReplicationGroupResourceName, &primaryReplicationGroup), - acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "elasticache", regexp.MustCompile(`globalreplicationgroup:`+tfelasticache.GlobalReplicationGroupRegionPrefixFormat+rName)), - resource.TestCheckResourceAttrPair(resourceName, "at_rest_encryption_enabled", primaryReplicationGroupResourceName, "at_rest_encryption_enabled"), - resource.TestCheckResourceAttr(resourceName, "auth_token_enabled", "false"), - resource.TestCheckResourceAttrPair(resourceName, "cache_node_type", primaryReplicationGroupResourceName, "node_type"), - resource.TestCheckResourceAttrPair(resourceName, "cluster_enabled", primaryReplicationGroupResourceName, "cluster_enabled"), - resource.TestCheckResourceAttrPair(resourceName, "engine", primaryReplicationGroupResourceName, "engine"), - resource.TestCheckResourceAttrPair(resourceName, "engine_version_actual", primaryReplicationGroupResourceName, "engine_version"), - resource.TestCheckResourceAttr(resourceName, "global_replication_group_id_suffix", rName), - resource.TestMatchResourceAttr(resourceName, "global_replication_group_id", regexp.MustCompile(tfelasticache.GlobalReplicationGroupRegionPrefixFormat+rName)), - resource.TestCheckResourceAttr(resourceName, "global_replication_group_description", tfelasticache.EmptyDescription), - resource.TestCheckResourceAttr(resourceName, "primary_replication_group_id", primaryReplicationGroupId), - resource.TestCheckResourceAttr(resourceName, "transit_encryption_enabled", "false"), + resource.TestCheckResourceAttrPair(resourceName, "engine_version_actual", primaryReplicationGroupResourceName, "engine_version_actual"), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.0\.[[:digit:]]+$`)), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "6.0", "6.2"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + ), }, }, }) } -func TestAccElastiCacheGlobalReplicationGroup_description(t *testing.T) { +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnUpdate_MinorUpgrade_6x(t *testing.T) { if testing.Short() { t.Skip("skipping long-running test in short mode") } @@ -74,9 +585,8 @@ func TestAccElastiCacheGlobalReplicationGroup_description(t *testing.T) { var globalReplicationGroup elasticache.GlobalReplicationGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - description1 := sdkacctest.RandString(10) - description2 := sdkacctest.RandString(10) resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, @@ -85,10 +595,90 @@ func TestAccElastiCacheGlobalReplicationGroup_description(t *testing.T) { CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalReplicationGroupConfig_description(rName, primaryReplicationGroupId, description1), - Check: resource.ComposeTestCheckFunc( + Config: testAccGlobalReplicationGroupConfig_engineVersionInherit(rName, primaryReplicationGroupId, "6.0"), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), - resource.TestCheckResourceAttr(resourceName, "global_replication_group_description", description1), + resource.TestCheckResourceAttrPair(resourceName, "engine_version_actual", primaryReplicationGroupResourceName, "engine_version_actual"), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.0\.[[:digit:]]+$`)), + ), + }, + { + Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "6.0", "6.x"), + PlanOnly: true, + }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnUpdate_MinorDowngrade(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersionInherit(rName, primaryReplicationGroupId, "6.2"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestCheckResourceAttrPair(resourceName, "engine_version_actual", primaryReplicationGroupResourceName, "engine_version_actual"), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), + ), + }, + { + Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "6.2", "6.0"), + ExpectError: regexp.MustCompile(`Downgrading Elasticache Global Replication Group \(.*\) engine version requires replacement`), + }, + // This step fails with: Error running pre-apply refresh + // { + // Config: testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, "6.0", "6.0"), + // Taint: []string{ + // resourceName, + // primaryReplicationGroupResourceName, + // }, + // Check: resource.ComposeAggregateTestCheckFunc( + // testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + // resource.TestCheckResourceAttrPair(resourceName, "engine_version_actual", primaryReplicationGroupResourceName, "engine_version_actual"), + // resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.0\.[[:digit:]]+$`)), + // ), + // }, + }, + }) +} + +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnUpdate_MajorUpgrade(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlobalReplicationGroupConfig_engineVersionInherit(rName, primaryReplicationGroupId, "5.0.6"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestCheckResourceAttrPair(resourceName, "engine_version_actual", primaryReplicationGroupResourceName, "engine_version_actual"), + resource.TestCheckResourceAttr(resourceName, "engine_version_actual", "5.0.6"), ), }, { @@ -97,17 +687,17 @@ func TestAccElastiCacheGlobalReplicationGroup_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccGlobalReplicationGroupConfig_description(rName, primaryReplicationGroupId, description2), - Check: resource.ComposeTestCheckFunc( + Config: testAccGlobalReplicationGroupConfig_engineVersionParam(rName, primaryReplicationGroupId, "5.0.6", "6.2", "default.redis6.x"), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), - resource.TestCheckResourceAttr(resourceName, "global_replication_group_description", description2), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), ), }, }, }) } -func TestAccElastiCacheGlobalReplicationGroup_disappears(t *testing.T) { +func TestAccElastiCacheGlobalReplicationGroup_SetEngineVersionOnUpdate_MajorUpgrade_6x(t *testing.T) { if testing.Short() { t.Skip("skipping long-running test in short mode") } @@ -116,6 +706,7 @@ func TestAccElastiCacheGlobalReplicationGroup_disappears(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_elasticache_global_replication_group.test" + primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, @@ -124,93 +715,109 @@ func TestAccElastiCacheGlobalReplicationGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalReplicationGroupConfig_basic(rName, primaryReplicationGroupId), - Check: resource.ComposeTestCheckFunc( + Config: testAccGlobalReplicationGroupConfig_engineVersionInherit(rName, primaryReplicationGroupId, "5.0.6"), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), - acctest.CheckResourceDisappears(acctest.Provider, tfelasticache.ResourceGlobalReplicationGroup(), resourceName), + resource.TestCheckResourceAttrPair(resourceName, "engine_version_actual", primaryReplicationGroupResourceName, "engine_version_actual"), + resource.TestCheckResourceAttr(resourceName, "engine_version_actual", "5.0.6"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccGlobalReplicationGroupConfig_engineVersionParam(rName, primaryReplicationGroupId, "5.0.6", "6.x", "default.redis6.x"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), ), - ExpectNonEmptyPlan: true, }, }, }) } -func TestAccElastiCacheGlobalReplicationGroup_multipleSecondaries(t *testing.T) { +func TestAccElastiCacheGlobalReplicationGroup_SetParameterGroupOnUpdate_NoVersion(t *testing.T) { if testing.Short() { t.Skip("skipping long-running test in short mode") } - var providers []*schema.Provider - var globalReplcationGroup elasticache.GlobalReplicationGroup + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - acctest.PreCheck(t) - acctest.PreCheckMultipleRegion(t, 3) - }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), - ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 3), - CheckDestroy: testAccCheckReplicationDestroy, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalReplicationGroupConfig_MultipleSecondaries(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplcationGroup), + Config: testAccGlobalReplicationGroupConfig_engineVersionInherit(rName, primaryReplicationGroupId, "6.2"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), ), }, + { + Config: testAccGlobalReplicationGroupConfig_param(rName, primaryReplicationGroupId, "6.2", "default.redis6.x"), + ExpectError: regexp.MustCompile(`cannot change parameter group name without upgrading major engine version`), + PlanOnly: true, + }, }, }) } -func TestAccElastiCacheGlobalReplicationGroup_ReplaceSecondary_differentRegion(t *testing.T) { +func TestAccElastiCacheGlobalReplicationGroup_SetParameterGroupOnUpdate_MinorUpgrade(t *testing.T) { if testing.Short() { t.Skip("skipping long-running test in short mode") } - var providers []*schema.Provider - var globalReplcationGroup elasticache.GlobalReplicationGroup + var globalReplicationGroup elasticache.GlobalReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_global_replication_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - acctest.PreCheck(t) - acctest.PreCheckMultipleRegion(t, 3) - }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), - ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 3), - CheckDestroy: testAccCheckReplicationDestroy, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_ReplaceSecondary_DifferentRegion_Setup(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplcationGroup), + Config: testAccGlobalReplicationGroupConfig_engineVersionInherit(rName, primaryReplicationGroupId, "6.0"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.0\.[[:digit:]]+$`)), ), }, { - Config: testAccReplicationGroupConfig_ReplaceSecondary_DifferentRegion_Move(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplcationGroup), - ), + Config: testAccGlobalReplicationGroupConfig_engineVersionParam(rName, primaryReplicationGroupId, "6.0", "6.2", "default.redis6.x"), + ExpectError: regexp.MustCompile(`cannot change parameter group name on minor engine version upgrade, upgrading from 6\.0\.[[:digit:]]+ to 6\.2\.[[:digit:]]+`), + PlanOnly: true, }, }, }) } -func TestAccElastiCacheGlobalReplicationGroup_clusterMode(t *testing.T) { +func TestAccElastiCacheGlobalReplicationGroup_UpdateParameterGroupName(t *testing.T) { if testing.Short() { t.Skip("skipping long-running test in short mode") } var globalReplicationGroup elasticache.GlobalReplicationGroup - var primaryReplicationGroup elasticache.ReplicationGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + primaryReplicationGroupId := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + parameterGroupName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_elasticache_global_replication_group.test" - primaryReplicationGroupResourceName := "aws_elasticache_replication_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); testAccPreCheckGlobalReplicationGroup(t) }, @@ -219,17 +826,16 @@ func TestAccElastiCacheGlobalReplicationGroup_clusterMode(t *testing.T) { CheckDestroy: testAccCheckGlobalReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalReplicationGroupConfig_ClusterMode(rName), - Check: resource.ComposeTestCheckFunc( + Config: testAccGlobalReplicationGroupConfig_engineVersionParam(rName, primaryReplicationGroupId, "5.0.6", "6.2", "default.redis6.x"), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGlobalReplicationGroupExists(resourceName, &globalReplicationGroup), - testAccCheckReplicationGroupExists(primaryReplicationGroupResourceName, &primaryReplicationGroup), - resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + Config: testAccGlobalReplicationGroupConfig_engineVersionCustomParam(rName, primaryReplicationGroupId, "5.0.6", "6.2", parameterGroupName, "redis6.x"), + ExpectError: regexp.MustCompile(`cannot change parameter group name without upgrading major engine version`), + PlanOnly: true, }, }, }) @@ -299,6 +905,23 @@ func testAccPreCheckGlobalReplicationGroup(t *testing.T) { } } +func testAccMatchReplicationGroupActualVersion(j *elasticache.ReplicationGroup, r *regexp.Regexp) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).ElastiCacheConn + + cacheCluster := j.NodeGroups[0].NodeGroupMembers[0] + cluster, err := tfelasticache.FindCacheClusterByID(conn, aws.StringValue(cacheCluster.CacheClusterId)) + if err != nil { + return err + } + + if !r.MatchString(aws.StringValue(cluster.EngineVersion)) { + return fmt.Errorf("Actual engine version didn't match %q, got %q", r.String(), aws.StringValue(cluster.EngineVersion)) + } + return nil + } +} + func testAccGlobalReplicationGroupConfig_basic(rName, primaryReplicationGroupId string) string { return fmt.Sprintf(` resource "aws_elasticache_global_replication_group" "test" { @@ -339,7 +962,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName, primaryReplicationGroupId, description) } -func testAccGlobalReplicationGroupConfig_MultipleSecondaries(rName string) string { +func testAccGlobalReplicationGroupConfig_multipleSecondaries(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(3), testAccVPCBaseWithProvider(rName, "primary", acctest.ProviderName, 1), @@ -394,7 +1017,7 @@ resource "aws_elasticache_replication_group" "third" { `, rName)) } -func testAccReplicationGroupConfig_ReplaceSecondary_DifferentRegion_Setup(rName string) string { +func testAccGlobalReplicationGroupConfig_replaceSecondaryDifferentRegionSetup(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(3), testAccVPCBaseWithProvider(rName, "primary", acctest.ProviderName, 1), @@ -437,7 +1060,7 @@ resource "aws_elasticache_replication_group" "secondary" { `, rName)) } -func testAccReplicationGroupConfig_ReplaceSecondary_DifferentRegion_Move(rName string) string { +func testAccGlobalReplicationGroupConfig_replaceSecondaryDifferentRegionMove(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(3), testAccVPCBaseWithProvider(rName, "primary", acctest.ProviderName, 1), @@ -480,7 +1103,7 @@ resource "aws_elasticache_replication_group" "third" { `, rName)) } -func testAccGlobalReplicationGroupConfig_ClusterMode(rName string) string { +func testAccGlobalReplicationGroupConfig_clusterMode(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_global_replication_group" "test" { global_replication_group_id_suffix = %[1]q @@ -505,6 +1128,133 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } +func testAccGlobalReplicationGroupConfig_engineVersionInherit(rName, primaryReplicationGroupId, repGroupEngineVersion string) string { + return fmt.Sprintf(` +resource "aws_elasticache_global_replication_group" "test" { + global_replication_group_id_suffix = %[1]q + primary_replication_group_id = aws_elasticache_replication_group.test.id +} + +resource "aws_elasticache_replication_group" "test" { + replication_group_id = %[2]q + replication_group_description = "test" + + engine = "redis" + engine_version = %[3]q + node_type = "cache.m5.large" + number_cache_clusters = 1 +} +`, rName, primaryReplicationGroupId, repGroupEngineVersion) +} + +func testAccGlobalReplicationGroupConfig_engineVersion(rName, primaryReplicationGroupId, repGroupEngineVersion, globalEngineVersion string) string { + return fmt.Sprintf(` +resource "aws_elasticache_global_replication_group" "test" { + global_replication_group_id_suffix = %[1]q + primary_replication_group_id = aws_elasticache_replication_group.test.id + + engine_version = %[4]q +} + +resource "aws_elasticache_replication_group" "test" { + replication_group_id = %[2]q + replication_group_description = "test" + + engine = "redis" + engine_version = %[3]q + node_type = "cache.m5.large" + number_cache_clusters = 1 + + lifecycle { + ignore_changes = [engine_version] + } +} +`, rName, primaryReplicationGroupId, repGroupEngineVersion, globalEngineVersion) +} + +func testAccGlobalReplicationGroupConfig_engineVersionParam(rName, primaryReplicationGroupId, repGroupEngineVersion, globalEngineVersion, parameterGroup string) string { + return fmt.Sprintf(` +resource "aws_elasticache_global_replication_group" "test" { + global_replication_group_id_suffix = %[1]q + primary_replication_group_id = aws_elasticache_replication_group.test.id + + engine_version = %[4]q + parameter_group_name = %[5]q +} + +resource "aws_elasticache_replication_group" "test" { + replication_group_id = %[2]q + replication_group_description = "test" + + engine = "redis" + engine_version = %[3]q + node_type = "cache.m5.large" + number_cache_clusters = 1 + + lifecycle { + ignore_changes = [engine_version] + } +} +`, rName, primaryReplicationGroupId, repGroupEngineVersion, globalEngineVersion, parameterGroup) +} + +func testAccGlobalReplicationGroupConfig_engineVersionCustomParam(rName, primaryReplicationGroupId, repGroupEngineVersion, globalEngineVersion, parameterGroupName, parameterGroupFamily string) string { + return fmt.Sprintf(` +resource "aws_elasticache_global_replication_group" "test" { + global_replication_group_id_suffix = %[1]q + primary_replication_group_id = aws_elasticache_replication_group.test.id + + engine_version = %[4]q + parameter_group_name = aws_elasticache_parameter_group.test.name +} + +resource "aws_elasticache_replication_group" "test" { + replication_group_id = %[2]q + replication_group_description = "test" + + engine = "redis" + engine_version = %[3]q + node_type = "cache.m5.large" + number_cache_clusters = 1 + + lifecycle { + ignore_changes = [engine_version] + } +} + +resource "aws_elasticache_parameter_group" "test" { + name = %[5]q + description = "test" + family = %[6]q +} +`, rName, primaryReplicationGroupId, repGroupEngineVersion, globalEngineVersion, parameterGroupName, parameterGroupFamily) +} + +func testAccGlobalReplicationGroupConfig_param(rName, primaryReplicationGroupId, repGroupEngineVersion, parameterGroup string) string { + return fmt.Sprintf(` +resource "aws_elasticache_global_replication_group" "test" { + global_replication_group_id_suffix = %[1]q + primary_replication_group_id = aws_elasticache_replication_group.test.id + + parameter_group_name = %[4]q +} + +resource "aws_elasticache_replication_group" "test" { + replication_group_id = %[2]q + replication_group_description = "test" + + engine = "redis" + engine_version = %[3]q + node_type = "cache.m5.large" + number_cache_clusters = 1 + + lifecycle { + ignore_changes = [engine_version] + } +} +`, rName, primaryReplicationGroupId, repGroupEngineVersion, parameterGroup) +} + func testAccVPCBaseWithProvider(rName, name, provider string, subnetCount int) string { return acctest.ConfigCompose( testAccAvailableAZsNoOptInConfigWithProvider(name, provider), diff --git a/internal/service/elasticache/parameter_group.go b/internal/service/elasticache/parameter_group.go index ee658786b15..46b1aee51a9 100644 --- a/internal/service/elasticache/parameter_group.go +++ b/internal/service/elasticache/parameter_group.go @@ -95,7 +95,7 @@ func resourceParameterGroupCreate(d *schema.ResourceData, meta interface{}) erro log.Printf("[DEBUG] Create ElastiCache Parameter Group: %#v", createOpts) resp, err := conn.CreateCacheParameterGroup(&createOpts) - if createOpts.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if createOpts.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating ElastiCache Parameter Group with tags: %s. Trying create without tags.", err) createOpts.Tags = nil @@ -118,24 +118,15 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - describeOpts := elasticache.DescribeCacheParameterGroupsInput{ - CacheParameterGroupName: aws.String(d.Id()), - } - - describeResp, err := conn.DescribeCacheParameterGroups(&describeOpts) + parameterGroup, err := FindParameterGroupByName(conn, d.Id()) if err != nil { - return err + return fmt.Errorf("unable to find ElastiCache Parameter Group (%s): %w", d.Id(), err) } - if len(describeResp.CacheParameterGroups) != 1 || - aws.StringValue(describeResp.CacheParameterGroups[0].CacheParameterGroupName) != d.Id() { - return fmt.Errorf("unable to find Parameter Group: %#v", describeResp.CacheParameterGroups) - } - - d.Set("name", describeResp.CacheParameterGroups[0].CacheParameterGroupName) - d.Set("family", describeResp.CacheParameterGroups[0].CacheParameterGroupFamily) - d.Set("description", describeResp.CacheParameterGroups[0].Description) - d.Set("arn", describeResp.CacheParameterGroups[0].ARN) + d.Set("name", parameterGroup.CacheParameterGroupName) + d.Set("family", parameterGroup.CacheParameterGroupFamily) + d.Set("description", parameterGroup.Description) + d.Set("arn", parameterGroup.ARN) // Only include user customized parameters as there's hundreds of system/default ones describeParametersOpts := elasticache.DescribeCacheParametersInput{ @@ -150,9 +141,9 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error d.Set("parameter", FlattenParameters(describeParametersResp.Parameters)) - tags, err := ListTags(conn, aws.StringValue(describeResp.CacheParameterGroups[0].ARN)) + tags, err := ListTags(conn, aws.StringValue(parameterGroup.ARN)) - if err != nil && !verify.CheckISOErrorTagsUnsupported(err) { + if err != nil && !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { return fmt.Errorf("error listing tags for ElastiCache Parameter Group (%s): %w", d.Id(), err) } @@ -300,7 +291,7 @@ func resourceParameterGroupUpdate(d *schema.ResourceData, meta interface{}) erro err := UpdateTags(conn, d.Get("arn").(string), o, n) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed updating ElastiCache Parameter Group (%s) tags: %w", d.Get("arn").(string), err) } @@ -315,8 +306,19 @@ func resourceParameterGroupUpdate(d *schema.ResourceData, meta interface{}) erro func resourceParameterGroupDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ElastiCacheConn + err := deleteParameterGroup(conn, d.Id()) + if tfawserr.ErrCodeEquals(err, elasticache.ErrCodeCacheParameterGroupNotFoundFault) { + return nil + } + if err != nil { + return fmt.Errorf("error deleting ElastiCache Parameter Group (%s): %w", d.Id(), err) + } + return nil +} + +func deleteParameterGroup(conn *elasticache.ElastiCache, name string) error { deleteOpts := elasticache.DeleteCacheParameterGroupInput{ - CacheParameterGroupName: aws.String(d.Id()), + CacheParameterGroupName: aws.String(name), } err := resource.Retry(3*time.Minute, func() *resource.RetryError { _, err := conn.DeleteCacheParameterGroup(&deleteOpts) @@ -335,15 +337,8 @@ func resourceParameterGroupDelete(d *schema.ResourceData, meta interface{}) erro if tfresource.TimedOut(err) { _, err = conn.DeleteCacheParameterGroup(&deleteOpts) } - if tfawserr.ErrCodeEquals(err, elasticache.ErrCodeCacheParameterGroupNotFoundFault) { - return nil - } - if err != nil { - return fmt.Errorf("error deleting ElastiCache Parameter Group (%s): %w", d.Id(), err) - } - - return nil + return err } func ParameterHash(v interface{}) int { diff --git a/internal/service/elasticache/parameter_group_test.go b/internal/service/elasticache/parameter_group_test.go index c07c60eb6ef..239470e2f0f 100644 --- a/internal/service/elasticache/parameter_group_test.go +++ b/internal/service/elasticache/parameter_group_test.go @@ -29,7 +29,7 @@ func TestAccElastiCacheParameterGroup_basic(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig(rName), + Config: testAccParameterGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, rName), @@ -60,7 +60,7 @@ func TestAccElastiCacheParameterGroup_addParameter(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupParameter1Config(rName, "redis2.8", "appendonly", "yes"), + Config: testAccParameterGroupConfig_1(rName, "redis2.8", "appendonly", "yes"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -76,7 +76,7 @@ func TestAccElastiCacheParameterGroup_addParameter(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupParameter2Config(rName, "redis2.8", "appendonly", "yes", "appendfsync", "always"), + Config: testAccParameterGroupConfig_2(rName, "redis2.8", "appendonly", "yes", "appendfsync", "always"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "parameter.#", "2"), @@ -107,7 +107,7 @@ func TestAccElastiCacheParameterGroup_removeAllParameters(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupParameter2Config(rName, "redis2.8", "appendonly", "yes", "appendfsync", "always"), + Config: testAccParameterGroupConfig_2(rName, "redis2.8", "appendonly", "yes", "appendfsync", "always"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "parameter.#", "2"), @@ -122,7 +122,7 @@ func TestAccElastiCacheParameterGroup_removeAllParameters(t *testing.T) { ), }, { - Config: testAccParameterGroupConfig(rName), + Config: testAccParameterGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "parameter.#", "0"), @@ -146,7 +146,7 @@ func TestAccElastiCacheParameterGroup_RemoveReservedMemoryParameter_allParameter CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupParameter1Config(rName, "redis3.2", "reserved-memory", "0"), + Config: testAccParameterGroupConfig_1(rName, "redis3.2", "reserved-memory", "0"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -157,7 +157,7 @@ func TestAccElastiCacheParameterGroup_RemoveReservedMemoryParameter_allParameter ), }, { - Config: testAccParameterGroupConfig(rName), + Config: testAccParameterGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "parameter.#", "0"), @@ -186,7 +186,7 @@ func TestAccElastiCacheParameterGroup_RemoveReservedMemoryParameter_remainingPar CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupParameter2Config(rName, "redis3.2", "reserved-memory", "0", "tcp-keepalive", "360"), + Config: testAccParameterGroupConfig_2(rName, "redis3.2", "reserved-memory", "0", "tcp-keepalive", "360"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "parameter.#", "2"), @@ -201,7 +201,7 @@ func TestAccElastiCacheParameterGroup_RemoveReservedMemoryParameter_remainingPar ), }, { - Config: testAccParameterGroupParameter1Config(rName, "redis3.2", "tcp-keepalive", "360"), + Config: testAccParameterGroupConfig_1(rName, "redis3.2", "tcp-keepalive", "360"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -234,7 +234,7 @@ func TestAccElastiCacheParameterGroup_switchReservedMemoryParameter(t *testing.T CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupParameter1Config(rName, "redis3.2", "reserved-memory", "0"), + Config: testAccParameterGroupConfig_1(rName, "redis3.2", "reserved-memory", "0"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -245,7 +245,7 @@ func TestAccElastiCacheParameterGroup_switchReservedMemoryParameter(t *testing.T ), }, { - Config: testAccParameterGroupParameter1Config(rName, "redis3.2", "reserved-memory-percent", "25"), + Config: testAccParameterGroupConfig_1(rName, "redis3.2", "reserved-memory-percent", "25"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -278,7 +278,7 @@ func TestAccElastiCacheParameterGroup_updateReservedMemoryParameter(t *testing.T CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupParameter1Config(rName, "redis2.8", "reserved-memory", "0"), + Config: testAccParameterGroupConfig_1(rName, "redis2.8", "reserved-memory", "0"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -289,7 +289,7 @@ func TestAccElastiCacheParameterGroup_updateReservedMemoryParameter(t *testing.T ), }, { - Config: testAccParameterGroupParameter1Config(rName, "redis2.8", "reserved-memory", "1"), + Config: testAccParameterGroupConfig_1(rName, "redis2.8", "reserved-memory", "1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -321,7 +321,7 @@ func TestAccElastiCacheParameterGroup_uppercaseName(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupParameter1Config(rName, "redis2.8", "appendonly", "yes"), + Config: testAccParameterGroupConfig_1(rName, "redis2.8", "appendonly", "yes"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("tf-elastipg-%d", rInt)), @@ -348,7 +348,7 @@ func TestAccElastiCacheParameterGroup_description(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupDescriptionConfig(rName, "description1"), + Config: testAccParameterGroupConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -375,7 +375,7 @@ func TestAccElastiCacheParameterGroup_tags(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupTags1Config(rName, "redis2.8", "key1", "value1"), + Config: testAccParameterGroupConfig_tags1(rName, "redis2.8", "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -383,7 +383,7 @@ func TestAccElastiCacheParameterGroup_tags(t *testing.T) { ), }, { - Config: testAccParameterGroupTags2Config(rName, "redis2.8", "key1", "updatedvalue1", "key2", "value2"), + Config: testAccParameterGroupConfig_tags2(rName, "redis2.8", "key1", "updatedvalue1", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -392,7 +392,7 @@ func TestAccElastiCacheParameterGroup_tags(t *testing.T) { ), }, { - Config: testAccParameterGroupConfig(rName), + Config: testAccParameterGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &cacheParameterGroup1), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -487,7 +487,7 @@ func testAccCheckParameterGroupExists(n string, v *elasticache.CacheParameterGro } } -func testAccParameterGroupConfig(rName string) string { +func testAccParameterGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_parameter_group" "test" { family = "redis2.8" @@ -496,7 +496,7 @@ resource "aws_elasticache_parameter_group" "test" { `, rName) } -func testAccParameterGroupDescriptionConfig(rName, description string) string { +func testAccParameterGroupConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_elasticache_parameter_group" "test" { description = %q @@ -506,7 +506,7 @@ resource "aws_elasticache_parameter_group" "test" { `, description, rName) } -func testAccParameterGroupParameter1Config(rName, family, parameterName1, parameterValue1 string) string { +func testAccParameterGroupConfig_1(rName, family, parameterName1, parameterValue1 string) string { return fmt.Sprintf(` resource "aws_elasticache_parameter_group" "test" { family = %q @@ -520,7 +520,7 @@ resource "aws_elasticache_parameter_group" "test" { `, family, rName, parameterName1, parameterValue1) } -func testAccParameterGroupParameter2Config(rName, family, parameterName1, parameterValue1, parameterName2, parameterValue2 string) string { +func testAccParameterGroupConfig_2(rName, family, parameterName1, parameterValue1, parameterName2, parameterValue2 string) string { return fmt.Sprintf(` resource "aws_elasticache_parameter_group" "test" { family = %q @@ -539,7 +539,7 @@ resource "aws_elasticache_parameter_group" "test" { `, family, rName, parameterName1, parameterValue1, parameterName2, parameterValue2) } -func testAccParameterGroupTags1Config(rName, family, tagName1, tagValue1 string) string { +func testAccParameterGroupConfig_tags1(rName, family, tagName1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_elasticache_parameter_group" "test" { family = %[1]q @@ -552,7 +552,7 @@ resource "aws_elasticache_parameter_group" "test" { `, family, rName, tagName1, tagValue1) } -func testAccParameterGroupTags2Config(rName, family, tagName1, tagValue1, tagName2, tagValue2 string) string { +func testAccParameterGroupConfig_tags2(rName, family, tagName1, tagValue1, tagName2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_elasticache_parameter_group" "test" { family = %[1]q diff --git a/internal/service/elasticache/replication_group.go b/internal/service/elasticache/replication_group.go index 5953806a5e9..64a66f952c8 100644 --- a/internal/service/elasticache/replication_group.go +++ b/internal/service/elasticache/replication_group.go @@ -565,7 +565,7 @@ func resourceReplicationGroupCreate(d *schema.ResourceData, meta interface{}) er resp, err := conn.CreateReplicationGroup(params) - if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating ElastiCache Replication Group with tags: %s. Trying create without tags.", err) params.Tags = nil @@ -598,7 +598,7 @@ func resourceReplicationGroupCreate(d *schema.ResourceData, meta interface{}) er err := UpdateTags(conn, aws.StringValue(resp.ReplicationGroup.ARN), nil, tags) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed adding tags after create for ElastiCache Replication Group (%s): %w", d.Id(), err) } @@ -685,22 +685,39 @@ func resourceReplicationGroupRead(d *schema.ResourceData, meta interface{}) erro d.Set("port", rgp.ConfigurationEndpoint.Port) d.Set("configuration_endpoint_address", rgp.ConfigurationEndpoint.Address) } else { - d.Set("port", rgp.NodeGroups[0].PrimaryEndpoint.Port) - d.Set("primary_endpoint_address", rgp.NodeGroups[0].PrimaryEndpoint.Address) - d.Set("reader_endpoint_address", rgp.NodeGroups[0].ReaderEndpoint.Address) + log.Printf("[DEBUG] ElastiCache Replication Group (%s) Configuration Endpoint is nil", d.Id()) + + if rgp.NodeGroups[0].PrimaryEndpoint != nil { + log.Printf("[DEBUG] ElastiCache Replication Group (%s) Primary Endpoint is not nil", d.Id()) + if rgp.NodeGroups[0].PrimaryEndpoint.Port != nil { + d.Set("port", rgp.NodeGroups[0].PrimaryEndpoint.Port) + } + + if rgp.NodeGroups[0].PrimaryEndpoint.Address != nil { + d.Set("primary_endpoint_address", rgp.NodeGroups[0].PrimaryEndpoint.Address) + } + } + + if rgp.NodeGroups[0].ReaderEndpoint != nil && rgp.NodeGroups[0].ReaderEndpoint.Address != nil { + d.Set("reader_endpoint_address", rgp.NodeGroups[0].ReaderEndpoint.Address) + } } d.Set("user_group_ids", rgp.UserGroupIds) // Tags cannot be read when the replication group is not Available + log.Printf("[DEBUG] Waiting for ElastiCache Replication Group (%s) to become available", d.Id()) + _, err = WaitReplicationGroupAvailable(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)) if err != nil { return fmt.Errorf("waiting for ElastiCache Replication Group to be available (%s): %w", aws.StringValue(rgp.ARN), err) } + log.Printf("[DEBUG] Listing tags for ElastiCache Replication Group (%s)", d.Id()) + tags, err := ListTags(conn, aws.StringValue(rgp.ARN)) - if err != nil && !verify.CheckISOErrorTagsUnsupported(err) { + if err != nil && !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { return fmt.Errorf("listing tags for ElastiCache Replication Group (%s): %w", aws.StringValue(rgp.ARN), err) } @@ -722,8 +739,10 @@ func resourceReplicationGroupRead(d *schema.ResourceData, meta interface{}) erro } } + log.Printf("[DEBUG] ElastiCache Replication Group (%s): Checking underlying cache clusters", d.Id()) + // This section reads settings that require checking the underlying cache clusters - if rgp.NodeGroups != nil && len(rgp.NodeGroups[0].NodeGroupMembers) != 0 { + if rgp.NodeGroups != nil && rgp.NodeGroups[0] != nil && len(rgp.NodeGroups[0].NodeGroupMembers) != 0 { cacheCluster := rgp.NodeGroups[0].NodeGroupMembers[0] res, err := conn.DescribeCacheClusters(&elasticache.DescribeCacheClustersInput{ @@ -951,7 +970,7 @@ func resourceReplicationGroupUpdate(d *schema.ResourceData, meta interface{}) er err := UpdateTags(conn, d.Get("arn").(string), o, n) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed updating ElastiCache Replication Group (%s) tags: %w", d.Id(), err) } @@ -966,8 +985,10 @@ func resourceReplicationGroupUpdate(d *schema.ResourceData, meta interface{}) er func resourceReplicationGroupDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ElastiCacheConn - if globalReplicationGroupID, ok := d.GetOk("global_replication_group_id"); ok { - err := DisassociateReplicationGroup(conn, globalReplicationGroupID.(string), d.Id(), meta.(*conns.AWSClient).Region, GlobalReplicationGroupDisassociationReadyTimeout) + v, hasGlobalReplicationGroupID := d.GetOk("global_replication_group_id") + if hasGlobalReplicationGroupID { + globalReplicationGroupID := v.(string) + err := DisassociateReplicationGroup(conn, globalReplicationGroupID, d.Id(), meta.(*conns.AWSClient).Region, GlobalReplicationGroupDisassociationReadyTimeout) if err != nil { return fmt.Errorf("error disassociating ElastiCache Replication Group (%s) from Global Replication Group (%s): %w", d.Id(), globalReplicationGroupID, err) } @@ -979,6 +1000,19 @@ func resourceReplicationGroupDelete(d *schema.ResourceData, meta interface{}) er return fmt.Errorf("error deleting ElastiCache Replication Group (%s): %w", d.Id(), err) } + if hasGlobalReplicationGroupID { + paramGroupName := d.Get("parameter_group_name").(string) + if paramGroupName != "" { + err := deleteParameterGroup(conn, paramGroupName) + if tfawserr.ErrCodeEquals(err, elasticache.ErrCodeCacheParameterGroupNotFoundFault) { + return nil + } + if err != nil { + return fmt.Errorf("error deleting ElastiCache Parameter Group (%s): %w", d.Id(), err) + } + } + } + return nil } diff --git a/internal/service/elasticache/replication_group_data_source_test.go b/internal/service/elasticache/replication_group_data_source_test.go index f9969626bfc..57d99f4d972 100644 --- a/internal/service/elasticache/replication_group_data_source_test.go +++ b/internal/service/elasticache/replication_group_data_source_test.go @@ -64,7 +64,7 @@ func TestAccElastiCacheReplicationGroupDataSource_clusterMode(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupDataSourceConfig_ClusterMode(rName), + Config: testAccReplicationGroupDataSourceConfig_clusterMode(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "auth_token_enabled", "false"), resource.TestCheckResourceAttrPair(dataSourceName, "automatic_failover_enabled", resourceName, "automatic_failover_enabled"), @@ -97,7 +97,7 @@ func TestAccElastiCacheReplicationGroupDataSource_multiAZ(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupDataSourceConfig_MultiAZ(rName), + Config: testAccReplicationGroupDataSourceConfig_multiAZ(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "automatic_failover_enabled", resourceName, "automatic_failover_enabled"), resource.TestCheckResourceAttrPair(dataSourceName, "multi_az_enabled", resourceName, "multi_az_enabled"), @@ -115,7 +115,7 @@ func TestAccElastiCacheReplicationGroupDataSource_nonExistent(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupDataSourceConfig_NonExistent, + Config: testAccReplicationGroupDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`couldn't find resource`), }, }, @@ -136,7 +136,7 @@ func TestAccElastiCacheReplicationGroupDataSource_Engine_Redis_LogDeliveryConfig ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName, false, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), + Config: testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, false, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "log_delivery_configuration.0.destination", rName), resource.TestCheckResourceAttr(dataSourceName, "log_delivery_configuration.0.destination_type", "cloudwatch-logs"), @@ -171,7 +171,7 @@ data "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupDataSourceConfig_ClusterMode(rName string) string { +func testAccReplicationGroupDataSourceConfig_clusterMode(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -192,7 +192,7 @@ data "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupDataSourceConfig_MultiAZ(rName string) string { +func testAccReplicationGroupDataSourceConfig_multiAZ(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -209,7 +209,7 @@ data "aws_elasticache_replication_group" "test" { `, rName) } -const testAccReplicationGroupDataSourceConfig_NonExistent = ` +const testAccReplicationGroupDataSourceConfig_nonExistent = ` data "aws_elasticache_replication_group" "test" { replication_group_id = "tf-acc-test-nonexistent" } diff --git a/internal/service/elasticache/replication_group_test.go b/internal/service/elasticache/replication_group_test.go index 76bacc181d5..27d48d9e773 100644 --- a/internal/service/elasticache/replication_group_test.go +++ b/internal/service/elasticache/replication_group_test.go @@ -34,10 +34,10 @@ func TestAccElastiCacheReplicationGroup_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig(rName), + Config: testAccReplicationGroupConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -80,7 +80,7 @@ func TestAccElastiCacheReplicationGroup_basic_v5(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { Config: testAccReplicationGroupConfig_v5(rName), @@ -116,10 +116,10 @@ func TestAccElastiCacheReplicationGroup_uppercase(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_Uppercase(strings.ToUpper(rName)), + Config: testAccReplicationGroupConfig_uppercase(strings.ToUpper(rName)), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "replication_group_id", rName), @@ -148,10 +148,10 @@ func TestAccElastiCacheReplicationGroup_EngineVersion_update(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_EngineVersion(rName, "3.2.6"), + Config: testAccReplicationGroupConfig_engineVersion(rName, "3.2.6"), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "engine_version", "3.2.6"), @@ -159,7 +159,13 @@ func TestAccElastiCacheReplicationGroup_EngineVersion_update(t *testing.T) { ), }, { - Config: testAccReplicationGroupConfig_EngineVersion(rName, "3.2.4"), + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"apply_immediately"}, + }, + { + Config: testAccReplicationGroupConfig_engineVersion(rName, "3.2.4"), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &v2), testAccCheckReplicationGroupRecreated(&v1, &v2), @@ -168,7 +174,7 @@ func TestAccElastiCacheReplicationGroup_EngineVersion_update(t *testing.T) { ), }, { - Config: testAccReplicationGroupConfig_EngineVersion(rName, "3.2.10"), + Config: testAccReplicationGroupConfig_engineVersion(rName, "3.2.10"), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &v3), testAccCheckReplicationGroupNotRecreated(&v2, &v3), @@ -177,25 +183,31 @@ func TestAccElastiCacheReplicationGroup_EngineVersion_update(t *testing.T) { ), }, { - Config: testAccReplicationGroupConfig_EngineVersion(rName, "6.0"), + Config: testAccReplicationGroupConfig_engineVersion(rName, "6.0"), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &v4), testAccCheckReplicationGroupNotRecreated(&v3, &v4), resource.TestCheckResourceAttr(resourceName, "engine_version", "6.0"), - resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.[[:digit:]]+\.[[:digit:]]+$`)), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.0\.[[:digit:]]+$`)), ), }, { - Config: testAccReplicationGroupConfig_EngineVersion(rName, "6.2"), + Config: testAccReplicationGroupConfig_engineVersion(rName, "6.2"), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &v5), testAccCheckReplicationGroupNotRecreated(&v4, &v5), resource.TestCheckResourceAttr(resourceName, "engine_version", "6.2"), - resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.[[:digit:]]+\.[[:digit:]]+$`)), + resource.TestMatchResourceAttr(resourceName, "engine_version_actual", regexp.MustCompile(`^6\.2\.[[:digit:]]+$`)), ), }, { - Config: testAccReplicationGroupConfig_EngineVersion(rName, "5.0.6"), + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"apply_immediately"}, + }, + { + Config: testAccReplicationGroupConfig_engineVersion(rName, "5.0.6"), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &v6), testAccCheckReplicationGroupRecreated(&v5, &v6), @@ -204,7 +216,7 @@ func TestAccElastiCacheReplicationGroup_EngineVersion_update(t *testing.T) { ), }, { - Config: testAccReplicationGroupConfig_EngineVersion(rName, "6.x"), + Config: testAccReplicationGroupConfig_engineVersion(rName, "6.x"), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &v7), testAccCheckReplicationGroupNotRecreated(&v6, &v7), @@ -213,7 +225,7 @@ func TestAccElastiCacheReplicationGroup_EngineVersion_update(t *testing.T) { ), }, { - Config: testAccReplicationGroupConfig_EngineVersion(rName, "6.0"), + Config: testAccReplicationGroupConfig_engineVersion(rName, "6.0"), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &v8), testAccCheckReplicationGroupRecreated(&v7, &v8), @@ -238,10 +250,10 @@ func TestAccElastiCacheReplicationGroup_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig(rName), + Config: testAccReplicationGroupConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), acctest.CheckResourceDisappears(acctest.Provider, tfelasticache.ResourceReplicationGroup(), resourceName), @@ -265,10 +277,10 @@ func TestAccElastiCacheReplicationGroup_updateDescription(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig(rName), + Config: testAccReplicationGroupConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "1"), @@ -282,7 +294,7 @@ func TestAccElastiCacheReplicationGroup_updateDescription(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupUpdatedDescriptionConfig(rName), + Config: testAccReplicationGroupConfig_updatedDescription(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "1"), @@ -306,10 +318,10 @@ func TestAccElastiCacheReplicationGroup_updateMaintenanceWindow(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig(rName), + Config: testAccReplicationGroupConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "maintenance_window", "tue:06:30-tue:07:30"), @@ -322,7 +334,7 @@ func TestAccElastiCacheReplicationGroup_updateMaintenanceWindow(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupUpdatedMaintenanceWindowConfig(rName), + Config: testAccReplicationGroupConfig_updatedMaintenanceWindow(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "maintenance_window", "wed:03:00-wed:06:00"), @@ -347,10 +359,10 @@ func TestAccElastiCacheReplicationGroup_updateUserGroups(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupUserGroup(rName, userGroup, 0), + Config: testAccReplicationGroupConfig_user(rName, userGroup, 0), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), testAccCheckReplicationGroupUserGroup(resourceName, fmt.Sprintf("%s-%d", userGroup, 0)), @@ -364,7 +376,7 @@ func TestAccElastiCacheReplicationGroup_updateUserGroups(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupUserGroup(rName, userGroup, 1), + Config: testAccReplicationGroupConfig_user(rName, userGroup, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), testAccCheckReplicationGroupUserGroup(resourceName, fmt.Sprintf("%s-%d", userGroup, 1)), @@ -388,10 +400,10 @@ func TestAccElastiCacheReplicationGroup_updateNodeSize(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig(rName), + Config: testAccReplicationGroupConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "1"), @@ -405,7 +417,7 @@ func TestAccElastiCacheReplicationGroup_updateNodeSize(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupUpdatedNodeSizeConfig(rName), + Config: testAccReplicationGroupConfig_updatedNodeSize(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "1"), @@ -432,10 +444,10 @@ func TestAccElastiCacheReplicationGroup_updateParameterGroup(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupParameterGroupNameConfig(rName, 0), + Config: testAccReplicationGroupConfig_parameterName(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttrPair(resourceName, "parameter_group_name", parameterGroupResourceName1, "name"), @@ -448,7 +460,7 @@ func TestAccElastiCacheReplicationGroup_updateParameterGroup(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupParameterGroupNameConfig(rName, 1), + Config: testAccReplicationGroupConfig_parameterName(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttrPair(resourceName, "parameter_group_name", parameterGroupResourceName2, "name"), @@ -471,10 +483,10 @@ func TestAccElastiCacheReplicationGroup_updateAuthToken(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroup_EnableAuthTokenTransitEncryptionConfig(rName, sdkacctest.RandString(16)), + Config: testAccReplicationGroupConfig_enableAuthTokenTransitEncryption(rName, sdkacctest.RandString(16)), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "transit_encryption_enabled", "true"), @@ -487,7 +499,7 @@ func TestAccElastiCacheReplicationGroup_updateAuthToken(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately", "auth_token"}, }, { - Config: testAccReplicationGroup_EnableAuthTokenTransitEncryptionConfig(rName, sdkacctest.RandString(16)), + Config: testAccReplicationGroupConfig_enableAuthTokenTransitEncryption(rName, sdkacctest.RandString(16)), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), ), @@ -509,10 +521,10 @@ func TestAccElastiCacheReplicationGroup_vpc(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupInVPCConfig(rName), + Config: testAccReplicationGroupConfig_inVPC(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "1"), @@ -542,10 +554,10 @@ func TestAccElastiCacheReplicationGroup_depecatedAvailabilityZones_vpc(t *testin PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupInVPCConfig_DeprecatedAvailabilityZones(rName), + Config: testAccReplicationGroupConfig_inVPCDeprecatedAvailabilityZones(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "1"), @@ -575,10 +587,10 @@ func TestAccElastiCacheReplicationGroup_multiAzNotInVPC(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_MultiAZNotInVPC_PreferredCacheClusterAZs_notRepeated(rName), + Config: testAccReplicationGroupConfig_multiAZNotInVPCPreferredCacheClusterAZsNotRepeated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "num_cache_clusters", "2"), @@ -613,10 +625,10 @@ func TestAccElastiCacheReplicationGroup_multiAzNotInVPC_repeated(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_MultiAZNotInVPC_PreferredCacheClusterAZs_repeated(rName), + Config: testAccReplicationGroupConfig_multiAZNotInVPCPreferredCacheClusterAZsRepeated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "num_cache_clusters", "4"), @@ -653,10 +665,10 @@ func TestAccElastiCacheReplicationGroup_deprecatedAvailabilityZones_multiAzNotIn PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_MultiAZNotInVPC_Basic(rName), + Config: testAccReplicationGroupConfig_multiAZNotInVPCBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg1), resource.TestCheckResourceAttr(resourceName, "num_cache_clusters", "2"), @@ -671,7 +683,7 @@ func TestAccElastiCacheReplicationGroup_deprecatedAvailabilityZones_multiAzNotIn ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupConfig_MultiAZNotInVPC_DeprecatedAvailabilityZones(rName), + Config: testAccReplicationGroupConfig_multiAZNotInVPCDeprecatedAvailabilityZones(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg2), testAccCheckReplicationGroupRecreated(&rg1, &rg2), @@ -707,10 +719,10 @@ func TestAccElastiCacheReplicationGroup_multiAzInVPC(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupMultiAZInVPCConfig(rName), + Config: testAccReplicationGroupConfig_multiAZInVPC(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "2"), @@ -751,10 +763,10 @@ func TestAccElastiCacheReplicationGroup_deprecatedAvailabilityZones_multiAzInVPC PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupMultiAZInVPCConfig(rName), + Config: testAccReplicationGroupConfig_multiAZInVPC(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "2"), @@ -789,10 +801,10 @@ func TestAccElastiCacheReplicationGroup_ValidationMultiAz_noAutomaticFailover(t PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_MultiAZ_NoAutomaticFailover(rName), + Config: testAccReplicationGroupConfig_multiAZNoAutomaticFailover(rName), ExpectError: regexp.MustCompile("automatic_failover_enabled must be true if multi_az_enabled is true"), }, }, @@ -812,10 +824,10 @@ func TestAccElastiCacheReplicationGroup_ClusterMode_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 2, 1), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -854,10 +866,10 @@ func TestAccElastiCacheReplicationGroup_ClusterMode_nonClusteredParameterGroup(t PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupNativeRedisClusterConfig_NonClusteredParameterGroup(rName), + Config: testAccReplicationGroupConfig_nativeRedisClusterNonClusteredParameter(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "false"), @@ -895,10 +907,10 @@ func TestAccElastiCacheReplicationGroup_ClusterModeUpdateNumNodeGroups_scaleUp(t PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 2, 1), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 2, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "4"), @@ -913,7 +925,7 @@ func TestAccElastiCacheReplicationGroup_ClusterModeUpdateNumNodeGroups_scaleUp(t ), }, { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 3, 1), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 3, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -945,10 +957,10 @@ func TestAccElastiCacheReplicationGroup_ClusterModeUpdateNumNodeGroups_scaleDown PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 3, 1), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 3, 1), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -961,7 +973,7 @@ func TestAccElastiCacheReplicationGroup_ClusterModeUpdateNumNodeGroups_scaleDown ), }, { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 2, 1), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -990,10 +1002,10 @@ func TestAccElastiCacheReplicationGroup_ClusterMode_updateReplicasPerNodeGroup(t PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 2, 1), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -1006,7 +1018,7 @@ func TestAccElastiCacheReplicationGroup_ClusterMode_updateReplicasPerNodeGroup(t ), }, { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 2, 3), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 2, 3), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -1019,7 +1031,7 @@ func TestAccElastiCacheReplicationGroup_ClusterMode_updateReplicasPerNodeGroup(t ), }, { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 2, 2), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 2, 2), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -1048,10 +1060,10 @@ func TestAccElastiCacheReplicationGroup_ClusterModeUpdateNumNodeGroupsAndReplica PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 2, 1), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -1064,7 +1076,7 @@ func TestAccElastiCacheReplicationGroup_ClusterModeUpdateNumNodeGroupsAndReplica ), }, { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 3, 2), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 3, 2), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -1093,10 +1105,10 @@ func TestAccElastiCacheReplicationGroup_ClusterModeUpdateNumNodeGroupsAndReplica PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 3, 2), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 3, 2), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -1109,7 +1121,7 @@ func TestAccElastiCacheReplicationGroup_ClusterModeUpdateNumNodeGroupsAndReplica ), }, { - Config: testAccReplicationGroupNativeRedisClusterConfig(rName, 2, 1), + Config: testAccReplicationGroupConfig_nativeRedisCluster(rName, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -1138,10 +1150,10 @@ func TestAccElastiCacheReplicationGroup_ClusterMode_singleNode(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupNativeRedisClusterConfig_SingleNode(rName), + Config: testAccReplicationGroupConfig_nativeRedisClusterSingleNode(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "cluster_enabled", "true"), @@ -1172,10 +1184,10 @@ func TestAccElastiCacheReplicationGroup_clusteringAndCacheNodesCausesError(t *te PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupNativeRedisClusterErrorConfig(rName), + Config: testAccReplicationGroupConfig_nativeRedisClusterError(rName), ExpectError: regexp.MustCompile(`"cluster_mode.0.num_node_groups": conflicts with number_cache_clusters`), }, }, @@ -1195,10 +1207,10 @@ func TestAccElastiCacheReplicationGroup_enableSnapshotting(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig(rName), + Config: testAccReplicationGroupConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "snapshot_retention_limit", "0"), @@ -1211,7 +1223,7 @@ func TestAccElastiCacheReplicationGroup_enableSnapshotting(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupEnableSnapshottingConfig(rName), + Config: testAccReplicationGroupConfig_enableSnapshotting(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "snapshot_retention_limit", "2"), @@ -1234,10 +1246,10 @@ func TestAccElastiCacheReplicationGroup_enableAuthTokenTransitEncryption(t *test PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroup_EnableAuthTokenTransitEncryptionConfig(rName, sdkacctest.RandString(16)), + Config: testAccReplicationGroupConfig_enableAuthTokenTransitEncryption(rName, sdkacctest.RandString(16)), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "transit_encryption_enabled", "true"), @@ -1266,10 +1278,10 @@ func TestAccElastiCacheReplicationGroup_enableAtRestEncryption(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroup_EnableAtRestEncryptionConfig(rName), + Config: testAccReplicationGroupConfig_enableAtRestEncryption(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "at_rest_encryption_enabled", "true"), @@ -1297,10 +1309,10 @@ func TestAccElastiCacheReplicationGroup_useCMKKMSKeyID(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroup_UseCMKKMSKeyID(rName), + Config: testAccReplicationGroupConfig_useCMKKMSKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttrSet(resourceName, "kms_key_id"), @@ -1324,10 +1336,10 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClusters_basic(t *testing.T) PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 2), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "automatic_failover_enabled", "false"), @@ -1346,7 +1358,7 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClusters_basic(t *testing.T) ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 4), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 4), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "automatic_failover_enabled", "false"), @@ -1359,7 +1371,7 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClusters_basic(t *testing.T) ), }, { - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 2), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "automatic_failover_enabled", "false"), @@ -1391,10 +1403,10 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersFailover_autoFailover PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_FailoverMultiAZ(rName, 3, autoFailoverEnabled, multiAZEnabled), + Config: testAccReplicationGroupConfig_failoverMultiAZ(rName, 3, autoFailoverEnabled, multiAZEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "automatic_failover_enabled", strconv.FormatBool(autoFailoverEnabled)), @@ -1419,7 +1431,7 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersFailover_autoFailover t.Fatalf("error changing primary cache cluster: %s", err) } }, - Config: testAccReplicationGroupConfig_FailoverMultiAZ(rName, 2, autoFailoverEnabled, multiAZEnabled), + Config: testAccReplicationGroupConfig_failoverMultiAZ(rName, 2, autoFailoverEnabled, multiAZEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "automatic_failover_enabled", strconv.FormatBool(autoFailoverEnabled)), @@ -1448,10 +1460,10 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersFailover_autoFailover PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_FailoverMultiAZ(rName, 3, autoFailoverEnabled, multiAZEnabled), + Config: testAccReplicationGroupConfig_failoverMultiAZ(rName, 3, autoFailoverEnabled, multiAZEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "automatic_failover_enabled", strconv.FormatBool(autoFailoverEnabled)), @@ -1481,7 +1493,7 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersFailover_autoFailover t.Fatalf("error re-enabling automatic failover: %s", err) } }, - Config: testAccReplicationGroupConfig_FailoverMultiAZ(rName, 2, autoFailoverEnabled, multiAZEnabled), + Config: testAccReplicationGroupConfig_failoverMultiAZ(rName, 2, autoFailoverEnabled, multiAZEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "automatic_failover_enabled", strconv.FormatBool(autoFailoverEnabled)), @@ -1510,10 +1522,10 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClusters_multiAZEnabled(t *te PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_FailoverMultiAZ(rName, 3, autoFailoverEnabled, multiAZEnabled), + Config: testAccReplicationGroupConfig_failoverMultiAZ(rName, 3, autoFailoverEnabled, multiAZEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "automatic_failover_enabled", strconv.FormatBool(autoFailoverEnabled)), @@ -1543,7 +1555,7 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClusters_multiAZEnabled(t *te t.Fatalf("error re-enabling automatic failover: %s", err) } }, - Config: testAccReplicationGroupConfig_FailoverMultiAZ(rName, 2, autoFailoverEnabled, multiAZEnabled), + Config: testAccReplicationGroupConfig_failoverMultiAZ(rName, 2, autoFailoverEnabled, multiAZEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "automatic_failover_enabled", strconv.FormatBool(autoFailoverEnabled)), @@ -1569,10 +1581,10 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersMemberClusterDisappea PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 3), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "3"), @@ -1595,7 +1607,7 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersMemberClusterDisappea t.Fatalf("error deleting Cache Cluster (%s): %s", cacheClusterID, err) } }, - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 3), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "3"), @@ -1619,10 +1631,10 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersMemberClusterDisappea PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 3), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "3"), @@ -1645,7 +1657,7 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersMemberClusterDisappea t.Fatalf("error deleting Cache Cluster (%s): %s", cacheClusterID, err) } }, - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 4), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 4), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "4"), @@ -1669,10 +1681,10 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersMemberClusterDisappea PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 3), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "3"), @@ -1695,7 +1707,7 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersMemberClusterDisappea t.Fatalf("error deleting Cache Cluster (%s): %s", cacheClusterID, err) } }, - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 2), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "2"), @@ -1719,10 +1731,10 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersMemberClusterDisappea PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 4), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 4), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "4"), @@ -1745,7 +1757,7 @@ func TestAccElastiCacheReplicationGroup_NumberCacheClustersMemberClusterDisappea t.Fatalf("error deleting Cache Cluster (%s): %s", cacheClusterID, err) } }, - Config: testAccReplicationGroupConfig_NumberCacheClusters(rName, 2), + Config: testAccReplicationGroupConfig_numberCacheClusters(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &replicationGroup), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", "2"), @@ -1770,10 +1782,10 @@ func TestAccElastiCacheReplicationGroup_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupTags1Config(rName, "key1", "value1"), + Config: testAccReplicationGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), testAccReplicationGroupCheckMemberClusterTags(resourceName, clusterDataSourcePrefix, 2, []kvp{ @@ -1788,7 +1800,7 @@ func TestAccElastiCacheReplicationGroup_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately"}, //not in the API }, { - Config: testAccReplicationGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccReplicationGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), testAccReplicationGroupCheckMemberClusterTags(resourceName, clusterDataSourcePrefix, 2, []kvp{ @@ -1798,7 +1810,7 @@ func TestAccElastiCacheReplicationGroup_tags(t *testing.T) { ), }, { - Config: testAccReplicationGroupTags1Config(rName, "key2", "value2"), + Config: testAccReplicationGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), testAccReplicationGroupCheckMemberClusterTags(resourceName, clusterDataSourcePrefix, 2, []kvp{ @@ -1824,10 +1836,10 @@ func TestAccElastiCacheReplicationGroup_tagWithOtherModification(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupVersionAndTagConfig(rName, "5.0.4", "key1", "value1"), + Config: testAccReplicationGroupConfig_versionAndTag(rName, "5.0.4", "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine_version", "5.0.4"), @@ -1837,7 +1849,7 @@ func TestAccElastiCacheReplicationGroup_tagWithOtherModification(t *testing.T) { ), }, { - Config: testAccReplicationGroupVersionAndTagConfig(rName, "5.0.6", "key1", "value1updated"), + Config: testAccReplicationGroupConfig_versionAndTag(rName, "5.0.6", "key1", "value1updated"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine_version", "5.0.6"), @@ -1863,10 +1875,10 @@ func TestAccElastiCacheReplicationGroup_finalSnapshot(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupFinalSnapshotConfig(rName), + Config: testAccReplicationGroupConfig_finalSnapshot(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "final_snapshot_identifier", rName), @@ -1892,7 +1904,7 @@ func TestAccElastiCacheReplicationGroup_autoMinorVersionUpgrade(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroup_AutoMinorVersionUpgrade(rName, false), + Config: testAccReplicationGroupConfig_autoMinorVersionUpgrade(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), @@ -1907,7 +1919,7 @@ func TestAccElastiCacheReplicationGroup_autoMinorVersionUpgrade(t *testing.T) { }, }, { - Config: testAccReplicationGroup_AutoMinorVersionUpgrade(rName, true), + Config: testAccReplicationGroupConfig_autoMinorVersionUpgrade(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "true"), @@ -1928,10 +1940,10 @@ func TestAccElastiCacheReplicationGroup_Validation_noNodeType(t *testing.T) { }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 2), - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_Validation_NoNodeType(rName), + Config: testAccReplicationGroupConfig_validationNoNodeType(rName), ExpectError: regexp.MustCompile(`"node_type" is required unless "global_replication_group_id" is set.`), }, }, @@ -1953,10 +1965,10 @@ func TestAccElastiCacheReplicationGroup_Validation_globalReplicationGroupIdAndNo }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 2), - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_Validation_GlobalReplicationGroupIdAndNodeType(rName), + Config: testAccReplicationGroupConfig_validationGlobalIdAndNodeType(rName), ExpectError: regexp.MustCompile(`"global_replication_group_id": conflicts with node_type`), }, }, @@ -1970,6 +1982,7 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_basic(t *testin var providers []*schema.Provider var rg elasticache.ReplicationGroup + var pg elasticache.CacheParameterGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_elasticache_replication_group.test" primaryGroupResourceName := "aws_elasticache_replication_group.primary" @@ -1981,12 +1994,16 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_basic(t *testin }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 2), - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: resource.ComposeAggregateTestCheckFunc( + testAccCheckReplicationGroupDestroy, + testAccCheckGlobalReplicationGroupMemberParameterGroupDestroy(&pg), + ), Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_Basic(rName), + Config: testAccReplicationGroupConfig_globalIDBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), + testAccCheckReplicationGroupParameterGroup(&rg, &pg), resource.TestCheckResourceAttrPair(resourceName, "global_replication_group_id", "aws_elasticache_global_replication_group.test", "global_replication_group_id"), resource.TestCheckResourceAttrPair(resourceName, "node_type", primaryGroupResourceName, "node_type"), resource.TestCheckResourceAttrPair(resourceName, "engine", primaryGroupResourceName, "engine"), @@ -1997,7 +2014,7 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_basic(t *testin ), }, { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_Basic(rName), + Config: testAccReplicationGroupConfig_globalIDBasic(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -2013,7 +2030,8 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_full(t *testing } var providers []*schema.Provider - var rg elasticache.ReplicationGroup + var rg1, rg2 elasticache.ReplicationGroup + var pg1, pg2 elasticache.CacheParameterGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_elasticache_replication_group.test" primaryGroupResourceName := "aws_elasticache_replication_group.primary" @@ -2028,12 +2046,17 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_full(t *testing }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 2), - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: resource.ComposeAggregateTestCheckFunc( + testAccCheckReplicationGroupDestroy, + testAccCheckGlobalReplicationGroupMemberParameterGroupDestroy(&pg1), + testAccCheckGlobalReplicationGroupMemberParameterGroupDestroy(&pg2), + ), Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_Full(rName, initialNumCacheClusters), + Config: testAccReplicationGroupConfig_globalIDFull(rName, initialNumCacheClusters), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckReplicationGroupExists(resourceName, &rg), + testAccCheckReplicationGroupExists(resourceName, &rg1), + testAccCheckReplicationGroupParameterGroup(&rg1, &pg1), resource.TestCheckResourceAttrPair(resourceName, "global_replication_group_id", "aws_elasticache_global_replication_group.test", "global_replication_group_id"), resource.TestCheckResourceAttrPair(resourceName, "node_type", primaryGroupResourceName, "node_type"), resource.TestCheckResourceAttrPair(resourceName, "engine", primaryGroupResourceName, "engine"), @@ -2051,16 +2074,17 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_full(t *testing ), }, { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_Basic(rName), + Config: testAccReplicationGroupConfig_globalIDBasic(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_Full(rName, updatedNumCacheClusters), + Config: testAccReplicationGroupConfig_globalIDFull(rName, updatedNumCacheClusters), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckReplicationGroupExists(resourceName, &rg), + testAccCheckReplicationGroupExists(resourceName, &rg2), + testAccCheckReplicationGroupParameterGroup(&rg2, &pg2), resource.TestCheckResourceAttr(resourceName, "number_cache_clusters", strconv.Itoa(updatedNumCacheClusters)), ), }, @@ -2068,6 +2092,39 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_full(t *testing }) } +// Test for out-of-band deletion +// Naming to allow grouping all TestAccAWSElasticacheReplicationGroup_GlobalReplicationGroupId_* tests +func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_disappears(t *testing.T) { // nosemgrep: acceptance-test-naming-parent-disappears + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var providers []*schema.Provider + var rg elasticache.ReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckMultipleRegion(t, 2) + }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 2), + CheckDestroy: testAccCheckReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccReplicationGroupConfig_globalIDBasic(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckReplicationGroupExists(resourceName, &rg), + acctest.CheckResourceDisappears(acctest.Provider, tfelasticache.ResourceReplicationGroup(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupIDClusterMode_basic(t *testing.T) { if testing.Short() { t.Skip("skipping long-running test in short mode") @@ -2075,6 +2132,7 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupIDClusterMode_basi var providers []*schema.Provider var rg1, rg2 elasticache.ReplicationGroup + var pg1, pg2 elasticache.CacheParameterGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_elasticache_replication_group.test" primaryGroupResourceName := "aws_elasticache_replication_group.primary" @@ -2086,12 +2144,17 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupIDClusterMode_basi }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 2), - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: resource.ComposeAggregateTestCheckFunc( + testAccCheckReplicationGroupDestroy, + testAccCheckGlobalReplicationGroupMemberParameterGroupDestroy(&pg1), + testAccCheckGlobalReplicationGroupMemberParameterGroupDestroy(&pg2), + ), Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_ClusterMode(rName, 2, 1), + Config: testAccReplicationGroupConfig_globalIDClusterMode(rName, 2, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg1), + testAccCheckReplicationGroupParameterGroup(&rg1, &pg1), resource.TestCheckResourceAttr(resourceName, "cluster_mode.#", "1"), resource.TestCheckResourceAttr(resourceName, "cluster_mode.0.num_node_groups", "2"), resource.TestCheckResourceAttr(resourceName, "cluster_mode.0.replicas_per_node_group", "1"), @@ -2104,16 +2167,17 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupIDClusterMode_basi ), }, { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_Basic(rName), + Config: testAccReplicationGroupConfig_globalIDBasic(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_ClusterMode(rName, 1, 3), + Config: testAccReplicationGroupConfig_globalIDClusterMode(rName, 1, 3), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg2), + testAccCheckReplicationGroupParameterGroup(&rg2, &pg2), resource.TestCheckResourceAttr(resourceName, "cluster_mode.#", "1"), resource.TestCheckResourceAttr(resourceName, "cluster_mode.0.num_node_groups", "2"), resource.TestCheckResourceAttr(resourceName, "cluster_mode.0.replicas_per_node_group", "3"), @@ -2127,6 +2191,65 @@ func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupIDClusterMode_basi }) } +func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupIDClusterModeValidation_numNodeGroupsOnSecondary(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var providers []*schema.Provider + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckMultipleRegion(t, 2) + }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 2), + CheckDestroy: testAccCheckReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccReplicationGroupConfig_globalIDClusterModeNumNodeOnSecondary(rName), + ExpectError: regexp.MustCompile(`"global_replication_group_id": conflicts with cluster_mode.0.num_node_groups`), + }, + }, + }) +} + +func TestAccElastiCacheReplicationGroup_dataTiering(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var rg elasticache.ReplicationGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_elasticache_replication_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckReplicationGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccReplicationGroupConfig_dataTiering(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckReplicationGroupExists(resourceName, &rg), + resource.TestCheckResourceAttr(resourceName, "engine", "redis"), + resource.TestCheckResourceAttr(resourceName, "engine_version", "6.2"), + resource.TestCheckResourceAttr(resourceName, "data_tiering_enabled", "true"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"apply_immediately"}, + }, + }, + }) +} + func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_ClusterMode_Disabled(t *testing.T) { if testing.Short() { t.Skip("skipping long-running test in short mode") @@ -2140,10 +2263,10 @@ func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_C PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName, false, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), + Config: testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, false, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -2165,7 +2288,7 @@ func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_C ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName, false, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), + Config: testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, false, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -2181,7 +2304,7 @@ func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_C ), }, { - Config: testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName, false, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, false, "", ""), + Config: testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, false, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, false, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -2196,7 +2319,7 @@ func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_C ), }, { - Config: testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName, false, false, "", "", false, "", ""), + Config: testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, false, false, "", "", false, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -2234,10 +2357,10 @@ func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_C PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, + CheckDestroy: testAccCheckReplicationGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), + Config: testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -2261,7 +2384,7 @@ func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_C ImportStateVerifyIgnore: []string{"apply_immediately"}, }, { - Config: testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), + Config: testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, true, elasticache.DestinationTypeCloudwatchLogs, elasticache.LogFormatText, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -2279,7 +2402,7 @@ func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_C ), }, { - Config: testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, false, "", ""), + Config: testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, true, elasticache.DestinationTypeKinesisFirehose, elasticache.LogFormatJson, false, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -2297,7 +2420,7 @@ func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_C ), }, { - Config: testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName, true, false, "", "", false, "", ""), + Config: testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName, true, false, "", "", false, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckReplicationGroupExists(resourceName, &rg), resource.TestCheckResourceAttr(resourceName, "engine", "redis"), @@ -2323,98 +2446,6 @@ func TestAccElastiCacheReplicationGroup_Engine_Redis_LogDeliveryConfigurations_C }) } -// Test for out-of-band deletion -// Naming to allow grouping all TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_* tests -func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupID_disappears(t *testing.T) { // nosemgrep: acceptance-test-naming-parent-disappears - if testing.Short() { - t.Skip("skipping long-running test in short mode") - } - - var providers []*schema.Provider - var rg elasticache.ReplicationGroup - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - resourceName := "aws_elasticache_replication_group.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - acctest.PreCheck(t) - acctest.PreCheckMultipleRegion(t, 2) - }, - ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), - ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 2), - CheckDestroy: testAccCheckReplicationDestroy, - Steps: []resource.TestStep{ - { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_Basic(rName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckReplicationGroupExists(resourceName, &rg), - acctest.CheckResourceDisappears(acctest.Provider, tfelasticache.ResourceReplicationGroup(), resourceName), - ), - ExpectNonEmptyPlan: true, - }, - }, - }) -} - -func TestAccElastiCacheReplicationGroup_GlobalReplicationGroupIDClusterModeValidation_numNodeGroupsOnSecondary(t *testing.T) { - if testing.Short() { - t.Skip("skipping long-running test in short mode") - } - - var providers []*schema.Provider - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - acctest.PreCheck(t) - acctest.PreCheckMultipleRegion(t, 2) - }, - ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), - ProviderFactories: acctest.FactoriesMultipleRegion(&providers, 2), - CheckDestroy: testAccCheckReplicationDestroy, - Steps: []resource.TestStep{ - { - Config: testAccReplicationGroupConfig_GlobalReplicationGroupId_ClusterMode_NumNodeGroupsOnSecondary(rName), - ExpectError: regexp.MustCompile(`"global_replication_group_id": conflicts with cluster_mode.0.num_node_groups`), - }, - }, - }) -} - -func TestAccElastiCacheReplicationGroup_dataTiering(t *testing.T) { - if testing.Short() { - t.Skip("skipping long-running test in short mode") - } - - var rg elasticache.ReplicationGroup - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - resourceName := "aws_elasticache_replication_group.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), - ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckReplicationDestroy, - Steps: []resource.TestStep{ - { - Config: testAccReplicationGroupConfigDataTiering(rName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckReplicationGroupExists(resourceName, &rg), - resource.TestCheckResourceAttr(resourceName, "engine", "redis"), - resource.TestCheckResourceAttr(resourceName, "engine_version", "6.2"), - resource.TestCheckResourceAttr(resourceName, "data_tiering_enabled", "true"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"apply_immediately"}, - }, - }, - }) -} - func testAccCheckReplicationGroupExists(n string, v *elasticache.ReplicationGroup) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -2438,7 +2469,7 @@ func testAccCheckReplicationGroupExists(n string, v *elasticache.ReplicationGrou } } -func testAccCheckReplicationDestroy(s *terraform.State) error { +func testAccCheckReplicationGroupDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).ElastiCacheConn for _, rs := range s.RootModule().Resources { @@ -2457,6 +2488,46 @@ func testAccCheckReplicationDestroy(s *terraform.State) error { return nil } +func testAccCheckReplicationGroupParameterGroup(rg *elasticache.ReplicationGroup, pg *elasticache.CacheParameterGroup) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).ElastiCacheConn + + cacheCluster := rg.NodeGroups[0].NodeGroupMembers[0] + cluster, err := tfelasticache.FindCacheClusterByID(conn, aws.StringValue(cacheCluster.CacheClusterId)) + if err != nil { + return fmt.Errorf("could not retrieve cache cluster (%s): %w", aws.StringValue(cacheCluster.CacheClusterId), err) + } + + paramGroupName := aws.StringValue(cluster.CacheParameterGroup.CacheParameterGroupName) + + group, err := tfelasticache.FindParameterGroupByName(conn, paramGroupName) + if err != nil { + return fmt.Errorf("error retrieving parameter group (%s): %w", paramGroupName, err) + } + + *pg = *group + + return nil + } +} + +func testAccCheckGlobalReplicationGroupMemberParameterGroupDestroy(pg *elasticache.CacheParameterGroup) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).ElastiCacheConn + + paramGroupName := aws.StringValue(pg.CacheParameterGroupName) + + _, err := tfelasticache.FindParameterGroupByName(conn, paramGroupName) + if tfresource.NotFound(err) { + return nil + } + if err != nil { + return fmt.Errorf("error finding parameter group (%s): %w", paramGroupName, err) + } + return fmt.Errorf("Cache Parameter Group (%s) still exists", paramGroupName) + } +} + func testAccCheckReplicationGroupUserGroup(resourceName, userGroupID string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] @@ -2527,7 +2598,7 @@ func testAccCheckResourceTags(resourceName string, kvs []kvp) []resource.TestChe return checks } -func testAccReplicationGroupConfig(rName string) string { +func testAccReplicationGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2552,9 +2623,9 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupConfig_Uppercase(rName string) string { +func testAccReplicationGroupConfig_uppercase(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { node_type = "cache.t2.micro" @@ -2573,7 +2644,7 @@ resource "aws_elasticache_subnet_group" "test" { ) } -func testAccReplicationGroupConfig_EngineVersion(rName, engineVersion string) string { +func testAccReplicationGroupConfig_engineVersion(rName, engineVersion string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2590,7 +2661,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName, engineVersion) } -func testAccReplicationGroupEnableSnapshottingConfig(rName string) string { +func testAccReplicationGroupConfig_enableSnapshotting(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2605,7 +2676,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupParameterGroupNameConfig(rName string, parameterGroupNameIndex int) string { +func testAccReplicationGroupConfig_parameterName(rName string, parameterGroupNameIndex int) string { return fmt.Sprintf(` resource "aws_elasticache_parameter_group" "test" { count = 2 @@ -2626,14 +2697,14 @@ resource "aws_elasticache_replication_group" "test" { apply_immediately = true node_type = "cache.t3.small" number_cache_clusters = 2 - parameter_group_name = aws_elasticache_parameter_group.test.*.name[%[2]d] + parameter_group_name = aws_elasticache_parameter_group.test[%[2]d].name replication_group_description = "test description" replication_group_id = %[1]q } `, rName, parameterGroupNameIndex) } -func testAccReplicationGroupUpdatedDescriptionConfig(rName string) string { +func testAccReplicationGroupConfig_updatedDescription(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2645,7 +2716,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupUpdatedMaintenanceWindowConfig(rName string) string { +func testAccReplicationGroupConfig_updatedMaintenanceWindow(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2659,7 +2730,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupUpdatedNodeSizeConfig(rName string) string { +func testAccReplicationGroupConfig_updatedNodeSize(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2671,7 +2742,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupUserGroup(rName, userGroup string, flag int) string { +func testAccReplicationGroupConfig_user(rName, userGroup string, flag int) string { return fmt.Sprintf(` resource "aws_elasticache_user" "test" { count = 2 @@ -2706,9 +2777,9 @@ resource "aws_elasticache_replication_group" "test" { } -func testAccReplicationGroupInVPCConfig(rName string) string { +func testAccReplicationGroupConfig_inVPC(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 1), + acctest.ConfigVPCWithSubnets(rName, 1), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2742,9 +2813,9 @@ resource "aws_security_group" "test" { ) } -func testAccReplicationGroupInVPCConfig_DeprecatedAvailabilityZones(rName string) string { +func testAccReplicationGroupConfig_inVPCDeprecatedAvailabilityZones(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 1), + acctest.ConfigVPCWithSubnets(rName, 1), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2778,7 +2849,7 @@ resource "aws_security_group" "test" { ) } -func testAccReplicationGroupConfig_MultiAZNotInVPC_Basic(rName string) string { +func testAccReplicationGroupConfig_multiAZNotInVPCBasic(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2791,7 +2862,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupConfig_MultiAZNotInVPC_PreferredCacheClusterAZs_notRepeated(rName string) string { +func testAccReplicationGroupConfig_multiAZNotInVPCPreferredCacheClusterAZsNotRepeated(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2808,7 +2879,7 @@ resource "aws_elasticache_replication_group" "test" { ) } -func testAccReplicationGroupConfig_MultiAZNotInVPC_PreferredCacheClusterAZs_repeated(rName string) string { +func testAccReplicationGroupConfig_multiAZNotInVPCPreferredCacheClusterAZsRepeated(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2825,7 +2896,7 @@ resource "aws_elasticache_replication_group" "test" { ) } -func testAccReplicationGroupConfig_MultiAZNotInVPC_DeprecatedAvailabilityZones(rName string) string { +func testAccReplicationGroupConfig_multiAZNotInVPCDeprecatedAvailabilityZones(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2842,9 +2913,9 @@ resource "aws_elasticache_replication_group" "test" { ) } -func testAccReplicationGroupMultiAZInVPCConfig(rName string) string { +func testAccReplicationGroupConfig_multiAZInVPC(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2882,7 +2953,7 @@ resource "aws_security_group" "test" { ) } -func testAccReplicationGroupConfig_MultiAZ_NoAutomaticFailover(rName string) string { +func testAccReplicationGroupConfig_multiAZNoAutomaticFailover(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2895,9 +2966,9 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupNativeRedisClusterErrorConfig(rName string) string { +func testAccReplicationGroupConfig_nativeRedisClusterError(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -2937,7 +3008,7 @@ resource "aws_security_group" "test" { ) } -func testAccReplicationGroupNativeRedisClusterConfig(rName string, numNodeGroups, replicasPerNodeGroup int) string { +func testAccReplicationGroupConfig_nativeRedisCluster(rName string, numNodeGroups, replicasPerNodeGroup int) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), testAccReplicationGroupClusterData(numNodeGroups*(1+replicasPerNodeGroup)), @@ -3015,7 +3086,7 @@ resource "aws_elasticache_replication_group" "test" { ) } -func testAccReplicationGroupNativeRedisClusterConfig_NonClusteredParameterGroup(rName string) string { +func testAccReplicationGroupConfig_nativeRedisClusterNonClusteredParameter(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -3035,7 +3106,7 @@ resource "aws_elasticache_replication_group" "test" { ) } -func testAccReplicationGroupNativeRedisClusterConfig_SingleNode(rName string) string { +func testAccReplicationGroupConfig_nativeRedisClusterSingleNode(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -3055,9 +3126,9 @@ resource "aws_elasticache_replication_group" "test" { ) } -func testAccReplicationGroup_UseCMKKMSKeyID(rName string) string { +func testAccReplicationGroupConfig_useCMKKMSKeyID(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 1), + acctest.ConfigVPCWithSubnets(rName, 1), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -3098,9 +3169,9 @@ resource "aws_kms_key" "test" { ) } -func testAccReplicationGroup_EnableAtRestEncryptionConfig(rName string) string { +func testAccReplicationGroupConfig_enableAtRestEncryption(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 1), + acctest.ConfigVPCWithSubnets(rName, 1), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -3136,9 +3207,9 @@ resource "aws_security_group" "test" { ) } -func testAccReplicationGroup_EnableAuthTokenTransitEncryptionConfig(rName string, authToken string) string { +func testAccReplicationGroupConfig_enableAuthTokenTransitEncryption(rName string, authToken string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 1), + acctest.ConfigVPCWithSubnets(rName, 1), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -3175,9 +3246,9 @@ resource "aws_security_group" "test" { ) } -func testAccReplicationGroupConfig_NumberCacheClusters(rName string, numberCacheClusters int) string { +func testAccReplicationGroupConfig_numberCacheClusters(rName string, numberCacheClusters int) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), testAccReplicationGroupClusterData(numberCacheClusters), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { @@ -3200,9 +3271,9 @@ resource "aws_elasticache_subnet_group" "test" { ) } -func testAccReplicationGroupConfig_FailoverMultiAZ(rName string, numberCacheClusters int, autoFailover, multiAZ bool) string { +func testAccReplicationGroupConfig_failoverMultiAZ(rName string, numberCacheClusters int, autoFailover, multiAZ bool) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { # InvalidParameterCombination: Automatic failover is not supported for T1 and T2 cache node types. @@ -3223,7 +3294,7 @@ resource "aws_elasticache_subnet_group" "test" { ) } -func testAccReplicationGroupTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccReplicationGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { const clusterCount = 2 return acctest.ConfigCompose( testAccReplicationGroupClusterData(clusterCount), @@ -3246,7 +3317,7 @@ resource "aws_elasticache_replication_group" "test" { ) } -func testAccReplicationGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccReplicationGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { const clusterCount = 2 return acctest.ConfigCompose( testAccReplicationGroupClusterData(clusterCount), @@ -3270,7 +3341,7 @@ resource "aws_elasticache_replication_group" "test" { ) } -func testAccReplicationGroupVersionAndTagConfig(rName, version, tagKey1, tagValue1 string) string { +func testAccReplicationGroupConfig_versionAndTag(rName, version, tagKey1, tagValue1 string) string { const clusterCount = 2 return acctest.ConfigCompose( testAccReplicationGroupClusterData(clusterCount), @@ -3301,7 +3372,7 @@ data "aws_elasticache_cluster" "test" { `, count) } -func testAccReplicationGroupFinalSnapshotConfig(rName string) string { +func testAccReplicationGroupConfig_finalSnapshot(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -3314,7 +3385,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroup_AutoMinorVersionUpgrade(rName string, enable bool) string { +func testAccReplicationGroupConfig_autoMinorVersionUpgrade(rName string, enable bool) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -3326,7 +3397,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName, enable) } -func testAccReplicationGroupConfig_Validation_NoNodeType(rName string) string { +func testAccReplicationGroupConfig_validationNoNodeType(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -3336,7 +3407,7 @@ resource "aws_elasticache_replication_group" "test" { `, rName) } -func testAccReplicationGroupConfig_Validation_GlobalReplicationGroupIdAndNodeType(rName string) string { +func testAccReplicationGroupConfig_validationGlobalIdAndNodeType(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), testAccVPCBaseWithProvider(rName, "test", acctest.ProviderName, 1), @@ -3381,7 +3452,7 @@ resource "aws_elasticache_replication_group" "primary" { ) } -func testAccReplicationGroupConfig_GlobalReplicationGroupId_Basic(rName string) string { +func testAccReplicationGroupConfig_globalIDBasic(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), testAccVPCBaseWithProvider(rName, "test", acctest.ProviderName, 1), @@ -3420,7 +3491,7 @@ resource "aws_elasticache_replication_group" "primary" { ) } -func testAccReplicationGroupConfig_GlobalReplicationGroupId_Full(rName string, numCacheClusters int) string { +func testAccReplicationGroupConfig_globalIDFull(rName string, numCacheClusters int) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), testAccVPCBaseWithProvider(rName, "test", acctest.ProviderName, 2), @@ -3472,7 +3543,7 @@ resource "aws_elasticache_replication_group" "primary" { ) } -func testAccReplicationGroupConfig_GlobalReplicationGroupId_ClusterMode(rName string, primaryReplicaCount, secondaryReplicaCount int) string { +func testAccReplicationGroupConfig_globalIDClusterMode(rName string, primaryReplicaCount, secondaryReplicaCount int) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), testAccVPCBaseWithProvider(rName, "test", acctest.ProviderName, 2), @@ -3522,7 +3593,7 @@ resource "aws_elasticache_replication_group" "primary" { ) } -func testAccReplicationGroupConfig_GlobalReplicationGroupId_ClusterMode_NumNodeGroupsOnSecondary(rName string) string { +func testAccReplicationGroupConfig_globalIDClusterModeNumNodeOnSecondary(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), testAccVPCBaseWithProvider(rName, "test", acctest.ProviderName, 2), @@ -3573,9 +3644,9 @@ resource "aws_elasticache_replication_group" "primary" { ) } -func testAccReplicationGroupConfigDataTiering(rName string) string { +func testAccReplicationGroupConfig_dataTiering(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 1), + acctest.ConfigVPCWithSubnets(rName, 1), fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { replication_group_id = %[1]q @@ -3608,7 +3679,7 @@ resource "aws_security_group" "test" { ) } -func testAccReplicationGroupConfig_Engine_Redis_LogDeliveryConfigurations(rName string, enableClusterMode bool, slowLogDeliveryEnabled bool, slowDeliveryDestination string, slowDeliveryFormat string, engineLogDeliveryEnabled bool, engineDeliveryDestination string, engineLogDeliveryFormat string) string { +func testAccReplicationGroupConfig_dataSourceEngineRedisLogDeliveryConfigurations(rName string, enableClusterMode bool, slowLogDeliveryEnabled bool, slowDeliveryDestination string, slowDeliveryFormat string, engineLogDeliveryEnabled bool, engineDeliveryDestination string, engineLogDeliveryFormat string) string { return fmt.Sprintf(` data "aws_iam_policy_document" "p" { statement { diff --git a/internal/service/elasticache/security_group_test.go b/internal/service/elasticache/security_group_test.go index 16339e2f83a..92f8b9a4334 100644 --- a/internal/service/elasticache/security_group_test.go +++ b/internal/service/elasticache/security_group_test.go @@ -25,7 +25,7 @@ func TestAccElastiCacheSecurityGroup_basic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig(rName), + Config: testAccSecurityGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), @@ -85,7 +85,7 @@ func testAccCheckSecurityGroupExists(n string) resource.TestCheckFunc { } } -func testAccSecurityGroupConfig(rName string) string { +func testAccSecurityGroupConfig_basic(rName string) string { return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` diff --git a/internal/service/elasticache/subnet_group.go b/internal/service/elasticache/subnet_group.go index 21f099f4551..0e9723da983 100644 --- a/internal/service/elasticache/subnet_group.go +++ b/internal/service/elasticache/subnet_group.go @@ -103,7 +103,7 @@ func resourceSubnetGroupCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateCacheSubnetGroup(req) - if req.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if req.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating ElastiCache Subnet Group with tags: %s. Trying create without tags.", err) req.Tags = nil @@ -125,7 +125,7 @@ func resourceSubnetGroupCreate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, aws.StringValue(output.CacheSubnetGroup.ARN), nil, tags) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed adding tags after create for ElastiCache Subnet Group (%s): %w", d.Id(), err) } @@ -183,7 +183,7 @@ func resourceSubnetGroupRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, d.Get("arn").(string)) - if err != nil && !verify.CheckISOErrorTagsUnsupported(err) { + if err != nil && !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { return fmt.Errorf("listing tags for ElastiCache Subnet Group (%s): %w", d.Id(), err) } @@ -236,7 +236,7 @@ func resourceSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, d.Get("arn").(string), o, n) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed updating ElastiCache Subnet Group (%s) tags: %w", d.Id(), err) } diff --git a/internal/service/elasticache/subnet_group_test.go b/internal/service/elasticache/subnet_group_test.go index 562d25c91f5..74fc993b7ea 100644 --- a/internal/service/elasticache/subnet_group_test.go +++ b/internal/service/elasticache/subnet_group_test.go @@ -25,7 +25,7 @@ func TestAccElastiCacheSubnetGroup_basic(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig(sdkacctest.RandInt()), + Config: testAccSubnetGroupConfig_basic(sdkacctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &csg), resource.TestCheckResourceAttr( @@ -55,7 +55,7 @@ func TestAccElastiCacheSubnetGroup_update(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupUpdatePreConfig(rInt), + Config: testAccSubnetGroupConfig_updatePre(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &csg), testAccCheckSubnetGroupAttrs(&csg, resourceName, 1), @@ -69,7 +69,7 @@ func TestAccElastiCacheSubnetGroup_update(t *testing.T) { "description"}, }, { - Config: testAccSubnetGroupUpdatePostConfig(rInt), + Config: testAccSubnetGroupConfig_updatePost(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &csg), testAccCheckSubnetGroupAttrs(&csg, resourceName, 2), @@ -91,7 +91,7 @@ func TestAccElastiCacheSubnetGroup_tags(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupTags1(rInt, "key1", "value1"), + Config: testAccSubnetGroupConfig_tags1(rInt, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &csg), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -108,7 +108,7 @@ func TestAccElastiCacheSubnetGroup_tags(t *testing.T) { "description"}, }, { - Config: testAccSubnetGroupTags2(rInt, "key1", "value1updated", "key2", "value2"), + Config: testAccSubnetGroupConfig_tags2(rInt, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &csg), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -120,7 +120,7 @@ func TestAccElastiCacheSubnetGroup_tags(t *testing.T) { ), }, { - Config: testAccSubnetGroupTags1(rInt, "key2", "value2"), + Config: testAccSubnetGroupConfig_tags1(rInt, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &csg), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -209,7 +209,7 @@ func testAccCheckSubnetGroupAttrs(csg *elasticache.CacheSubnetGroup, n string, c } } -func testAccSubnetGroupConfig(rInt int) string { +func testAccSubnetGroupConfig_basic(rInt int) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "192.168.0.0/16" @@ -239,7 +239,7 @@ resource "aws_elasticache_subnet_group" "test" { `, rInt)) } -func testAccSubnetGroupUpdatePreConfig(rInt int) string { +func testAccSubnetGroupConfig_updatePre(rInt int) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.0.0.0/16" @@ -267,7 +267,7 @@ resource "aws_elasticache_subnet_group" "test" { `, rInt)) } -func testAccSubnetGroupUpdatePostConfig(rInt int) string { +func testAccSubnetGroupConfig_updatePost(rInt int) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.0.0.0/16" @@ -308,7 +308,7 @@ resource "aws_elasticache_subnet_group" "test" { `, rInt)) } -func testAccSubnetGroupTags1(rInt int, tag1Key, tag1Value string) string { +func testAccSubnetGroupConfig_tags1(rInt int, tag1Key, tag1Value string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "192.168.0.0/16" @@ -342,7 +342,7 @@ resource "aws_elasticache_subnet_group" "test" { `, rInt, tag1Key, tag1Value)) } -func testAccSubnetGroupTags2(rInt int, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccSubnetGroupConfig_tags2(rInt int, tag1Key, tag1Value, tag2Key, tag2Value string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "192.168.0.0/16" diff --git a/internal/service/elasticache/user.go b/internal/service/elasticache/user.go index aad9f7802ec..56c230fabf2 100644 --- a/internal/service/elasticache/user.go +++ b/internal/service/elasticache/user.go @@ -100,7 +100,7 @@ func resourceUserCreate(d *schema.ResourceData, meta interface{}) error { out, err := conn.CreateUser(input) - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating ElastiCache User with tags: %s. Trying create without tags.", err) input.Tags = nil @@ -118,7 +118,7 @@ func resourceUserCreate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, aws.StringValue(out.ARN), nil, tags) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed adding tags after create for ElastiCache User (%s): %w", d.Id(), err) } @@ -154,7 +154,7 @@ func resourceUserRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, aws.StringValue(resp.ARN)) - if err != nil && !verify.CheckISOErrorTagsUnsupported(err) { + if err != nil && !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { return fmt.Errorf("listing tags for ElastiCache User (%s): %w", aws.StringValue(resp.ARN), err) } @@ -222,7 +222,7 @@ func resourceUserUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, d.Get("arn").(string), o, n) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed updating ElastiCache User (%s) tags: %w", d.Get("arn").(string), err) } diff --git a/internal/service/elasticache/user_data_source_test.go b/internal/service/elasticache/user_data_source_test.go index 00911f49ed2..20222f2d6b7 100644 --- a/internal/service/elasticache/user_data_source_test.go +++ b/internal/service/elasticache/user_data_source_test.go @@ -21,7 +21,7 @@ func TestAccElastiCacheUserDataSource_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccUserWithDataSourceConfig(rName), + Config: testAccUserDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "engine", resourceName, "engine"), resource.TestCheckResourceAttrPair(dataSourceName, "user_id", resourceName, "user_id"), @@ -34,7 +34,7 @@ func TestAccElastiCacheUserDataSource_basic(t *testing.T) { } // Basic Resource -func testAccUserWithDataSourceConfig(rName string) string { +func testAccUserDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_user" "test-basic" { user_id = %[1]q diff --git a/internal/service/elasticache/user_group.go b/internal/service/elasticache/user_group.go index a4137e4dbc5..dc05fd9edb6 100644 --- a/internal/service/elasticache/user_group.go +++ b/internal/service/elasticache/user_group.go @@ -85,7 +85,7 @@ func resourceUserGroupCreate(d *schema.ResourceData, meta interface{}) error { out, err := conn.CreateUserGroup(input) - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating ElastiCache User Group with tags: %s. Trying create without tags.", err) input.Tags = nil @@ -118,7 +118,7 @@ func resourceUserGroupCreate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, aws.StringValue(out.ARN), nil, tags) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed adding tags after create for ElastiCache User Group (%s): %w", d.Id(), err) } @@ -153,7 +153,7 @@ func resourceUserGroupRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, aws.StringValue(resp.ARN)) - if err != nil && !verify.CheckISOErrorTagsUnsupported(err) { + if err != nil && !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { return fmt.Errorf("listing tags for ElastiCache User Group (%s): %w", aws.StringValue(resp.ARN), err) } @@ -230,7 +230,7 @@ func resourceUserGroupUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, d.Get("arn").(string), o, n) if err != nil { - if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (ok && len(v.(map[string]interface{})) > 0) || !verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // explicitly setting tags or not an iso-unsupported error return fmt.Errorf("failed updating ElastiCache User Group (%s) tags: %w", d.Get("arn").(string), err) } diff --git a/internal/service/elasticache/user_group_association_test.go b/internal/service/elasticache/user_group_association_test.go index 27daebbe8f2..ecf1224c438 100644 --- a/internal/service/elasticache/user_group_association_test.go +++ b/internal/service/elasticache/user_group_association_test.go @@ -31,7 +31,7 @@ func TestAccElastiCacheUserGroupAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckUserGroupAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserGroupAssociationBasicConfig(rName), + Config: testAccUserGroupAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "user_id", fmt.Sprintf("%s-2", rName)), @@ -62,7 +62,7 @@ func TestAccElastiCacheUserGroupAssociation_update(t *testing.T) { CheckDestroy: testAccCheckUserGroupAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserGroupAssociationPreUpdateConfig(rName), + Config: testAccUserGroupAssociationConfig_preUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "user_id", fmt.Sprintf("%s-2", rName)), @@ -70,7 +70,7 @@ func TestAccElastiCacheUserGroupAssociation_update(t *testing.T) { ), }, { - Config: testAccUserGroupAssociationUpdateConfig(rName), + Config: testAccUserGroupAssociationConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "user_id", fmt.Sprintf("%s-3", rName)), @@ -92,7 +92,7 @@ func TestAccElastiCacheUserGroupAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckUserGroupAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccUserGroupAssociationBasicConfig(rName), + Config: testAccUserGroupAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfelasticache.ResourceUserGroupAssociation(), resourceName), @@ -220,7 +220,7 @@ resource "aws_elasticache_user_group" "test" { `, rName)) } -func testAccUserGroupAssociationBasicConfig(rName string) string { +func testAccUserGroupAssociationConfig_basic(rName string) string { return acctest.ConfigCompose( testAccUserGroupAssociationBaseConfig(rName), ` @@ -231,7 +231,7 @@ resource "aws_elasticache_user_group_association" "test" { `) } -func testAccUserGroupAssociationPreUpdateConfig(rName string) string { +func testAccUserGroupAssociationConfig_preUpdate(rName string) string { return acctest.ConfigCompose( testAccUserGroupAssociationBaseConfig(rName), fmt.Sprintf(` @@ -250,7 +250,7 @@ resource "aws_elasticache_user_group_association" "test" { `, rName)) } -func testAccUserGroupAssociationUpdateConfig(rName string) string { +func testAccUserGroupAssociationConfig_update(rName string) string { return acctest.ConfigCompose( testAccUserGroupAssociationBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/elasticache/user_group_test.go b/internal/service/elasticache/user_group_test.go index 3b8878b7a83..861cb0deabd 100644 --- a/internal/service/elasticache/user_group_test.go +++ b/internal/service/elasticache/user_group_test.go @@ -27,7 +27,7 @@ func TestAccElastiCacheUserGroup_basic(t *testing.T) { CheckDestroy: testAccCheckUserGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccUserGroupBasicConfig(rName), + Config: testAccUserGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupExists(resourceName, &userGroup), resource.TestCheckResourceAttr(resourceName, "user_ids.#", "1"), @@ -56,7 +56,7 @@ func TestAccElastiCacheUserGroup_update(t *testing.T) { CheckDestroy: testAccCheckUserGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccUserGroupBasicConfig(rName), + Config: testAccUserGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupExists(resourceName, &userGroup), resource.TestCheckResourceAttr(resourceName, "user_ids.#", "1"), @@ -65,7 +65,7 @@ func TestAccElastiCacheUserGroup_update(t *testing.T) { ), }, { - Config: testAccUserGroupMultipleConfig(rName), + Config: testAccUserGroupConfig_multiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupExists(resourceName, &userGroup), resource.TestCheckResourceAttr(resourceName, "user_ids.#", "2"), @@ -74,7 +74,7 @@ func TestAccElastiCacheUserGroup_update(t *testing.T) { ), }, { - Config: testAccUserGroupBasicConfig(rName), + Config: testAccUserGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupExists(resourceName, &userGroup), resource.TestCheckResourceAttr(resourceName, "user_ids.#", "1"), @@ -98,7 +98,7 @@ func TestAccElastiCacheUserGroup_tags(t *testing.T) { CheckDestroy: testAccCheckUserGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccUserGroupConfigTags1(rName, "key1", "value1"), + Config: testAccUserGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupExists(resourceName, &userGroup), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -106,7 +106,7 @@ func TestAccElastiCacheUserGroup_tags(t *testing.T) { ), }, { - Config: testAccUserGroupConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccUserGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupExists(resourceName, &userGroup), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -115,7 +115,7 @@ func TestAccElastiCacheUserGroup_tags(t *testing.T) { ), }, { - Config: testAccUserGroupConfigTags1(rName, "key2", "value2"), + Config: testAccUserGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupExists(resourceName, &userGroup), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -138,7 +138,7 @@ func TestAccElastiCacheUserGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckUserGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccUserGroupBasicConfig(rName), + Config: testAccUserGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserGroupExists(resourceName, &userGroup), acctest.CheckResourceDisappears(acctest.Provider, tfelasticache.ResourceUserGroup(), resourceName), @@ -202,7 +202,7 @@ func testAccCheckUserGroupExistsWithProvider(n string, v *elasticache.UserGroup, } } -func testAccUserGroupBasicConfig(rName string) string { +func testAccUserGroupConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elasticache_user" "test1" { user_id = "%[1]s-1" @@ -228,7 +228,7 @@ resource "aws_elasticache_user_group" "test" { `, rName)) } -func testAccUserGroupMultipleConfig(rName string) string { +func testAccUserGroupConfig_multiple(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elasticache_user" "test1" { user_id = "%[1]s-1" @@ -254,7 +254,7 @@ resource "aws_elasticache_user_group" "test" { `, rName)) } -func testAccUserGroupConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccUserGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elasticache_user" "test1" { user_id = "%[1]s-1" @@ -274,7 +274,7 @@ resource "aws_elasticache_user_group" "test" { `, rName, tagKey1, tagValue1)) } -func testAccUserGroupConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccUserGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elasticache_user" "test1" { user_id = "%[1]s-1" diff --git a/internal/service/elasticache/user_test.go b/internal/service/elasticache/user_test.go index e1fba2087a0..9d059dc1990 100644 --- a/internal/service/elasticache/user_test.go +++ b/internal/service/elasticache/user_test.go @@ -28,7 +28,7 @@ func TestAccElastiCacheUser_basic(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserBasicConfig(rName), + Config: testAccUserConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), resource.TestCheckResourceAttr(resourceName, "user_id", rName), @@ -62,13 +62,13 @@ func TestAccElastiCacheUser_update(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserBasicConfig(rName), + Config: testAccUserConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), ), }, { - Config: testAccUserUpdateConfig(rName), + Config: testAccUserConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), resource.TestCheckResourceAttr(resourceName, "access_string", "on ~* +@all"), @@ -99,7 +99,7 @@ func TestAccElastiCacheUser_tags(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserTagsConfig(rName, "tagKey", "tagVal"), + Config: testAccUserConfig_tags(rName, "tagKey", "tagVal"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), resource.TestCheckResourceAttr(resourceName, "user_id", rName), @@ -111,7 +111,7 @@ func TestAccElastiCacheUser_tags(t *testing.T) { ), }, { - Config: testAccUserTagsConfig(rName, "tagKey", "tagVal2"), + Config: testAccUserConfig_tags(rName, "tagKey", "tagVal2"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), resource.TestCheckResourceAttr(resourceName, "user_id", rName), @@ -123,7 +123,7 @@ func TestAccElastiCacheUser_tags(t *testing.T) { ), }, { - Config: testAccUserBasicConfig(rName), + Config: testAccUserConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), resource.TestCheckResourceAttr(resourceName, "user_id", rName), @@ -149,7 +149,7 @@ func TestAccElastiCacheUser_disappears(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserBasicConfig(rName), + Config: testAccUserConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), acctest.CheckResourceDisappears(acctest.Provider, tfelasticache.ResourceUser(), resourceName), @@ -218,7 +218,7 @@ func testAccCheckUserExistsWithProvider(n string, v *elasticache.User, providerF } } -func testAccUserBasicConfig(rName string) string { +func testAccUserConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elasticache_user" "test" { user_id = %[1]q @@ -230,7 +230,7 @@ resource "aws_elasticache_user" "test" { `, rName)) } -func testAccUserUpdateConfig(rName string) string { +func testAccUserConfig_update(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elasticache_user" "test" { user_id = %[1]q @@ -242,7 +242,7 @@ resource "aws_elasticache_user" "test" { `, rName)) } -func testAccUserTagsConfig(rName, tagKey, tagValue string) string { +func testAccUserConfig_tags(rName, tagKey, tagValue string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elasticache_user" "test" { user_id = %[1]q diff --git a/internal/service/elasticbeanstalk/application.go b/internal/service/elasticbeanstalk/application.go index efdfbce6691..991a69ce61c 100644 --- a/internal/service/elasticbeanstalk/application.go +++ b/internal/service/elasticbeanstalk/application.go @@ -225,7 +225,7 @@ func resourceApplicationRead(d *schema.ResourceData, meta interface{}) error { var app *elasticbeanstalk.ApplicationDescription err := resource.Retry(30*time.Second, func() *resource.RetryError { var err error - app, err = getBeanstalkApplication(d.Id(), conn) + app, err = getApplication(d.Id(), conn) if err != nil { return resource.NonRetryableError(err) } @@ -240,7 +240,7 @@ func resourceApplicationRead(d *schema.ResourceData, meta interface{}) error { return nil }) if tfresource.TimedOut(err) { - app, err = getBeanstalkApplication(d.Id(), conn) + app, err = getApplication(d.Id(), conn) } if err != nil { if app == nil { @@ -292,7 +292,7 @@ func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { var app *elasticbeanstalk.ApplicationDescription err = resource.Retry(10*time.Second, func() *resource.RetryError { - app, err = getBeanstalkApplication(d.Id(), meta.(*conns.AWSClient).ElasticBeanstalkConn) + app, err = getApplication(d.Id(), meta.(*conns.AWSClient).ElasticBeanstalkConn) if err != nil { return resource.NonRetryableError(err) } @@ -304,7 +304,7 @@ func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { return nil }) if tfresource.TimedOut(err) { - app, err = getBeanstalkApplication(d.Id(), meta.(*conns.AWSClient).ElasticBeanstalkConn) + app, err = getApplication(d.Id(), meta.(*conns.AWSClient).ElasticBeanstalkConn) } if err != nil { return fmt.Errorf("Error deleting Beanstalk application: %s", err) @@ -312,7 +312,7 @@ func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func getBeanstalkApplication(id string, conn *elasticbeanstalk.ElasticBeanstalk) (*elasticbeanstalk.ApplicationDescription, error) { +func getApplication(id string, conn *elasticbeanstalk.ElasticBeanstalk) (*elasticbeanstalk.ApplicationDescription, error) { resp, err := conn.DescribeApplications(&elasticbeanstalk.DescribeApplicationsInput{ ApplicationNames: []*string{aws.String(id)}, }) diff --git a/internal/service/elasticbeanstalk/application_data_source_test.go b/internal/service/elasticbeanstalk/application_data_source_test.go index 44a2a414f13..3e31670232b 100644 --- a/internal/service/elasticbeanstalk/application_data_source_test.go +++ b/internal/service/elasticbeanstalk/application_data_source_test.go @@ -26,7 +26,7 @@ func TestAccElasticBeanstalkApplicationDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckEKSClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationDataSourceConfig_Basic(rName), + Config: testAccApplicationDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceResourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceResourceName, "name"), @@ -41,14 +41,14 @@ func TestAccElasticBeanstalkApplicationDataSource_basic(t *testing.T) { }) } -func testAccApplicationDataSourceConfig_Basic(rName string) string { +func testAccApplicationDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` %s data "aws_elastic_beanstalk_application" "test" { name = aws_elastic_beanstalk_application.tftest.name } -`, testAccBeanstalkAppConfigWithMaxAge(rName)) +`, testAccApplicationConfig_maxAge(rName)) } func testAccCheckEKSClusterDestroy(s *terraform.State) error { diff --git a/internal/service/elasticbeanstalk/application_test.go b/internal/service/elasticbeanstalk/application_test.go index 4e3808c94c2..447f562ebf9 100644 --- a/internal/service/elasticbeanstalk/application_test.go +++ b/internal/service/elasticbeanstalk/application_test.go @@ -23,12 +23,12 @@ func TestAccElasticBeanstalkApplication_BeanstalkApp_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkAppDestroy, + CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkAppConfig(rName), + Config: testAccApplicationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkAppExists(resourceName, &app), + testAccCheckApplicationExists(resourceName, &app), ), }, { @@ -48,12 +48,12 @@ func TestAccElasticBeanstalkApplication_BeanstalkApp_appVersionLifecycle(t *test PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkAppDestroy, + CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkAppConfig(rName), + Config: testAccApplicationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkAppExists("aws_elastic_beanstalk_application.tftest", &app), + testAccCheckApplicationExists("aws_elastic_beanstalk_application.tftest", &app), resource.TestCheckNoResourceAttr("aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.0.service_role"), resource.TestCheckNoResourceAttr("aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.0.max_age_in_days"), resource.TestCheckNoResourceAttr("aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.0.max_count"), @@ -61,9 +61,9 @@ func TestAccElasticBeanstalkApplication_BeanstalkApp_appVersionLifecycle(t *test ), }, { - Config: testAccBeanstalkAppConfigWithMaxAge(rName), + Config: testAccApplicationConfig_maxAge(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkAppExists("aws_elastic_beanstalk_application.tftest", &app), + testAccCheckApplicationExists("aws_elastic_beanstalk_application.tftest", &app), resource.TestCheckResourceAttr("aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.#", "1"), resource.TestCheckResourceAttrPair( "aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.0.service_role", @@ -74,9 +74,9 @@ func TestAccElasticBeanstalkApplication_BeanstalkApp_appVersionLifecycle(t *test ), }, { - Config: testAccBeanstalkAppConfigWithMaxCount(rName), + Config: testAccApplicationConfig_maxCount(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkAppExists("aws_elastic_beanstalk_application.tftest", &app), + testAccCheckApplicationExists("aws_elastic_beanstalk_application.tftest", &app), resource.TestCheckResourceAttr("aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.#", "1"), resource.TestCheckResourceAttrPair( "aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.0.service_role", @@ -87,9 +87,9 @@ func TestAccElasticBeanstalkApplication_BeanstalkApp_appVersionLifecycle(t *test ), }, { - Config: testAccBeanstalkAppConfig(rName), + Config: testAccApplicationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkAppExists("aws_elastic_beanstalk_application.tftest", &app), + testAccCheckApplicationExists("aws_elastic_beanstalk_application.tftest", &app), resource.TestCheckNoResourceAttr("aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.0.service_role"), resource.TestCheckNoResourceAttr("aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.0.max_age_in_days"), resource.TestCheckNoResourceAttr("aws_elastic_beanstalk_application.tftest", "appversion_lifecycle.0.max_count"), @@ -109,30 +109,30 @@ func TestAccElasticBeanstalkApplication_BeanstalkApp_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkAppDestroy, + CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkAppConfigWithTags(rName, "test1", "test2"), + Config: testAccApplicationConfig_tags2(rName, "test1", "test2"), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkAppExists(resourceName, &app), + testAccCheckApplicationExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.firstTag", "test1"), resource.TestCheckResourceAttr(resourceName, "tags.secondTag", "test2"), ), }, { - Config: testAccBeanstalkAppConfigWithTags(rName, "updateTest1", "updateTest2"), + Config: testAccApplicationConfig_tags2(rName, "updateTest1", "updateTest2"), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkAppExists(resourceName, &app), + testAccCheckApplicationExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.firstTag", "updateTest1"), resource.TestCheckResourceAttr(resourceName, "tags.secondTag", "updateTest2"), ), }, { - Config: testAccBeanstalkAppConfigWithAddTags(rName, "updateTest1", "updateTest2", "addTest3"), + Config: testAccApplicationConfig_tags(rName, "updateTest1", "updateTest2", "addTest3"), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkAppExists(resourceName, &app), + testAccCheckApplicationExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), resource.TestCheckResourceAttr(resourceName, "tags.firstTag", "updateTest1"), resource.TestCheckResourceAttr(resourceName, "tags.secondTag", "updateTest2"), @@ -140,9 +140,9 @@ func TestAccElasticBeanstalkApplication_BeanstalkApp_tags(t *testing.T) { ), }, { - Config: testAccBeanstalkAppConfigWithTags(rName, "updateTest1", "updateTest2"), + Config: testAccApplicationConfig_tags2(rName, "updateTest1", "updateTest2"), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkAppExists(resourceName, &app), + testAccCheckApplicationExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.firstTag", "updateTest1"), resource.TestCheckResourceAttr(resourceName, "tags.secondTag", "updateTest2"), @@ -157,7 +157,7 @@ func TestAccElasticBeanstalkApplication_BeanstalkApp_tags(t *testing.T) { }) } -func testAccCheckBeanstalkAppDestroy(s *terraform.State) error { +func testAccCheckApplicationDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn for _, rs := range s.RootModule().Resources { @@ -185,7 +185,7 @@ func testAccCheckBeanstalkAppDestroy(s *terraform.State) error { return nil } -func testAccCheckBeanstalkAppExists(n string, app *elasticbeanstalk.ApplicationDescription) resource.TestCheckFunc { +func testAccCheckApplicationExists(n string, app *elasticbeanstalk.ApplicationDescription) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -214,7 +214,7 @@ func testAccCheckBeanstalkAppExists(n string, app *elasticbeanstalk.ApplicationD } } -func testAccBeanstalkAppConfig(rName string) string { +func testAccApplicationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "%s" @@ -223,7 +223,7 @@ resource "aws_elastic_beanstalk_application" "tftest" { `, rName) } -func testAccBeanstalkAppServiceRole(rName string) string { +func testAccApplicationConfig_serviceRole(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "beanstalk_service" { name = "%[1]s" @@ -275,8 +275,8 @@ EOF `, rName) } -func testAccBeanstalkAppConfigWithMaxAge(rName string) string { - return testAccBeanstalkAppServiceRole(rName) + fmt.Sprintf(` +func testAccApplicationConfig_maxAge(rName string) string { + return testAccApplicationConfig_serviceRole(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "%s" description = "tf-test-desc" @@ -290,8 +290,8 @@ resource "aws_elastic_beanstalk_application" "tftest" { `, rName) } -func testAccBeanstalkAppConfigWithMaxCount(rName string) string { - return testAccBeanstalkAppServiceRole(rName) + fmt.Sprintf(` +func testAccApplicationConfig_maxCount(rName string) string { + return testAccApplicationConfig_serviceRole(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "%s" description = "tf-test-desc" @@ -305,7 +305,7 @@ resource "aws_elastic_beanstalk_application" "tftest" { `, rName) } -func testAccBeanstalkAppConfigWithTags(rName, tag1, tag2 string) string { +func testAccApplicationConfig_tags2(rName, tag1, tag2 string) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "%s" @@ -319,7 +319,7 @@ resource "aws_elastic_beanstalk_application" "tftest" { `, rName, tag1, tag2) } -func testAccBeanstalkAppConfigWithAddTags(rName, tag1, tag2, tag3 string) string { +func testAccApplicationConfig_tags(rName, tag1, tag2, tag3 string) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "%s" diff --git a/internal/service/elasticbeanstalk/application_version_test.go b/internal/service/elasticbeanstalk/application_version_test.go index 80b716140d3..222adf65bd0 100644 --- a/internal/service/elasticbeanstalk/application_version_test.go +++ b/internal/service/elasticbeanstalk/application_version_test.go @@ -25,7 +25,7 @@ func TestAccElasticBeanstalkApplicationVersion_BeanstalkApp_basic(t *testing.T) CheckDestroy: testAccCheckApplicationVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkApplicationVersionConfig(sdkacctest.RandInt()), + Config: testAccApplicationVersionConfig_basic(sdkacctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationVersionExists("aws_elastic_beanstalk_application_version.default", &appVersion), ), @@ -45,7 +45,7 @@ func TestAccElasticBeanstalkApplicationVersion_BeanstalkApp_duplicateLabels(t *t CheckDestroy: testAccCheckApplicationVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkApplicationVersionConfig_duplicateLabel(sdkacctest.RandInt()), + Config: testAccApplicationVersionConfig_duplicateLabel(sdkacctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationVersionExists("aws_elastic_beanstalk_application_version.first", &firstAppVersion), testAccCheckApplicationVersionExists("aws_elastic_beanstalk_application_version.second", &secondAppVersion), @@ -66,7 +66,7 @@ func TestAccElasticBeanstalkApplicationVersion_BeanstalkApp_tags(t *testing.T) { CheckDestroy: testAccCheckApplicationVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkApplicationVersionConfigWithTags(sdkacctest.RandInt(), "test1", "test2"), + Config: testAccApplicationVersionConfig_tags(sdkacctest.RandInt(), "test1", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationVersionExists(resourceName, &appVersion), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -75,7 +75,7 @@ func TestAccElasticBeanstalkApplicationVersion_BeanstalkApp_tags(t *testing.T) { ), }, { - Config: testAccBeanstalkApplicationVersionConfigWithTags(sdkacctest.RandInt(), "updateTest1", "updateTest2"), + Config: testAccApplicationVersionConfig_tags(sdkacctest.RandInt(), "updateTest1", "updateTest2"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationVersionExists(resourceName, &appVersion), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -84,7 +84,7 @@ func TestAccElasticBeanstalkApplicationVersion_BeanstalkApp_tags(t *testing.T) { ), }, { - Config: testAccBeanstalkApplicationVersionConfigWithAddTags(sdkacctest.RandInt(), "updateTest1", "updateTest2", "addTest3"), + Config: testAccApplicationVersionConfig_addTags(sdkacctest.RandInt(), "updateTest1", "updateTest2", "addTest3"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationVersionExists(resourceName, &appVersion), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -94,7 +94,7 @@ func TestAccElasticBeanstalkApplicationVersion_BeanstalkApp_tags(t *testing.T) { ), }, { - Config: testAccBeanstalkApplicationVersionConfigWithTags(sdkacctest.RandInt(), "updateTest1", "updateTest2"), + Config: testAccApplicationVersionConfig_tags(sdkacctest.RandInt(), "updateTest1", "updateTest2"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationVersionExists(resourceName, &appVersion), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -171,7 +171,7 @@ func testAccCheckApplicationVersionExists(n string, app *elasticbeanstalk.Applic } } -func testAccBeanstalkApplicationVersionConfig(randInt int) string { +func testAccApplicationVersionConfig_basic(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "default" { bucket = "tftest.applicationversion.bucket-%d" @@ -197,7 +197,7 @@ resource "aws_elastic_beanstalk_application_version" "default" { `, randInt, randInt, randInt) } -func testAccBeanstalkApplicationVersionConfig_duplicateLabel(randInt int) string { +func testAccApplicationVersionConfig_duplicateLabel(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "default" { bucket = "tftest.applicationversion.bucket-%d" @@ -235,7 +235,7 @@ resource "aws_elastic_beanstalk_application_version" "second" { `, randInt, randInt, randInt, randInt, randInt) } -func testAccBeanstalkApplicationVersionConfigWithTags(randInt int, tag1, tag2 string) string { +func testAccApplicationVersionConfig_tags(randInt int, tag1, tag2 string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "default" { bucket = "tftest.applicationversion.bucket-%[1]d" @@ -266,7 +266,7 @@ resource "aws_elastic_beanstalk_application_version" "default" { `, randInt, tag1, tag2) } -func testAccBeanstalkApplicationVersionConfigWithAddTags(randInt int, tag1, tag2, tag3 string) string { +func testAccApplicationVersionConfig_addTags(randInt int, tag1, tag2, tag3 string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "default" { bucket = "tftest.applicationversion.bucket-%[1]d" diff --git a/internal/service/elasticbeanstalk/configuration_template_test.go b/internal/service/elasticbeanstalk/configuration_template_test.go index eaa800acddb..7e42d286094 100644 --- a/internal/service/elasticbeanstalk/configuration_template_test.go +++ b/internal/service/elasticbeanstalk/configuration_template_test.go @@ -21,12 +21,12 @@ func TestAccElasticBeanstalkConfigurationTemplate_Beanstalk_basic(t *testing.T) PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkConfigurationTemplateDestroy, + CheckDestroy: testAccCheckConfigurationTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkConfigurationTemplateConfig(sdkacctest.RandString(5)), + Config: testAccConfigurationTemplateConfig_basic(sdkacctest.RandString(5)), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkConfigurationTemplateExists("aws_elastic_beanstalk_configuration_template.tf_template", &config), + testAccCheckConfigurationTemplateExists("aws_elastic_beanstalk_configuration_template.tf_template", &config), ), }, }, @@ -40,12 +40,12 @@ func TestAccElasticBeanstalkConfigurationTemplate_Beanstalk_vpc(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkConfigurationTemplateDestroy, + CheckDestroy: testAccCheckConfigurationTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkConfigurationTemplateConfig_VPC(sdkacctest.RandString(5)), + Config: testAccConfigurationTemplateConfig_vpc(sdkacctest.RandString(5)), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkConfigurationTemplateExists("aws_elastic_beanstalk_configuration_template.tf_template", &config), + testAccCheckConfigurationTemplateExists("aws_elastic_beanstalk_configuration_template.tf_template", &config), ), }, }, @@ -59,12 +59,12 @@ func TestAccElasticBeanstalkConfigurationTemplate_Beanstalk_setting(t *testing.T PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkConfigurationTemplateDestroy, + CheckDestroy: testAccCheckConfigurationTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkConfigurationTemplateConfig_Setting(sdkacctest.RandString(5)), + Config: testAccConfigurationTemplateConfig_setting(sdkacctest.RandString(5)), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkConfigurationTemplateExists("aws_elastic_beanstalk_configuration_template.tf_template", &config), + testAccCheckConfigurationTemplateExists("aws_elastic_beanstalk_configuration_template.tf_template", &config), resource.TestCheckResourceAttr( "aws_elastic_beanstalk_configuration_template.tf_template", "setting.#", "1"), resource.TestCheckTypeSetElemNestedAttrs("aws_elastic_beanstalk_configuration_template.tf_template", "setting.*", map[string]string{ @@ -76,7 +76,7 @@ func TestAccElasticBeanstalkConfigurationTemplate_Beanstalk_setting(t *testing.T }) } -func testAccCheckBeanstalkConfigurationTemplateDestroy(s *terraform.State) error { +func testAccCheckConfigurationTemplateDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn for _, rs := range s.RootModule().Resources { @@ -118,7 +118,7 @@ func testAccCheckBeanstalkConfigurationTemplateDestroy(s *terraform.State) error return nil } -func testAccCheckBeanstalkConfigurationTemplateExists(n string, config *elasticbeanstalk.ConfigurationSettingsDescription) resource.TestCheckFunc { +func testAccCheckConfigurationTemplateExists(n string, config *elasticbeanstalk.ConfigurationSettingsDescription) resource.TestCheckFunc { return func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn rs, ok := s.RootModule().Resources[n] @@ -148,7 +148,7 @@ func testAccCheckBeanstalkConfigurationTemplateExists(n string, config *elasticb } } -func testAccBeanstalkConfigurationTemplateConfig(r string) string { +func testAccConfigurationTemplateConfig_basic(r string) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-%s" @@ -163,7 +163,7 @@ resource "aws_elastic_beanstalk_configuration_template" "tf_template" { `, r, r) } -func testAccBeanstalkConfigurationTemplateConfig_VPC(name string) string { +func testAccConfigurationTemplateConfig_vpc(name string) string { return fmt.Sprintf(` resource "aws_vpc" "tf_b_test" { cidr_block = "10.0.0.0/16" @@ -208,7 +208,7 @@ resource "aws_elastic_beanstalk_configuration_template" "tf_template" { `, name, name) } -func testAccBeanstalkConfigurationTemplateConfig_Setting(name string) string { +func testAccConfigurationTemplateConfig_setting(name string) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-%s" diff --git a/internal/service/elasticbeanstalk/environment.go b/internal/service/elasticbeanstalk/environment.go index e4314936c6e..d92c093314c 100644 --- a/internal/service/elasticbeanstalk/environment.go +++ b/internal/service/elasticbeanstalk/environment.go @@ -283,7 +283,7 @@ func resourceEnvironmentCreate(d *schema.ResourceData, meta interface{}) error { createOpts.VersionLabel = aws.String(version) } - // Get the current time to filter getBeanstalkEnvironmentErrors messages + // Get the current time to filter getEnvironmentErrors messages t := time.Now() log.Printf("[DEBUG] Elastic Beanstalk Environment create opts: %s", createOpts) resp, err := conn.CreateEnvironment(&createOpts) @@ -310,7 +310,7 @@ func resourceEnvironmentCreate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error waiting for Elastic Beanstalk Environment (%s) to become ready: %w", d.Id(), err) } - envErrors, err := getBeanstalkEnvironmentErrors(conn, d.Id(), t) + envErrors, err := getEnvironmentErrors(conn, d.Id(), t) if err != nil { return err } @@ -430,7 +430,7 @@ func resourceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { } if hasChange { - // Get the current time to filter getBeanstalkEnvironmentErrors messages + // Get the current time to filter getEnvironmentErrors messages t := time.Now() log.Printf("[DEBUG] Elastic Beanstalk Environment update opts: %s", updateOpts) _, err := conn.UpdateEnvironment(&updateOpts) @@ -455,7 +455,7 @@ func resourceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { d.Id(), err) } - envErrors, err := getBeanstalkEnvironmentErrors(conn, d.Id(), t) + envErrors, err := getEnvironmentErrors(conn, d.Id(), t) if err != nil { return err } @@ -468,7 +468,7 @@ func resourceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("tags_all") { o, n := d.GetChange("tags_all") - // Get the current time to filter getBeanstalkEnvironmentErrors messages + // Get the current time to filter getEnvironmentErrors messages t := time.Now() if err := UpdateTags(conn, arn, o, n); err != nil { return fmt.Errorf("error updating Elastic Beanstalk environment (%s) tags: %s", arn, err) @@ -489,7 +489,7 @@ func resourceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error waiting for Elastic Beanstalk Environment %q to become ready: %w", d.Id(), err) } - envErrors, err := getBeanstalkEnvironmentErrors(conn, d.Id(), t) + envErrors, err := getEnvironmentErrors(conn, d.Id(), t) if err != nil { return err } @@ -863,7 +863,7 @@ func environmentStateRefreshFunc(conn *elasticbeanstalk.ElasticBeanstalk, enviro return -1, "failed", fmt.Errorf("Error finding Elastic Beanstalk Environment, environment not found") } - envErrors, err := getBeanstalkEnvironmentErrors(conn, environmentID, t) + envErrors, err := getEnvironmentErrors(conn, environmentID, t) if err != nil { return -1, "failed", err } @@ -1033,7 +1033,7 @@ func (e beanstalkEnvironmentErrors) Less(i, j int) bool { return e[i].eventDate.Before(*e[j].eventDate) } -func getBeanstalkEnvironmentErrors(conn *elasticbeanstalk.ElasticBeanstalk, environmentId string, t time.Time) (*multierror.Error, error) { +func getEnvironmentErrors(conn *elasticbeanstalk.ElasticBeanstalk, environmentId string, t time.Time) (*multierror.Error, error) { environmentErrors, err := conn.DescribeEvents(&elasticbeanstalk.DescribeEventsInput{ EnvironmentId: aws.String(environmentId), Severity: aws.String("ERROR"), diff --git a/internal/service/elasticbeanstalk/environment_migrate.go b/internal/service/elasticbeanstalk/environment_migrate.go index dd1059873da..296f4fcf12b 100644 --- a/internal/service/elasticbeanstalk/environment_migrate.go +++ b/internal/service/elasticbeanstalk/environment_migrate.go @@ -12,13 +12,13 @@ func EnvironmentMigrateState( switch v { case 0: log.Println("[INFO] Found AWS Elastic Beanstalk Environment State v0; migrating to v1") - return migrateBeanstalkEnvironmentStateV0toV1(is) + return migrateEnvironmentStateV0toV1(is) default: return is, fmt.Errorf("Unexpected schema version: %d", v) } } -func migrateBeanstalkEnvironmentStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { +func migrateEnvironmentStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { if is.Empty() || is.Attributes == nil { log.Println("[DEBUG] Empty Elastic Beanstalk Environment State; nothing to migrate.") return is, nil diff --git a/internal/service/elasticbeanstalk/environment_test.go b/internal/service/elasticbeanstalk/environment_test.go index 73bbf0c149a..168faff2b54 100644 --- a/internal/service/elasticbeanstalk/environment_test.go +++ b/internal/service/elasticbeanstalk/environment_test.go @@ -35,12 +35,12 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnv_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkEnvConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), + testAccCheckEnvironmentExists(resourceName, &app), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "elasticbeanstalk", fmt.Sprintf("environment/%s/%s", rName, rName)), resource.TestMatchResourceAttr(resourceName, "autoscaling_groups.0", beanstalkAsgNameRegexp), resource.TestMatchResourceAttr(resourceName, "endpoint_url", beanstalkEndpointURL), @@ -73,12 +73,12 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnv_tier(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkWorkerEnvConfig(rName), + Config: testAccEnvironmentConfig_worker(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvTier(resourceName, &app), + testAccCheckEnvironmentTier(resourceName, &app), resource.TestMatchResourceAttr(resourceName, "queues.0", beanstalkQueuesNameRegexp), ), }, @@ -107,12 +107,12 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnvCNAME_prefix(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkEnvCnamePrefixConfig(rName), + Config: testAccEnvironmentConfig_cnamePrefix(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), + testAccCheckEnvironmentExists(resourceName, &app), resource.TestMatchResourceAttr(resourceName, "cname", beanstalkCnameRegexp), ), }, @@ -139,13 +139,13 @@ func TestAccElasticBeanstalkEnvironment_beanstalkEnv(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkConfigTemplate(rName, 1), + Config: testAccEnvironmentConfig_template(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccCheckBeanstalkEnvConfigValue(resourceName, "1"), + testAccCheckEnvironmentExists(resourceName, &app), + testAccCheckEnvironmentConfigValue(resourceName, "1"), ), }, { @@ -159,17 +159,17 @@ func TestAccElasticBeanstalkEnvironment_beanstalkEnv(t *testing.T) { }, }, { - Config: testAccBeanstalkConfigTemplate(rName, 2), + Config: testAccEnvironmentConfig_template(rName, 2), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccCheckBeanstalkEnvConfigValue(resourceName, "2"), + testAccCheckEnvironmentExists(resourceName, &app), + testAccCheckEnvironmentConfigValue(resourceName, "2"), ), }, { - Config: testAccBeanstalkConfigTemplate(rName, 3), + Config: testAccEnvironmentConfig_template(rName, 3), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccCheckBeanstalkEnvConfigValue(resourceName, "3"), + testAccCheckEnvironmentExists(resourceName, &app), + testAccCheckEnvironmentConfigValue(resourceName, "3"), ), }, }, @@ -186,12 +186,12 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnv_resource(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkResourceOptionSetting(rName), + Config: testAccEnvironmentConfig_resourceOptionSetting(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), + testAccCheckEnvironmentExists(resourceName, &app), ), }, { @@ -217,13 +217,13 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnv_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkTagsTemplate(rName, "test1", "test2"), + Config: testAccEnvironmentConfig_tagsTemplate(rName, "test1", "test2"), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccCheckBeanstalkEnvTagsMatch(&app, map[string]string{"firstTag": "test1", "secondTag": "test2"}), + testAccCheckEnvironmentExists(resourceName, &app), + testAccCheckEnvironmentTagsMatch(&app, map[string]string{"firstTag": "test1", "secondTag": "test2"}), ), }, { @@ -236,17 +236,17 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnv_tags(t *testing.T) { }, }, { - Config: testAccBeanstalkTagsTemplate(rName, "test2", "test1"), + Config: testAccEnvironmentConfig_tagsTemplate(rName, "test2", "test1"), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccCheckBeanstalkEnvTagsMatch(&app, map[string]string{"firstTag": "test2", "secondTag": "test1"}), + testAccCheckEnvironmentExists(resourceName, &app), + testAccCheckEnvironmentTagsMatch(&app, map[string]string{"firstTag": "test2", "secondTag": "test1"}), ), }, { - Config: testAccBeanstalkEnvConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccCheckBeanstalkEnvTagsMatch(&app, map[string]string{}), + testAccCheckEnvironmentExists(resourceName, &app), + testAccCheckEnvironmentTagsMatch(&app, map[string]string{}), ), }, }, @@ -263,24 +263,24 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnvTemplate_change(t *testing.T PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkEnv_TemplateChange_stack(rName), + Config: testAccEnvironmentConfig_templateChangeStack(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), + testAccCheckEnvironmentExists(resourceName, &app), ), }, { - Config: testAccBeanstalkEnv_TemplateChange_temp(rName), + Config: testAccEnvironmentConfig_templateChangeTemp(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), + testAccCheckEnvironmentExists(resourceName, &app), ), }, { - Config: testAccBeanstalkEnv_TemplateChange_stack(rName), + Config: testAccEnvironmentConfig_templateChangeStack(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), + testAccCheckEnvironmentExists(resourceName, &app), ), }, }, @@ -297,34 +297,34 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnvSettings_update(t *testing.T PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkEnvConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccVerifyBeanstalkConfig(&app, []string{}), + testAccCheckEnvironmentExists(resourceName, &app), + testAccVerifyConfig(&app, []string{}), ), }, { - Config: testAccBeanstalkEnvConfig_settings(rName), + Config: testAccEnvironmentConfig_settings(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccVerifyBeanstalkConfig(&app, []string{"ENV_STATIC", "ENV_UPDATE"}), + testAccCheckEnvironmentExists(resourceName, &app), + testAccVerifyConfig(&app, []string{"ENV_STATIC", "ENV_UPDATE"}), ), }, { - Config: testAccBeanstalkEnvConfig_settings(rName), + Config: testAccEnvironmentConfig_settings(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccVerifyBeanstalkConfig(&app, []string{"ENV_STATIC", "ENV_UPDATE"}), + testAccCheckEnvironmentExists(resourceName, &app), + testAccVerifyConfig(&app, []string{"ENV_STATIC", "ENV_UPDATE"}), ), }, { - Config: testAccBeanstalkEnvConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), - testAccVerifyBeanstalkConfig(&app, []string{}), + testAccCheckEnvironmentExists(resourceName, &app), + testAccVerifyConfig(&app, []string{}), ), }, }, @@ -341,12 +341,12 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnvVersion_label(t *testing.T) PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkEnvApplicationVersionConfig(rName), + Config: testAccEnvironmentConfig_applicationVersion(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkApplicationVersionDeployed(resourceName, &app), + testAccCheckApplicationVersionDeployed(resourceName, &app), ), }, { @@ -359,9 +359,9 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnvVersion_label(t *testing.T) }, }, { - Config: testAccBeanstalkEnvApplicationVersionConfigUpdate(rName), + Config: testAccEnvironmentConfig_applicationVersionUpdate(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkApplicationVersionDeployed(resourceName, &app), + testAccCheckApplicationVersionDeployed(resourceName, &app), ), }, }, @@ -382,12 +382,12 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnv_settingWithJSONValue(t *tes PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkEnvSettingJsonValue(rName, publicKey, acctest.DefaultEmailAddress), + Config: testAccEnvironmentConfig_settingJSONValue(rName, publicKey, acctest.DefaultEmailAddress), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), + testAccCheckEnvironmentExists(resourceName, &app), ), }, { @@ -413,12 +413,12 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnv_platformARN(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticbeanstalk.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckBeanstalkEnvDestroy, + CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccBeanstalkEnvConfig_platform_arn(rName), + Config: testAccEnvironmentConfig_platformARN(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBeanstalkEnvExists(resourceName, &app), + testAccCheckEnvironmentExists(resourceName, &app), acctest.CheckResourceAttrRegionalARNNoAccount(resourceName, "platform_arn", "elasticbeanstalk", "platform/Python 3.6 running on 64bit Amazon Linux/2.9.6"), ), }, @@ -435,10 +435,10 @@ func TestAccElasticBeanstalkEnvironment_BeanstalkEnv_platformARN(t *testing.T) { }) } -func testAccVerifyBeanstalkConfig(env *elasticbeanstalk.EnvironmentDescription, expected []string) resource.TestCheckFunc { +func testAccVerifyConfig(env *elasticbeanstalk.EnvironmentDescription, expected []string) resource.TestCheckFunc { return func(s *terraform.State) error { if env == nil { - return fmt.Errorf("Nil environment in testAccVerifyBeanstalkConfig") + return fmt.Errorf("Nil environment in testAccVerifyConfig") } conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn @@ -448,12 +448,12 @@ func testAccVerifyBeanstalkConfig(env *elasticbeanstalk.EnvironmentDescription, }) if err != nil { - return fmt.Errorf("Error describing config settings in testAccVerifyBeanstalkConfig: %s", err) + return fmt.Errorf("Error describing config settings in testAccVerifyConfig: %s", err) } // should only be 1 environment if len(resp.ConfigurationSettings) != 1 { - return fmt.Errorf("Expected only 1 set of Configuration Settings in testAccVerifyBeanstalkConfig, got (%d)", len(resp.ConfigurationSettings)) + return fmt.Errorf("Expected only 1 set of Configuration Settings in testAccVerifyConfig, got (%d)", len(resp.ConfigurationSettings)) } cs := resp.ConfigurationSettings[0] @@ -487,7 +487,7 @@ func testAccVerifyBeanstalkConfig(env *elasticbeanstalk.EnvironmentDescription, } } -func testAccCheckBeanstalkEnvDestroy(s *terraform.State) error { +func testAccCheckEnvironmentDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn for _, rs := range s.RootModule().Resources { @@ -522,7 +522,7 @@ func testAccCheckBeanstalkEnvDestroy(s *terraform.State) error { return nil } -func testAccCheckBeanstalkEnvExists(n string, app *elasticbeanstalk.EnvironmentDescription) resource.TestCheckFunc { +func testAccCheckEnvironmentExists(n string, app *elasticbeanstalk.EnvironmentDescription) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -533,7 +533,7 @@ func testAccCheckBeanstalkEnvExists(n string, app *elasticbeanstalk.EnvironmentD return fmt.Errorf("Elastic Beanstalk ENV is not set") } - env, err := describeBeanstalkEnv(acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn, aws.String(rs.Primary.ID)) + env, err := describeEnvironment(acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn, aws.String(rs.Primary.ID)) if err != nil { return err } @@ -544,7 +544,7 @@ func testAccCheckBeanstalkEnvExists(n string, app *elasticbeanstalk.EnvironmentD } } -func testAccCheckBeanstalkEnvTier(n string, app *elasticbeanstalk.EnvironmentDescription) resource.TestCheckFunc { +func testAccCheckEnvironmentTier(n string, app *elasticbeanstalk.EnvironmentDescription) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -555,7 +555,7 @@ func testAccCheckBeanstalkEnvTier(n string, app *elasticbeanstalk.EnvironmentDes return fmt.Errorf("Elastic Beanstalk ENV is not set") } - env, err := describeBeanstalkEnv(acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn, aws.String(rs.Primary.ID)) + env, err := describeEnvironment(acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn, aws.String(rs.Primary.ID)) if err != nil { return err } @@ -569,7 +569,7 @@ func testAccCheckBeanstalkEnvTier(n string, app *elasticbeanstalk.EnvironmentDes } } -func testAccCheckBeanstalkEnvConfigValue(n string, expectedValue string) resource.TestCheckFunc { +func testAccCheckEnvironmentConfigValue(n string, expectedValue string) resource.TestCheckFunc { return func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn @@ -612,10 +612,10 @@ func testAccCheckBeanstalkEnvConfigValue(n string, expectedValue string) resourc } } -func testAccCheckBeanstalkEnvTagsMatch(env *elasticbeanstalk.EnvironmentDescription, expectedValue map[string]string) resource.TestCheckFunc { +func testAccCheckEnvironmentTagsMatch(env *elasticbeanstalk.EnvironmentDescription, expectedValue map[string]string) resource.TestCheckFunc { return func(s *terraform.State) error { if env == nil { - return fmt.Errorf("Nil environment in testAccCheckBeanstalkEnvTagsMatch") + return fmt.Errorf("Nil environment in testAccCheckEnvironmentTagsMatch") } conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn @@ -638,7 +638,7 @@ func testAccCheckBeanstalkEnvTagsMatch(env *elasticbeanstalk.EnvironmentDescript } } -func testAccCheckBeanstalkApplicationVersionDeployed(n string, app *elasticbeanstalk.EnvironmentDescription) resource.TestCheckFunc { +func testAccCheckApplicationVersionDeployed(n string, app *elasticbeanstalk.EnvironmentDescription) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -649,7 +649,7 @@ func testAccCheckBeanstalkApplicationVersionDeployed(n string, app *elasticbeans return fmt.Errorf("Elastic Beanstalk ENV is not set") } - env, err := describeBeanstalkEnv(acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn, aws.String(rs.Primary.ID)) + env, err := describeEnvironment(acctest.Provider.Meta().(*conns.AWSClient).ElasticBeanstalkConn, aws.String(rs.Primary.ID)) if err != nil { return err } @@ -664,7 +664,7 @@ func testAccCheckBeanstalkApplicationVersionDeployed(n string, app *elasticbeans } } -func describeBeanstalkEnv(conn *elasticbeanstalk.ElasticBeanstalk, +func describeEnvironment(conn *elasticbeanstalk.ElasticBeanstalk, envID *string) (*elasticbeanstalk.EnvironmentDescription, error) { describeBeanstalkEnvOpts := &elasticbeanstalk.DescribeEnvironmentsInput{ EnvironmentIds: []*string{envID}, @@ -685,7 +685,7 @@ func describeBeanstalkEnv(conn *elasticbeanstalk.ElasticBeanstalk, return resp.Environments[0], nil } -func testAccBeanstalkEnvConfigBase(rName string) string { +func testAccEnvironmentConfig_base(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { # Default instance type of t2.micro is not available in this Availability Zone @@ -819,8 +819,8 @@ resource "aws_iam_instance_profile" "test" { `, rName) } -func testAccBeanstalkEnvConfig(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_basic(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name name = %[1]q @@ -865,8 +865,8 @@ resource "aws_elastic_beanstalk_environment" "test" { `, rName) } -func testAccBeanstalkEnvConfig_platform_arn(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_platformARN(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name name = %[1]q @@ -911,8 +911,8 @@ resource "aws_elastic_beanstalk_environment" "test" { `, rName) } -func testAccBeanstalkEnvConfig_settings(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_settings(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name name = %[1]q @@ -996,8 +996,8 @@ resource "aws_elastic_beanstalk_environment" "test" { `, rName) } -func testAccBeanstalkWorkerEnvConfig(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_worker(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name name = %[1]q @@ -1043,8 +1043,8 @@ resource "aws_elastic_beanstalk_environment" "test" { `, rName) } -func testAccBeanstalkEnvCnamePrefixConfig(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_cnamePrefix(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name cname_prefix = %[1]q @@ -1090,8 +1090,8 @@ resource "aws_elastic_beanstalk_environment" "test" { `, rName) } -func testAccBeanstalkConfigTemplate(rName string, cfgTplValue int) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_template(rName string, cfgTplValue int) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name name = %[1]q @@ -1148,8 +1148,8 @@ resource "aws_elastic_beanstalk_configuration_template" "test" { `, rName, cfgTplValue) } -func testAccBeanstalkResourceOptionSetting(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_resourceOptionSetting(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name name = %[1]q @@ -1215,8 +1215,8 @@ resource "aws_elastic_beanstalk_environment" "test" { `, rName) } -func testAccBeanstalkTagsTemplate(rName, firstTag, secondTag string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_tagsTemplate(rName, firstTag, secondTag string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name name = %[1]q @@ -1266,8 +1266,8 @@ resource "aws_elastic_beanstalk_environment" "test" { `, rName, firstTag, secondTag) } -func testAccBeanstalkEnv_TemplateChange_stack(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_templateChangeStack(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name name = %[1]q @@ -1318,8 +1318,8 @@ resource "aws_elastic_beanstalk_configuration_template" "test" { `, rName) } -func testAccBeanstalkEnv_TemplateChange_temp(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_templateChangeTemp(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_elastic_beanstalk_environment" "test" { application = aws_elastic_beanstalk_application.test.name name = %[1]q @@ -1370,8 +1370,8 @@ resource "aws_elastic_beanstalk_configuration_template" "test" { `, rName) } -func testAccBeanstalkEnvApplicationVersionConfig(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_applicationVersion(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q } @@ -1434,8 +1434,8 @@ resource "aws_elastic_beanstalk_environment" "test" { `, rName) } -func testAccBeanstalkEnvApplicationVersionConfigUpdate(rName string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_applicationVersionUpdate(rName string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q } @@ -1498,8 +1498,8 @@ resource "aws_elastic_beanstalk_environment" "test" { `, rName) } -func testAccBeanstalkEnvSettingJsonValue(rName, publicKey, email string) string { - return testAccBeanstalkEnvConfigBase(rName) + fmt.Sprintf(` +func testAccEnvironmentConfig_settingJSONValue(rName, publicKey, email string) string { + return testAccEnvironmentConfig_base(rName) + fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q } diff --git a/internal/service/elasticbeanstalk/hosted_zone_data_source_test.go b/internal/service/elasticbeanstalk/hosted_zone_data_source_test.go index b58193d4def..92adffd524a 100644 --- a/internal/service/elasticbeanstalk/hosted_zone_data_source_test.go +++ b/internal/service/elasticbeanstalk/hosted_zone_data_source_test.go @@ -39,19 +39,19 @@ func TestAccElasticBeanstalkHostedZoneDataSource_region(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckHostedZoneDataSource_byRegion("ap-southeast-2"), //lintignore:AWSAT003 // passes in GovCloud + Config: testAccHostedZoneDataSourceConfig_byRegion("ap-southeast-2"), //lintignore:AWSAT003 // passes in GovCloud Check: resource.ComposeTestCheckFunc( testAccCheckHostedZone(dataSourceName, "ap-southeast-2"), //lintignore:AWSAT003 // passes in GovCloud ), }, { - Config: testAccCheckHostedZoneDataSource_byRegion("eu-west-1"), //lintignore:AWSAT003 // passes in GovCloud + Config: testAccHostedZoneDataSourceConfig_byRegion("eu-west-1"), //lintignore:AWSAT003 // passes in GovCloud Check: resource.ComposeTestCheckFunc( testAccCheckHostedZone(dataSourceName, "eu-west-1"), //lintignore:AWSAT003 // passes in GovCloud ), }, { - Config: testAccCheckHostedZoneDataSource_byRegion("ss-pluto-1"), + Config: testAccHostedZoneDataSourceConfig_byRegion("ss-pluto-1"), ExpectError: regexp.MustCompile("Unsupported region"), }, }, @@ -74,7 +74,7 @@ const testAccHostedZoneDataSourceConfig_currentRegion = ` data "aws_elastic_beanstalk_hosted_zone" "test" {} ` -func testAccCheckHostedZoneDataSource_byRegion(r string) string { +func testAccHostedZoneDataSourceConfig_byRegion(r string) string { return fmt.Sprintf(` data "aws_elastic_beanstalk_hosted_zone" "test" { region = "%s" diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index 67a55a79080..eaf19a8e6fd 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -419,7 +419,7 @@ func ResourceDomain() *schema.Resource { Optional: true, Computed: true, ForceNew: true, - DiffSuppressFunc: suppressEquivalentKmsKeyIds, + DiffSuppressFunc: suppressEquivalentKMSKeyIDs, }, }, }, @@ -1041,7 +1041,7 @@ func inPlaceEncryptionEnableVersion(version string) bool { return verify.SemVerGreaterThanOrEqual(version, "6.7") } -func suppressEquivalentKmsKeyIds(k, old, new string, d *schema.ResourceData) bool { +func suppressEquivalentKMSKeyIDs(k, old, new string, d *schema.ResourceData) bool { // The Elasticsearch API accepts a short KMS key id but always returns the ARN of the key. // The ARN is of the format 'arn:aws:kms:REGION:ACCOUNT_ID:key/KMS_KEY_ID'. // These should be treated as equivalent. diff --git a/internal/service/elasticsearch/domain_data_source_test.go b/internal/service/elasticsearch/domain_data_source_test.go index e3f93628d27..f689bee1940 100644 --- a/internal/service/elasticsearch/domain_data_source_test.go +++ b/internal/service/elasticsearch/domain_data_source_test.go @@ -21,12 +21,12 @@ func TestAccElasticsearchDomainDataSource_Data_basic(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearchservice.EndpointsID), ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDomainWithDataSourceConfig(rInt, autoTuneStartAtTime), + Config: testAccDomainDataSourceConfig_basic(rInt, autoTuneStartAtTime), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "processing", "false"), resource.TestCheckResourceAttrPair(datasourceName, "elasticsearch_version", resourceName, "elasticsearch_version"), @@ -63,12 +63,12 @@ func TestAccElasticsearchDomainDataSource_Data_advanced(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearchservice.EndpointsID), ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDomainAdvancedWithDataSourceConfig(rInt, autoTuneStartAtTime), + Config: testAccDomainDataSourceConfig_advanced(rInt, autoTuneStartAtTime), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "elasticsearch_version", resourceName, "elasticsearch_version"), resource.TestCheckResourceAttrPair(datasourceName, "auto_tune_options.#", resourceName, "auto_tune_options.#"), @@ -96,7 +96,7 @@ func TestAccElasticsearchDomainDataSource_Data_advanced(t *testing.T) { }) } -func testAccDomainWithDataSourceConfig(rInt int, autoTuneStartAtTime string) string { +func testAccDomainDataSourceConfig_basic(rInt int, autoTuneStartAtTime string) string { return fmt.Sprintf(` locals { random_name = "test-es-%d" @@ -178,7 +178,7 @@ data "aws_elasticsearch_domain" "test" { `, rInt, autoTuneStartAtTime) } -func testAccDomainAdvancedWithDataSourceConfig(rInt int, autoTuneStartAtTime string) string { +func testAccDomainDataSourceConfig_advanced(rInt int, autoTuneStartAtTime string) string { return acctest.ConfigAvailableAZsNoOptIn() + fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/elasticsearch/domain_policy_test.go b/internal/service/elasticsearch/domain_policy_test.go index dcd9fa47893..3320f8320d0 100644 --- a/internal/service/elasticsearch/domain_policy_test.go +++ b/internal/service/elasticsearch/domain_policy_test.go @@ -52,7 +52,7 @@ func TestAccElasticsearchDomainPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainPolicyConfig(ri, policy), + Config: testAccDomainPolicyConfig_basic(ri, policy), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists("aws_elasticsearch_domain.example", &domain), resource.TestCheckResourceAttr("aws_elasticsearch_domain.example", "elasticsearch_version", "2.3"), @@ -83,7 +83,7 @@ func buildDomainARN(name, partition, accId, region string) (string, error) { return fmt.Sprintf("arn:%s:es:%s:%s:domain/%s", partition, region, accId, name), nil } -func testAccDomainPolicyConfig(randInt int, policy string) string { +func testAccDomainPolicyConfig_basic(randInt int, policy string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "example" { domain_name = "tf-test-%d" diff --git a/internal/service/elasticsearch/domain_saml_options_test.go b/internal/service/elasticsearch/domain_saml_options_test.go index 966a915ca31..58b57630e64 100644 --- a/internal/service/elasticsearch/domain_saml_options_test.go +++ b/internal/service/elasticsearch/domain_saml_options_test.go @@ -31,7 +31,7 @@ func TestAccElasticsearchDomainSAMLOptions_basic(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(esDomainResourceName, &domain), testAccCheckESDomainSAMLOptions(esDomainResourceName, resourceName), @@ -65,7 +65,7 @@ func TestAccElasticsearchDomainSAMLOptions_disappears(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( testAccCheckESDomainSAMLOptions(esDomainResourceName, resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfelasticsearch.ResourceDomainSAMLOptions(), resourceName), @@ -90,7 +90,7 @@ func TestAccElasticsearchDomainSAMLOptions_disappears_Domain(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( testAccCheckESDomainSAMLOptions(esDomainResourceName, resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfelasticsearch.ResourceDomain(), esDomainResourceName), @@ -116,7 +116,7 @@ func TestAccElasticsearchDomainSAMLOptions_Update(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "saml_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "60"), @@ -124,7 +124,7 @@ func TestAccElasticsearchDomainSAMLOptions_Update(t *testing.T) { ), }, { - Config: testAccDomainSAMLOptionsConfigUpdate(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_update(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "saml_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "180"), @@ -150,7 +150,7 @@ func TestAccElasticsearchDomainSAMLOptions_Disabled(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "saml_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "60"), @@ -158,7 +158,7 @@ func TestAccElasticsearchDomainSAMLOptions_Disabled(t *testing.T) { ), }, { - Config: testAccDomainSAMLOptionsConfigDisabled(rUserName, rName), + Config: testAccDomainSAMLOptionsConfig_disabled(rUserName, rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "saml_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "0"), @@ -215,7 +215,7 @@ func testAccCheckESDomainSAMLOptions(esResource string, samlOptionsResource stri } } -func testAccDomainSAMLOptionsConfig(userName, domainName, idpEntityId string) string { +func testAccDomainSAMLOptionsConfig_basic(userName, domainName, idpEntityId string) string { return fmt.Sprintf(` resource "aws_iam_user" "es_master_user" { name = %[1]q @@ -272,7 +272,7 @@ resource "aws_elasticsearch_domain_saml_options" "main" { `, userName, domainName, idpEntityId) } -func testAccDomainSAMLOptionsConfigUpdate(userName, domainName, idpEntityId string) string { +func testAccDomainSAMLOptionsConfig_update(userName, domainName, idpEntityId string) string { return fmt.Sprintf(` resource "aws_iam_user" "es_master_user" { name = %[1]q @@ -330,7 +330,7 @@ resource "aws_elasticsearch_domain_saml_options" "main" { `, userName, domainName, idpEntityId) } -func testAccDomainSAMLOptionsConfigDisabled(userName string, domainName string) string { +func testAccDomainSAMLOptionsConfig_disabled(userName string, domainName string) string { return fmt.Sprintf(` resource "aws_iam_user" "es_master_user" { name = "%s" diff --git a/internal/service/elasticsearch/domain_test.go b/internal/service/elasticsearch/domain_test.go index ec15fbf6858..074232fa119 100644 --- a/internal/service/elasticsearch/domain_test.go +++ b/internal/service/elasticsearch/domain_test.go @@ -32,13 +32,13 @@ func TestAccElasticsearchDomain_basic(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "elasticsearch_version", "1.5"), @@ -68,7 +68,7 @@ func TestAccElasticsearchDomain_requireHTTPS(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_DomainEndpointOptions(rName, true, "Policy-Min-TLS-1-0-2019-07"), + Config: testAccDomainConfig_endpointOptions(rName, true, "Policy-Min-TLS-1-0-2019-07"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists("aws_elasticsearch_domain.test", &domain), testAccCheckDomainEndpointOptions(true, "Policy-Min-TLS-1-0-2019-07", &domain), @@ -81,7 +81,7 @@ func TestAccElasticsearchDomain_requireHTTPS(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_DomainEndpointOptions(rName, true, "Policy-Min-TLS-1-2-2019-07"), + Config: testAccDomainConfig_endpointOptions(rName, true, "Policy-Min-TLS-1-2-2019-07"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists("aws_elasticsearch_domain.test", &domain), testAccCheckDomainEndpointOptions(true, "Policy-Min-TLS-1-2-2019-07", &domain), @@ -111,7 +111,7 @@ func TestAccElasticsearchDomain_customEndpoint(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_CustomEndpoint(rName, true, "Policy-Min-TLS-1-0-2019-07", true, customEndpoint, certKey, certificate), + Config: testAccDomainConfig_customEndpoint(rName, true, "Policy-Min-TLS-1-0-2019-07", true, customEndpoint, certKey, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "domain_endpoint_options.#", "1"), @@ -127,7 +127,7 @@ func TestAccElasticsearchDomain_customEndpoint(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_CustomEndpoint(rName, true, "Policy-Min-TLS-1-0-2019-07", true, customEndpoint, certKey, certificate), + Config: testAccDomainConfig_customEndpoint(rName, true, "Policy-Min-TLS-1-0-2019-07", true, customEndpoint, certKey, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckDomainEndpointOptions(true, "Policy-Min-TLS-1-0-2019-07", &domain), @@ -135,7 +135,7 @@ func TestAccElasticsearchDomain_customEndpoint(t *testing.T) { ), }, { - Config: testAccDomainConfig_CustomEndpoint(rName, true, "Policy-Min-TLS-1-0-2019-07", false, customEndpoint, certKey, certificate), + Config: testAccDomainConfig_customEndpoint(rName, true, "Policy-Min-TLS-1-0-2019-07", false, customEndpoint, certKey, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckDomainEndpointOptions(true, "Policy-Min-TLS-1-0-2019-07", &domain), @@ -152,13 +152,13 @@ func TestAccElasticsearchDomain_Cluster_zoneAwareness(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_ClusterConfig_ZoneAwarenessConfig_AvailabilityZoneCount(rName, 3), + Config: testAccDomainConfig_clusterZoneAwarenessAvailabilityZoneCount(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain1), resource.TestCheckResourceAttr(resourceName, "cluster_config.0.zone_awareness_config.#", "1"), @@ -173,7 +173,7 @@ func TestAccElasticsearchDomain_Cluster_zoneAwareness(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_ClusterConfig_ZoneAwarenessConfig_AvailabilityZoneCount(rName, 2), + Config: testAccDomainConfig_clusterZoneAwarenessAvailabilityZoneCount(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain2), testAccCheckDomainNotRecreated(&domain1, &domain2), // note: this check does not work and always passes @@ -183,7 +183,7 @@ func TestAccElasticsearchDomain_Cluster_zoneAwareness(t *testing.T) { ), }, { - Config: testAccDomainConfig_ClusterConfig_ZoneAwarenessEnabled(rName, false), + Config: testAccDomainConfig_clusterZoneAwarenessEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain3), testAccCheckDomainNotRecreated(&domain2, &domain3), // note: this check does not work and always passes @@ -192,7 +192,7 @@ func TestAccElasticsearchDomain_Cluster_zoneAwareness(t *testing.T) { ), }, { - Config: testAccDomainConfig_ClusterConfig_ZoneAwarenessConfig_AvailabilityZoneCount(rName, 3), + Config: testAccDomainConfig_clusterZoneAwarenessAvailabilityZoneCount(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain4), testAccCheckDomainNotRecreated(&domain3, &domain4), // note: this check does not work and always passes @@ -211,13 +211,13 @@ func TestAccElasticsearchDomain_warm(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigWarm(rName, "ultrawarm1.medium.elasticsearch", false, 6), + Config: testAccDomainConfig_warm(rName, "ultrawarm1.medium.elasticsearch", false, 6), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "cluster_config.0.warm_enabled", "false"), @@ -226,7 +226,7 @@ func TestAccElasticsearchDomain_warm(t *testing.T) { ), }, { - Config: testAccDomainConfigWarm(rName, "ultrawarm1.medium.elasticsearch", true, 6), + Config: testAccDomainConfig_warm(rName, "ultrawarm1.medium.elasticsearch", true, 6), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "cluster_config.0.warm_enabled", "true"), @@ -241,7 +241,7 @@ func TestAccElasticsearchDomain_warm(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfigWarm(rName, "ultrawarm1.medium.elasticsearch", true, 7), + Config: testAccDomainConfig_warm(rName, "ultrawarm1.medium.elasticsearch", true, 7), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "cluster_config.0.warm_enabled", "true"), @@ -250,7 +250,7 @@ func TestAccElasticsearchDomain_warm(t *testing.T) { ), }, { - Config: testAccDomainConfigWarm(rName, "ultrawarm1.large.elasticsearch", true, 7), + Config: testAccDomainConfig_warm(rName, "ultrawarm1.large.elasticsearch", true, 7), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "cluster_config.0.warm_enabled", "true"), @@ -268,13 +268,13 @@ func TestAccElasticsearchDomain_withColdStorageOptions(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_WithColdStorageOptions(rName, false, false, false), + Config: testAccDomainConfig_coldStorageOptions(rName, false, false, false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "cluster_config.0.cold_storage_options.*", map[string]string{ @@ -288,7 +288,7 @@ func TestAccElasticsearchDomain_withColdStorageOptions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_WithColdStorageOptions(rName, true, true, true), + Config: testAccDomainConfig_coldStorageOptions(rName, true, true, true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "cluster_config.0.cold_storage_options.*", map[string]string{ @@ -305,13 +305,13 @@ func TestAccElasticsearchDomain_withDedicatedMaster(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_WithDedicatedClusterMaster(rName, false), + Config: testAccDomainConfig_dedicatedClusterMaster(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), ), @@ -323,13 +323,13 @@ func TestAccElasticsearchDomain_withDedicatedMaster(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_WithDedicatedClusterMaster(rName, true), + Config: testAccDomainConfig_dedicatedClusterMaster(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), ), }, { - Config: testAccDomainConfig_WithDedicatedClusterMaster(rName, false), + Config: testAccDomainConfig_dedicatedClusterMaster(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), ), @@ -348,7 +348,7 @@ func TestAccElasticsearchDomain_duplicate(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: func(s *terraform.State) error { @@ -379,7 +379,7 @@ func TestAccElasticsearchDomain_duplicate(t *testing.T) { t.Fatal(err) } }, - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr( @@ -401,13 +401,13 @@ func TestAccElasticsearchDomain_v23(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigV23(rName), + Config: testAccDomainConfig_v23(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr( @@ -434,7 +434,7 @@ func TestAccElasticsearchDomain_complex(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, @@ -465,7 +465,7 @@ func TestAccElasticsearchDomain_vpc(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, @@ -492,13 +492,13 @@ func TestAccElasticsearchDomain_VPC_update(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_vpc_update1(rName), + Config: testAccDomainConfig_vpcUpdate1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckNumberOfSecurityGroups(1, &domain), @@ -511,7 +511,7 @@ func TestAccElasticsearchDomain_VPC_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_vpc_update2(rName), + Config: testAccDomainConfig_vpcUpdate2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckNumberOfSecurityGroups(2, &domain), @@ -531,13 +531,13 @@ func TestAccElasticsearchDomain_internetToVPCEndpoint(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), ), @@ -549,7 +549,7 @@ func TestAccElasticsearchDomain_internetToVPCEndpoint(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_internetToVpcEndpoint(rName), + Config: testAccDomainConfig_internetToVPCEndpoint(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), ), @@ -569,13 +569,13 @@ func TestAccElasticsearchDomain_AutoTuneOptions(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigWithAutoTuneOptions(rName, autoTuneStartAtTime), + Config: testAccDomainConfig_autoTuneOptions(rName, autoTuneStartAtTime), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr( @@ -612,13 +612,13 @@ func TestAccElasticsearchDomain_AdvancedSecurityOptions_userDB(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_AdvancedSecurityOptionsUserDb(rName), + Config: testAccDomainConfig_advancedSecurityOptionsUserDB(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckAdvancedSecurityOptions(true, true, &domain), @@ -649,13 +649,13 @@ func TestAccElasticsearchDomain_AdvancedSecurityOptions_iam(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_AdvancedSecurityOptionsIAM(rName), + Config: testAccDomainConfig_advancedSecurityOptionsIAM(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckAdvancedSecurityOptions(true, false, &domain), @@ -686,13 +686,13 @@ func TestAccElasticsearchDomain_AdvancedSecurityOptions_disabled(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_AdvancedSecurityOptionsDisabled(rName), + Config: testAccDomainConfig_advancedSecurityOptionsDisabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckAdvancedSecurityOptions(false, false, &domain), @@ -723,13 +723,13 @@ func TestAccElasticsearchDomain_LogPublishingOptions_indexSlowLogs(t *testing.T) resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_LogPublishingOptions(rName, elasticsearch.LogTypeIndexSlowLogs), + Config: testAccDomainConfig_logPublishingOptions(rName, elasticsearch.LogTypeIndexSlowLogs), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "log_publishing_options.#", "1"), @@ -758,13 +758,13 @@ func TestAccElasticsearchDomain_LogPublishingOptions_searchSlowLogs(t *testing.T resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_LogPublishingOptions(rName, elasticsearch.LogTypeSearchSlowLogs), + Config: testAccDomainConfig_logPublishingOptions(rName, elasticsearch.LogTypeSearchSlowLogs), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "log_publishing_options.#", "1"), @@ -793,13 +793,13 @@ func TestAccElasticsearchDomain_LogPublishingOptions_esApplicationLogs(t *testin resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_LogPublishingOptions(rName, elasticsearch.LogTypeEsApplicationLogs), + Config: testAccDomainConfig_logPublishingOptions(rName, elasticsearch.LogTypeEsApplicationLogs), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "log_publishing_options.#", "1"), @@ -828,13 +828,13 @@ func TestAccElasticsearchDomain_LogPublishingOptions_auditLogs(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_LogPublishingOptions(rName, elasticsearch.LogTypeAuditLogs), + Config: testAccDomainConfig_logPublishingOptions(rName, elasticsearch.LogTypeAuditLogs), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "log_publishing_options.#", "1"), @@ -868,14 +868,14 @@ func TestAccElasticsearchDomain_cognitoOptionsCreateAndRemove(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) testAccPreCheckCognitoIdentityProvider(t) - testAccPreCheckIamServiceLinkedRoleEs(t) + testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_CognitoOptions(rName, true), + Config: testAccDomainConfig_cognitoOptions(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckCognitoOptions(true, &domain), @@ -888,7 +888,7 @@ func TestAccElasticsearchDomain_cognitoOptionsCreateAndRemove(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_CognitoOptions(rName, false), + Config: testAccDomainConfig_cognitoOptions(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckCognitoOptions(false, &domain), @@ -911,14 +911,14 @@ func TestAccElasticsearchDomain_cognitoOptionsUpdate(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) testAccPreCheckCognitoIdentityProvider(t) - testAccPreCheckIamServiceLinkedRoleEs(t) + testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_CognitoOptions(rName, false), + Config: testAccDomainConfig_cognitoOptions(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckCognitoOptions(false, &domain), @@ -931,7 +931,7 @@ func TestAccElasticsearchDomain_cognitoOptionsUpdate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_CognitoOptions(rName, true), + Config: testAccDomainConfig_cognitoOptions(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckCognitoOptions(true, &domain), @@ -951,13 +951,13 @@ func TestAccElasticsearchDomain_policy(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigWithPolicy(rName), + Config: testAccDomainConfig_policy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), ), @@ -982,19 +982,19 @@ func TestAccElasticsearchDomain_policyIgnoreEquivalent(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainPolicyOrderConfig(rName), + Config: testAccDomainConfig_policyOrder(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), ), }, { - Config: testAccDomainPolicyNewOrderConfig(rName), + Config: testAccDomainConfig_policyNewOrder(rName), PlanOnly: true, }, }, @@ -1011,13 +1011,13 @@ func TestAccElasticsearchDomain_Encryption_atRestDefaultKey(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigWithEncryptAtRestDefaultKey(rName, "6.0", true), + Config: testAccDomainConfig_encryptAtRestDefaultKey(rName, "6.0", true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckDomainEncrypted(true, &domain), @@ -1043,13 +1043,13 @@ func TestAccElasticsearchDomain_Encryption_atRestSpecifyKey(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigWithEncryptAtRestWithKey(rName, "6.0", true), + Config: testAccDomainConfig_encryptAtRestKey(rName, "6.0", true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckDomainEncrypted(true, &domain), @@ -1075,20 +1075,20 @@ func TestAccElasticsearchDomain_Encryption_atRestEnable(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigWithEncryptAtRestDefaultKey(rName, "6.7", false), + Config: testAccDomainConfig_encryptAtRestDefaultKey(rName, "6.7", false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain1), testAccCheckDomainEncrypted(false, &domain1), ), }, { - Config: testAccDomainConfigWithEncryptAtRestDefaultKey(rName, "6.7", true), + Config: testAccDomainConfig_encryptAtRestDefaultKey(rName, "6.7", true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain2), testAccCheckDomainEncrypted(true, &domain2), @@ -1096,7 +1096,7 @@ func TestAccElasticsearchDomain_Encryption_atRestEnable(t *testing.T) { ), }, { - Config: testAccDomainConfigWithEncryptAtRestDefaultKey(rName, "6.7", false), + Config: testAccDomainConfig_encryptAtRestDefaultKey(rName, "6.7", false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain1), testAccCheckDomainEncrypted(false, &domain1), @@ -1116,20 +1116,20 @@ func TestAccElasticsearchDomain_Encryption_atRestEnableLegacy(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigWithEncryptAtRestDefaultKey(rName, "5.6", false), + Config: testAccDomainConfig_encryptAtRestDefaultKey(rName, "5.6", false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain1), testAccCheckDomainEncrypted(false, &domain1), ), }, { - Config: testAccDomainConfigWithEncryptAtRestDefaultKey(rName, "5.6", true), + Config: testAccDomainConfig_encryptAtRestDefaultKey(rName, "5.6", true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain2), testAccCheckDomainEncrypted(true, &domain2), @@ -1149,13 +1149,13 @@ func TestAccElasticsearchDomain_Encryption_nodeToNode(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigwithNodeToNodeEncryption(rName, "6.0", true), + Config: testAccDomainConfig_nodeToNodeEncryption(rName, "6.0", true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckNodeToNodeEncrypted(true, &domain), @@ -1181,20 +1181,20 @@ func TestAccElasticsearchDomain_Encryption_nodeToNodeEnable(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigwithNodeToNodeEncryption(rName, "6.7", false), + Config: testAccDomainConfig_nodeToNodeEncryption(rName, "6.7", false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain1), testAccCheckNodeToNodeEncrypted(false, &domain1), ), }, { - Config: testAccDomainConfigwithNodeToNodeEncryption(rName, "6.7", true), + Config: testAccDomainConfig_nodeToNodeEncryption(rName, "6.7", true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain2), testAccCheckNodeToNodeEncrypted(true, &domain2), @@ -1202,7 +1202,7 @@ func TestAccElasticsearchDomain_Encryption_nodeToNodeEnable(t *testing.T) { ), }, { - Config: testAccDomainConfigwithNodeToNodeEncryption(rName, "6.7", false), + Config: testAccDomainConfig_nodeToNodeEncryption(rName, "6.7", false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain1), testAccCheckNodeToNodeEncrypted(false, &domain1), @@ -1222,27 +1222,27 @@ func TestAccElasticsearchDomain_Encryption_nodeToNodeEnableLegacy(t *testing.T) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigwithNodeToNodeEncryption(rName, "6.0", false), + Config: testAccDomainConfig_nodeToNodeEncryption(rName, "6.0", false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain1), testAccCheckNodeToNodeEncrypted(false, &domain1), ), }, { - Config: testAccDomainConfigwithNodeToNodeEncryption(rName, "6.0", true), + Config: testAccDomainConfig_nodeToNodeEncryption(rName, "6.0", true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain2), testAccCheckNodeToNodeEncrypted(true, &domain2), ), }, { - Config: testAccDomainConfigwithNodeToNodeEncryption(rName, "6.0", false), + Config: testAccDomainConfig_nodeToNodeEncryption(rName, "6.0", false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain1), testAccCheckNodeToNodeEncrypted(false, &domain1), @@ -1262,13 +1262,13 @@ func TestAccElasticsearchDomain_tags(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckELBDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigTags1(rName, "key1", "value1"), + Config: testAccDomainConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1282,7 +1282,7 @@ func TestAccElasticsearchDomain_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDomainConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1291,7 +1291,7 @@ func TestAccElasticsearchDomain_tags(t *testing.T) { ), }, { - Config: testAccDomainConfigTags1(rName, "key2", "value2"), + Config: testAccDomainConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1312,13 +1312,13 @@ func TestAccElasticsearchDomain_update(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_ClusterUpdate(rName, 2, 22), + Config: testAccDomainConfig_clusterUpdate(rName, 2, 22), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &input), testAccCheckNumberOfInstances(2, &input), @@ -1332,7 +1332,7 @@ func TestAccElasticsearchDomain_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_ClusterUpdate(rName, 4, 23), + Config: testAccDomainConfig_clusterUpdate(rName, 4, 23), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &input), testAccCheckNumberOfInstances(4, &input), @@ -1352,13 +1352,13 @@ func TestAccElasticsearchDomain_UpdateVolume_type(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_ClusterUpdateEBSVolume(rName, 24), + Config: testAccDomainConfig_clusterUpdateEBSVolume(rName, 24), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &input), testAccCheckEBSVolumeEnabled(true, &input), @@ -1372,14 +1372,14 @@ func TestAccElasticsearchDomain_UpdateVolume_type(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_ClusterUpdateInstanceStore(rName), + Config: testAccDomainConfig_clusterUpdateInstanceStore(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &input), testAccCheckEBSVolumeEnabled(false, &input), ), }, { - Config: testAccDomainConfig_ClusterUpdateEBSVolume(rName, 12), + Config: testAccDomainConfig_clusterUpdateEBSVolume(rName, 12), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &input), testAccCheckEBSVolumeEnabled(true, &input), @@ -1400,13 +1400,13 @@ func TestAccElasticsearchDomain_WithVolumeType_missing(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfigWithDisabledEBSNullVolumeType(rName), + Config: testAccDomainConfig_disabledEBSNullVolumeType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "cluster_config.#", "1"), @@ -1434,13 +1434,13 @@ func TestAccElasticsearchDomain_Update_version(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_ClusterUpdateVersion(rName, "5.5"), + Config: testAccDomainConfig_clusterUpdateVersion(rName, "5.5"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain1), resource.TestCheckResourceAttr(resourceName, "elasticsearch_version", "5.5"), @@ -1453,7 +1453,7 @@ func TestAccElasticsearchDomain_Update_version(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_ClusterUpdateVersion(rName, "5.6"), + Config: testAccDomainConfig_clusterUpdateVersion(rName, "5.6"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain2), testAccCheckDomainNotRecreated(&domain1, &domain2), // note: this check does not work and always passes @@ -1461,7 +1461,7 @@ func TestAccElasticsearchDomain_Update_version(t *testing.T) { ), }, { - Config: testAccDomainConfig_ClusterUpdateVersion(rName, "6.3"), + Config: testAccDomainConfig_clusterUpdateVersion(rName, "6.3"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain3), testAccCheckDomainNotRecreated(&domain2, &domain3), // note: this check does not work and always passes @@ -1480,13 +1480,13 @@ func TestAccElasticsearchDomain_disappears(t *testing.T) { resourceName := "aws_elasticsearch_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, elasticsearch.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceDisappears(acctest.Provider, tfelasticsearch.ResourceDomain(), resourceName), ), @@ -1732,7 +1732,7 @@ func testAccGetValidStartAtTime(t *testing.T, timeUntilStart string) string { return n.Add(d).Format(time.RFC3339) } -func testAccPreCheckIamServiceLinkedRoleEs(t *testing.T) { +func testAccPreCheckIAMServiceLinkedRoleEs(t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).IAMConn dnsSuffix := acctest.Provider.Meta().(*conns.AWSClient).DNSSuffix @@ -1764,7 +1764,7 @@ func testAccPreCheckIamServiceLinkedRoleEs(t *testing.T) { } } -func testAccDomainConfig(rName string) string { +func testAccDomainConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -1777,7 +1777,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName) } -func testAccDomainConfigWithAutoTuneOptions(rName, autoTuneStartAtTime string) string { +func testAccDomainConfig_autoTuneOptions(rName, autoTuneStartAtTime string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -1807,7 +1807,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, autoTuneStartAtTime) } -func testAccDomainConfigWithDisabledEBSNullVolumeType(rName string) string { +func testAccDomainConfig_disabledEBSNullVolumeType(rName string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -1827,7 +1827,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName) } -func testAccDomainConfig_DomainEndpointOptions(rName string, enforceHttps bool, tlsSecurityPolicy string) string { +func testAccDomainConfig_endpointOptions(rName string, enforceHttps bool, tlsSecurityPolicy string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -1845,7 +1845,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, enforceHttps, tlsSecurityPolicy) } -func testAccDomainConfig_CustomEndpoint(rName string, enforceHttps bool, tlsSecurityPolicy string, customEndpointEnabled bool, customEndpoint string, certKey string, certBody string) string { +func testAccDomainConfig_customEndpoint(rName string, enforceHttps bool, tlsSecurityPolicy string, customEndpointEnabled bool, customEndpoint string, certKey string, certBody string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "test" { private_key = "%[6]s" @@ -1871,7 +1871,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, enforceHttps, tlsSecurityPolicy, customEndpointEnabled, customEndpoint, acctest.TLSPEMEscapeNewlines(certKey), acctest.TLSPEMEscapeNewlines(certBody)) } -func testAccDomainConfig_ClusterConfig_ZoneAwarenessConfig_AvailabilityZoneCount(rName string, availabilityZoneCount int) string { +func testAccDomainConfig_clusterZoneAwarenessAvailabilityZoneCount(rName string, availabilityZoneCount int) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -1894,7 +1894,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, availabilityZoneCount) } -func testAccDomainConfig_ClusterConfig_ZoneAwarenessEnabled(rName string, zoneAwarenessEnabled bool) string { +func testAccDomainConfig_clusterZoneAwarenessEnabled(rName string, zoneAwarenessEnabled bool) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -1913,7 +1913,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, zoneAwarenessEnabled) } -func testAccDomainConfigWarm(rName, warmType string, enabled bool, warmCnt int) string { +func testAccDomainConfig_warm(rName, warmType string, enabled bool, warmCnt int) string { warmConfig := "" if enabled { warmConfig = fmt.Sprintf(` @@ -1951,7 +1951,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, enabled, warmConfig) } -func testAccDomainConfig_WithDedicatedClusterMaster(rName string, enabled bool) string { +func testAccDomainConfig_dedicatedClusterMaster(rName string, enabled bool) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -1972,7 +1972,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, enabled) } -func testAccDomainConfig_WithColdStorageOptions(rName string, dMasterEnabled bool, warmEnabled bool, csEnabled bool) string { +func testAccDomainConfig_coldStorageOptions(rName string, dMasterEnabled bool, warmEnabled bool, csEnabled bool) string { warmConfig := "" if warmEnabled { warmConfig = ` @@ -2017,7 +2017,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, dMasterEnabled, warmEnabled, warmConfig, coldConfig) } -func testAccDomainConfig_ClusterUpdate(rName string, instanceInt, snapshotInt int) string { +func testAccDomainConfig_clusterUpdate(rName string, instanceInt, snapshotInt int) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2048,7 +2048,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, instanceInt, snapshotInt) } -func testAccDomainConfig_ClusterUpdateEBSVolume(rName string, volumeSize int) string { +func testAccDomainConfig_clusterUpdateEBSVolume(rName string, volumeSize int) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2073,7 +2073,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, volumeSize) } -func testAccDomainConfig_ClusterUpdateVersion(rName, version string) string { +func testAccDomainConfig_clusterUpdateVersion(rName, version string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2094,7 +2094,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, version) } -func testAccDomainConfig_ClusterUpdateInstanceStore(rName string) string { +func testAccDomainConfig_clusterUpdateInstanceStore(rName string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2118,7 +2118,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName) } -func testAccDomainConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccDomainConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2135,7 +2135,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, tagKey1, tagValue1) } -func testAccDomainConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDomainConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2151,7 +2151,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccDomainConfigWithPolicy(rName string) string { +func testAccDomainConfig_policy(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -2193,7 +2193,7 @@ data "aws_iam_policy_document" "test" { `, rName) } -func testAccDomainPolicyOrderConfig(rName string) string { +func testAccDomainConfig_policyOrder(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -2244,7 +2244,7 @@ data "aws_iam_policy_document" "test" { `, rName) } -func testAccDomainPolicyNewOrderConfig(rName string) string { +func testAccDomainConfig_policyNewOrder(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -2295,7 +2295,7 @@ data "aws_iam_policy_document" "test" { `, rName) } -func testAccDomainConfigWithEncryptAtRestDefaultKey(rName, version string, enabled bool) string { +func testAccDomainConfig_encryptAtRestDefaultKey(rName, version string, enabled bool) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2319,7 +2319,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, version, enabled) } -func testAccDomainConfigWithEncryptAtRestWithKey(rName, version string, enabled bool) string { +func testAccDomainConfig_encryptAtRestKey(rName, version string, enabled bool) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -2349,7 +2349,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, version, enabled) } -func testAccDomainConfigwithNodeToNodeEncryption(rName, version string, enabled bool) string { +func testAccDomainConfig_nodeToNodeEncryption(rName, version string, enabled bool) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2403,7 +2403,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName) } -func testAccDomainConfigV23(rName string) string { +func testAccDomainConfig_v23(rName string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2480,7 +2480,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName)) } -func testAccDomainConfig_vpc_update1(rName string) string { +func testAccDomainConfig_vpcUpdate1(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2562,7 +2562,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName)) } -func testAccDomainConfig_vpc_update2(rName string) string { +func testAccDomainConfig_vpcUpdate2(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2644,7 +2644,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName)) } -func testAccDomainConfig_internetToVpcEndpoint(rName string) string { +func testAccDomainConfig_internetToVPCEndpoint(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2706,7 +2706,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName)) } -func testAccDomainConfig_AdvancedSecurityOptionsUserDb(rName string) string { +func testAccDomainConfig_advancedSecurityOptionsUserDB(rName string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2746,7 +2746,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName) } -func testAccDomainConfig_AdvancedSecurityOptionsIAM(rName string) string { +func testAccDomainConfig_advancedSecurityOptionsIAM(rName string) string { return fmt.Sprintf(` resource "aws_iam_user" "test" { name = %[1]q @@ -2789,7 +2789,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName) } -func testAccDomainConfig_AdvancedSecurityOptionsDisabled(rName string) string { +func testAccDomainConfig_advancedSecurityOptionsDisabled(rName string) string { return fmt.Sprintf(` resource "aws_elasticsearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2859,7 +2859,7 @@ resource "aws_cloudwatch_log_resource_policy" "test" { `, rName) } -func testAccDomainConfig_LogPublishingOptions(rName, logType string) string { +func testAccDomainConfig_logPublishingOptions(rName, logType string) string { var auditLogsConfig string if logType == elasticsearch.LogTypeAuditLogs { auditLogsConfig = ` @@ -2905,7 +2905,7 @@ resource "aws_elasticsearch_domain" "test" { `, rName, auditLogsConfig, logType)) } -func testAccDomainConfig_CognitoOptions(rName string, includeCognitoOptions bool) string { +func testAccDomainConfig_cognitoOptions(rName string, includeCognitoOptions bool) string { var cognitoOptions string if includeCognitoOptions { cognitoOptions = ` diff --git a/internal/service/elastictranscoder/pipeline_test.go b/internal/service/elastictranscoder/pipeline_test.go index 87a74fc932b..419f726038b 100644 --- a/internal/service/elastictranscoder/pipeline_test.go +++ b/internal/service/elastictranscoder/pipeline_test.go @@ -30,7 +30,7 @@ func TestAccElasticTranscoderPipeline_basic(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccPipelineBasicConfig(rName), + Config: testAccPipelineConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, pipeline), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elastictranscoder", regexp.MustCompile(`pipeline/.+`)), @@ -58,7 +58,7 @@ func TestAccElasticTranscoderPipeline_kmsKey(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccPipelineKMSKeyConfig(rName), + Config: testAccPipelineConfig_kmsKey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, pipeline), resource.TestCheckResourceAttrPair(resourceName, "aws_kms_key_arn", keyResourceName, "arn"), @@ -86,7 +86,7 @@ func TestAccElasticTranscoderPipeline_notifications(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccNotificationsConfig(rName), + Config: testAccPipelineConfig_notifications(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &pipeline), testAccCheckPipeline_notifications(&pipeline, []string{"warning", "completed"}), @@ -99,7 +99,7 @@ func TestAccElasticTranscoderPipeline_notifications(t *testing.T) { }, // update and check that we have 1 less notification { - Config: testAccNotificationsUpdateConfig(rName), + Config: testAccPipelineConfig_notificationsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, &pipeline), testAccCheckPipeline_notifications(&pipeline, []string{"completed"}), @@ -156,7 +156,7 @@ func TestAccElasticTranscoderPipeline_withContent(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccPipelineWithContentConfig(rName), + Config: testAccPipelineConfig_content(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, pipeline), ), @@ -167,7 +167,7 @@ func TestAccElasticTranscoderPipeline_withContent(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPipelineWithContentUpdateConfig(rName), + Config: testAccPipelineConfig_contentUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, pipeline), ), @@ -189,7 +189,7 @@ func TestAccElasticTranscoderPipeline_withPermissions(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccPipelineWithPermsConfig(rName), + Config: testAccPipelineConfig_perms(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, pipeline), ), @@ -215,7 +215,7 @@ func TestAccElasticTranscoderPipeline_disappears(t *testing.T) { CheckDestroy: testAccCheckPipelineDestroy, Steps: []resource.TestStep{ { - Config: testAccPipelineBasicConfig(rName), + Config: testAccPipelineConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPipelineExists(resourceName, pipeline), acctest.CheckResourceDisappears(acctest.Provider, tfelastictranscoder.ResourcePipeline(), resourceName), @@ -294,7 +294,7 @@ func testAccPreCheck(t *testing.T) { } } -func testAccPipelineBasicConfig(rName string) string { +func testAccPipelineConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_pipeline" "test" { input_bucket = aws_s3_bucket.test.bucket @@ -334,7 +334,7 @@ resource "aws_s3_bucket_acl" "test" { `, rName) } -func testAccPipelineKMSKeyConfig(rName string) string { +func testAccPipelineConfig_kmsKey(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -396,7 +396,7 @@ resource "aws_s3_bucket_acl" "test" { `, rName) } -func testAccPipelineWithContentConfig(rName string) string { +func testAccPipelineConfig_content(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_pipeline" "test" { input_bucket = aws_s3_bucket.content_bucket.bucket @@ -463,7 +463,7 @@ resource "aws_s3_bucket_acl" "thumb_bucket_acl" { `, rName) } -func testAccPipelineWithContentUpdateConfig(rName string) string { +func testAccPipelineConfig_contentUpdate(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_pipeline" "test" { input_bucket = aws_s3_bucket.input_bucket.bucket @@ -530,7 +530,7 @@ resource "aws_s3_bucket_acl" "thumb_bucket_acl" { `, rName) } -func testAccPipelineWithPermsConfig(rName string) string { +func testAccPipelineConfig_perms(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_pipeline" "test" { input_bucket = aws_s3_bucket.test.bucket @@ -591,7 +591,7 @@ resource "aws_s3_bucket_acl" "test" { `, rName) } -func testAccNotificationsConfig(rName string) string { +func testAccPipelineConfig_notifications(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_pipeline" "test" { input_bucket = aws_s3_bucket.test.bucket @@ -656,7 +656,7 @@ EOF `, rName) } -func testAccNotificationsUpdateConfig(rName string) string { +func testAccPipelineConfig_notificationsUpdate(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_pipeline" "test" { input_bucket = aws_s3_bucket.test.bucket diff --git a/internal/service/elastictranscoder/preset_test.go b/internal/service/elastictranscoder/preset_test.go index e47754c6549..0cc5159d865 100644 --- a/internal/service/elastictranscoder/preset_test.go +++ b/internal/service/elastictranscoder/preset_test.go @@ -28,7 +28,7 @@ func TestAccElasticTranscoderPreset_basic(t *testing.T) { CheckDestroy: testAccCheckPresetDestroy, Steps: []resource.TestStep{ { - Config: testAccPresetConfig(rName), + Config: testAccPresetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPresetExists(resourceName, &preset), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elastictranscoder", regexp.MustCompile(`preset/.+`)), @@ -55,7 +55,7 @@ func TestAccElasticTranscoderPreset_video_noCodec(t *testing.T) { CheckDestroy: testAccCheckPresetDestroy, Steps: []resource.TestStep{ { - Config: testAccPresetVideoNoCodec(rName), + Config: testAccPresetConfig_videoNoCodec(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPresetExists(resourceName, &preset), ), @@ -82,7 +82,7 @@ func TestAccElasticTranscoderPreset_audio_noBitRate(t *testing.T) { CheckDestroy: testAccCheckPresetDestroy, Steps: []resource.TestStep{ { - Config: testAccPresetNoBitRateConfig(rName), + Config: testAccPresetConfig_noBitRate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPresetExists(resourceName, &preset), ), @@ -108,7 +108,7 @@ func TestAccElasticTranscoderPreset_disappears(t *testing.T) { CheckDestroy: testAccCheckPresetDestroy, Steps: []resource.TestStep{ { - Config: testAccPresetConfig(rName), + Config: testAccPresetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPresetExists(resourceName, &preset), acctest.CheckResourceDisappears(acctest.Provider, tfet.ResourcePreset(), resourceName), @@ -132,7 +132,7 @@ func TestAccElasticTranscoderPreset_AudioCodecOptions_empty(t *testing.T) { CheckDestroy: testAccCheckPresetDestroy, Steps: []resource.TestStep{ { - Config: testAccPresetAudioCodecOptionsEmptyConfig(rName), + Config: testAccPresetConfig_audioCodecOptionsEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPresetExists(resourceName, &preset), ), @@ -159,7 +159,7 @@ func TestAccElasticTranscoderPreset_description(t *testing.T) { CheckDestroy: testAccCheckPresetDestroy, Steps: []resource.TestStep{ { - Config: testAccPresetDescriptionConfig(rName, "description1"), + Config: testAccPresetConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckPresetExists(resourceName, &preset), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -187,7 +187,7 @@ func TestAccElasticTranscoderPreset_full(t *testing.T) { CheckDestroy: testAccCheckPresetDestroy, Steps: []resource.TestStep{ { - Config: testAccPresetFull1Config(rName), + Config: testAccPresetConfig_full1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPresetExists(resourceName, &preset), resource.TestCheckResourceAttr(resourceName, "audio.#", "1"), @@ -204,7 +204,7 @@ func TestAccElasticTranscoderPreset_full(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPresetFull2Config(rName), + Config: testAccPresetConfig_full2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPresetExists(resourceName, &preset), resource.TestCheckResourceAttr(resourceName, "audio.#", "1"), @@ -237,7 +237,7 @@ func TestAccElasticTranscoderPreset_Video_frameRate(t *testing.T) { CheckDestroy: testAccCheckPresetDestroy, Steps: []resource.TestStep{ { - Config: testAccPresetVideoFrameRateConfig(rName, "29.97"), + Config: testAccPresetConfig_videoFrameRate(rName, "29.97"), Check: resource.ComposeTestCheckFunc( testAccCheckPresetExists(resourceName, &preset), resource.TestCheckResourceAttr(resourceName, "video.0.frame_rate", "29.97"), @@ -304,7 +304,7 @@ func testAccCheckPresetDestroy(s *terraform.State) error { return nil } -func testAccPresetConfig(rName string) string { +func testAccPresetConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_preset" "test" { container = "mp4" @@ -321,7 +321,7 @@ resource "aws_elastictranscoder_preset" "test" { `, rName) } -func testAccPresetAudioCodecOptionsEmptyConfig(rName string) string { +func testAccPresetConfig_audioCodecOptionsEmpty(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_preset" "test" { container = "mp4" @@ -340,7 +340,7 @@ resource "aws_elastictranscoder_preset" "test" { `, rName) } -func testAccPresetDescriptionConfig(rName string, description string) string { +func testAccPresetConfig_description(rName string, description string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_preset" "test" { container = "mp4" @@ -358,7 +358,7 @@ resource "aws_elastictranscoder_preset" "test" { `, rName, description) } -func testAccPresetFull1Config(rName string) string { +func testAccPresetConfig_full1(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_preset" "test" { container = "mp4" @@ -409,7 +409,7 @@ resource "aws_elastictranscoder_preset" "test" { `, rName) } -func testAccPresetFull2Config(rName string) string { +func testAccPresetConfig_full2(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_preset" "test" { container = "mp4" @@ -474,7 +474,7 @@ resource "aws_elastictranscoder_preset" "test" { `, rName) } -func testAccPresetVideoFrameRateConfig(rName string, frameRate string) string { +func testAccPresetConfig_videoFrameRate(rName string, frameRate string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_preset" "test" { container = "mp4" @@ -513,7 +513,7 @@ resource "aws_elastictranscoder_preset" "test" { `, rName, frameRate) } -func testAccPresetVideoNoCodec(rName string) string { +func testAccPresetConfig_videoNoCodec(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_preset" "test" { container = "webm" @@ -553,7 +553,7 @@ resource "aws_elastictranscoder_preset" "test" { `, rName) } -func testAccPresetNoBitRateConfig(rName string) string { +func testAccPresetConfig_noBitRate(rName string) string { return fmt.Sprintf(` resource "aws_elastictranscoder_preset" "test" { container = "wav" diff --git a/internal/service/elb/app_cookie_stickiness_policy.go b/internal/service/elb/app_cookie_stickiness_policy.go index 48aa1aefa03..b3b5ff17f25 100644 --- a/internal/service/elb/app_cookie_stickiness_policy.go +++ b/internal/service/elb/app_cookie_stickiness_policy.go @@ -104,14 +104,18 @@ func resourceAppCookieStickinessPolicyRead(d *schema.ResourceData, meta interfac getResp, err := conn.DescribeLoadBalancerPolicies(request) - if tfawserr.ErrCodeEquals(err, elb.ErrCodeAccessPointNotFoundException, elb.ErrCodePolicyNotFoundException) { - log.Printf("[WARN] Load Balancer / Load Balancer Policy (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error retrieving policy: %s", err) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodePolicyNotFoundException) { + log.Printf("[WARN] ELB Classic LB (%s) App Cookie Policy (%s) not found, removing from state", lbName, policyName) + d.SetId("") + return nil + } + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodeAccessPointNotFoundException) { + log.Printf("[WARN] ELB Classic LB (%s) not found, removing App Cookie Policy (%s) from state", lbName, policyName) + d.SetId("") + return nil + } + return fmt.Errorf("error retrieving ELB Classic (%s) App Cookie Policy (%s): %w", lbName, policyName, err) } if len(getResp.PolicyDescriptions) != 1 { @@ -123,9 +127,8 @@ func resourceAppCookieStickinessPolicyRead(d *schema.ResourceData, meta interfac if err != nil { return err } - if !assigned { - // policy exists, but isn't assigned to a listener - log.Printf("[DEBUG] policy '%s' exists, but isn't assigned to a listener", policyName) + if !d.IsNewResource() && !assigned { + log.Printf("[WARN] ELB Classic LB (%s) App Cookie Policy (%s) exists, but isn't assigned to a listener", lbName, policyName) d.SetId("") return nil } diff --git a/internal/service/elb/app_cookie_stickiness_policy_test.go b/internal/service/elb/app_cookie_stickiness_policy_test.go index 56d972c854f..3d3d6e9b89a 100644 --- a/internal/service/elb/app_cookie_stickiness_policy_test.go +++ b/internal/service/elb/app_cookie_stickiness_policy_test.go @@ -25,7 +25,7 @@ func TestAccELBAppCookieStickinessPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckAppCookieStickinessPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAppCookieStickinessPolicyConfig(lbName), + Config: testAccAppCookieStickinessPolicyConfig_basic(lbName), Check: resource.ComposeTestCheckFunc( testAccCheckAppCookieStickinessPolicy( "aws_elb.lb", @@ -39,7 +39,7 @@ func TestAccELBAppCookieStickinessPolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAppCookieStickinessPolicyConfigUpdate(lbName), + Config: testAccAppCookieStickinessPolicyConfig_update(lbName), Check: resource.ComposeTestCheckFunc( testAccCheckAppCookieStickinessPolicy( "aws_elb.lb", @@ -63,7 +63,7 @@ func TestAccELBAppCookieStickinessPolicy_Disappears_elb(t *testing.T) { CheckDestroy: testAccCheckAppCookieStickinessPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAppCookieStickinessPolicyConfig(lbName), + Config: testAccAppCookieStickinessPolicyConfig_basic(lbName), Check: resource.ComposeTestCheckFunc( testAccCheckAppCookieStickinessPolicy(elbResourceName, resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfelb.ResourceLoadBalancer(), elbResourceName), @@ -142,7 +142,7 @@ func TestAccELBAppCookieStickinessPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckAppCookieStickinessPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAppCookieStickinessPolicyConfig(lbName), + Config: testAccAppCookieStickinessPolicyConfig_basic(lbName), Check: resource.ComposeTestCheckFunc( testAccCheckAppCookieStickinessPolicy(elbResourceName, resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfelb.ResourceAppCookieStickinessPolicy(), resourceName), @@ -153,7 +153,7 @@ func TestAccELBAppCookieStickinessPolicy_disappears(t *testing.T) { }) } -func testAccAppCookieStickinessPolicyConfig(rName string) string { +func testAccAppCookieStickinessPolicyConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elb" "lb" { name = "%s" @@ -177,7 +177,7 @@ resource "aws_app_cookie_stickiness_policy" "foo" { } // Change the cookie_name to "MyOtherAppCookie". -func testAccAppCookieStickinessPolicyConfigUpdate(rName string) string { +func testAccAppCookieStickinessPolicyConfig_update(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elb" "lb" { name = "%s" diff --git a/internal/service/elb/attachment.go b/internal/service/elb/attachment.go index 2440c8355db..0edbcb73187 100644 --- a/internal/service/elb/attachment.go +++ b/internal/service/elb/attachment.go @@ -89,15 +89,15 @@ func resourceAttachmentRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.DescribeLoadBalancers(describeElbOpts) if err != nil { - if IsNotFound(err) { - log.Printf("[ERROR] ELB %s not found", elbName) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodeAccessPointNotFoundException) { + log.Printf("[WARN] ELB Classic LB (%s) not found, removing from state", elbName) d.SetId("") return nil } - return fmt.Errorf("Error retrieving ELB: %s", err) + return fmt.Errorf("error retrieving ELB Classic LB (%s): %w", elbName, err) } - if len(resp.LoadBalancerDescriptions) != 1 { - log.Printf("[ERROR] Unable to find ELB: %s", resp.LoadBalancerDescriptions) + if !d.IsNewResource() && len(resp.LoadBalancerDescriptions) != 1 { + log.Printf("[WARN] ELB Classic LB (%s) not found, removing from state", elbName) d.SetId("") return nil } @@ -111,7 +111,7 @@ func resourceAttachmentRead(d *schema.ResourceData, meta interface{}) error { } } - if !found { + if !d.IsNewResource() && !found { log.Printf("[WARN] instance %s not found in elb attachments", expected) d.SetId("") } diff --git a/internal/service/elb/attachment_test.go b/internal/service/elb/attachment_test.go index 183fb33cc9b..f6e23f656bb 100644 --- a/internal/service/elb/attachment_test.go +++ b/internal/service/elb/attachment_test.go @@ -23,28 +23,28 @@ func TestAccELBAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccAttachment1Config(), + Config: testAccAttachmentConfig_1(), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccAttachmentCheckInstanceCount(&conf, 1), ), }, { - Config: testAccAttachment2Config(), + Config: testAccAttachmentConfig_2(), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccAttachmentCheckInstanceCount(&conf, 2), ), }, { - Config: testAccAttachment3Config(), + Config: testAccAttachmentConfig_3(), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccAttachmentCheckInstanceCount(&conf, 2), ), }, { - Config: testAccAttachment4Config(), + Config: testAccAttachmentConfig_4(), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccAttachmentCheckInstanceCount(&conf, 0), @@ -59,7 +59,7 @@ func TestAccELBAttachment_drift(t *testing.T) { var conf elb.LoadBalancerDescription resourceName := "aws_elb.test" - deregInstance := func() { + testAccAttachmentConfig_deregInstance := func() { conn := acctest.Provider.Meta().(*conns.AWSClient).ELBConn deRegisterInstancesOpts := elb.DeregisterInstancesFromLoadBalancerInput{ @@ -83,7 +83,7 @@ func TestAccELBAttachment_drift(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccAttachment1Config(), + Config: testAccAttachmentConfig_1(), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccAttachmentCheckInstanceCount(&conf, 1), @@ -91,8 +91,8 @@ func TestAccELBAttachment_drift(t *testing.T) { }, // remove an instance from the ELB, and make sure it gets re-added { - Config: testAccAttachment1Config(), - PreConfig: deregInstance, + Config: testAccAttachmentConfig_1(), + PreConfig: testAccAttachmentConfig_deregInstance, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccAttachmentCheckInstanceCount(&conf, 1), @@ -112,8 +112,8 @@ func testAccAttachmentCheckInstanceCount(conf *elb.LoadBalancerDescription, expe } // add one attachment -func testAccAttachment1Config() string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), ` +func testAccAttachmentConfig_1() string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), ` data "aws_availability_zones" "available" { state = "available" @@ -147,8 +147,8 @@ resource "aws_elb_attachment" "foo1" { } // add a second attachment -func testAccAttachment2Config() string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), ` +func testAccAttachmentConfig_2() string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), ` data "aws_availability_zones" "available" { state = "available" @@ -192,8 +192,8 @@ resource "aws_elb_attachment" "foo2" { } // swap attachments between resources -func testAccAttachment3Config() string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), ` +func testAccAttachmentConfig_3() string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), ` data "aws_availability_zones" "available" { state = "available" @@ -237,7 +237,7 @@ resource "aws_elb_attachment" "foo2" { } // destroy attachments -func testAccAttachment4Config() string { +func testAccAttachmentConfig_4() string { return ` data "aws_availability_zones" "available" { state = "available" diff --git a/internal/service/elb/lb_cookie_stickiness_policy.go b/internal/service/elb/lb_cookie_stickiness_policy.go index 4107f12e5a0..a0453aa296e 100644 --- a/internal/service/elb/lb_cookie_stickiness_policy.go +++ b/internal/service/elb/lb_cookie_stickiness_policy.go @@ -7,8 +7,8 @@ import ( "strings" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "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" @@ -99,13 +99,17 @@ func resourceCookieStickinessPolicyRead(d *schema.ResourceData, meta interface{} getResp, err := conn.DescribeLoadBalancerPolicies(request) if err != nil { - if ec2err, ok := err.(awserr.Error); ok { - if ec2err.Code() == "PolicyNotFound" || ec2err.Code() == "LoadBalancerNotFound" { - d.SetId("") - } + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodePolicyNotFoundException) { + log.Printf("[WARN] ELB Classic LB (%s) LB Cookie Policy (%s) not found, removing from state", lbName, policyName) + d.SetId("") return nil } - return fmt.Errorf("Error retrieving policy: %s", err) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodeAccessPointNotFoundException) { + log.Printf("[WARN] ELB Classic LB (%s) not found, removing from state", lbName) + d.SetId("") + return nil + } + return fmt.Errorf("error retrieving ELB Classic (%s) LB Cookie Policy (%s): %w", lbName, policyName, err) } if len(getResp.PolicyDescriptions) != 1 { @@ -117,9 +121,9 @@ func resourceCookieStickinessPolicyRead(d *schema.ResourceData, meta interface{} if err != nil { return err } - if !assigned { + if !d.IsNewResource() && !assigned { // policy exists, but isn't assigned to a listener - log.Printf("[DEBUG] policy '%s' exists, but isn't assigned to a listener", policyName) + log.Printf("[WARN] ELB Classic LB (%s) LB Cookie Policy (%s) exists, but isn't assigned to a listener", lbName, policyName) d.SetId("") return nil } diff --git a/internal/service/elb/lb_cookie_stickiness_policy_test.go b/internal/service/elb/lb_cookie_stickiness_policy_test.go index 98c99a2b6b0..aeece9de357 100644 --- a/internal/service/elb/lb_cookie_stickiness_policy_test.go +++ b/internal/service/elb/lb_cookie_stickiness_policy_test.go @@ -25,7 +25,7 @@ func TestAccELBCookieStickinessPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckLBCookieStickinessPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccLBCookieStickinessPolicyConfig(lbName), + Config: testAccLBCookieStickinessPolicyConfig_basic(lbName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "cookie_expiration_period", "300"), testAccCheckLBCookieStickinessPolicy( @@ -35,7 +35,7 @@ func TestAccELBCookieStickinessPolicy_basic(t *testing.T) { ), }, { - Config: testAccLBCookieStickinessPolicyConfigUpdate(lbName), + Config: testAccLBCookieStickinessPolicyConfig_update(lbName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "cookie_expiration_period", "0"), testAccCheckLBCookieStickinessPolicy( @@ -116,7 +116,7 @@ func TestAccELBCookieStickinessPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckLBCookieStickinessPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccLBCookieStickinessPolicyConfig(lbName), + Config: testAccLBCookieStickinessPolicyConfig_basic(lbName), Check: resource.ComposeTestCheckFunc( testAccCheckLBCookieStickinessPolicy(elbResourceName, resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfelb.ResourceCookieStickinessPolicy(), resourceName), @@ -139,7 +139,7 @@ func TestAccELBCookieStickinessPolicy_Disappears_elb(t *testing.T) { CheckDestroy: testAccCheckLBCookieStickinessPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccLBCookieStickinessPolicyConfig(lbName), + Config: testAccLBCookieStickinessPolicyConfig_basic(lbName), Check: resource.ComposeTestCheckFunc( testAccCheckLBCookieStickinessPolicy(elbResourceName, resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfelb.ResourceLoadBalancer(), elbResourceName), @@ -150,7 +150,7 @@ func TestAccELBCookieStickinessPolicy_Disappears_elb(t *testing.T) { }) } -func testAccLBCookieStickinessPolicyConfig(rName string) string { +func testAccLBCookieStickinessPolicyConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elb" "lb" { name = "%s" @@ -174,7 +174,7 @@ resource "aws_lb_cookie_stickiness_policy" "foo" { } // Sets the cookie_expiration_period to 0s. -func testAccLBCookieStickinessPolicyConfigUpdate(rName string) string { +func testAccLBCookieStickinessPolicyConfig_update(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elb" "lb" { name = "%s" diff --git a/internal/service/elb/lb_ssl_negotiation_policy.go b/internal/service/elb/lb_ssl_negotiation_policy.go index 3b1ac817f73..ace8a5ddff0 100644 --- a/internal/service/elb/lb_ssl_negotiation_policy.go +++ b/internal/service/elb/lb_ssl_negotiation_policy.go @@ -8,8 +8,8 @@ import ( "strings" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "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" @@ -124,16 +124,16 @@ func resourceSSLNegotiationPolicyRead(d *schema.ResourceData, meta interface{}) getResp, err := conn.DescribeLoadBalancerPolicies(request) if err != nil { - if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "PolicyNotFound" { - // The policy is gone. + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodePolicyNotFoundException) { + log.Printf("[WARN] ELB Classic LB (%s) policy (%s) not found, removing from state", lbName, policyName) d.SetId("") return nil - } else if IsNotFound(err) { - // The ELB is gone now, so just remove it from the state + } else if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodeAccessPointNotFoundException) { + log.Printf("[WARN] ELB Classic LB (%s) not found, removing from state", lbName) d.SetId("") return nil } - return fmt.Errorf("Error retrieving policy: %s", err) + return fmt.Errorf("error retrieving ELB Classic (%s) SSL Negotiation Policy: %w", lbName, err) } if len(getResp.PolicyDescriptions) != 1 { diff --git a/internal/service/elb/lb_ssl_negotiation_policy_test.go b/internal/service/elb/lb_ssl_negotiation_policy_test.go index b6113628a3d..9f2ee1c29f9 100644 --- a/internal/service/elb/lb_ssl_negotiation_policy_test.go +++ b/internal/service/elb/lb_ssl_negotiation_policy_test.go @@ -31,7 +31,7 @@ func TestAccELBSSLNegotiationPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckLBSSLNegotiationPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccSslNegotiationPolicyConfig(rName, key, certificate), + Config: testAccLBSSLNegotiationPolicyConfig_basic(rName, key, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckLBSSLNegotiationPolicy(elbResourceName, resourceName), resource.TestCheckResourceAttr(resourceName, "attribute.#", "7"), @@ -57,7 +57,7 @@ func TestAccELBSSLNegotiationPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckLBSSLNegotiationPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccSslNegotiationPolicyConfig(rName, key, certificate), + Config: testAccLBSSLNegotiationPolicyConfig_basic(rName, key, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckLBSSLNegotiationPolicy(elbResourceName, resourceName), testAccCheckLoadBalancerExists(elbResourceName, &loadBalancer), @@ -195,7 +195,7 @@ func policyAttributesToMap(attributes *[]*elb.PolicyAttributeDescription) map[st } // Sets the SSL Negotiation policy with attributes. -func testAccSslNegotiationPolicyConfig(rName, key, certificate string) string { +func testAccLBSSLNegotiationPolicyConfig_basic(rName, key, certificate string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" diff --git a/internal/service/elb/load_balancer.go b/internal/service/elb/load_balancer.go index 2edb9a4c8d6..db18ee6f06a 100644 --- a/internal/service/elb/load_balancer.go +++ b/internal/service/elb/load_balancer.go @@ -11,7 +11,6 @@ import ( // nosemgrep: aws-sdk-go-multiple-service-imports "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/elb" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" @@ -372,13 +371,13 @@ func resourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error { describeResp, err := elbconn.DescribeLoadBalancers(describeElbOpts) if err != nil { - if IsNotFound(err) { - // The ELB is gone now, so just remove it from the state + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodeAccessPointNotFoundException) { + log.Printf("[WARN] ELB Classic LB (%s) not found, removing from state", elbName) d.SetId("") return nil } - return fmt.Errorf("Error retrieving ELB: %s", err) + return fmt.Errorf("Error retrieving ELB Classic LB (%s): %w", elbName, err) } if len(describeResp.LoadBalancerDescriptions) != 1 { return fmt.Errorf("Unable to find ELB: %#v", describeResp.LoadBalancerDescriptions) @@ -836,11 +835,9 @@ func ListenerHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%d-", m["instance_port"].(int))) - buf.WriteString(fmt.Sprintf("%s-", - strings.ToLower(m["instance_protocol"].(string)))) + buf.WriteString(fmt.Sprintf("%s-", strings.ToLower(m["instance_protocol"].(string)))) buf.WriteString(fmt.Sprintf("%d-", m["lb_port"].(int))) - buf.WriteString(fmt.Sprintf("%s-", - strings.ToLower(m["lb_protocol"].(string)))) + buf.WriteString(fmt.Sprintf("%s-", strings.ToLower(m["lb_protocol"].(string)))) if v, ok := m["ssl_certificate_id"]; ok { buf.WriteString(fmt.Sprintf("%s-", v.(string))) @@ -849,11 +846,6 @@ func ListenerHash(v interface{}) int { return create.StringHashcode(buf.String()) } -func IsNotFound(err error) bool { - elberr, ok := err.(awserr.Error) - return ok && elberr.Code() == elb.ErrCodeAccessPointNotFoundException -} - func ValidAccessLogsInterval(v interface{}, k string) (ws []string, errors []error) { value := v.(int) diff --git a/internal/service/elb/load_balancer_data_source_test.go b/internal/service/elb/load_balancer_data_source_test.go index e367da330fe..ce007d6cd66 100644 --- a/internal/service/elb/load_balancer_data_source_test.go +++ b/internal/service/elb/load_balancer_data_source_test.go @@ -21,7 +21,7 @@ func TestAccELBLoadBalancerDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccBasicDataSourceConfig(rName, t.Name()), + Config: testAccLoadBalancerDataSourceConfig_basic(rName, t.Name()), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "name", rName), resource.TestCheckResourceAttr(dataSourceName, "cross_zone_load_balancing", "true"), @@ -42,7 +42,7 @@ func TestAccELBLoadBalancerDataSource_basic(t *testing.T) { }) } -func testAccBasicDataSourceConfig(rName, testName string) string { +func testAccLoadBalancerDataSourceConfig_basic(rName, testName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elb" "test" { name = %[1]q diff --git a/internal/service/elb/load_balancer_test.go b/internal/service/elb/load_balancer_test.go index 29059cfd5e0..2319749db1c 100644 --- a/internal/service/elb/load_balancer_test.go +++ b/internal/service/elb/load_balancer_test.go @@ -30,7 +30,7 @@ func TestAccELBLoadBalancer_basic(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig, + Config: testAccLoadBalancerConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttributes(&conf), @@ -68,7 +68,7 @@ func TestAccELBLoadBalancer_disappears(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig, + Config: testAccLoadBalancerConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &loadBalancer), testAccCheckLoadBalancerDisappears(&loadBalancer), @@ -82,7 +82,7 @@ func TestAccELBLoadBalancer_disappears(t *testing.T) { func TestAccELBLoadBalancer_fullCharacterRange(t *testing.T) { var conf elb.LoadBalancerDescription resourceName := "aws_elb.test" - lbName := fmt.Sprintf("Tf-%d", sdkacctest.RandInt()) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -91,10 +91,10 @@ func TestAccELBLoadBalancer_fullCharacterRange(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: fmt.Sprintf(testAccLoadBalancerFullRangeOfCharacters, lbName), + Config: testAccLoadBalancerConfig_fullRangeOfCharacters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), - resource.TestCheckResourceAttr(resourceName, "name", lbName), + resource.TestCheckResourceAttr(resourceName, "name", rName), ), }, }, @@ -113,14 +113,14 @@ func TestAccELBLoadBalancer_AccessLogs_enabled(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerAccessLogs, + Config: testAccLoadBalancerConfig_accessLogs, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), ), }, { - Config: testAccLoadBalancerAccessLogsOn(rName), + Config: testAccLoadBalancerConfig_accessLogsOn(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "access_logs.#", "1"), @@ -131,7 +131,7 @@ func TestAccELBLoadBalancer_AccessLogs_enabled(t *testing.T) { }, { - Config: testAccLoadBalancerAccessLogs, + Config: testAccLoadBalancerConfig_accessLogs, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "access_logs.#", "0"), @@ -153,13 +153,13 @@ func TestAccELBLoadBalancer_AccessLogs_disabled(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerAccessLogs, + Config: testAccLoadBalancerConfig_accessLogs, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), ), }, { - Config: testAccLoadBalancerAccessLogsDisabled(rName), + Config: testAccLoadBalancerConfig_accessLogsDisabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "access_logs.#", "1"), @@ -169,7 +169,7 @@ func TestAccELBLoadBalancer_AccessLogs_disabled(t *testing.T) { ), }, { - Config: testAccLoadBalancerAccessLogs, + Config: testAccLoadBalancerConfig_accessLogs, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr( @@ -192,7 +192,7 @@ func TestAccELBLoadBalancer_namePrefix(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancer_namePrefix, + Config: testAccLoadBalancerConfig_namePrefix, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestMatchResourceAttr(resourceName, "name", nameRegex), @@ -214,7 +214,7 @@ func TestAccELBLoadBalancer_generatedName(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerGeneratedName, + Config: testAccLoadBalancerConfig_generatedName, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestMatchResourceAttr(resourceName, "name", generatedNameRegexp), @@ -236,7 +236,7 @@ func TestAccELBLoadBalancer_generatesNameForZeroValue(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancer_zeroValueName, + Config: testAccLoadBalancerConfig_zeroValueName, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestMatchResourceAttr(resourceName, "name", generatedNameRegexp), @@ -257,7 +257,7 @@ func TestAccELBLoadBalancer_availabilityZones(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig, + Config: testAccLoadBalancerConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "availability_zones.#", "3"), @@ -265,7 +265,7 @@ func TestAccELBLoadBalancer_availabilityZones(t *testing.T) { }, { - Config: testAccLoadBalancerConfig_AvailabilityZonesUpdate, + Config: testAccLoadBalancerConfig_availabilityZonesUpdate, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "availability_zones.#", "2"), @@ -286,7 +286,7 @@ func TestAccELBLoadBalancer_tags(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerTags1Config("key1", "value1"), + Config: testAccLoadBalancerConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttributes(&conf), @@ -300,7 +300,7 @@ func TestAccELBLoadBalancer_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccLoadBalancerConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttributes(&conf), @@ -310,7 +310,7 @@ func TestAccELBLoadBalancer_tags(t *testing.T) { ), }, { - Config: testAccLoadBalancerTags1Config("key2", "value2"), + Config: testAccLoadBalancerConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttributes(&conf), @@ -345,18 +345,18 @@ func TestAccELBLoadBalancer_ListenerSSLCertificateID_iamServerCertificate(t *tes CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLBConfig_Listener_iamServerCertificate(rName, certificate, key, "tcp"), + Config: testAccLoadBalancerConfig_listenerIAMServerCertificate(rName, certificate, key, "tcp"), ExpectError: regexp.MustCompile(`ssl_certificate_id may be set only when protocol is 'https' or 'ssl'`), }, { - Config: testAccLBConfig_Listener_iamServerCertificate(rName, certificate, key, "https"), + Config: testAccLoadBalancerConfig_listenerIAMServerCertificate(rName, certificate, key, "https"), Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testCheck, ), }, { - Config: testAccLBConfig_Listener_iamServerCertificateAddInvalidListener(rName, certificate, key), + Config: testAccLoadBalancerConfig_listenerIAMServerCertificateAddInvalidListener(rName, certificate, key), ExpectError: regexp.MustCompile(`ssl_certificate_id may be set only when protocol is 'https' or 'ssl'`), }, }, @@ -382,7 +382,7 @@ func TestAccELBLoadBalancer_Swap_subnets(t *testing.T) { }, { - Config: testAccLoadBalancerConfig_subnet_swap, + Config: testAccLoadBalancerConfig_subnetSwap, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists("aws_elb.test", &conf), resource.TestCheckResourceAttr("aws_elb.test", "subnets.#", "2"), @@ -412,7 +412,7 @@ func TestAccELBLoadBalancer_instanceAttaching(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig, + Config: testAccLoadBalancerConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttributes(&conf), @@ -420,7 +420,7 @@ func TestAccELBLoadBalancer_instanceAttaching(t *testing.T) { }, { - Config: testAccLoadBalancerNewInstanceConfig, + Config: testAccLoadBalancerConfig_newInstance, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testCheckInstanceAttached(1), @@ -441,7 +441,7 @@ func TestAccELBLoadBalancer_listener(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig, + Config: testAccLoadBalancerConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "listener.#", "1"), @@ -454,7 +454,7 @@ func TestAccELBLoadBalancer_listener(t *testing.T) { ), }, { - Config: testAccLoadBalancerListenerConfig_multipleListeners, + Config: testAccLoadBalancerConfig_listenerMultipleListeners, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "listener.#", "2"), @@ -473,7 +473,7 @@ func TestAccELBLoadBalancer_listener(t *testing.T) { ), }, { - Config: testAccLoadBalancerConfig, + Config: testAccLoadBalancerConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "listener.#", "1"), @@ -486,7 +486,7 @@ func TestAccELBLoadBalancer_listener(t *testing.T) { ), }, { - Config: testAccLoadBalancerListenerConfig_update, + Config: testAccLoadBalancerConfig_listenerUpdate, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "listener.#", "1"), @@ -510,7 +510,7 @@ func TestAccELBLoadBalancer_listener(t *testing.T) { t.Fatalf("Error deleting listener: %s", err) } }, - Config: testAccLoadBalancerConfig, + Config: testAccLoadBalancerConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "listener.#", "1"), @@ -541,7 +541,7 @@ func TestAccELBLoadBalancer_listener(t *testing.T) { t.Fatalf("Error creating listener: %s", err) } }, - Config: testAccLoadBalancerConfig, + Config: testAccLoadBalancerConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "listener.#", "1"), @@ -567,14 +567,14 @@ func TestAccELBLoadBalancer_healthCheck(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerHealthCheckConfig, + Config: testAccLoadBalancerConfig_healthCheck, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( resourceName, "health_check.0.healthy_threshold", "5"), ), }, { - Config: testAccLoadBalancerHealthCheckConfig_update, + Config: testAccLoadBalancerConfig_healthCheckUpdate, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "health_check.0.healthy_threshold", "10"), ), @@ -593,13 +593,13 @@ func TestAccELBLoadBalancer_timeout(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerIdleTimeoutConfig, + Config: testAccLoadBalancerConfig_idleTimeout, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "idle_timeout", "200"), ), }, { - Config: testAccLoadBalancerIdleTimeoutConfig_update, + Config: testAccLoadBalancerConfig_idleTimeoutUpdate, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "idle_timeout", "400"), ), @@ -618,21 +618,21 @@ func TestAccELBLoadBalancer_connectionDraining(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConnectionDrainingConfig, + Config: testAccLoadBalancerConfig_connectionDraining, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "connection_draining", "true"), resource.TestCheckResourceAttr(resourceName, "connection_draining_timeout", "400"), ), }, { - Config: testAccLoadBalancerConnectionDrainingConfig_update_timeout, + Config: testAccLoadBalancerConfig_connectionDrainingUpdateTimeout, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "connection_draining", "true"), resource.TestCheckResourceAttr(resourceName, "connection_draining_timeout", "600"), ), }, { - Config: testAccLoadBalancerConnectionDrainingConfig_update_disable, + Config: testAccLoadBalancerConfig_connectionDrainingUpdateDisable, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "connection_draining", "false"), ), @@ -651,14 +651,14 @@ func TestAccELBLoadBalancer_securityGroups(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig, + Config: testAccLoadBalancerConfig_basic, Check: resource.ComposeTestCheckFunc( // ELBs get a default security group resource.TestCheckResourceAttr(resourceName, "security_groups.#", "1"), ), }, { - Config: testAccLoadBalancerSecurityGroupsConfig, + Config: testAccLoadBalancerConfig_securityGroups, Check: resource.ComposeTestCheckFunc( // Count should still be one as we swap in a custom security group resource.TestCheckResourceAttr(resourceName, "security_groups.#", "1"), @@ -678,7 +678,7 @@ func TestAccELBLoadBalancer_desyncMitigationMode(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfigDesyncMitigationMode, + Config: testAccLoadBalancerConfig_desyncMitigationMode, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "desync_mitigation_mode", "strictest"), ), @@ -702,7 +702,7 @@ func TestAccELBLoadBalancer_desyncMitigationMode_update(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfigDesyncMitigationMode_update_default, + Config: testAccLoadBalancerConfig_desyncMitigationModeUpdateDefault, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "desync_mitigation_mode", "defensive"), ), @@ -713,7 +713,7 @@ func TestAccELBLoadBalancer_desyncMitigationMode_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerConfigDesyncMitigationMode_update_monitor, + Config: testAccLoadBalancerConfig_desyncMitigationModeUpdateMonitor, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "desync_mitigation_mode", "monitor"), ), @@ -724,7 +724,7 @@ func TestAccELBLoadBalancer_desyncMitigationMode_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerConfigDesyncMitigationMode_update_default, + Config: testAccLoadBalancerConfig_desyncMitigationModeUpdateDefault, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "desync_mitigation_mode", "defensive"), ), @@ -1049,7 +1049,7 @@ func testAccCheckLoadBalancerExists(n string, res *elb.LoadBalancerDescription) } } -const testAccLoadBalancerConfig = ` +const testAccLoadBalancerConfig_basic = ` data "aws_availability_zones" "available" { state = "available" @@ -1073,7 +1073,7 @@ resource "aws_elb" "test" { } ` -func testAccLoadBalancerTags1Config(tagKey1, tagValue1 string) string { +func testAccLoadBalancerConfig_tags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1103,7 +1103,7 @@ resource "aws_elb" "test" { `, tagKey1, tagValue1) } -func testAccLoadBalancerTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccLoadBalancerConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1134,7 +1134,8 @@ resource "aws_elb" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2) } -const testAccLoadBalancerFullRangeOfCharacters = ` +func testAccLoadBalancerConfig_fullRangeOfCharacters(rName string) string { + return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1145,7 +1146,7 @@ data "aws_availability_zones" "available" { } resource "aws_elb" "test" { - name = "%s" + name = %[1]q availability_zones = [data.aws_availability_zones.available.names[0], data.aws_availability_zones.available.names[1], data.aws_availability_zones.available.names[2]] listener { @@ -1155,9 +1156,10 @@ resource "aws_elb" "test" { lb_protocol = "http" } } -` +`, rName) +} -const testAccLoadBalancerAccessLogs = ` +const testAccLoadBalancerConfig_accessLogs = ` data "aws_availability_zones" "available" { state = "available" @@ -1179,7 +1181,7 @@ resource "aws_elb" "test" { } ` -func testAccLoadBalancerAccessLogsOn(r string) string { +func testAccLoadBalancerConfig_accessLogsOn(r string) string { return ` resource "aws_elb" "test" { # Must have bucket policy attached first @@ -1211,7 +1213,7 @@ data "aws_availability_zones" "available" { ` + testAccLoadBalancerAccessLogsCommon(r) } -func testAccLoadBalancerAccessLogsDisabled(r string) string { +func testAccLoadBalancerConfig_accessLogsDisabled(r string) string { return ` resource "aws_elb" "test" { # Must have bucket policy attached first @@ -1283,7 +1285,7 @@ EOF `, r) } -const testAccLoadBalancer_namePrefix = ` +const testAccLoadBalancerConfig_namePrefix = ` data "aws_availability_zones" "available" { state = "available" @@ -1306,7 +1308,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerGeneratedName = ` +const testAccLoadBalancerConfig_generatedName = ` data "aws_availability_zones" "available" { state = "available" @@ -1328,7 +1330,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancer_zeroValueName = ` +const testAccLoadBalancerConfig_zeroValueName = ` data "aws_availability_zones" "available" { state = "available" @@ -1356,7 +1358,7 @@ output "lb_name" { } ` -const testAccLoadBalancerConfig_AvailabilityZonesUpdate = ` +const testAccLoadBalancerConfig_availabilityZonesUpdate = ` data "aws_availability_zones" "available" { state = "available" @@ -1378,7 +1380,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerNewInstanceConfig = ` +const testAccLoadBalancerConfig_newInstance = ` data "aws_ami" "amzn-ami-minimal-hvm-ebs" { most_recent = true owners = ["amazon"] @@ -1422,7 +1424,7 @@ resource "aws_instance" "test" { } ` -const testAccLoadBalancerHealthCheckConfig = ` +const testAccLoadBalancerConfig_healthCheck = ` data "aws_availability_zones" "available" { state = "available" @@ -1452,7 +1454,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerHealthCheckConfig_update = ` +const testAccLoadBalancerConfig_healthCheckUpdate = ` data "aws_availability_zones" "available" { state = "available" @@ -1482,7 +1484,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerListenerConfig_update = ` +const testAccLoadBalancerConfig_listenerUpdate = ` data "aws_availability_zones" "available" { state = "available" @@ -1504,7 +1506,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerListenerConfig_multipleListeners = ` +const testAccLoadBalancerConfig_listenerMultipleListeners = ` data "aws_availability_zones" "available" { state = "available" @@ -1533,7 +1535,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerIdleTimeoutConfig = ` +const testAccLoadBalancerConfig_idleTimeout = ` data "aws_availability_zones" "available" { state = "available" @@ -1557,7 +1559,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerIdleTimeoutConfig_update = ` +const testAccLoadBalancerConfig_idleTimeoutUpdate = ` data "aws_availability_zones" "available" { state = "available" @@ -1581,7 +1583,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerConnectionDrainingConfig = ` +const testAccLoadBalancerConfig_connectionDraining = ` data "aws_availability_zones" "available" { state = "available" @@ -1606,7 +1608,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerConnectionDrainingConfig_update_timeout = ` +const testAccLoadBalancerConfig_connectionDrainingUpdateTimeout = ` data "aws_availability_zones" "available" { state = "available" @@ -1631,7 +1633,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerConnectionDrainingConfig_update_disable = ` +const testAccLoadBalancerConfig_connectionDrainingUpdateDisable = ` data "aws_availability_zones" "available" { state = "available" @@ -1655,7 +1657,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerSecurityGroupsConfig = ` +const testAccLoadBalancerConfig_securityGroups = ` data "aws_availability_zones" "available" { state = "available" @@ -1692,7 +1694,7 @@ resource "aws_security_group" "test" { } ` -func testAccLBConfig_Listener_iamServerCertificate(certName, certificate, key, lbProtocol string) string { +func testAccLoadBalancerConfig_listenerIAMServerCertificate(certName, certificate, key, lbProtocol string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1723,7 +1725,7 @@ resource "aws_elb" "test" { `, certName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key), lbProtocol) } -func testAccLBConfig_Listener_iamServerCertificateAddInvalidListener(certName, certificate, key string) string { +func testAccLoadBalancerConfig_listenerIAMServerCertificateAddInvalidListener(certName, certificate, key string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1841,7 +1843,7 @@ resource "aws_internet_gateway" "gw" { } ` -const testAccLoadBalancerConfig_subnet_swap = ` +const testAccLoadBalancerConfig_subnetSwap = ` data "aws_availability_zones" "available" { state = "available" @@ -1917,7 +1919,7 @@ resource "aws_internet_gateway" "gw" { } ` -const testAccLoadBalancerConfigDesyncMitigationMode = ` +const testAccLoadBalancerConfig_desyncMitigationMode = ` data "aws_availability_zones" "available" { state = "available" @@ -1940,7 +1942,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerConfigDesyncMitigationMode_update_default = ` +const testAccLoadBalancerConfig_desyncMitigationModeUpdateDefault = ` data "aws_availability_zones" "available" { state = "available" @@ -1962,7 +1964,7 @@ resource "aws_elb" "test" { } ` -const testAccLoadBalancerConfigDesyncMitigationMode_update_monitor = ` +const testAccLoadBalancerConfig_desyncMitigationModeUpdateMonitor = ` data "aws_availability_zones" "available" { state = "available" diff --git a/internal/service/elb/policy.go b/internal/service/elb/policy.go index 7b07c6ba832..dec396dcfae 100644 --- a/internal/service/elb/policy.go +++ b/internal/service/elb/policy.go @@ -102,13 +102,12 @@ func resourcePolicyRead(d *schema.ResourceData, meta interface{}) error { getResp, err := conn.DescribeLoadBalancerPolicies(request) - if tfawserr.ErrCodeEquals(err, "LoadBalancerNotFound") { - log.Printf("[WARN] Load Balancer Policy (%s) not found, removing from state", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, "LoadBalancerNotFound") { + log.Printf("[WARN] Load Balancer (%s) not found, removing from state", loadBalancerName) d.SetId("") return nil } - - if tfawserr.ErrCodeEquals(err, elb.ErrCodePolicyNotFoundException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodePolicyNotFoundException) { log.Printf("[WARN] Load Balancer Policy (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/internal/service/elb/policy_test.go b/internal/service/elb/policy_test.go index 88ebdf7339e..ebbcd840d04 100644 --- a/internal/service/elb/policy_test.go +++ b/internal/service/elb/policy_test.go @@ -89,7 +89,7 @@ func TestAccELBPolicy_LBCookieStickinessPolicyType_computedAttributesOnly(t *tes CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_policyTypeNameOnly(rName, policyTypeName), + Config: testAccPolicyConfig_typeNameOnly(rName, policyTypeName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "policy_type_name", policyTypeName), @@ -112,7 +112,7 @@ func TestAccELBPolicy_SSLNegotiationPolicyType_computedAttributesOnly(t *testing CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_policyTypeNameOnly(rName, tfelb.SSLNegotiationPolicyType), + Config: testAccPolicyConfig_typeNameOnly(rName, tfelb.SSLNegotiationPolicyType), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "policy_type_name", tfelb.SSLNegotiationPolicyType), @@ -135,7 +135,7 @@ func TestAccELBPolicy_SSLNegotiationPolicyType_customPolicy(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_customSSLSecurityPolicy(rName, "Protocol-TLSv1.1", "DHE-RSA-AES256-SHA256"), + Config: testAccPolicyConfig_customSSLSecurity(rName, "Protocol-TLSv1.1", "DHE-RSA-AES256-SHA256"), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "policy_name", rName), @@ -152,7 +152,7 @@ func TestAccELBPolicy_SSLNegotiationPolicyType_customPolicy(t *testing.T) { ), }, { - Config: testAccPolicyConfig_customSSLSecurityPolicy(rName, "Protocol-TLSv1.2", "ECDHE-ECDSA-AES128-GCM-SHA256"), + Config: testAccPolicyConfig_customSSLSecurity(rName, "Protocol-TLSv1.2", "ECDHE-ECDSA-AES128-GCM-SHA256"), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "policy_name", rName), @@ -186,7 +186,7 @@ func TestAccELBPolicy_SSLSecurityPolicy_predefined(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_predefinedSSLSecurityPolicy(rName, predefinedSecurityPolicy), + Config: testAccPolicyConfig_predefinedSSLSecurity(rName, predefinedSecurityPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "policy_attribute.#", "1"), @@ -198,7 +198,7 @@ func TestAccELBPolicy_SSLSecurityPolicy_predefined(t *testing.T) { ), }, { - Config: testAccPolicyConfig_predefinedSSLSecurityPolicy(rName, predefinedSecurityPolicyUpdated), + Config: testAccPolicyConfig_predefinedSSLSecurity(rName, predefinedSecurityPolicyUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "policy_attribute.#", "1"), @@ -411,7 +411,7 @@ resource "aws_load_balancer_policy" "test-policy" { `, rInt)) } -func testAccPolicyConfig_policyTypeNameOnly(rName, policyType string) string { +func testAccPolicyConfig_typeNameOnly(rName, policyType string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -439,7 +439,7 @@ resource "aws_load_balancer_policy" "test" { `, rName, policyType)) } -func testAccPolicyConfig_customSSLSecurityPolicy(rName, protocol, cipher string) string { +func testAccPolicyConfig_customSSLSecurity(rName, protocol, cipher string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elb" "test" { name = %[1]q @@ -475,7 +475,7 @@ resource "aws_load_balancer_policy" "test" { `, rName, protocol, cipher)) } -func testAccPolicyConfig_predefinedSSLSecurityPolicy(rName, securityPolicy string) string { +func testAccPolicyConfig_predefinedSSLSecurity(rName, securityPolicy string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elb" "test" { name = %[1]q diff --git a/internal/service/elb/proxy_protocol_policy.go b/internal/service/elb/proxy_protocol_policy.go index 295a9ba5d0d..ac72596e97f 100644 --- a/internal/service/elb/proxy_protocol_policy.go +++ b/internal/service/elb/proxy_protocol_policy.go @@ -8,6 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elb" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -56,12 +57,11 @@ func resourceProxyProtocolPolicyCreate(d *schema.ResourceData, meta interface{}) *input.PolicyName, *input.PolicyTypeName) if _, err := conn.CreateLoadBalancerPolicy(input); err != nil { - return fmt.Errorf("Error creating a policy %s: %s", + return fmt.Errorf("Error creating a policy %s: %w", *input.PolicyName, err) } d.SetId(fmt.Sprintf("%s:%s", *elbname, *input.PolicyName)) - log.Printf("[INFO] ELB PolicyName: %s", *input.PolicyName) return resourceProxyProtocolPolicyUpdate(d, meta) } @@ -76,12 +76,12 @@ func resourceProxyProtocolPolicyRead(d *schema.ResourceData, meta interface{}) e } resp, err := conn.DescribeLoadBalancers(req) if err != nil { - if IsNotFound(err) { - // The ELB is gone now, so just remove it from the state + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, elb.ErrCodeAccessPointNotFoundException) { + log.Printf("[WARN] ELB Classic Proxy Protocol Policy (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return fmt.Errorf("Error retrieving ELB attributes: %s", err) + return fmt.Errorf("Error retrieving ELB attributes: %w", err) } backends := flattenBackendPolicies(resp.LoadBalancerDescriptions[0].BackendServerDescriptions) @@ -106,12 +106,7 @@ func resourceProxyProtocolPolicyUpdate(d *schema.ResourceData, meta interface{}) } resp, err := conn.DescribeLoadBalancers(req) if err != nil { - if IsNotFound(err) { - // The ELB is gone now, so just remove it from the state - d.SetId("") - return nil - } - return fmt.Errorf("Error retrieving ELB attributes: %s", err) + return fmt.Errorf("Error retrieving ELB attributes: %w", err) } backends := flattenBackendPolicies(resp.LoadBalancerDescriptions[0].BackendServerDescriptions) @@ -157,13 +152,12 @@ func resourceProxyProtocolPolicyDelete(d *schema.ResourceData, meta interface{}) req := &elb.DescribeLoadBalancersInput{ LoadBalancerNames: []*string{elbname}, } - var err error resp, err := conn.DescribeLoadBalancers(req) if err != nil { - if IsNotFound(err) { + if tfawserr.ErrCodeEquals(err, elb.ErrCodeAccessPointNotFoundException) { return nil } - return fmt.Errorf("Error retrieving ELB attributes: %s", err) + return fmt.Errorf("Error retrieving ELB attributes: %w", err) } backends := flattenBackendPolicies(resp.LoadBalancerDescriptions[0].BackendServerDescriptions) @@ -172,12 +166,12 @@ func resourceProxyProtocolPolicyDelete(d *schema.ResourceData, meta interface{}) inputs, err := resourceProxyProtocolPolicyRemove(policyName, ports, backends) if err != nil { - return fmt.Errorf("Error detaching a policy from backend: %s", err) + return fmt.Errorf("Error detaching a policy from backend: %w", err) } for _, input := range inputs { input.LoadBalancerName = elbname if _, err := conn.SetLoadBalancerPoliciesForBackendServer(input); err != nil { - return fmt.Errorf("Error setting policy for backend: %s", err) + return fmt.Errorf("Error setting policy for backend: %w", err) } } @@ -186,7 +180,7 @@ func resourceProxyProtocolPolicyDelete(d *schema.ResourceData, meta interface{}) PolicyName: aws.String(policyName), } if _, err := conn.DeleteLoadBalancerPolicy(pOpt); err != nil { - return fmt.Errorf("Error removing a policy from load balancer: %s", err) + return fmt.Errorf("Error removing a policy from load balancer: %w", err) } return nil diff --git a/internal/service/elb/proxy_protocol_policy_test.go b/internal/service/elb/proxy_protocol_policy_test.go index e3372190093..e518b36973e 100644 --- a/internal/service/elb/proxy_protocol_policy_test.go +++ b/internal/service/elb/proxy_protocol_policy_test.go @@ -6,12 +6,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elb" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - tfelb "github.com/hashicorp/terraform-provider-aws/internal/service/elb" ) func TestAccELBProxyProtocolPolicy_basic(t *testing.T) { @@ -23,7 +23,7 @@ func TestAccELBProxyProtocolPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckProxyProtocolPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyProtocolPolicyConfig(lbName), + Config: testAccProxyProtocolPolicyConfig_basic(lbName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "aws_proxy_protocol_policy.smtp", "load_balancer", lbName), @@ -33,12 +33,10 @@ func TestAccELBProxyProtocolPolicy_basic(t *testing.T) { ), }, { - Config: testAccProxyProtocolPolicyConfigUpdate(lbName), + Config: testAccProxyProtocolPolicyConfig_update(lbName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "aws_proxy_protocol_policy.smtp", "load_balancer", lbName), - resource.TestCheckResourceAttr( - "aws_proxy_protocol_policy.smtp", "instance_ports.#", "2"), + resource.TestCheckResourceAttr("aws_proxy_protocol_policy.smtp", "load_balancer", lbName), + resource.TestCheckResourceAttr("aws_proxy_protocol_policy.smtp", "instance_ports.#", "2"), resource.TestCheckTypeSetElemAttr("aws_proxy_protocol_policy.smtp", "instance_ports.*", "25"), resource.TestCheckTypeSetElemAttr("aws_proxy_protocol_policy.smtp", "instance_ports.*", "587"), ), @@ -62,7 +60,7 @@ func testAccCheckProxyProtocolPolicyDestroy(s *terraform.State) error { _, err := conn.DescribeLoadBalancers(req) if err != nil { // Verify the error is what we want - if tfelb.IsNotFound(err) { + if tfawserr.ErrCodeEquals(err, elb.ErrCodeAccessPointNotFoundException) { continue } return err @@ -73,7 +71,7 @@ func testAccCheckProxyProtocolPolicyDestroy(s *terraform.State) error { return nil } -func testAccProxyProtocolPolicyConfig(rName string) string { +func testAccProxyProtocolPolicyConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elb" "lb" { name = "%s" @@ -101,7 +99,7 @@ resource "aws_proxy_protocol_policy" "smtp" { `, rName)) } -func testAccProxyProtocolPolicyConfigUpdate(rName string) string { +func testAccProxyProtocolPolicyConfig_update(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_elb" "lb" { name = "%s" diff --git a/internal/service/elbv2/hosted_zone_id_data_source_test.go b/internal/service/elbv2/hosted_zone_id_data_source_test.go index 5d05c923aad..49ce8bc880d 100644 --- a/internal/service/elbv2/hosted_zone_id_data_source_test.go +++ b/internal/service/elbv2/hosted_zone_id_data_source_test.go @@ -16,25 +16,25 @@ func TestAccELBV2HostedZoneIDDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckAWSLbHostedZoneIdConfig, + Config: testAccHostedZoneIDDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_lb_hosted_zone_id.main", "id", tfelbv2.HostedZoneIdPerRegionALBMap[acctest.Region()]), ), }, { - Config: testAccCheckAWSLbHostedZoneIdExplicitRegionConfig, + Config: testAccHostedZoneIDDataSourceConfig_explicitRegion, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_lb_hosted_zone_id.regional", "id", "Z32O12XQLNTSW2"), ), }, { - Config: testAccCheckAWSLbHostedZoneIdExplicitNetworkConfig, + Config: testAccHostedZoneIDDataSourceConfig_explicitNetwork, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_lb_hosted_zone_id.network", "id", tfelbv2.HostedZoneIdPerRegionNLBMap[acctest.Region()]), ), }, { - Config: testAccCheckAWSLbHostedZoneIdExplicitNetworkRegionConfig, + Config: testAccHostedZoneIDDataSourceConfig_explicitNetworkRegion, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_lb_hosted_zone_id.network-regional", "id", "Z2IFOLAFXWLO4F"), ), @@ -43,25 +43,25 @@ func TestAccELBV2HostedZoneIDDataSource_basic(t *testing.T) { }) } -const testAccCheckAWSLbHostedZoneIdConfig = ` +const testAccHostedZoneIDDataSourceConfig_basic = ` data "aws_lb_hosted_zone_id" "main" {} ` //lintignore:AWSAT003 -const testAccCheckAWSLbHostedZoneIdExplicitRegionConfig = ` +const testAccHostedZoneIDDataSourceConfig_explicitRegion = ` data "aws_lb_hosted_zone_id" "regional" { region = "eu-west-1" } ` -const testAccCheckAWSLbHostedZoneIdExplicitNetworkConfig = ` +const testAccHostedZoneIDDataSourceConfig_explicitNetwork = ` data "aws_lb_hosted_zone_id" "network" { load_balancer_type = "network" } ` //lintignore:AWSAT003 -const testAccCheckAWSLbHostedZoneIdExplicitNetworkRegionConfig = ` +const testAccHostedZoneIDDataSourceConfig_explicitNetworkRegion = ` data "aws_lb_hosted_zone_id" "network-regional" { region = "eu-west-1" load_balancer_type = "network" diff --git a/internal/service/elbv2/listener.go b/internal/service/elbv2/listener.go index bd358cc44bd..104235dfd34 100644 --- a/internal/service/elbv2/listener.go +++ b/internal/service/elbv2/listener.go @@ -435,7 +435,7 @@ func resourceListenerCreate(d *schema.ResourceData, meta interface{}) error { output, err := retryListenerCreate(conn, params) // Some partitions may not support tag-on-create - if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ELBv2 Listener (%s) create failed (%s) with tags. Trying create without tags.", lbArn, err) params.Tags = nil output, err = retryListenerCreate(conn, params) @@ -451,7 +451,7 @@ func resourceListenerCreate(d *schema.ResourceData, meta interface{}) error { if params.Tags == nil && len(tags) > 0 { err := UpdateTags(conn, d.Id(), nil, tags) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // if default tags only, log and continue (i.e., should error if explicitly setting tags and they can't be) log.Printf("[WARN] error adding tags after create for ELBv2 Listener (%s): %s", d.Id(), err) return resourceListenerRead(d, meta) @@ -534,7 +534,7 @@ func resourceListenerRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, d.Id()) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to list tags for ELBv2 Listener %s: %s", d.Id(), err) return nil } @@ -643,7 +643,7 @@ func resourceListenerUpdate(d *schema.ResourceData, meta interface{}) error { } // ISO partitions may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to update tags for ELBv2 Listener %s: %s", d.Id(), err) return resourceListenerRead(d, meta) } @@ -759,7 +759,7 @@ func expandLbListenerActions(l []interface{}) ([]*elbv2.Action, error) { case elbv2.ActionTypeEnumAuthenticateOidc: if v, ok := tfMap["authenticate_oidc"].([]interface{}); ok { - action.AuthenticateOidcConfig = expandLbListenerAuthenticateOidcConfig(v) + action.AuthenticateOidcConfig = expandAuthenticateOIDCConfig(v) } else { err = errors.New("for actions of type 'authenticate-oidc', you must specify a 'authenticate_oidc' block") } @@ -808,7 +808,7 @@ func expandLbListenerAuthenticateCognitoConfig(l []interface{}) *elbv2.Authentic return config } -func expandLbListenerAuthenticateOidcConfig(l []interface{}) *elbv2.AuthenticateOidcActionConfig { +func expandAuthenticateOIDCConfig(l []interface{}) *elbv2.AuthenticateOidcActionConfig { if len(l) == 0 || l[0] == nil { return nil } @@ -989,7 +989,7 @@ func flattenLbListenerActions(d *schema.ResourceData, Actions []*elbv2.Action) [ clientSecret = v.(string) } - m["authenticate_oidc"] = flattenLbListenerActionAuthenticateOidcConfig(action.AuthenticateOidcConfig, clientSecret) + m["authenticate_oidc"] = flattenAuthenticateOIDCActionConfig(action.AuthenticateOidcConfig, clientSecret) } vActions = append(vActions, m) @@ -998,7 +998,7 @@ func flattenLbListenerActions(d *schema.ResourceData, Actions []*elbv2.Action) [ return vActions } -func flattenLbListenerActionAuthenticateOidcConfig(config *elbv2.AuthenticateOidcActionConfig, clientSecret string) []interface{} { +func flattenAuthenticateOIDCActionConfig(config *elbv2.AuthenticateOidcActionConfig, clientSecret string) []interface{} { if config == nil { return []interface{}{} } diff --git a/internal/service/elbv2/listener_certificate_test.go b/internal/service/elbv2/listener_certificate_test.go index ed1539f3f5f..1a2c899651d 100644 --- a/internal/service/elbv2/listener_certificate_test.go +++ b/internal/service/elbv2/listener_certificate_test.go @@ -31,7 +31,7 @@ func TestAccELBV2ListenerCertificate_basic(t *testing.T) { CheckDestroy: testAccCheckListenerCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccLbListenerCertificateConfig(rName, key, certificate), + Config: testAccListenerCertificateConfig_basic(rName, key, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckListenerCertificateExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", iamServerCertificateResourceName, "arn"), @@ -63,7 +63,7 @@ func TestAccELBV2ListenerCertificate_CertificateARN_underscores(t *testing.T) { CheckDestroy: testAccCheckListenerCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccLbListenerCertificateConfigCertificateArnUnderscores(rName, key, certificate), + Config: testAccListenerCertificateConfig_arnUnderscores(rName, key, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckListenerCertificateExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", iamServerCertificateResourceName, "arn"), @@ -97,7 +97,7 @@ func TestAccELBV2ListenerCertificate_multiple(t *testing.T) { CheckDestroy: testAccCheckListenerCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccLbListenerCertificateConfigMultiple(rName, keys, certificates), + Config: testAccListenerCertificateConfig_multiple(rName, keys, certificates), Check: resource.ComposeTestCheckFunc( testAccCheckListenerCertificateExists("aws_lb_listener_certificate.default"), testAccCheckListenerCertificateExists("aws_lb_listener_certificate.additional_1"), @@ -116,7 +116,7 @@ func TestAccELBV2ListenerCertificate_multiple(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLbListenerCertificateConfigMultipleAddNew(rName, keys, certificates), + Config: testAccListenerCertificateConfig_multipleAddNew(rName, keys, certificates), Check: resource.ComposeTestCheckFunc( testAccCheckListenerCertificateExists("aws_lb_listener_certificate.default"), testAccCheckListenerCertificateExists("aws_lb_listener_certificate.additional_1"), @@ -133,7 +133,7 @@ func TestAccELBV2ListenerCertificate_multiple(t *testing.T) { ), }, { - Config: testAccLbListenerCertificateConfigMultiple(rName, keys, certificates), + Config: testAccListenerCertificateConfig_multiple(rName, keys, certificates), Check: resource.ComposeTestCheckFunc( testAccCheckListenerCertificateExists("aws_lb_listener_certificate.default"), testAccCheckListenerCertificateExists("aws_lb_listener_certificate.additional_1"), @@ -164,7 +164,7 @@ func TestAccELBV2ListenerCertificate_disappears(t *testing.T) { CheckDestroy: testAccCheckListenerCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccLbListenerCertificateConfig(rName, key, certificate), + Config: testAccListenerCertificateConfig_basic(rName, key, certificate), Check: resource.ComposeTestCheckFunc( testAccCheckListenerCertificateExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfelbv2.ResourceListenerCertificate(), resourceName), @@ -233,7 +233,7 @@ func testAccCheckListenerCertificateNotExists(name string) resource.TestCheckFun } } -func testAccLbListenerCertificateConfigLbListenerBase(rName, key, certificate string) string { +func testAccListenerCertificateConfig_base(rName, key, certificate string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -297,8 +297,8 @@ resource "aws_lb_listener" "test" { `, rName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key)) } -func testAccLbListenerCertificateConfig(rName, key, certificate string) string { - return testAccLbListenerCertificateConfigLbListenerBase(rName, key, certificate) + ` +func testAccListenerCertificateConfig_basic(rName, key, certificate string) string { + return testAccListenerCertificateConfig_base(rName, key, certificate) + ` resource "aws_lb_listener_certificate" "test" { certificate_arn = aws_iam_server_certificate.test.arn listener_arn = aws_lb_listener.test.arn @@ -306,7 +306,7 @@ resource "aws_lb_listener_certificate" "test" { ` } -func testAccLbListenerCertificateConfigCertificateArnUnderscores(rName, key, certificate string) string { +func testAccListenerCertificateConfig_arnUnderscores(rName, key, certificate string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -375,8 +375,8 @@ resource "aws_lb_listener_certificate" "test" { `, rName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key)) } -func testAccLbListenerCertificateConfigMultiple(rName string, keys, certificates []string) string { - return testAccLbListenerCertificateConfigLbListenerBase(rName, keys[0], certificates[0]) + fmt.Sprintf(` +func testAccListenerCertificateConfig_multiple(rName string, keys, certificates []string) string { + return testAccListenerCertificateConfig_base(rName, keys[0], certificates[0]) + fmt.Sprintf(` resource "aws_lb_listener_certificate" "default" { listener_arn = aws_lb_listener.test.arn certificate_arn = aws_iam_server_certificate.test.arn @@ -406,8 +406,8 @@ resource "aws_iam_server_certificate" "additional_2" { `, rName, acctest.TLSPEMEscapeNewlines(certificates[1]), acctest.TLSPEMEscapeNewlines(keys[1]), acctest.TLSPEMEscapeNewlines(certificates[2]), acctest.TLSPEMEscapeNewlines(keys[2])) } -func testAccLbListenerCertificateConfigMultipleAddNew(rName string, keys, certificates []string) string { - return testAccLbListenerCertificateConfigMultiple(rName, keys, certificates) + fmt.Sprintf(` +func testAccListenerCertificateConfig_multipleAddNew(rName string, keys, certificates []string) string { + return testAccListenerCertificateConfig_multiple(rName, keys, certificates) + fmt.Sprintf(` resource "aws_iam_server_certificate" "additional_3" { name = "%[1]s-additional-3" certificate_body = "%[2]s" diff --git a/internal/service/elbv2/listener_data_source.go b/internal/service/elbv2/listener_data_source.go index 6e8fcf250d8..c557c7aae0d 100644 --- a/internal/service/elbv2/listener_data_source.go +++ b/internal/service/elbv2/listener_data_source.go @@ -341,7 +341,7 @@ func dataSourceListenerRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, d.Id()) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to list tags for ELBv2 Listener %s: %s", d.Id(), err) return nil } diff --git a/internal/service/elbv2/listener_data_source_test.go b/internal/service/elbv2/listener_data_source_test.go index 8e8c750128a..49a4b434d14 100644 --- a/internal/service/elbv2/listener_data_source_test.go +++ b/internal/service/elbv2/listener_data_source_test.go @@ -21,7 +21,7 @@ func TestAccELBV2ListenerDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbListenerBasicDataSourceConfig(rName), + Config: testAccListenerDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "load_balancer_arn"), resource.TestCheckResourceAttrSet(dataSourceName, "arn"), @@ -56,7 +56,7 @@ func TestAccELBV2ListenerDataSource_backwardsCompatibility(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbListenerBackwardsCompatibilityDataSourceConfig(rName), + Config: testAccListenerDataSourceConfig_backwardsCompatibility(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "load_balancer_arn"), resource.TestCheckResourceAttrSet(dataSourceName, "arn"), @@ -91,7 +91,7 @@ func TestAccELBV2ListenerDataSource_https(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbListenerHTTPSDataSourceConfig(rName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key)), + Config: testAccListenerDataSourceConfig_https(rName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key)), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "load_balancer_arn"), resource.TestCheckResourceAttrSet(dataSourceName, "arn"), @@ -128,7 +128,7 @@ func TestAccELBV2ListenerDataSource_DefaultAction_forward(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbListenerDefaultActionForwardDataSourceConfig(rName), + Config: testAccListenerDataSourceConfig_defaultActionForward(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "default_action.#", resourceName, "default_action.#"), resource.TestCheckResourceAttrPair(dataSourceName, "default_action.0.forward.#", resourceName, "default_action.0.forward.#"), @@ -138,7 +138,7 @@ func TestAccELBV2ListenerDataSource_DefaultAction_forward(t *testing.T) { }) } -func testAcclbListenerBasicDataSourceConfig(rName string) string { +func testAccListenerDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(testAccListenerBaseConfig(rName), fmt.Sprintf(` resource "aws_lb_listener" "test" { load_balancer_arn = aws_lb.test.id @@ -194,7 +194,7 @@ data "aws_lb_listener" "from_lb_and_port" { `, rName)) } -func testAcclbListenerBackwardsCompatibilityDataSourceConfig(rName string) string { +func testAccListenerDataSourceConfig_backwardsCompatibility(rName string) string { return acctest.ConfigCompose(testAccListenerBaseConfig(rName), fmt.Sprintf(` resource "aws_alb_listener" "test" { load_balancer_arn = aws_alb.test.id @@ -250,7 +250,7 @@ data "aws_alb_listener" "from_lb_and_port" { `, rName)) } -func testAcclbListenerHTTPSDataSourceConfig(rName, certificate, key string) string { +func testAccListenerDataSourceConfig_https(rName, certificate, key string) string { return acctest.ConfigCompose(testAccListenerBaseConfig(rName), fmt.Sprintf(` resource "aws_lb_listener" "test" { load_balancer_arn = aws_lb.test.id @@ -325,7 +325,7 @@ data "aws_lb_listener" "from_lb_and_port" { `, rName, certificate, key)) } -func testAcclbListenerDefaultActionForwardDataSourceConfig(rName string) string { +func testAccListenerDataSourceConfig_defaultActionForward(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` diff --git a/internal/service/elbv2/listener_rule.go b/internal/service/elbv2/listener_rule.go index fe8e19292e4..131505d858b 100644 --- a/internal/service/elbv2/listener_rule.go +++ b/internal/service/elbv2/listener_rule.go @@ -513,7 +513,7 @@ func resourceListenerRuleCreate(d *schema.ResourceData, meta interface{}) error resp, err := retryListenerRuleCreate(conn, d, params, listenerArn) // Some partitions may not support tag-on-create - if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ELBv2 Listener Rule (%s) create failed (%s) with tags. Trying create without tags.", listenerArn, err) params.Tags = nil resp, err = retryListenerRuleCreate(conn, d, params, listenerArn) @@ -529,7 +529,7 @@ func resourceListenerRuleCreate(d *schema.ResourceData, meta interface{}) error if params.Tags == nil && len(tags) > 0 { err := UpdateTags(conn, d.Id(), nil, tags) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // if default tags only, log and continue (i.e., should error if explicitly setting tags and they can't be) log.Printf("[WARN] error adding tags after create for ELBv2 Listener Rule (%s): %s", d.Id(), err) return resourceListenerRuleRead(d, meta) @@ -767,7 +767,7 @@ func resourceListenerRuleRead(d *schema.ResourceData, meta interface{}) error { // tags at the end because, if not supported, will skip the rest of Read tags, err := ListTags(conn, d.Id()) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to list tags for ELBv2 Listener Rule %s: %s", d.Id(), err) return nil } @@ -866,7 +866,7 @@ func resourceListenerRuleUpdate(d *schema.ResourceData, meta interface{}) error } // ISO partitions may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to update tags for ELBv2 Listener Rule %s: %s", d.Id(), err) return resourceListenerRuleRead(d, meta) } diff --git a/internal/service/elbv2/listener_rule_test.go b/internal/service/elbv2/listener_rule_test.go index f8cdc37a553..d1c34cad3ad 100644 --- a/internal/service/elbv2/listener_rule_test.go +++ b/internal/service/elbv2/listener_rule_test.go @@ -121,7 +121,7 @@ func TestAccELBV2ListenerRule_tags(t *testing.T) { CheckDestroy: testAccCheckListenerRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerRuleTags1Config(lbName, targetGroupName, "key1", "value1"), + Config: testAccListenerRuleConfig_tags1(lbName, targetGroupName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -129,7 +129,7 @@ func TestAccELBV2ListenerRule_tags(t *testing.T) { ), }, { - Config: testAccListenerRuleTags2Config(lbName, targetGroupName, "key1", "value1updated", "key2", "value2"), + Config: testAccListenerRuleConfig_tags2(lbName, targetGroupName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -138,7 +138,7 @@ func TestAccELBV2ListenerRule_tags(t *testing.T) { ), }, { - Config: testAccListenerRuleTags1Config(lbName, targetGroupName, "key2", "value2"), + Config: testAccListenerRuleConfig_tags1(lbName, targetGroupName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -245,7 +245,7 @@ func TestAccELBV2ListenerRule_backwardsCompatibility(t *testing.T) { CheckDestroy: testAccCheckListenerRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerRuleBackwardsCompatibilityConfig(lbName, targetGroupName), + Config: testAccListenerRuleConfig_backwardsCompatibility(lbName, targetGroupName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), @@ -455,7 +455,7 @@ func TestAccELBV2ListenerRule_updateRulePriority(t *testing.T) { ), }, { - Config: testAccListenerRuleConfig_updateRulePriority(lbName, targetGroupName), + Config: testAccListenerRuleConfig_updatePriority(lbName, targetGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &after), testAccCheckListenerRuleNotRecreated(t, &before, &after), @@ -486,7 +486,7 @@ func TestAccELBV2ListenerRule_changeListenerRuleARNForcesNew(t *testing.T) { ), }, { - Config: testAccListenerRuleConfig_changeRuleARN(lbName, targetGroupName), + Config: testAccListenerRuleConfig_changeARN(lbName, targetGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &after), testAccCheckListenerRuleRecreated(t, &before, &after), @@ -676,7 +676,7 @@ func TestAccELBV2ListenerRule_Action_order(t *testing.T) { CheckDestroy: testAccCheckListenerRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerRuleConfig_Action_Order(rName, key, certificate), + Config: testAccListenerRuleConfig_actionOrder(rName, key, certificate), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "action.#", "2"), @@ -703,7 +703,7 @@ func TestAccELBV2ListenerRule_ActionOrder_recreates(t *testing.T) { CheckDestroy: testAccCheckListenerRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerRuleConfig_Action_Order(rName, key, certificate), + Config: testAccListenerRuleConfig_actionOrder(rName, key, certificate), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "action.#", "2"), @@ -727,23 +727,23 @@ func TestAccELBV2ListenerRule_conditionAttributesCount(t *testing.T) { CheckDestroy: testAccCheckListenerRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerRuleConfig_conditionAttributesCount_http_header(), + Config: testAccListenerRuleConfig_conditionAttributesCountHTTPHeader(), ExpectError: err_many, }, { - Config: testAccListenerRuleConfig_conditionAttributesCount_http_request_method(), + Config: testAccListenerRuleConfig_conditionAttributesCountHTTPRequestMethod(), ExpectError: err_many, }, { - Config: testAccListenerRuleConfig_conditionAttributesCount_path_pattern(), + Config: testAccListenerRuleConfig_conditionAttributesCountPathPattern(), ExpectError: err_many, }, { - Config: testAccListenerRuleConfig_conditionAttributesCount_query_string(), + Config: testAccListenerRuleConfig_conditionAttributesCountQueryString(), ExpectError: err_many, }, { - Config: testAccListenerRuleConfig_conditionAttributesCount_source_ip(), + Config: testAccListenerRuleConfig_conditionAttributesCountSourceIP(), ExpectError: err_many, }, }, @@ -848,7 +848,7 @@ func TestAccELBV2ListenerRule_ConditionHTTPHeader_invalid(t *testing.T) { CheckDestroy: testAccCheckListenerRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerRuleConfig_conditionHTTPHeader_invalid(), + Config: testAccListenerRuleConfig_conditionHTTPHeaderInvalid(), ExpectError: regexp.MustCompile(`expected value of condition.0.http_header.0.http_header_name to match regular expression`), }, }, @@ -1072,7 +1072,7 @@ func TestAccELBV2ListenerRule_conditionUpdateMixed(t *testing.T) { ), }, { - Config: testAccListenerRuleConfig_conditionMixed_updated(lbName), + Config: testAccListenerRuleConfig_conditionMixedUpdated(lbName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), @@ -1091,7 +1091,7 @@ func TestAccELBV2ListenerRule_conditionUpdateMixed(t *testing.T) { ), }, { - Config: testAccListenerRuleConfig_conditionMixed_updated2(lbName), + Config: testAccListenerRuleConfig_conditionMixedUpdated2(lbName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), @@ -1250,7 +1250,7 @@ func TestAccELBV2ListenerRule_conditionUpdateMultiple(t *testing.T) { ), }, { - Config: testAccListenerRuleConfig_conditionMultiple_updated(lbName), + Config: testAccListenerRuleConfig_conditionMultipleUpdated(lbName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerRuleExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), @@ -1967,7 +1967,7 @@ resource "aws_security_group" "alb_test" { `, lbName, targetGroupName1, targetGroupName2) } -func testAccListenerRuleBackwardsCompatibilityConfig(lbName, targetGroupName string) string { +func testAccListenerRuleConfig_backwardsCompatibility(lbName, targetGroupName string) string { return fmt.Sprintf(` resource "aws_alb_listener_rule" "static" { listener_arn = aws_alb_listener.front_end.arn @@ -2319,7 +2319,7 @@ resource "aws_security_group" "alb_test" { `, response, lbName) } -func testAccListenerRuleConfig_updateRulePriority(lbName, targetGroupName string) string { +func testAccListenerRuleConfig_updatePriority(lbName, targetGroupName string) string { return fmt.Sprintf(` resource "aws_lb_listener_rule" "static" { listener_arn = aws_lb_listener.front_end.arn @@ -2440,7 +2440,7 @@ resource "aws_security_group" "alb_test" { `, lbName, targetGroupName) } -func testAccListenerRuleConfig_changeRuleARN(lbName, targetGroupName string) string { +func testAccListenerRuleConfig_changeARN(lbName, targetGroupName string) string { return fmt.Sprintf(` resource "aws_lb_listener_rule" "static" { listener_arn = aws_lb_listener.front_end_ruleupdate.arn @@ -3144,7 +3144,7 @@ resource "aws_security_group" "alb_test" { `, rName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key)) } -func testAccListenerRuleConfig_Action_Order(rName, key, certificate string) string { +func testAccListenerRuleConfig_actionOrder(rName, key, certificate string) string { return fmt.Sprintf(` variable "rName" { default = %[1]q @@ -3308,7 +3308,7 @@ resource "aws_lb_listener_rule" "error" { `, condition) } -func testAccListenerRuleConfig_conditionAttributesCount_http_header() string { +func testAccListenerRuleConfig_conditionAttributesCountHTTPHeader() string { return testAccListenerRuleConfig_condition_error(` condition { host_header { @@ -3323,7 +3323,7 @@ condition { `) } -func testAccListenerRuleConfig_conditionAttributesCount_http_request_method() string { +func testAccListenerRuleConfig_conditionAttributesCountHTTPRequestMethod() string { return testAccListenerRuleConfig_condition_error(` condition { host_header { @@ -3337,7 +3337,7 @@ condition { `) } -func testAccListenerRuleConfig_conditionAttributesCount_path_pattern() string { +func testAccListenerRuleConfig_conditionAttributesCountPathPattern() string { return testAccListenerRuleConfig_condition_error(` condition { host_header { @@ -3351,7 +3351,7 @@ condition { `) } -func testAccListenerRuleConfig_conditionAttributesCount_query_string() string { +func testAccListenerRuleConfig_conditionAttributesCountQueryString() string { return testAccListenerRuleConfig_condition_error(` condition { host_header { @@ -3366,7 +3366,7 @@ condition { `) } -func testAccListenerRuleConfig_conditionAttributesCount_source_ip() string { +func testAccListenerRuleConfig_conditionAttributesCountSourceIP() string { return testAccListenerRuleConfig_condition_error(` condition { host_header { @@ -3517,7 +3517,7 @@ condition { `, lbName) } -func testAccListenerRuleConfig_conditionHTTPHeader_invalid() string { +func testAccListenerRuleConfig_conditionHTTPHeaderInvalid() string { return ` data "aws_partition" "current" {} @@ -3626,7 +3626,7 @@ condition { } // Update new style condition without modifying deprecated. Issue GH-11323 -func testAccListenerRuleConfig_conditionMixed_updated(lbName string) string { +func testAccListenerRuleConfig_conditionMixedUpdated(lbName string) string { return testAccListenerRuleConfig_conditionBase(` condition { path_pattern { @@ -3645,7 +3645,7 @@ condition { } // Then update deprecated syntax without touching new. Issue GH-11362 -func testAccListenerRuleConfig_conditionMixed_updated2(lbName string) string { +func testAccListenerRuleConfig_conditionMixedUpdated2(lbName string) string { return testAccListenerRuleConfig_conditionBase(` condition { path_pattern { @@ -3699,7 +3699,7 @@ condition { `, lbName) } -func testAccListenerRuleConfig_conditionMultiple_updated(lbName string) string { +func testAccListenerRuleConfig_conditionMultipleUpdated(lbName string) string { return testAccListenerRuleConfig_conditionBase(` condition { host_header { @@ -3734,7 +3734,7 @@ condition { `, lbName) } -func testAccListenerRuleTags1Config(lbName, targetGroupName, tagKey1, tagValue1 string) string { +func testAccListenerRuleConfig_tags1(lbName, targetGroupName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_lb_listener_rule" "static" { listener_arn = aws_lb_listener.front_end.arn @@ -3859,7 +3859,7 @@ resource "aws_security_group" "alb_test" { `, lbName, targetGroupName, tagKey1, tagValue1) } -func testAccListenerRuleTags2Config(lbName, targetGroupName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccListenerRuleConfig_tags2(lbName, targetGroupName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_lb_listener_rule" "static" { listener_arn = aws_lb_listener.front_end.arn diff --git a/internal/service/elbv2/listener_test.go b/internal/service/elbv2/listener_test.go index b721203498d..4ce95ce68da 100644 --- a/internal/service/elbv2/listener_test.go +++ b/internal/service/elbv2/listener_test.go @@ -66,7 +66,7 @@ func TestAccELBV2Listener_tags(t *testing.T) { CheckDestroy: testAccCheckListenerDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerTags1Config(rName, "key1", "value1"), + Config: testAccListenerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -79,7 +79,7 @@ func TestAccELBV2Listener_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccListenerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccListenerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -88,7 +88,7 @@ func TestAccELBV2Listener_tags(t *testing.T) { ), }, { - Config: testAccListenerTags1Config(rName, "key2", "value2"), + Config: testAccListenerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -227,7 +227,7 @@ func TestAccELBV2Listener_backwardsCompatibility(t *testing.T) { CheckDestroy: testAccCheckListenerDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerBackwardsCompatibilityConfig(rName), + Config: testAccListenerConfig_backwardsCompatibility(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerExists(resourceName, &conf), resource.TestCheckResourceAttrPair(resourceName, "load_balancer_arn", "aws_alb.test", "arn"), @@ -308,7 +308,7 @@ func TestAccELBV2Listener_LoadBalancerARN_gatewayLoadBalancer(t *testing.T) { CheckDestroy: testAccCheckListenerDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerConfig_LoadBalancerARN_GatewayLoadBalancer(rName), + Config: testAccListenerConfig_arnGateway(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerExists(resourceName, &conf), resource.TestCheckResourceAttrPair(resourceName, "load_balancer_arn", lbResourceName, "arn"), @@ -338,7 +338,7 @@ func TestAccELBV2Listener_Protocol_tls(t *testing.T) { CheckDestroy: testAccCheckListenerDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerConfig_Protocol_TLS(rName, key, certificate), + Config: testAccListenerConfig_protocolTLS(rName, key, certificate), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerExists(resourceName, &listener1), resource.TestCheckResourceAttr(resourceName, "protocol", "TLS"), @@ -541,7 +541,7 @@ func TestAccELBV2Listener_DefaultAction_order(t *testing.T) { CheckDestroy: testAccCheckListenerDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerConfig_DefaultAction_Order(rName, key, certificate), + Config: testAccListenerConfig_defaultActionOrder(rName, key, certificate), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerExists(resourceName, &listener), resource.TestCheckResourceAttr(resourceName, "default_action.#", "2"), @@ -574,7 +574,7 @@ func TestAccELBV2Listener_DefaultAction_orderRecreates(t *testing.T) { CheckDestroy: testAccCheckListenerDestroy, Steps: []resource.TestStep{ { - Config: testAccListenerConfig_DefaultAction_Order(rName, key, certificate), + Config: testAccListenerConfig_defaultActionOrder(rName, key, certificate), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckListenerExists(resourceName, &listener), resource.TestCheckResourceAttr(resourceName, "default_action.#", "2"), @@ -1070,7 +1070,7 @@ resource "aws_internet_gateway" "test" { `, rName)) } -func testAccListenerBackwardsCompatibilityConfig(rName string) string { +func testAccListenerConfig_backwardsCompatibility(rName string) string { return acctest.ConfigCompose(testAccListenerBaseConfig(rName), fmt.Sprintf(` resource "aws_alb_listener" "test" { load_balancer_arn = aws_alb.test.id @@ -1188,7 +1188,7 @@ resource "aws_internet_gateway" "test" { `, rName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key))) } -func testAccListenerConfig_LoadBalancerARN_GatewayLoadBalancer(rName string) string { +func testAccListenerConfig_arnGateway(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1242,7 +1242,7 @@ resource "aws_lb_listener" "test" { `, rName)) } -func testAccListenerConfig_Protocol_TLS(rName, key, certificate string) string { +func testAccListenerConfig_protocolTLS(rName, key, certificate string) string { return acctest.ConfigCompose(testAccListenerBaseConfig(rName), fmt.Sprintf(` resource "aws_acm_certificate" "test" { certificate_body = "%[2]s" @@ -1553,7 +1553,7 @@ resource "aws_lb_listener" "test" { `, rName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key))) } -func testAccListenerConfig_DefaultAction_Order(rName, key, certificate string) string { +func testAccListenerConfig_defaultActionOrder(rName, key, certificate string) string { return acctest.ConfigCompose(testAccListenerBaseConfig(rName), fmt.Sprintf(` resource "aws_lb_listener" "test" { load_balancer_arn = aws_lb.test.id @@ -1628,7 +1628,7 @@ resource "aws_lb_target_group" "test" { `, rName, acctest.TLSPEMEscapeNewlines(certificate), acctest.TLSPEMEscapeNewlines(key))) } -func testAccListenerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccListenerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccListenerBaseConfig(rName), fmt.Sprintf(` resource "aws_lb_listener" "test" { load_balancer_arn = aws_lb.test.id @@ -1683,7 +1683,7 @@ resource "aws_lb_target_group" "test" { `, rName, tagKey1, tagValue1)) } -func testAccListenerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccListenerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccListenerBaseConfig(rName), fmt.Sprintf(` resource "aws_lb_listener" "test" { load_balancer_arn = aws_lb.test.id diff --git a/internal/service/elbv2/load_balancer.go b/internal/service/elbv2/load_balancer.go index 895b9054228..c4d0b9626d2 100644 --- a/internal/service/elbv2/load_balancer.go +++ b/internal/service/elbv2/load_balancer.go @@ -361,7 +361,7 @@ func resourceLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error resp, err := conn.CreateLoadBalancer(elbOpts) // Some partitions may not support tag-on-create - if elbOpts.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if elbOpts.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ELBv2 Load Balancer (%s) create failed (%s) with tags. Trying create without tags.", name, err) elbOpts.Tags = nil resp, err = conn.CreateLoadBalancer(elbOpts) @@ -389,7 +389,7 @@ func resourceLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error err := UpdateTags(conn, d.Id(), nil, tags) // if default tags only, log and continue (i.e., should error if explicitly setting tags and they can't be) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] error adding tags after create for ELBv2 Load Balancer (%s): %s", d.Id(), err) return resourceLoadBalancerUpdate(d, meta) } @@ -624,7 +624,7 @@ func resourceLoadBalancerUpdate(d *schema.ResourceData, meta interface{}) error } // ISO partitions may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to update tags for ELBv2 Load Balancer %s: %s", d.Id(), err) _, err := waitLoadBalancerActive(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)) @@ -692,7 +692,7 @@ func removeAttribute(attributes []*elbv2.LoadBalancerAttribute, key string) []*e // which then blocks IGW, SG or VPC on deletion // So we make the cleanup "synchronous" here func cleanupALBNetworkInterfaces(conn *ec2.EC2, lbArn string) error { - name, err := getLbNameFromArn(lbArn) + name, err := getLBNameFromARN(lbArn) if err != nil { return err @@ -735,7 +735,7 @@ func cleanupALBNetworkInterfaces(conn *ec2.EC2, lbArn string) error { } func waitForNLBNetworkInterfacesToDetach(conn *ec2.EC2, lbArn string) error { - name, err := getLbNameFromArn(lbArn) + name, err := getLBNameFromARN(lbArn) if err != nil { return err @@ -774,7 +774,7 @@ func waitForNLBNetworkInterfacesToDetach(conn *ec2.EC2, lbArn string) error { return nil } -func getLbNameFromArn(arn string) (string, error) { +func getLBNameFromARN(arn string) (string, error) { re := regexp.MustCompile("([^/]+/[^/]+/[^/]+)$") matches := re.FindStringSubmatch(arn) if len(matches) != 2 { @@ -914,7 +914,7 @@ func flattenResource(d *schema.ResourceData, meta interface{}, lb *elbv2.LoadBal tags, err := ListTags(conn, d.Id()) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to list tags for ELBv2 Load Balancer %s: %s", d.Id(), err) return nil } diff --git a/internal/service/elbv2/load_balancer_data_source.go b/internal/service/elbv2/load_balancer_data_source.go index 6546b153893..b59471a346a 100644 --- a/internal/service/elbv2/load_balancer_data_source.go +++ b/internal/service/elbv2/load_balancer_data_source.go @@ -306,7 +306,7 @@ func dataSourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error tags, err := ListTags(conn, d.Id()) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to list tags for ELBv2 Load Balancer %s: %s", d.Id(), err) return nil } diff --git a/internal/service/elbv2/load_balancer_data_source_test.go b/internal/service/elbv2/load_balancer_data_source_test.go index 9fc43627358..ae66aa6e984 100644 --- a/internal/service/elbv2/load_balancer_data_source_test.go +++ b/internal/service/elbv2/load_balancer_data_source_test.go @@ -23,7 +23,7 @@ func TestAccELBV2LoadBalancerDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbBasicDataSourceConfig(rName), + Config: testAccLoadBalancerDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(dataSourceName, "internal", resourceName, "internal"), @@ -90,7 +90,7 @@ func TestAccELBV2LoadBalancerDataSource_outpost(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbOutpostDataSourceConfig(rName), + Config: testAccLoadBalancerDataSourceConfig_outpost(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(dataSourceName, "internal", resourceName, "internal"), @@ -127,7 +127,7 @@ func TestAccELBV2LoadBalancerDataSource_backwardsCompatibility(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbBackwardsCompatibilityDataSourceConfig(rName), + Config: testAccLoadBalancerDataSourceConfig_backwardsCompatibility(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName1, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(dataSourceName1, "internal", resourceName, "internal"), @@ -192,7 +192,7 @@ func TestAccELBV2LoadBalancerDataSource_backwardsCompatibility(t *testing.T) { }) } -func testAcclbBasicDataSourceConfig(rName string) string { +func testAccLoadBalancerDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_lb" "test" { name = %[1]q @@ -274,7 +274,7 @@ data "aws_lb" "alb_test_with_tags" { `, rName)) } -func testAcclbOutpostDataSourceConfig(rName string) string { +func testAccLoadBalancerDataSourceConfig_outpost(rName string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -346,7 +346,7 @@ data "aws_lb" "alb_test_with_arn" { `, rName) } -func testAcclbBackwardsCompatibilityDataSourceConfig(rName string) string { +func testAccLoadBalancerDataSourceConfig_backwardsCompatibility(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_alb" "test" { name = %[1]q diff --git a/internal/service/elbv2/load_balancer_test.go b/internal/service/elbv2/load_balancer_test.go index 6a190690afa..dfdd8ed3cf1 100644 --- a/internal/service/elbv2/load_balancer_test.go +++ b/internal/service/elbv2/load_balancer_test.go @@ -31,7 +31,7 @@ func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { ) } -func TestLBCloudwatchSuffixFromARN(t *testing.T) { +func TestLBCloudWatchSuffixFromARN(t *testing.T) { cases := []struct { name string arn *string @@ -112,7 +112,7 @@ func TestAccELBV2LoadBalancer_NLB_basic(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig_networkLoadbalancer(rName, false), + Config: testAccLoadBalancerConfig_nlb(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "access_logs.#", "1"), @@ -145,7 +145,7 @@ func TestAccELBV2LoadBalancer_LoadBalancerType_gateway(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig_LoadBalancerType_Gateway(rName), + Config: testAccLoadBalancerConfig_typeGateway(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf("loadbalancer/gwy/%s/.+", rName))), @@ -179,7 +179,7 @@ func TestAccELBV2LoadBalancer_ipv6SubnetMapping(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig_IPv6(rName), + Config: testAccLoadBalancerConfig_ipv6(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestMatchTypeSetElemNestedAttrs(resourceName, "subnet_mapping.*", map[string]*regexp.Regexp{ @@ -213,7 +213,7 @@ func TestAccELBV2LoadBalancer_LoadBalancerTypeGateway_enableCrossZoneLoadBalanci CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig_LoadBalancerType_Gateway_EnableCrossZoneLoadBalancing(rName, true), + Config: testAccLoadBalancerConfig_typeGatewayEnableCrossZoneBalancing(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf("loadbalancer/gwy/%s/.+", rName))), @@ -233,7 +233,7 @@ func TestAccELBV2LoadBalancer_LoadBalancerTypeGateway_enableCrossZoneLoadBalanci }, }, { - Config: testAccLoadBalancerConfig_LoadBalancerType_Gateway_EnableCrossZoneLoadBalancing(rName, false), + Config: testAccLoadBalancerConfig_typeGatewayEnableCrossZoneBalancing(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf("loadbalancer/gwy/%s/.+", rName))), @@ -296,7 +296,7 @@ func TestAccELBV2LoadBalancer_networkLoadBalancerEIP(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig_networkLoadBalancerEIP(rName), + Config: testAccLoadBalancerConfig_nlbEIP(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -326,7 +326,7 @@ func TestAccELBV2LoadBalancer_NLB_privateIPv4Address(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig_networkLoadBalancerPrivateIPV4Address(rName), + Config: testAccLoadBalancerConfig_nlbPrivateIPV4Address(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "internal", "true"), @@ -355,7 +355,7 @@ func TestAccELBV2LoadBalancer_backwardsCompatibility(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerBackwardsCompatibilityConfig(rName), + Config: testAccLoadBalancerConfig_backwardsCompatibility(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -502,7 +502,7 @@ func TestAccELBV2LoadBalancer_NetworkLoadBalancer_updateCrossZone(t *testing.T) CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig_networkLoadbalancer(rName, true), + Config: testAccLoadBalancerConfig_nlb(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &pre), testAccCheckLoadBalancerAttribute(resourceName, "load_balancing.cross_zone.enabled", "true"), @@ -510,7 +510,7 @@ func TestAccELBV2LoadBalancer_NetworkLoadBalancer_updateCrossZone(t *testing.T) ), }, { - Config: testAccLoadBalancerConfig_networkLoadbalancer(rName, false), + Config: testAccLoadBalancerConfig_nlb(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &mid), testAccCheckLoadBalancerAttribute(resourceName, "load_balancing.cross_zone.enabled", "false"), @@ -519,7 +519,7 @@ func TestAccELBV2LoadBalancer_NetworkLoadBalancer_updateCrossZone(t *testing.T) ), }, { - Config: testAccLoadBalancerConfig_networkLoadbalancer(rName, true), + Config: testAccLoadBalancerConfig_nlb(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &post), testAccCheckLoadBalancerAttribute(resourceName, "load_balancing.cross_zone.enabled", "true"), @@ -665,7 +665,7 @@ func TestAccELBV2LoadBalancer_ApplicationLoadBalancer_updateDeletionProtection(t }) } -func TestAccELBV2LoadBalancer_ApplicationLoadBalancer_updateWafFailOpen(t *testing.T) { +func TestAccELBV2LoadBalancer_ApplicationLoadBalancer_updateWAFFailOpen(t *testing.T) { var pre, mid, post elbv2.LoadBalancer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_lb.lb_test" @@ -681,7 +681,7 @@ func TestAccELBV2LoadBalancer_ApplicationLoadBalancer_updateWafFailOpen(t *testi CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLBConfig_enableWafFailOpen(rName, false), + Config: testAccLoadBalancerConfig_enableWAFFailOpen(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &pre), resource.TestCheckResourceAttr(resourceName, "enable_waf_fail_open", "false"), @@ -693,7 +693,7 @@ func TestAccELBV2LoadBalancer_ApplicationLoadBalancer_updateWafFailOpen(t *testi ImportStateVerify: true, }, { - Config: testAccLBConfig_enableWafFailOpen(rName, true), + Config: testAccLoadBalancerConfig_enableWAFFailOpen(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &mid), resource.TestCheckResourceAttr(resourceName, "enable_waf_fail_open", "true"), @@ -706,7 +706,7 @@ func TestAccELBV2LoadBalancer_ApplicationLoadBalancer_updateWafFailOpen(t *testi ImportStateVerify: true, }, { - Config: testAccLBConfig_enableWafFailOpen(rName, false), + Config: testAccLoadBalancerConfig_enableWAFFailOpen(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &post), resource.TestCheckResourceAttr(resourceName, "enable_waf_fail_open", "false"), @@ -797,14 +797,14 @@ func TestAccELBV2LoadBalancer_updatedIPAddressType(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerWithIPAddressTypeConfig(rName), + Config: testAccLoadBalancerConfig_ipAddressType(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &pre), resource.TestCheckResourceAttr(resourceName, "ip_address_type", "ipv4"), ), }, { - Config: testAccLoadBalancerWithIPAddressTypeUpdatedConfig(rName), + Config: testAccLoadBalancerConfig_ipAddressTypeUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &post), resource.TestCheckResourceAttr(resourceName, "ip_address_type", "dualstack"), @@ -865,7 +865,7 @@ func TestAccELBV2LoadBalancer_ALB_accessLogs(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerALBAccessLogsConfig(true, rName, ""), + Config: testAccLoadBalancerConfig_albAccessLogs(true, rName, ""), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -883,7 +883,7 @@ func TestAccELBV2LoadBalancer_ALB_accessLogs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerALBAccessLogsConfig(false, rName, ""), + Config: testAccLoadBalancerConfig_albAccessLogs(false, rName, ""), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -901,7 +901,7 @@ func TestAccELBV2LoadBalancer_ALB_accessLogs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerALBAccessLogsConfig(true, rName, ""), + Config: testAccLoadBalancerConfig_albAccessLogs(true, rName, ""), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -919,7 +919,7 @@ func TestAccELBV2LoadBalancer_ALB_accessLogs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerALBAccessLogsNoBlocksConfig(rName), + Config: testAccLoadBalancerConfig_albAccessLogsNoBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -956,7 +956,7 @@ func TestAccELBV2LoadBalancer_ALBAccessLogs_prefix(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerALBAccessLogsConfig(true, rName, "prefix1"), + Config: testAccLoadBalancerConfig_albAccessLogs(true, rName, "prefix1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -974,7 +974,7 @@ func TestAccELBV2LoadBalancer_ALBAccessLogs_prefix(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerALBAccessLogsConfig(true, rName, ""), + Config: testAccLoadBalancerConfig_albAccessLogs(true, rName, ""), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -992,7 +992,7 @@ func TestAccELBV2LoadBalancer_ALBAccessLogs_prefix(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerALBAccessLogsConfig(true, rName, "prefix1"), + Config: testAccLoadBalancerConfig_albAccessLogs(true, rName, "prefix1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -1029,7 +1029,7 @@ func TestAccELBV2LoadBalancer_NLB_accessLogs(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerNLBAccessLogsConfig(true, rName, ""), + Config: testAccLoadBalancerConfig_nlbAccessLogs(true, rName, ""), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -1047,7 +1047,7 @@ func TestAccELBV2LoadBalancer_NLB_accessLogs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerNLBAccessLogsConfig(false, rName, ""), + Config: testAccLoadBalancerConfig_nlbAccessLogs(false, rName, ""), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -1065,7 +1065,7 @@ func TestAccELBV2LoadBalancer_NLB_accessLogs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerNLBAccessLogsConfig(true, rName, ""), + Config: testAccLoadBalancerConfig_nlbAccessLogs(true, rName, ""), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -1083,7 +1083,7 @@ func TestAccELBV2LoadBalancer_NLB_accessLogs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerNLBAccessLogsNoBlocksConfig(rName), + Config: testAccLoadBalancerConfig_nlbAccessLogsNoBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -1120,7 +1120,7 @@ func TestAccELBV2LoadBalancer_NLBAccessLogs_prefix(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerNLBAccessLogsConfig(true, rName, "prefix1"), + Config: testAccLoadBalancerConfig_nlbAccessLogs(true, rName, "prefix1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -1138,7 +1138,7 @@ func TestAccELBV2LoadBalancer_NLBAccessLogs_prefix(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerNLBAccessLogsConfig(true, rName, ""), + Config: testAccLoadBalancerConfig_nlbAccessLogs(true, rName, ""), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -1156,7 +1156,7 @@ func TestAccELBV2LoadBalancer_NLBAccessLogs_prefix(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLoadBalancerNLBAccessLogsConfig(true, rName, "prefix1"), + Config: testAccLoadBalancerConfig_nlbAccessLogs(true, rName, "prefix1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), testAccCheckLoadBalancerAttribute(resourceName, "access_logs.s3.bucket", rName), @@ -1189,7 +1189,7 @@ func TestAccELBV2LoadBalancer_NetworkLoadBalancerSubnet_change(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLoadBalancerConfig_networkLoadbalancer_subnets(rName), + Config: testAccLoadBalancerConfig_nlbSubnets(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -1219,7 +1219,7 @@ func TestAccELBV2LoadBalancer_updateDesyncMitigationMode(t *testing.T) { CheckDestroy: testAccCheckLoadBalancerDestroy, Steps: []resource.TestStep{ { - Config: testAccLBConfig_desyncMitigationMode(rName, "strictest"), + Config: testAccLoadBalancerConfig_desyncMitigationMode(rName, "strictest"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &pre), testAccCheckLoadBalancerAttribute(resourceName, "routing.http.desync_mitigation_mode", "strictest"), @@ -1232,7 +1232,7 @@ func TestAccELBV2LoadBalancer_updateDesyncMitigationMode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLBConfig_desyncMitigationMode(rName, "monitor"), + Config: testAccLoadBalancerConfig_desyncMitigationMode(rName, "monitor"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &mid), testAccCheckLoadBalancerAttribute(resourceName, "routing.http.desync_mitigation_mode", "monitor"), @@ -1245,7 +1245,7 @@ func TestAccELBV2LoadBalancer_updateDesyncMitigationMode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLBConfig_desyncMitigationMode(rName, "defensive"), + Config: testAccLoadBalancerConfig_desyncMitigationMode(rName, "defensive"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLoadBalancerExists(resourceName, &post), testAccCheckLoadBalancerAttribute(resourceName, "routing.http.desync_mitigation_mode", "defensive"), @@ -1383,7 +1383,7 @@ func testAccPreCheckGatewayLoadBalancer(t *testing.T) { t.Skip("skipping acceptance testing: region does not support ELBv2 Gateway Load Balancers") } -func testAccLoadBalancerWithIPAddressTypeUpdatedConfig(rName string) string { +func testAccLoadBalancerConfig_ipAddressTypeUpdated(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_lb" "lb_test" { name = %[1]q @@ -1496,7 +1496,7 @@ resource "aws_security_group" "alb_test" { `, rName)) } -func testAccLoadBalancerWithIPAddressTypeConfig(rName string) string { +func testAccLoadBalancerConfig_ipAddressType(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_lb" "lb_test" { name = %[1]q @@ -1970,7 +1970,7 @@ resource "aws_security_group" "alb_test" { `, rName, deletionProtection)) } -func testAccLBConfig_enableWafFailOpen(rName string, wafFailOpen bool) string { +func testAccLoadBalancerConfig_enableWAFFailOpen(rName string, wafFailOpen bool) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2041,7 +2041,7 @@ resource "aws_security_group" "alb_test" { `, rName, wafFailOpen)) } -func testAccLoadBalancerConfig_networkLoadbalancer_subnets(rName string) string { +func testAccLoadBalancerConfig_nlbSubnets(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "alb_test" { cidr_block = "10.0.0.0/16" @@ -2103,7 +2103,7 @@ resource "aws_subnet" "alb_test_3" { `, rName)) } -func testAccLoadBalancerConfig_networkLoadbalancer(rName string, cz bool) string { +func testAccLoadBalancerConfig_nlb(rName string, cz bool) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_lb" "lb_test" { name = %[1]q @@ -2143,7 +2143,7 @@ resource "aws_subnet" "alb_test" { `, rName, cz)) } -func testAccLoadBalancerConfig_LoadBalancerType_Gateway(rName string) string { +func testAccLoadBalancerConfig_typeGateway(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2176,7 +2176,7 @@ resource "aws_lb" "test" { `, rName)) } -func testAccLoadBalancerConfig_IPv6(rName string) string { +func testAccLoadBalancerConfig_ipv6(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2227,7 +2227,7 @@ resource "aws_lb" "test" { `, rName)) } -func testAccLoadBalancerConfig_LoadBalancerType_Gateway_EnableCrossZoneLoadBalancing(rName string, enableCrossZoneLoadBalancing bool) string { +func testAccLoadBalancerConfig_typeGatewayEnableCrossZoneBalancing(rName string, enableCrossZoneLoadBalancing bool) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -2261,7 +2261,7 @@ resource "aws_lb" "test" { `, rName, enableCrossZoneLoadBalancing)) } -func testAccLoadBalancerConfig_networkLoadBalancerEIP(rName string) string { +func testAccLoadBalancerConfig_nlbEIP(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "main" { cidr_block = "10.10.0.0/16" @@ -2324,7 +2324,7 @@ resource "aws_eip" "lb" { `, rName)) } -func testAccLoadBalancerConfig_networkLoadBalancerPrivateIPV4Address(rName string) string { +func testAccLoadBalancerConfig_nlbPrivateIPV4Address(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_lb" "test" { name = %[1]q @@ -2363,7 +2363,7 @@ resource "aws_subnet" "test" { `, rName)) } -func testAccLoadBalancerBackwardsCompatibilityConfig(rName string) string { +func testAccLoadBalancerConfig_backwardsCompatibility(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_alb" "lb_test" { name = %[1]q @@ -2841,7 +2841,7 @@ resource "aws_s3_bucket_policy" "test" { `, rName)) } -func testAccLoadBalancerALBAccessLogsConfig(enabled bool, rName, bucketPrefix string) string { +func testAccLoadBalancerConfig_albAccessLogs(enabled bool, rName, bucketPrefix string) string { return acctest.ConfigCompose(testAccLoadBalancerALBAccessLogsBaseConfig(rName), fmt.Sprintf(` resource "aws_lb" "test" { internal = true @@ -2857,7 +2857,7 @@ resource "aws_lb" "test" { `, rName, enabled, bucketPrefix)) } -func testAccLoadBalancerALBAccessLogsNoBlocksConfig(rName string) string { +func testAccLoadBalancerConfig_albAccessLogsNoBlocks(rName string) string { return acctest.ConfigCompose(testAccLoadBalancerALBAccessLogsBaseConfig(rName), fmt.Sprintf(` resource "aws_lb" "test" { internal = true @@ -2927,7 +2927,7 @@ resource "aws_s3_bucket_policy" "test" { `, rName)) } -func testAccLoadBalancerNLBAccessLogsConfig(enabled bool, rName, bucketPrefix string) string { +func testAccLoadBalancerConfig_nlbAccessLogs(enabled bool, rName, bucketPrefix string) string { return acctest.ConfigCompose(testAccLoadBalancerNLBAccessLogsBaseConfig(rName), fmt.Sprintf(` resource "aws_lb" "test" { internal = true @@ -2944,7 +2944,7 @@ resource "aws_lb" "test" { `, rName, enabled, bucketPrefix)) } -func testAccLoadBalancerNLBAccessLogsNoBlocksConfig(rName string) string { +func testAccLoadBalancerConfig_nlbAccessLogsNoBlocks(rName string) string { return acctest.ConfigCompose(testAccLoadBalancerNLBAccessLogsBaseConfig(rName), fmt.Sprintf(` resource "aws_lb" "test" { internal = true @@ -3081,7 +3081,7 @@ resource "aws_security_group" "alb_test" { `, rName)) } -func testAccLBConfig_desyncMitigationMode(rName string, mode string) string { +func testAccLoadBalancerConfig_desyncMitigationMode(rName string, mode string) string { return fmt.Sprintf(` resource "aws_lb" "lb_test" { name = %[1]q diff --git a/internal/service/elbv2/target_group.go b/internal/service/elbv2/target_group.go index 71a44e75bf9..ec35d33e675 100644 --- a/internal/service/elbv2/target_group.go +++ b/internal/service/elbv2/target_group.go @@ -368,7 +368,7 @@ func resourceTargetGroupCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateTargetGroup(params) // Some partitions may not support tag-on-create - if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if params.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] ELBv2 Target Group (%s) create failed (%s) with tags. Trying create without tags.", groupName, err) params.Tags = nil resp, err = conn.CreateTargetGroup(params) @@ -521,7 +521,7 @@ func resourceTargetGroupCreate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, d.Id(), nil, tags) // if default tags only, log and continue (i.e., should error if explicitly setting tags and they can't be) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] error adding tags after create for ELBv2 Target Group (%s): %s", d.Id(), err) return resourceTargetGroupRead(d, meta) } @@ -778,7 +778,7 @@ func resourceTargetGroupUpdate(d *schema.ResourceData, meta interface{}) error { } // ISO partitions may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to update tags for ELBv2 Target Group %s: %s", d.Id(), err) return resourceTargetGroupRead(d, meta) } @@ -967,7 +967,7 @@ func flattenTargetGroupResource(d *schema.ResourceData, meta interface{}, target tags, err := ListTags(conn, d.Id()) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to list tags for ELBv2 Target Group %s: %s", d.Id(), err) return nil } diff --git a/internal/service/elbv2/target_group_attachment_test.go b/internal/service/elbv2/target_group_attachment_test.go index 0af074d0da5..c6665e3dcb6 100644 --- a/internal/service/elbv2/target_group_attachment_test.go +++ b/internal/service/elbv2/target_group_attachment_test.go @@ -26,7 +26,7 @@ func TestAccELBV2TargetGroupAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckTargetGroupAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupAttachmentTargetIdInstanceConfig(targetGroupName), + Config: testAccTargetGroupAttachmentConfig_idInstance(targetGroupName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupAttachmentExists("aws_lb_target_group_attachment.test"), ), @@ -44,7 +44,7 @@ func TestAccELBV2TargetGroupAttachment_disappears(t *testing.T) { CheckDestroy: testAccCheckTargetGroupAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupAttachmentTargetIdInstanceConfig(targetGroupName), + Config: testAccTargetGroupAttachmentConfig_idInstance(targetGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetGroupAttachmentExists("aws_lb_target_group_attachment.test"), testAccCheckTargetGroupAttachmentDisappears("aws_lb_target_group_attachment.test"), @@ -65,7 +65,7 @@ func TestAccELBV2TargetGroupAttachment_backwardsCompatibility(t *testing.T) { CheckDestroy: testAccCheckTargetGroupAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupAttachmentBackwardsCompatibilityConfig(targetGroupName), + Config: testAccTargetGroupAttachmentConfig_backwardsCompatibility(targetGroupName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupAttachmentExists("aws_alb_target_group_attachment.test"), ), @@ -84,7 +84,7 @@ func TestAccELBV2TargetGroupAttachment_port(t *testing.T) { CheckDestroy: testAccCheckTargetGroupAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupAttachmentPortConfig(targetGroupName), + Config: testAccTargetGroupAttachmentConfig_port(targetGroupName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupAttachmentExists("aws_lb_target_group_attachment.test"), ), @@ -103,7 +103,7 @@ func TestAccELBV2TargetGroupAttachment_ipAddress(t *testing.T) { CheckDestroy: testAccCheckTargetGroupAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupAttachmentTargetIdIPAddressConfig(targetGroupName), + Config: testAccTargetGroupAttachmentConfig_idIPAddress(targetGroupName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupAttachmentExists("aws_lb_target_group_attachment.test"), ), @@ -122,7 +122,7 @@ func TestAccELBV2TargetGroupAttachment_lambda(t *testing.T) { CheckDestroy: testAccCheckTargetGroupAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupAttachmentTargetIdLambdaConfig(targetGroupName), + Config: testAccTargetGroupAttachmentConfig_idLambda(targetGroupName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupAttachmentExists("aws_lb_target_group_attachment.test"), ), @@ -300,7 +300,7 @@ resource "aws_vpc" "test" { ` } -func testAccTargetGroupAttachmentTargetIdInstanceConfig(rName string) string { +func testAccTargetGroupAttachmentConfig_idInstance(rName string) string { return testAccTargetGroupAttachmentInstanceBaseConfig() + fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -316,7 +316,7 @@ resource "aws_lb_target_group_attachment" "test" { `, rName) } -func testAccTargetGroupAttachmentPortConfig(rName string) string { +func testAccTargetGroupAttachmentConfig_port(rName string) string { return testAccTargetGroupAttachmentInstanceBaseConfig() + fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -333,7 +333,7 @@ resource "aws_lb_target_group_attachment" "test" { `, rName) } -func testAccTargetGroupAttachmentBackwardsCompatibilityConfig(rName string) string { +func testAccTargetGroupAttachmentConfig_backwardsCompatibility(rName string) string { return testAccTargetGroupAttachmentInstanceBaseConfig() + fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -350,7 +350,7 @@ resource "aws_alb_target_group_attachment" "test" { `, rName) } -func testAccTargetGroupAttachmentTargetIdIPAddressConfig(rName string) string { +func testAccTargetGroupAttachmentConfig_idIPAddress(rName string) string { return testAccTargetGroupAttachmentInstanceBaseConfig() + fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -368,7 +368,7 @@ resource "aws_lb_target_group_attachment" "test" { `, rName) } -func testAccTargetGroupAttachmentTargetIdLambdaConfig(rName string) string { +func testAccTargetGroupAttachmentConfig_idLambda(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/elbv2/target_group_data_source.go b/internal/service/elbv2/target_group_data_source.go index 8dc06aa858b..852c410b7b7 100644 --- a/internal/service/elbv2/target_group_data_source.go +++ b/internal/service/elbv2/target_group_data_source.go @@ -268,7 +268,7 @@ func dataSourceTargetGroupRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, d.Id()) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to list tags for ELBv2 Target Group %s: %s", d.Id(), err) return nil } diff --git a/internal/service/elbv2/target_group_data_source_test.go b/internal/service/elbv2/target_group_data_source_test.go index 297c7e720a2..7897bbe4a4a 100644 --- a/internal/service/elbv2/target_group_data_source_test.go +++ b/internal/service/elbv2/target_group_data_source_test.go @@ -21,7 +21,7 @@ func TestAccELBV2TargetGroupDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbTargetGroupBasicDataSourceConfig(rName), + Config: testAccTargetGroupDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceNameArn, "name", rName), resource.TestCheckResourceAttrSet(resourceNameArn, "arn"), @@ -81,7 +81,7 @@ func TestAccELBV2TargetGroupDataSource_appCookie(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbTargetGroupAppCookieDataSourceConfig(rName), + Config: testAccTargetGroupDataSourceConfig_appCookie(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceNameArn, "name", rName), resource.TestCheckResourceAttrSet(resourceNameArn, "arn"), @@ -123,7 +123,7 @@ func TestAccELBV2TargetGroupDataSource_backwardsCompatibility(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcclbTargetGroupBackwardsCompatibilityDataSourceConfig(rName), + Config: testAccTargetGroupDataSourceConfig_backwardsCompatibility(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceNameArn, "name", rName), resource.TestCheckResourceAttrSet(resourceNameArn, "arn"), @@ -171,7 +171,7 @@ func TestAccELBV2TargetGroupDataSource_backwardsCompatibility(t *testing.T) { }) } -func testAcclbTargetGroupBasicDataSourceConfig(rName string) string { +func testAccTargetGroupDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_lb_listener" "front_end" { load_balancer_arn = aws_lb.alb_test.id @@ -288,7 +288,7 @@ data "aws_lb_target_group" "alb_tg_test_with_name" { `, rName) } -func testAcclbTargetGroupAppCookieDataSourceConfig(rName string) string { +func testAccTargetGroupDataSourceConfig_appCookie(rName string) string { return fmt.Sprintf(` resource "aws_lb_listener" "front_end" { load_balancer_arn = aws_lb.alb_test.id @@ -407,7 +407,7 @@ data "aws_lb_target_group" "alb_tg_test_with_arn" { `, rName) } -func testAcclbTargetGroupBackwardsCompatibilityDataSourceConfig(rName string) string { +func testAccTargetGroupDataSourceConfig_backwardsCompatibility(rName string) string { return fmt.Sprintf(` resource "aws_alb_listener" "front_end" { load_balancer_arn = aws_alb.alb_test.id diff --git a/internal/service/elbv2/target_group_test.go b/internal/service/elbv2/target_group_test.go index 5b352080aeb..bd161fea47f 100644 --- a/internal/service/elbv2/target_group_test.go +++ b/internal/service/elbv2/target_group_test.go @@ -17,7 +17,7 @@ import ( tfelbv2 "github.com/hashicorp/terraform-provider-aws/internal/service/elbv2" ) -func TestLBTargetGroupCloudwatchSuffixFromARN(t *testing.T) { +func TestLBTargetGroupCloudWatchSuffixFromARN(t *testing.T) { cases := []struct { name string arn *string @@ -48,7 +48,7 @@ func TestLBTargetGroupCloudwatchSuffixFromARN(t *testing.T) { } } -func TestALBTargetGroupCloudwatchSuffixFromARN(t *testing.T) { +func TestALBTargetGroupCloudWatchSuffixFromARN(t *testing.T) { cases := []struct { name string arn *string @@ -91,7 +91,7 @@ func TestAccELBV2TargetGroup_backwardsCompatibility(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupBackwardsCompatibilityConfig(rName), + Config: testAccTargetGroupConfig_backwardsCompatibility(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -134,7 +134,7 @@ func TestAccELBV2TargetGroup_ProtocolVersion_basic(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupConfig_ProtocolVersion(rName), + Config: testAccTargetGroupConfig_protocolVersion(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -179,7 +179,7 @@ func TestAccELBV2TargetGroup_ProtocolVersion_grpcHealthCheck(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupConfig_GRPC_ProtocolVersion(rName), + Config: testAccTargetGroupConfig_grpcProtocolVersion(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &targetGroup1), resource.TestCheckResourceAttr(resourceName, "health_check.#", "1"), @@ -211,7 +211,7 @@ func TestAccELBV2TargetGroup_ProtocolVersion_grpcUpdate(t *testing.T) { ), }, { - Config: testAccTargetGroupConfig_GRPC_ProtocolVersion(rName), + Config: testAccTargetGroupConfig_grpcProtocolVersion(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &targetGroup1), resource.TestCheckResourceAttr(resourceName, "protocol", "HTTP"), @@ -242,7 +242,7 @@ func TestAccELBV2TargetGroup_HealthCheck_tcp(t *testing.T) { ), }, { - Config: testAccTargetGroupConfig_typeTCP_HTTPHealthCheck(rName, "/", 5), + Config: testAccTargetGroupConfig_typeTCPHTTPHealthCheck(rName, "/", 5), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &targetGroup2), testAccCheckTargetGroupRecreated(&targetGroup1, &targetGroup2), @@ -266,7 +266,7 @@ func TestAccELBV2TargetGroup_tls(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupConfig_Protocol_TLS(rName), + Config: testAccTargetGroupConfig_protocolTLS(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &targetGroup1), resource.TestCheckResourceAttr(resourceName, "protocol", "TLS"), @@ -288,7 +288,7 @@ func TestAccELBV2TargetGroup_HealthCheck_tcpHTTPS(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupConfig_typeTCP_HTTPHealthCheck(rName, "/healthz", 2), + Config: testAccTargetGroupConfig_typeTCPHTTPHealthCheck(rName, "/healthz", 2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &confBefore), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -310,7 +310,7 @@ func TestAccELBV2TargetGroup_HealthCheck_tcpHTTPS(t *testing.T) { ), }, { - Config: testAccTargetGroupConfig_typeTCP_HTTPHealthCheck(rName, "/healthz2", 4), + Config: testAccTargetGroupConfig_typeTCPHTTPHealthCheck(rName, "/healthz2", 4), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &confAfter), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -571,7 +571,7 @@ func TestAccELBV2TargetGroup_Defaults_application(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccALB_defaults(rName), + Config: testAccTargetGroupConfig_albDefaults(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -632,19 +632,19 @@ protocol = "TCP" CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccNLB_defaults(rName, healthCheckInvalid1), + Config: testAccTargetGroupConfig_nlbDefaults(rName, healthCheckInvalid1), ExpectError: regexp.MustCompile("health_check.path is not supported for target_groups with TCP protocol"), }, { - Config: testAccNLB_defaults(rName, healthCheckInvalid2), + Config: testAccTargetGroupConfig_nlbDefaults(rName, healthCheckInvalid2), ExpectError: regexp.MustCompile("health_check.matcher is not supported for target_groups with TCP protocol"), }, { - Config: testAccNLB_defaults(rName, healthCheckInvalid3), + Config: testAccTargetGroupConfig_nlbDefaults(rName, healthCheckInvalid3), ExpectError: regexp.MustCompile("health_check.timeout is not supported for target_groups with TCP protocol"), }, { - Config: testAccNLB_defaults(rName, healthCheckValid), + Config: testAccTargetGroupConfig_nlbDefaults(rName, healthCheckValid), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -681,7 +681,7 @@ func TestAccELBV2TargetGroup_HealthCheck_enable(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupConfig_withoutHealthcheck(rName), + Config: testAccTargetGroupConfig_noHealthcheck(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -839,7 +839,7 @@ func TestAccELBV2TargetGroup_networkLB_TargetGroupWithConnectionTermination(t *t ), }, { - Config: testAccTargetGroupConfig_typeTCP_withConnectionTermination(rName), + Config: testAccTargetGroupConfig_typeTCPConnectionTermination(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &confAfter), resource.TestCheckResourceAttr(resourceName, "connection_termination", "true"), @@ -868,7 +868,7 @@ func TestAccELBV2TargetGroup_NetworkLB_targetGroupWithProxy(t *testing.T) { ), }, { - Config: testAccTargetGroupConfig_typeTCP_withProxyProtocol(rName), + Config: testAccTargetGroupConfig_typeTCPProxyProtocol(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &confAfter), resource.TestCheckResourceAttr(resourceName, "proxy_protocol_v2", "true"), @@ -919,7 +919,7 @@ func TestAccELBV2TargetGroup_Geneve_basic(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupProtocolGeneveConfig(rName), + Config: testAccTargetGroupConfig_protocolGeneve(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "port", "6081"), @@ -953,7 +953,7 @@ func TestAccELBV2TargetGroup_Geneve_notSticky(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupProtocolGeneveConfig(rName), + Config: testAccTargetGroupConfig_protocolGeneve(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "port", "6081"), @@ -961,7 +961,7 @@ func TestAccELBV2TargetGroup_Geneve_notSticky(t *testing.T) { ), }, { - Config: testAccTargetGroupProtocolGeneveHealthConfig(rName), + Config: testAccTargetGroupConfig_protocolGeneveHealth(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "port", "6081"), @@ -1204,7 +1204,7 @@ func TestAccELBV2TargetGroup_tags(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupTags1Config(rName, "key1", "value1"), + Config: testAccTargetGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1212,7 +1212,7 @@ func TestAccELBV2TargetGroup_tags(t *testing.T) { ), }, { - Config: testAccTargetGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTargetGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1221,7 +1221,7 @@ func TestAccELBV2TargetGroup_tags(t *testing.T) { ), }, { - Config: testAccTargetGroupTags1Config(rName, "key2", "value2"), + Config: testAccTargetGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1483,7 +1483,7 @@ func TestAccELBV2TargetGroup_HealthCheck_without(t *testing.T) { CheckDestroy: testAccCheckTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetGroupConfig_withoutHealthcheck(rName), + Config: testAccTargetGroupConfig_noHealthcheck(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -1508,7 +1508,7 @@ func TestAccELBV2TargetGroup_ALBAlias_basic(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_basic(rName), + Config: testAccTargetGroupConfig_albBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -1553,14 +1553,14 @@ func TestAccELBV2TargetGroup_ALBAlias_changeNameForceNew(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_basic(rName), + Config: testAccTargetGroupConfig_albBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", rName), ), }, { - Config: testAccATargetGroupConfig_basic(rNameAfter), + Config: testAccTargetGroupConfig_albBasic(rNameAfter), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", rNameAfter), @@ -1582,14 +1582,14 @@ func TestAccELBV2TargetGroup_ALBAlias_changePortForceNew(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_basic(rName), + Config: testAccTargetGroupConfig_albBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "port", "443"), ), }, { - Config: testAccATargetGroupConfig_updatedPort(rName), + Config: testAccTargetGroupConfig_albUpdatedPort(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "port", "442"), @@ -1611,14 +1611,14 @@ func TestAccELBV2TargetGroup_ALBAlias_changeProtocolForceNew(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_basic(rName), + Config: testAccTargetGroupConfig_albBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "protocol", "HTTPS"), ), }, { - Config: testAccATargetGroupConfig_updatedProtocol(rName), + Config: testAccTargetGroupConfig_albUpdatedProtocol(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "protocol", "HTTP"), @@ -1640,13 +1640,13 @@ func TestAccELBV2TargetGroup_ALBAlias_changeVPCForceNew(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_basic(rName), + Config: testAccTargetGroupConfig_albBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &before), ), }, { - Config: testAccATargetGroupConfig_updatedVPC(rName), + Config: testAccTargetGroupConfig_albUpdatedVPC(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &after), ), @@ -1667,7 +1667,7 @@ func TestAccELBV2TargetGroup_ALBAlias_generatedName(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_generatedName(rName), + Config: testAccTargetGroupConfig_albGeneratedName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), ), @@ -1688,7 +1688,7 @@ func TestAccELBV2TargetGroup_ALBAlias_lambda(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_lambda(rName), + Config: testAccTargetGroupConfig_albLambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &targetGroup1), resource.TestCheckResourceAttr(resourceName, "lambda_multi_value_headers_enabled", "false"), @@ -1723,7 +1723,7 @@ func TestAccELBV2TargetGroup_ALBAlias_lambdaMultiValueHeadersEnabled(t *testing. CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_lambdaMultiValueHeadersEnabled(rName, true), + Config: testAccTargetGroupConfig_albLambdaMultiValueHeadersEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &targetGroup1), resource.TestCheckResourceAttr(resourceName, "lambda_multi_value_headers_enabled", "true"), @@ -1743,7 +1743,7 @@ func TestAccELBV2TargetGroup_ALBAlias_lambdaMultiValueHeadersEnabled(t *testing. }, }, { - Config: testAccATargetGroupConfig_lambdaMultiValueHeadersEnabled(rName, false), + Config: testAccTargetGroupConfig_albLambdaMultiValueHeadersEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &targetGroup1), resource.TestCheckResourceAttr(resourceName, "lambda_multi_value_headers_enabled", "false"), @@ -1751,7 +1751,7 @@ func TestAccELBV2TargetGroup_ALBAlias_lambdaMultiValueHeadersEnabled(t *testing. ), }, { - Config: testAccATargetGroupConfig_lambdaMultiValueHeadersEnabled(rName, true), + Config: testAccTargetGroupConfig_albLambdaMultiValueHeadersEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &targetGroup1), resource.TestCheckResourceAttr(resourceName, "lambda_multi_value_headers_enabled", "true"), @@ -1772,15 +1772,15 @@ func TestAccELBV2TargetGroup_ALBAlias_missingPortProtocolVPC(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_missing_port(rName), + Config: testAccTargetGroupConfig_albMissingPort(rName), ExpectError: regexp.MustCompile(`port should be set when target type is`), }, { - Config: testAccATargetGroupConfig_missing_protocol(rName), + Config: testAccTargetGroupConfig_albMissingProtocol(rName), ExpectError: regexp.MustCompile(`protocol should be set when target type is`), }, { - Config: testAccATargetGroupConfig_missing_vpc(rName), + Config: testAccTargetGroupConfig_albMissingVPC(rName), ExpectError: regexp.MustCompile(`vpc_id should be set when target type is`), }, }, @@ -1799,7 +1799,7 @@ func TestAccELBV2TargetGroup_ALBAlias_namePrefix(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_namePrefix(rName), + Config: testAccTargetGroupConfig_albNamePrefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile("^tf-")), @@ -1821,14 +1821,14 @@ func TestAccELBV2TargetGroup_ALBAlias_setAndUpdateSlowStart(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_updateSlowStart(rName, 30), + Config: testAccTargetGroupConfig_albUpdateSlowStart(rName, 30), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "slow_start", "30"), ), }, { - Config: testAccATargetGroupConfig_updateSlowStart(rName, 60), + Config: testAccTargetGroupConfig_albUpdateSlowStart(rName, 60), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "slow_start", "60"), @@ -1850,7 +1850,7 @@ func TestAccELBV2TargetGroup_ALBAlias_tags(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_basic(rName), + Config: testAccTargetGroupConfig_albBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1858,7 +1858,7 @@ func TestAccELBV2TargetGroup_ALBAlias_tags(t *testing.T) { ), }, { - Config: testAccATargetGroupConfig_updateTags(rName), + Config: testAccTargetGroupConfig_albUpdateTags(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1882,7 +1882,7 @@ func TestAccELBV2TargetGroup_ALBAlias_updateHealthCheck(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_basic(rName), + Config: testAccTargetGroupConfig_albBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -1906,7 +1906,7 @@ func TestAccELBV2TargetGroup_ALBAlias_updateHealthCheck(t *testing.T) { ), }, { - Config: testAccATargetGroupConfig_updateHealthCheck(rName), + Config: testAccTargetGroupConfig_albUpdateHealthCheck(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -1945,7 +1945,7 @@ func TestAccELBV2TargetGroup_ALBAlias_updateLoadBalancingAlgorithmType(t *testin CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_loadBalancingAlgorithm(rName, false, ""), + Config: testAccTargetGroupConfig_albLoadBalancingAlgorithm(rName, false, ""), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -1954,7 +1954,7 @@ func TestAccELBV2TargetGroup_ALBAlias_updateLoadBalancingAlgorithmType(t *testin ), }, { - Config: testAccATargetGroupConfig_loadBalancingAlgorithm(rName, true, "round_robin"), + Config: testAccTargetGroupConfig_albLoadBalancingAlgorithm(rName, true, "round_robin"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -1963,7 +1963,7 @@ func TestAccELBV2TargetGroup_ALBAlias_updateLoadBalancingAlgorithmType(t *testin ), }, { - Config: testAccATargetGroupConfig_loadBalancingAlgorithm(rName, true, "least_outstanding_requests"), + Config: testAccTargetGroupConfig_albLoadBalancingAlgorithm(rName, true, "least_outstanding_requests"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -1987,7 +1987,7 @@ func TestAccELBV2TargetGroup_ALBAlias_updateStickinessEnabled(t *testing.T) { CheckDestroy: testAccCheckATargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccATargetGroupConfig_stickiness(rName, false, false), + Config: testAccTargetGroupConfig_albStickiness(rName, false, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -2008,7 +2008,7 @@ func TestAccELBV2TargetGroup_ALBAlias_updateStickinessEnabled(t *testing.T) { ), }, { - Config: testAccATargetGroupConfig_stickiness(rName, true, true), + Config: testAccTargetGroupConfig_albStickiness(rName, true, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -2033,7 +2033,7 @@ func TestAccELBV2TargetGroup_ALBAlias_updateStickinessEnabled(t *testing.T) { ), }, { - Config: testAccATargetGroupConfig_stickiness(rName, true, false), + Config: testAccTargetGroupConfig_albStickiness(rName, true, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckATargetGroupExists(resourceName, &conf), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -2061,7 +2061,7 @@ func TestAccELBV2TargetGroup_ALBAlias_updateStickinessEnabled(t *testing.T) { }) } -func testAccALB_defaults(rName string) string { +func testAccTargetGroupConfig_albDefaults(rName string) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -2102,7 +2102,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccTargetGroupBackwardsCompatibilityConfig(rName string) string { +func testAccTargetGroupConfig_backwardsCompatibility(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -2144,7 +2144,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccTargetGroupProtocolGeneveConfig(rName string) string { +func testAccTargetGroupConfig_protocolGeneve(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.10.0/25" @@ -2168,7 +2168,7 @@ resource "aws_lb_target_group" "test" { `, rName) } -func testAccTargetGroupTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccTargetGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -2210,7 +2210,7 @@ resource "aws_vpc" "test" { `, rName, tagKey1, tagValue1) } -func testAccTargetGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTargetGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -2253,7 +2253,7 @@ resource "aws_vpc" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccTargetGroupConfig_GRPC_ProtocolVersion(rName string) string { +func testAccTargetGroupConfig_grpcProtocolVersion(rName string) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -2303,7 +2303,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccTargetGroupConfig_ProtocolVersion(rName string) string { +func testAccTargetGroupConfig_protocolVersion(rName string) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -2346,7 +2346,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccTargetGroupConfig_Protocol_TLS(rName string) string { +func testAccTargetGroupConfig_protocolTLS(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -2793,7 +2793,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccTargetGroupConfig_typeTCP_HTTPHealthCheck(rName, path string, threshold int) string { +func testAccTargetGroupConfig_typeTCPHTTPHealthCheck(rName, path string, threshold int) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = "%[1]s" @@ -2827,7 +2827,7 @@ resource "aws_vpc" "test" { `, rName, threshold, path) } -func testAccTargetGroupConfig_typeTCP_withProxyProtocol(rName string) string { +func testAccTargetGroupConfig_typeTCPProxyProtocol(rName string) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -2861,7 +2861,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccTargetGroupConfig_typeTCP_withConnectionTermination(rName string) string { +func testAccTargetGroupConfig_typeTCPConnectionTermination(rName string) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -3063,7 +3063,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccTargetGroupConfig_withoutHealthcheck(rName string) string { +func testAccTargetGroupConfig_noHealthcheck(rName string) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -3072,7 +3072,7 @@ resource "aws_lb_target_group" "test" { `, rName) } -func testAccTargetGroupProtocolGeneveHealthConfig(rName string) string { +func testAccTargetGroupConfig_protocolGeneveHealth(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.10.10.0/25" @@ -3177,7 +3177,7 @@ func testAccCheckTargetGroupRecreated(i, j *elbv2.TargetGroup) resource.TestChec } } -func testAccNLB_defaults(rName, healthCheckBlock string) string { +func testAccTargetGroupConfig_nlbDefaults(rName, healthCheckBlock string) string { return fmt.Sprintf(` resource "aws_lb_target_group" "test" { name = %[1]q @@ -3207,7 +3207,7 @@ resource "aws_vpc" "test" { `, rName, healthCheckBlock) } -func testAccATargetGroupConfig_basic(rName string) string { +func testAccTargetGroupConfig_albBasic(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3247,7 +3247,7 @@ resource "aws_vpc" "test" { }`, rName) } -func testAccATargetGroupConfig_generatedName(rName string) string { +func testAccTargetGroupConfig_albGeneratedName(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { port = 80 @@ -3273,7 +3273,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccATargetGroupConfig_lambda(rName string) string { +func testAccTargetGroupConfig_albLambda(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3281,7 +3281,7 @@ resource "aws_alb_target_group" "test" { }`, rName) } -func testAccATargetGroupConfig_lambdaMultiValueHeadersEnabled(rName string, lambdaMultiValueHadersEnabled bool) string { +func testAccTargetGroupConfig_albLambdaMultiValueHeadersEnabled(rName string, lambdaMultiValueHadersEnabled bool) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { lambda_multi_value_headers_enabled = %[1]t @@ -3291,7 +3291,7 @@ resource "aws_alb_target_group" "test" { `, lambdaMultiValueHadersEnabled, rName) } -func testAccATargetGroupConfig_loadBalancingAlgorithm(rName string, nonDefault bool, algoType string) string { +func testAccTargetGroupConfig_albLoadBalancingAlgorithm(rName string, nonDefault bool, algoType string) string { var algoTypeParam string if nonDefault { @@ -3317,7 +3317,7 @@ resource "aws_vpc" "test" { }`, rName, algoTypeParam) } -func testAccATargetGroupConfig_missing_port(rName string) string { +func testAccTargetGroupConfig_albMissingPort(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3330,7 +3330,7 @@ resource "aws_vpc" "test" { }`, rName) } -func testAccATargetGroupConfig_missing_protocol(rName string) string { +func testAccTargetGroupConfig_albMissingProtocol(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3343,7 +3343,7 @@ resource "aws_vpc" "test" { }`, rName) } -func testAccATargetGroupConfig_missing_vpc(rName string) string { +func testAccTargetGroupConfig_albMissingVPC(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3353,7 +3353,7 @@ resource "aws_alb_target_group" "test" { `, rName) } -func testAccATargetGroupConfig_namePrefix(rName string) string { +func testAccTargetGroupConfig_albNamePrefix(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name_prefix = "tf-" @@ -3371,7 +3371,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccATargetGroupConfig_stickiness(rName string, addStickinessBlock bool, enabled bool) string { +func testAccTargetGroupConfig_albStickiness(rName string, addStickinessBlock bool, enabled bool) string { var stickinessBlock string if addStickinessBlock { @@ -3415,7 +3415,7 @@ resource "aws_vpc" "test" { }`, rName, stickinessBlock) } -func testAccATargetGroupConfig_updateHealthCheck(rName string) string { +func testAccTargetGroupConfig_albUpdateHealthCheck(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3451,7 +3451,7 @@ resource "aws_vpc" "test" { }`, rName) } -func testAccATargetGroupConfig_updateSlowStart(rName string, slowStartDuration int) string { +func testAccTargetGroupConfig_albUpdateSlowStart(rName string, slowStartDuration int) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3492,7 +3492,7 @@ resource "aws_vpc" "test" { }`, rName, slowStartDuration) } -func testAccATargetGroupConfig_updateTags(rName string) string { +func testAccTargetGroupConfig_albUpdateTags(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3533,7 +3533,7 @@ resource "aws_vpc" "test" { }`, rName) } -func testAccATargetGroupConfig_updatedPort(rName string) string { +func testAccTargetGroupConfig_albUpdatedPort(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3573,7 +3573,7 @@ resource "aws_vpc" "test" { }`, rName) } -func testAccATargetGroupConfig_updatedProtocol(rName string) string { +func testAccTargetGroupConfig_albUpdatedProtocol(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q @@ -3621,7 +3621,7 @@ resource "aws_vpc" "test" { }`, rName) } -func testAccATargetGroupConfig_updatedVPC(rName string) string { +func testAccTargetGroupConfig_albUpdatedVPC(rName string) string { return fmt.Sprintf(` resource "aws_alb_target_group" "test" { name = %[1]q diff --git a/internal/service/emr/cluster.go b/internal/service/emr/cluster.go index ba835155152..f57b436d8e4 100644 --- a/internal/service/emr/cluster.go +++ b/internal/service/emr/cluster.go @@ -764,7 +764,7 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { instanceGroup.Market = aws.String(emr.MarketTypeSpot) } - expandEbsConfig(m, instanceGroup) + expandEBSConfig(m, instanceGroup) instanceConfig.InstanceGroups = append(instanceConfig.InstanceGroups, instanceGroup) } @@ -795,7 +795,7 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { instanceGroup.Market = aws.String(emr.MarketTypeSpot) } - expandEbsConfig(m, instanceGroup) + expandEBSConfig(m, instanceGroup) instanceConfig.InstanceGroups = append(instanceConfig.InstanceGroups, instanceGroup) } @@ -932,7 +932,7 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { if err != nil { return fmt.Errorf("configurations_json contains an invalid JSON: %v", err) } - params.Configurations, err = expandConfigurationJson(info) + params.Configurations, err = expandConfigurationJSON(info) if err != nil { return fmt.Errorf("Error reading EMR configurations_json: %w", err) } @@ -1095,7 +1095,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { } if _, ok := d.GetOk("configurations_json"); ok { - configOut, err := flattenConfigurationJson(cluster.Configurations) + configOut, err := flattenConfigurationJSON(cluster.Configurations) if err != nil { return fmt.Errorf("Error reading EMR cluster configurations: %w", err) } @@ -1104,7 +1104,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { } } - if err := d.Set("ec2_attributes", flattenEc2Attributes(cluster.Ec2InstanceAttributes)); err != nil { + if err := d.Set("ec2_attributes", flattenEC2InstanceAttributes(cluster.Ec2InstanceAttributes)); err != nil { return fmt.Errorf("error setting EMR Ec2 Attributes: %w", err) } @@ -1438,7 +1438,7 @@ func flattenApplications(apps []*emr.Application) []interface{} { return appOut } -func flattenEc2Attributes(ia *emr.Ec2InstanceAttributes) []map[string]interface{} { +func flattenEC2InstanceAttributes(ia *emr.Ec2InstanceAttributes) []map[string]interface{} { attrs := map[string]interface{}{} result := make([]map[string]interface{}, 0) @@ -1800,7 +1800,7 @@ func expandStepConfigs(l []interface{}) []*emr.StepConfig { return stepConfigs } -func expandEbsConfig(configAttributes map[string]interface{}, config *emr.InstanceGroupConfig) { +func expandEBSConfig(configAttributes map[string]interface{}, config *emr.InstanceGroupConfig) { if rawEbsConfigs, ok := configAttributes["ebs_config"]; ok { ebsConfig := &emr.EbsConfiguration{} @@ -1825,7 +1825,7 @@ func expandEbsConfig(configAttributes map[string]interface{}, config *emr.Instan } } -func expandConfigurationJson(input string) ([]*emr.Configuration, error) { +func expandConfigurationJSON(input string) ([]*emr.Configuration, error) { configsOut := []*emr.Configuration{} err := json.Unmarshal([]byte(input), &configsOut) if err != nil { @@ -1836,7 +1836,7 @@ func expandConfigurationJson(input string) ([]*emr.Configuration, error) { return configsOut, nil } -func flattenConfigurationJson(config []*emr.Configuration) (string, error) { +func flattenConfigurationJSON(config []*emr.Configuration) (string, error) { out, err := jsonutil.BuildJSON(config) if err != nil { return "", err @@ -1847,15 +1847,15 @@ func flattenConfigurationJson(config []*emr.Configuration) (string, error) { func expandConfigures(input string) []*emr.Configuration { configsOut := []*emr.Configuration{} if strings.HasPrefix(input, "http") { - if err := readHttpJson(input, &configsOut); err != nil { + if err := readHTTPJSON(input, &configsOut); err != nil { log.Printf("[ERR] Error reading HTTP JSON: %s", err) } } else if strings.HasSuffix(input, ".json") { - if err := readLocalJson(input, &configsOut); err != nil { + if err := readLocalJSON(input, &configsOut); err != nil { log.Printf("[ERR] Error reading local JSON: %s", err) } } else { - if err := readBodyJson(input, &configsOut); err != nil { + if err := readBodyJSON(input, &configsOut); err != nil { log.Printf("[ERR] Error reading body JSON: %s", err) } } @@ -1864,7 +1864,7 @@ func expandConfigures(input string) []*emr.Configuration { return configsOut } -func readHttpJson(url string, target interface{}) error { +func readHTTPJSON(url string, target interface{}) error { r, err := http.Get(url) if err != nil { return err @@ -1874,7 +1874,7 @@ func readHttpJson(url string, target interface{}) error { return json.NewDecoder(r.Body).Decode(target) } -func readLocalJson(localFile string, target interface{}) error { +func readLocalJSON(localFile string, target interface{}) error { file, e := os.ReadFile(localFile) if e != nil { log.Printf("[ERROR] %s", e) @@ -1884,7 +1884,7 @@ func readLocalJson(localFile string, target interface{}) error { return json.Unmarshal(file, target) } -func readBodyJson(body string, target interface{}) error { +func readBodyJSON(body string, target interface{}) error { log.Printf("[DEBUG] Raw Body %s\n", body) err := json.Unmarshal([]byte(body), target) if err != nil { @@ -2080,7 +2080,7 @@ func flattenSpotSpecification(spotSpecification *emr.SpotProvisioningSpecificati return []interface{}{m} } -func expandEbsConfiguration(ebsConfigurations []interface{}) *emr.EbsConfiguration { +func expandEBSConfiguration(ebsConfigurations []interface{}) *emr.EbsConfiguration { ebsConfig := &emr.EbsConfiguration{} ebsConfigs := make([]*emr.EbsBlockDeviceConfig, 0) for _, ebsConfiguration := range ebsConfigurations { @@ -2130,7 +2130,7 @@ func expandInstanceTypeConfigs(instanceTypeConfigs []interface{}) []*emr.Instanc } if v, ok := configAttributes["ebs_config"].(*schema.Set); ok && v.Len() == 1 { - config.EbsConfiguration = expandEbsConfiguration(v.List()) + config.EbsConfiguration = expandEBSConfiguration(v.List()) } configsOut = append(configsOut, config) diff --git a/internal/service/emr/cluster_test.go b/internal/service/emr/cluster_test.go index 4a6a5d8f6c0..2cc99e6a692 100644 --- a/internal/service/emr/cluster_test.go +++ b/internal/service/emr/cluster_test.go @@ -31,7 +31,7 @@ func TestAccEMRCluster_basic(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -86,7 +86,7 @@ func TestAccEMRCluster_autoTerminationPolicy(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterAutoTerminationConfig(rName, 10000), + Config: testAccClusterConfig_autoTermination(rName, 10000), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "auto_termination_policy.#", "1"), @@ -104,7 +104,7 @@ func TestAccEMRCluster_autoTerminationPolicy(t *testing.T) { }, }, { - Config: testAccClusterAutoTerminationConfig(rName, 20000), + Config: testAccClusterConfig_autoTermination(rName, 20000), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "auto_termination_policy.#", "1"), @@ -112,14 +112,14 @@ func TestAccEMRCluster_autoTerminationPolicy(t *testing.T) { ), }, { - Config: testAccClusterNoAutoTerminationConfig(rName), + Config: testAccClusterConfig_noAutoTermination(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "auto_termination_policy.#", "0"), ), }, { - Config: testAccClusterAutoTerminationConfig(rName, 20000), + Config: testAccClusterConfig_autoTermination(rName, 20000), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "auto_termination_policy.#", "1"), @@ -149,7 +149,7 @@ func TestAccEMRCluster_additionalInfo(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterAdditionalInfoConfig(rName), + Config: testAccClusterConfig_additionalInfo(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "scale_down_behavior", "TERMINATE_AT_TASK_COMPLETION"), @@ -184,7 +184,7 @@ func TestAccEMRCluster_disappears(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), acctest.CheckResourceDisappears(acctest.Provider, tfemr.ResourceCluster(), resourceName), @@ -208,7 +208,7 @@ func TestAccEMRCluster_sJSON(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfigurationsJSONConfig(rName), + Config: testAccClusterConfig_configurationsJSON(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestMatchResourceAttr(resourceName, "configurations_json", @@ -307,7 +307,7 @@ func TestAccEMRCluster_CoreInstanceGroup_autoScalingPolicy(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCoreInstanceGroupAutoScalingPolicyConfig(rName, autoscalingPolicy1), + Config: testAccClusterConfig_coreInstanceGroupAutoScalingPolicy(rName, autoscalingPolicy1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "core_instance_group.#", "1"), @@ -325,7 +325,7 @@ func TestAccEMRCluster_CoreInstanceGroup_autoScalingPolicy(t *testing.T) { }, }, { - Config: testAccClusterCoreInstanceGroupAutoScalingPolicyConfig(rName, autoscalingPolicy2), + Config: testAccClusterConfig_coreInstanceGroupAutoScalingPolicy(rName, autoscalingPolicy2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -334,7 +334,7 @@ func TestAccEMRCluster_CoreInstanceGroup_autoScalingPolicy(t *testing.T) { ), }, { - Config: testAccClusterCoreInstanceGroupAutoScalingPolicyRemovedConfig(rName), + Config: testAccClusterConfig_coreInstanceGroupAutoScalingPolicyRemoved(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster3), testAccCheckClusterNotRecreated(&cluster2, &cluster3), @@ -358,7 +358,7 @@ func TestAccEMRCluster_CoreInstanceGroup_bidPrice(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCoreInstanceGroupBidPriceConfig(rName, "0.50"), + Config: testAccClusterConfig_coreInstanceGroupBidPrice(rName, "0.50"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "core_instance_group.#", "1"), @@ -376,7 +376,7 @@ func TestAccEMRCluster_CoreInstanceGroup_bidPrice(t *testing.T) { }, }, { - Config: testAccClusterCoreInstanceGroupBidPriceConfig(rName, "0.51"), + Config: testAccClusterConfig_coreInstanceGroupBidPrice(rName, "0.51"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -400,7 +400,7 @@ func TestAccEMRCluster_CoreInstanceGroup_instanceCount(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCoreInstanceGroupInstanceCountConfig(rName, 2), + Config: testAccClusterConfig_coreInstanceGroupInstanceCount(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "core_instance_group.#", "1"), @@ -418,7 +418,7 @@ func TestAccEMRCluster_CoreInstanceGroup_instanceCount(t *testing.T) { }, }, { - Config: testAccClusterCoreInstanceGroupInstanceCountConfig(rName, 1), + Config: testAccClusterConfig_coreInstanceGroupInstanceCount(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -427,7 +427,7 @@ func TestAccEMRCluster_CoreInstanceGroup_instanceCount(t *testing.T) { ), }, { - Config: testAccClusterCoreInstanceGroupInstanceCountConfig(rName, 2), + Config: testAccClusterConfig_coreInstanceGroupInstanceCount(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster3), testAccCheckClusterNotRecreated(&cluster2, &cluster3), @@ -451,7 +451,7 @@ func TestAccEMRCluster_CoreInstanceGroup_instanceType(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCoreInstanceGroupInstanceTypeConfig(rName, "m4.large"), + Config: testAccClusterConfig_coreInstanceGroupInstanceType(rName, "m4.large"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "core_instance_group.#", "1"), @@ -469,7 +469,7 @@ func TestAccEMRCluster_CoreInstanceGroup_instanceType(t *testing.T) { }, }, { - Config: testAccClusterCoreInstanceGroupInstanceTypeConfig(rName, "m4.xlarge"), + Config: testAccClusterConfig_coreInstanceGroupInstanceType(rName, "m4.xlarge"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -493,7 +493,7 @@ func TestAccEMRCluster_CoreInstanceGroup_name(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCoreInstanceGroupNameConfig(rName, "name1"), + Config: testAccClusterConfig_coreInstanceGroupName(rName, "name1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "core_instance_group.#", "1"), @@ -511,7 +511,7 @@ func TestAccEMRCluster_CoreInstanceGroup_name(t *testing.T) { }, }, { - Config: testAccClusterCoreInstanceGroupNameConfig(rName, "name2"), + Config: testAccClusterConfig_coreInstanceGroupName(rName, "name2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -538,14 +538,14 @@ func TestAccEMRCluster_EC2Attributes_defaultManagedSecurityGroups(t *testing.T) CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEC2AttributesDefaultManagedSecurityGroupsConfig(rName), + Config: testAccClusterConfig_ec2AttributesDefaultManagedSecurityGroups(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), acctest.CheckVPCExists(vpcResourceName, &vpc), ), }, { - Config: testAccClusterEC2AttributesDefaultManagedSecurityGroupsConfig(rName), + Config: testAccClusterConfig_ec2AttributesDefaultManagedSecurityGroups(rName), Destroy: true, ExpectError: regexp.MustCompile(`DependencyViolation`), }, @@ -559,7 +559,7 @@ func TestAccEMRCluster_EC2Attributes_defaultManagedSecurityGroups(t *testing.T) t.Fatal(err) } }, - Config: testAccClusterEC2AttributesDefaultManagedSecurityGroupsConfig(rName), + Config: testAccClusterConfig_ec2AttributesDefaultManagedSecurityGroups(rName), Destroy: true, }, }, @@ -579,7 +579,7 @@ func TestAccEMRCluster_Kerberos_clusterDedicatedKdc(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Kerberos_ClusterDedicatedKdc(rName, password), + Config: testAccClusterConfig_kerberosDedicatedKdc(rName, password), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "kerberos_attributes.#", "1"), @@ -614,7 +614,7 @@ func TestAccEMRCluster_MasterInstanceGroup_bidPrice(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterMasterInstanceGroupBidPriceConfig(rName, "0.50"), + Config: testAccClusterConfig_masterInstanceGroupBidPrice(rName, "0.50"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "master_instance_group.#", "1"), @@ -632,7 +632,7 @@ func TestAccEMRCluster_MasterInstanceGroup_bidPrice(t *testing.T) { }, }, { - Config: testAccClusterMasterInstanceGroupBidPriceConfig(rName, "0.51"), + Config: testAccClusterConfig_masterInstanceGroupBidPrice(rName, "0.51"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -656,7 +656,7 @@ func TestAccEMRCluster_MasterInstanceGroup_instanceCount(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterMasterInstanceGroupInstanceCountConfig(rName, 3), + Config: testAccClusterConfig_masterInstanceGroupInstanceCount(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "master_instance_group.#", "1"), @@ -674,7 +674,7 @@ func TestAccEMRCluster_MasterInstanceGroup_instanceCount(t *testing.T) { }, }, { - Config: testAccClusterMasterInstanceGroupInstanceCountConfig(rName, 1), + Config: testAccClusterConfig_masterInstanceGroupInstanceCount(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -698,7 +698,7 @@ func TestAccEMRCluster_MasterInstanceGroup_instanceType(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterMasterInstanceGroupInstanceTypeConfig(rName, "m4.large"), + Config: testAccClusterConfig_masterInstanceGroupInstanceType(rName, "m4.large"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "master_instance_group.#", "1"), @@ -716,7 +716,7 @@ func TestAccEMRCluster_MasterInstanceGroup_instanceType(t *testing.T) { }, }, { - Config: testAccClusterMasterInstanceGroupInstanceTypeConfig(rName, "m4.xlarge"), + Config: testAccClusterConfig_masterInstanceGroupInstanceType(rName, "m4.xlarge"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -740,7 +740,7 @@ func TestAccEMRCluster_MasterInstanceGroup_name(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterMasterInstanceGroupNameConfig(rName, "name1"), + Config: testAccClusterConfig_masterInstanceGroupName(rName, "name1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "master_instance_group.#", "1"), @@ -758,7 +758,7 @@ func TestAccEMRCluster_MasterInstanceGroup_name(t *testing.T) { }, }, { - Config: testAccClusterMasterInstanceGroupNameConfig(rName, "name2"), + Config: testAccClusterConfig_masterInstanceGroupName(rName, "name2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -782,7 +782,7 @@ func TestAccEMRCluster_security(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SecurityConfiguration(rName), + Config: testAccClusterConfig_securityConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttrPair(resourceName, "security_configuration", "aws_emr_security_configuration.test", "name"), @@ -814,7 +814,7 @@ func TestAccEMRCluster_Step_basic(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Step_Single(rName), + Config: testAccClusterConfig_stepSingle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "step.#", "1"), @@ -852,7 +852,7 @@ func TestAccEMRCluster_Step_mode(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Step_Single(rName), + Config: testAccClusterConfig_stepSingle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "step.#", "1"), @@ -869,7 +869,7 @@ func TestAccEMRCluster_Step_mode(t *testing.T) { }, }, { - Config: testAccClusterConfig_Step_NoBlocks(rName), + Config: testAccClusterConfig_stepNoBlocks(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), resource.TestCheckResourceAttr(resourceName, "step.#", "1"), @@ -886,7 +886,7 @@ func TestAccEMRCluster_Step_mode(t *testing.T) { }, }, { - Config: testAccClusterConfig_Step_Zeroed(rName), + Config: testAccClusterConfig_stepZeroed(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster3), resource.TestCheckResourceAttr(resourceName, "step.#", "0"), @@ -918,7 +918,7 @@ func TestAccEMRCluster_Step_multiple(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Step_Multiple(rName), + Config: testAccClusterConfig_stepMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "step.#", "2"), @@ -960,7 +960,7 @@ func TestAccEMRCluster_Step_multiple_listStates(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Step_Multiple_ListStates(rName), + Config: testAccClusterConfig_stepMultipleListStates(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "step.#", "2"), @@ -1103,14 +1103,14 @@ func TestAccEMRCluster_terminationProtected(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterTerminationPolicyConfig(rName, "false"), + Config: testAccClusterConfig_terminationPolicy(rName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "termination_protection", "false"), ), }, { - Config: testAccClusterTerminationPolicyConfig(rName, "true"), + Config: testAccClusterConfig_terminationPolicy(rName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "termination_protection", "true"), @@ -1128,7 +1128,7 @@ func TestAccEMRCluster_terminationProtected(t *testing.T) { }, { //Need to turn off termination_protection to allow the job to be deleted - Config: testAccClusterTerminationPolicyConfig(rName, "false"), + Config: testAccClusterConfig_terminationPolicy(rName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "termination_protection", "false"), @@ -1192,7 +1192,7 @@ func TestAccEMRCluster_visibleToAllUsers(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "visible_to_all_users", "true"), @@ -1209,7 +1209,7 @@ func TestAccEMRCluster_visibleToAllUsers(t *testing.T) { }, }, { - Config: testAccClusterVisibleToAllUsersUpdatedConfig(rName), + Config: testAccClusterConfig_visibleToAllUsersUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "visible_to_all_users", "false"), @@ -1242,7 +1242,7 @@ func TestAccEMRCluster_s3Logging(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterS3LoggingConfig(rName), + Config: testAccClusterConfig_s3Logging(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "log_uri", bucketName), @@ -1275,7 +1275,7 @@ func TestAccEMRCluster_s3LogEncryption(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterS3EncryptionConfig(rName), + Config: testAccClusterConfig_s3Encryption(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "log_uri", bucketName), @@ -1308,7 +1308,7 @@ func TestAccEMRCluster_tags(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "4"), @@ -1318,7 +1318,7 @@ func TestAccEMRCluster_tags(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tags.name", "name-env")), }, { - Config: testAccClusterUpdatedTagsConfig(rName), + Config: testAccClusterConfig_updatedTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -1353,14 +1353,14 @@ func TestAccEMRCluster_RootVolume_size(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "ebs_root_volume_size", "21"), ), }, { - Config: testAccClusterUpdatedRootVolumeSizeConfig(rName), + Config: testAccClusterConfig_updatedRootVolumeSize(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "ebs_root_volume_size", "48"), @@ -1391,14 +1391,14 @@ func TestAccEMRCluster_StepConcurrency_level(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterStepConcurrencyLevelConfig(rName, 2), + Config: testAccClusterConfig_stepConcurrencyLevel(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "step_concurrency_level", "2"), ), }, { - Config: testAccClusterStepConcurrencyLevelConfig(rName, 1), + Config: testAccClusterConfig_stepConcurrencyLevel(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "step_concurrency_level", "1"), @@ -1429,7 +1429,7 @@ func TestAccEMRCluster_ebs(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccEBSConfig(rName, 2), + Config: testAccClusterConfig_ebs(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "master_instance_group.0.ebs_config.0.volumes_per_instance", "2"), @@ -1462,7 +1462,7 @@ func TestAccEMRCluster_CustomAMI_id(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCustomAMIIDConfig(rName), + Config: testAccClusterConfig_customAMIID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttrSet(resourceName, "custom_ami_id"), @@ -1497,7 +1497,7 @@ func TestAccEMRCluster_InstanceFleet_basic(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_InstanceFleets(rName), + Config: testAccClusterConfig_instanceFleets(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "master_instance_fleet.#", "1"), @@ -1521,7 +1521,7 @@ func TestAccEMRCluster_InstanceFleet_basic(t *testing.T) { }, }, { - Config: testAccClusterConfig_InstanceFleet_MultipleSubnets(rName), + Config: testAccClusterConfig_instanceFleetMultipleSubnets(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), @@ -1561,7 +1561,7 @@ func TestAccEMRCluster_InstanceFleetMaster_only(t *testing.T) { CheckDestroy: testAccCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceFleetsMasterOnlyConfig(rName), + Config: testAccClusterConfig_instanceFleetsMasterOnly(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "master_instance_fleet.#", "1"), @@ -2124,7 +2124,7 @@ const testAccClusterConfig_Step_SparkStep = ` // Configs -func testAccClusterConfig(rName string) string { +func testAccClusterConfig_basic(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -2182,7 +2182,7 @@ resource "aws_emr_cluster" "test" { `, rName)) } -func testAccClusterAdditionalInfoConfig(rName string) string { +func testAccClusterConfig_additionalInfo(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -2249,7 +2249,7 @@ EOF `, rName)) } -func testAccClusterConfigurationsJSONConfig(rName string) string { +func testAccClusterConfig_configurationsJSON(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -2322,7 +2322,7 @@ EOF `, rName)) } -func testAccClusterCoreInstanceGroupAutoScalingPolicyConfig(rName, autoscalingPolicy string) string { +func testAccClusterConfig_coreInstanceGroupAutoScalingPolicy(rName, autoscalingPolicy string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2387,7 +2387,7 @@ POLICY `, rName, autoscalingPolicy)) } -func testAccClusterCoreInstanceGroupAutoScalingPolicyRemovedConfig(rName string) string { +func testAccClusterConfig_coreInstanceGroupAutoScalingPolicyRemoved(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2449,7 +2449,7 @@ resource "aws_emr_cluster" "test" { `, rName)) } -func testAccClusterCoreInstanceGroupBidPriceConfig(rName, bidPrice string) string { +func testAccClusterConfig_coreInstanceGroupBidPrice(rName, bidPrice string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2481,7 +2481,7 @@ resource "aws_emr_cluster" "test" { `, rName, bidPrice)) } -func testAccClusterCoreInstanceGroupInstanceCountConfig(rName string, instanceCount int) string { +func testAccClusterConfig_coreInstanceGroupInstanceCount(rName string, instanceCount int) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2513,7 +2513,7 @@ resource "aws_emr_cluster" "test" { `, rName, instanceCount)) } -func testAccClusterCoreInstanceGroupInstanceTypeConfig(rName, instanceType string) string { +func testAccClusterConfig_coreInstanceGroupInstanceType(rName, instanceType string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2544,7 +2544,7 @@ resource "aws_emr_cluster" "test" { `, rName, instanceType)) } -func testAccClusterCoreInstanceGroupNameConfig(rName, instanceGroupName string) string { +func testAccClusterConfig_coreInstanceGroupName(rName, instanceGroupName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2576,7 +2576,7 @@ resource "aws_emr_cluster" "test" { `, rName, instanceGroupName)) } -func testAccClusterEC2AttributesDefaultManagedSecurityGroupsConfig(rName string) string { +func testAccClusterConfig_ec2AttributesDefaultManagedSecurityGroups(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2601,7 +2601,7 @@ resource "aws_emr_cluster" "test" { `, rName)) } -func testAccClusterConfig_Kerberos_ClusterDedicatedKdc(rName string, password string) string { +func testAccClusterConfig_kerberosDedicatedKdc(rName string, password string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2655,7 +2655,7 @@ resource "aws_emr_cluster" "test" { `, rName, password)) } -func testAccClusterMasterInstanceGroupBidPriceConfig(rName, bidPrice string) string { +func testAccClusterConfig_masterInstanceGroupBidPrice(rName, bidPrice string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2683,7 +2683,7 @@ resource "aws_emr_cluster" "test" { `, rName, bidPrice)) } -func testAccClusterMasterInstanceGroupInstanceCountConfig(rName string, instanceCount int) string { +func testAccClusterConfig_masterInstanceGroupInstanceCount(rName string, instanceCount int) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, true), fmt.Sprintf(` @@ -2719,7 +2719,7 @@ resource "aws_emr_cluster" "test" { `, rName, instanceCount)) } -func testAccClusterMasterInstanceGroupInstanceTypeConfig(rName, instanceType string) string { +func testAccClusterConfig_masterInstanceGroupInstanceType(rName, instanceType string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2746,7 +2746,7 @@ resource "aws_emr_cluster" "test" { `, rName, instanceType)) } -func testAccClusterMasterInstanceGroupNameConfig(rName, instanceGroupName string) string { +func testAccClusterConfig_masterInstanceGroupName(rName, instanceGroupName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -2774,7 +2774,7 @@ resource "aws_emr_cluster" "test" { `, rName, instanceGroupName)) } -func testAccClusterConfig_SecurityConfiguration(rName string) string { +func testAccClusterConfig_securityConfiguration(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -2874,24 +2874,24 @@ POLICY `, rName)) } -func testAccClusterConfig_Step_Single(rName string) string { +func testAccClusterConfig_stepSingle(rName string) string { return testAccClusterConfig_Step(rName, testAccClusterConfig_Step_DebugLoggingStep) } -func testAccClusterConfig_Step_NoBlocks(rName string) string { +func testAccClusterConfig_stepNoBlocks(rName string) string { return testAccClusterConfig_Step(rName, "") } -func testAccClusterConfig_Step_Zeroed(rName string) string { +func testAccClusterConfig_stepZeroed(rName string) string { return testAccClusterConfig_Step(rName, "step = []") } -func testAccClusterConfig_Step_Multiple(rName string) string { +func testAccClusterConfig_stepMultiple(rName string) string { stepConfig := acctest.ConfigCompose(testAccClusterConfig_Step_DebugLoggingStep, testAccClusterConfig_Step_SparkStep) return testAccClusterConfig_Step(rName, stepConfig) } -func testAccClusterConfig_Step_Multiple_ListStates(rName string) string { +func testAccClusterConfig_stepMultipleListStates(rName string) string { stepConfig := acctest.ConfigCompose( testAccClusterConfig_Step_DebugLoggingStep, testAccClusterConfig_Step_SparkStep, @@ -3104,7 +3104,7 @@ resource "aws_emr_cluster" "test" { `, rName)) } -func testAccClusterTerminationPolicyConfig(rName string, term string) string { +func testAccClusterConfig_terminationPolicy(rName string, term string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -3224,7 +3224,7 @@ resource "aws_emr_cluster" "test" { `, rName, keepJob)) } -func testAccClusterVisibleToAllUsersUpdatedConfig(rName string) string { +func testAccClusterConfig_visibleToAllUsersUpdated(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -3279,7 +3279,7 @@ resource "aws_emr_cluster" "test" { `, rName)) } -func testAccClusterS3LoggingConfig(rName string) string { +func testAccClusterConfig_s3Logging(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleCustomAMIIDConfig(rName), @@ -3325,7 +3325,7 @@ data "aws_caller_identity" "current" {} `, rName)) } -func testAccClusterS3EncryptionConfig(rName string) string { +func testAccClusterConfig_s3Encryption(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleCustomAMIIDConfig(rName), @@ -3394,7 +3394,7 @@ data "aws_caller_identity" "current" {} `, rName)) } -func testAccClusterUpdatedTagsConfig(rName string) string { +func testAccClusterConfig_updatedTags(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -3448,7 +3448,7 @@ resource "aws_emr_cluster" "test" { `, rName)) } -func testAccClusterUpdatedRootVolumeSizeConfig(rName string) string { +func testAccClusterConfig_updatedRootVolumeSize(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -3504,7 +3504,7 @@ resource "aws_emr_cluster" "test" { `, rName)) } -func testAccClusterStepConcurrencyLevelConfig(rName string, stepConcurrencyLevel int) string { +func testAccClusterConfig_stepConcurrencyLevel(rName string, stepConcurrencyLevel int) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -3533,7 +3533,7 @@ resource "aws_emr_cluster" "test" { `, rName, stepConcurrencyLevel)) } -func testAccEBSConfig(rName string, volumesPerInstance int) string { +func testAccClusterConfig_ebs(rName string, volumesPerInstance int) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -3579,7 +3579,7 @@ resource "aws_emr_cluster" "test" { `, rName, volumesPerInstance)) } -func testAccClusterCustomAMIIDConfig(rName string) string { +func testAccClusterConfig_customAMIID(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleCustomAMIIDConfig(rName), @@ -3661,7 +3661,7 @@ data "aws_ami" "emr-custom-ami" { `, rName)) } -func testAccClusterConfig_InstanceFleets(rName string) string { +func testAccClusterConfig_instanceFleets(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -3749,7 +3749,7 @@ resource "aws_emr_cluster" "test" { `, rName)) } -func testAccClusterConfig_InstanceFleet_MultipleSubnets(rName string) string { +func testAccClusterConfig_instanceFleetMultipleSubnets(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -3849,7 +3849,7 @@ resource "aws_route_table_association" "test2" { `, rName)) } -func testAccClusterInstanceFleetsMasterOnlyConfig(rName string) string { +func testAccClusterConfig_instanceFleetsMasterOnly(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), testAccClusterIAMServiceRoleBaseConfig(rName), @@ -3894,7 +3894,7 @@ resource "aws_emr_cluster" "test" { `, rName)) } -func testAccClusterAutoTerminationConfig(rName string, timeout int) string { +func testAccClusterConfig_autoTermination(rName string, timeout int) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` @@ -3927,7 +3927,7 @@ resource "aws_emr_cluster" "test" { `, rName, timeout)) } -func testAccClusterNoAutoTerminationConfig(rName string) string { +func testAccClusterConfig_noAutoTermination(rName string) string { return acctest.ConfigCompose( testAccClusterBaseVPCConfig(rName, false), fmt.Sprintf(` diff --git a/internal/service/emr/instance_fleet_test.go b/internal/service/emr/instance_fleet_test.go index 6f4172402e5..08ab49c6b4f 100644 --- a/internal/service/emr/instance_fleet_test.go +++ b/internal/service/emr/instance_fleet_test.go @@ -27,7 +27,7 @@ func TestAccEMRInstanceFleet_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceFleetConfig(rName), + Config: testAccInstanceFleetConfig_basic(rName), Check: resource.ComposeTestCheckFunc(testAccCheckInstanceFleetExists(resourceName, &fleet), resource.TestCheckResourceAttr(resourceName, "instance_type_configs.#", "1"), resource.TestCheckResourceAttr(resourceName, "target_on_demand_capacity", "1"), @@ -55,7 +55,7 @@ func TestAccEMRInstanceFleet_Zero_count(t *testing.T) { CheckDestroy: testAccCheckInstanceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceFleetConfig(rName), + Config: testAccInstanceFleetConfig_basic(rName), Check: resource.ComposeTestCheckFunc(testAccCheckInstanceFleetExists(resourceName, &fleet), resource.TestCheckResourceAttr(resourceName, "instance_type_configs.#", "1"), resource.TestCheckResourceAttr(resourceName, "target_on_demand_capacity", "1"), @@ -63,7 +63,7 @@ func TestAccEMRInstanceFleet_Zero_count(t *testing.T) { ), }, { - Config: testAccInstanceFleetZeroCountConfig(rName), + Config: testAccInstanceFleetConfig_zeroCount(rName), Check: resource.ComposeTestCheckFunc(testAccCheckInstanceFleetExists(resourceName, &fleet), resource.TestCheckResourceAttr(resourceName, "instance_type_configs.#", "1"), resource.TestCheckResourceAttr(resourceName, "target_on_demand_capacity", "0"), @@ -91,7 +91,7 @@ func TestAccEMRInstanceFleet_ebsBasic(t *testing.T) { CheckDestroy: testAccCheckInstanceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceFleetEBSBasicConfig(rName), + Config: testAccInstanceFleetConfig_ebsBasic(rName), Check: resource.ComposeTestCheckFunc(testAccCheckInstanceFleetExists(resourceName, &fleet), resource.TestCheckResourceAttr(resourceName, "instance_type_configs.#", "1"), resource.TestCheckResourceAttr(resourceName, "target_on_demand_capacity", "0"), @@ -119,7 +119,7 @@ func TestAccEMRInstanceFleet_full(t *testing.T) { CheckDestroy: testAccCheckInstanceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceFleetFullConfig(rName), + Config: testAccInstanceFleetConfig_full(rName), Check: resource.ComposeTestCheckFunc(testAccCheckInstanceFleetExists(resourceName, &fleet), resource.TestCheckResourceAttr(resourceName, "instance_type_configs.#", "2"), resource.TestCheckResourceAttr(resourceName, "target_on_demand_capacity", "2"), @@ -149,7 +149,7 @@ func TestAccEMRInstanceFleet_disappears(t *testing.T) { CheckDestroy: testAccCheckInstanceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceFleetConfig(rName), + Config: testAccInstanceFleetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceFleetExists(resourceName, &fleet), // EMR Instance Fleet can only be scaled down and are not removed until the @@ -451,7 +451,7 @@ resource "aws_emr_cluster" "test" { } ` -func testAccInstanceFleetConfig(r string) string { +func testAccInstanceFleetConfig_basic(r string) string { return fmt.Sprintf(testAccInstanceFleetBase+` resource "aws_emr_instance_fleet" "task" { cluster_id = aws_emr_cluster.test.id @@ -474,7 +474,7 @@ resource "aws_emr_instance_fleet" "task" { `, r) } -func testAccInstanceFleetZeroCountConfig(r string) string { +func testAccInstanceFleetConfig_zeroCount(r string) string { return fmt.Sprintf(testAccInstanceFleetBase+` resource "aws_emr_instance_fleet" "task" { cluster_id = aws_emr_cluster.test.id @@ -497,7 +497,7 @@ resource "aws_emr_instance_fleet" "task" { `, r) } -func testAccInstanceFleetEBSBasicConfig(r string) string { +func testAccInstanceFleetConfig_ebsBasic(r string) string { return fmt.Sprintf(testAccInstanceFleetBase+` resource "aws_emr_instance_fleet" "task" { cluster_id = aws_emr_cluster.test.id @@ -529,7 +529,7 @@ resource "aws_emr_instance_fleet" "task" { `, r) } -func testAccInstanceFleetFullConfig(r string) string { +func testAccInstanceFleetConfig_full(r string) string { return fmt.Sprintf(testAccInstanceFleetBase+` resource "aws_emr_instance_fleet" "task" { cluster_id = aws_emr_cluster.test.id diff --git a/internal/service/emr/instance_group.go b/internal/service/emr/instance_group.go index 9325fd95d69..d0bd2d1ccfd 100644 --- a/internal/service/emr/instance_group.go +++ b/internal/service/emr/instance_group.go @@ -160,7 +160,7 @@ func resourceInstanceGroupCreate(d *schema.ResourceData, meta interface{}) error if err != nil { return fmt.Errorf("configurations_json contains an invalid JSON: %s", err) } - groupConfig.Configurations, err = expandConfigurationJson(info) + groupConfig.Configurations, err = expandConfigurationJSON(info) if err != nil { return fmt.Errorf("Error reading EMR configurations_json: %s", err) } @@ -224,7 +224,7 @@ func resourceInstanceGroupRead(d *schema.ResourceData, meta interface{}) error { switch { case len(ig.Configurations) > 0: - configOut, err := flattenConfigurationJson(ig.Configurations) + configOut, err := flattenConfigurationJSON(ig.Configurations) if err != nil { return fmt.Errorf("Error reading EMR instance group configurations: %s", err) } @@ -302,7 +302,7 @@ func resourceInstanceGroupUpdate(d *schema.ResourceData, meta interface{}) error if err != nil { return fmt.Errorf("configurations_json contains an invalid JSON: %s", err) } - instanceGroupModifyConfig.Configurations, err = expandConfigurationJson(info) + instanceGroupModifyConfig.Configurations, err = expandConfigurationJSON(info) if err != nil { return fmt.Errorf("Error reading EMR configurations_json: %s", err) } diff --git a/internal/service/emr/instance_group_test.go b/internal/service/emr/instance_group_test.go index 5faf050c24c..c2c5adb43ca 100644 --- a/internal/service/emr/instance_group_test.go +++ b/internal/service/emr/instance_group_test.go @@ -73,7 +73,7 @@ func TestAccEMRInstanceGroup_bidPrice(t *testing.T) { ImportStateVerifyIgnore: []string{"status"}, }, { - Config: testAccInstanceGroupConfig_BidPrice(rInt), + Config: testAccInstanceGroupConfig_bidPrice(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceGroupExists(resourceName, &ig2), resource.TestCheckResourceAttr(resourceName, "bid_price", "0.30"), @@ -111,7 +111,7 @@ func TestAccEMRInstanceGroup_sJSON(t *testing.T) { CheckDestroy: testAccCheckInstanceGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceGroupConfig_ConfigurationsJSON(rInt, "partitionName1"), + Config: testAccInstanceGroupConfig_configurationsJSON(rInt, "partitionName1"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceGroupExists(resourceName, &ig), resource.TestCheckResourceAttrSet(resourceName, "configurations_json"), @@ -125,7 +125,7 @@ func TestAccEMRInstanceGroup_sJSON(t *testing.T) { ImportStateVerifyIgnore: []string{"status"}, }, { - Config: testAccInstanceGroupConfig_ConfigurationsJSON(rInt, "partitionName2"), + Config: testAccInstanceGroupConfig_configurationsJSON(rInt, "partitionName2"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceGroupExists(resourceName, &ig), resource.TestCheckResourceAttrSet(resourceName, "configurations_json"), @@ -154,7 +154,7 @@ func TestAccEMRInstanceGroup_autoScalingPolicy(t *testing.T) { CheckDestroy: testAccCheckInstanceGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceGroupConfig_AutoScalingPolicy(rInt, 1, 3), + Config: testAccInstanceGroupConfig_autoScalingPolicy(rInt, 1, 3), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceGroupExists(resourceName, &ig), resource.TestCheckResourceAttrSet(resourceName, "autoscaling_policy"), @@ -168,7 +168,7 @@ func TestAccEMRInstanceGroup_autoScalingPolicy(t *testing.T) { ImportStateVerifyIgnore: []string{"status"}, }, { - Config: testAccInstanceGroupConfig_AutoScalingPolicy(rInt, 2, 3), + Config: testAccInstanceGroupConfig_autoScalingPolicy(rInt, 2, 3), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceGroupExists(resourceName, &ig), resource.TestCheckResourceAttrSet(resourceName, "autoscaling_policy"), @@ -256,7 +256,7 @@ func TestAccEMRInstanceGroup_EBS_ebsOptimized(t *testing.T) { CheckDestroy: testAccCheckInstanceGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceGroupConfig_ebsConfig(rInt, true), + Config: testAccInstanceGroupConfig_ebs(rInt, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceGroupExists(resourceName, &ig), resource.TestCheckResourceAttr(resourceName, "ebs_config.#", "1"), @@ -271,7 +271,7 @@ func TestAccEMRInstanceGroup_EBS_ebsOptimized(t *testing.T) { ImportStateVerifyIgnore: []string{"status"}, }, { - Config: testAccInstanceGroupConfig_ebsConfig(rInt, false), + Config: testAccInstanceGroupConfig_ebs(rInt, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceGroupExists(resourceName, &ig), resource.TestCheckResourceAttr(resourceName, "ebs_config.#", "1"), @@ -658,7 +658,7 @@ resource "aws_emr_instance_group" "task" { `, r) } -func testAccInstanceGroupConfig_BidPrice(r int) string { +func testAccInstanceGroupConfig_bidPrice(r int) string { return fmt.Sprintf(testAccInstanceGroupBase+` resource "aws_emr_instance_group" "task" { cluster_id = aws_emr_cluster.tf-test-cluster.id @@ -669,7 +669,7 @@ resource "aws_emr_instance_group" "task" { `, r) } -func testAccInstanceGroupConfig_ConfigurationsJSON(r int, name string) string { +func testAccInstanceGroupConfig_configurationsJSON(r int, name string) string { return fmt.Sprintf(testAccInstanceGroupBase+` resource "aws_emr_instance_group" "task" { cluster_id = aws_emr_cluster.tf-test-cluster.id @@ -690,7 +690,7 @@ EOF `, r, name) } -func testAccInstanceGroupConfig_AutoScalingPolicy(r, min, max int) string { +func testAccInstanceGroupConfig_autoScalingPolicy(r, min, max int) string { return fmt.Sprintf(testAccInstanceGroupBase+` resource "aws_emr_instance_group" "task" { cluster_id = aws_emr_cluster.tf-test-cluster.id @@ -733,7 +733,7 @@ EOT `, r, min, max) } -func testAccInstanceGroupConfig_ebsConfig(r int, o bool) string { +func testAccInstanceGroupConfig_ebs(r int, o bool) string { return fmt.Sprintf(testAccInstanceGroupBase+` resource "aws_emr_instance_group" "task" { cluster_id = aws_emr_cluster.tf-test-cluster.id diff --git a/internal/service/emr/managed_scaling_policy_test.go b/internal/service/emr/managed_scaling_policy_test.go index c58d0862b91..5949769c4a3 100644 --- a/internal/service/emr/managed_scaling_policy_test.go +++ b/internal/service/emr/managed_scaling_policy_test.go @@ -38,7 +38,7 @@ func TestAccEMRManagedScalingPolicy_basic(t *testing.T) { Steps: []resource.TestStep{ { - Config: testAccManagedScalingPolicy_basic(rName), + Config: testAccManagedScalingPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckManagedScalingPolicyExists(resourceName), ), @@ -63,7 +63,7 @@ func TestAccEMRManagedScalingPolicy_ComputeLimits_maximumCoreCapacityUnits(t *te Steps: []resource.TestStep{ { - Config: testAccManagedScalingPolicy_ComputeLimits_MaximumCoreCapacityUnits(rName, 2), + Config: testAccManagedScalingPolicyConfig_computeLimitsMaximumCoreCapacityUnits(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckManagedScalingPolicyExists(resourceName), ), @@ -88,7 +88,7 @@ func TestAccEMRManagedScalingPolicy_ComputeLimits_maximumOnDemandCapacityUnits(t Steps: []resource.TestStep{ { - Config: testAccManagedScalingPolicy_ComputeLimits_MaximumOndemandCapacityUnits(rName, 2), + Config: testAccManagedScalingPolicyConfig_computeLimitsMaximumOndemandCapacityUnits(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckManagedScalingPolicyExists(resourceName), ), @@ -112,7 +112,7 @@ func TestAccEMRManagedScalingPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckManagedScalingPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccManagedScalingPolicy_basic(rName), + Config: testAccManagedScalingPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckManagedScalingPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfemr.ResourceManagedScalingPolicy(), resourceName), @@ -123,7 +123,7 @@ func TestAccEMRManagedScalingPolicy_disappears(t *testing.T) { }) } -func testAccManagedScalingPolicy_basic(r string) string { +func testAccManagedScalingPolicyConfig_basic(r string) string { return fmt.Sprintf(testAccManagedScalingPolicyBase+` resource "aws_emr_managed_scaling_policy" "testpolicy" { cluster_id = aws_emr_cluster.test.id @@ -136,7 +136,7 @@ resource "aws_emr_managed_scaling_policy" "testpolicy" { `, r) } -func testAccManagedScalingPolicy_ComputeLimits_MaximumCoreCapacityUnits(r string, maximumCoreCapacityUnits int) string { +func testAccManagedScalingPolicyConfig_computeLimitsMaximumCoreCapacityUnits(r string, maximumCoreCapacityUnits int) string { return fmt.Sprintf(testAccManagedScalingPolicyBase+` resource "aws_emr_managed_scaling_policy" "testpolicy" { cluster_id = aws_emr_cluster.test.id @@ -150,7 +150,7 @@ resource "aws_emr_managed_scaling_policy" "testpolicy" { `, r, maximumCoreCapacityUnits) } -func testAccManagedScalingPolicy_ComputeLimits_MaximumOndemandCapacityUnits(r string, maximumOndemandCapacityUnits int) string { +func testAccManagedScalingPolicyConfig_computeLimitsMaximumOndemandCapacityUnits(r string, maximumOndemandCapacityUnits int) string { return fmt.Sprintf(testAccManagedScalingPolicyBase+` resource "aws_emr_managed_scaling_policy" "testpolicy" { cluster_id = aws_emr_cluster.test.id diff --git a/internal/service/emr/release_labels_data_source_test.go b/internal/service/emr/release_labels_data_source_test.go index 646adf090a6..17da7bd00c1 100644 --- a/internal/service/emr/release_labels_data_source_test.go +++ b/internal/service/emr/release_labels_data_source_test.go @@ -18,7 +18,7 @@ func TestAccEMRReleaseLabels_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccReleaseLabelsDataSourceConfigBasic(), + Config: testAccReleaseLabelsDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceResourceName, "release_labels.#"), ), @@ -37,7 +37,7 @@ func TestAccEMRReleaseLabels_prefix(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccReleaseLabelsDataSourceConfigPrefix(), + Config: testAccReleaseLabelsDataSourceConfig_prefix(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceResourceName, "release_labels.#"), ), @@ -56,7 +56,7 @@ func TestAccEMRReleaseLabels_application(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccReleaseLabelsDataSourceConfigApplication(), + Config: testAccReleaseLabelsDataSourceConfig_application(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceResourceName, "release_labels.#"), ), @@ -75,7 +75,7 @@ func TestAccEMRReleaseLabels_full(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccReleaseLabelsDataSourceConfigFull(), + Config: testAccReleaseLabelsDataSourceConfig_full(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceResourceName, "release_labels.#"), ), @@ -94,7 +94,7 @@ func TestAccEMRReleaseLabels_empty(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccReleaseLabelsDataSourceConfigEmpty(), + Config: testAccReleaseLabelsDataSourceConfig_empty(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceResourceName, "release_labels.#", "0"), ), @@ -103,13 +103,13 @@ func TestAccEMRReleaseLabels_empty(t *testing.T) { }) } -func testAccReleaseLabelsDataSourceConfigBasic() string { +func testAccReleaseLabelsDataSourceConfig_basic() string { return ` data "aws_emr_release_labels" "test" {} ` } -func testAccReleaseLabelsDataSourceConfigPrefix() string { +func testAccReleaseLabelsDataSourceConfig_prefix() string { return ` data "aws_emr_release_labels" "test" { filters { @@ -119,7 +119,7 @@ data "aws_emr_release_labels" "test" { ` } -func testAccReleaseLabelsDataSourceConfigApplication() string { +func testAccReleaseLabelsDataSourceConfig_application() string { return ` data "aws_emr_release_labels" "test" { filters { @@ -129,7 +129,7 @@ data "aws_emr_release_labels" "test" { ` } -func testAccReleaseLabelsDataSourceConfigFull() string { +func testAccReleaseLabelsDataSourceConfig_full() string { return ` data "aws_emr_release_labels" "test" { filters { @@ -140,7 +140,7 @@ data "aws_emr_release_labels" "test" { ` } -func testAccReleaseLabelsDataSourceConfigEmpty() string { +func testAccReleaseLabelsDataSourceConfig_empty() string { return ` data "aws_emr_release_labels" "test" { filters { diff --git a/internal/service/emrcontainers/virtual_cluster.go b/internal/service/emrcontainers/virtual_cluster.go index 4f7f3070eec..2dab78d96e5 100644 --- a/internal/service/emrcontainers/virtual_cluster.go +++ b/internal/service/emrcontainers/virtual_cluster.go @@ -242,13 +242,13 @@ func expandContainerInfo(tfMap map[string]interface{}) *emrcontainers.ContainerI apiObject := &emrcontainers.ContainerInfo{} if v, ok := tfMap["eks_info"].([]interface{}); ok && len(v) > 0 { - apiObject.EksInfo = expandEksInfo(v[0].(map[string]interface{})) + apiObject.EksInfo = expandEKSInfo(v[0].(map[string]interface{})) } return apiObject } -func expandEksInfo(tfMap map[string]interface{}) *emrcontainers.EksInfo { +func expandEKSInfo(tfMap map[string]interface{}) *emrcontainers.EksInfo { if tfMap == nil { return nil } @@ -292,13 +292,13 @@ func flattenContainerInfo(apiObject *emrcontainers.ContainerInfo) map[string]int tfMap := map[string]interface{}{} if v := apiObject.EksInfo; v != nil { - tfMap["eks_info"] = []interface{}{flattenEksInfo(v)} + tfMap["eks_info"] = []interface{}{flattenEKSInfo(v)} } return tfMap } -func flattenEksInfo(apiObject *emrcontainers.EksInfo) map[string]interface{} { +func flattenEKSInfo(apiObject *emrcontainers.EksInfo) map[string]interface{} { if apiObject == nil { return nil } diff --git a/internal/service/emrcontainers/virtual_cluster_data_source_test.go b/internal/service/emrcontainers/virtual_cluster_data_source_test.go index 81bcdfa77b7..59a300df3e6 100644 --- a/internal/service/emrcontainers/virtual_cluster_data_source_test.go +++ b/internal/service/emrcontainers/virtual_cluster_data_source_test.go @@ -31,7 +31,7 @@ func TestAccEMRContainersVirtualClusterDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckVirtualClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccVirtualClusterDataSourceConfig_Basic(rName), + Config: testAccVirtualClusterDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceResourceName, "arn"), resource.TestCheckResourceAttr(dataSourceResourceName, "container_provider.#", "1"), @@ -51,8 +51,8 @@ func TestAccEMRContainersVirtualClusterDataSource_basic(t *testing.T) { }) } -func testAccVirtualClusterDataSourceConfig_Basic(rName string) string { - return acctest.ConfigCompose(testAccVirtualClusterConfig(rName), ` +func testAccVirtualClusterDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccVirtualClusterConfig_basic(rName), ` data "aws_emrcontainers_virtual_cluster" "test" { virtual_cluster_id = aws_emrcontainers_virtual_cluster.test.id } diff --git a/internal/service/emrcontainers/virtual_cluster_test.go b/internal/service/emrcontainers/virtual_cluster_test.go index 26476b71548..07d4e103975 100644 --- a/internal/service/emrcontainers/virtual_cluster_test.go +++ b/internal/service/emrcontainers/virtual_cluster_test.go @@ -37,7 +37,7 @@ func TestAccEMRContainersVirtualCluster_basic(t *testing.T) { CheckDestroy: testAccCheckVirtualClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccVirtualClusterConfig(rName), + Config: testAccVirtualClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVirtualClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "container_provider.#", "1"), @@ -92,7 +92,7 @@ func TestAccEMRContainersVirtualCluster_disappears(t *testing.T) { CheckDestroy: testAccCheckVirtualClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccVirtualClusterConfig(rName), + Config: testAccVirtualClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVirtualClusterExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfemrcontainers.ResourceVirtualCluster(), resourceName), @@ -125,7 +125,7 @@ func TestAccEMRContainersVirtualCluster_tags(t *testing.T) { CheckDestroy: testAccCheckVirtualClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccVirtualClusterConfigTags1(rName, "key1", "value1"), + Config: testAccVirtualClusterConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckVirtualClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -133,7 +133,7 @@ func TestAccEMRContainersVirtualCluster_tags(t *testing.T) { ), }, { - Config: testAccVirtualClusterConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVirtualClusterConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVirtualClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -142,7 +142,7 @@ func TestAccEMRContainersVirtualCluster_tags(t *testing.T) { ), }, { - Config: testAccVirtualClusterConfigTags1(rName, "key2", "value2"), + Config: testAccVirtualClusterConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVirtualClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -469,7 +469,7 @@ EOF `, rName)) } -func testAccVirtualClusterConfig(rName string) string { +func testAccVirtualClusterConfig_basic(rName string) string { return acctest.ConfigCompose(testAccVirtualClusterBase(rName), fmt.Sprintf(` resource "aws_emrcontainers_virtual_cluster" "test" { container_provider { @@ -490,7 +490,7 @@ resource "aws_emrcontainers_virtual_cluster" "test" { `, rName)) } -func testAccVirtualClusterConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccVirtualClusterConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccVirtualClusterBase(rName), fmt.Sprintf(` resource "aws_emrcontainers_virtual_cluster" "test" { container_provider { @@ -515,7 +515,7 @@ resource "aws_emrcontainers_virtual_cluster" "test" { `, rName, tagKey1, tagValue1)) } -func testAccVirtualClusterConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVirtualClusterConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccVirtualClusterBase(rName), fmt.Sprintf(` resource "aws_emrcontainers_virtual_cluster" "test" { container_provider { diff --git a/internal/service/emrserverless/application.go b/internal/service/emrserverless/application.go new file mode 100644 index 00000000000..483fc2715d0 --- /dev/null +++ b/internal/service/emrserverless/application.go @@ -0,0 +1,642 @@ +package emrserverless + +import ( + "fmt" + "log" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/emrserverless" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceApplication() *schema.Resource { + return &schema.Resource{ + Create: resourceApplicationCreate, + Read: resourceApplicationRead, + Update: resourceApplicationUpdate, + Delete: resourceApplicationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + CustomizeDiff: verify.SetTagsDiff, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "auto_start_configuration": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + }, + }, + }, + "auto_stop_configuration": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "idle_timeout_minutes": { + Type: schema.TypeInt, + Optional: true, + Default: 15, + ValidateFunc: validation.IntBetween(1, 10080), + }, + }, + }, + }, + "initial_capacity": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "initial_capacity_config": { + Type: schema.TypeList, + Optional: true, + DiffSuppressFunc: verify.SuppressMissingOptionalConfigurationBlock, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "worker_configuration": { + Type: schema.TypeList, + Optional: true, + DiffSuppressFunc: verify.SuppressMissingOptionalConfigurationBlock, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeString, + Required: true, + }, + "disk": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "memory": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + "worker_count": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 1000000), + }, + }, + }, + }, + "initial_capacity_type": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + "maximum_capacity": { + Type: schema.TypeList, + Optional: true, + DiffSuppressFunc: verify.SuppressMissingOptionalConfigurationBlock, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeString, + Required: true, + }, + "disk": { + Type: schema.TypeString, + Optional: true, + }, + "memory": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 64), + }, + "network_configuration": { + Type: schema.TypeList, + Optional: true, + DiffSuppressFunc: verify.SuppressMissingOptionalConfigurationBlock, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "security_group_ids": { + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "subnet_ids": { + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + "release_label": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + "type": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: func(val interface{}) string { + return strings.ToLower(val.(string)) + }, + }, + }, + } +} + +func resourceApplicationCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).EMRServerlessConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + name := d.Get("name").(string) + input := &emrserverless.CreateApplicationInput{ + ClientToken: aws.String(resource.UniqueId()), + ReleaseLabel: aws.String(d.Get("release_label").(string)), + Name: aws.String(name), + Type: aws.String(d.Get("type").(string)), + } + + if v, ok := d.GetOk("auto_start_configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.AutoStartConfiguration = expandAutoStartConfig(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("auto_stop_configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.AutoStopConfiguration = expandAutoStopConfig(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("initial_capacity"); ok && v.(*schema.Set).Len() > 0 { + input.InitialCapacity = expandInitialCapacity(v.(*schema.Set)) + } + + if v, ok := d.GetOk("maximum_capacity"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.MaximumCapacity = expandMaximumCapacity(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("network_configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.NetworkConfiguration = expandNetworkConfiguration(v.([]interface{})[0].(map[string]interface{})) + } + + if len(tags) > 0 { + input.Tags = Tags(tags.IgnoreAWS()) + } + + log.Printf("[DEBUG] Creating EMR Serveless Application: %s", input) + result, err := conn.CreateApplication(input) + + if err != nil { + return fmt.Errorf("creating EMR Serveless Application (%s): %w", name, err) + } + + d.SetId(aws.StringValue(result.ApplicationId)) + + if _, err := waitApplicationCreated(conn, d.Id()); err != nil { + return fmt.Errorf("waiting for EMR Serveless Application (%s) create: %w", d.Id(), err) + } + + return resourceApplicationRead(d, meta) +} + +func resourceApplicationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).EMRServerlessConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + application, err := FindApplicationByID(conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] EMR Serverless Application (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("reading EMR Serverless Application (%s): %w", d.Id(), err) + } + + d.Set("arn", application.Arn) + d.Set("name", application.Name) + d.Set("release_label", application.ReleaseLabel) + d.Set("type", strings.ToLower(aws.StringValue(application.Type))) + + if err := d.Set("auto_start_configuration", []interface{}{flattenAutoStartConfig(application.AutoStartConfiguration)}); err != nil { + return fmt.Errorf("setting auto_start_configuration: %w", err) + } + + if err := d.Set("auto_stop_configuration", []interface{}{flattenAutoStopConfig(application.AutoStopConfiguration)}); err != nil { + return fmt.Errorf("setting auto_stop_configuration: %w", err) + } + + if err := d.Set("initial_capacity", flattenInitialCapacity(application.InitialCapacity)); err != nil { + return fmt.Errorf("setting initial_capacity: %w", err) + } + + if err := d.Set("maximum_capacity", []interface{}{flattenMaximumCapacity(application.MaximumCapacity)}); err != nil { + return fmt.Errorf("setting maximum_capacity: %w", err) + } + + if err := d.Set("network_configuration", []interface{}{flattenNetworkConfiguration(application.NetworkConfiguration)}); err != nil { + return fmt.Errorf("setting network_configuration: %w", err) + } + + tags := KeyValueTags(application.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return fmt.Errorf("setting tags: %w", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return fmt.Errorf("setting tags_all: %w", err) + } + + return nil +} + +func resourceApplicationUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).EMRServerlessConn + + if d.HasChangesExcept("tags", "tags_all") { + input := &emrserverless.UpdateApplicationInput{ + ApplicationId: aws.String(d.Id()), + ClientToken: aws.String(resource.UniqueId()), + } + + if v, ok := d.GetOk("auto_start_configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.AutoStartConfiguration = expandAutoStartConfig(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("auto_stop_configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.AutoStopConfiguration = expandAutoStopConfig(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("initial_capacity"); ok && v.(*schema.Set).Len() > 0 { + input.InitialCapacity = expandInitialCapacity(v.(*schema.Set)) + } + + if v, ok := d.GetOk("maximum_capacity"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.MaximumCapacity = expandMaximumCapacity(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("network_configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.NetworkConfiguration = expandNetworkConfiguration(v.([]interface{})[0].(map[string]interface{})) + } + + log.Printf("[DEBUG] Updating EMR Serveless Application: %s", input) + _, err := conn.UpdateApplication(input) + + if err != nil { + return fmt.Errorf("updating EMR Serveless Application (%s): %w", d.Id(), err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("updating EMR Serverless Application (%s) tags: %w", d.Id(), err) + } + } + + return resourceApplicationRead(d, meta) +} + +func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).EMRServerlessConn + + log.Printf("[INFO] Deleting EMR Serverless Application: %s", d.Id()) + _, err := conn.DeleteApplication(&emrserverless.DeleteApplicationInput{ + ApplicationId: aws.String(d.Id()), + }) + + if tfawserr.ErrCodeEquals(err, emrserverless.ErrCodeResourceNotFoundException) { + return nil + } + + if err != nil { + return fmt.Errorf("deleting EMR Serverless Application (%s): %w", d.Id(), err) + } + + if _, err := waitApplicationTerminated(conn, d.Id()); err != nil { + return fmt.Errorf("waiting for EMR Serveless Application (%s) delete: %w", d.Id(), err) + } + + return nil +} + +func expandAutoStartConfig(tfMap map[string]interface{}) *emrserverless.AutoStartConfig { + if tfMap == nil { + return nil + } + + apiObject := &emrserverless.AutoStartConfig{} + + if v, ok := tfMap["enabled"].(bool); ok { + apiObject.Enabled = aws.Bool(v) + } + + return apiObject +} + +func flattenAutoStartConfig(apiObject *emrserverless.AutoStartConfig) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.Enabled; v != nil { + tfMap["enabled"] = aws.BoolValue(v) + } + + return tfMap +} + +func expandAutoStopConfig(tfMap map[string]interface{}) *emrserverless.AutoStopConfig { + if tfMap == nil { + return nil + } + + apiObject := &emrserverless.AutoStopConfig{} + + if v, ok := tfMap["enabled"].(bool); ok { + apiObject.Enabled = aws.Bool(v) + } + + if v, ok := tfMap["idle_timeout_minutes"].(int); ok { + apiObject.IdleTimeoutMinutes = aws.Int64(int64(v)) + } + + return apiObject +} + +func flattenAutoStopConfig(apiObject *emrserverless.AutoStopConfig) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.Enabled; v != nil { + tfMap["enabled"] = aws.BoolValue(v) + } + + if v := apiObject.IdleTimeoutMinutes; v != nil { + tfMap["idle_timeout_minutes"] = aws.Int64Value(v) + } + + return tfMap +} + +func expandMaximumCapacity(tfMap map[string]interface{}) *emrserverless.MaximumAllowedResources { + if tfMap == nil { + return nil + } + + apiObject := &emrserverless.MaximumAllowedResources{} + + if v, ok := tfMap["cpu"].(string); ok && v != "" { + apiObject.Cpu = aws.String(v) + } + + if v, ok := tfMap["disk"].(string); ok && v != "" { + apiObject.Disk = aws.String(v) + } + + if v, ok := tfMap["memory"].(string); ok && v != "" { + apiObject.Memory = aws.String(v) + } + + return apiObject +} + +func flattenMaximumCapacity(apiObject *emrserverless.MaximumAllowedResources) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.Cpu; v != nil { + tfMap["cpu"] = aws.StringValue(v) + } + + if v := apiObject.Disk; v != nil { + tfMap["disk"] = aws.StringValue(v) + } + + if v := apiObject.Memory; v != nil { + tfMap["memory"] = aws.StringValue(v) + } + + return tfMap +} + +func expandNetworkConfiguration(tfMap map[string]interface{}) *emrserverless.NetworkConfiguration { + if tfMap == nil { + return nil + } + + apiObject := &emrserverless.NetworkConfiguration{} + + if v, ok := tfMap["security_group_ids"].(*schema.Set); ok && v.Len() > 0 { + apiObject.SecurityGroupIds = flex.ExpandStringSet(v) + } + + if v, ok := tfMap["subnet_ids"].(*schema.Set); ok && v.Len() > 0 { + apiObject.SubnetIds = flex.ExpandStringSet(v) + } + + return apiObject +} + +func flattenNetworkConfiguration(apiObject *emrserverless.NetworkConfiguration) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.SecurityGroupIds; v != nil { + tfMap["security_group_ids"] = flex.FlattenStringSet(v) + } + + if v := apiObject.SubnetIds; v != nil { + tfMap["subnet_ids"] = flex.FlattenStringSet(v) + } + + return tfMap +} + +func expandInitialCapacity(tfMap *schema.Set) map[string]*emrserverless.InitialCapacityConfig { + if tfMap == nil { + return nil + } + + configs := make(map[string]*emrserverless.InitialCapacityConfig) + + for _, tfMapRaw := range tfMap.List() { + + config, ok := tfMapRaw.(map[string]interface{}) + + if !ok { + continue + } + + if v, ok := config["initial_capacity_type"].(string); ok && v != "" { + if conf, ok := config["initial_capacity_config"].([]interface{}); ok && len(conf) > 0 { + configs[v] = expandInitialCapacityConfig(conf[0].(map[string]interface{})) + } + } + } + + return configs +} + +func flattenInitialCapacity(apiObject map[string]*emrserverless.InitialCapacityConfig) []interface{} { + if apiObject == nil { + return nil + } + + var tfList []interface{} + + for capacityType, config := range apiObject { + + if config == nil { + continue + } + + tfList = append(tfList, map[string]interface{}{ + "initial_capacity_type": capacityType, + "initial_capacity_config": []interface{}{flattenInitialCapacityConfig(config)}, + }) + } + + return tfList +} + +func expandInitialCapacityConfig(tfMap map[string]interface{}) *emrserverless.InitialCapacityConfig { + if tfMap == nil { + return nil + } + + apiObject := &emrserverless.InitialCapacityConfig{} + + if v, ok := tfMap["worker_count"].(int); ok { + apiObject.WorkerCount = aws.Int64(int64(v)) + } + + if v, ok := tfMap["worker_configuration"].([]interface{}); ok && v[0] != nil { + apiObject.WorkerConfiguration = expandWorkerResourceConfig(v[0].(map[string]interface{})) + } + + return apiObject +} + +func flattenInitialCapacityConfig(apiObject *emrserverless.InitialCapacityConfig) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.WorkerCount; v != nil { + tfMap["worker_count"] = aws.Int64Value(v) + } + + if v := apiObject.WorkerConfiguration; v != nil { + tfMap["worker_configuration"] = []interface{}{flattenWorkerResourceConfig(v)} + } + + return tfMap +} + +func expandWorkerResourceConfig(tfMap map[string]interface{}) *emrserverless.WorkerResourceConfig { + if tfMap == nil { + return nil + } + + apiObject := &emrserverless.WorkerResourceConfig{} + + if v, ok := tfMap["cpu"].(string); ok && v != "" { + apiObject.Cpu = aws.String(v) + } + + if v, ok := tfMap["disk"].(string); ok && v != "" { + apiObject.Disk = aws.String(v) + } + + if v, ok := tfMap["memory"].(string); ok && v != "" { + apiObject.Memory = aws.String(v) + } + + return apiObject +} + +func flattenWorkerResourceConfig(apiObject *emrserverless.WorkerResourceConfig) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.Cpu; v != nil { + tfMap["cpu"] = aws.StringValue(v) + } + + if v := apiObject.Disk; v != nil { + tfMap["disk"] = aws.StringValue(v) + } + + if v := apiObject.Memory; v != nil { + tfMap["memory"] = aws.StringValue(v) + } + + return tfMap +} diff --git a/internal/service/emrserverless/application_test.go b/internal/service/emrserverless/application_test.go new file mode 100644 index 00000000000..75952334199 --- /dev/null +++ b/internal/service/emrserverless/application_test.go @@ -0,0 +1,391 @@ +package emrserverless_test + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/emrserverless" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfemrserverless "github.com/hashicorp/terraform-provider-aws/internal/service/emrserverless" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccEMRServerlessApplication_basic(t *testing.T) { + var application emrserverless.Application + resourceName := "aws_emrserverless_application.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, emrserverless.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "emr-serverless", regexp.MustCompile(`/applications/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "type", "hive"), + resource.TestCheckResourceAttr(resourceName, "release_label", "emr-6.6.0"), + resource.TestCheckResourceAttr(resourceName, "auto_start_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "auto_start_configuration.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "auto_stop_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "auto_stop_configuration.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "auto_stop_configuration.0.idle_timeout_minutes", "15"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccEMRServerlessApplication_initialCapacity(t *testing.T) { + var application emrserverless.Application + resourceName := "aws_emrserverless_application.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, emrserverless.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_initialCapacity(rName, "2 vCPU"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.#", "1"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_type", "HiveDriver"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.0.worker_count", "1"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.0.worker_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.0.worker_configuration.0.cpu", "2 vCPU"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.0.worker_configuration.0.memory", "10 GB"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccApplicationConfig_initialCapacity(rName, "4 vCPU"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.#", "1"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_type", "HiveDriver"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.0.worker_count", "1"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.0.worker_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.0.worker_configuration.0.cpu", "4 vCPU"), + resource.TestCheckResourceAttr(resourceName, "initial_capacity.0.initial_capacity_config.0.worker_configuration.0.memory", "10 GB"), + ), + }, + }, + }) +} + +func TestAccEMRServerlessApplication_maxCapacity(t *testing.T) { + var application emrserverless.Application + resourceName := "aws_emrserverless_application.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, emrserverless.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_maxCapacity(rName, "2 vCPU"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + resource.TestCheckResourceAttr(resourceName, "maximum_capacity.#", "1"), + resource.TestCheckResourceAttr(resourceName, "maximum_capacity.0.cpu", "2 vCPU"), + resource.TestCheckResourceAttr(resourceName, "maximum_capacity.0.memory", "10 GB"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccApplicationConfig_maxCapacity(rName, "4 vCPU"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + resource.TestCheckResourceAttr(resourceName, "maximum_capacity.#", "1"), + resource.TestCheckResourceAttr(resourceName, "maximum_capacity.0.cpu", "4 vCPU"), + resource.TestCheckResourceAttr(resourceName, "maximum_capacity.0.memory", "10 GB")), + }, + }, + }) +} + +func TestAccEMRServerlessApplication_network(t *testing.T) { + var application emrserverless.Application + resourceName := "aws_emrserverless_application.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, emrserverless.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_network(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + resource.TestCheckResourceAttr(resourceName, "network_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_configuration.0.security_group_ids.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_configuration.0.subnet_ids.#", "2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccEMRServerlessApplication_disappears(t *testing.T) { + var application emrserverless.Application + resourceName := "aws_emrserverless_application.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, emrserverless.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + acctest.CheckResourceDisappears(acctest.Provider, tfemrserverless.ResourceApplication(), resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfemrserverless.ResourceApplication(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccEMRServerlessApplication_tags(t *testing.T) { + var application emrserverless.Application + resourceName := "aws_emrserverless_application.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, emrserverless.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckApplicationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccApplicationConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccApplicationConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccApplicationConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckApplicationExists(resourceName, &application), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func testAccCheckApplicationExists(resourceName string, application *emrserverless.Application) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Not found: %s", resourceName) + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).EMRServerlessConn + + output, err := tfemrserverless.FindApplicationByID(conn, rs.Primary.ID) + if err != nil { + return err + } + + if output == nil { + return fmt.Errorf("EMR Serverless Application (%s) not found", rs.Primary.ID) + } + + *application = *output + + return nil + } +} + +func testAccCheckApplicationDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).EMRServerlessConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_emrserverless_application" { + continue + } + + _, err := tfemrserverless.FindApplicationByID(conn, rs.Primary.ID) + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("EMR Serverless Application %s still exists", rs.Primary.ID) + } + return nil +} + +func testAccApplicationConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_emrserverless_application" "test" { + name = %[1]q + release_label = "emr-6.6.0" + type = "hive" +} +`, rName) +} + +func testAccApplicationConfig_initialCapacity(rName, cpu string) string { + return fmt.Sprintf(` +resource "aws_emrserverless_application" "test" { + name = %[1]q + release_label = "emr-6.6.0" + type = "hive" + + initial_capacity { + initial_capacity_type = "HiveDriver" + + initial_capacity_config { + worker_count = 1 + worker_configuration { + cpu = %[2]q + memory = "10 GB" + } + } + } +} +`, rName, cpu) +} + +func testAccApplicationConfig_maxCapacity(rName, cpu string) string { + return fmt.Sprintf(` +resource "aws_emrserverless_application" "test" { + name = %[1]q + release_label = "emr-6.6.0" + type = "hive" + + maximum_capacity { + cpu = %[2]q + memory = "10 GB" + } +} +`, rName, cpu) +} + +func testAccApplicationConfig_network(rName string) string { + return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` +resource "aws_security_group" "test" { + name = %[1]q + description = "Allow all inbound traffic" + vpc_id = aws_vpc.test.id + + ingress { + from_port = 0 + to_port = 0 + protocol = "-1" + self = true + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } +} + +resource "aws_emrserverless_application" "test" { + name = %[1]q + release_label = "emr-6.6.0" + type = "hive" + + network_configuration { + security_group_ids = [aws_security_group.test.id] + subnet_ids = aws_subnet.test[*].id + } +} +`, rName)) +} + +func testAccApplicationConfig_tags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_emrserverless_application" "test" { + name = %[1]q + release_label = "emr-6.6.0" + type = "hive" + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccApplicationConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_emrserverless_application" "test" { + name = %[1]q + release_label = "emr-6.6.0" + type = "hive" + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/internal/service/emrserverless/find.go b/internal/service/emrserverless/find.go new file mode 100644 index 00000000000..e11bb4a3247 --- /dev/null +++ b/internal/service/emrserverless/find.go @@ -0,0 +1,38 @@ +package emrserverless + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/emrserverless" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func FindApplicationByID(conn *emrserverless.EMRServerless, id string) (*emrserverless.Application, error) { + input := &emrserverless.GetApplicationInput{ + ApplicationId: aws.String(id), + } + + output, err := conn.GetApplication(input) + + if tfawserr.ErrCodeEquals(err, emrserverless.ErrCodeResourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || output.Application == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if aws.StringValue(output.Application.State) == emrserverless.ApplicationStateTerminated { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.Application, nil +} diff --git a/internal/service/emrserverless/generate.go b/internal/service/emrserverless/generate.go new file mode 100644 index 00000000000..e77eca73acf --- /dev/null +++ b/internal/service/emrserverless/generate.go @@ -0,0 +1,4 @@ +//go:generate go run ../../generate/tags/main.go -ListTags -ServiceTagsMap -UpdateTags +// ONLY generate directives and package declaration! Do not add anything else to this file. + +package emrserverless diff --git a/internal/service/emrserverless/status.go b/internal/service/emrserverless/status.go new file mode 100644 index 00000000000..6367edda54e --- /dev/null +++ b/internal/service/emrserverless/status.go @@ -0,0 +1,24 @@ +package emrserverless + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/emrserverless" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func statusApplication(conn *emrserverless.EMRServerless, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindApplicationByID(conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.StringValue(output.State), nil + } +} diff --git a/internal/service/emrserverless/sweep.go b/internal/service/emrserverless/sweep.go new file mode 100644 index 00000000000..703e5b29e28 --- /dev/null +++ b/internal/service/emrserverless/sweep.go @@ -0,0 +1,69 @@ +//go:build sweep +// +build sweep + +package emrserverless + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/emrserverless" + "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_emrserverless_application", &resource.Sweeper{ + Name: "aws_emrserverless_application", + F: sweepApplications, + }) +} + +func sweepApplications(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + conn := client.(*conns.AWSClient).EMRServerlessConn + input := &emrserverless.ListApplicationsInput{} + sweepResources := make([]*sweep.SweepResource, 0) + + err = conn.ListApplicationsPages(input, func(page *emrserverless.ListApplicationsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.Applications { + if aws.StringValue(v.State) == emrserverless.ApplicationStateTerminated { + continue + } + + r := ResourceApplication() + d := r.Data(nil) + d.SetId(aws.StringValue(v.Id)) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + return !lastPage + }) + + if sweep.SkipSweepError(err) { + log.Printf("[WARN] Skipping EMR Serverless Application sweep for %s: %s", region, err) + return nil + } + + if err != nil { + return fmt.Errorf("error listing EMR Serverless Applications (%s): %w", region, err) + } + + err = sweep.SweepOrchestrator(sweepResources) + + if err != nil { + return fmt.Errorf("error sweeping EMR Serverless Applications (%s): %w", region, err) + } + + return nil +} diff --git a/internal/service/emrserverless/tags_gen.go b/internal/service/emrserverless/tags_gen.go new file mode 100644 index 00000000000..8833e71db97 --- /dev/null +++ b/internal/service/emrserverless/tags_gen.go @@ -0,0 +1,75 @@ +// Code generated by internal/generate/tags/main.go; DO NOT EDIT. +package emrserverless + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/emrserverless" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" +) + +// ListTags lists emrserverless service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func ListTags(conn *emrserverless.EMRServerless, identifier string) (tftags.KeyValueTags, error) { + input := &emrserverless.ListTagsForResourceInput{ + ResourceArn: aws.String(identifier), + } + + output, err := conn.ListTagsForResource(input) + + if err != nil { + return tftags.New(nil), err + } + + return KeyValueTags(output.Tags), nil +} + +// map[string]*string handling + +// Tags returns emrserverless service tags. +func Tags(tags tftags.KeyValueTags) map[string]*string { + return aws.StringMap(tags.Map()) +} + +// KeyValueTags creates KeyValueTags from emrserverless service tags. +func KeyValueTags(tags map[string]*string) tftags.KeyValueTags { + return tftags.New(tags) +} + +// UpdateTags updates emrserverless service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func UpdateTags(conn *emrserverless.EMRServerless, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error { + oldTags := tftags.New(oldTagsMap) + newTags := tftags.New(newTagsMap) + + if removedTags := oldTags.Removed(newTags); len(removedTags) > 0 { + input := &emrserverless.UntagResourceInput{ + ResourceArn: aws.String(identifier), + TagKeys: aws.StringSlice(removedTags.IgnoreAWS().Keys()), + } + + _, err := conn.UntagResource(input) + + if err != nil { + return fmt.Errorf("error untagging resource (%s): %w", identifier, err) + } + } + + if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 { + input := &emrserverless.TagResourceInput{ + ResourceArn: aws.String(identifier), + Tags: Tags(updatedTags.IgnoreAWS()), + } + + _, err := conn.TagResource(input) + + if err != nil { + return fmt.Errorf("error tagging resource (%s): %w", identifier, err) + } + } + + return nil +} diff --git a/internal/service/emrserverless/wait.go b/internal/service/emrserverless/wait.go new file mode 100644 index 00000000000..e49c39f20fb --- /dev/null +++ b/internal/service/emrserverless/wait.go @@ -0,0 +1,67 @@ +package emrserverless + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/emrserverless" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +const ( + ApplicationCreatedTimeout = 75 * time.Minute + ApplicationCreatedMinTimeout = 10 * time.Second + ApplicationCreatedDelay = 30 * time.Second + + ApplicationDeletedTimeout = 20 * time.Minute + ApplicationDeletedMinTimeout = 10 * time.Second + ApplicationDeletedDelay = 30 * time.Second +) + +func waitApplicationCreated(conn *emrserverless.EMRServerless, id string) (*emrserverless.Application, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{emrserverless.ApplicationStateCreating}, + Target: []string{emrserverless.ApplicationStateCreated}, + Refresh: statusApplication(conn, id), + Timeout: ApplicationCreatedTimeout, + MinTimeout: ApplicationCreatedMinTimeout, + Delay: ApplicationCreatedDelay, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*emrserverless.Application); ok { + if stateChangeReason := output.StateDetails; stateChangeReason != nil { + tfresource.SetLastError(err, fmt.Errorf(aws.StringValue(stateChangeReason))) + } + + return output, err + } + + return nil, err +} + +func waitApplicationTerminated(conn *emrserverless.EMRServerless, id string) (*emrserverless.Application, error) { + stateConf := &resource.StateChangeConf{ + Pending: emrserverless.ApplicationState_Values(), + Target: []string{}, + Refresh: statusApplication(conn, id), + Timeout: ApplicationDeletedTimeout, + MinTimeout: ApplicationDeletedMinTimeout, + Delay: ApplicationDeletedDelay, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*emrserverless.Application); ok { + if stateChangeReason := output.StateDetails; stateChangeReason != nil { + tfresource.SetLastError(err, fmt.Errorf(aws.StringValue(stateChangeReason))) + } + + return output, err + } + + return nil, err +} diff --git a/internal/service/events/api_destination.go b/internal/service/events/api_destination.go index 2a7f8ae14fe..789b6436d11 100644 --- a/internal/service/events/api_destination.go +++ b/internal/service/events/api_destination.go @@ -46,7 +46,7 @@ func ResourceAPIDestination() *schema.Resource { "invocation_rate_limit_per_second": { Type: schema.TypeInt, Optional: true, - ValidateFunc: validation.IntBetween(1, 300), + ValidateFunc: validation.IntAtLeast(1), Default: 300, }, "http_method": { @@ -91,11 +91,9 @@ func resourceAPIDestinationCreate(d *schema.ResourceData, meta interface{}) erro input.ConnectionArn = aws.String(connectionArn.(string)) } - log.Printf("[DEBUG] Creating EventBridge API Destination: %v", input) - _, err := conn.CreateApiDestination(input) if err != nil { - return fmt.Errorf("Creating EventBridge API Destination (%s) failed: %w", *input.Name, err) + return fmt.Errorf("Creating EventBridge API Destination (%s) failed: %w", aws.StringValue(input.Name), err) } d.SetId(aws.StringValue(input.Name)) @@ -112,19 +110,16 @@ func resourceAPIDestinationRead(d *schema.ResourceData, meta interface{}) error Name: aws.String(d.Id()), } - log.Printf("[DEBUG] Reading EventBridge API Destination (%s)", d.Id()) output, err := conn.DescribeApiDestination(input) - if tfawserr.ErrCodeEquals(err, eventbridge.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, eventbridge.ErrCodeResourceNotFoundException) { log.Printf("[WARN] EventBridge API Destination (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("error reading EventBridge API Destination: %w", err) + return fmt.Errorf("error reading EventBridge API Destination (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] Found EventBridge API Destination: %#v", *output) - d.Set("arn", output.ApiDestinationArn) d.Set("name", output.Name) d.Set("description", output.Description) diff --git a/internal/service/events/api_destination_test.go b/internal/service/events/api_destination_test.go index 6addbbbcf61..5f91d2a6329 100644 --- a/internal/service/events/api_destination_test.go +++ b/internal/service/events/api_destination_test.go @@ -36,7 +36,7 @@ func TestAccEventsAPIDestination_basic(t *testing.T) { CheckDestroy: testAccCheckAPIDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIDestinationConfig( + Config: testAccAPIDestinationConfig_basic( name, invocationEndpoint, httpMethod, @@ -55,7 +55,7 @@ func TestAccEventsAPIDestination_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAPIDestinationConfig( + Config: testAccAPIDestinationConfig_basic( nameModified, invocationEndpointModified, httpMethodModified, @@ -70,7 +70,7 @@ func TestAccEventsAPIDestination_basic(t *testing.T) { ), }, { - Config: testAccAPIDestinationConfig( + Config: testAccAPIDestinationConfig_basic( nameModified, invocationEndpointModified, httpMethodModified, @@ -185,7 +185,7 @@ func TestAccEventsAPIDestination_disappears(t *testing.T) { CheckDestroy: testAccCheckAPIDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccAPIDestinationConfig( + Config: testAccAPIDestinationConfig_basic( name, invocationEndpoint, httpMethod, @@ -265,7 +265,7 @@ func testAccCheckAPIDestinationNotRecreated(i, j *eventbridge.DescribeApiDestina } } -func testAccAPIDestinationConfig(name, invocationEndpoint, httpMethod string) string { +func testAccAPIDestinationConfig_basic(name, invocationEndpoint, httpMethod string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_api_destination" "basic" { name = %[1]q diff --git a/internal/service/events/archive.go b/internal/service/events/archive.go index 229a1f1952e..74d6ff68b85 100644 --- a/internal/service/events/archive.go +++ b/internal/service/events/archive.go @@ -94,18 +94,16 @@ func resourceArchiveRead(d *schema.ResourceData, meta interface{}) error { out, err := conn.DescribeArchive(input) - if tfawserr.ErrCodeEquals(err, eventbridge.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, eventbridge.ErrCodeResourceNotFoundException) { log.Printf("[WARN] EventBridge archive (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("Error reading EventBridge archive: %w", err) + return fmt.Errorf("Error reading EventBridge archive (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] Found Archive: #{*out}") - d.Set("name", out.ArchiveName) d.Set("description", out.Description) d.Set("event_pattern", out.EventPattern) diff --git a/internal/service/events/archive_test.go b/internal/service/events/archive_test.go index d47f12c564b..bfc614750bd 100644 --- a/internal/service/events/archive_test.go +++ b/internal/service/events/archive_test.go @@ -26,7 +26,7 @@ func TestAccEventsArchive_basic(t *testing.T) { CheckDestroy: testAccCheckArchiveDestroy, Steps: []resource.TestStep{ { - Config: testAccArchiveConfig(archiveName), + Config: testAccArchiveConfig_basic(archiveName), Check: resource.ComposeTestCheckFunc( testAccCheckArchiveExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "name", archiveName), @@ -57,7 +57,7 @@ func TestAccEventsArchive_update(t *testing.T) { CheckDestroy: testAccCheckArchiveDestroy, Steps: []resource.TestStep{ { - Config: testAccArchiveConfig(archiveName), + Config: testAccArchiveConfig_basic(archiveName), Check: resource.ComposeTestCheckFunc( testAccCheckArchiveExists(resourceName, &v1), ), @@ -87,7 +87,7 @@ func TestAccEventsArchive_disappears(t *testing.T) { CheckDestroy: testAccCheckArchiveDestroy, Steps: []resource.TestStep{ { - Config: testAccArchiveConfig(archiveName), + Config: testAccArchiveConfig_basic(archiveName), Check: resource.ComposeTestCheckFunc( testAccCheckArchiveExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfevents.ResourceArchive(), resourceName), @@ -178,7 +178,7 @@ func TestAccEventsArchive_retentionSetOnCreation(t *testing.T) { }) } -func testAccArchiveConfig(name string) string { +func testAccArchiveConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q diff --git a/internal/service/events/bus.go b/internal/service/events/bus.go index fce25ed8a79..db566ec6469 100644 --- a/internal/service/events/bus.go +++ b/internal/service/events/bus.go @@ -71,7 +71,7 @@ func resourceBusCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateEventBus(input) // Some partitions may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] EventBridge Bus (%s) create failed (%s) with tags. Trying create without tags.", eventBusName, err) input.Tags = nil output, err = conn.CreateEventBus(input) @@ -89,7 +89,7 @@ func resourceBusCreate(d *schema.ResourceData, meta interface{}) error { if input.Tags == nil && len(tags) > 0 { err := UpdateTags(conn, aws.StringValue(output.EventBusArn), nil, tags) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] error adding tags after create for EventBridge Bus (%s): %s", d.Id(), err) return resourceBusRead(d, meta) } @@ -111,9 +111,8 @@ func resourceBusRead(d *schema.ResourceData, meta interface{}) error { Name: aws.String(d.Id()), } - log.Printf("[DEBUG] Reading EventBridge event bus (%s)", d.Id()) output, err := conn.DescribeEventBus(input) - if tfawserr.ErrCodeEquals(err, eventbridge.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, eventbridge.ErrCodeResourceNotFoundException) { log.Printf("[WARN] EventBridge event bus (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -122,15 +121,13 @@ func resourceBusRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error reading EventBridge event bus: %w", err) } - log.Printf("[DEBUG] Found EventBridge bus: %#v", *output) - d.Set("arn", output.Arn) d.Set("name", output.Name) tags, err := ListTags(conn, aws.StringValue(output.Arn)) // ISO partitions may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to list tags for EventBridge Bus %s: %s", d.Id(), err) return nil } @@ -162,7 +159,7 @@ func resourceBusUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, arn, o, n) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to update tags for EventBridge Bus %s: %s", d.Id(), err) return resourceBusRead(d, meta) } diff --git a/internal/service/events/bus_policy.go b/internal/service/events/bus_policy.go index d323ccc5b1b..0da0611dea2 100644 --- a/internal/service/events/bus_policy.go +++ b/internal/service/events/bus_policy.go @@ -113,8 +113,8 @@ func resourceBusPolicyRead(d *schema.ResourceData, meta interface{}) error { } } - if tfresource.NotFound(err) { - log.Printf("[WARN] Policy on {%s} EventBus not found, removing from state", d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Policy on EventBridge Bus (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -142,7 +142,7 @@ func resourceBusPolicyRead(d *schema.ResourceData, meta interface{}) error { func getEventBusPolicy(output *eventbridge.DescribeEventBusOutput) (*string, error) { if output == nil || output.Policy == nil { return nil, &resource.NotFoundError{ - Message: fmt.Sprintf("Policy for EventBridge Bus %s not found", *output.Name), + Message: fmt.Sprintf("Policy for EventBridge Bus (%s) not found", *output.Name), LastResponse: output, } } @@ -168,11 +168,6 @@ func resourceBusPolicyUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Update EventBridge Bus policy: %s", input) _, err = conn.PutPermission(&input) - if tfawserr.ErrCodeEquals(err, eventbridge.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] EventBridge Bus %q not found, removing from state", d.Id()) - d.SetId("") - return nil - } if err != nil { return fmt.Errorf("error updating policy for EventBridge Bus (%s): %w", d.Id(), err) } diff --git a/internal/service/events/bus_policy_test.go b/internal/service/events/bus_policy_test.go index d16a13e41df..0964bbabac1 100644 --- a/internal/service/events/bus_policy_test.go +++ b/internal/service/events/bus_policy_test.go @@ -26,14 +26,14 @@ func TestAccEventsBusPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckBusDestroy, Steps: []resource.TestStep{ { - Config: testAccBusPolicyConfig(rstring), + Config: testAccBusPolicyConfig_basic(rstring), Check: resource.ComposeTestCheckFunc( testAccCheckBusPolicyExists(resourceName), testAccBusPolicyDocument(resourceName), ), }, { - Config: testAccBusPolicyUpdateConfig(rstring), + Config: testAccBusPolicyConfig_update(rstring), Check: resource.ComposeTestCheckFunc( testAccCheckBusPolicyExists(resourceName), testAccBusPolicyDocument(resourceName), @@ -59,14 +59,14 @@ func TestAccEventsBusPolicy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckBusDestroy, Steps: []resource.TestStep{ { - Config: testAccBusPolicyOrderConfig(rName), + Config: testAccBusPolicyConfig_order(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBusPolicyExists(resourceName), testAccBusPolicyDocument(resourceName), ), }, { - Config: testAccBusPolicyNewOrderConfig(rName), + Config: testAccBusPolicyConfig_newOrder(rName), PlanOnly: true, }, }, @@ -84,7 +84,7 @@ func TestAccEventsBusPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckBusDestroy, Steps: []resource.TestStep{ { - Config: testAccBusPolicyConfig(rstring), + Config: testAccBusPolicyConfig_basic(rstring), Check: resource.ComposeTestCheckFunc( testAccCheckBusPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfevents.ResourceBusPolicy(), resourceName), @@ -161,7 +161,7 @@ func testAccBusPolicyDocument(pr string) resource.TestCheckFunc { } } -func testAccBusPolicyConfig(name string) string { +func testAccBusPolicyConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q @@ -192,7 +192,7 @@ resource "aws_cloudwatch_event_bus_policy" "test" { `, name) } -func testAccBusPolicyUpdateConfig(name string) string { +func testAccBusPolicyConfig_update(name string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q @@ -236,7 +236,7 @@ resource "aws_cloudwatch_event_bus_policy" "test" { `, name) } -func testAccBusPolicyOrderConfig(rName string) string { +func testAccBusPolicyConfig_order(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q @@ -270,7 +270,7 @@ resource "aws_cloudwatch_event_bus_policy" "test" { `, rName) } -func testAccBusPolicyNewOrderConfig(rName string) string { +func testAccBusPolicyConfig_newOrder(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q diff --git a/internal/service/events/bus_test.go b/internal/service/events/bus_test.go index 13fb76e4f03..19e753673a4 100644 --- a/internal/service/events/bus_test.go +++ b/internal/service/events/bus_test.go @@ -30,7 +30,7 @@ func TestAccEventsBus_basic(t *testing.T) { CheckDestroy: testAccCheckBusDestroy, Steps: []resource.TestStep{ { - Config: testAccBusConfig(busName), + Config: testAccBusConfig_basic(busName), Check: resource.ComposeTestCheckFunc( testAccCheckBusExists(resourceName, &v1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "events", fmt.Sprintf("event-bus/%s", busName)), @@ -45,7 +45,7 @@ func TestAccEventsBus_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBusConfig(busNameModified), + Config: testAccBusConfig_basic(busNameModified), Check: resource.ComposeTestCheckFunc( testAccCheckBusExists(resourceName, &v2), testAccCheckBusRecreated(&v1, &v2), @@ -56,7 +56,7 @@ func TestAccEventsBus_basic(t *testing.T) { ), }, { - Config: testAccBusConfig_Tags1(busNameModified, "key", "value"), + Config: testAccBusConfig_tags1(busNameModified, "key", "value"), Check: resource.ComposeTestCheckFunc( testAccCheckBusExists(resourceName, &v3), testAccCheckBusNotRecreated(&v2, &v3), @@ -81,7 +81,7 @@ func TestAccEventsBus_tags(t *testing.T) { CheckDestroy: testAccCheckBusDestroy, Steps: []resource.TestStep{ { - Config: testAccBusConfig_Tags1(busName, "key1", "value"), + Config: testAccBusConfig_tags1(busName, "key1", "value"), Check: resource.ComposeTestCheckFunc( testAccCheckBusExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -94,7 +94,7 @@ func TestAccEventsBus_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBusConfig_Tags2(busName, "key1", "updated", "key2", "added"), + Config: testAccBusConfig_tags2(busName, "key1", "updated", "key2", "added"), Check: resource.ComposeTestCheckFunc( testAccCheckBusExists(resourceName, &v2), testAccCheckBusNotRecreated(&v1, &v2), @@ -104,7 +104,7 @@ func TestAccEventsBus_tags(t *testing.T) { ), }, { - Config: testAccBusConfig_Tags1(busName, "key2", "added"), + Config: testAccBusConfig_tags1(busName, "key2", "added"), Check: resource.ComposeTestCheckFunc( testAccCheckBusExists(resourceName, &v3), testAccCheckBusNotRecreated(&v2, &v3), @@ -113,7 +113,7 @@ func TestAccEventsBus_tags(t *testing.T) { ), }, { - Config: testAccBusConfig(busName), + Config: testAccBusConfig_basic(busName), Check: resource.ComposeTestCheckFunc( testAccCheckBusExists(resourceName, &v4), testAccCheckBusNotRecreated(&v3, &v4), @@ -132,7 +132,7 @@ func TestAccEventsBus_default(t *testing.T) { CheckDestroy: testAccCheckBusDestroy, Steps: []resource.TestStep{ { - Config: testAccBusConfig("default"), + Config: testAccBusConfig_basic("default"), ExpectError: regexp.MustCompile(`cannot be 'default'`), }, }, @@ -152,7 +152,7 @@ func TestAccEventsBus_disappears(t *testing.T) { CheckDestroy: testAccCheckBusDestroy, Steps: []resource.TestStep{ { - Config: testAccBusConfig(busName), + Config: testAccBusConfig_basic(busName), Check: resource.ComposeTestCheckFunc( testAccCheckBusExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfevents.ResourceBus(), resourceName), @@ -258,7 +258,7 @@ func testAccCheckBusNotRecreated(i, j *eventbridge.DescribeEventBusOutput) resou } } -func testAccBusConfig(name string) string { +func testAccBusConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q @@ -266,7 +266,7 @@ resource "aws_cloudwatch_event_bus" "test" { `, name) } -func testAccBusConfig_Tags1(name, key, value string) string { +func testAccBusConfig_tags1(name, key, value string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q @@ -278,7 +278,7 @@ resource "aws_cloudwatch_event_bus" "test" { `, name, key, value) } -func testAccBusConfig_Tags2(name, key1, value1, key2, value2 string) string { +func testAccBusConfig_tags2(name, key1, value1, key2, value2 string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q diff --git a/internal/service/events/connection_data_source_test.go b/internal/service/events/connection_data_source_test.go index c969a54a1bb..10119510ed3 100644 --- a/internal/service/events/connection_data_source_test.go +++ b/internal/service/events/connection_data_source_test.go @@ -24,7 +24,7 @@ func TestAccEventsConnectionDataSource_Connection_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAcc_ConnectionDataConfig( + Config: testAccConnectDataSourceConfig_basic( name, description, authorizationType, @@ -42,7 +42,7 @@ func TestAccEventsConnectionDataSource_Connection_basic(t *testing.T) { }) } -func testAcc_ConnectionDataConfig(name, description, authorizationType, key, value string) string { +func testAccConnectDataSourceConfig_basic(name, description, authorizationType, key, value string) string { return acctest.ConfigCompose( testAccConnectionConfig_apiKey(name, description, authorizationType, key, value), ` diff --git a/internal/service/events/permission.go b/internal/service/events/permission.go index dd0e227ace1..e06e373d2f2 100644 --- a/internal/service/events/permission.go +++ b/internal/service/events/permission.go @@ -143,7 +143,7 @@ func resourcePermissionRead(d *schema.ResourceData, meta interface{}) error { } } - if tfresource.NotFound(err) { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EventBridge permission (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -220,13 +220,7 @@ func resourcePermissionUpdate(d *schema.ResourceData, meta interface{}) error { StatementId: aws.String(statementID), } - log.Printf("[DEBUG] Update EventBridge permission: %s", input) _, err = conn.PutPermission(&input) - if tfawserr.ErrCodeEquals(err, eventbridge.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] EventBridge permission %q not found, removing from state", d.Id()) - d.SetId("") - return nil - } if err != nil { return fmt.Errorf("error updating EventBridge permission (%s): %w", d.Id(), err) } diff --git a/internal/service/events/permission_test.go b/internal/service/events/permission_test.go index b1d4e27a341..70ed2a8ae35 100644 --- a/internal/service/events/permission_test.go +++ b/internal/service/events/permission_test.go @@ -31,35 +31,35 @@ func TestAccEventsPermission_basic(t *testing.T) { CheckDestroy: testAccCheckPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPermissionResourceBasicConfig("", statementID), + Config: testAccPermissionConfig_basic("", statementID), ExpectError: regexp.MustCompile(`must be \* or a 12 digit AWS account ID`), }, { - Config: testAccCheckPermissionResourceBasicConfig(".", statementID), + Config: testAccPermissionConfig_basic(".", statementID), ExpectError: regexp.MustCompile(`must be \* or a 12 digit AWS account ID`), }, { - Config: testAccCheckPermissionResourceBasicConfig("12345678901", statementID), + Config: testAccPermissionConfig_basic("12345678901", statementID), ExpectError: regexp.MustCompile(`must be \* or a 12 digit AWS account ID`), }, { - Config: testAccCheckPermissionResourceBasicConfig("abcdefghijkl", statementID), + Config: testAccPermissionConfig_basic("abcdefghijkl", statementID), ExpectError: regexp.MustCompile(`must be \* or a 12 digit AWS account ID`), }, { - Config: testAccCheckPermissionResourceBasicConfig(principal1, ""), + Config: testAccPermissionConfig_basic(principal1, ""), ExpectError: regexp.MustCompile(`must be between 1 and 64 characters`), }, { - Config: testAccCheckPermissionResourceBasicConfig(principal1, sdkacctest.RandString(65)), + Config: testAccPermissionConfig_basic(principal1, sdkacctest.RandString(65)), ExpectError: regexp.MustCompile(`must be between 1 and 64 characters`), }, { - Config: testAccCheckPermissionResourceBasicConfig(principal1, " "), + Config: testAccPermissionConfig_basic(principal1, " "), ExpectError: regexp.MustCompile(`must be one or more alphanumeric, hyphen, or underscore characters`), }, { - Config: testAccCheckPermissionResourceBasicConfig(principal1, statementID), + Config: testAccPermissionConfig_basic(principal1, statementID), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "action", "events:PutEvents"), @@ -70,7 +70,7 @@ func TestAccEventsPermission_basic(t *testing.T) { ), }, { - Config: testAccCheckPermissionResourceBasicConfig(principal2, statementID), + Config: testAccPermissionConfig_basic(principal2, statementID), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "principal", principal2), @@ -82,7 +82,7 @@ func TestAccEventsPermission_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCheckPermissionResourceDefaultEventBusNameConfig(principal2, statementID), + Config: testAccPermissionConfig_defaultBusName(principal2, statementID), PlanOnly: true, }, }, @@ -103,7 +103,7 @@ func TestAccEventsPermission_eventBusName(t *testing.T) { CheckDestroy: testAccCheckPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPermissionResourceEventBusNameConfig(principal1, busName, statementID), + Config: testAccPermissionConfig_eventBusName(principal1, busName, statementID), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "action", "events:PutEvents"), @@ -134,23 +134,23 @@ func TestAccEventsPermission_action(t *testing.T) { CheckDestroy: testAccCheckPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPermissionResourceActionConfig("", principal, statementID), + Config: testAccPermissionConfig_action("", principal, statementID), ExpectError: regexp.MustCompile(`must be between 1 and 64 characters`), }, { - Config: testAccCheckPermissionResourceActionConfig(sdkacctest.RandString(65), principal, statementID), + Config: testAccPermissionConfig_action(sdkacctest.RandString(65), principal, statementID), ExpectError: regexp.MustCompile(`must be between 1 and 64 characters`), }, { - Config: testAccCheckPermissionResourceActionConfig("events:", principal, statementID), + Config: testAccPermissionConfig_action("events:", principal, statementID), ExpectError: regexp.MustCompile(`must be: events: followed by one or more alphabetic characters`), }, { - Config: testAccCheckPermissionResourceActionConfig("events:1", principal, statementID), + Config: testAccPermissionConfig_action("events:1", principal, statementID), ExpectError: regexp.MustCompile(`must be: events: followed by one or more alphabetic characters`), }, { - Config: testAccCheckPermissionResourceActionConfig("events:PutEvents", principal, statementID), + Config: testAccPermissionConfig_action("events:PutEvents", principal, statementID), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "action", "events:PutEvents"), @@ -176,7 +176,7 @@ func TestAccEventsPermission_condition(t *testing.T) { CheckDestroy: testAccCheckPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPermissionResourceConditionOrganizationConfig(statementID, "o-1234567890"), + Config: testAccPermissionConfig_conditionOrganization(statementID, "o-1234567890"), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), @@ -186,7 +186,7 @@ func TestAccEventsPermission_condition(t *testing.T) { ), }, { - Config: testAccCheckPermissionResourceConditionOrganizationConfig(statementID, "o-0123456789"), + Config: testAccPermissionConfig_conditionOrganization(statementID, "o-0123456789"), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), @@ -219,7 +219,7 @@ func TestAccEventsPermission_multiple(t *testing.T) { CheckDestroy: testAccCheckPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPermissionResourceBasicConfig(principal1, statementID1), + Config: testAccPermissionConfig_basic(principal1, statementID1), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName1), resource.TestCheckResourceAttr(resourceName1, "principal", principal1), @@ -227,7 +227,7 @@ func TestAccEventsPermission_multiple(t *testing.T) { ), }, { - Config: testAccCheckPermissionResourceMultipleConfig(principal1, statementID1, principal2, statementID2), + Config: testAccPermissionConfig_multiple(principal1, statementID1, principal2, statementID2), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName1), testAccCheckPermissionExists(resourceName2), @@ -253,7 +253,7 @@ func TestAccEventsPermission_disappears(t *testing.T) { CheckDestroy: testAccCheckPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPermissionResourceBasicConfig(principal, statementID), + Config: testAccPermissionConfig_basic(principal, statementID), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfevents.ResourcePermission(), resourceName), @@ -352,7 +352,7 @@ func testAccCheckPermissionDestroy(s *terraform.State) error { return nil } -func testAccCheckPermissionResourceBasicConfig(principal, statementID string) string { +func testAccPermissionConfig_basic(principal, statementID string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_permission" "test" { principal = "%[1]s" @@ -361,7 +361,7 @@ resource "aws_cloudwatch_event_permission" "test" { `, principal, statementID) } -func testAccCheckPermissionResourceDefaultEventBusNameConfig(principal, statementID string) string { +func testAccPermissionConfig_defaultBusName(principal, statementID string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_permission" "test" { principal = %[1]q @@ -371,7 +371,7 @@ resource "aws_cloudwatch_event_permission" "test" { `, principal, statementID) } -func testAccCheckPermissionResourceEventBusNameConfig(principal, busName, statementID string) string { +func testAccPermissionConfig_eventBusName(principal, busName, statementID string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_permission" "test" { principal = %[1]q @@ -385,7 +385,7 @@ resource "aws_cloudwatch_event_bus" "test" { `, principal, statementID, busName) } -func testAccCheckPermissionResourceActionConfig(action, principal, statementID string) string { +func testAccPermissionConfig_action(action, principal, statementID string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_permission" "test" { action = "%[1]s" @@ -395,7 +395,7 @@ resource "aws_cloudwatch_event_permission" "test" { `, action, principal, statementID) } -func testAccCheckPermissionResourceConditionOrganizationConfig(statementID, value string) string { +func testAccPermissionConfig_conditionOrganization(statementID, value string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_permission" "test" { principal = "*" @@ -410,7 +410,7 @@ resource "aws_cloudwatch_event_permission" "test" { `, statementID, value) } -func testAccCheckPermissionResourceMultipleConfig(principal1, statementID1, principal2, statementID2 string) string { +func testAccPermissionConfig_multiple(principal1, statementID1, principal2, statementID2 string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_permission" "test" { principal = "%[1]s" diff --git a/internal/service/events/rule.go b/internal/service/events/rule.go index 8a18c8e0ab3..29ff679e6c1 100644 --- a/internal/service/events/rule.go +++ b/internal/service/events/rule.go @@ -123,7 +123,7 @@ func resourceRuleCreate(d *schema.ResourceData, meta interface{}) error { arn, err := retryPutRule(conn, input) // Some partitions may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] EventBridge Rule (%s) create failed (%s) with tags. Trying create without tags.", name, err) input.Tags = nil arn, err = retryPutRule(conn, input) @@ -139,7 +139,7 @@ func resourceRuleCreate(d *schema.ResourceData, meta interface{}) error { if input.Tags == nil && len(tags) > 0 { err := UpdateTags(conn, arn, nil, tags) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] error adding tags after create for EventBridge Rule (%s): %s", d.Id(), err) return resourceRuleRead(d, meta) } @@ -202,7 +202,7 @@ func resourceRuleRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, arn) // ISO partitions may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to list tags for EventBridge Rule %s: %s", d.Id(), err) return nil } @@ -269,7 +269,7 @@ func resourceRuleUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, arn, o, n) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] Unable to update tags for EventBridge Rule %s: %s", d.Id(), err) return resourceRuleRead(d, meta) } @@ -404,9 +404,9 @@ func validateEventPatternValue() schema.SchemaValidateFunc { } // Check whether the normalized JSON is within the given length. - const maxJsonLength = 2048 - if len(json) > maxJsonLength { - errors = append(errors, fmt.Errorf("%q cannot be longer than %d characters: %q", k, maxJsonLength, json)) + const maxJSONLength = 2048 + if len(json) > maxJSONLength { + errors = append(errors, fmt.Errorf("%q cannot be longer than %d characters: %q", k, maxJSONLength, json)) } return } diff --git a/internal/service/events/rule_test.go b/internal/service/events/rule_test.go index 3c6895ce9b9..8be4949c0db 100644 --- a/internal/service/events/rule_test.go +++ b/internal/service/events/rule_test.go @@ -43,7 +43,7 @@ func TestAccEventsRule_basic(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleConfig(rName), + Config: testAccRuleConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "events", regexp.MustCompile(fmt.Sprintf(`rule/%s$`, rName))), @@ -71,7 +71,7 @@ func TestAccEventsRule_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRuleConfig(rName2), + Config: testAccRuleConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v2), testAccCheckRuleRecreated(&v1, &v2), @@ -86,7 +86,7 @@ func TestAccEventsRule_basic(t *testing.T) { ), }, { - Config: testAccRuleDefaultEventBusNameConfig(rName2), + Config: testAccRuleConfig_defaultBusName(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v3), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "events", regexp.MustCompile(fmt.Sprintf(`rule/%s$`, rName2))), @@ -114,7 +114,7 @@ func TestAccEventsRule_eventBusName(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleEventBusNameConfig(rName, busName, "description 1"), + Config: testAccRuleConfig_busName(rName, busName, "description 1"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -128,7 +128,7 @@ func TestAccEventsRule_eventBusName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRuleEventBusNameConfig(rName, busName, "description 2"), + Config: testAccRuleConfig_busName(rName, busName, "description 2"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v2), testAccCheckRuleNotRecreated(&v1, &v2), @@ -137,7 +137,7 @@ func TestAccEventsRule_eventBusName(t *testing.T) { ), }, { - Config: testAccRuleEventBusNameConfig(rName2, busName2, "description 2"), + Config: testAccRuleConfig_busName(rName2, busName2, "description 2"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v3), testAccCheckRuleRecreated(&v2, &v3), @@ -164,7 +164,7 @@ func TestAccEventsRule_role(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleRoleConfig(rName), + Config: testAccRuleConfig_role(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -192,7 +192,7 @@ func TestAccEventsRule_description(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleDescriptionConfig(rName, "description1"), + Config: testAccRuleConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -205,7 +205,7 @@ func TestAccEventsRule_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRuleDescriptionConfig(rName, "description2"), + Config: testAccRuleConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -228,7 +228,7 @@ func TestAccEventsRule_pattern(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRulePatternConfig(rName, "{\"source\":[\"aws.ec2\"]}"), + Config: testAccRuleConfig_pattern(rName, "{\"source\":[\"aws.ec2\"]}"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -242,7 +242,7 @@ func TestAccEventsRule_pattern(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRulePatternConfig(rName, "{\"source\":[\"aws.lambda\"]}"), + Config: testAccRuleConfig_pattern(rName, "{\"source\":[\"aws.lambda\"]}"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -265,7 +265,7 @@ func TestAccEventsRule_scheduleAndPattern(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleScheduleAndPatternConfig(rName, "{\"source\":[\"aws.ec2\"]}"), + Config: testAccRuleConfig_scheduleAndPattern(rName, "{\"source\":[\"aws.ec2\"]}"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -294,7 +294,7 @@ func TestAccEventsRule_namePrefix(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleNamePrefixConfig(rName), + Config: testAccRuleConfig_namePrefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", rName), @@ -321,7 +321,7 @@ func TestAccEventsRule_Name_generated(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleNameGeneratedConfig, + Config: testAccRuleConfig_nameGenerated, Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -349,7 +349,7 @@ func TestAccEventsRule_tags(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleTags1Config(rName, "key1", "value1"), + Config: testAccRuleConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -362,7 +362,7 @@ func TestAccEventsRule_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRuleTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccRuleConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -371,7 +371,7 @@ func TestAccEventsRule_tags(t *testing.T) { ), }, { - Config: testAccRuleTags1Config(rName, "key2", "value2"), + Config: testAccRuleConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -379,7 +379,7 @@ func TestAccEventsRule_tags(t *testing.T) { ), }, { - Config: testAccRuleTags0Config(rName), + Config: testAccRuleConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v3), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -401,7 +401,7 @@ func TestAccEventsRule_isEnabled(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleIsEnabledConfig(rName, false), + Config: testAccRuleConfig_isEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "is_enabled", "false"), @@ -414,7 +414,7 @@ func TestAccEventsRule_isEnabled(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRuleIsEnabledConfig(rName, true), + Config: testAccRuleConfig_isEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "is_enabled", "true"), @@ -422,7 +422,7 @@ func TestAccEventsRule_isEnabled(t *testing.T) { ), }, { - Config: testAccRuleIsEnabledConfig(rName, false), + Config: testAccRuleConfig_isEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v3), resource.TestCheckResourceAttr(resourceName, "is_enabled", "false"), @@ -451,7 +451,7 @@ func TestAccEventsRule_partnerEventBus(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRulePartnerEventBusConfig(rName, busName), + Config: testAccRuleConfig_partnerBus(rName, busName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "events", regexp.MustCompile(fmt.Sprintf(`rule/%s/%s$`, busName, rName))), @@ -487,7 +487,7 @@ func TestAccEventsRule_eventBusARN(t *testing.T) { CheckDestroy: testAccCheckRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleEventBusARN(rName, eventBusName), + Config: testAccRuleConfig_busARN(rName, eventBusName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "events", regexp.MustCompile(fmt.Sprintf(`rule/%s/%s$`, eventBusName, rName))), @@ -611,7 +611,7 @@ func testAccRuleNoBusNameImportStateIdFunc(resourceName string) resource.ImportS } } -func testAccRuleConfig(name string) string { +func testAccRuleConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%s" @@ -620,7 +620,7 @@ resource "aws_cloudwatch_event_rule" "test" { `, name) } -func testAccRuleDefaultEventBusNameConfig(name string) string { +func testAccRuleConfig_defaultBusName(name string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = %[1]q @@ -630,7 +630,7 @@ resource "aws_cloudwatch_event_rule" "test" { `, name) } -func testAccRuleEventBusNameConfig(name, eventBusName, description string) string { +func testAccRuleConfig_busName(name, eventBusName, description string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = %[1]q @@ -651,7 +651,7 @@ resource "aws_cloudwatch_event_bus" "test" { `, name, description, eventBusName) } -func testAccRulePatternConfig(name, pattern string) string { +func testAccRuleConfig_pattern(name, pattern string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%s" @@ -662,7 +662,7 @@ PATTERN `, name, pattern) } -func testAccRuleScheduleAndPatternConfig(name, pattern string) string { +func testAccRuleConfig_scheduleAndPattern(name, pattern string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%s" @@ -674,7 +674,7 @@ PATTERN `, name, pattern) } -func testAccRuleDescriptionConfig(name, description string) string { +func testAccRuleConfig_description(name, description string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = %[1]q @@ -684,7 +684,7 @@ resource "aws_cloudwatch_event_rule" "test" { `, name, description) } -func testAccRuleIsEnabledConfig(name string, enabled bool) string { +func testAccRuleConfig_isEnabled(name string, enabled bool) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%s" @@ -694,7 +694,7 @@ resource "aws_cloudwatch_event_rule" "test" { `, name, enabled) } -func testAccRuleNamePrefixConfig(name string) string { +func testAccRuleConfig_namePrefix(name string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name_prefix = "%s" @@ -703,13 +703,13 @@ resource "aws_cloudwatch_event_rule" "test" { `, name) } -const testAccRuleNameGeneratedConfig = ` +const testAccRuleConfig_nameGenerated = ` resource "aws_cloudwatch_event_rule" "test" { schedule_expression = "rate(5 minutes)" } ` -func testAccRuleTags1Config(name, tagKey1, tagValue1 string) string { +func testAccRuleConfig_tags1(name, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = %[1]q @@ -722,7 +722,7 @@ resource "aws_cloudwatch_event_rule" "test" { `, name, tagKey1, tagValue1) } -func testAccRuleTags2Config(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccRuleConfig_tags2(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = %[1]q @@ -736,7 +736,7 @@ resource "aws_cloudwatch_event_rule" "test" { `, name, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccRuleTags0Config(name string) string { +func testAccRuleConfig_tags0(name string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = %[1]q @@ -745,7 +745,7 @@ resource "aws_cloudwatch_event_rule" "test" { `, name) } -func testAccRuleRoleConfig(name string) string { +func testAccRuleConfig_role(name string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -775,7 +775,7 @@ resource "aws_cloudwatch_event_rule" "test" { `, name) } -func testAccRulePartnerEventBusConfig(rName, eventBusName string) string { +func testAccRuleConfig_partnerBus(rName, eventBusName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = %[1]q @@ -790,7 +790,7 @@ PATTERN `, rName, eventBusName) } -func testAccRuleEventBusARN(rName, eventBusName string) string { +func testAccRuleConfig_busARN(rName, eventBusName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[2]q diff --git a/internal/service/events/source_data_source_test.go b/internal/service/events/source_data_source_test.go index cd04227340c..23e17f6fc5a 100644 --- a/internal/service/events/source_data_source_test.go +++ b/internal/service/events/source_data_source_test.go @@ -32,7 +32,7 @@ func TestAccEventsSourceDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSourceDataSourceConfig_partnerEvent(busName), + Config: testAccSourceDataSourceConfig_partner(busName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "name", busName), resource.TestCheckResourceAttr(dataSourceName, "created_by", createdBy), @@ -43,7 +43,7 @@ func TestAccEventsSourceDataSource_basic(t *testing.T) { }) } -func testAccSourceDataSourceConfig_partnerEvent(namePrefix string) string { +func testAccSourceDataSourceConfig_partner(namePrefix string) string { return fmt.Sprintf(` data "aws_cloudwatch_event_source" "test" { name_prefix = "%s" diff --git a/internal/service/events/target.go b/internal/service/events/target.go index 945c749baf7..edeabbd2063 100644 --- a/internal/service/events/target.go +++ b/internal/service/events/target.go @@ -454,9 +454,8 @@ func resourceTargetRead(d *schema.ResourceData, meta interface{}) error { t, err := FindTarget(conn, busName, d.Get("rule").(string), d.Get("target_id").(string)) if err != nil { - if tfawserr.ErrCodeEquals(err, "ValidationException") || - tfawserr.ErrCodeEquals(err, eventbridge.ErrCodeResourceNotFoundException) || - regexp.MustCompile(" not found$").MatchString(err.Error()) { + if !d.IsNewResource() && (tfawserr.ErrCodeEquals(err, "ValidationException", eventbridge.ErrCodeResourceNotFoundException) || + regexp.MustCompile(" not found$").MatchString(err.Error())) { log.Printf("[WARN] EventBridge Target (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/internal/service/events/target_test.go b/internal/service/events/target_test.go index 9dba5f7105c..9f1243ef5a6 100644 --- a/internal/service/events/target_test.go +++ b/internal/service/events/target_test.go @@ -37,7 +37,7 @@ func TestAccEventsTarget_basic(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetConfig(ruleName, snsTopicName1, targetID1), + Config: testAccTargetConfig_basic(ruleName, snsTopicName1, targetID1), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "rule", ruleName), @@ -70,7 +70,7 @@ func TestAccEventsTarget_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTargetConfig(ruleName, snsTopicName2, targetID2), + Config: testAccTargetConfig_basic(ruleName, snsTopicName2, targetID2), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "rule", ruleName), @@ -80,7 +80,7 @@ func TestAccEventsTarget_basic(t *testing.T) { ), }, { - Config: testAccTargetDefaultEventBusNameConfig(ruleName, snsTopicName2, targetID2), + Config: testAccTargetConfig_defaultBusName(ruleName, snsTopicName2, targetID2), PlanOnly: true, }, }, @@ -105,7 +105,7 @@ func TestAccEventsTarget_eventBusName(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetEventBusNameConfig(ruleName, busName, snsTopicName1, targetID1), + Config: testAccTargetConfig_busName(ruleName, busName, snsTopicName1, targetID1), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "rule", ruleName), @@ -120,7 +120,7 @@ func TestAccEventsTarget_eventBusName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTargetEventBusNameConfig(ruleName, busName, snsTopicName2, targetID2), + Config: testAccTargetConfig_busName(ruleName, busName, snsTopicName2, targetID2), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "rule", ruleName), @@ -153,7 +153,7 @@ func TestAccEventsTarget_eventBusARN(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetEventBusARNConfig(ruleName, originEventBusName, targetID, destinationEventBusName, sdkacctest.RandomWithPrefix("tf-acc-test-target"), sdkacctest.RandomWithPrefix("tf-acc-test-target")), + Config: testAccTargetConfig_busARN(ruleName, originEventBusName, targetID, destinationEventBusName, sdkacctest.RandomWithPrefix("tf-acc-test-target"), sdkacctest.RandomWithPrefix("tf-acc-test-target")), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &target), resource.TestCheckResourceAttr(resourceName, "rule", ruleName), @@ -187,7 +187,7 @@ func TestAccEventsTarget_generatedTargetID(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetMissingTargetIDConfig(ruleName, snsTopicName), + Config: testAccTargetConfig_missingID(ruleName, snsTopicName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "rule", ruleName), @@ -291,7 +291,7 @@ func TestAccEventsTarget_disappears(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetConfig(ruleName, snsTopicName, targetID), + Config: testAccTargetConfig_basic(ruleName, snsTopicName, targetID), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfevents.ResourceTarget(), resourceName), @@ -314,7 +314,7 @@ func TestAccEventsTarget_ssmDocument(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetSSMDocumentConfig(rName), + Config: testAccTargetConfig_ssmDocument(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "run_command_targets.#", "1"), @@ -346,7 +346,7 @@ func TestAccEventsTarget_http(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetHTTPConfig(rName), + Config: testAccTargetConfig_http(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "http_target.#", "1"), @@ -382,7 +382,7 @@ func TestAccEventsTarget_http_params(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetHTTPParameterConfig(rName), + Config: testAccTargetConfig_httpParameter(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "http_target.#", "1"), @@ -402,7 +402,7 @@ func TestAccEventsTarget_http_params(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTargetHTTPParameterConfigUpdated(rName), + Config: testAccTargetConfig_httpParameterUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "http_target.#", "1"), @@ -434,7 +434,7 @@ func TestAccEventsTarget_ecs(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetECSConfig(rName), + Config: testAccTargetConfig_ecs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "role_arn", iamRoleResourceName, "arn"), @@ -469,7 +469,7 @@ func TestAccEventsTarget_redshift(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetRedshiftConfig(rName), + Config: testAccTargetConfig_redshift(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "role_arn", iamRoleResourceName, "arn"), @@ -506,7 +506,7 @@ func TestAccEventsTarget_ecsWithoutLaunchType(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetECSWithoutLaunchTypeConfig(rName), + Config: testAccTargetConfig_ecsNoLaunchType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "role_arn", iamRoleResourceName, "arn"), @@ -525,7 +525,7 @@ func TestAccEventsTarget_ecsWithoutLaunchType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTargetECSConfig(rName), + Config: testAccTargetConfig_ecs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ecs_target.0.launch_type", "FARGATE"), @@ -538,7 +538,7 @@ func TestAccEventsTarget_ecsWithoutLaunchType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTargetECSWithoutLaunchTypeConfig(rName), + Config: testAccTargetConfig_ecsNoLaunchType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ecs_target.0.launch_type", ""), @@ -566,7 +566,7 @@ func TestAccEventsTarget_ecsWithBlankLaunchType(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetECSWithBlankLaunchTypeConfig(rName), + Config: testAccTargetConfig_ecsBlankLaunchType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "role_arn", iamRoleResourceName, "arn"), @@ -585,7 +585,7 @@ func TestAccEventsTarget_ecsWithBlankLaunchType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTargetECSConfig(rName), + Config: testAccTargetConfig_ecs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ecs_target.0.launch_type", "FARGATE"), @@ -598,7 +598,7 @@ func TestAccEventsTarget_ecsWithBlankLaunchType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTargetECSWithBlankLaunchTypeConfig(rName), + Config: testAccTargetConfig_ecsBlankLaunchType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ecs_target.0.launch_type", ""), @@ -620,7 +620,7 @@ func TestAccEventsTarget_ecsWithBlankTaskCount(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetECSWithBlankTaskCountConfig(rName), + Config: testAccTargetConfig_ecsBlankTaskCount(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ecs_target.#", "1"), @@ -649,7 +649,7 @@ func TestAccEventsTarget_ecsFull(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetECSWithBlankTaskCountFullConfig(rName), + Config: testAccTargetConfig_ecsBlankTaskCountFull(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ecs_target.#", "1"), @@ -687,7 +687,7 @@ func TestAccEventsTarget_batch(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetBatchConfig(rName), + Config: testAccTargetConfig_batch(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "batch_target.#", "1"), @@ -717,7 +717,7 @@ func TestAccEventsTarget_kinesis(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetKinesisConfig(rName), + Config: testAccTargetConfig_kinesis(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "kinesis_target.#", "1"), @@ -745,7 +745,7 @@ func TestAccEventsTarget_sqs(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetSQSConfig(rName), + Config: testAccTargetConfig_sqs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "sqs_target.#", "1"), @@ -796,11 +796,11 @@ func TestAccEventsTarget_Input_transformer(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetInputTransformerConfig(rName, tooManyInputPaths), + Config: testAccTargetConfig_inputTransformer(rName, tooManyInputPaths), ExpectError: regexp.MustCompile(`.*expected number of items in.* to be less than or equal to.*`), }, { - Config: testAccTargetInputTransformerConfig(rName, validInputPaths), + Config: testAccTargetConfig_inputTransformer(rName, validInputPaths), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "input_transformer.#", "1"), @@ -832,7 +832,7 @@ func TestAccEventsTarget_inputTransformerJSONString(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetInputTransformerJSONStringConfig(rName), + Config: testAccTargetConfig_inputTransformerJSONString(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &target), resource.TestCheckResourceAttr(resourceName, "input_transformer.#", "1"), @@ -864,7 +864,7 @@ func TestAccEventsTarget_partnerEventBus(t *testing.T) { CheckDestroy: testAccCheckTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccTargetPartnerEventBusConfig(rName, busName), + Config: testAccTargetConfig_partnerBus(rName, busName), Check: resource.ComposeTestCheckFunc( testAccCheckTargetExists(resourceName, &target), resource.TestCheckResourceAttr(resourceName, "rule", rName), @@ -942,7 +942,7 @@ func testAccTargetNoBusNameImportStateIdFunc(resourceName string) resource.Impor } } -func testAccTargetConfig(ruleName, snsTopicName, targetID string) string { +func testAccTargetConfig_basic(ruleName, snsTopicName, targetID string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%s" @@ -961,7 +961,7 @@ resource "aws_sns_topic" "test" { `, ruleName, targetID, snsTopicName) } -func testAccTargetDefaultEventBusNameConfig(ruleName, snsTopicName, targetID string) string { +func testAccTargetConfig_defaultBusName(ruleName, snsTopicName, targetID string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%s" @@ -982,7 +982,7 @@ resource "aws_sns_topic" "test" { `, ruleName, targetID, snsTopicName) } -func testAccTargetEventBusNameConfig(ruleName, eventBusName, snsTopicName, targetID string) string { +func testAccTargetConfig_busName(ruleName, eventBusName, snsTopicName, targetID string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_target" "test" { rule = aws_cloudwatch_event_rule.test.name @@ -1013,7 +1013,7 @@ resource "aws_cloudwatch_event_bus" "test" { `, targetID, snsTopicName, ruleName, eventBusName) } -func testAccTargetEventBusARNConfig(ruleName, originEventBusName, targetID, destinationEventBusName, roleName, policyName string) string { +func testAccTargetConfig_busARN(ruleName, originEventBusName, targetID, destinationEventBusName, roleName, policyName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -1062,7 +1062,7 @@ EOF `, originEventBusName, ruleName, targetID, destinationEventBusName, roleName, policyName) } -func testAccTargetMissingTargetIDConfig(ruleName, snsTopicName string) string { +func testAccTargetConfig_missingID(ruleName, snsTopicName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%s" @@ -1234,7 +1234,7 @@ data "aws_partition" "current" {} `, ruleName, rName, targetName) } -func testAccTargetSSMDocumentConfig(rName string) string { +func testAccTargetConfig_ssmDocument(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -1383,7 +1383,7 @@ data "aws_partition" "current" {} `, rName) } -func testAccTargetHTTPConfig(rName string) string { +func testAccTargetConfig_http(rName string) string { return testAccTargetHTTPConfigBase(rName) + ` resource "aws_cloudwatch_event_target" "test" { arn = "${aws_api_gateway_stage.test.execution_arn}/GET" @@ -1403,7 +1403,7 @@ resource "aws_cloudwatch_event_target" "test" { ` } -func testAccTargetHTTPParameterConfig(rName string) string { +func testAccTargetConfig_httpParameter(rName string) string { return testAccTargetHTTPConfigBase(rName) + ` resource "aws_cloudwatch_event_target" "test" { arn = "${aws_api_gateway_stage.test.execution_arn}/*/*/GET" @@ -1423,7 +1423,7 @@ resource "aws_cloudwatch_event_target" "test" { ` } -func testAccTargetHTTPParameterConfigUpdated(rName string) string { +func testAccTargetConfig_httpParameterUpdated(rName string) string { return testAccTargetHTTPConfigBase(rName) + ` resource "aws_cloudwatch_event_target" "test" { arn = "${aws_api_gateway_stage.test.execution_arn}/*/*/*/GET" @@ -1531,7 +1531,7 @@ resource "aws_cloudwatch_event_rule" "test" { `, rName) } -func testAccTargetECSConfig(rName string) string { +func testAccTargetConfig_ecs(rName string) string { return testAccTargetECSBaseConfig(rName) + ` resource "aws_cloudwatch_event_target" "test" { arn = aws_ecs_cluster.test.id @@ -1551,7 +1551,7 @@ resource "aws_cloudwatch_event_target" "test" { ` } -func testAccTargetRedshiftConfig(rName string) string { +func testAccTargetConfig_redshift(rName string) string { return acctest.ConfigCompose(testAccTargetECSBaseConfig(rName), acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1580,7 +1580,7 @@ resource "aws_redshift_cluster" "test" { `, 123)) } -func testAccTargetECSWithoutLaunchTypeConfig(rName string) string { +func testAccTargetConfig_ecsNoLaunchType(rName string) string { return testAccTargetECSBaseConfig(rName) + ` resource "aws_cloudwatch_event_target" "test" { arn = aws_ecs_cluster.test.id @@ -1599,7 +1599,7 @@ resource "aws_cloudwatch_event_target" "test" { ` } -func testAccTargetECSWithBlankLaunchTypeConfig(rName string) string { +func testAccTargetConfig_ecsBlankLaunchType(rName string) string { return testAccTargetECSBaseConfig(rName) + ` resource "aws_cloudwatch_event_target" "test" { arn = aws_ecs_cluster.test.id @@ -1619,7 +1619,7 @@ resource "aws_cloudwatch_event_target" "test" { ` } -func testAccTargetECSWithBlankTaskCountConfig(rName string) string { +func testAccTargetConfig_ecsBlankTaskCount(rName string) string { return testAccTargetECSBaseConfig(rName) + ` resource "aws_cloudwatch_event_target" "test" { arn = aws_ecs_cluster.test.id @@ -1638,7 +1638,7 @@ resource "aws_cloudwatch_event_target" "test" { ` } -func testAccTargetECSWithBlankTaskCountFullConfig(rName string) string { +func testAccTargetConfig_ecsBlankTaskCountFull(rName string) string { return testAccTargetECSBaseConfig(rName) + ` resource "aws_cloudwatch_event_target" "test" { arn = aws_ecs_cluster.test.id @@ -1668,7 +1668,7 @@ resource "aws_cloudwatch_event_target" "test" { ` } -func testAccTargetBatchConfig(rName string) string { +func testAccTargetConfig_batch(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%[1]s" @@ -1836,7 +1836,7 @@ CONTAINER_PROPERTIES `, rName) } -func testAccTargetKinesisConfig(rName string) string { +func testAccTargetConfig_kinesis(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%[1]s" @@ -1882,7 +1882,7 @@ data "aws_partition" "current" {} `, rName) } -func testAccTargetSQSConfig(rName string) string { +func testAccTargetConfig_sqs(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = "%[1]s" @@ -1906,7 +1906,7 @@ resource "aws_sqs_queue" "test" { `, rName) } -func testAccTargetInputTransformerConfig(rName string, inputPathKeys []string) string { +func testAccTargetConfig_inputTransformer(rName string, inputPathKeys []string) string { var inputPaths, inputTemplates strings.Builder for _, inputPath := range inputPathKeys { @@ -1946,7 +1946,7 @@ resource "aws_cloudwatch_event_rule" "schedule" { `, rName, inputPaths.String(), strings.TrimSpace(inputTemplates.String()))) } -func testAccTargetInputTransformerJSONStringConfig(name string) string { +func testAccTargetConfig_inputTransformerJSONString(name string) string { return acctest.ConfigCompose( testAccTargetLambdaBaseConfig(name), fmt.Sprintf(` @@ -2007,7 +2007,7 @@ data "aws_partition" "current" {} `, name) } -func testAccTargetPartnerEventBusConfig(rName, eventBusName string) string { +func testAccTargetConfig_partnerBus(rName, eventBusName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_rule" "test" { name = %[1]q diff --git a/internal/service/firehose/delivery_stream.go b/internal/service/firehose/delivery_stream.go index 67af2ebcd11..25cb89e13cb 100644 --- a/internal/service/firehose/delivery_stream.go +++ b/internal/service/firehose/delivery_stream.go @@ -26,7 +26,7 @@ const ( destinationTypeElasticsearch = "elasticsearch" destinationTypeRedshift = "redshift" destinationTypeSplunk = "splunk" - destinationTypeHttpEndpoint = "http_endpoint" + destinationTypeHTTPEndpoint = "http_endpoint" ) func cloudWatchLoggingOptionsSchema() *schema.Schema { @@ -227,7 +227,7 @@ func processingConfigurationSchema() *schema.Schema { } } -func flattenCloudwatchLoggingOptions(clo *firehose.CloudWatchLoggingOptions) []interface{} { +func flattenCloudWatchLoggingOptions(clo *firehose.CloudWatchLoggingOptions) []interface{} { if clo == nil { return []interface{}{} } @@ -248,13 +248,13 @@ func flattenElasticsearchConfiguration(description *firehose.ElasticsearchDestin } m := map[string]interface{}{ - "cloudwatch_logging_options": flattenCloudwatchLoggingOptions(description.CloudWatchLoggingOptions), + "cloudwatch_logging_options": flattenCloudWatchLoggingOptions(description.CloudWatchLoggingOptions), "role_arn": aws.StringValue(description.RoleARN), "type_name": aws.StringValue(description.TypeName), "index_name": aws.StringValue(description.IndexName), "s3_backup_mode": aws.StringValue(description.S3BackupMode), "index_rotation_period": aws.StringValue(description.IndexRotationPeriod), - "vpc_config": flattenVpcConfiguration(description.VpcConfigurationDescription), + "vpc_config": flattenVPCConfiguration(description.VpcConfigurationDescription), "processing_configuration": flattenProcessingConfiguration(description.ProcessingConfiguration, aws.StringValue(description.RoleARN)), } @@ -278,7 +278,7 @@ func flattenElasticsearchConfiguration(description *firehose.ElasticsearchDestin return []map[string]interface{}{m} } -func flattenVpcConfiguration(description *firehose.VpcConfigurationDescription) []map[string]interface{} { +func flattenVPCConfiguration(description *firehose.VpcConfigurationDescription) []map[string]interface{} { if description == nil { return []map[string]interface{}{} } @@ -300,7 +300,7 @@ func flattenExtendedS3Configuration(description *firehose.ExtendedS3DestinationD m := map[string]interface{}{ "bucket_arn": aws.StringValue(description.BucketARN), - "cloudwatch_logging_options": flattenCloudwatchLoggingOptions(description.CloudWatchLoggingOptions), + "cloudwatch_logging_options": flattenCloudWatchLoggingOptions(description.CloudWatchLoggingOptions), "compression_format": aws.StringValue(description.CompressionFormat), "data_format_conversion_configuration": flattenDataFormatConversionConfiguration(description.DataFormatConversionConfiguration), "error_output_prefix": aws.StringValue(description.ErrorOutputPrefix), @@ -330,7 +330,7 @@ func flattenRedshiftConfiguration(description *firehose.RedshiftDestinationDescr } m := map[string]interface{}{ - "cloudwatch_logging_options": flattenCloudwatchLoggingOptions(description.CloudWatchLoggingOptions), + "cloudwatch_logging_options": flattenCloudWatchLoggingOptions(description.CloudWatchLoggingOptions), "cluster_jdbcurl": aws.StringValue(description.ClusterJDBCURL), "password": configuredPassword, "processing_configuration": flattenProcessingConfiguration(description.ProcessingConfiguration, aws.StringValue(description.RoleARN)), @@ -358,7 +358,7 @@ func flattenSplunkConfiguration(description *firehose.SplunkDestinationDescripti return []map[string]interface{}{} } m := map[string]interface{}{ - "cloudwatch_logging_options": flattenCloudwatchLoggingOptions(description.CloudWatchLoggingOptions), + "cloudwatch_logging_options": flattenCloudWatchLoggingOptions(description.CloudWatchLoggingOptions), "hec_acknowledgment_timeout": int(aws.Int64Value(description.HECAcknowledgmentTimeoutInSeconds)), "hec_endpoint_type": aws.StringValue(description.HECEndpointType), "hec_endpoint": aws.StringValue(description.HECEndpoint), @@ -381,7 +381,7 @@ func flattenS3Configuration(description *firehose.S3DestinationDescription) []ma m := map[string]interface{}{ "bucket_arn": aws.StringValue(description.BucketARN), - "cloudwatch_logging_options": flattenCloudwatchLoggingOptions(description.CloudWatchLoggingOptions), + "cloudwatch_logging_options": flattenCloudWatchLoggingOptions(description.CloudWatchLoggingOptions), "compression_format": aws.StringValue(description.CompressionFormat), "error_output_prefix": aws.StringValue(description.ErrorOutputPrefix), "prefix": aws.StringValue(description.Prefix), @@ -784,7 +784,7 @@ func flattenDeliveryStream(d *schema.ResourceData, s *firehose.DeliveryStreamDes return fmt.Errorf("error setting s3_configuration: %s", err) } } else if destination.HttpEndpointDestinationDescription != nil { - d.Set("destination", destinationTypeHttpEndpoint) + d.Set("destination", destinationTypeHTTPEndpoint) configuredAccessKey := d.Get("http_endpoint_configuration.0.access_key").(string) if err := d.Set("http_endpoint_configuration", flattenHTTPEndpointConfiguration(destination.HttpEndpointDestinationDescription, configuredAccessKey)); err != nil { return fmt.Errorf("error setting http_endpoint_configuration: %s", err) @@ -820,7 +820,7 @@ func flattenHTTPEndpointConfiguration(description *firehose.HttpEndpointDestinat "role_arn": aws.StringValue(description.RoleARN), "s3_backup_mode": aws.StringValue(description.S3BackupMode), "request_configuration": flattenRequestConfiguration(description.RequestConfiguration), - "cloudwatch_logging_options": flattenCloudwatchLoggingOptions(description.CloudWatchLoggingOptions), + "cloudwatch_logging_options": flattenCloudWatchLoggingOptions(description.CloudWatchLoggingOptions), "processing_configuration": flattenProcessingConfiguration(description.ProcessingConfiguration, aws.StringValue(description.RoleARN)), } @@ -947,7 +947,7 @@ func ResourceDeliveryStream() *schema.Resource { destinationTypeRedshift, destinationTypeElasticsearch, destinationTypeSplunk, - destinationTypeHttpEndpoint, + destinationTypeHTTPEndpoint, }, false), }, @@ -2601,7 +2601,7 @@ func resourceDeliveryStreamCreate(d *schema.ResourceData, meta interface{}) erro return err } createInput.SplunkDestinationConfiguration = rc - } else if d.Get("destination").(string) == destinationTypeHttpEndpoint { + } else if d.Get("destination").(string) == destinationTypeHTTPEndpoint { rc, err := createHTTPEndpointConfig(d, s3Config) if err != nil { return err @@ -2759,7 +2759,7 @@ func resourceDeliveryStreamUpdate(d *schema.ResourceData, meta interface{}) erro return err } updateInput.SplunkDestinationUpdate = rc - } else if d.Get("destination").(string) == destinationTypeHttpEndpoint { + } else if d.Get("destination").(string) == destinationTypeHTTPEndpoint { rc, err := updateHTTPEndpointConfig(d, s3Config) if err != nil { return err diff --git a/internal/service/firehose/delivery_stream_data_source_test.go b/internal/service/firehose/delivery_stream_data_source_test.go index f15322251d6..0c7258c263c 100644 --- a/internal/service/firehose/delivery_stream_data_source_test.go +++ b/internal/service/firehose/delivery_stream_data_source_test.go @@ -22,7 +22,7 @@ func TestAccFirehoseDeliveryStreamDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamBasicDataSourceConfig(rName), + Config: testAccDeliveryStreamDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttr(dataSourceName, "name", rName), @@ -32,7 +32,7 @@ func TestAccFirehoseDeliveryStreamDataSource_basic(t *testing.T) { }) } -func testAccDeliveryStreamBasicDataSourceConfig(rName string) string { +func testAccDeliveryStreamDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/firehose/delivery_stream_test.go b/internal/service/firehose/delivery_stream_test.go index 4a1a5f24833..8b980a2e5c0 100644 --- a/internal/service/firehose/delivery_stream_test.go +++ b/internal/service/firehose/delivery_stream_test.go @@ -116,7 +116,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithPrefixes(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_s3basicWithPrefixes(rName, "logs/", ""), + Config: testAccDeliveryStreamConfig_s3basicPrefixes(rName, "logs/", ""), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -126,7 +126,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithPrefixes(t *testing.T) { ), }, { - Config: testAccDeliveryStreamConfig_s3basicWithPrefixes(rName, "logs/", "errors/"), + Config: testAccDeliveryStreamConfig_s3basicPrefixes(rName, "logs/", "errors/"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -136,7 +136,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithPrefixes(t *testing.T) { ), }, { - Config: testAccDeliveryStreamConfig_s3basicWithPrefixes(rName, "logs/{timestamp:yyyy-MM-dd}/", "errors/{timestamp:yyyy-MM-dd}/"), + Config: testAccDeliveryStreamConfig_s3basicPrefixes(rName, "logs/{timestamp:yyyy-MM-dd}/", "errors/{timestamp:yyyy-MM-dd}/"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -146,7 +146,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithPrefixes(t *testing.T) { ), }, { - Config: testAccDeliveryStreamConfig_s3basicWithPrefixes(rName, "", ""), + Config: testAccDeliveryStreamConfig_s3basicPrefixes(rName, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -171,7 +171,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithSSE(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_s3basicWithSSE(rName, true), + Config: testAccDeliveryStreamConfig_s3basicSSE(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -181,7 +181,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithSSE(t *testing.T) { ), }, { - Config: testAccDeliveryStreamConfig_s3basicWithSSE(rName, false), + Config: testAccDeliveryStreamConfig_s3basicSSE(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -194,7 +194,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithSSE(t *testing.T) { PlanOnly: true, }, { - Config: testAccDeliveryStreamConfig_s3basicWithSSE(rName, true), + Config: testAccDeliveryStreamConfig_s3basicSSE(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -219,7 +219,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithSSEAndKeyARN(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_s3basicWithSSEAndKeyArn(rName, true), + Config: testAccDeliveryStreamConfig_s3BasicSSEAndKeyARN(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -230,7 +230,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithSSEAndKeyARN(t *testing.T) { ), }, { - Config: testAccDeliveryStreamConfig_s3basicWithSSE(rName, false), + Config: testAccDeliveryStreamConfig_s3basicSSE(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -239,7 +239,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithSSEAndKeyARN(t *testing.T) { ), }, { - Config: testAccDeliveryStreamConfig_s3basicWithSSEAndKeyArn(rName, true), + Config: testAccDeliveryStreamConfig_s3BasicSSEAndKeyARN(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -265,7 +265,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithSSEAndKeyType(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_s3basicWithSSEAndKeyType(rName, true, firehose.KeyTypeAwsOwnedCmk), + Config: testAccDeliveryStreamConfig_s3basicSSEAndKeyType(rName, true, firehose.KeyTypeAwsOwnedCmk), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -275,7 +275,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithSSEAndKeyType(t *testing.T) { ), }, { - Config: testAccDeliveryStreamConfig_s3basicWithSSE(rName, false), + Config: testAccDeliveryStreamConfig_s3basicSSE(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -284,7 +284,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithSSEAndKeyType(t *testing.T) { ), }, { - Config: testAccDeliveryStreamConfig_s3basicWithSSEAndKeyType(rName, true, firehose.KeyTypeAwsOwnedCmk), + Config: testAccDeliveryStreamConfig_s3basicSSEAndKeyType(rName, true, firehose.KeyTypeAwsOwnedCmk), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -309,7 +309,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithTags(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_s3basicWithTags(rName), + Config: testAccDeliveryStreamConfig_s3basicTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -318,7 +318,7 @@ func TestAccFirehoseDeliveryStream_s3basicWithTags(t *testing.T) { ), }, { - Config: testAccDeliveryStreamConfig_s3basicWithTagsChanged(rName), + Config: testAccDeliveryStreamConfig_s3basicTagsChanged(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -350,7 +350,7 @@ func TestAccFirehoseDeliveryStream_s3KinesisStreamSource(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_s3StreamSource(rName), + Config: testAccDeliveryStreamConfig_s3Source(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -372,7 +372,7 @@ func TestAccFirehoseDeliveryStream_s3WithCloudWatchLogging(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_s3WithCloudwatchLogging(rName), + Config: testAccDeliveryStreamConfig_s3CloudWatchLogging(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -459,7 +459,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversion_enabled(t *tes CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_Enabled(rName, false), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -473,7 +473,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversion_enabled(t *tes ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_Enabled(rName, true), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -482,7 +482,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversion_enabled(t *tes ), }, { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_Enabled(rName, false), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -506,7 +506,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3_externalUpdate(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_ExternalUpdate(rName), + Config: testAccDeliveryStreamConfig_extendedS3ExternalUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -541,7 +541,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3_externalUpdate(t *testing.T) { t.Fatalf("Unable to update firehose destination: %s", err) } }, - Config: testAccDeliveryStreamConfig_ExtendedS3_ExternalUpdate(rName), + Config: testAccDeliveryStreamConfig_extendedS3ExternalUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -565,7 +565,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversionDeserializer_up CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_HiveJsonSerDe_Empty(rName), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationHiveJSONSerDeEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -581,7 +581,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversionDeserializer_up ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_OpenXJsonSerDe_Empty(rName), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationOpenXJSONSerDeEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -607,7 +607,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversionHiveJSONSerDe_e CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_HiveJsonSerDe_Empty(rName), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationHiveJSONSerDeEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -638,7 +638,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversionOpenXJSONSerDe_ CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_OpenXJsonSerDe_Empty(rName), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationOpenXJSONSerDeEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -669,7 +669,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversionOrcSerDe_empty( CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_OrcSerDe_Empty(rName), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationOrcSerDeEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -700,7 +700,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversionParquetSerDe_em CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_ParquetSerDe_Empty(rName), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationParquetSerDeEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -731,7 +731,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversionSerializer_upda CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_OrcSerDe_Empty(rName), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationOrcSerDeEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -747,7 +747,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3DataFormatConversionSerializer_upda ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_ParquetSerDe_Empty(rName), + Config: testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationParquetSerDeEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -773,7 +773,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3_errorOutputPrefix(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_ErrorOutputPrefix(rName, "prefix1"), + Config: testAccDeliveryStreamConfig_extendedS3ErrorOutputPrefix(rName, "prefix1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -786,7 +786,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3_errorOutputPrefix(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_ExtendedS3_ErrorOutputPrefix(rName, "prefix2"), + Config: testAccDeliveryStreamConfig_extendedS3ErrorOutputPrefix(rName, "prefix2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -801,7 +801,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3_errorOutputPrefix(t *testing.T) { { // Ensure the ErrorOutputPrefix can be updated to an empty value // Reference: https://github.com/hashicorp/terraform-provider-aws/pull/11229#discussion_r356282765 - Config: testAccDeliveryStreamConfig_ExtendedS3_ErrorOutputPrefix(rName, ""), + Config: testAccDeliveryStreamConfig_extendedS3ErrorOutputPrefix(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -824,7 +824,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3_S3BackupConfiguration_ErrorOutputP CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_S3BackUpConfiguration_ErrorOutputPrefix(rName, "prefix1"), + Config: testAccDeliveryStreamConfig_extendedS3S3BackUpConfigurationErrorOutputPrefix(rName, "prefix1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -838,7 +838,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3_S3BackupConfiguration_ErrorOutputP ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_ExtendedS3_S3BackUpConfiguration_ErrorOutputPrefix(rName, "prefix2"), + Config: testAccDeliveryStreamConfig_extendedS3S3BackUpConfigurationErrorOutputPrefix(rName, "prefix2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -851,7 +851,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3_S3BackupConfiguration_ErrorOutputP ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_ExtendedS3_S3BackUpConfiguration_ErrorOutputPrefix(rName, ""), + Config: testAccDeliveryStreamConfig_extendedS3S3BackUpConfigurationErrorOutputPrefix(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -875,7 +875,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3Processing_empty(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_ProcessingConfiguration_Empty(rName), + Config: testAccDeliveryStreamConfig_extendedS3ProcessingConfigurationEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "extended_s3_configuration.#", "1"), @@ -903,7 +903,7 @@ func TestAccFirehoseDeliveryStream_extendedS3KMSKeyARN(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_extendedS3KmsKeyArn(rName), + Config: testAccDeliveryStreamConfig_extendedS3KMSKeyARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -1006,14 +1006,14 @@ func TestAccFirehoseDeliveryStream_extendedS3Updates(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_extendedS3Updates_Initial(rName), + Config: testAccDeliveryStreamConfig_extendedS3UpdatesInitial(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, firstUpdateExtendedS3DestinationConfig, nil, nil, nil, nil), ), }, { - Config: testAccDeliveryStreamConfig_extendedS3Updates_RemoveProcessors(rName), + Config: testAccDeliveryStreamConfig_extendedS3UpdatesRemoveProcessors(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, removeProcessorsExtendedS3DestinationConfig, nil, nil, nil, nil), @@ -1035,7 +1035,7 @@ func TestAccFirehoseDeliveryStream_ExtendedS3_kinesisStreamSource(t *testing.T) CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ExtendedS3_streamSource(rName), + Config: testAccDeliveryStreamConfig_extendedS3Source(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -1083,7 +1083,7 @@ func TestAccFirehoseDeliveryStream_redshiftUpdates(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamRedshiftConfig(rName), + Config: testAccDeliveryStreamConfig_redshift(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -1096,7 +1096,7 @@ func TestAccFirehoseDeliveryStream_redshiftUpdates(t *testing.T) { ImportStateVerifyIgnore: []string{"redshift_configuration.0.password"}, }, { - Config: testAccDeliveryStreamRedshiftConfigUpdates(rName), + Config: testAccDeliveryStreamConfig_redshiftUpdates(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, updatedRedshiftConfig, nil, nil, nil), @@ -1138,7 +1138,7 @@ func TestAccFirehoseDeliveryStream_splunkUpdates(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_SplunkBasic(rName), + Config: testAccDeliveryStreamConfig_splunkBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -1150,7 +1150,7 @@ func TestAccFirehoseDeliveryStream_splunkUpdates(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_SplunkUpdates(rName), + Config: testAccDeliveryStreamConfig_splunkUpdates(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, updatedSplunkConfig, nil), @@ -1172,7 +1172,7 @@ func TestAccFirehoseDeliveryStream_Splunk_ErrorOutputPrefix(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_Splunk_ErrorOutputPrefix(rName, "prefix1"), + Config: testAccDeliveryStreamConfig_splunkErrorOutputPrefix(rName, "prefix1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "s3_configuration.#", "1"), @@ -1185,7 +1185,7 @@ func TestAccFirehoseDeliveryStream_Splunk_ErrorOutputPrefix(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_Splunk_ErrorOutputPrefix(rName, "prefix2"), + Config: testAccDeliveryStreamConfig_splunkErrorOutputPrefix(rName, "prefix2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "s3_configuration.#", "1"), @@ -1198,7 +1198,7 @@ func TestAccFirehoseDeliveryStream_Splunk_ErrorOutputPrefix(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_Splunk_ErrorOutputPrefix(rName, ""), + Config: testAccDeliveryStreamConfig_splunkErrorOutputPrefix(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "s3_configuration.#", "1"), @@ -1243,7 +1243,7 @@ func TestAccFirehoseDeliveryStream_httpEndpoint(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_HTTPEndpointBasic(rName), + Config: testAccDeliveryStreamConfig_httpEndpointBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -1255,7 +1255,7 @@ func TestAccFirehoseDeliveryStream_httpEndpoint(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_HTTPEndpointUpdates(rName), + Config: testAccDeliveryStreamConfig_httpEndpointUpdates(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, updatedHTTPEndpointConfig), @@ -1277,7 +1277,7 @@ func TestAccFirehoseDeliveryStream_HTTPEndpoint_ErrorOutputPrefix(t *testing.T) CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_HTTPEndpoint_ErrorOutputPrefix(rName, "prefix1"), + Config: testAccDeliveryStreamConfig_httpEndpointErrorOutputPrefix(rName, "prefix1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "s3_configuration.#", "1"), @@ -1290,7 +1290,7 @@ func TestAccFirehoseDeliveryStream_HTTPEndpoint_ErrorOutputPrefix(t *testing.T) ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_HTTPEndpoint_ErrorOutputPrefix(rName, "prefix2"), + Config: testAccDeliveryStreamConfig_httpEndpointErrorOutputPrefix(rName, "prefix2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "s3_configuration.#", "1"), @@ -1303,7 +1303,7 @@ func TestAccFirehoseDeliveryStream_HTTPEndpoint_ErrorOutputPrefix(t *testing.T) ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_HTTPEndpoint_ErrorOutputPrefix(rName, ""), + Config: testAccDeliveryStreamConfig_httpEndpointErrorOutputPrefix(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "s3_configuration.#", "1"), @@ -1326,7 +1326,7 @@ func TestAccFirehoseDeliveryStream_HTTPEndpoint_retryDuration(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_HTTPEndpoint_RetryDuration(rName, 301), + Config: testAccDeliveryStreamConfig_httpEndpointRetryDuration(rName, 301), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), ), @@ -1337,7 +1337,7 @@ func TestAccFirehoseDeliveryStream_HTTPEndpoint_retryDuration(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_HTTPEndpoint_RetryDuration(rName, 302), + Config: testAccDeliveryStreamConfig_httpEndpointRetryDuration(rName, 302), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), ), @@ -1378,7 +1378,7 @@ func TestAccFirehoseDeliveryStream_elasticSearchUpdates(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ElasticsearchBasic(rName), + Config: testAccDeliveryStreamConfig_elasticsearchBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -1390,7 +1390,7 @@ func TestAccFirehoseDeliveryStream_elasticSearchUpdates(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_ElasticsearchUpdate(rName), + Config: testAccDeliveryStreamConfig_elasticsearchUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, updatedElasticsearchConfig, nil, nil), @@ -1432,7 +1432,7 @@ func TestAccFirehoseDeliveryStream_elasticSearchEndpointUpdates(t *testing.T) { CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ElasticsearchEndpoint(rName), + Config: testAccDeliveryStreamConfig_elasticsearchEndpoint(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -1444,7 +1444,7 @@ func TestAccFirehoseDeliveryStream_elasticSearchEndpointUpdates(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_ElasticsearchEndpointUpdate(rName), + Config: testAccDeliveryStreamConfig_elasticsearchEndpointUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, updatedElasticsearchConfig, nil, nil), @@ -1482,13 +1482,13 @@ func TestAccFirehoseDeliveryStream_elasticSearchWithVPCUpdates(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIamServiceLinkedRoleEs(t) }, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckIAMServiceLinkedRoleEs(t) }, ErrorCheck: acctest.ErrorCheck(t, firehose.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_ElasticsearchVPCBasic(rName), + Config: testAccDeliveryStreamConfig_elasticsearchVPCBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil, nil), @@ -1504,7 +1504,7 @@ func TestAccFirehoseDeliveryStream_elasticSearchWithVPCUpdates(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_ElasticsearchVPCUpdate(rName), + Config: testAccDeliveryStreamConfig_elasticsearchVPCUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), testAccCheckDeliveryStreamAttributes(&stream, nil, nil, nil, updatedElasticsearchConfig, nil, nil), @@ -1530,7 +1530,7 @@ func TestAccFirehoseDeliveryStream_Elasticsearch_ErrorOutputPrefix(t *testing.T) CheckDestroy: testAccCheckDeliveryStreamDestroy_ExtendedS3, Steps: []resource.TestStep{ { - Config: testAccDeliveryStreamConfig_Elasticsearch_ErrorOutputPrefix(rName, "prefix1"), + Config: testAccDeliveryStreamConfig_elasticsearchErrorOutputPrefix(rName, "prefix1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "s3_configuration.#", "1"), @@ -1543,7 +1543,7 @@ func TestAccFirehoseDeliveryStream_Elasticsearch_ErrorOutputPrefix(t *testing.T) ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_Elasticsearch_ErrorOutputPrefix(rName, "prefix2"), + Config: testAccDeliveryStreamConfig_elasticsearchErrorOutputPrefix(rName, "prefix2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "s3_configuration.#", "1"), @@ -1556,7 +1556,7 @@ func TestAccFirehoseDeliveryStream_Elasticsearch_ErrorOutputPrefix(t *testing.T) ImportStateVerify: true, }, { - Config: testAccDeliveryStreamConfig_Elasticsearch_ErrorOutputPrefix(rName, ""), + Config: testAccDeliveryStreamConfig_elasticsearchErrorOutputPrefix(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckDeliveryStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "s3_configuration.#", "1"), @@ -2062,7 +2062,7 @@ EOF `, rName) } -func testAccDeliveryStreamConfig_s3WithCloudwatchLogging(rName string) string { +func testAccDeliveryStreamConfig_s3CloudWatchLogging(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -2185,7 +2185,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_s3basicWithPrefixes(rName, prefix, errorOutputPrefix string) string { +func testAccDeliveryStreamConfig_s3basicPrefixes(rName, prefix, errorOutputPrefix string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2204,7 +2204,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, prefix, errorOutputPrefix)) } -func testAccDeliveryStreamConfig_s3basicWithSSE(rName string, sseEnabled bool) string { +func testAccDeliveryStreamConfig_s3basicSSE(rName string, sseEnabled bool) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2225,7 +2225,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, sseEnabled)) } -func testAccDeliveryStreamConfig_s3basicWithSSEAndKeyArn(rName string, sseEnabled bool) string { +func testAccDeliveryStreamConfig_s3BasicSSEAndKeyARN(rName string, sseEnabled bool) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2253,7 +2253,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, sseEnabled)) } -func testAccDeliveryStreamConfig_s3basicWithSSEAndKeyType(rName string, sseEnabled bool, keyType string) string { +func testAccDeliveryStreamConfig_s3basicSSEAndKeyType(rName string, sseEnabled bool, keyType string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2275,7 +2275,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, sseEnabled, keyType)) } -func testAccDeliveryStreamConfig_s3basicWithTags(rName string) string { +func testAccDeliveryStreamConfig_s3basicTags(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2297,7 +2297,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_s3basicWithTagsChanged(rName string) string { +func testAccDeliveryStreamConfig_s3basicTagsChanged(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2318,7 +2318,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_s3StreamSource(rName string) string { +func testAccDeliveryStreamConfig_s3Source(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), testAccStreamSourceConfig(rName), @@ -2395,7 +2395,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_ExtendedS3_streamSource(rName string) string { +func testAccDeliveryStreamConfig_extendedS3Source(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), testAccStreamSourceConfig(rName), @@ -2419,7 +2419,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_Enabled(rName string, enabled bool) string { +func testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationEnabled(rName string, enabled bool) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2487,7 +2487,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, enabled)) } -func testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_HiveJsonSerDe_Empty(rName string) string { +func testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationHiveJSONSerDeEmpty(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2553,7 +2553,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_ExtendedS3_ExternalUpdate(rName string) string { +func testAccDeliveryStreamConfig_extendedS3ExternalUpdate(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2569,7 +2569,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_OpenXJsonSerDe_Empty(rName string) string { +func testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationOpenXJSONSerDeEmpty(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2635,7 +2635,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_OrcSerDe_Empty(rName string) string { +func testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationOrcSerDeEmpty(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2701,7 +2701,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_ParquetSerDe_Empty(rName string) string { +func testAccDeliveryStreamConfig_extendedS3DataFormatConversionConfigurationParquetSerDeEmpty(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2767,7 +2767,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_ExtendedS3_ErrorOutputPrefix(rName, errorOutputPrefix string) string { +func testAccDeliveryStreamConfig_extendedS3ErrorOutputPrefix(rName, errorOutputPrefix string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2786,7 +2786,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, errorOutputPrefix)) } -func testAccDeliveryStreamConfig_ExtendedS3_S3BackUpConfiguration_ErrorOutputPrefix(rName, errorOutputPrefix string) string { +func testAccDeliveryStreamConfig_extendedS3S3BackUpConfigurationErrorOutputPrefix(rName, errorOutputPrefix string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2810,7 +2810,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, errorOutputPrefix)) } -func testAccDeliveryStreamConfig_ExtendedS3_ProcessingConfiguration_Empty(rName string) string { +func testAccDeliveryStreamConfig_extendedS3ProcessingConfigurationEmpty(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -2830,7 +2830,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_extendedS3KmsKeyArn(rName string) string { +func testAccDeliveryStreamConfig_extendedS3KMSKeyARN(rName string) string { return acctest.ConfigCompose( testAccLambdaBasicConfig(rName), testAccDeliveryStreamBaseConfig(rName), @@ -2914,7 +2914,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_extendedS3Updates_Initial(rName string) string { +func testAccDeliveryStreamConfig_extendedS3UpdatesInitial(rName string) string { return acctest.ConfigCompose( testAccLambdaBasicConfig(rName), testAccDeliveryStreamBaseConfig(rName), @@ -2955,7 +2955,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_extendedS3Updates_RemoveProcessors(rName string) string { +func testAccDeliveryStreamConfig_extendedS3UpdatesRemoveProcessors(rName string) string { return acctest.ConfigCompose( testAccLambdaBasicConfig(rName), testAccDeliveryStreamBaseConfig(rName), @@ -3026,7 +3026,7 @@ resource "aws_redshift_cluster" "test" { `, rName)) } -func testAccDeliveryStreamRedshiftConfig(rName string) string { +func testAccDeliveryStreamConfig_redshift(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamRedshiftConfigBase(rName), fmt.Sprintf(` @@ -3050,7 +3050,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamRedshiftConfigUpdates(rName string) string { +func testAccDeliveryStreamConfig_redshiftUpdates(rName string) string { return acctest.ConfigCompose( testAccLambdaBasicConfig(rName), testAccDeliveryStreamRedshiftConfigBase(rName), @@ -3100,7 +3100,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_SplunkBasic(rName string) string { +func testAccDeliveryStreamConfig_splunkBasic(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -3122,7 +3122,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_SplunkUpdates(rName string) string { +func testAccDeliveryStreamConfig_splunkUpdates(rName string) string { return acctest.ConfigCompose( testAccLambdaBasicConfig(rName), testAccDeliveryStreamBaseConfig(rName), @@ -3179,7 +3179,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_Splunk_ErrorOutputPrefix(rName, errorOutputPrefix string) string { +func testAccDeliveryStreamConfig_splunkErrorOutputPrefix(rName, errorOutputPrefix string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -3202,7 +3202,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, errorOutputPrefix)) } -func testAccDeliveryStreamConfig_HTTPEndpointBasic(rName string) string { +func testAccDeliveryStreamConfig_httpEndpointBasic(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -3225,7 +3225,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_HTTPEndpoint_ErrorOutputPrefix(rName, errorOutputPrefix string) string { +func testAccDeliveryStreamConfig_httpEndpointErrorOutputPrefix(rName, errorOutputPrefix string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -3249,7 +3249,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, errorOutputPrefix)) } -func testAccDeliveryStreamConfig_HTTPEndpoint_RetryDuration(rName string, retryDuration int) string { +func testAccDeliveryStreamConfig_httpEndpointRetryDuration(rName string, retryDuration int) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseConfig(rName), fmt.Sprintf(` @@ -3273,7 +3273,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, retryDuration)) } -func testAccDeliveryStreamConfig_HTTPEndpointUpdates(rName string) string { +func testAccDeliveryStreamConfig_httpEndpointUpdates(rName string) string { return acctest.ConfigCompose( testAccLambdaBasicConfig(rName), testAccDeliveryStreamBaseConfig(rName), @@ -3477,7 +3477,7 @@ EOF `, rName)) } -func testAccDeliveryStreamConfig_ElasticsearchBasic(rName string) string { +func testAccDeliveryStreamConfig_elasticsearchBasic(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseElasticsearchConfig(rName), fmt.Sprintf(` @@ -3502,7 +3502,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_Elasticsearch_ErrorOutputPrefix(rName, errorOutputPrefix string) string { +func testAccDeliveryStreamConfig_elasticsearchErrorOutputPrefix(rName, errorOutputPrefix string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseElasticsearchConfig(rName), fmt.Sprintf(` @@ -3528,7 +3528,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName, errorOutputPrefix)) } -func testAccDeliveryStreamConfig_ElasticsearchVPCBasic(rName string) string { +func testAccDeliveryStreamConfig_elasticsearchVPCBasic(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseElasticsearchVPCConfig(rName), fmt.Sprintf(` @@ -3559,7 +3559,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_ElasticsearchUpdate(rName string) string { +func testAccDeliveryStreamConfig_elasticsearchUpdate(rName string) string { return acctest.ConfigCompose( testAccLambdaBasicConfig(rName), testAccDeliveryStreamBaseElasticsearchConfig(rName), @@ -3599,7 +3599,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName)) } -func testAccDeliveryStreamConfig_ElasticsearchVPCUpdate(rName string) string { +func testAccDeliveryStreamConfig_elasticsearchVPCUpdate(rName string) string { return acctest.ConfigCompose( testAccLambdaBasicConfig(rName), testAccDeliveryStreamBaseElasticsearchVPCConfig(rName), @@ -3642,7 +3642,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { }`, rName)) } -func testAccDeliveryStreamConfig_ElasticsearchEndpoint(rName string) string { +func testAccDeliveryStreamConfig_elasticsearchEndpoint(rName string) string { return acctest.ConfigCompose( testAccDeliveryStreamBaseElasticsearchConfig(rName), fmt.Sprintf(` @@ -3666,7 +3666,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { }`, rName)) } -func testAccDeliveryStreamConfig_ElasticsearchEndpointUpdate(rName string) string { +func testAccDeliveryStreamConfig_elasticsearchEndpointUpdate(rName string) string { return acctest.ConfigCompose( testAccLambdaBasicConfig(rName), testAccDeliveryStreamBaseElasticsearchConfig(rName), @@ -3792,7 +3792,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { `, rName) } -func testAccPreCheckIamServiceLinkedRoleEs(t *testing.T) { +func testAccPreCheckIAMServiceLinkedRoleEs(t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).IAMConn dnsSuffix := acctest.Provider.Meta().(*conns.AWSClient).DNSSuffix diff --git a/internal/service/fsx/backup_test.go b/internal/service/fsx/backup_test.go index 26f9aac3acb..9fe4dfc6973 100644 --- a/internal/service/fsx/backup_test.go +++ b/internal/service/fsx/backup_test.go @@ -28,7 +28,7 @@ func TestAccFSxBackup_basic(t *testing.T) { CheckDestroy: testAccCheckBackupDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupBasicConfig(rName), + Config: testAccBackupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`backup/.+`)), @@ -59,7 +59,7 @@ func TestAccFSxBackup_ontapBasic(t *testing.T) { CheckDestroy: testAccCheckBackupDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupONTAPBasicConfig(rName, vName), + Config: testAccBackupConfig_ontapBasic(rName, vName), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`backup/.+`)), @@ -88,7 +88,7 @@ func TestAccFSxBackup_openzfsBasic(t *testing.T) { CheckDestroy: testAccCheckBackupDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupOpenzfsBasicConfig(rName), + Config: testAccBackupConfig_openZFSBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`backup/.+`)), @@ -117,7 +117,7 @@ func TestAccFSxBackup_windowsBasic(t *testing.T) { CheckDestroy: testAccCheckBackupDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupWindowsBasicConfig(rName), + Config: testAccBackupConfig_windowsBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`backup/.+`)), @@ -146,7 +146,7 @@ func TestAccFSxBackup_disappears(t *testing.T) { CheckDestroy: testAccCheckBackupDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupBasicConfig(rName), + Config: testAccBackupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceBackup(), resourceName), @@ -169,7 +169,7 @@ func TestAccFSxBackup_Disappears_filesystem(t *testing.T) { CheckDestroy: testAccCheckBackupDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupBasicConfig(rName), + Config: testAccBackupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceLustreFileSystem(), "aws_fsx_lustre_file_system.test"), @@ -192,7 +192,7 @@ func TestAccFSxBackup_tags(t *testing.T) { CheckDestroy: testAccCheckBackupDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupTags1Config(rName, "key1", "value1"), + Config: testAccBackupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -205,7 +205,7 @@ func TestAccFSxBackup_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBackupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccBackupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -214,7 +214,7 @@ func TestAccFSxBackup_tags(t *testing.T) { ), }, { - Config: testAccBackupTags1Config(rName, "key2", "value2"), + Config: testAccBackupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -236,7 +236,7 @@ func TestAccFSxBackup_implicitTags(t *testing.T) { CheckDestroy: testAccCheckBackupDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupImplictTagsConfig("key1", "value1"), + Config: testAccBackupConfig_implictTags("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckBackupExists(resourceName, &backup), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -407,7 +407,7 @@ resource "aws_fsx_windows_file_system" "test" { `, rName)) } -func testAccBackupBasicConfig(rName string) string { +func testAccBackupConfig_basic(rName string) string { return acctest.ConfigCompose(testAccBackupLustreBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_backup" "test" { file_system_id = aws_fsx_lustre_file_system.test.id @@ -419,7 +419,7 @@ resource "aws_fsx_backup" "test" { `, rName)) } -func testAccBackupONTAPBasicConfig(rName string, vName string) string { +func testAccBackupConfig_ontapBasic(rName string, vName string) string { return acctest.ConfigCompose(testAccBackupONTAPBaseConfig(rName, vName), fmt.Sprintf(` resource "aws_fsx_backup" "test" { volume_id = aws_fsx_ontap_volume.test.id @@ -431,7 +431,7 @@ resource "aws_fsx_backup" "test" { `, rName)) } -func testAccBackupOpenzfsBasicConfig(rName string) string { +func testAccBackupConfig_openZFSBasic(rName string) string { return acctest.ConfigCompose(testAccBackupOpenzfsBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_backup" "test" { file_system_id = aws_fsx_openzfs_file_system.test.id @@ -443,7 +443,7 @@ resource "aws_fsx_backup" "test" { `, rName)) } -func testAccBackupWindowsBasicConfig(rName string) string { +func testAccBackupConfig_windowsBasic(rName string) string { return acctest.ConfigCompose(testAccBackupWindowsBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_backup" "test" { file_system_id = aws_fsx_windows_file_system.test.id @@ -455,7 +455,7 @@ resource "aws_fsx_backup" "test" { `, rName)) } -func testAccBackupTags1Config(rName string, tagKey1, tagValue1 string) string { +func testAccBackupConfig_tags1(rName string, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccBackupLustreBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_backup" "test" { file_system_id = aws_fsx_lustre_file_system.test.id @@ -467,7 +467,7 @@ resource "aws_fsx_backup" "test" { `, tagKey1, tagValue1)) } -func testAccBackupTags2Config(rName string, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccBackupConfig_tags2(rName string, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccBackupLustreBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_backup" "test" { file_system_id = aws_fsx_lustre_file_system.test.id @@ -480,7 +480,7 @@ resource "aws_fsx_backup" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccBackupImplictTagsConfig(tagKey1, tagValue1 string) string { +func testAccBackupConfig_implictTags(tagKey1, tagValue1 string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/fsx/data_repository_association_test.go b/internal/service/fsx/data_repository_association_test.go index de1cc684a23..e3520f25200 100644 --- a/internal/service/fsx/data_repository_association_test.go +++ b/internal/service/fsx/data_repository_association_test.go @@ -293,7 +293,7 @@ func TestAccFSxDataRepositoryAssociation_deleteDataInFilesystem(t *testing.T) { CheckDestroy: testAccCheckDataRepositoryAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccDataRepositoryAssociationConfig_deleteDataInFilesystem(bucketName, fileSystemPath, "true"), + Config: testAccDataRepositoryAssociationConfig_deleteInFilesystem(bucketName, fileSystemPath, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckDataRepositoryAssociationExists(resourceName, &association), resource.TestCheckResourceAttr(resourceName, "delete_data_in_filesystem", "true"), @@ -615,7 +615,7 @@ resource "aws_fsx_data_repository_association" "test" { `, bucketPath, fileSystemPath, fileChunkSize)) } -func testAccDataRepositoryAssociationConfig_deleteDataInFilesystem(bucketName, fileSystemPath, deleteDataInFilesystem string) string { +func testAccDataRepositoryAssociationConfig_deleteInFilesystem(bucketName, fileSystemPath, deleteDataInFilesystem string) string { bucketPath := fmt.Sprintf("s3://%s", bucketName) return acctest.ConfigCompose(testAccDataRepositoryAssociationBucketConfig(bucketName), fmt.Sprintf(` resource "aws_fsx_data_repository_association" "test" { diff --git a/internal/service/fsx/lustre_file_system_test.go b/internal/service/fsx/lustre_file_system_test.go index 4e4f1b21094..9ed9164ae68 100644 --- a/internal/service/fsx/lustre_file_system_test.go +++ b/internal/service/fsx/lustre_file_system_test.go @@ -33,7 +33,7 @@ func TestAccFSxLustreFileSystem_basic(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemSubnetIds1Config(), + Config: testAccLustreFileSystemConfig_subnetIDs1(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`file-system/fs-.+`)), @@ -80,7 +80,7 @@ func TestAccFSxLustreFileSystem_disappears(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemSubnetIds1Config(), + Config: testAccLustreFileSystemConfig_subnetIDs1(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceLustreFileSystem(), resourceName), @@ -102,7 +102,7 @@ func TestAccFSxLustreFileSystem_dataCompression(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemCompressionConfig(), + Config: testAccLustreFileSystemConfig_compression(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "data_compression_type", fsx.DataCompressionTypeLz4), @@ -115,14 +115,14 @@ func TestAccFSxLustreFileSystem_dataCompression(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemSubnetIds1Config(), + Config: testAccLustreFileSystemConfig_subnetIDs1(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "data_compression_type", fsx.DataCompressionTypeNone), ), }, { - Config: testAccLustreFileSystemCompressionConfig(), + Config: testAccLustreFileSystemConfig_compression(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "data_compression_type", fsx.DataCompressionTypeLz4), @@ -144,7 +144,7 @@ func TestAccFSxLustreFileSystem_exportPath(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemExportPathConfig(rName, ""), + Config: testAccLustreFileSystemConfig_exportPath(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "export_path", fmt.Sprintf("s3://%s", rName)), @@ -158,7 +158,7 @@ func TestAccFSxLustreFileSystem_exportPath(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemExportPathConfig(rName, "/prefix/"), + Config: testAccLustreFileSystemConfig_exportPath(rName, "/prefix/"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemRecreated(&filesystem1, &filesystem2), @@ -183,7 +183,7 @@ func TestAccFSxLustreFileSystem_importPath(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemImportPathConfig(rName, ""), + Config: testAccLustreFileSystemConfig_importPath(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "import_path", fmt.Sprintf("s3://%s", rName)), @@ -196,7 +196,7 @@ func TestAccFSxLustreFileSystem_importPath(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemImportPathConfig(rName, "/prefix/"), + Config: testAccLustreFileSystemConfig_importPath(rName, "/prefix/"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemRecreated(&filesystem1, &filesystem2), @@ -220,7 +220,7 @@ func TestAccFSxLustreFileSystem_importedFileChunkSize(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemImportedFileChunkSizeConfig(rName, 2048), + Config: testAccLustreFileSystemConfig_importedChunkSize(rName, 2048), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "imported_file_chunk_size", "2048"), @@ -233,7 +233,7 @@ func TestAccFSxLustreFileSystem_importedFileChunkSize(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemImportedFileChunkSizeConfig(rName, 4096), + Config: testAccLustreFileSystemConfig_importedChunkSize(rName, 4096), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemRecreated(&filesystem1, &filesystem2), @@ -255,7 +255,7 @@ func TestAccFSxLustreFileSystem_securityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemSecurityGroupIds1Config(), + Config: testAccLustreFileSystemConfig_securityGroupIDs1(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), @@ -268,7 +268,7 @@ func TestAccFSxLustreFileSystem_securityGroupIDs(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemSecurityGroupIds2Config(), + Config: testAccLustreFileSystemConfig_securityGroupIDs2(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemRecreated(&filesystem1, &filesystem2), @@ -290,7 +290,7 @@ func TestAccFSxLustreFileSystem_storageCapacity(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemStorageCapacityConfig(7200), + Config: testAccLustreFileSystemConfig_storageCapacity(7200), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "storage_capacity", "7200"), @@ -303,7 +303,7 @@ func TestAccFSxLustreFileSystem_storageCapacity(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemStorageCapacityConfig(1200), + Config: testAccLustreFileSystemConfig_storageCapacity(1200), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemRecreated(&filesystem1, &filesystem2), @@ -325,7 +325,7 @@ func TestAccFSxLustreFileSystem_storageCapacityUpdate(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemStorageCapacityScratch2Config(7200), + Config: testAccLustreFileSystemConfig_storageCapacityScratch2(7200), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "storage_capacity", "7200"), @@ -338,7 +338,7 @@ func TestAccFSxLustreFileSystem_storageCapacityUpdate(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemStorageCapacityScratch2Config(1200), + Config: testAccLustreFileSystemConfig_storageCapacityScratch2(1200), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemRecreated(&filesystem1, &filesystem2), @@ -346,7 +346,7 @@ func TestAccFSxLustreFileSystem_storageCapacityUpdate(t *testing.T) { ), }, { - Config: testAccLustreFileSystemStorageCapacityScratch2Config(7200), + Config: testAccLustreFileSystemConfig_storageCapacityScratch2(7200), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem3), testAccCheckLustreFileSystemNotRecreated(&filesystem2, &filesystem3), @@ -368,7 +368,7 @@ func TestAccFSxLustreFileSystem_fileSystemTypeVersion(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemFileSystemTypeVersionConfig("2.10"), + Config: testAccLustreFileSystemConfig_typeVersion("2.10"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "file_system_type_version", "2.10"), @@ -381,7 +381,7 @@ func TestAccFSxLustreFileSystem_fileSystemTypeVersion(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemFileSystemTypeVersionConfig("2.12"), + Config: testAccLustreFileSystemConfig_typeVersion("2.12"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemRecreated(&filesystem1, &filesystem2), @@ -403,7 +403,7 @@ func TestAccFSxLustreFileSystem_tags(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemTags1Config("key1", "value1"), + Config: testAccLustreFileSystemConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -417,7 +417,7 @@ func TestAccFSxLustreFileSystem_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccLustreFileSystemConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -427,7 +427,7 @@ func TestAccFSxLustreFileSystem_tags(t *testing.T) { ), }, { - Config: testAccLustreFileSystemTags1Config("key2", "value2"), + Config: testAccLustreFileSystemConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem3), testAccCheckLustreFileSystemNotRecreated(&filesystem2, &filesystem3), @@ -450,7 +450,7 @@ func TestAccFSxLustreFileSystem_weeklyMaintenanceStartTime(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemWeeklyMaintenanceStartTimeConfig("1:01:01"), + Config: testAccLustreFileSystemConfig_weeklyMaintenanceStartTime("1:01:01"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "weekly_maintenance_start_time", "1:01:01"), @@ -463,7 +463,7 @@ func TestAccFSxLustreFileSystem_weeklyMaintenanceStartTime(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemWeeklyMaintenanceStartTimeConfig("2:02:02"), + Config: testAccLustreFileSystemConfig_weeklyMaintenanceStartTime("2:02:02"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -485,7 +485,7 @@ func TestAccFSxLustreFileSystem_automaticBackupRetentionDays(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemAutomaticBackupRetentionDaysConfig(90), + Config: testAccLustreFileSystemConfig_automaticBackupRetentionDays(90), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "automatic_backup_retention_days", "90"), @@ -498,7 +498,7 @@ func TestAccFSxLustreFileSystem_automaticBackupRetentionDays(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemAutomaticBackupRetentionDaysConfig(0), + Config: testAccLustreFileSystemConfig_automaticBackupRetentionDays(0), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -506,7 +506,7 @@ func TestAccFSxLustreFileSystem_automaticBackupRetentionDays(t *testing.T) { ), }, { - Config: testAccLustreFileSystemAutomaticBackupRetentionDaysConfig(1), + Config: testAccLustreFileSystemConfig_automaticBackupRetentionDays(1), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "automatic_backup_retention_days", "1"), @@ -527,7 +527,7 @@ func TestAccFSxLustreFileSystem_dailyAutomaticBackupStartTime(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemDailyAutomaticBackupStartTimeConfig("01:01"), + Config: testAccLustreFileSystemConfig_dailyAutomaticBackupStartTime("01:01"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "daily_automatic_backup_start_time", "01:01"), @@ -540,7 +540,7 @@ func TestAccFSxLustreFileSystem_dailyAutomaticBackupStartTime(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemDailyAutomaticBackupStartTimeConfig("02:02"), + Config: testAccLustreFileSystemConfig_dailyAutomaticBackupStartTime("02:02"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), testAccCheckLustreFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -562,7 +562,7 @@ func TestAccFSxLustreFileSystem_deploymentTypePersistent1(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemPersistent1DeploymentType(50), + Config: testAccLustreFileSystemConfig_persistent1DeploymentType(50), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), // per_unit_storage_throughput=50 is only available with deployment_type=PERSISTENT_1, so we test both here. @@ -595,7 +595,7 @@ func TestAccFSxLustreFileSystem_deploymentTypePersistent2(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemPersistent2DeploymentType(125), + Config: testAccLustreFileSystemConfig_persistent2DeploymentType(125), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), // per_unit_storage_throughput=125 is only available with deployment_type=PERSISTENT_2, so we test both here. @@ -629,7 +629,7 @@ func TestAccFSxLustreFileSystem_logConfig(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemLogConfig(rName, "WARN_ONLY"), + Config: testAccLustreFileSystemConfig_log(rName, "WARN_ONLY"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "log_configuration.#", "1"), @@ -644,7 +644,7 @@ func TestAccFSxLustreFileSystem_logConfig(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemLogConfig(rName, "ERROR_ONLY"), + Config: testAccLustreFileSystemConfig_log(rName, "ERROR_ONLY"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "log_configuration.#", "1"), @@ -667,7 +667,7 @@ func TestAccFSxLustreFileSystem_fromBackup(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemFromBackup(), + Config: testAccLustreFileSystemConfig_fromBackup(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "per_unit_storage_throughput", "50"), @@ -698,7 +698,7 @@ func TestAccFSxLustreFileSystem_kmsKeyID(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemKMSKeyId1Config(), + Config: testAccLustreFileSystemConfig_kmsKeyID1(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "deployment_type", fsx.LustreDeploymentTypePersistent1), @@ -712,7 +712,7 @@ func TestAccFSxLustreFileSystem_kmsKeyID(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemKMSKeyId2Config(), + Config: testAccLustreFileSystemConfig_kmsKeyID2(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem2), resource.TestCheckResourceAttr(resourceName, "deployment_type", fsx.LustreDeploymentTypePersistent1), @@ -735,7 +735,7 @@ func TestAccFSxLustreFileSystem_deploymentTypeScratch2(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemDeploymentType(fsx.LustreDeploymentTypeScratch2), + Config: testAccLustreFileSystemConfig_deploymentType(fsx.LustreDeploymentTypeScratch2), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "deployment_type", fsx.LustreDeploymentTypeScratch2), @@ -764,7 +764,7 @@ func TestAccFSxLustreFileSystem_storageTypeHddDriveCacheRead(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemHddStorageType(fsx.DriveCacheTypeRead), + Config: testAccLustreFileSystemConfig_hddStorageType(fsx.DriveCacheTypeRead), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "storage_type", fsx.StorageTypeHdd), @@ -792,7 +792,7 @@ func TestAccFSxLustreFileSystem_storageTypeHddDriveCacheNone(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemHddStorageType(fsx.DriveCacheTypeNone), + Config: testAccLustreFileSystemConfig_hddStorageType(fsx.DriveCacheTypeNone), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "storage_type", fsx.StorageTypeHdd), @@ -820,7 +820,7 @@ func TestAccFSxLustreFileSystem_copyTagsToBackups(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemCopyTagsToBackups(), + Config: testAccLustreFileSystemConfig_copyTagsToBackups(), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_backups", "true"), @@ -848,7 +848,7 @@ func TestAccFSxLustreFileSystem_autoImportPolicy(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccLustreFileSystemAutoImportPolicyConfig(rName, "", "NEW"), + Config: testAccLustreFileSystemConfig_autoImportPolicy(rName, "", "NEW"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "auto_import_policy", "NEW"), @@ -861,7 +861,7 @@ func TestAccFSxLustreFileSystem_autoImportPolicy(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccLustreFileSystemAutoImportPolicyConfig(rName, "", "NEW_CHANGED"), + Config: testAccLustreFileSystemConfig_autoImportPolicy(rName, "", "NEW_CHANGED"), Check: resource.ComposeTestCheckFunc( testAccCheckLustreFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "auto_import_policy", "NEW_CHANGED"), @@ -951,7 +951,7 @@ resource "aws_subnet" "test1" { `) } -func testAccLustreFileSystemExportPathConfig(rName, exportPrefix string) string { +func testAccLustreFileSystemConfig_exportPath(rName, exportPrefix string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -972,7 +972,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, rName, exportPrefix)) } -func testAccLustreFileSystemImportPathConfig(rName, importPrefix string) string { +func testAccLustreFileSystemConfig_importPath(rName, importPrefix string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -992,7 +992,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, rName, importPrefix)) } -func testAccLustreFileSystemImportedFileChunkSizeConfig(rName string, importedFileChunkSize int) string { +func testAccLustreFileSystemConfig_importedChunkSize(rName string, importedFileChunkSize int) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1013,7 +1013,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, rName, importedFileChunkSize)) } -func testAccLustreFileSystemSecurityGroupIds1Config() string { +func testAccLustreFileSystemConfig_securityGroupIDs1() string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), ` resource "aws_security_group" "test1" { description = "security group for FSx testing" @@ -1043,7 +1043,7 @@ resource "aws_fsx_lustre_file_system" "test" { `) } -func testAccLustreFileSystemSecurityGroupIds2Config() string { +func testAccLustreFileSystemConfig_securityGroupIDs2() string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), ` resource "aws_security_group" "test1" { description = "security group for FSx testing" @@ -1092,7 +1092,7 @@ resource "aws_fsx_lustre_file_system" "test" { `) } -func testAccLustreFileSystemFileSystemTypeVersionConfig(fileSystemTypeVersion string) string { +func testAccLustreFileSystemConfig_typeVersion(fileSystemTypeVersion string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { file_system_type_version = %[1]q @@ -1103,7 +1103,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, fileSystemTypeVersion)) } -func testAccLustreFileSystemStorageCapacityConfig(storageCapacity int) string { +func testAccLustreFileSystemConfig_storageCapacity(storageCapacity int) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = %[1]d @@ -1113,7 +1113,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, storageCapacity)) } -func testAccLustreFileSystemStorageCapacityScratch2Config(storageCapacity int) string { +func testAccLustreFileSystemConfig_storageCapacityScratch2(storageCapacity int) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = %[1]d @@ -1123,7 +1123,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, storageCapacity)) } -func testAccLustreFileSystemSubnetIds1Config() string { +func testAccLustreFileSystemConfig_subnetIDs1() string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), ` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1133,7 +1133,7 @@ resource "aws_fsx_lustre_file_system" "test" { `) } -func testAccLustreFileSystemTags1Config(tagKey1, tagValue1 string) string { +func testAccLustreFileSystemConfig_tags1(tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1147,7 +1147,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, tagKey1, tagValue1)) } -func testAccLustreFileSystemTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccLustreFileSystemConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1162,7 +1162,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccLustreFileSystemWeeklyMaintenanceStartTimeConfig(weeklyMaintenanceStartTime string) string { +func testAccLustreFileSystemConfig_weeklyMaintenanceStartTime(weeklyMaintenanceStartTime string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1173,7 +1173,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, weeklyMaintenanceStartTime)) } -func testAccLustreFileSystemDailyAutomaticBackupStartTimeConfig(dailyAutomaticBackupStartTime string) string { +func testAccLustreFileSystemConfig_dailyAutomaticBackupStartTime(dailyAutomaticBackupStartTime string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1186,7 +1186,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, dailyAutomaticBackupStartTime)) } -func testAccLustreFileSystemAutomaticBackupRetentionDaysConfig(retention int) string { +func testAccLustreFileSystemConfig_automaticBackupRetentionDays(retention int) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1198,7 +1198,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, retention)) } -func testAccLustreFileSystemDeploymentType(deploymentType string) string { +func testAccLustreFileSystemConfig_deploymentType(deploymentType string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1208,7 +1208,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, deploymentType)) } -func testAccLustreFileSystemPersistent1DeploymentType(perUnitStorageThroughput int) string { +func testAccLustreFileSystemConfig_persistent1DeploymentType(perUnitStorageThroughput int) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1219,7 +1219,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, perUnitStorageThroughput)) } -func testAccLustreFileSystemPersistent2DeploymentType(perUnitStorageThroughput int) string { +func testAccLustreFileSystemConfig_persistent2DeploymentType(perUnitStorageThroughput int) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1230,7 +1230,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, perUnitStorageThroughput)) } -func testAccLustreFileSystemFromBackup() string { +func testAccLustreFileSystemConfig_fromBackup() string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), ` resource "aws_fsx_lustre_file_system" "base" { storage_capacity = 1200 @@ -1253,7 +1253,7 @@ resource "aws_fsx_lustre_file_system" "test" { `) } -func testAccLustreFileSystemKMSKeyId1Config() string { +func testAccLustreFileSystemConfig_kmsKeyID1() string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), ` resource "aws_kms_key" "test1" { description = "FSx KMS Testing key" @@ -1270,7 +1270,7 @@ resource "aws_fsx_lustre_file_system" "test" { `) } -func testAccLustreFileSystemKMSKeyId2Config() string { +func testAccLustreFileSystemConfig_kmsKeyID2() string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), ` resource "aws_kms_key" "test2" { description = "FSx KMS Testing key" @@ -1287,7 +1287,7 @@ resource "aws_fsx_lustre_file_system" "test" { `) } -func testAccLustreFileSystemHddStorageType(drive_cache_type string) string { +func testAccLustreFileSystemConfig_hddStorageType(drive_cache_type string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 6000 @@ -1300,7 +1300,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, drive_cache_type)) } -func testAccLustreFileSystemAutoImportPolicyConfig(rName, exportPrefix, policy string) string { +func testAccLustreFileSystemConfig_autoImportPolicy(rName, exportPrefix, policy string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1322,7 +1322,7 @@ resource "aws_fsx_lustre_file_system" "test" { `, rName, exportPrefix, policy)) } -func testAccLustreFileSystemCopyTagsToBackups() string { +func testAccLustreFileSystemConfig_copyTagsToBackups() string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), ` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1334,7 +1334,7 @@ resource "aws_fsx_lustre_file_system" "test" { `) } -func testAccLustreFileSystemCompressionConfig() string { +func testAccLustreFileSystemConfig_compression() string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), ` resource "aws_fsx_lustre_file_system" "test" { storage_capacity = 1200 @@ -1345,7 +1345,7 @@ resource "aws_fsx_lustre_file_system" "test" { `) } -func testAccLustreFileSystemLogConfig(rName, status string) string { +func testAccLustreFileSystemConfig_log(rName, status string) string { return acctest.ConfigCompose(testAccLustreFileSystemBaseConfig(), fmt.Sprintf(` resource aws_cloudwatch_log_group "test" { name = "/aws/fsx/%[1]s" diff --git a/internal/service/fsx/ontap_file_system_test.go b/internal/service/fsx/ontap_file_system_test.go index 4131847bc88..6e407c2424d 100644 --- a/internal/service/fsx/ontap_file_system_test.go +++ b/internal/service/fsx/ontap_file_system_test.go @@ -28,7 +28,7 @@ func TestAccFSxOntapFileSystem_basic(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemBasicConfig(rName), + Config: testAccONTAPFileSystemConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`file-system/fs-.+`)), @@ -82,7 +82,7 @@ func TestAccFSxOntapFileSystem_fsxSingleAz(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemSingleAzConfig(rName), + Config: testAccONTAPFileSystemConfig_singleAz(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`file-system/fs-.+`)), @@ -113,7 +113,7 @@ func TestAccFSxOntapFileSystem_fsxAdminPassword(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemConfig_adminPassword(rName, pass1), + Config: testAccONTAPFileSystemConfig_adminPassword(rName, pass1), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "fsx_admin_password", pass1), @@ -126,7 +126,7 @@ func TestAccFSxOntapFileSystem_fsxAdminPassword(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids", "fsx_admin_password"}, }, { - Config: testAccOntapFileSystemConfig_adminPassword(rName, pass2), + Config: testAccONTAPFileSystemConfig_adminPassword(rName, pass2), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem2), testAccCheckOntapFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -149,7 +149,7 @@ func TestAccFSxOntapFileSystem_endpointIPAddressRange(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemEndpointIPAddressRangeConfig(rName), + Config: testAccONTAPFileSystemConfig_endpointIPAddressRange(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "endpoint_ip_address_range", "198.19.255.0/24"), @@ -177,7 +177,7 @@ func TestAccFSxOntapFileSystem_diskIops(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemDiskIopsConfigurationConfig(rName, 3072), + Config: testAccONTAPFileSystemConfig_diskIOPSConfiguration(rName, 3072), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "disk_iops_configuration.#", "1"), @@ -192,7 +192,7 @@ func TestAccFSxOntapFileSystem_diskIops(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOntapFileSystemDiskIopsConfigurationConfig(rName, 4000), + Config: testAccONTAPFileSystemConfig_diskIOPSConfiguration(rName, 4000), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "disk_iops_configuration.#", "1"), @@ -216,7 +216,7 @@ func TestAccFSxOntapFileSystem_disappears(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemBasicConfig(rName), + Config: testAccONTAPFileSystemConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceOntapFileSystem(), resourceName), @@ -239,7 +239,7 @@ func TestAccFSxOntapFileSystem_securityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemSecurityGroupIds1Config(rName), + Config: testAccONTAPFileSystemConfig_securityGroupIDs1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), @@ -252,7 +252,7 @@ func TestAccFSxOntapFileSystem_securityGroupIDs(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOntapFileSystemSecurityGroupIds2Config(rName), + Config: testAccONTAPFileSystemConfig_securityGroupIDs2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem2), testAccCheckOntapFileSystemRecreated(&filesystem1, &filesystem2), @@ -275,7 +275,7 @@ func TestAccFSxOntapFileSystem_routeTableIDs(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemRouteTableConfig(rName), + Config: testAccONTAPFileSystemConfig_routeTable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "1"), @@ -304,7 +304,7 @@ func TestAccFSxOntapFileSystem_tags(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemTags1Config(rName, "key1", "value1"), + Config: testAccONTAPFileSystemConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -318,7 +318,7 @@ func TestAccFSxOntapFileSystem_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOntapFileSystemTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccONTAPFileSystemConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem2), testAccCheckOntapFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -328,7 +328,7 @@ func TestAccFSxOntapFileSystem_tags(t *testing.T) { ), }, { - Config: testAccOntapFileSystemTags1Config(rName, "key2", "value2"), + Config: testAccONTAPFileSystemConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem3), testAccCheckOntapFileSystemNotRecreated(&filesystem2, &filesystem3), @@ -352,7 +352,7 @@ func TestAccFSxOntapFileSystem_weeklyMaintenanceStartTime(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemWeeklyMaintenanceStartTimeConfig(rName, "1:01:01"), + Config: testAccONTAPFileSystemConfig_weeklyMaintenanceStartTime(rName, "1:01:01"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "weekly_maintenance_start_time", "1:01:01"), @@ -365,7 +365,7 @@ func TestAccFSxOntapFileSystem_weeklyMaintenanceStartTime(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOntapFileSystemWeeklyMaintenanceStartTimeConfig(rName, "2:02:02"), + Config: testAccONTAPFileSystemConfig_weeklyMaintenanceStartTime(rName, "2:02:02"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem2), testAccCheckOntapFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -388,7 +388,7 @@ func TestAccFSxOntapFileSystem_automaticBackupRetentionDays(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemAutomaticBackupRetentionDaysConfig(rName, 90), + Config: testAccONTAPFileSystemConfig_automaticBackupRetentionDays(rName, 90), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "automatic_backup_retention_days", "90"), @@ -401,7 +401,7 @@ func TestAccFSxOntapFileSystem_automaticBackupRetentionDays(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOntapFileSystemAutomaticBackupRetentionDaysConfig(rName, 0), + Config: testAccONTAPFileSystemConfig_automaticBackupRetentionDays(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem2), testAccCheckOntapFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -409,7 +409,7 @@ func TestAccFSxOntapFileSystem_automaticBackupRetentionDays(t *testing.T) { ), }, { - Config: testAccOntapFileSystemAutomaticBackupRetentionDaysConfig(rName, 1), + Config: testAccONTAPFileSystemConfig_automaticBackupRetentionDays(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "automatic_backup_retention_days", "1"), @@ -431,7 +431,7 @@ func TestAccFSxOntapFileSystem_kmsKeyID(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemKMSKeyIDConfig(rName), + Config: testAccONTAPFileSystemConfig_kmsKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", "aws_kms_key.test", "arn"), @@ -459,7 +459,7 @@ func TestAccFSxOntapFileSystem_dailyAutomaticBackupStartTime(t *testing.T) { CheckDestroy: testAccCheckLustreFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemDailyAutomaticBackupStartTimeConfig(rName, "01:01"), + Config: testAccONTAPFileSystemConfig_dailyAutomaticBackupStartTime(rName, "01:01"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "daily_automatic_backup_start_time", "01:01"), @@ -472,7 +472,7 @@ func TestAccFSxOntapFileSystem_dailyAutomaticBackupStartTime(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOntapFileSystemDailyAutomaticBackupStartTimeConfig(rName, "02:02"), + Config: testAccONTAPFileSystemConfig_dailyAutomaticBackupStartTime(rName, "02:02"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem2), testAccCheckOntapFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -495,7 +495,7 @@ func TestAccFSxOntapFileSystem_throughputCapacity(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemBasicConfig(rName), + Config: testAccONTAPFileSystemConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "throughput_capacity", "128"), @@ -508,7 +508,7 @@ func TestAccFSxOntapFileSystem_throughputCapacity(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOntapFileSystemThroughputCapacityConfig(rName), + Config: testAccONTAPFileSystemConfig_throughputCapacity(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem2), testAccCheckOntapFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -531,7 +531,7 @@ func TestAccFSxOntapFileSystem_storageCapacity(t *testing.T) { CheckDestroy: testAccCheckOntapFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapFileSystemBasicConfig(rName), + Config: testAccONTAPFileSystemConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "storage_capacity", "1024"), @@ -544,7 +544,7 @@ func TestAccFSxOntapFileSystem_storageCapacity(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOntapFileSystemStorageCapacityConfig(rName), + Config: testAccONTAPFileSystemConfig_storageCapacity(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapFileSystemExists(resourceName, &filesystem2), testAccCheckOntapFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -653,7 +653,7 @@ resource "aws_subnet" "test2" { `, rName)) } -func testAccOntapFileSystemBasicConfig(rName string) string { +func testAccONTAPFileSystemConfig_basic(rName string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), ` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -665,7 +665,7 @@ resource "aws_fsx_ontap_file_system" "test" { `) } -func testAccOntapFileSystemSingleAzConfig(rName string) string { +func testAccONTAPFileSystemConfig_singleAz(rName string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), ` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -677,7 +677,7 @@ resource "aws_fsx_ontap_file_system" "test" { `) } -func testAccOntapFileSystemConfig_adminPassword(rName, pass string) string { +func testAccONTAPFileSystemConfig_adminPassword(rName, pass string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -694,7 +694,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName, pass)) } -func testAccOntapFileSystemEndpointIPAddressRangeConfig(rName string) string { +func testAccONTAPFileSystemConfig_endpointIPAddressRange(rName string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -711,7 +711,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName)) } -func testAccOntapFileSystemDiskIopsConfigurationConfig(rName string, iops int) string { +func testAccONTAPFileSystemConfig_diskIOPSConfiguration(rName string, iops int) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -732,7 +732,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName, iops)) } -func testAccOntapFileSystemRouteTableConfig(rName string) string { +func testAccONTAPFileSystemConfig_routeTable(rName string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_internet_gateway" "test" { vpc_id = aws_vpc.test.id @@ -770,7 +770,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName)) } -func testAccOntapFileSystemSecurityGroupIds1Config(rName string) string { +func testAccONTAPFileSystemConfig_securityGroupIDs1(rName string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_security_group" "test1" { description = "security group for FSx testing" @@ -810,7 +810,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName)) } -func testAccOntapFileSystemSecurityGroupIds2Config(rName string) string { +func testAccONTAPFileSystemConfig_securityGroupIDs2(rName string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_security_group" "test1" { description = "security group for FSx testing" @@ -873,7 +873,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName)) } -func testAccOntapFileSystemTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccONTAPFileSystemConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -889,7 +889,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, tagKey1, tagValue1)) } -func testAccOntapFileSystemTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccONTAPFileSystemConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -906,7 +906,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccOntapFileSystemWeeklyMaintenanceStartTimeConfig(rName, weeklyMaintenanceStartTime string) string { +func testAccONTAPFileSystemConfig_weeklyMaintenanceStartTime(rName, weeklyMaintenanceStartTime string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -923,7 +923,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName, weeklyMaintenanceStartTime)) } -func testAccOntapFileSystemDailyAutomaticBackupStartTimeConfig(rName, dailyAutomaticBackupStartTime string) string { +func testAccONTAPFileSystemConfig_dailyAutomaticBackupStartTime(rName, dailyAutomaticBackupStartTime string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -941,7 +941,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName, dailyAutomaticBackupStartTime)) } -func testAccOntapFileSystemAutomaticBackupRetentionDaysConfig(rName string, retention int) string { +func testAccONTAPFileSystemConfig_automaticBackupRetentionDays(rName string, retention int) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -958,7 +958,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName, retention)) } -func testAccOntapFileSystemKMSKeyIDConfig(rName string) string { +func testAccONTAPFileSystemConfig_kmsKeyID(rName string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -980,7 +980,7 @@ resource "aws_fsx_ontap_file_system" "test" { `, rName)) } -func testAccOntapFileSystemThroughputCapacityConfig(rName string) string { +func testAccONTAPFileSystemConfig_throughputCapacity(rName string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), ` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 1024 @@ -992,7 +992,7 @@ resource "aws_fsx_ontap_file_system" "test" { `) } -func testAccOntapFileSystemStorageCapacityConfig(rName string) string { +func testAccONTAPFileSystemConfig_storageCapacity(rName string) string { return acctest.ConfigCompose(testAccOntapFileSystemBaseConfig(rName), ` resource "aws_fsx_ontap_file_system" "test" { storage_capacity = 2048 diff --git a/internal/service/fsx/ontap_storage_virtual_machine_test.go b/internal/service/fsx/ontap_storage_virtual_machine_test.go index 39a56360fa3..35f77cd4e1b 100644 --- a/internal/service/fsx/ontap_storage_virtual_machine_test.go +++ b/internal/service/fsx/ontap_storage_virtual_machine_test.go @@ -29,7 +29,7 @@ func TestAccFSxOntapStorageVirtualMachine_basic(t *testing.T) { CheckDestroy: testAccCheckOntapStorageVirtualMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapStorageVirtualMachineBasicConfig(rName), + Config: testAccONTAPStorageVirtualMachineConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`storage-virtual-machine/fs-.+`)), @@ -68,7 +68,7 @@ func TestAccFSxOntapStorageVirtualMachine_rootVolumeSecurityStyle(t *testing.T) CheckDestroy: testAccCheckOntapStorageVirtualMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapStorageVirtualMachineRootVolumeSecurityStyleConfig(rName), + Config: testAccONTAPStorageVirtualMachineConfig_rootVolumeSecurityStyle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`storage-virtual-machine/fs-.+`)), @@ -107,7 +107,7 @@ func TestAccFSxOntapStorageVirtualMachine_svmAdminPassword(t *testing.T) { CheckDestroy: testAccCheckOntapStorageVirtualMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapStorageVirtualMachineSvmAdminPasswordConfig(rName, pass1), + Config: testAccONTAPStorageVirtualMachineConfig_svmAdminPassword(rName, pass1), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine1), resource.TestCheckResourceAttr(resourceName, "svm_admin_password", pass1), @@ -120,7 +120,7 @@ func TestAccFSxOntapStorageVirtualMachine_svmAdminPassword(t *testing.T) { ImportStateVerifyIgnore: []string{"svm_admin_password"}, }, { - Config: testAccOntapStorageVirtualMachineSvmAdminPasswordConfig(rName, pass2), + Config: testAccONTAPStorageVirtualMachineConfig_svmAdminPassword(rName, pass2), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine2), testAccCheckOntapStorageVirtualMachineNotRecreated(&storageVirtualMachine1, &storageVirtualMachine2), @@ -143,7 +143,7 @@ func TestAccFSxOntapStorageVirtualMachine_disappears(t *testing.T) { CheckDestroy: testAccCheckOntapStorageVirtualMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapStorageVirtualMachineBasicConfig(rName), + Config: testAccONTAPStorageVirtualMachineConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceOntapStorageVirtualMachine(), resourceName), @@ -167,7 +167,7 @@ func TestAccFSxOntapStorageVirtualMachine_name(t *testing.T) { CheckDestroy: testAccCheckOntapStorageVirtualMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapStorageVirtualMachineBasicConfig(rName), + Config: testAccONTAPStorageVirtualMachineConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -179,7 +179,7 @@ func TestAccFSxOntapStorageVirtualMachine_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOntapStorageVirtualMachineBasicConfig(rName2), + Config: testAccONTAPStorageVirtualMachineConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine2), testAccCheckOntapStorageVirtualMachineRecreated(&storageVirtualMachine1, &storageVirtualMachine2), @@ -202,7 +202,7 @@ func TestAccFSxOntapStorageVirtualMachine_tags(t *testing.T) { CheckDestroy: testAccCheckOntapStorageVirtualMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapStorageVirtualMachineTags1Config(rName, "key1", "value1"), + Config: testAccONTAPStorageVirtualMachineConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -215,7 +215,7 @@ func TestAccFSxOntapStorageVirtualMachine_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOntapStorageVirtualMachineTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccONTAPStorageVirtualMachineConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine2), testAccCheckOntapStorageVirtualMachineNotRecreated(&storageVirtualMachine1, &storageVirtualMachine2), @@ -225,7 +225,7 @@ func TestAccFSxOntapStorageVirtualMachine_tags(t *testing.T) { ), }, { - Config: testAccOntapStorageVirtualMachineTags1Config(rName, "key2", "value2"), + Config: testAccONTAPStorageVirtualMachineConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine3), testAccCheckOntapStorageVirtualMachineNotRecreated(&storageVirtualMachine2, &storageVirtualMachine3), @@ -253,7 +253,7 @@ func TestAccFSxOntapStorageVirtualMachine_activeDirectory(t *testing.T) { CheckDestroy: testAccCheckOntapStorageVirtualMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapStorageVirtualMachineConfig_ontapStorageVirutalMachineSelfManagedActiveDirectory(rName, netBiosName, domainNetbiosName, domainName, domainPassword1), + Config: testAccONTAPStorageVirtualMachineConfig_virutalSelfManagedActiveDirectory(rName, netBiosName, domainNetbiosName, domainName, domainPassword1), Check: resource.ComposeTestCheckFunc( testAccCheckOntapStorageVirtualMachineExists(resourceName, &storageVirtualMachine1), resource.TestCheckResourceAttr(resourceName, "active_directory_configuration.#", "1"), @@ -404,7 +404,7 @@ resource "aws_directory_service_directory" "test" { `, rName, domainName, domainPassword)) } -func testAccOntapStorageVirtualMachineBasicConfig(rName string) string { +func testAccONTAPStorageVirtualMachineConfig_basic(rName string) string { return acctest.ConfigCompose(testAccOntapStorageVirtualMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_storage_virtual_machine" "test" { file_system_id = aws_fsx_ontap_file_system.test.id @@ -413,7 +413,7 @@ resource "aws_fsx_ontap_storage_virtual_machine" "test" { `, rName)) } -func testAccOntapStorageVirtualMachineRootVolumeSecurityStyleConfig(rName string) string { +func testAccONTAPStorageVirtualMachineConfig_rootVolumeSecurityStyle(rName string) string { return acctest.ConfigCompose(testAccOntapStorageVirtualMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_storage_virtual_machine" "test" { file_system_id = aws_fsx_ontap_file_system.test.id @@ -423,7 +423,7 @@ resource "aws_fsx_ontap_storage_virtual_machine" "test" { `, rName)) } -func testAccOntapStorageVirtualMachineSvmAdminPasswordConfig(rName string, pass string) string { +func testAccONTAPStorageVirtualMachineConfig_svmAdminPassword(rName string, pass string) string { return acctest.ConfigCompose(testAccOntapStorageVirtualMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_storage_virtual_machine" "test" { file_system_id = aws_fsx_ontap_file_system.test.id @@ -433,7 +433,7 @@ resource "aws_fsx_ontap_storage_virtual_machine" "test" { `, rName, pass)) } -func testAccOntapStorageVirtualMachineTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccONTAPStorageVirtualMachineConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccOntapStorageVirtualMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_storage_virtual_machine" "test" { file_system_id = aws_fsx_ontap_file_system.test.id @@ -446,7 +446,7 @@ resource "aws_fsx_ontap_storage_virtual_machine" "test" { `, rName, tagKey1, tagValue1)) } -func testAccOntapStorageVirtualMachineTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccONTAPStorageVirtualMachineConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccOntapStorageVirtualMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_storage_virtual_machine" "test" { file_system_id = aws_fsx_ontap_file_system.test.id @@ -460,7 +460,7 @@ resource "aws_fsx_ontap_storage_virtual_machine" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccOntapStorageVirtualMachineConfig_ontapStorageVirutalMachineSelfManagedActiveDirectory(rName string, netBiosName string, domainNetbiosName string, domainName string, domainPassword string) string { +func testAccONTAPStorageVirtualMachineConfig_virutalSelfManagedActiveDirectory(rName string, netBiosName string, domainNetbiosName string, domainName string, domainPassword string) string { return acctest.ConfigCompose(testAccOntapStorageVirtualMachineADConfig(rName, domainName, domainPassword), fmt.Sprintf(` resource "aws_fsx_ontap_storage_virtual_machine" "test" { file_system_id = aws_fsx_ontap_file_system.test.id diff --git a/internal/service/fsx/ontap_volume_test.go b/internal/service/fsx/ontap_volume_test.go index 9bdb1bffc4e..f6942db14a2 100644 --- a/internal/service/fsx/ontap_volume_test.go +++ b/internal/service/fsx/ontap_volume_test.go @@ -28,7 +28,7 @@ func TestAccFSxOntapVolume_basic(t *testing.T) { CheckDestroy: testAccCheckOntapVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapVolumeBasicConfig(rName), + Config: testAccONTAPVolumeConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`volume/fs-.+/fsvol-.+`)), @@ -66,7 +66,7 @@ func TestAccFSxOntapVolume_disappears(t *testing.T) { CheckDestroy: testAccCheckOntapVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapVolumeBasicConfig(rName), + Config: testAccONTAPVolumeConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceOntapVolume(), resourceName), @@ -90,7 +90,7 @@ func TestAccFSxOntapVolume_name(t *testing.T) { CheckDestroy: testAccCheckOntapVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapVolumeBasicConfig(rName), + Config: testAccONTAPVolumeConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -102,7 +102,7 @@ func TestAccFSxOntapVolume_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOntapVolumeBasicConfig(rName2), + Config: testAccONTAPVolumeConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume2), testAccCheckOntapVolumeRecreated(&volume1, &volume2), @@ -127,7 +127,7 @@ func TestAccFSxOntapVolume_junctionPath(t *testing.T) { CheckDestroy: testAccCheckOntapVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapVolumeJunctionPathConfig(rName, jPath1), + Config: testAccONTAPVolumeConfig_junctionPath(rName, jPath1), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -140,7 +140,7 @@ func TestAccFSxOntapVolume_junctionPath(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOntapVolumeJunctionPathConfig(rName, jPath2), + Config: testAccONTAPVolumeConfig_junctionPath(rName, jPath2), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume2), testAccCheckOntapVolumeNotRecreated(&volume1, &volume2), @@ -164,7 +164,7 @@ func TestAccFSxOntapVolume_securityStyle(t *testing.T) { CheckDestroy: testAccCheckOntapVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapVolumeSecurityStyleConfig(rName, "UNIX"), + Config: testAccONTAPVolumeConfig_securityStyle(rName, "UNIX"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -177,7 +177,7 @@ func TestAccFSxOntapVolume_securityStyle(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOntapVolumeSecurityStyleConfig(rName, "NTFS"), + Config: testAccONTAPVolumeConfig_securityStyle(rName, "NTFS"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume2), testAccCheckOntapVolumeNotRecreated(&volume1, &volume2), @@ -186,7 +186,7 @@ func TestAccFSxOntapVolume_securityStyle(t *testing.T) { ), }, { - Config: testAccOntapVolumeSecurityStyleConfig(rName, "MIXED"), + Config: testAccONTAPVolumeConfig_securityStyle(rName, "MIXED"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume3), testAccCheckOntapVolumeNotRecreated(&volume1, &volume3), @@ -212,7 +212,7 @@ func TestAccFSxOntapVolume_size(t *testing.T) { CheckDestroy: testAccCheckOntapVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapVolumeSizeConfig(rName, size1), + Config: testAccONTAPVolumeConfig_size(rName, size1), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -225,7 +225,7 @@ func TestAccFSxOntapVolume_size(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOntapVolumeSizeConfig(rName, size2), + Config: testAccONTAPVolumeConfig_size(rName, size2), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume2), testAccCheckOntapVolumeNotRecreated(&volume1, &volume2), @@ -249,7 +249,7 @@ func TestAccFSxOntapVolume_storageEfficiency(t *testing.T) { CheckDestroy: testAccCheckOntapVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapVolumeStorageEfficiencyConfig(rName, true), + Config: testAccONTAPVolumeConfig_storageEfficiency(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -262,7 +262,7 @@ func TestAccFSxOntapVolume_storageEfficiency(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOntapVolumeStorageEfficiencyConfig(rName, false), + Config: testAccONTAPVolumeConfig_storageEfficiency(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume2), testAccCheckOntapVolumeNotRecreated(&volume1, &volume2), @@ -286,7 +286,7 @@ func TestAccFSxOntapVolume_tags(t *testing.T) { CheckDestroy: testAccCheckOntapVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapVolumeTags1Config(rName, "key1", "value1"), + Config: testAccONTAPVolumeConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -299,7 +299,7 @@ func TestAccFSxOntapVolume_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOntapVolumeTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccONTAPVolumeConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume2), testAccCheckOntapVolumeNotRecreated(&volume1, &volume2), @@ -309,7 +309,7 @@ func TestAccFSxOntapVolume_tags(t *testing.T) { ), }, { - Config: testAccOntapVolumeTags1Config(rName, "key2", "value2"), + Config: testAccONTAPVolumeConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume3), testAccCheckOntapVolumeNotRecreated(&volume2, &volume3), @@ -333,7 +333,7 @@ func TestAccFSxOntapVolume_tieringPolicy(t *testing.T) { CheckDestroy: testAccCheckOntapVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOntapVolumeTieringPolicyNoCoolingConfig(rName, "NONE"), + Config: testAccONTAPVolumeConfig_tieringPolicyNoCooling(rName, "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -346,7 +346,7 @@ func TestAccFSxOntapVolume_tieringPolicy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOntapVolumeTieringPolicyConfig(rName, "SNAPSHOT_ONLY", 10), + Config: testAccONTAPVolumeConfig_tieringPolicy(rName, "SNAPSHOT_ONLY", 10), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume2), testAccCheckOntapVolumeNotRecreated(&volume1, &volume2), @@ -356,7 +356,7 @@ func TestAccFSxOntapVolume_tieringPolicy(t *testing.T) { ), }, { - Config: testAccOntapVolumeTieringPolicyConfig(rName, "AUTO", 60), + Config: testAccONTAPVolumeConfig_tieringPolicy(rName, "AUTO", 60), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume3), testAccCheckOntapVolumeNotRecreated(&volume1, &volume3), @@ -366,7 +366,7 @@ func TestAccFSxOntapVolume_tieringPolicy(t *testing.T) { ), }, { - Config: testAccOntapVolumeTieringPolicyNoCoolingConfig(rName, "ALL"), + Config: testAccONTAPVolumeConfig_tieringPolicyNoCooling(rName, "ALL"), Check: resource.ComposeTestCheckFunc( testAccCheckOntapVolumeExists(resourceName, &volume4), testAccCheckOntapVolumeNotRecreated(&volume1, &volume4), @@ -491,7 +491,7 @@ resource "aws_fsx_ontap_storage_virtual_machine" "test" { `, rName)) } -func testAccOntapVolumeBasicConfig(rName string) string { +func testAccONTAPVolumeConfig_basic(rName string) string { return acctest.ConfigCompose(testAccOntapVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_volume" "test" { name = %[1]q @@ -503,7 +503,7 @@ resource "aws_fsx_ontap_volume" "test" { `, rName)) } -func testAccOntapVolumeJunctionPathConfig(rName string, junctionPath string) string { +func testAccONTAPVolumeConfig_junctionPath(rName string, junctionPath string) string { return acctest.ConfigCompose(testAccOntapVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_volume" "test" { name = %[1]q @@ -515,7 +515,7 @@ resource "aws_fsx_ontap_volume" "test" { `, rName, junctionPath)) } -func testAccOntapVolumeSecurityStyleConfig(rName string, securityStyle string) string { +func testAccONTAPVolumeConfig_securityStyle(rName string, securityStyle string) string { return acctest.ConfigCompose(testAccOntapVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_volume" "test" { name = %[1]q @@ -528,7 +528,7 @@ resource "aws_fsx_ontap_volume" "test" { `, rName, securityStyle)) } -func testAccOntapVolumeSizeConfig(rName string, size int) string { +func testAccONTAPVolumeConfig_size(rName string, size int) string { return acctest.ConfigCompose(testAccOntapVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_volume" "test" { name = %[1]q @@ -540,7 +540,7 @@ resource "aws_fsx_ontap_volume" "test" { `, rName, size)) } -func testAccOntapVolumeStorageEfficiencyConfig(rName string, storageEfficiencyEnabled bool) string { +func testAccONTAPVolumeConfig_storageEfficiency(rName string, storageEfficiencyEnabled bool) string { return acctest.ConfigCompose(testAccOntapVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_volume" "test" { name = %[1]q @@ -552,7 +552,7 @@ resource "aws_fsx_ontap_volume" "test" { `, rName, storageEfficiencyEnabled)) } -func testAccOntapVolumeTieringPolicyConfig(rName string, policy string, coolingPeriod int) string { +func testAccONTAPVolumeConfig_tieringPolicy(rName string, policy string, coolingPeriod int) string { return acctest.ConfigCompose(testAccOntapVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_volume" "test" { name = %[1]q @@ -568,7 +568,7 @@ resource "aws_fsx_ontap_volume" "test" { `, rName, policy, coolingPeriod)) } -func testAccOntapVolumeTieringPolicyNoCoolingConfig(rName string, policy string) string { +func testAccONTAPVolumeConfig_tieringPolicyNoCooling(rName string, policy string) string { return acctest.ConfigCompose(testAccOntapVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_volume" "test" { name = %[1]q @@ -583,7 +583,7 @@ resource "aws_fsx_ontap_volume" "test" { `, rName, policy)) } -func testAccOntapVolumeTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccONTAPVolumeConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccOntapVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_volume" "test" { name = %[1]q @@ -599,7 +599,7 @@ resource "aws_fsx_ontap_volume" "test" { `, rName, tagKey1, tagValue1)) } -func testAccOntapVolumeTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccONTAPVolumeConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccOntapVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_ontap_volume" "test" { name = %[1]q diff --git a/internal/service/fsx/openzfs_file_system_test.go b/internal/service/fsx/openzfs_file_system_test.go index 7f8e4db8044..4d62cc34099 100644 --- a/internal/service/fsx/openzfs_file_system_test.go +++ b/internal/service/fsx/openzfs_file_system_test.go @@ -38,7 +38,7 @@ func TestAccFSxOpenzfsFileSystem_basic(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemBasicConfig(rName), + Config: testAccOpenZFSFileSystemConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`file-system/fs-.+`)), @@ -93,7 +93,7 @@ func TestAccFSxOpenzfsFileSystem_diskIops(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemDiskIopsConfigurationConfig(rName), + Config: testAccOpenZFSFileSystemConfig_diskIOPSConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "disk_iops_configuration.#", "1"), @@ -123,7 +123,7 @@ func TestAccFSxOpenzfsFileSystem_disappears(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemBasicConfig(rName), + Config: testAccOpenZFSFileSystemConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceOpenzfsFileSystem(), resourceName), @@ -146,7 +146,7 @@ func TestAccFSxOpenzfsFileSystem_rootVolume(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemRootVolume1Config(rName, "NONE", "false", 128), + Config: testAccOpenZFSFileSystemConfig_rootVolume1(rName, "NONE", "false", 128), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "root_volume_configuration.#", "1"), @@ -173,7 +173,7 @@ func TestAccFSxOpenzfsFileSystem_rootVolume(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOpenzfsFileSystemRootVolume2Config(rName, "ZSTD", "true", 256), + Config: testAccOpenZFSFileSystemConfig_rootVolume2(rName, "ZSTD", "true", 256), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem2), testAccCheckOpenzfsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -195,7 +195,7 @@ func TestAccFSxOpenzfsFileSystem_rootVolume(t *testing.T) { ), }, { - Config: testAccOpenzfsFileSystemRootVolume3ClientConfig(rName, "NONE", "false", 128, 1024), + Config: testAccOpenZFSFileSystemConfig_rootVolume3Client(rName, "NONE", "false", 128, 1024), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem3), testAccCheckOpenzfsFileSystemNotRecreated(&filesystem1, &filesystem3), @@ -238,7 +238,7 @@ func TestAccFSxOpenzfsFileSystem_rootVolume(t *testing.T) { ), }, { - Config: testAccOpenzfsFileSystemRootVolume4Config(rName, "NONE", "false", 128, 1024), + Config: testAccOpenZFSFileSystemConfig_rootVolume4(rName, "NONE", "false", 128, 1024), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "root_volume_configuration.#", "1"), @@ -284,7 +284,7 @@ func TestAccFSxOpenzfsFileSystem_securityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemSecurityGroupIds1Config(rName), + Config: testAccOpenZFSFileSystemConfig_securityGroupIDs1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), @@ -297,7 +297,7 @@ func TestAccFSxOpenzfsFileSystem_securityGroupIDs(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOpenzfsFileSystemSecurityGroupIds2Config(rName), + Config: testAccOpenZFSFileSystemConfig_securityGroupIDs2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem2), testAccCheckOpenzfsFileSystemRecreated(&filesystem1, &filesystem2), @@ -320,7 +320,7 @@ func TestAccFSxOpenzfsFileSystem_tags(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemTags1Config(rName, "key1", "value1"), + Config: testAccOpenZFSFileSystemConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -334,7 +334,7 @@ func TestAccFSxOpenzfsFileSystem_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOpenzfsFileSystemTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccOpenZFSFileSystemConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem2), testAccCheckOpenzfsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -344,7 +344,7 @@ func TestAccFSxOpenzfsFileSystem_tags(t *testing.T) { ), }, { - Config: testAccOpenzfsFileSystemTags1Config(rName, "key2", "value2"), + Config: testAccOpenZFSFileSystemConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem3), testAccCheckOpenzfsFileSystemNotRecreated(&filesystem2, &filesystem3), @@ -368,7 +368,7 @@ func TestAccFSxOpenzfsFileSystem_copyTags(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemCopyTagsConfig(rName, "key1", "value1", "true"), + Config: testAccOpenZFSFileSystemConfig_copyTags(rName, "key1", "value1", "true"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -384,7 +384,7 @@ func TestAccFSxOpenzfsFileSystem_copyTags(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOpenzfsFileSystemCopyTagsConfig(rName, "key1", "value1", "false"), + Config: testAccOpenZFSFileSystemConfig_copyTags(rName, "key1", "value1", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem2), testAccCheckOpenzfsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -409,7 +409,7 @@ func TestAccFSxOpenzfsFileSystem_throughput(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemThroughputConfig(rName, 64), + Config: testAccOpenZFSFileSystemConfig_throughput(rName, 64), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "throughput_capacity", "64"), @@ -422,7 +422,7 @@ func TestAccFSxOpenzfsFileSystem_throughput(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOpenzfsFileSystemThroughputConfig(rName, 128), + Config: testAccOpenZFSFileSystemConfig_throughput(rName, 128), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem2), testAccCheckOpenzfsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -445,7 +445,7 @@ func TestAccFSxOpenzfsFileSystem_storageType(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemStorageTypeConfig(rName, "SSD"), + Config: testAccOpenZFSFileSystemConfig_storageType(rName, "SSD"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "storage_type", "SSD"), @@ -473,7 +473,7 @@ func TestAccFSxOpenzfsFileSystem_weeklyMaintenanceStartTime(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemWeeklyMaintenanceStartTimeConfig(rName, "1:01:01"), + Config: testAccOpenZFSFileSystemConfig_weeklyMaintenanceStartTime(rName, "1:01:01"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "weekly_maintenance_start_time", "1:01:01"), @@ -486,7 +486,7 @@ func TestAccFSxOpenzfsFileSystem_weeklyMaintenanceStartTime(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOpenzfsFileSystemWeeklyMaintenanceStartTimeConfig(rName, "2:02:02"), + Config: testAccOpenZFSFileSystemConfig_weeklyMaintenanceStartTime(rName, "2:02:02"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem2), testAccCheckOpenzfsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -509,7 +509,7 @@ func TestAccFSxOpenzfsFileSystem_automaticBackupRetentionDays(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemAutomaticBackupRetentionDaysConfig(rName, 90), + Config: testAccOpenZFSFileSystemConfig_automaticBackupRetentionDays(rName, 90), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "automatic_backup_retention_days", "90"), @@ -522,7 +522,7 @@ func TestAccFSxOpenzfsFileSystem_automaticBackupRetentionDays(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOpenzfsFileSystemAutomaticBackupRetentionDaysConfig(rName, 0), + Config: testAccOpenZFSFileSystemConfig_automaticBackupRetentionDays(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem2), testAccCheckOpenzfsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -530,7 +530,7 @@ func TestAccFSxOpenzfsFileSystem_automaticBackupRetentionDays(t *testing.T) { ), }, { - Config: testAccOpenzfsFileSystemAutomaticBackupRetentionDaysConfig(rName, 1), + Config: testAccOpenZFSFileSystemConfig_automaticBackupRetentionDays(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "automatic_backup_retention_days", "1"), @@ -552,7 +552,7 @@ func TestAccFSxOpenzfsFileSystem_kmsKeyID(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemKMSKeyIDConfig(rName), + Config: testAccOpenZFSFileSystemConfig_kmsKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", "aws_kms_key.test", "arn"), @@ -580,7 +580,7 @@ func TestAccFSxOpenzfsFileSystem_dailyAutomaticBackupStartTime(t *testing.T) { CheckDestroy: testAccCheckOpenzfsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsFileSystemDailyAutomaticBackupStartTimeConfig(rName, "01:01"), + Config: testAccOpenZFSFileSystemConfig_dailyAutomaticBackupStartTime(rName, "01:01"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "daily_automatic_backup_start_time", "01:01"), @@ -593,7 +593,7 @@ func TestAccFSxOpenzfsFileSystem_dailyAutomaticBackupStartTime(t *testing.T) { ImportStateVerifyIgnore: []string{"security_group_ids"}, }, { - Config: testAccOpenzfsFileSystemDailyAutomaticBackupStartTimeConfig(rName, "02:02"), + Config: testAccOpenZFSFileSystemConfig_dailyAutomaticBackupStartTime(rName, "02:02"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsFileSystemExists(resourceName, &filesystem2), testAccCheckOpenzfsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -693,7 +693,7 @@ resource "aws_subnet" "test1" { `, rName)) } -func testAccOpenzfsFileSystemBasicConfig(rName string) string { +func testAccOpenZFSFileSystemConfig_basic(rName string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), ` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -704,7 +704,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `) } -func testAccOpenzfsFileSystemDiskIopsConfigurationConfig(rName string) string { +func testAccOpenZFSFileSystemConfig_diskIOPSConfiguration(rName string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), ` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -720,7 +720,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `) } -func testAccOpenzfsFileSystemSecurityGroupIds1Config(rName string) string { +func testAccOpenZFSFileSystemConfig_securityGroupIDs1(rName string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_security_group" "test1" { description = "security group for FSx testing" @@ -760,7 +760,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName)) } -func testAccOpenzfsFileSystemSecurityGroupIds2Config(rName string) string { +func testAccOpenZFSFileSystemConfig_securityGroupIDs2(rName string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_security_group" "test1" { description = "security group for FSx testing" @@ -823,7 +823,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName)) } -func testAccOpenzfsFileSystemTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccOpenZFSFileSystemConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -839,7 +839,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, tagKey1, tagValue1)) } -func testAccOpenzfsFileSystemTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccOpenZFSFileSystemConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -856,7 +856,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccOpenzfsFileSystemCopyTagsConfig(rName, tagKey1, tagValue1, copyTags string) string { +func testAccOpenZFSFileSystemConfig_copyTags(rName, tagKey1, tagValue1, copyTags string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -874,7 +874,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, tagKey1, tagValue1, copyTags)) } -func testAccOpenzfsFileSystemWeeklyMaintenanceStartTimeConfig(rName, weeklyMaintenanceStartTime string) string { +func testAccOpenZFSFileSystemConfig_weeklyMaintenanceStartTime(rName, weeklyMaintenanceStartTime string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -891,7 +891,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName, weeklyMaintenanceStartTime)) } -func testAccOpenzfsFileSystemDailyAutomaticBackupStartTimeConfig(rName, dailyAutomaticBackupStartTime string) string { +func testAccOpenZFSFileSystemConfig_dailyAutomaticBackupStartTime(rName, dailyAutomaticBackupStartTime string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -909,7 +909,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName, dailyAutomaticBackupStartTime)) } -func testAccOpenzfsFileSystemAutomaticBackupRetentionDaysConfig(rName string, retention int) string { +func testAccOpenZFSFileSystemConfig_automaticBackupRetentionDays(rName string, retention int) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -926,7 +926,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName, retention)) } -func testAccOpenzfsFileSystemKMSKeyIDConfig(rName string) string { +func testAccOpenZFSFileSystemConfig_kmsKeyID(rName string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -948,7 +948,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName)) } -func testAccOpenzfsFileSystemThroughputConfig(rName string, throughput int) string { +func testAccOpenZFSFileSystemConfig_throughput(rName string, throughput int) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -963,7 +963,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName, throughput)) } -func testAccOpenzfsFileSystemStorageTypeConfig(rName, storageType string) string { +func testAccOpenZFSFileSystemConfig_storageType(rName, storageType string) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -979,7 +979,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName, storageType)) } -func testAccOpenzfsFileSystemRootVolume1Config(rName, dataCompression, readOnly string, quotaSize int) string { +func testAccOpenZFSFileSystemConfig_rootVolume1(rName, dataCompression, readOnly string, quotaSize int) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -1010,7 +1010,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName, dataCompression, readOnly, quotaSize)) } -func testAccOpenzfsFileSystemRootVolume2Config(rName, dataCompression, readOnly string, quotaSize int) string { +func testAccOpenZFSFileSystemConfig_rootVolume2(rName, dataCompression, readOnly string, quotaSize int) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -1041,7 +1041,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName, dataCompression, readOnly, quotaSize)) } -func testAccOpenzfsFileSystemRootVolume3ClientConfig(rName, dataCompression, readOnly string, userQuota, groupQuota int) string { +func testAccOpenZFSFileSystemConfig_rootVolume3Client(rName, dataCompression, readOnly string, userQuota, groupQuota int) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 @@ -1091,7 +1091,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName, dataCompression, readOnly, userQuota, groupQuota)) } -func testAccOpenzfsFileSystemRootVolume4Config(rName, dataCompression, readOnly string, userQuota, groupQuota int) string { +func testAccOpenZFSFileSystemConfig_rootVolume4(rName, dataCompression, readOnly string, userQuota, groupQuota int) string { return acctest.ConfigCompose(testAccOpenzfsFileSystemBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_file_system" "test" { storage_capacity = 64 diff --git a/internal/service/fsx/openzfs_snapshot_test.go b/internal/service/fsx/openzfs_snapshot_test.go index a599f44f587..0b11663ad6c 100644 --- a/internal/service/fsx/openzfs_snapshot_test.go +++ b/internal/service/fsx/openzfs_snapshot_test.go @@ -28,7 +28,7 @@ func TestAccFSxOpenzfsSnapshot_basic(t *testing.T) { CheckDestroy: testAccCheckOpenzfsSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsSnapshotBasicConfig(rName), + Config: testAccOpenZFSSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`snapshot/.+`)), @@ -59,7 +59,7 @@ func TestAccFSxOpenzfsSnapshot_disappears(t *testing.T) { CheckDestroy: testAccCheckOpenzfsSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsSnapshotBasicConfig(rName), + Config: testAccOpenZFSSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceOpenzfsSnapshot(), resourceName), @@ -82,7 +82,7 @@ func TestAccFSxOpenzfsSnapshot_tags(t *testing.T) { CheckDestroy: testAccCheckOpenzfsSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsSnapshotTags1Config(rName, "key1", "value1"), + Config: testAccOpenZFSSnapshotConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -95,7 +95,7 @@ func TestAccFSxOpenzfsSnapshot_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsSnapshotTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccOpenZFSSnapshotConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -104,7 +104,7 @@ func TestAccFSxOpenzfsSnapshot_tags(t *testing.T) { ), }, { - Config: testAccOpenzfsSnapshotTags1Config(rName, "key2", "value2"), + Config: testAccOpenZFSSnapshotConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -128,7 +128,7 @@ func TestAccFSxOpenzfsSnapshot_name(t *testing.T) { CheckDestroy: testAccCheckOpenzfsSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsSnapshotBasicConfig(rName), + Config: testAccOpenZFSSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -140,7 +140,7 @@ func TestAccFSxOpenzfsSnapshot_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsSnapshotBasicConfig(rName2), + Config: testAccOpenZFSSnapshotConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot2), testAccCheckOpenzfsSnapshotNotRecreated(&snapshot1, &snapshot2), @@ -163,7 +163,7 @@ func TestAccFSxOpenzfsSnapshot_childVolume(t *testing.T) { CheckDestroy: testAccCheckOpenzfsSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsSnapshotChildVolumeConfig(rName), + Config: testAccOpenZFSSnapshotConfig_childVolume(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`snapshot/.+`)), @@ -193,7 +193,7 @@ func TestAccFSxOpenzfsSnapshot_volumeId(t *testing.T) { CheckDestroy: testAccCheckOpenzfsSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsSnapshotVolumeId1Config(rName), + Config: testAccOpenZFSSnapshotConfig_volumeID1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -205,7 +205,7 @@ func TestAccFSxOpenzfsSnapshot_volumeId(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsSnapshotVolumeId2Config(rName2), + Config: testAccOpenZFSSnapshotConfig_volumeID2(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsSnapshotExists(resourceName, &snapshot2), testAccCheckOpenzfsSnapshotRecreated(&snapshot1, &snapshot2), @@ -308,7 +308,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName)) } -func testAccOpenzfsSnapshotBasicConfig(rName string) string { +func testAccOpenZFSSnapshotConfig_basic(rName string) string { return acctest.ConfigCompose(testAccOpenzfsSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_snapshot" "test" { name = %[1]q @@ -317,7 +317,7 @@ resource "aws_fsx_openzfs_snapshot" "test" { `, rName)) } -func testAccOpenzfsSnapshotTags1Config(rName string, tagKey1, tagValue1 string) string { +func testAccOpenZFSSnapshotConfig_tags1(rName string, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccOpenzfsSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_snapshot" "test" { name = %[1]q @@ -330,7 +330,7 @@ resource "aws_fsx_openzfs_snapshot" "test" { `, rName, tagKey1, tagValue1)) } -func testAccOpenzfsSnapshotTags2Config(rName string, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccOpenZFSSnapshotConfig_tags2(rName string, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccOpenzfsSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_snapshot" "test" { name = %[1]q @@ -345,7 +345,7 @@ resource "aws_fsx_openzfs_snapshot" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccOpenzfsSnapshotChildVolumeConfig(rName string) string { +func testAccOpenZFSSnapshotConfig_childVolume(rName string) string { return acctest.ConfigCompose(testAccOpenzfsSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -359,7 +359,7 @@ resource "aws_fsx_openzfs_snapshot" "test" { `, rName)) } -func testAccOpenzfsSnapshotVolumeId1Config(rName string) string { +func testAccOpenZFSSnapshotConfig_volumeID1(rName string) string { return acctest.ConfigCompose(testAccOpenzfsSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test1" { name = %[1]q @@ -373,7 +373,7 @@ resource "aws_fsx_openzfs_snapshot" "test" { `, rName)) } -func testAccOpenzfsSnapshotVolumeId2Config(rName string) string { +func testAccOpenZFSSnapshotConfig_volumeID2(rName string) string { return acctest.ConfigCompose(testAccOpenzfsSnapshotBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test2" { name = %[1]q diff --git a/internal/service/fsx/openzfs_volume_test.go b/internal/service/fsx/openzfs_volume_test.go index 12555dcf6e6..a4471234199 100644 --- a/internal/service/fsx/openzfs_volume_test.go +++ b/internal/service/fsx/openzfs_volume_test.go @@ -28,7 +28,7 @@ func TestAccFSxOpenzfsVolume_basic(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeBasicConfig(rName), + Config: testAccOpenZFSVolumeConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`volume/fs-.+/fsvol-.+`)), @@ -70,7 +70,7 @@ func TestAccFSxOpenzfsVolume_parentVolume(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeParentVolumeConfig(rName, rName2), + Config: testAccOpenZFSVolumeConfig_parent(rName, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume), testAccCheckOpenzfsVolumeExists(resourceName2, &volume2), @@ -101,7 +101,7 @@ func TestAccFSxOpenzfsVolume_tags(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeTags1Config(rName, "key1", "value1"), + Config: testAccOpenZFSVolumeConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -114,7 +114,7 @@ func TestAccFSxOpenzfsVolume_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsVolumeTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccOpenZFSVolumeConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume2), testAccCheckOpenzfsVolumeNotRecreated(&volume1, &volume2), @@ -124,7 +124,7 @@ func TestAccFSxOpenzfsVolume_tags(t *testing.T) { ), }, { - Config: testAccOpenzfsVolumeTags1Config(rName, "key2", "value2"), + Config: testAccOpenZFSVolumeConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume3), testAccCheckOpenzfsVolumeNotRecreated(&volume2, &volume3), @@ -148,7 +148,7 @@ func TestAccFSxOpenzfsVolume_copyTags(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeCopyTagsConfig(rName, "key1", "value1", "true"), + Config: testAccOpenZFSVolumeConfig_copyTags(rName, "key1", "value1", "true"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -162,7 +162,7 @@ func TestAccFSxOpenzfsVolume_copyTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsVolumeCopyTagsConfig(rName, "key1", "value1", "false"), + Config: testAccOpenZFSVolumeConfig_copyTags(rName, "key1", "value1", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume2), testAccCheckOpenzfsVolumeRecreated(&volume1, &volume2), @@ -187,7 +187,7 @@ func TestAccFSxOpenzfsVolume_name(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeBasicConfig(rName), + Config: testAccOpenZFSVolumeConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -199,7 +199,7 @@ func TestAccFSxOpenzfsVolume_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsVolumeBasicConfig(rName2), + Config: testAccOpenZFSVolumeConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume2), testAccCheckOpenzfsVolumeNotRecreated(&volume1, &volume2), @@ -222,7 +222,7 @@ func TestAccFSxOpenzfsVolume_dataCompressionType(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeDataCompressionConfig(rName, "ZSTD"), + Config: testAccOpenZFSVolumeConfig_dataCompression(rName, "ZSTD"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "data_compression_type", "ZSTD"), @@ -234,7 +234,7 @@ func TestAccFSxOpenzfsVolume_dataCompressionType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsVolumeDataCompressionConfig(rName, "NONE"), + Config: testAccOpenZFSVolumeConfig_dataCompression(rName, "NONE"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume2), testAccCheckOpenzfsVolumeNotRecreated(&volume1, &volume2), @@ -257,7 +257,7 @@ func TestAccFSxOpenzfsVolume_readOnly(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeReadOnlyConfig(rName, "false"), + Config: testAccOpenZFSVolumeConfig_readOnly(rName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "read_only", "false"), @@ -269,7 +269,7 @@ func TestAccFSxOpenzfsVolume_readOnly(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsVolumeReadOnlyConfig(rName, "true"), + Config: testAccOpenZFSVolumeConfig_readOnly(rName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume2), testAccCheckOpenzfsVolumeNotRecreated(&volume1, &volume2), @@ -292,7 +292,7 @@ func TestAccFSxOpenzfsVolume_storageCapacity(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeStorageCapacityConfig(rName, 30, 20), + Config: testAccOpenZFSVolumeConfig_storageCapacity(rName, 30, 20), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "storage_capacity_quota_gib", "30"), @@ -305,7 +305,7 @@ func TestAccFSxOpenzfsVolume_storageCapacity(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsVolumeStorageCapacityConfig(rName, 40, 30), + Config: testAccOpenZFSVolumeConfig_storageCapacity(rName, 40, 30), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume2), testAccCheckOpenzfsVolumeNotRecreated(&volume1, &volume2), @@ -329,7 +329,7 @@ func TestAccFSxOpenzfsVolume_nfsExports(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeNFSExports1Config(rName), + Config: testAccOpenZFSVolumeConfig_nfsExports1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "nfs_exports.#", "1"), @@ -346,7 +346,7 @@ func TestAccFSxOpenzfsVolume_nfsExports(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsVolumeNFSExports2Config(rName), + Config: testAccOpenZFSVolumeConfig_nfsExports2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume2), testAccCheckOpenzfsVolumeNotRecreated(&volume1, &volume2), @@ -380,7 +380,7 @@ func TestAccFSxOpenzfsVolume_userAndGroupQuotas(t *testing.T) { CheckDestroy: testAccCheckOpenzfsVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccOpenzfsVolumeUserAndGroupQuotas1Config(rName, 256), + Config: testAccOpenZFSVolumeConfig_userAndGroupQuotas1(rName, 256), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume1), resource.TestCheckResourceAttr(resourceName, "user_and_group_quotas.#", "1"), @@ -397,7 +397,7 @@ func TestAccFSxOpenzfsVolume_userAndGroupQuotas(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOpenzfsVolumeUserAndGroupQuotas2Config(rName, 128, 1024), + Config: testAccOpenZFSVolumeConfig_userAndGroupQuotas2(rName, 128, 1024), Check: resource.ComposeTestCheckFunc( testAccCheckOpenzfsVolumeExists(resourceName, &volume2), testAccCheckOpenzfsVolumeNotRecreated(&volume1, &volume2), @@ -536,7 +536,7 @@ resource "aws_fsx_openzfs_file_system" "test" { `, rName)) } -func testAccOpenzfsVolumeBasicConfig(rName string) string { +func testAccOpenZFSVolumeConfig_basic(rName string) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -545,7 +545,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName)) } -func testAccOpenzfsVolumeParentVolumeConfig(rName, rName2 string) string { +func testAccOpenZFSVolumeConfig_parent(rName, rName2 string) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -559,7 +559,7 @@ resource "aws_fsx_openzfs_volume" "test2" { `, rName, rName2)) } -func testAccOpenzfsVolumeTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccOpenZFSVolumeConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -572,7 +572,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName, tagKey1, tagValue1)) } -func testAccOpenzfsVolumeTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccOpenZFSVolumeConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -587,7 +587,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccOpenzfsVolumeCopyTagsConfig(rName, tagKey1, tagValue1, copyTags string) string { +func testAccOpenZFSVolumeConfig_copyTags(rName, tagKey1, tagValue1, copyTags string) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -601,7 +601,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName, tagKey1, tagValue1, copyTags)) } -func testAccOpenzfsVolumeDataCompressionConfig(rName, dType string) string { +func testAccOpenZFSVolumeConfig_dataCompression(rName, dType string) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -611,7 +611,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName, dType)) } -func testAccOpenzfsVolumeReadOnlyConfig(rName, readOnly string) string { +func testAccOpenZFSVolumeConfig_readOnly(rName, readOnly string) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -621,7 +621,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName, readOnly)) } -func testAccOpenzfsVolumeStorageCapacityConfig(rName string, storageQuota, storageReservation int) string { +func testAccOpenZFSVolumeConfig_storageCapacity(rName string, storageQuota, storageReservation int) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -632,7 +632,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName, storageQuota, storageReservation)) } -func testAccOpenzfsVolumeNFSExports1Config(rName string) string { +func testAccOpenZFSVolumeConfig_nfsExports1(rName string) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -648,7 +648,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName)) } -func testAccOpenzfsVolumeNFSExports2Config(rName string) string { +func testAccOpenZFSVolumeConfig_nfsExports2(rName string) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -667,7 +667,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName)) } -func testAccOpenzfsVolumeUserAndGroupQuotas1Config(rName string, quotaSize int) string { +func testAccOpenZFSVolumeConfig_userAndGroupQuotas1(rName string, quotaSize int) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q @@ -681,7 +681,7 @@ resource "aws_fsx_openzfs_volume" "test" { `, rName, quotaSize)) } -func testAccOpenzfsVolumeUserAndGroupQuotas2Config(rName string, userQuota, groupQuota int) string { +func testAccOpenZFSVolumeConfig_userAndGroupQuotas2(rName string, userQuota, groupQuota int) string { return acctest.ConfigCompose(testAccOpenzfsVolumeBaseConfig(rName), fmt.Sprintf(` resource "aws_fsx_openzfs_volume" "test" { name = %[1]q diff --git a/internal/service/fsx/windows_file_system_test.go b/internal/service/fsx/windows_file_system_test.go index c4c74f6d87e..e2da692047f 100644 --- a/internal/service/fsx/windows_file_system_test.go +++ b/internal/service/fsx/windows_file_system_test.go @@ -27,7 +27,7 @@ func TestAccFSxWindowsFileSystem_basic(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemSubnetIds1Config(), + Config: testAccWindowsFileSystemConfig_subnetIDs1(), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`file-system/fs-.+`)), @@ -65,7 +65,7 @@ func TestAccFSxWindowsFileSystem_basic(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemSubnetIds1WithSingleTypeConfig("SINGLE_AZ_1"), + Config: testAccWindowsFileSystemConfig_subnetIDs1SingleType("SINGLE_AZ_1"), PlanOnly: true, }, }, @@ -83,7 +83,7 @@ func TestAccFSxWindowsFileSystem_singleAz2(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemSubnetIds1WithSingleTypeConfig("SINGLE_AZ_2"), + Config: testAccWindowsFileSystemConfig_subnetIDs1SingleType("SINGLE_AZ_2"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`file-system/fs-.+`)), @@ -132,7 +132,7 @@ func TestAccFSxWindowsFileSystem_storageTypeHdd(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemSubnetIds1WithStorageTypeConfig("SINGLE_AZ_2", "HDD"), + Config: testAccWindowsFileSystemConfig_subnetIDs1StorageType("SINGLE_AZ_2", "HDD"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "deployment_type", "SINGLE_AZ_2"), @@ -163,7 +163,7 @@ func TestAccFSxWindowsFileSystem_multiAz(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemSubnetIds2Config(), + Config: testAccWindowsFileSystemConfig_subnetIDs2(), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "fsx", regexp.MustCompile(`file-system/fs-.+`)), @@ -211,7 +211,7 @@ func TestAccFSxWindowsFileSystem_disappears(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemSubnetIds1Config(), + Config: testAccWindowsFileSystemConfig_subnetIDs1(), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceWindowsFileSystem(), resourceName), @@ -233,7 +233,7 @@ func TestAccFSxWindowsFileSystem_aliases(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemAliases1Config("filesystem1.example.com"), + Config: testAccWindowsFileSystemConfig_aliases1("filesystem1.example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "aliases.#", "1"), @@ -250,7 +250,7 @@ func TestAccFSxWindowsFileSystem_aliases(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemAliases2Config("filesystem2.example.com", "filesystem3.example.com"), + Config: testAccWindowsFileSystemConfig_aliases2("filesystem2.example.com", "filesystem3.example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -260,7 +260,7 @@ func TestAccFSxWindowsFileSystem_aliases(t *testing.T) { ), }, { - Config: testAccWindowsFileSystemAliases1Config("filesystem3.example.com"), + Config: testAccWindowsFileSystemConfig_aliases1("filesystem3.example.com"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem3), testAccCheckWindowsFileSystemNotRecreated(&filesystem2, &filesystem3), @@ -283,7 +283,7 @@ func TestAccFSxWindowsFileSystem_automaticBackupRetentionDays(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemAutomaticBackupRetentionDaysConfig(90), + Config: testAccWindowsFileSystemConfig_automaticBackupRetentionDays(90), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "automatic_backup_retention_days", "90"), @@ -299,7 +299,7 @@ func TestAccFSxWindowsFileSystem_automaticBackupRetentionDays(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemAutomaticBackupRetentionDaysConfig(0), + Config: testAccWindowsFileSystemConfig_automaticBackupRetentionDays(0), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -307,7 +307,7 @@ func TestAccFSxWindowsFileSystem_automaticBackupRetentionDays(t *testing.T) { ), }, { - Config: testAccWindowsFileSystemAutomaticBackupRetentionDaysConfig(14), + Config: testAccWindowsFileSystemConfig_automaticBackupRetentionDays(14), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem3), testAccCheckWindowsFileSystemNotRecreated(&filesystem2, &filesystem3), @@ -329,7 +329,7 @@ func TestAccFSxWindowsFileSystem_copyTagsToBackups(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemCopyTagsToBackupsConfig(true), + Config: testAccWindowsFileSystemConfig_copyTagsToBackups(true), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_backups", "true"), @@ -345,7 +345,7 @@ func TestAccFSxWindowsFileSystem_copyTagsToBackups(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemCopyTagsToBackupsConfig(false), + Config: testAccWindowsFileSystemConfig_copyTagsToBackups(false), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemRecreated(&filesystem1, &filesystem2), @@ -367,7 +367,7 @@ func TestAccFSxWindowsFileSystem_dailyAutomaticBackupStartTime(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemDailyAutomaticBackupStartTimeConfig("01:01"), + Config: testAccWindowsFileSystemConfig_dailyAutomaticBackupStartTime("01:01"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "daily_automatic_backup_start_time", "01:01"), @@ -383,7 +383,7 @@ func TestAccFSxWindowsFileSystem_dailyAutomaticBackupStartTime(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemDailyAutomaticBackupStartTimeConfig("02:02"), + Config: testAccWindowsFileSystemConfig_dailyAutomaticBackupStartTime("02:02"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -407,7 +407,7 @@ func TestAccFSxWindowsFileSystem_kmsKeyID(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemKMSKeyId1Config(), + Config: testAccWindowsFileSystemConfig_kmsKeyID1(), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsKeyResourceName1, "arn"), @@ -423,7 +423,7 @@ func TestAccFSxWindowsFileSystem_kmsKeyID(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemKMSKeyId2Config(), + Config: testAccWindowsFileSystemConfig_kmsKeyID2(), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemRecreated(&filesystem1, &filesystem2), @@ -445,7 +445,7 @@ func TestAccFSxWindowsFileSystem_securityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemSecurityGroupIds1Config(), + Config: testAccWindowsFileSystemConfig_securityGroupIDs1(), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), @@ -461,7 +461,7 @@ func TestAccFSxWindowsFileSystem_securityGroupIDs(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemSecurityGroupIds2Config(), + Config: testAccWindowsFileSystemConfig_securityGroupIDs2(), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemRecreated(&filesystem1, &filesystem2), @@ -483,7 +483,7 @@ func TestAccFSxWindowsFileSystem_selfManagedActiveDirectory(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemSelfManagedActiveDirectoryConfig(), + Config: testAccWindowsFileSystemConfig_selfManagedActiveDirectory(), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "self_managed_active_directory.#", "1"), @@ -514,7 +514,7 @@ func TestAccFSxWindowsFileSystem_SelfManagedActiveDirectory_username(t *testing. CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemSelfManagedActiveDirectoryUsernameConfig("Admin"), + Config: testAccWindowsFileSystemConfig_selfManagedActiveDirectoryUsername("Admin"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "self_managed_active_directory.#", "1"), @@ -531,7 +531,7 @@ func TestAccFSxWindowsFileSystem_SelfManagedActiveDirectory_username(t *testing. }, }, { - Config: testAccWindowsFileSystemSelfManagedActiveDirectoryUsernameConfig("Administrator"), + Config: testAccWindowsFileSystemConfig_selfManagedActiveDirectoryUsername("Administrator"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "self_managed_active_directory.#", "1"), @@ -552,7 +552,7 @@ func TestAccFSxWindowsFileSystem_storageCapacity(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemStorageCapacityConfig(32), + Config: testAccWindowsFileSystemConfig_storageCapacity(32), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "storage_capacity", "32"), @@ -568,7 +568,7 @@ func TestAccFSxWindowsFileSystem_storageCapacity(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemStorageCapacityConfig(36), + Config: testAccWindowsFileSystemConfig_storageCapacity(36), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -590,7 +590,7 @@ func TestAccFSxWindowsFileSystem_fromBackup(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemFromBackup(), + Config: testAccWindowsFileSystemConfig_fromBackup(), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttrPair(resourceName, "backup_id", "aws_fsx_backup.test", "id"), @@ -621,7 +621,7 @@ func TestAccFSxWindowsFileSystem_tags(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemTags1Config("key1", "value1"), + Config: testAccWindowsFileSystemConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -638,7 +638,7 @@ func TestAccFSxWindowsFileSystem_tags(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemTags2Config("key1", "value1updated", "key2", "value2"), + Config: testAccWindowsFileSystemConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -648,7 +648,7 @@ func TestAccFSxWindowsFileSystem_tags(t *testing.T) { ), }, { - Config: testAccWindowsFileSystemTags1Config("key2", "value2"), + Config: testAccWindowsFileSystemConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem3), testAccCheckWindowsFileSystemNotRecreated(&filesystem2, &filesystem3), @@ -671,7 +671,7 @@ func TestAccFSxWindowsFileSystem_throughputCapacity(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemThroughputCapacityConfig(16), + Config: testAccWindowsFileSystemConfig_throughputCapacity(16), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "throughput_capacity", "16"), @@ -687,7 +687,7 @@ func TestAccFSxWindowsFileSystem_throughputCapacity(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemThroughputCapacityConfig(32), + Config: testAccWindowsFileSystemConfig_throughputCapacity(32), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -709,7 +709,7 @@ func TestAccFSxWindowsFileSystem_weeklyMaintenanceStartTime(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemWeeklyMaintenanceStartTimeConfig("1:01:01"), + Config: testAccWindowsFileSystemConfig_weeklyMaintenanceStartTime("1:01:01"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem1), resource.TestCheckResourceAttr(resourceName, "weekly_maintenance_start_time", "1:01:01"), @@ -725,7 +725,7 @@ func TestAccFSxWindowsFileSystem_weeklyMaintenanceStartTime(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemWeeklyMaintenanceStartTimeConfig("2:02:02"), + Config: testAccWindowsFileSystemConfig_weeklyMaintenanceStartTime("2:02:02"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem2), testAccCheckWindowsFileSystemNotRecreated(&filesystem1, &filesystem2), @@ -748,7 +748,7 @@ func TestAccFSxWindowsFileSystem_audit(t *testing.T) { CheckDestroy: testAccCheckWindowsFileSystemDestroy, Steps: []resource.TestStep{ { - Config: testAccWindowsFileSystemAuditConfig(rName, "SUCCESS_ONLY"), + Config: testAccWindowsFileSystemConfig_audit(rName, "SUCCESS_ONLY"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "audit_log_configuration.#", "1"), @@ -767,7 +767,7 @@ func TestAccFSxWindowsFileSystem_audit(t *testing.T) { }, }, { - Config: testAccWindowsFileSystemAuditConfig(rName, "SUCCESS_AND_FAILURE"), + Config: testAccWindowsFileSystemConfig_audit(rName, "SUCCESS_AND_FAILURE"), Check: resource.ComposeTestCheckFunc( testAccCheckWindowsFileSystemExists(resourceName, &filesystem), resource.TestCheckResourceAttr(resourceName, "audit_log_configuration.#", "1"), @@ -885,7 +885,7 @@ resource "aws_directory_service_directory" "test" { ` } -func testAccWindowsFileSystemAliases1Config(alias1 string) string { +func testAccWindowsFileSystemConfig_aliases1(alias1 string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -899,7 +899,7 @@ resource "aws_fsx_windows_file_system" "test" { `, alias1) } -func testAccWindowsFileSystemAliases2Config(alias1, alias2 string) string { +func testAccWindowsFileSystemConfig_aliases2(alias1, alias2 string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -913,7 +913,7 @@ resource "aws_fsx_windows_file_system" "test" { `, alias1, alias2) } -func testAccWindowsFileSystemAutomaticBackupRetentionDaysConfig(automaticBackupRetentionDays int) string { +func testAccWindowsFileSystemConfig_automaticBackupRetentionDays(automaticBackupRetentionDays int) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -926,7 +926,7 @@ resource "aws_fsx_windows_file_system" "test" { `, automaticBackupRetentionDays) } -func testAccWindowsFileSystemCopyTagsToBackupsConfig(copyTagsToBackups bool) string { +func testAccWindowsFileSystemConfig_copyTagsToBackups(copyTagsToBackups bool) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -939,7 +939,7 @@ resource "aws_fsx_windows_file_system" "test" { `, copyTagsToBackups) } -func testAccWindowsFileSystemDailyAutomaticBackupStartTimeConfig(dailyAutomaticBackupStartTime string) string { +func testAccWindowsFileSystemConfig_dailyAutomaticBackupStartTime(dailyAutomaticBackupStartTime string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -952,7 +952,7 @@ resource "aws_fsx_windows_file_system" "test" { `, dailyAutomaticBackupStartTime) } -func testAccWindowsFileSystemKMSKeyId1Config() string { +func testAccWindowsFileSystemConfig_kmsKeyID1() string { return testAccWindowsFileSystemBaseConfig() + ` resource "aws_kms_key" "test1" { description = "FSx KMS Testing key" @@ -970,7 +970,7 @@ resource "aws_fsx_windows_file_system" "test" { ` } -func testAccWindowsFileSystemKMSKeyId2Config() string { +func testAccWindowsFileSystemConfig_kmsKeyID2() string { return testAccWindowsFileSystemBaseConfig() + ` resource "aws_kms_key" "test2" { description = "FSx KMS Testing key" @@ -988,7 +988,7 @@ resource "aws_fsx_windows_file_system" "test" { ` } -func testAccWindowsFileSystemSecurityGroupIds1Config() string { +func testAccWindowsFileSystemConfig_securityGroupIDs1() string { return testAccWindowsFileSystemBaseConfig() + ` resource "aws_security_group" "test1" { description = "security group for FSx testing" @@ -1020,7 +1020,7 @@ resource "aws_fsx_windows_file_system" "test" { ` } -func testAccWindowsFileSystemSecurityGroupIds2Config() string { +func testAccWindowsFileSystemConfig_securityGroupIDs2() string { return testAccWindowsFileSystemBaseConfig() + ` resource "aws_security_group" "test1" { description = "security group for FSx testing" @@ -1071,7 +1071,7 @@ resource "aws_fsx_windows_file_system" "test" { ` } -func testAccWindowsFileSystemSelfManagedActiveDirectoryConfig() string { +func testAccWindowsFileSystemConfig_selfManagedActiveDirectory() string { return testAccWindowsFileSystemBaseConfig() + ` resource "aws_fsx_windows_file_system" "test" { skip_final_backup = true @@ -1089,7 +1089,7 @@ resource "aws_fsx_windows_file_system" "test" { ` } -func testAccWindowsFileSystemSelfManagedActiveDirectoryUsernameConfig(username string) string { +func testAccWindowsFileSystemConfig_selfManagedActiveDirectoryUsername(username string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { skip_final_backup = true @@ -1107,7 +1107,7 @@ resource "aws_fsx_windows_file_system" "test" { `, username) } -func testAccWindowsFileSystemStorageCapacityConfig(storageCapacity int) string { +func testAccWindowsFileSystemConfig_storageCapacity(storageCapacity int) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -1119,7 +1119,7 @@ resource "aws_fsx_windows_file_system" "test" { `, storageCapacity) } -func testAccWindowsFileSystemSubnetIds1Config() string { +func testAccWindowsFileSystemConfig_subnetIDs1() string { return testAccWindowsFileSystemBaseConfig() + ` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -1131,7 +1131,7 @@ resource "aws_fsx_windows_file_system" "test" { ` } -func testAccWindowsFileSystemSubnetIds1WithSingleTypeConfig(azType string) string { +func testAccWindowsFileSystemConfig_subnetIDs1SingleType(azType string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -1144,7 +1144,7 @@ resource "aws_fsx_windows_file_system" "test" { `, azType) } -func testAccWindowsFileSystemSubnetIds1WithStorageTypeConfig(azType, storageType string) string { +func testAccWindowsFileSystemConfig_subnetIDs1StorageType(azType, storageType string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -1158,7 +1158,7 @@ resource "aws_fsx_windows_file_system" "test" { `, azType, storageType) } -func testAccWindowsFileSystemSubnetIds2Config() string { +func testAccWindowsFileSystemConfig_subnetIDs2() string { return acctest.ConfigCompose(testAccWindowsFileSystemBaseConfig(), ` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -1172,7 +1172,7 @@ resource "aws_fsx_windows_file_system" "test" { `) } -func testAccWindowsFileSystemFromBackup() string { +func testAccWindowsFileSystemConfig_fromBackup() string { return testAccWindowsFileSystemBaseConfig() + ` resource "aws_fsx_windows_file_system" "base" { active_directory_id = aws_directory_service_directory.test.id @@ -1196,7 +1196,7 @@ resource "aws_fsx_windows_file_system" "test" { ` } -func testAccWindowsFileSystemTags1Config(tagKey1, tagValue1 string) string { +func testAccWindowsFileSystemConfig_tags1(tagKey1, tagValue1 string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -1212,7 +1212,7 @@ resource "aws_fsx_windows_file_system" "test" { `, tagKey1, tagValue1) } -func testAccWindowsFileSystemTags2Config(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccWindowsFileSystemConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -1229,7 +1229,7 @@ resource "aws_fsx_windows_file_system" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccWindowsFileSystemThroughputCapacityConfig(throughputCapacity int) string { +func testAccWindowsFileSystemConfig_throughputCapacity(throughputCapacity int) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -1241,7 +1241,7 @@ resource "aws_fsx_windows_file_system" "test" { `, throughputCapacity) } -func testAccWindowsFileSystemWeeklyMaintenanceStartTimeConfig(weeklyMaintenanceStartTime string) string { +func testAccWindowsFileSystemConfig_weeklyMaintenanceStartTime(weeklyMaintenanceStartTime string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource "aws_fsx_windows_file_system" "test" { active_directory_id = aws_directory_service_directory.test.id @@ -1254,7 +1254,7 @@ resource "aws_fsx_windows_file_system" "test" { `, weeklyMaintenanceStartTime) } -func testAccWindowsFileSystemAuditConfig(rName, status string) string { +func testAccWindowsFileSystemConfig_audit(rName, status string) string { return testAccWindowsFileSystemBaseConfig() + fmt.Sprintf(` resource aws_cloudwatch_log_group "test" { name = "/aws/fsx/%[1]s" diff --git a/internal/service/gamelift/alias_test.go b/internal/service/gamelift/alias_test.go index 6aff52d52cb..1604460a61e 100644 --- a/internal/service/gamelift/alias_test.go +++ b/internal/service/gamelift/alias_test.go @@ -41,7 +41,7 @@ func TestAccGameLiftAlias_basic(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasBasicConfig(aliasName, description, message), + Config: testAccAliasConfig_basic(aliasName, description, message), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "gamelift", regexp.MustCompile(`alias/alias-.+`)), @@ -59,7 +59,7 @@ func TestAccGameLiftAlias_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAliasBasicConfig(uAliasName, uDescription, uMessage), + Config: testAccAliasConfig_basic(uAliasName, uDescription, uMessage), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "gamelift", regexp.MustCompile(`alias/.+`)), @@ -92,7 +92,7 @@ func TestAccGameLiftAlias_tags(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasBasicTags1Config(aliasName, "key1", "value1"), + Config: testAccAliasConfig_basicTags1(aliasName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -105,7 +105,7 @@ func TestAccGameLiftAlias_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAliasBasicTags2Config(aliasName, "key1", "value1updated", "key2", "value2"), + Config: testAccAliasConfig_basicTags2(aliasName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -114,7 +114,7 @@ func TestAccGameLiftAlias_tags(t *testing.T) { ), }, { - Config: testAccAliasBasicTags1Config(aliasName, "key2", "value2"), + Config: testAccAliasConfig_basicTags1(aliasName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -169,7 +169,7 @@ func TestAccGameLiftAlias_fleetRouting(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasAllFieldsConfig(aliasName, description, + Config: testAccAliasConfig_allFields(aliasName, description, fleetName, launchPath, params, bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &conf), @@ -211,7 +211,7 @@ func TestAccGameLiftAlias_disappears(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasBasicConfig(aliasName, description, message), + Config: testAccAliasConfig_basic(aliasName, description, message), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &conf), testAccCheckAliasDisappears(&conf), @@ -290,7 +290,7 @@ func testAccCheckAliasDestroy(s *terraform.State) error { return nil } -func testAccAliasBasicConfig(aliasName, description, message string) string { +func testAccAliasConfig_basic(aliasName, description, message string) string { return fmt.Sprintf(` resource "aws_gamelift_alias" "test" { name = "%s" @@ -304,7 +304,7 @@ resource "aws_gamelift_alias" "test" { `, aliasName, description, message) } -func testAccAliasBasicTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAliasConfig_basicTags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_gamelift_alias" "test" { name = %[1]q @@ -322,7 +322,7 @@ resource "aws_gamelift_alias" "test" { `, rName, tagKey1, tagValue1) } -func testAccAliasBasicTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAliasConfig_basicTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_gamelift_alias" "test" { name = %[1]q @@ -341,7 +341,7 @@ resource "aws_gamelift_alias" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccAliasAllFieldsConfig(aliasName, description, +func testAccAliasConfig_allFields(aliasName, description, fleetName, launchPath, params, bucketName, key, roleArn string) string { return fmt.Sprintf(` resource "aws_gamelift_alias" "test" { @@ -355,5 +355,5 @@ resource "aws_gamelift_alias" "test" { } %s `, aliasName, description, - testAccFleetBasicConfig(fleetName, launchPath, params, bucketName, key, roleArn)) + testAccFleetConfig_basic(fleetName, launchPath, params, bucketName, key, roleArn)) } diff --git a/internal/service/gamelift/build_test.go b/internal/service/gamelift/build_test.go index 849df1ab0d1..980c4aa65aa 100644 --- a/internal/service/gamelift/build_test.go +++ b/internal/service/gamelift/build_test.go @@ -50,7 +50,7 @@ func TestAccGameLiftBuild_basic(t *testing.T) { CheckDestroy: testAccCheckBuildDestroy, Steps: []resource.TestStep{ { - Config: testAccBuildBasicConfig(rName, bucketName, key, roleArn), + Config: testAccBuildConfig_basic(rName, bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckBuildExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -70,7 +70,7 @@ func TestAccGameLiftBuild_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"storage_location"}, }, { - Config: testAccBuildBasicConfig(rNameUpdated, bucketName, key, roleArn), + Config: testAccBuildConfig_basic(rNameUpdated, bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckBuildExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), @@ -120,7 +120,7 @@ func TestAccGameLiftBuild_tags(t *testing.T) { CheckDestroy: testAccCheckBuildDestroy, Steps: []resource.TestStep{ { - Config: testAccBuildBasicTags1Config(rName, bucketName, key, roleArn, "key1", "value1"), + Config: testAccBuildConfig_basicTags1(rName, bucketName, key, roleArn, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckBuildExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -134,7 +134,7 @@ func TestAccGameLiftBuild_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"storage_location"}, }, { - Config: testAccBuildBasicTags2Config(rName, bucketName, key, roleArn, "key1", "value1updated", "key2", "value2"), + Config: testAccBuildConfig_basicTags2(rName, bucketName, key, roleArn, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBuildExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -143,7 +143,7 @@ func TestAccGameLiftBuild_tags(t *testing.T) { ), }, { - Config: testAccBuildBasicTags1Config(rName, bucketName, key, roleArn, "key2", "value2"), + Config: testAccBuildConfig_basicTags1(rName, bucketName, key, roleArn, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBuildExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -187,7 +187,7 @@ func TestAccGameLiftBuild_disappears(t *testing.T) { CheckDestroy: testAccCheckBuildDestroy, Steps: []resource.TestStep{ { - Config: testAccBuildBasicConfig(rName, bucketName, key, roleArn), + Config: testAccBuildConfig_basic(rName, bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckBuildExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfgamelift.ResourceBuild(), resourceName), @@ -265,7 +265,7 @@ func testAccPreCheck(t *testing.T) { } } -func testAccBuildBasicConfig(buildName, bucketName, key, roleArn string) string { +func testAccBuildConfig_basic(buildName, bucketName, key, roleArn string) string { return fmt.Sprintf(` resource "aws_gamelift_build" "test" { name = "%s" @@ -280,7 +280,7 @@ resource "aws_gamelift_build" "test" { `, buildName, bucketName, key, roleArn) } -func testAccBuildBasicTags1Config(buildName, bucketName, key, roleArn, tagKey1, tagValue1 string) string { +func testAccBuildConfig_basicTags1(buildName, bucketName, key, roleArn, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_gamelift_build" "test" { name = %[1]q @@ -299,7 +299,7 @@ resource "aws_gamelift_build" "test" { `, buildName, bucketName, key, roleArn, tagKey1, tagValue1) } -func testAccBuildBasicTags2Config(buildName, bucketName, key, roleArn, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccBuildConfig_basicTags2(buildName, bucketName, key, roleArn, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_gamelift_build" "test" { name = %[1]q diff --git a/internal/service/gamelift/fleet.go b/internal/service/gamelift/fleet.go index a266ad18886..a2f35a69eb9 100644 --- a/internal/service/gamelift/fleet.go +++ b/internal/service/gamelift/fleet.go @@ -260,7 +260,7 @@ func resourceFleetCreate(d *schema.ResourceData, meta interface{}) error { input.FleetType = aws.String(v.(string)) } if v, ok := d.GetOk("ec2_inbound_permission"); ok { - input.EC2InboundPermissions = expandIpPermissions(v.(*schema.Set)) + input.EC2InboundPermissions = expandIPPermissions(v.(*schema.Set)) } if v, ok := d.GetOk("instance_role_arn"); ok { @@ -368,7 +368,7 @@ func resourceFleetRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error reading for GameLift Fleet ec2 inbound permission (%s): %w", d.Id(), err) } - if err := d.Set("ec2_inbound_permission", flattenIpPermissions(portConfig.InboundPermissions)); err != nil { + if err := d.Set("ec2_inbound_permission", flattenIPPermissions(portConfig.InboundPermissions)); err != nil { return fmt.Errorf("error setting ec2_inbound_permission: %w", err) } @@ -488,7 +488,7 @@ func resourceFleetDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func expandIpPermissions(cfgs *schema.Set) []*gamelift.IpPermission { +func expandIPPermissions(cfgs *schema.Set) []*gamelift.IpPermission { if cfgs.Len() < 1 { return []*gamelift.IpPermission{} } @@ -496,12 +496,12 @@ func expandIpPermissions(cfgs *schema.Set) []*gamelift.IpPermission { perms := make([]*gamelift.IpPermission, cfgs.Len()) for i, rawCfg := range cfgs.List() { cfg := rawCfg.(map[string]interface{}) - perms[i] = expandIpPermission(cfg) + perms[i] = expandIPPermission(cfg) } return perms } -func expandIpPermission(cfg map[string]interface{}) *gamelift.IpPermission { +func expandIPPermission(cfg map[string]interface{}) *gamelift.IpPermission { return &gamelift.IpPermission{ FromPort: aws.Int64(int64(cfg["from_port"].(int))), IpRange: aws.String(cfg["ip_range"].(string)), @@ -510,7 +510,7 @@ func expandIpPermission(cfg map[string]interface{}) *gamelift.IpPermission { } } -func flattenIpPermissions(apiObjects []*gamelift.IpPermission) []interface{} { +func flattenIPPermissions(apiObjects []*gamelift.IpPermission) []interface{} { if len(apiObjects) == 0 { return nil } @@ -521,7 +521,7 @@ func flattenIpPermissions(apiObjects []*gamelift.IpPermission) []interface{} { continue } - if v := flattenIpPermission(apiObject); len(v) > 0 { + if v := flattenIPPermission(apiObject); len(v) > 0 { tfList = append(tfList, v) } } @@ -529,7 +529,7 @@ func flattenIpPermissions(apiObjects []*gamelift.IpPermission) []interface{} { return tfList } -func flattenIpPermission(apiObject *gamelift.IpPermission) map[string]interface{} { +func flattenIPPermission(apiObject *gamelift.IpPermission) map[string]interface{} { if apiObject == nil { return nil } @@ -655,13 +655,13 @@ OUTER: } // Add what's left for revocation - r = append(r, expandIpPermission(oldPerm)) + r = append(r, expandIPPermission(oldPerm)) } for _, np := range newPerms { newPerm := np.(map[string]interface{}) // Add what's left for authorization - a = append(a, expandIpPermission(newPerm)) + a = append(a, expandIPPermission(newPerm)) } return } diff --git a/internal/service/gamelift/fleet_test.go b/internal/service/gamelift/fleet_test.go index e4e4b736c4e..c006f43beb8 100644 --- a/internal/service/gamelift/fleet_test.go +++ b/internal/service/gamelift/fleet_test.go @@ -190,7 +190,7 @@ func TestAccGameLiftFleet_basic(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetBasicConfig(rName, launchPath, params, bucketName, key, roleArn), + Config: testAccFleetConfig_basic(rName, launchPath, params, bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), resource.TestCheckResourceAttrPair(resourceName, "build_id", "aws_gamelift_build.test", "id"), @@ -218,7 +218,7 @@ func TestAccGameLiftFleet_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"runtime_configuration"}, }, { - Config: testAccFleetBasicUpdatedConfig(rNameUpdated, launchPath, params, bucketName, key, roleArn), + Config: testAccFleetConfig_basicUpdated(rNameUpdated, launchPath, params, bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), resource.TestCheckResourceAttrPair(resourceName, "build_id", "aws_gamelift_build.test", "id"), @@ -283,7 +283,7 @@ func TestAccGameLiftFleet_tags(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetBasicTags1Config(rName, launchPath, params, bucketName, key, roleArn, "key1", "value1"), + Config: testAccFleetConfig_basicTags1(rName, launchPath, params, bucketName, key, roleArn, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -297,7 +297,7 @@ func TestAccGameLiftFleet_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"runtime_configuration"}, }, { - Config: testAccFleetBasicTags2Config(rName, launchPath, params, bucketName, key, roleArn, "key1", "value1updated", "key2", "value2"), + Config: testAccFleetConfig_basicTags2(rName, launchPath, params, bucketName, key, roleArn, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -306,7 +306,7 @@ func TestAccGameLiftFleet_tags(t *testing.T) { ), }, { - Config: testAccFleetBasicTags1Config(rName, launchPath, params, bucketName, key, roleArn, "key2", "value2"), + Config: testAccFleetConfig_basicTags1(rName, launchPath, params, bucketName, key, roleArn, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -363,7 +363,7 @@ func TestAccGameLiftFleet_allFields(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetAllFieldsConfig(rName, desc, launchPath, params[0], bucketName, key, roleArn), + Config: testAccFleetConfig_allFields(rName, desc, launchPath, params[0], bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), resource.TestCheckResourceAttrPair(resourceName, "build_id", "aws_gamelift_build.test", "id"), @@ -415,7 +415,7 @@ func TestAccGameLiftFleet_allFields(t *testing.T) { ImportStateVerifyIgnore: []string{"runtime_configuration"}, }, { - Config: testAccFleetAllFieldsUpdatedConfig(rNameUpdated, desc, launchPath, params[1], bucketName, key, roleArn), + Config: testAccFleetConfig_allFieldsUpdated(rNameUpdated, desc, launchPath, params[1], bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), resource.TestCheckResourceAttrPair(resourceName, "build_id", "aws_gamelift_build.test", "id"), @@ -503,7 +503,7 @@ func TestAccGameLiftFleet_cert(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetCertConfig(rName, launchPath, params, bucketName, key, roleArn), + Config: testAccFleetConfig_cert(rName, launchPath, params, bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "certificate_configuration.#", "1"), @@ -542,7 +542,7 @@ func TestAccGameLiftFleet_script(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetScriptConfig(rName), + Config: testAccFleetConfig_script(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), resource.TestCheckResourceAttrPair(resourceName, "script_id", "aws_gamelift_script.test", "id"), @@ -613,7 +613,7 @@ func TestAccGameLiftFleet_disappears(t *testing.T) { CheckDestroy: testAccCheckFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccFleetBasicConfig(rName, launchPath, params, bucketName, key, roleArn), + Config: testAccFleetConfig_basic(rName, launchPath, params, bucketName, key, roleArn), Check: resource.ComposeTestCheckFunc( testAccCheckFleetExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfgamelift.ResourceFleet(), resourceName), @@ -673,7 +673,7 @@ func testAccCheckFleetDestroy(s *terraform.State) error { return nil } -func testAccFleetBasicConfig(rName, launchPath, params, bucketName, key, roleArn string) string { +func testAccFleetConfig_basic(rName, launchPath, params, bucketName, key, roleArn string) string { return testAccFleetBasicTemplate(rName, bucketName, key, roleArn) + fmt.Sprintf(` resource "aws_gamelift_fleet" "test" { build_id = aws_gamelift_build.test.id @@ -691,7 +691,7 @@ resource "aws_gamelift_fleet" "test" { `, rName, launchPath, params) } -func testAccFleetBasicTags1Config(rName, launchPath, params, bucketName, key, roleArn, tagKey1, tagValue1 string) string { +func testAccFleetConfig_basicTags1(rName, launchPath, params, bucketName, key, roleArn, tagKey1, tagValue1 string) string { return testAccFleetBasicTemplate(rName, bucketName, key, roleArn) + fmt.Sprintf(` resource "aws_gamelift_fleet" "test" { build_id = aws_gamelift_build.test.id @@ -713,7 +713,7 @@ resource "aws_gamelift_fleet" "test" { `, rName, launchPath, params, tagKey1, tagValue1) } -func testAccFleetBasicTags2Config(rName, launchPath, params, bucketName, key, roleArn, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccFleetConfig_basicTags2(rName, launchPath, params, bucketName, key, roleArn, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccFleetBasicTemplate(rName, bucketName, key, roleArn) + fmt.Sprintf(` resource "aws_gamelift_fleet" "test" { build_id = aws_gamelift_build.test.id @@ -736,7 +736,7 @@ resource "aws_gamelift_fleet" "test" { `, rName, launchPath, params, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccFleetBasicUpdatedConfig(rName, launchPath, params, bucketName, key, roleArn string) string { +func testAccFleetConfig_basicUpdated(rName, launchPath, params, bucketName, key, roleArn string) string { return testAccFleetBasicTemplate(rName, bucketName, key, roleArn) + fmt.Sprintf(` resource "aws_gamelift_fleet" "test" { build_id = aws_gamelift_build.test.id @@ -762,7 +762,7 @@ resource "aws_gamelift_fleet" "test" { `, rName, launchPath, params) } -func testAccFleetAllFieldsConfig(rName, desc, launchPath, params, bucketName, key, roleArn string) string { +func testAccFleetConfig_allFields(rName, desc, launchPath, params, bucketName, key, roleArn string) string { return testAccFleetBasicTemplate(rName, bucketName, key, roleArn) + testAccFleetIAMRole(rName) + fmt.Sprintf(` resource "aws_gamelift_fleet" "test" { @@ -816,7 +816,7 @@ resource "aws_gamelift_fleet" "test" { `, rName, desc, launchPath, params) } -func testAccFleetAllFieldsUpdatedConfig(rName, desc, launchPath, params, bucketName, key, roleArn string) string { +func testAccFleetConfig_allFieldsUpdated(rName, desc, launchPath, params, bucketName, key, roleArn string) string { return testAccFleetBasicTemplate(rName, bucketName, key, roleArn) + testAccFleetIAMRole(rName) + fmt.Sprintf(` resource "aws_gamelift_fleet" "test" { @@ -944,7 +944,7 @@ resource "aws_iam_policy_attachment" "test" { `, rName) } -func testAccFleetCertConfig(rName, launchPath, params, bucketName, key, roleArn string) string { +func testAccFleetConfig_cert(rName, launchPath, params, bucketName, key, roleArn string) string { return testAccFleetBasicTemplate(rName, bucketName, key, roleArn) + fmt.Sprintf(` resource "aws_gamelift_fleet" "test" { build_id = aws_gamelift_build.test.id @@ -966,7 +966,7 @@ resource "aws_gamelift_fleet" "test" { `, rName, launchPath, params) } -func testAccFleetScriptConfig(rName string) string { +func testAccFleetConfig_script(rName string) string { return fmt.Sprintf(` resource "aws_gamelift_script" "test" { name = %[1]q diff --git a/internal/service/gamelift/game_server_group.go b/internal/service/gamelift/game_server_group.go index 37482b0bb49..0d92b4bfcc9 100644 --- a/internal/service/gamelift/game_server_group.go +++ b/internal/service/gamelift/game_server_group.go @@ -311,7 +311,7 @@ func resourceGameServerGroupRead(d *schema.ResourceData, meta interface{}) error return fmt.Errorf("error setting instance_definition: %s", err) } - if err := d.Set("launch_template", flattenAutoscalingLaunchTemplateSpecification(autoScalingGroup.MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification)); err != nil { + if err := d.Set("launch_template", flattenAutoScalingLaunchTemplateSpecification(autoScalingGroup.MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification)); err != nil { return fmt.Errorf("error setting launch_template: %s", err) } @@ -536,7 +536,7 @@ func flattenInstanceDefinition(apiObject *gamelift.InstanceDefinition) map[strin return tfMap } -func flattenAutoscalingLaunchTemplateSpecification(apiObject *autoscaling.LaunchTemplateSpecification) []map[string]interface{} { +func flattenAutoScalingLaunchTemplateSpecification(apiObject *autoscaling.LaunchTemplateSpecification) []map[string]interface{} { if apiObject == nil { return nil } diff --git a/internal/service/gamelift/game_server_group_test.go b/internal/service/gamelift/game_server_group_test.go index b4fe38d46ca..c8c8be2c20a 100644 --- a/internal/service/gamelift/game_server_group_test.go +++ b/internal/service/gamelift/game_server_group_test.go @@ -30,7 +30,7 @@ func TestAccGameLiftGameServerGroup_basic(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfig(rName), + Config: testAccGameServerGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "gamelift", regexp.MustCompile(`gameservergroup/.+`)), @@ -67,7 +67,7 @@ func TestAccGameLiftGameServerGroup_AutoScalingPolicy(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigAutoScalingPolicy(rName), + Config: testAccGameServerGroupConfig_autoScalingPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "auto_scaling_policy.0.estimated_instance_warmup", "60"), @@ -99,7 +99,7 @@ func TestAccGameLiftGameServerGroup_AutoScalingPolicy_EstimatedInstanceWarmup(t CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigAutoScalingPolicyEstimatedInstanceWarmup(rName), + Config: testAccGameServerGroupConfig_autoScalingPolicyEstimatedInstanceWarmup(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "auto_scaling_policy.0.estimated_instance_warmup", "66"), @@ -131,7 +131,7 @@ func TestAccGameLiftGameServerGroup_BalancingStrategy(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigBalancingStrategy(rName, gamelift.BalancingStrategySpotOnly), + Config: testAccGameServerGroupConfig_balancingStrategy(rName, gamelift.BalancingStrategySpotOnly), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "balancing_strategy", gamelift.BalancingStrategySpotOnly), @@ -166,7 +166,7 @@ func TestAccGameLiftGameServerGroup_GameServerGroupName(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigGameServerGroupName(rName, rName), + Config: testAccGameServerGroupConfig_name(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "game_server_group_name", rName), @@ -179,7 +179,7 @@ func TestAccGameLiftGameServerGroup_GameServerGroupName(t *testing.T) { ImportStateVerifyIgnore: []string{"vpc_subnets"}, }, { - Config: testAccGameServerGroupConfigGameServerGroupName(rName, rName+"-new"), + Config: testAccGameServerGroupConfig_name(rName, rName+"-new"), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "game_server_group_name", rName+"-new"), @@ -204,7 +204,7 @@ func TestAccGameLiftGameServerGroup_InstanceDefinition(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigInstanceDefinition(rName, 2), + Config: testAccGameServerGroupConfig_instanceDefinition(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "instance_definition.#", "2"), @@ -217,7 +217,7 @@ func TestAccGameLiftGameServerGroup_InstanceDefinition(t *testing.T) { ImportStateVerifyIgnore: []string{"vpc_subnets"}, }, { - Config: testAccGameServerGroupConfigInstanceDefinition(rName, 3), + Config: testAccGameServerGroupConfig_instanceDefinition(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "instance_definition.#", "3"), @@ -242,7 +242,7 @@ func TestAccGameLiftGameServerGroup_InstanceDefinition_WeightedCapacity(t *testi CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigInstanceDefinitionWeightedCapacity(rName, "1"), + Config: testAccGameServerGroupConfig_instanceDefinitionWeightedCapacity(rName, "1"), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "instance_definition.#", "2"), @@ -257,7 +257,7 @@ func TestAccGameLiftGameServerGroup_InstanceDefinition_WeightedCapacity(t *testi ImportStateVerifyIgnore: []string{"vpc_subnets"}, }, { - Config: testAccGameServerGroupConfigInstanceDefinitionWeightedCapacity(rName, "2"), + Config: testAccGameServerGroupConfig_instanceDefinitionWeightedCapacity(rName, "2"), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "instance_definition.#", "2"), @@ -284,7 +284,7 @@ func TestAccGameLiftGameServerGroup_LaunchTemplate_Id(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigLaunchTemplateId(rName), + Config: testAccGameServerGroupConfig_launchTemplateID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", "aws_launch_template.test", "id"), @@ -317,7 +317,7 @@ func TestAccGameLiftGameServerGroup_LaunchTemplate_Name(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigLaunchTemplateName(rName), + Config: testAccGameServerGroupConfig_launchTemplateName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", "aws_launch_template.test", "id"), @@ -350,7 +350,7 @@ func TestAccGameLiftGameServerGroup_LaunchTemplate_Version(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigLaunchTemplateVersion(rName), + Config: testAccGameServerGroupConfig_launchTemplateVersion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "launch_template.0.id", "aws_launch_template.test", "id"), @@ -383,7 +383,7 @@ func TestAccGameLiftGameServerGroup_GameServerProtectionPolicy(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigGameServerProtectionPolicy(rName, gamelift.GameServerProtectionPolicyFullProtection), + Config: testAccGameServerGroupConfig_protectionPolicy(rName, gamelift.GameServerProtectionPolicyFullProtection), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "game_server_protection_policy", gamelift.GameServerProtectionPolicyFullProtection), @@ -418,7 +418,7 @@ func TestAccGameLiftGameServerGroup_MaxSize(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigMaxSize(rName, "1"), + Config: testAccGameServerGroupConfig_maxSize(rName, "1"), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "max_size", "1"), @@ -431,7 +431,7 @@ func TestAccGameLiftGameServerGroup_MaxSize(t *testing.T) { ImportStateVerifyIgnore: []string{"vpc_subnets"}, }, { - Config: testAccGameServerGroupConfigMaxSize(rName, "2"), + Config: testAccGameServerGroupConfig_maxSize(rName, "2"), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "max_size", "2"), @@ -460,7 +460,7 @@ func TestAccGameLiftGameServerGroup_MinSize(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigMinSize(rName, "1"), + Config: testAccGameServerGroupConfig_minSize(rName, "1"), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "min_size", "1"), @@ -473,7 +473,7 @@ func TestAccGameLiftGameServerGroup_MinSize(t *testing.T) { ImportStateVerifyIgnore: []string{"vpc_subnets"}, }, { - Config: testAccGameServerGroupConfigMinSize(rName, "2"), + Config: testAccGameServerGroupConfig_minSize(rName, "2"), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "min_size", "2"), @@ -483,7 +483,7 @@ func TestAccGameLiftGameServerGroup_MinSize(t *testing.T) { }) } -func TestAccGameLiftGameServerGroup_RoleArn(t *testing.T) { +func TestAccGameLiftGameServerGroup_roleARN(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_gamelift_game_server_group.test" @@ -498,7 +498,7 @@ func TestAccGameLiftGameServerGroup_RoleArn(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigRoleArn(rName, "test1"), + Config: testAccGameServerGroupConfig_roleARN(rName, "test1"), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), acctest.CheckResourceAttrGlobalARN(resourceName, "role_arn", "iam", fmt.Sprintf(`role/%s-test1`, rName)), @@ -512,7 +512,7 @@ func TestAccGameLiftGameServerGroup_RoleArn(t *testing.T) { ImportStateVerifyIgnore: []string{"vpc_subnets"}, }, { - Config: testAccGameServerGroupConfigRoleArn(rName, "test2"), + Config: testAccGameServerGroupConfig_roleARN(rName, "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), acctest.CheckResourceAttrGlobalARN(resourceName, "role_arn", "iam", fmt.Sprintf(`role/%s-test2`, rName)), @@ -523,7 +523,7 @@ func TestAccGameLiftGameServerGroup_RoleArn(t *testing.T) { }) } -func TestAccGameLiftGameServerGroup_VpcSubnets(t *testing.T) { +func TestAccGameLiftGameServerGroup_vpcSubnets(t *testing.T) { if testing.Short() { t.Skip("skipping long-running test in short mode") } @@ -542,7 +542,7 @@ func TestAccGameLiftGameServerGroup_VpcSubnets(t *testing.T) { CheckDestroy: testAccCheckGameServerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGameServerGroupConfigVpcSubnets(rName, 1), + Config: testAccGameServerGroupConfig_vpcSubnets(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), ), @@ -554,7 +554,7 @@ func TestAccGameLiftGameServerGroup_VpcSubnets(t *testing.T) { ImportStateVerifyIgnore: []string{"vpc_subnets"}, }, { - Config: testAccGameServerGroupConfigVpcSubnets(rName, 2), + Config: testAccGameServerGroupConfig_vpcSubnets(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckGameServerGroupExists(resourceName), ), @@ -624,7 +624,7 @@ func testAccCheckGameServerGroupExists(resourceName string) resource.TestCheckFu } } -func testAccGameServerGroupIamConfig(rName string, name string) string { +func testAccGameServerGroupConfig_iam(rName string, name string) string { return fmt.Sprintf(` data "aws_partition" %[2]q {} @@ -691,10 +691,10 @@ data "aws_ec2_instance_type_offerings" "available" { ` } -func testAccGameServerGroupConfig(rName string) string { +func testAccGameServerGroupConfig_basic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -721,10 +721,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName)) } -func testAccGameServerGroupConfigAutoScalingPolicy(rName string) string { +func testAccGameServerGroupConfig_autoScalingPolicy(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -756,10 +756,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName)) } -func testAccGameServerGroupConfigAutoScalingPolicyEstimatedInstanceWarmup(rName string) string { +func testAccGameServerGroupConfig_autoScalingPolicyEstimatedInstanceWarmup(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -792,10 +792,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName)) } -func testAccGameServerGroupConfigBalancingStrategy(rName string, balancingStrategy string) string { +func testAccGameServerGroupConfig_balancingStrategy(rName string, balancingStrategy string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -823,10 +823,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName, balancingStrategy)) } -func testAccGameServerGroupConfigGameServerGroupName(rName string, gameServerGroupName string) string { +func testAccGameServerGroupConfig_name(rName string, gameServerGroupName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -853,10 +853,10 @@ resource "aws_gamelift_game_server_group" "test" { `, gameServerGroupName)) } -func testAccGameServerGroupConfigInstanceDefinition(rName string, count int) string { +func testAccGameServerGroupConfig_instanceDefinition(rName string, count int) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -883,10 +883,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName, count)) } -func testAccGameServerGroupConfigInstanceDefinitionWeightedCapacity(rName string, weightedCapacity string) string { +func testAccGameServerGroupConfig_instanceDefinitionWeightedCapacity(rName string, weightedCapacity string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -914,10 +914,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName, weightedCapacity)) } -func testAccGameServerGroupConfigLaunchTemplateId(rName string) string { +func testAccGameServerGroupConfig_launchTemplateID(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -944,10 +944,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName)) } -func testAccGameServerGroupConfigLaunchTemplateName(rName string) string { +func testAccGameServerGroupConfig_launchTemplateName(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -974,10 +974,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName)) } -func testAccGameServerGroupConfigLaunchTemplateVersion(rName string) string { +func testAccGameServerGroupConfig_launchTemplateVersion(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -1005,10 +1005,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName)) } -func testAccGameServerGroupConfigMaxSize(rName string, maxSize string) string { +func testAccGameServerGroupConfig_maxSize(rName string, maxSize string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -1035,10 +1035,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName, maxSize)) } -func testAccGameServerGroupConfigMinSize(rName string, minSize string) string { +func testAccGameServerGroupConfig_minSize(rName string, minSize string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -1065,10 +1065,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName, minSize)) } -func testAccGameServerGroupConfigGameServerProtectionPolicy(rName string, gameServerProtectionPolicy string) string { +func testAccGameServerGroupConfig_protectionPolicy(rName string, gameServerProtectionPolicy string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -1096,10 +1096,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName, gameServerProtectionPolicy)) } -func testAccGameServerGroupConfigRoleArn(rName string, roleArn string) string { +func testAccGameServerGroupConfig_roleARN(rName string, roleArn string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, roleArn), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, roleArn), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` @@ -1126,10 +1126,10 @@ resource "aws_gamelift_game_server_group" "test" { `, rName, roleArn)) } -func testAccGameServerGroupConfigVpcSubnets(rName string, count int) string { +func testAccGameServerGroupConfig_vpcSubnets(rName string, count int) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), - testAccGameServerGroupIamConfig(rName, "test"), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), + testAccGameServerGroupConfig_iam(rName, "test"), testAccGameServerGroupInstanceTypeOfferingsConfig(), testAccGameServerGroupLaunchTemplateConfig(rName), fmt.Sprintf(` diff --git a/internal/service/gamelift/game_session_queue_test.go b/internal/service/gamelift/game_session_queue_test.go index d40dc664c1a..91ed61fcdd3 100644 --- a/internal/service/gamelift/game_session_queue_test.go +++ b/internal/service/gamelift/game_session_queue_test.go @@ -59,7 +59,7 @@ func TestAccGameLiftGameSessionQueue_basic(t *testing.T) { CheckDestroy: testAccCheckGameSessionQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccGameSessionQueueBasicConfig(queueName, + Config: testAccGameSessionQueueConfig_basic(queueName, playerLatencyPolicies, timeoutInSeconds), Check: resource.ComposeTestCheckFunc( testAccCheckGameSessionQueueExists(resourceName, &conf), @@ -79,7 +79,7 @@ func TestAccGameLiftGameSessionQueue_basic(t *testing.T) { ), }, { - Config: testAccGameSessionQueueBasicConfig(uQueueName, uPlayerLatencyPolicies, uTimeoutInSeconds), + Config: testAccGameSessionQueueConfig_basic(uQueueName, uPlayerLatencyPolicies, uTimeoutInSeconds), Check: resource.ComposeTestCheckFunc( testAccCheckGameSessionQueueExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "gamelift", regexp.MustCompile(`gamesessionqueue/.+`)), @@ -123,7 +123,7 @@ func TestAccGameLiftGameSessionQueue_tags(t *testing.T) { CheckDestroy: testAccCheckGameSessionQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccGameSessionQueueBasicTags1Config(queueName, "key1", "value1"), + Config: testAccGameSessionQueueConfig_basicTags1(queueName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckGameSessionQueueExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -136,7 +136,7 @@ func TestAccGameLiftGameSessionQueue_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccGameSessionQueueBasicTags2Config(queueName, "key1", "value1updated", "key2", "value2"), + Config: testAccGameSessionQueueConfig_basicTags2(queueName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckGameSessionQueueExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -145,7 +145,7 @@ func TestAccGameLiftGameSessionQueue_tags(t *testing.T) { ), }, { - Config: testAccGameSessionQueueBasicTags1Config(queueName, "key2", "value2"), + Config: testAccGameSessionQueueConfig_basicTags1(queueName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckGameSessionQueueExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -184,7 +184,7 @@ func TestAccGameLiftGameSessionQueue_disappears(t *testing.T) { CheckDestroy: testAccCheckGameSessionQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccGameSessionQueueBasicConfig(queueName, + Config: testAccGameSessionQueueConfig_basic(queueName, playerLatencyPolicies, timeoutInSeconds), Check: resource.ComposeTestCheckFunc( testAccCheckGameSessionQueueExists(resourceName, &conf), @@ -292,7 +292,7 @@ func testAccCheckGameSessionQueueDestroy(s *terraform.State) error { return nil } -func testAccGameSessionQueueBasicConfig(queueName string, +func testAccGameSessionQueueConfig_basic(queueName string, playerLatencyPolicies []gamelift.PlayerLatencyPolicy, timeoutInSeconds int64) string { return fmt.Sprintf(` resource "aws_gamelift_game_session_queue" "test" { @@ -318,7 +318,7 @@ resource "aws_gamelift_game_session_queue" "test" { timeoutInSeconds) } -func testAccGameSessionQueueBasicTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccGameSessionQueueConfig_basicTags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_gamelift_game_session_queue" "test" { name = %[1]q @@ -342,7 +342,7 @@ resource "aws_gamelift_game_session_queue" "test" { `, rName, tagKey1, tagValue1) } -func testAccGameSessionQueueBasicTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccGameSessionQueueConfig_basicTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_gamelift_game_session_queue" "test" { name = %[1]q diff --git a/internal/service/gamelift/script_test.go b/internal/service/gamelift/script_test.go index 2bf859d4b9e..1d40422407f 100644 --- a/internal/service/gamelift/script_test.go +++ b/internal/service/gamelift/script_test.go @@ -35,7 +35,7 @@ func TestAccGameLiftScript_basic(t *testing.T) { CheckDestroy: testAccCheckScriptDestroy, Steps: []resource.TestStep{ { - Config: testAccScriptBasicConfig(rName), + Config: testAccScriptConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScriptExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -53,7 +53,7 @@ func TestAccGameLiftScript_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"zip_file"}, }, { - Config: testAccScriptBasicConfig(rNameUpdated), + Config: testAccScriptConfig_basic(rNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckScriptExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), @@ -83,7 +83,7 @@ func TestAccGameLiftScript_tags(t *testing.T) { CheckDestroy: testAccCheckScriptDestroy, Steps: []resource.TestStep{ { - Config: testAccScriptBasicTags1Config(rName, "key1", "value1"), + Config: testAccScriptConfig_basicTags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckScriptExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -97,7 +97,7 @@ func TestAccGameLiftScript_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"zip_file"}, }, { - Config: testAccScriptBasicTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccScriptConfig_basicTags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckScriptExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -106,7 +106,7 @@ func TestAccGameLiftScript_tags(t *testing.T) { ), }, { - Config: testAccScriptBasicTags1Config(rName, "key2", "value2"), + Config: testAccScriptConfig_basicTags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckScriptExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -134,7 +134,7 @@ func TestAccGameLiftScript_disappears(t *testing.T) { CheckDestroy: testAccCheckScriptDestroy, Steps: []resource.TestStep{ { - Config: testAccScriptBasicConfig(rName), + Config: testAccScriptConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckScriptExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfgamelift.ResourceScript(), resourceName), @@ -196,7 +196,7 @@ func testAccCheckScriptDestroy(s *terraform.State) error { return nil } -func testAccScriptBasicConfig(rName string) string { +func testAccScriptConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_gamelift_script" "test" { name = %[1]q @@ -205,7 +205,7 @@ resource "aws_gamelift_script" "test" { `, rName) } -func testAccScriptBasicTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccScriptConfig_basicTags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_gamelift_script" "test" { name = %[1]q @@ -218,7 +218,7 @@ resource "aws_gamelift_script" "test" { `, rName, tagKey1, tagValue1) } -func testAccScriptBasicTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccScriptConfig_basicTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_gamelift_script" "test" { name = %[1]q diff --git a/internal/service/glacier/vault_lock_test.go b/internal/service/glacier/vault_lock_test.go index 5fc8ff7daa6..02f7a08c789 100644 --- a/internal/service/glacier/vault_lock_test.go +++ b/internal/service/glacier/vault_lock_test.go @@ -27,7 +27,7 @@ func TestAccGlacierVaultLock_basic(t *testing.T) { CheckDestroy: testAccCheckVaultLockDestroy, Steps: []resource.TestStep{ { - Config: testAccVaultLockConfigCompleteLock(rName, false), + Config: testAccVaultLockConfig_complete(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckVaultLockExists(resourceName, &vaultLock1), resource.TestCheckResourceAttr(resourceName, "complete_lock", "false"), @@ -59,7 +59,7 @@ func TestAccGlacierVaultLock_completeLock(t *testing.T) { CheckDestroy: testAccCheckVaultLockDestroy, Steps: []resource.TestStep{ { - Config: testAccVaultLockConfigCompleteLock(rName, true), + Config: testAccVaultLockConfig_complete(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckVaultLockExists(resourceName, &vaultLock1), resource.TestCheckResourceAttr(resourceName, "complete_lock", "true"), @@ -91,7 +91,7 @@ func TestAccGlacierVaultLock_ignoreEquivalentPolicy(t *testing.T) { CheckDestroy: testAccCheckVaultLockDestroy, Steps: []resource.TestStep{ { - Config: testAccVaultLockPolicyOrderConfig(rName, false), + Config: testAccVaultLockConfig_policyOrder(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckVaultLockExists(resourceName, &vaultLock1), resource.TestCheckResourceAttr(resourceName, "complete_lock", "false"), @@ -101,7 +101,7 @@ func TestAccGlacierVaultLock_ignoreEquivalentPolicy(t *testing.T) { ), }, { - Config: testAccVaultLockPolicyNewOrderConfig(rName, false), + Config: testAccVaultLockConfig_policyNewOrder(rName, false), PlanOnly: true, }, }, @@ -169,7 +169,7 @@ func testAccCheckVaultLockDestroy(s *terraform.State) error { return nil } -func testAccVaultLockConfigCompleteLock(rName string, completeLock bool) string { +func testAccVaultLockConfig_complete(rName string, completeLock bool) string { return fmt.Sprintf(` resource "aws_glacier_vault" "test" { name = %q @@ -207,7 +207,7 @@ resource "aws_glacier_vault_lock" "test" { `, rName, completeLock, completeLock) } -func testAccVaultLockPolicyOrderConfig(rName string, completeLock bool) string { +func testAccVaultLockConfig_policyOrder(rName string, completeLock bool) string { return fmt.Sprintf(` resource "aws_glacier_vault" "test" { name = %[1]q @@ -241,7 +241,7 @@ resource "aws_glacier_vault_lock" "test" { `, rName, completeLock) } -func testAccVaultLockPolicyNewOrderConfig(rName string, completeLock bool) string { +func testAccVaultLockConfig_policyNewOrder(rName string, completeLock bool) string { return fmt.Sprintf(` resource "aws_glacier_vault" "test" { name = %[1]q diff --git a/internal/service/glacier/vault_test.go b/internal/service/glacier/vault_test.go index 639075391c6..004dc567baa 100644 --- a/internal/service/glacier/vault_test.go +++ b/internal/service/glacier/vault_test.go @@ -28,7 +28,7 @@ func TestAccGlacierVault_basic(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccVaultBasicConfig(rName), + Config: testAccVaultConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -60,7 +60,7 @@ func TestAccGlacierVault_notification(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccVaultNotificationConfig(rName), + Config: testAccVaultConfig_notification(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "notification.#", "1"), @@ -74,7 +74,7 @@ func TestAccGlacierVault_notification(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVaultBasicConfig(rName), + Config: testAccVaultConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "notification.#", "0"), @@ -82,7 +82,7 @@ func TestAccGlacierVault_notification(t *testing.T) { ), }, { - Config: testAccVaultNotificationConfig(rName), + Config: testAccVaultConfig_notification(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "notification.#", "1"), @@ -106,7 +106,7 @@ func TestAccGlacierVault_policy(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccVaultPolicyConfig(rName), + Config: testAccVaultConfig_policy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -120,7 +120,7 @@ func TestAccGlacierVault_policy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVaultPolicyConfigUpdated(rName), + Config: testAccVaultConfig_policyUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -129,7 +129,7 @@ func TestAccGlacierVault_policy(t *testing.T) { ), }, { - Config: testAccVaultBasicConfig(rName), + Config: testAccVaultConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "access_policy", ""), @@ -151,7 +151,7 @@ func TestAccGlacierVault_tags(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccVaultConfigTags1(rName, "key1", "value1"), + Config: testAccVaultConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -164,7 +164,7 @@ func TestAccGlacierVault_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVaultConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVaultConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -173,7 +173,7 @@ func TestAccGlacierVault_tags(t *testing.T) { ), }, { - Config: testAccVaultConfigTags1(rName, "key2", "value2"), + Config: testAccVaultConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -196,7 +196,7 @@ func TestAccGlacierVault_disappears(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccVaultBasicConfig(rName), + Config: testAccVaultConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), acctest.CheckResourceDisappears(acctest.Provider, tfglacier.ResourceVault(), resourceName), @@ -219,7 +219,7 @@ func TestAccGlacierVault_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckVaultDestroy, Steps: []resource.TestStep{ { - Config: testAccVaultPolicyOrderConfig(rName), + Config: testAccVaultConfig_policyOrder(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVaultExists(resourceName, &vault), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -230,7 +230,7 @@ func TestAccGlacierVault_ignoreEquivalent(t *testing.T) { ), }, { - Config: testAccVaultPolicyNewOrderConfig(rName), + Config: testAccVaultConfig_policyNewOrder(rName), PlanOnly: true, }, }, @@ -325,7 +325,7 @@ func testAccCheckVaultDestroy(s *terraform.State) error { return nil } -func testAccVaultBasicConfig(rName string) string { +func testAccVaultConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_glacier_vault" "test" { name = %[1]q @@ -333,7 +333,7 @@ resource "aws_glacier_vault" "test" { `, rName) } -func testAccVaultNotificationConfig(rName string) string { +func testAccVaultConfig_notification(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -350,7 +350,7 @@ resource "aws_glacier_vault" "test" { `, rName) } -func testAccVaultPolicyConfig(rName string) string { +func testAccVaultConfig_policy(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -385,7 +385,7 @@ EOF `, rName) } -func testAccVaultPolicyConfigUpdated(rName string) string { +func testAccVaultConfig_policyUpdated(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -421,7 +421,7 @@ EOF `, rName) } -func testAccVaultConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccVaultConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_glacier_vault" "test" { name = %[1]q @@ -433,7 +433,7 @@ resource "aws_glacier_vault" "test" { `, rName, tagKey1, tagValue1) } -func testAccVaultConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVaultConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_glacier_vault" "test" { name = %[1]q @@ -446,7 +446,7 @@ resource "aws_glacier_vault" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccVaultPolicyOrderConfig(rName string) string { +func testAccVaultConfig_policyOrder(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -479,7 +479,7 @@ resource "aws_glacier_vault" "test" { `, rName) } -func testAccVaultPolicyNewOrderConfig(rName string) string { +func testAccVaultConfig_policyNewOrder(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/globalaccelerator/accelerator_data_source_test.go b/internal/service/globalaccelerator/accelerator_data_source_test.go index e937a66fb84..c80ae1d24b4 100644 --- a/internal/service/globalaccelerator/accelerator_data_source_test.go +++ b/internal/service/globalaccelerator/accelerator_data_source_test.go @@ -22,7 +22,7 @@ func TestAccGlobalAcceleratorAcceleratorDataSource_Data_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAcceleratorWithDataSourceConfig(rName), + Config: testAccAcceleratorDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "attributes.#", resourceName, "attributes.#"), resource.TestCheckResourceAttrPair(dataSourceName, "attributes.0.flow_logs_enabled", resourceName, "attributes.0.flow_logs_enabled"), @@ -58,7 +58,7 @@ func TestAccGlobalAcceleratorAcceleratorDataSource_Data_basic(t *testing.T) { }) } -func testAccAcceleratorWithDataSourceConfig(rName string) string { +func testAccAcceleratorDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_globalaccelerator_accelerator" "test" { name = %[1]q diff --git a/internal/service/globalaccelerator/endpoint_group_test.go b/internal/service/globalaccelerator/endpoint_group_test.go index 9d2dc251596..652fce835e6 100644 --- a/internal/service/globalaccelerator/endpoint_group_test.go +++ b/internal/service/globalaccelerator/endpoint_group_test.go @@ -94,7 +94,7 @@ func TestAccGlobalAcceleratorEndpointGroup_ALBEndpoint_clientIP(t *testing.T) { CheckDestroy: testAccCheckEndpointGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointGroupConfig_albEndpointClientIP(rName, false), + Config: testAccEndpointGroupConfig_albClientIP(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointGroupExists(resourceName, &v), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "globalaccelerator", regexp.MustCompile(`accelerator/[^/]+/listener/[^/]+/endpoint-group/[^/]+`)), @@ -121,7 +121,7 @@ func TestAccGlobalAcceleratorEndpointGroup_ALBEndpoint_clientIP(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEndpointGroupConfig_albEndpointClientIP(rName, true), + Config: testAccEndpointGroupConfig_albClientIP(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointGroupExists(resourceName, &v), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "globalaccelerator", regexp.MustCompile(`accelerator/[^/]+/listener/[^/]+/endpoint-group/[^/]+`)), @@ -168,7 +168,7 @@ func TestAccGlobalAcceleratorEndpointGroup_instanceEndpoint(t *testing.T) { CheckDestroy: testAccCheckEndpointGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointGroupConfig_instanceEndpoint(rName), + Config: testAccEndpointGroupConfig_instance(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointGroupExists(resourceName, &v), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "globalaccelerator", regexp.MustCompile(`accelerator/[^/]+/listener/[^/]+/endpoint-group/[^/]+`)), @@ -528,7 +528,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccEndpointGroupConfig_albEndpointClientIP(rName string, clientIP bool) string { +func testAccEndpointGroupConfig_albClientIP(rName string, clientIP bool) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), testAccEndpointGroupConfig_baseVPC(rName), @@ -629,11 +629,11 @@ resource "aws_globalaccelerator_endpoint_group" "test" { `, rName, clientIP)) } -func testAccEndpointGroupConfig_instanceEndpoint(rName string) string { +func testAccEndpointGroupConfig_instance(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), acctest.AvailableEC2InstanceTypeForAvailabilityZone("data.aws_availability_zones.available.names[0]", "t3.micro", "t2.micro"), - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), testAccEndpointGroupConfig_baseVPC(rName), fmt.Sprintf(` resource "aws_subnet" "test" { diff --git a/internal/service/glue/catalog_database_test.go b/internal/service/glue/catalog_database_test.go index 74b1ebccbce..bb7a40f4b26 100644 --- a/internal/service/glue/catalog_database_test.go +++ b/internal/service/glue/catalog_database_test.go @@ -124,7 +124,7 @@ func TestAccGlueCatalogDatabase_targetDatabase(t *testing.T) { CheckDestroy: testAccCheckDatabaseDestroy, Steps: []resource.TestStep{ { - Config: testAccCatalogDatabaseConfig_targetDatabase(rName), + Config: testAccCatalogDatabaseConfig_target(rName), Destroy: false, Check: resource.ComposeTestCheckFunc( testAccCheckCatalogDatabaseExists(resourceName), @@ -139,7 +139,7 @@ func TestAccGlueCatalogDatabase_targetDatabase(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCatalogDatabaseConfig_targetDatabaseLocation(rName), + Config: testAccCatalogDatabaseConfig_targetLocation(rName), Destroy: false, Check: resource.ComposeTestCheckFunc( testAccCheckCatalogDatabaseExists(resourceName), @@ -228,7 +228,7 @@ resource "aws_glue_catalog_database" "test" { `, rName, desc) } -func testAccCatalogDatabaseConfig_targetDatabase(rName string) string { +func testAccCatalogDatabaseConfig_target(rName string) string { return fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -245,7 +245,7 @@ resource "aws_glue_catalog_database" "test2" { `, rName) } -func testAccCatalogDatabaseConfig_targetDatabaseLocation(rName string) string { +func testAccCatalogDatabaseConfig_targetLocation(rName string) string { return fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q diff --git a/internal/service/glue/catalog_table_test.go b/internal/service/glue/catalog_table_test.go index 55fc24969ad..0d95735ebd6 100644 --- a/internal/service/glue/catalog_table_test.go +++ b/internal/service/glue/catalog_table_test.go @@ -287,7 +287,7 @@ func TestAccGlueCatalogTable_Update_replaceValues(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCatalogTableConfig_Full_replacedValues(rName), + Config: testAccCatalogTableConfig_fullReplacedValues(rName), Destroy: false, Check: resource.ComposeTestCheckFunc( testAccCheckCatalogTableExists(resourceName), @@ -619,7 +619,7 @@ func TestAccGlueCatalogTable_targetTable(t *testing.T) { CheckDestroy: testAccCheckTableDestroy, Steps: []resource.TestStep{ { - Config: testAccCatalogTableConfig_targetTable(rName), + Config: testAccCatalogTableConfig_target(rName), Destroy: false, Check: resource.ComposeTestCheckFunc( testAccCheckCatalogTableExists(resourceName), @@ -765,7 +765,7 @@ resource "aws_glue_catalog_table" "test" { `, rName, desc) } -func testAccCatalogTableConfig_Full_replacedValues(rName string) string { +func testAccCatalogTableConfig_fullReplacedValues(rName string) string { return fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -1361,7 +1361,7 @@ resource "aws_glue_catalog_table" "test" { `, rName) } -func testAccCatalogTableConfig_targetTable(rName string) string { +func testAccCatalogTableConfig_target(rName string) string { return fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q diff --git a/internal/service/glue/classifier_test.go b/internal/service/glue/classifier_test.go index b35dbfd26e3..fd4e80539d7 100644 --- a/internal/service/glue/classifier_test.go +++ b/internal/service/glue/classifier_test.go @@ -28,7 +28,7 @@ func TestAccGlueClassifier_csvClassifier(t *testing.T) { CheckDestroy: testAccCheckClassifierDestroy, Steps: []resource.TestStep{ { - Config: testAccClassifierConfig_CSVClassifier(rName, false, "PRESENT", "|", false), + Config: testAccClassifierConfig_csv(rName, false, "PRESENT", "|", false), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "1"), @@ -45,7 +45,7 @@ func TestAccGlueClassifier_csvClassifier(t *testing.T) { ), }, { - Config: testAccClassifierConfig_CSVClassifier(rName, false, "PRESENT", ",", false), + Config: testAccClassifierConfig_csv(rName, false, "PRESENT", ",", false), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "1"), @@ -83,7 +83,7 @@ func TestAccGlueClassifier_CSVClassifier_quoteSymbol(t *testing.T) { CheckDestroy: testAccCheckClassifierDestroy, Steps: []resource.TestStep{ { - Config: testAccClassifierCSVClassifierQuoteSymbolConfig(rName, "\""), + Config: testAccClassifierConfig_csvQuoteSymbol(rName, "\""), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "1"), @@ -91,7 +91,7 @@ func TestAccGlueClassifier_CSVClassifier_quoteSymbol(t *testing.T) { ), }, { - Config: testAccClassifierCSVClassifierQuoteSymbolConfig(rName, "'"), + Config: testAccClassifierConfig_csvQuoteSymbol(rName, "'"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "1"), @@ -120,7 +120,7 @@ func TestAccGlueClassifier_grokClassifier(t *testing.T) { CheckDestroy: testAccCheckClassifierDestroy, Steps: []resource.TestStep{ { - Config: testAccClassifierConfig_GrokClassifier(rName, "classification1", "pattern1"), + Config: testAccClassifierConfig_grok(rName, "classification1", "pattern1"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -134,7 +134,7 @@ func TestAccGlueClassifier_grokClassifier(t *testing.T) { ), }, { - Config: testAccClassifierConfig_GrokClassifier(rName, "classification2", "pattern2"), + Config: testAccClassifierConfig_grok(rName, "classification2", "pattern2"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -169,7 +169,7 @@ func TestAccGlueClassifier_GrokClassifier_customPatterns(t *testing.T) { CheckDestroy: testAccCheckClassifierDestroy, Steps: []resource.TestStep{ { - Config: testAccClassifierConfig_GrokClassifier_CustomPatterns(rName, "custompattern1"), + Config: testAccClassifierConfig_grokCustomPatterns(rName, "custompattern1"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -183,7 +183,7 @@ func TestAccGlueClassifier_GrokClassifier_customPatterns(t *testing.T) { ), }, { - Config: testAccClassifierConfig_GrokClassifier_CustomPatterns(rName, "custompattern2"), + Config: testAccClassifierConfig_grokCustomPatterns(rName, "custompattern2"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -218,7 +218,7 @@ func TestAccGlueClassifier_jsonClassifier(t *testing.T) { CheckDestroy: testAccCheckClassifierDestroy, Steps: []resource.TestStep{ { - Config: testAccClassifierConfig_JSONClassifier(rName, "jsonpath1"), + Config: testAccClassifierConfig_json(rName, "jsonpath1"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -230,7 +230,7 @@ func TestAccGlueClassifier_jsonClassifier(t *testing.T) { ), }, { - Config: testAccClassifierConfig_JSONClassifier(rName, "jsonpath2"), + Config: testAccClassifierConfig_json(rName, "jsonpath2"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -263,7 +263,7 @@ func TestAccGlueClassifier_typeChange(t *testing.T) { CheckDestroy: testAccCheckClassifierDestroy, Steps: []resource.TestStep{ { - Config: testAccClassifierConfig_GrokClassifier(rName, "classification1", "pattern1"), + Config: testAccClassifierConfig_grok(rName, "classification1", "pattern1"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -277,7 +277,7 @@ func TestAccGlueClassifier_typeChange(t *testing.T) { ), }, { - Config: testAccClassifierConfig_JSONClassifier(rName, "jsonpath1"), + Config: testAccClassifierConfig_json(rName, "jsonpath1"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -289,7 +289,7 @@ func TestAccGlueClassifier_typeChange(t *testing.T) { ), }, { - Config: testAccClassifierConfig_XmlClassifier(rName, "classification1", "rowtag1"), + Config: testAccClassifierConfig_xml(rName, "classification1", "rowtag1"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -302,7 +302,7 @@ func TestAccGlueClassifier_typeChange(t *testing.T) { ), }, { - Config: testAccClassifierConfig_GrokClassifier(rName, "classification1", "pattern1"), + Config: testAccClassifierConfig_grok(rName, "classification1", "pattern1"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -332,7 +332,7 @@ func TestAccGlueClassifier_xmlClassifier(t *testing.T) { CheckDestroy: testAccCheckClassifierDestroy, Steps: []resource.TestStep{ { - Config: testAccClassifierConfig_XmlClassifier(rName, "classification1", "rowtag1"), + Config: testAccClassifierConfig_xml(rName, "classification1", "rowtag1"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -345,7 +345,7 @@ func TestAccGlueClassifier_xmlClassifier(t *testing.T) { ), }, { - Config: testAccClassifierConfig_XmlClassifier(rName, "classification2", "rowtag2"), + Config: testAccClassifierConfig_xml(rName, "classification2", "rowtag2"), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), resource.TestCheckResourceAttr(resourceName, "csv_classifier.#", "0"), @@ -379,7 +379,7 @@ func TestAccGlueClassifier_disappears(t *testing.T) { CheckDestroy: testAccCheckClassifierDestroy, Steps: []resource.TestStep{ { - Config: testAccClassifierConfig_CSVClassifier(rName, false, "PRESENT", "|", false), + Config: testAccClassifierConfig_csv(rName, false, "PRESENT", "|", false), Check: resource.ComposeTestCheckFunc( testAccCheckClassifierExists(resourceName, &classifier), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceClassifier(), resourceName), @@ -449,7 +449,7 @@ func testAccCheckClassifierDestroy(s *terraform.State) error { return nil } -func testAccClassifierConfig_CSVClassifier(rName string, allowSingleColumn bool, containsHeader string, delimiter string, disableValueTrimming bool) string { +func testAccClassifierConfig_csv(rName string, allowSingleColumn bool, containsHeader string, delimiter string, disableValueTrimming bool) string { return fmt.Sprintf(` resource "aws_glue_classifier" "test" { name = "%s" @@ -465,7 +465,7 @@ resource "aws_glue_classifier" "test" { `, rName, allowSingleColumn, containsHeader, delimiter, disableValueTrimming) } -func testAccClassifierCSVClassifierQuoteSymbolConfig(rName, symbol string) string { +func testAccClassifierConfig_csvQuoteSymbol(rName, symbol string) string { return fmt.Sprintf(` resource "aws_glue_classifier" "test" { name = %[1]q @@ -481,7 +481,7 @@ resource "aws_glue_classifier" "test" { `, rName, symbol) } -func testAccClassifierConfig_GrokClassifier(rName, classification, grokPattern string) string { +func testAccClassifierConfig_grok(rName, classification, grokPattern string) string { return fmt.Sprintf(` resource "aws_glue_classifier" "test" { name = "%s" @@ -494,7 +494,7 @@ resource "aws_glue_classifier" "test" { `, rName, classification, grokPattern) } -func testAccClassifierConfig_GrokClassifier_CustomPatterns(rName, customPatterns string) string { +func testAccClassifierConfig_grokCustomPatterns(rName, customPatterns string) string { return fmt.Sprintf(` resource "aws_glue_classifier" "test" { name = "%s" @@ -508,7 +508,7 @@ resource "aws_glue_classifier" "test" { `, rName, customPatterns) } -func testAccClassifierConfig_JSONClassifier(rName, jsonPath string) string { +func testAccClassifierConfig_json(rName, jsonPath string) string { return fmt.Sprintf(` resource "aws_glue_classifier" "test" { name = "%s" @@ -520,7 +520,7 @@ resource "aws_glue_classifier" "test" { `, rName, jsonPath) } -func testAccClassifierConfig_XmlClassifier(rName, classification, rowTag string) string { +func testAccClassifierConfig_xml(rName, classification, rowTag string) string { return fmt.Sprintf(` resource "aws_glue_classifier" "test" { name = "%s" diff --git a/internal/service/glue/connection_data_source_test.go b/internal/service/glue/connection_data_source_test.go index 46a3d5c74ca..fd18eac8b27 100644 --- a/internal/service/glue/connection_data_source_test.go +++ b/internal/service/glue/connection_data_source_test.go @@ -24,7 +24,7 @@ func TestAccGlueConnectionDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectionDataSourceConfig(rName, jdbcConnectionUrl), + Config: testAccConnectionDataSourceConfig_basic(rName, jdbcConnectionUrl), Check: resource.ComposeTestCheckFunc( testAccConnectionCheckDataSource(datasourceName), resource.TestCheckResourceAttrPair(datasourceName, "catalog_id", resourceName, "catalog_id"), @@ -53,7 +53,7 @@ func testAccConnectionCheckDataSource(name string) resource.TestCheckFunc { } } -func testAccConnectionDataSourceConfig(rName, jdbcConnectionUrl string) string { +func testAccConnectionDataSourceConfig_basic(rName, jdbcConnectionUrl string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = %[1]q diff --git a/internal/service/glue/connection_test.go b/internal/service/glue/connection_test.go index 231066b1233..5ab77daf6e6 100644 --- a/internal/service/glue/connection_test.go +++ b/internal/service/glue/connection_test.go @@ -29,7 +29,7 @@ func TestAccGlueConnection_basic(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig_Required(rName, jdbcConnectionUrl), + Config: testAccConnectionConfig_required(rName, jdbcConnectionUrl), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("connection/%s", rName)), @@ -66,7 +66,7 @@ func TestAccGlueConnection_tags(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionTags1Config(rName, jdbcConnectionUrl, "key1", "value1"), + Config: testAccConnectionConfig_tags1(rName, jdbcConnectionUrl, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -79,7 +79,7 @@ func TestAccGlueConnection_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConnectionTags2Config(rName, jdbcConnectionUrl, "key1", "value1updated", "key2", "value2"), + Config: testAccConnectionConfig_tags2(rName, jdbcConnectionUrl, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -88,7 +88,7 @@ func TestAccGlueConnection_tags(t *testing.T) { ), }, { - Config: testAccConnectionTags1Config(rName, jdbcConnectionUrl, "key2", "value2"), + Config: testAccConnectionConfig_tags1(rName, jdbcConnectionUrl, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -114,7 +114,7 @@ func TestAccGlueConnection_mongoDB(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig_MongoDB(rName, connectionUrl), + Config: testAccConnectionConfig_mongoDB(rName, connectionUrl), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "connection_properties.%", "3"), @@ -150,7 +150,7 @@ func TestAccGlueConnection_kafka(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig_Kafka(rName, bootstrapServers), + Config: testAccConnectionConfig_kafka(rName, bootstrapServers), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "connection_properties.%", "1"), @@ -182,7 +182,7 @@ func TestAccGlueConnection_network(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig_Network(rName), + Config: testAccConnectionConfig_network(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "connection_properties.%", "0"), @@ -218,14 +218,14 @@ func TestAccGlueConnection_description(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig_Description(rName, jdbcConnectionUrl, "First Description"), + Config: testAccConnectionConfig_description(rName, jdbcConnectionUrl, "First Description"), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "description", "First Description"), ), }, { - Config: testAccConnectionConfig_Description(rName, jdbcConnectionUrl, "Second Description"), + Config: testAccConnectionConfig_description(rName, jdbcConnectionUrl, "Second Description"), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "description", "Second Description"), @@ -255,7 +255,7 @@ func TestAccGlueConnection_matchCriteria(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig_MatchCriteria_First(rName, jdbcConnectionUrl), + Config: testAccConnectionConfig_matchCriteriaFirst(rName, jdbcConnectionUrl), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "match_criteria.#", "4"), @@ -266,7 +266,7 @@ func TestAccGlueConnection_matchCriteria(t *testing.T) { ), }, { - Config: testAccConnectionConfig_MatchCriteria_Second(rName, jdbcConnectionUrl), + Config: testAccConnectionConfig_matchCriteriaSecond(rName, jdbcConnectionUrl), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "match_criteria.#", "1"), @@ -274,7 +274,7 @@ func TestAccGlueConnection_matchCriteria(t *testing.T) { ), }, { - Config: testAccConnectionConfig_MatchCriteria_Third(rName, jdbcConnectionUrl), + Config: testAccConnectionConfig_matchCriteriaThird(rName, jdbcConnectionUrl), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "match_criteria.#", "3"), @@ -305,7 +305,7 @@ func TestAccGlueConnection_physicalConnectionRequirements(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig_PhysicalConnectionRequirements(rName), + Config: testAccConnectionConfig_physicalRequirements(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), resource.TestCheckResourceAttr(resourceName, "connection_properties.%", "3"), @@ -344,7 +344,7 @@ func TestAccGlueConnection_disappears(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig_Required(rName, jdbcConnectionUrl), + Config: testAccConnectionConfig_required(rName, jdbcConnectionUrl), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName, &connection), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceConnection(), resourceName), @@ -413,7 +413,7 @@ func testAccCheckConnectionDestroy(s *terraform.State) error { return nil } -func testAccConnectionConfig_Description(rName, jdbcConnectionUrl, description string) string { +func testAccConnectionConfig_description(rName, jdbcConnectionUrl, description string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = %[1]q @@ -429,7 +429,7 @@ resource "aws_glue_connection" "test" { `, rName, description, jdbcConnectionUrl) } -func testAccConnectionConfig_MatchCriteria_First(rName, jdbcConnectionUrl string) string { +func testAccConnectionConfig_matchCriteriaFirst(rName, jdbcConnectionUrl string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = %[1]q @@ -445,7 +445,7 @@ resource "aws_glue_connection" "test" { `, rName, jdbcConnectionUrl) } -func testAccConnectionConfig_MatchCriteria_Second(rName, jdbcConnectionUrl string) string { +func testAccConnectionConfig_matchCriteriaSecond(rName, jdbcConnectionUrl string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = %[1]q @@ -461,7 +461,7 @@ resource "aws_glue_connection" "test" { `, rName, jdbcConnectionUrl) } -func testAccConnectionConfig_MatchCriteria_Third(rName, jdbcConnectionUrl string) string { +func testAccConnectionConfig_matchCriteriaThird(rName, jdbcConnectionUrl string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = "%s" @@ -477,7 +477,7 @@ resource "aws_glue_connection" "test" { `, rName, jdbcConnectionUrl) } -func testAccConnectionConfig_PhysicalConnectionRequirements(rName string) string { +func testAccConnectionConfig_physicalRequirements(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -562,7 +562,7 @@ resource "aws_glue_connection" "test" { `, rName) } -func testAccConnectionConfig_Required(rName, jdbcConnectionUrl string) string { +func testAccConnectionConfig_required(rName, jdbcConnectionUrl string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = %[1]q @@ -576,7 +576,7 @@ resource "aws_glue_connection" "test" { `, rName, jdbcConnectionUrl) } -func testAccConnectionTags1Config(rName, jdbcConnectionUrl, tagKey1, tagValue1 string) string { +func testAccConnectionConfig_tags1(rName, jdbcConnectionUrl, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = %[1]q @@ -594,7 +594,7 @@ resource "aws_glue_connection" "test" { `, rName, jdbcConnectionUrl, tagKey1, tagValue1) } -func testAccConnectionTags2Config(rName, jdbcConnectionUrl, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccConnectionConfig_tags2(rName, jdbcConnectionUrl, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = %[1]q @@ -613,7 +613,7 @@ resource "aws_glue_connection" "test" { `, rName, jdbcConnectionUrl, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccConnectionConfig_MongoDB(rName, connectionUrl string) string { +func testAccConnectionConfig_mongoDB(rName, connectionUrl string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = %[1]q @@ -628,7 +628,7 @@ resource "aws_glue_connection" "test" { `, rName, connectionUrl) } -func testAccConnectionConfig_Kafka(rName, bootstrapServers string) string { +func testAccConnectionConfig_kafka(rName, bootstrapServers string) string { return fmt.Sprintf(` resource "aws_glue_connection" "test" { name = %[1]q @@ -641,7 +641,7 @@ resource "aws_glue_connection" "test" { `, rName, bootstrapServers) } -func testAccConnectionConfig_Network(rName string) string { +func testAccConnectionConfig_network(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" diff --git a/internal/service/glue/crawler_test.go b/internal/service/glue/crawler_test.go index 307482ee11a..a42d8cdb4d9 100644 --- a/internal/service/glue/crawler_test.go +++ b/internal/service/glue/crawler_test.go @@ -261,7 +261,7 @@ func TestAccGlueCrawler_JDBCTarget_exclusions(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_JDBCTarget_exclusions2(rName, jdbcConnectionUrl, "exclusion1", "exclusion2"), + Config: testAccCrawlerConfig_jdbcTargetExclusions2(rName, jdbcConnectionUrl, "exclusion1", "exclusion2"), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -272,7 +272,7 @@ func TestAccGlueCrawler_JDBCTarget_exclusions(t *testing.T) { ), }, { - Config: testAccCrawlerConfig_JDBCTarget_exclusions1(rName, jdbcConnectionUrl, "exclusion1"), + Config: testAccCrawlerConfig_jdbcTargetExclusions1(rName, jdbcConnectionUrl, "exclusion1"), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -304,7 +304,7 @@ func TestAccGlueCrawler_JDBCTarget_multiple(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_JDBCTarget_multiple(rName, jdbcConnectionUrl, "database-name/table1", "database-name/table2"), + Config: testAccCrawlerConfig_jdbcTargetMultiple(rName, jdbcConnectionUrl, "database-name/table1", "database-name/table2"), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -329,7 +329,7 @@ func TestAccGlueCrawler_JDBCTarget_multiple(t *testing.T) { ), }, { - Config: testAccCrawlerConfig_JDBCTarget_multiple(rName, jdbcConnectionUrl, "database-name/table1", "database-name/table2"), + Config: testAccCrawlerConfig_jdbcTargetMultiple(rName, jdbcConnectionUrl, "database-name/table1", "database-name/table2"), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), resource.TestCheckResourceAttr(resourceName, "jdbc_target.#", "2"), @@ -628,7 +628,7 @@ func TestAccGlueCrawler_S3Target_connectionName(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_S3Target_connectionName(rName), + Config: testAccCrawlerConfig_s3TargetConnectionName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -693,7 +693,7 @@ func TestAccGlueCrawler_S3Target_exclusions(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_S3Target_exclusions2(rName, "exclusion1", "exclusion2"), + Config: testAccCrawlerConfig_s3TargetExclusions2(rName, "exclusion1", "exclusion2"), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -704,7 +704,7 @@ func TestAccGlueCrawler_S3Target_exclusions(t *testing.T) { ), }, { - Config: testAccCrawlerConfig_S3Target_exclusions1(rName, "exclusion1"), + Config: testAccCrawlerConfig_s3TargetExclusions1(rName, "exclusion1"), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -734,7 +734,7 @@ func TestAccGlueCrawler_S3Target_eventqueue(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_S3Target_eventQueue(rName), + Config: testAccCrawlerConfig_s3TargetEventQueue(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -764,7 +764,7 @@ func TestAccGlueCrawler_S3Target_dlqeventqueue(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_S3Target_dlqEventQueue(rName), + Config: testAccCrawlerConfig_s3TargetDlqEventQueue(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -795,7 +795,7 @@ func TestAccGlueCrawler_S3Target_multiple(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_S3Target_multiple(rName, "s3://bucket1", "s3://bucket2"), + Config: testAccCrawlerConfig_s3TargetMultiple(rName, "s3://bucket1", "s3://bucket2"), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -817,7 +817,7 @@ func TestAccGlueCrawler_S3Target_multiple(t *testing.T) { ), }, { - Config: testAccCrawlerConfig_S3Target_multiple(rName, "s3://bucket1", "s3://bucket2"), + Config: testAccCrawlerConfig_s3TargetMultiple(rName, "s3://bucket1", "s3://bucket2"), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -933,7 +933,7 @@ func TestAccGlueCrawler_CatalogTarget_multiple(t *testing.T) { ), }, { - Config: testAccCrawlerConfig_CatalogTarget_multiple(rName), + Config: testAccCrawlerConfig_catalogTargetMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("crawler/%s", rName)), @@ -1001,7 +1001,7 @@ func TestAccGlueCrawler_classifiers(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_Classifiers_single(rName), + Config: testAccCrawlerConfig_classifiersSingle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), resource.TestCheckResourceAttr(resourceName, "classifiers.#", "1"), @@ -1009,7 +1009,7 @@ func TestAccGlueCrawler_classifiers(t *testing.T) { ), }, { - Config: testAccCrawlerConfig_Classifiers_multiple(rName), + Config: testAccCrawlerConfig_classifiersMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), resource.TestCheckResourceAttr(resourceName, "classifiers.#", "2"), @@ -1018,7 +1018,7 @@ func TestAccGlueCrawler_classifiers(t *testing.T) { ), }, { - Config: testAccCrawlerConfig_Classifiers_single(rName), + Config: testAccCrawlerConfig_classifiersSingle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), resource.TestCheckResourceAttr(resourceName, "classifiers.#", "1"), @@ -1124,7 +1124,7 @@ func TestAccGlueCrawler_RoleARN_noPath(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_Role_ARN_noPath(rName), + Config: testAccCrawlerConfig_roleARNNoPath(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "name"), @@ -1151,7 +1151,7 @@ func TestAccGlueCrawler_RoleARN_path(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_Role_ARN_path(rName), + Config: testAccCrawlerConfig_roleARNPath(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), resource.TestCheckResourceAttr(resourceName, "role", fmt.Sprintf("path/%s", rName)), @@ -1178,7 +1178,7 @@ func TestAccGlueCrawler_RoleName_path(t *testing.T) { CheckDestroy: testAccCheckCrawlerDestroy, Steps: []resource.TestStep{ { - Config: testAccCrawlerConfig_Role_Name_path(rName), + Config: testAccCrawlerConfig_roleNamePath(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCrawlerExists(resourceName, &crawler), resource.TestCheckResourceAttr(resourceName, "role", fmt.Sprintf("path/%s", rName)), @@ -1635,7 +1635,7 @@ EOF `, rName) } -func testAccCrawlerConfig_Classifiers_single(rName string) string { +func testAccCrawlerConfig_classifiersSingle(rName string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %q @@ -1674,7 +1674,7 @@ resource "aws_glue_crawler" "test" { `, rName, rName+"1", rName+"2", rName) } -func testAccCrawlerConfig_Classifiers_multiple(rName string) string { +func testAccCrawlerConfig_classifiersMultiple(rName string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %q @@ -1848,7 +1848,7 @@ resource "aws_glue_crawler" "test" { `, rName, jdbcConnectionUrl, path) } -func testAccCrawlerConfig_JDBCTarget_exclusions1(rName, jdbcConnectionUrl, exclusion1 string) string { +func testAccCrawlerConfig_jdbcTargetExclusions1(rName, jdbcConnectionUrl, exclusion1 string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -1880,7 +1880,7 @@ resource "aws_glue_crawler" "test" { `, rName, jdbcConnectionUrl, exclusion1) } -func testAccCrawlerConfig_JDBCTarget_exclusions2(rName, jdbcConnectionUrl, exclusion1, exclusion2 string) string { +func testAccCrawlerConfig_jdbcTargetExclusions2(rName, jdbcConnectionUrl, exclusion1, exclusion2 string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -1912,7 +1912,7 @@ resource "aws_glue_crawler" "test" { `, rName, jdbcConnectionUrl, exclusion1, exclusion2) } -func testAccCrawlerConfig_JDBCTarget_multiple(rName, jdbcConnectionUrl, path1, path2 string) string { +func testAccCrawlerConfig_jdbcTargetMultiple(rName, jdbcConnectionUrl, path1, path2 string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -1948,7 +1948,7 @@ resource "aws_glue_crawler" "test" { `, rName, jdbcConnectionUrl, path1, path2) } -func testAccCrawlerConfig_Role_ARN_noPath(rName string) string { +func testAccCrawlerConfig_roleARNNoPath(rName string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -1968,7 +1968,7 @@ resource "aws_glue_crawler" "test" { `, rName) } -func testAccCrawlerConfig_Role_ARN_path(rName string) string { +func testAccCrawlerConfig_roleARNPath(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -2016,7 +2016,7 @@ resource "aws_glue_crawler" "test" { `, rName) } -func testAccCrawlerConfig_Role_Name_path(rName string) string { +func testAccCrawlerConfig_roleNamePath(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -2084,7 +2084,7 @@ resource "aws_glue_crawler" "test" { `, rName, path) } -func testAccCrawlerConfig_S3Target_exclusions1(rName, exclusion1 string) string { +func testAccCrawlerConfig_s3TargetExclusions1(rName, exclusion1 string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -2105,7 +2105,7 @@ resource "aws_glue_crawler" "test" { `, rName, exclusion1) } -func testAccCrawlerConfig_S3Target_connectionName(rName string) string { +func testAccCrawlerConfig_s3TargetConnectionName(rName string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -2183,7 +2183,7 @@ resource "aws_glue_crawler" "test" { `, rName) } -func testAccCrawlerConfig_S3Target_exclusions2(rName, exclusion1, exclusion2 string) string { +func testAccCrawlerConfig_s3TargetExclusions2(rName, exclusion1, exclusion2 string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -2204,7 +2204,7 @@ resource "aws_glue_crawler" "test" { `, rName, exclusion1, exclusion2) } -func testAccCrawlerConfig_S3Target_eventQueue(rName string) string { +func testAccCrawlerConfig_s3TargetEventQueue(rName string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -2272,7 +2272,7 @@ resource "aws_glue_crawler" "test" { `, rName) } -func testAccCrawlerConfig_S3Target_dlqEventQueue(rName string) string { +func testAccCrawlerConfig_s3TargetDlqEventQueue(rName string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -2348,7 +2348,7 @@ resource "aws_glue_crawler" "test" { `, rName) } -func testAccCrawlerConfig_S3Target_multiple(rName, path1, path2 string) string { +func testAccCrawlerConfig_s3TargetMultiple(rName, path1, path2 string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { name = %[1]q @@ -2435,7 +2435,7 @@ EOF `, rName, tableCount) } -func testAccCrawlerConfig_CatalogTarget_multiple(rName string) string { +func testAccCrawlerConfig_catalogTargetMultiple(rName string) string { return testAccCrawlerConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { count = 2 diff --git a/internal/service/glue/data_catalog_encryption_settings_data_source_test.go b/internal/service/glue/data_catalog_encryption_settings_data_source_test.go index 6c1e58f5598..5587bd431d3 100644 --- a/internal/service/glue/data_catalog_encryption_settings_data_source_test.go +++ b/internal/service/glue/data_catalog_encryption_settings_data_source_test.go @@ -20,7 +20,7 @@ func testAccDataCatalogEncryptionSettingsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDataCatalogEncryptionSettingsDataSourceConfig(), + Config: testAccDataCatalogEncryptionSettingsDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "catalog_id", resourceName, "catalog_id"), resource.TestCheckResourceAttrPair(dataSourceName, "data_catalog_encryption_settings", resourceName, "data_catalog_encryption_settings"), @@ -30,7 +30,7 @@ func testAccDataCatalogEncryptionSettingsDataSource_basic(t *testing.T) { }) } -func testAccDataCatalogEncryptionSettingsDataSourceConfig() string { +func testAccDataCatalogEncryptionSettingsDataSourceConfig_basic() string { return ` resource "aws_glue_data_catalog_encryption_settings" "test" { data_catalog_encryption_settings { diff --git a/internal/service/glue/data_catalog_encryption_settings_test.go b/internal/service/glue/data_catalog_encryption_settings_test.go index e46424b02a6..cdecffcdcdb 100644 --- a/internal/service/glue/data_catalog_encryption_settings_test.go +++ b/internal/service/glue/data_catalog_encryption_settings_test.go @@ -29,7 +29,7 @@ func testAccDataCatalogEncryptionSettings_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccDataCatalogEncryptionSettingsNonEncryptedConfig(), + Config: testAccDataCatalogEncryptionSettingsConfig_nonEncrypted(), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogEncryptionSettingsExists(resourceName, &settings), resource.TestCheckResourceAttr(resourceName, "data_catalog_encryption_settings.#", "1"), @@ -47,7 +47,7 @@ func testAccDataCatalogEncryptionSettings_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDataCatalogEncryptionSettingsEncryptedConfig(rName), + Config: testAccDataCatalogEncryptionSettingsConfig_encrypted(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogEncryptionSettingsExists(resourceName, &settings), resource.TestCheckResourceAttr(resourceName, "data_catalog_encryption_settings.#", "1"), @@ -60,7 +60,7 @@ func testAccDataCatalogEncryptionSettings_basic(t *testing.T) { ), }, { - Config: testAccDataCatalogEncryptionSettingsNonEncryptedConfig(), + Config: testAccDataCatalogEncryptionSettingsConfig_nonEncrypted(), Check: resource.ComposeTestCheckFunc( testAccCheckDataCatalogEncryptionSettingsExists(resourceName, &settings), resource.TestCheckResourceAttr(resourceName, "data_catalog_encryption_settings.#", "1"), @@ -103,7 +103,7 @@ func testAccCheckDataCatalogEncryptionSettingsExists(resourceName string, v *glu } } -func testAccDataCatalogEncryptionSettingsEncryptedConfig(rName string) string { +func testAccDataCatalogEncryptionSettingsConfig_encrypted(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -142,7 +142,7 @@ resource "aws_glue_data_catalog_encryption_settings" "test" { `, rName) } -func testAccDataCatalogEncryptionSettingsNonEncryptedConfig() string { +func testAccDataCatalogEncryptionSettingsConfig_nonEncrypted() string { return ` resource "aws_glue_data_catalog_encryption_settings" "test" { data_catalog_encryption_settings { diff --git a/internal/service/glue/dev_endpoint_test.go b/internal/service/glue/dev_endpoint_test.go index 21f75a3788e..522298e2bc8 100644 --- a/internal/service/glue/dev_endpoint_test.go +++ b/internal/service/glue/dev_endpoint_test.go @@ -431,7 +431,7 @@ func TestAccGlueDevEndpoint_SubnetID_securityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckDevEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccDevEndpointConfig_SubnetID_securityGroupIDs(rName), + Config: testAccDevEndpointConfig_subnetIDSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDevEndpointExists(resourceName, &endpoint), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), @@ -462,7 +462,7 @@ func TestAccGlueDevEndpoint_tags(t *testing.T) { CheckDestroy: testAccCheckDevEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccDevEndpointConfig_Tags1(rName, "key1", "value1"), + Config: testAccDevEndpointConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDevEndpointExists(resourceName, &endpoint1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -475,7 +475,7 @@ func TestAccGlueDevEndpoint_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDevEndpointConfig_Tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDevEndpointConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDevEndpointExists(resourceName, &endpoint2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -484,7 +484,7 @@ func TestAccGlueDevEndpoint_tags(t *testing.T) { ), }, { - Config: testAccDevEndpointConfig_Tags1(rName, "key2", "value2"), + Config: testAccDevEndpointConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDevEndpointExists(resourceName, &endpoint3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -508,7 +508,7 @@ func TestAccGlueDevEndpoint_workerType(t *testing.T) { CheckDestroy: testAccCheckDevEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccDevEndpointConfig_WorkerType_standard(rName), + Config: testAccDevEndpointConfig_workerTypeStandard(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDevEndpointExists(resourceName, &endpoint), resource.TestCheckResourceAttr(resourceName, "worker_type", glue.WorkerTypeStandard), @@ -790,7 +790,7 @@ resource "aws_glue_security_configuration" "test" { `, rName) } -func testAccDevEndpointConfig_SubnetID_securityGroupIDs(rName string) string { +func testAccDevEndpointConfig_subnetIDSecurityGroupIDs(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), testAccDevEndpointConfig_base(rName), fmt.Sprintf(` resource "aws_glue_dev_endpoint" "test" { name = %[1]q @@ -865,7 +865,7 @@ resource "aws_security_group" "test" { `, rName)) } -func testAccDevEndpointConfig_Tags1(rName, tagKey1, tagValue1 string) string { +func testAccDevEndpointConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccJobConfig_Base(rName) + fmt.Sprintf(` resource "aws_glue_dev_endpoint" "test" { name = %[1]q @@ -878,7 +878,7 @@ resource "aws_glue_dev_endpoint" "test" { `, rName, tagKey1, tagValue1) } -func testAccDevEndpointConfig_Tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDevEndpointConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccJobConfig_Base(rName) + fmt.Sprintf(` resource "aws_glue_dev_endpoint" "test" { name = %[1]q @@ -903,7 +903,7 @@ resource "aws_glue_dev_endpoint" "test" { `, rName, workerType) } -func testAccDevEndpointConfig_WorkerType_standard(rName string) string { +func testAccDevEndpointConfig_workerTypeStandard(rName string) string { return testAccDevEndpointConfig_base(rName) + fmt.Sprintf(` resource "aws_glue_dev_endpoint" "test" { name = %[1]q diff --git a/internal/service/glue/job_test.go b/internal/service/glue/job_test.go index 0d8e3423044..c894032e877 100644 --- a/internal/service/glue/job_test.go +++ b/internal/service/glue/job_test.go @@ -30,7 +30,7 @@ func TestAccGlueJob_basic(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_Required(rName), + Config: testAccJobConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("job/%s", rName)), @@ -67,7 +67,7 @@ func TestAccGlueJob_basicStreaming(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_RequiredStreaming(rName), + Config: testAccJobConfig_requiredStreaming(rName), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("job/%s", rName)), @@ -103,7 +103,7 @@ func TestAccGlueJob_command(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_Command(rName, "testscriptlocation1"), + Config: testAccJobConfig_command(rName, "testscriptlocation1"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "command.#", "1"), @@ -111,7 +111,7 @@ func TestAccGlueJob_command(t *testing.T) { ), }, { - Config: testAccJobConfig_Command(rName, "testscriptlocation2"), + Config: testAccJobConfig_command(rName, "testscriptlocation2"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "command.#", "1"), @@ -140,7 +140,7 @@ func TestAccGlueJob_defaultArguments(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_DefaultArguments(rName, "job-bookmark-disable", "python"), + Config: testAccJobConfig_defaultArguments(rName, "job-bookmark-disable", "python"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "default_arguments.%", "2"), @@ -149,7 +149,7 @@ func TestAccGlueJob_defaultArguments(t *testing.T) { ), }, { - Config: testAccJobConfig_DefaultArguments(rName, "job-bookmark-enable", "scala"), + Config: testAccJobConfig_defaultArguments(rName, "job-bookmark-enable", "scala"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "default_arguments.%", "2"), @@ -179,7 +179,7 @@ func TestAccGlueJob_nonOverridableArguments(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobnonOverridableArgumentsConfig(rName, "job-bookmark-disable", "python"), + Config: testAccJobConfig_nonOverridableArguments(rName, "job-bookmark-disable", "python"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "non_overridable_arguments.%", "2"), @@ -188,7 +188,7 @@ func TestAccGlueJob_nonOverridableArguments(t *testing.T) { ), }, { - Config: testAccJobnonOverridableArgumentsConfig(rName, "job-bookmark-enable", "scala"), + Config: testAccJobConfig_nonOverridableArguments(rName, "job-bookmark-enable", "scala"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "non_overridable_arguments.%", "2"), @@ -218,14 +218,14 @@ func TestAccGlueJob_description(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_Description(rName, "First Description"), + Config: testAccJobConfig_description(rName, "First Description"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "description", "First Description"), ), }, { - Config: testAccJobConfig_Description(rName, "Second Description"), + Config: testAccJobConfig_description(rName, "Second Description"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "description", "Second Description"), @@ -253,14 +253,14 @@ func TestAccGlueJob_glueVersion(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_Version_maxCapacity(rName, "0.9"), + Config: testAccJobConfig_versionMaxCapacity(rName, "0.9"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "glue_version", "0.9"), ), }, { - Config: testAccJobConfig_Version_maxCapacity(rName, "1.0"), + Config: testAccJobConfig_versionMaxCapacity(rName, "1.0"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "glue_version", "1.0"), @@ -272,7 +272,7 @@ func TestAccGlueJob_glueVersion(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccJobConfig_Version_numberOfWorkers(rName, "2.0"), + Config: testAccJobConfig_versionNumberOfWorkers(rName, "2.0"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "glue_version", "2.0"), @@ -295,11 +295,11 @@ func TestAccGlueJob_executionProperty(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_ExecutionProperty(rName, 0), + Config: testAccJobConfig_executionProperty(rName, 0), ExpectError: regexp.MustCompile(`expected execution_property.0.max_concurrent_runs to be at least`), }, { - Config: testAccJobConfig_ExecutionProperty(rName, 1), + Config: testAccJobConfig_executionProperty(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "execution_property.#", "1"), @@ -307,7 +307,7 @@ func TestAccGlueJob_executionProperty(t *testing.T) { ), }, { - Config: testAccJobConfig_ExecutionProperty(rName, 2), + Config: testAccJobConfig_executionProperty(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "execution_property.#", "1"), @@ -336,18 +336,18 @@ func TestAccGlueJob_maxRetries(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_MaxRetries(rName, 11), + Config: testAccJobConfig_maxRetries(rName, 11), ExpectError: regexp.MustCompile(`expected max_retries to be in the range`), }, { - Config: testAccJobConfig_MaxRetries(rName, 0), + Config: testAccJobConfig_maxRetries(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_retries", "0"), ), }, { - Config: testAccJobConfig_MaxRetries(rName, 10), + Config: testAccJobConfig_maxRetries(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_retries", "10"), @@ -375,11 +375,11 @@ func TestAccGlueJob_notificationProperty(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_NotificationProperty(rName, 0), + Config: testAccJobConfig_notificationProperty(rName, 0), ExpectError: regexp.MustCompile(`expected notification_property.0.notify_delay_after to be at least`), }, { - Config: testAccJobConfig_NotificationProperty(rName, 1), + Config: testAccJobConfig_notificationProperty(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "notification_property.#", "1"), @@ -387,7 +387,7 @@ func TestAccGlueJob_notificationProperty(t *testing.T) { ), }, { - Config: testAccJobConfig_NotificationProperty(rName, 2), + Config: testAccJobConfig_notificationProperty(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "notification_property.#", "1"), @@ -416,7 +416,7 @@ func TestAccGlueJob_tags(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobTags1Config(rName, "key1", "value1"), + Config: testAccJobConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -429,7 +429,7 @@ func TestAccGlueJob_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccJobTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccJobConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -438,7 +438,7 @@ func TestAccGlueJob_tags(t *testing.T) { ), }, { - Config: testAccJobTags1Config(rName, "key2", "value2"), + Config: testAccJobConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -462,14 +462,14 @@ func TestAccGlueJob_streamingTimeout(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_Timeout(rName, 1), + Config: testAccJobConfig_timeout(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "timeout", "1"), ), }, { - Config: testAccJobConfig_Timeout(rName, 2), + Config: testAccJobConfig_timeout(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "timeout", "2"), @@ -496,14 +496,14 @@ func TestAccGlueJob_timeout(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_Timeout(rName, 1), + Config: testAccJobConfig_timeout(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "timeout", "1"), ), }, { - Config: testAccJobConfig_Timeout(rName, 2), + Config: testAccJobConfig_timeout(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "timeout", "2"), @@ -531,14 +531,14 @@ func TestAccGlueJob_security(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_SecurityConfiguration(rName, "default_encryption"), + Config: testAccJobConfig_securityConfiguration(rName, "default_encryption"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "security_configuration", "default_encryption"), ), }, { - Config: testAccJobConfig_SecurityConfiguration(rName, "custom_encryption2"), + Config: testAccJobConfig_securityConfiguration(rName, "custom_encryption2"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "security_configuration", "custom_encryption2"), @@ -566,21 +566,21 @@ func TestAccGlueJob_workerType(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_WorkerType(rName, "Standard"), + Config: testAccJobConfig_workerType(rName, "Standard"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "worker_type", "Standard"), ), }, { - Config: testAccJobConfig_WorkerType(rName, "G.1X"), + Config: testAccJobConfig_workerType(rName, "G.1X"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "worker_type", "G.1X"), ), }, { - Config: testAccJobConfig_WorkerType(rName, "G.2X"), + Config: testAccJobConfig_workerType(rName, "G.2X"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "worker_type", "G.2X"), @@ -608,7 +608,7 @@ func TestAccGlueJob_pythonShell(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_PythonShell(rName), + Config: testAccJobConfig_pythonShell(rName), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_capacity", "0.0625"), @@ -623,7 +623,7 @@ func TestAccGlueJob_pythonShell(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccJobConfig_PythonShellWithVersion(rName, "2"), + Config: testAccJobConfig_pythonShellVersion(rName, "2"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "command.#", "1"), @@ -638,7 +638,7 @@ func TestAccGlueJob_pythonShell(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccJobConfig_PythonShellWithVersion(rName, "3"), + Config: testAccJobConfig_pythonShellVersion(rName, "3"), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "command.#", "1"), @@ -664,7 +664,7 @@ func TestAccGlueJob_maxCapacity(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_MaxCapacity(rName, 10), + Config: testAccJobConfig_maxCapacity(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_capacity", "10"), @@ -674,7 +674,7 @@ func TestAccGlueJob_maxCapacity(t *testing.T) { ), }, { - Config: testAccJobConfig_MaxCapacity(rName, 15), + Config: testAccJobConfig_maxCapacity(rName, 15), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_capacity", "15"), @@ -702,7 +702,7 @@ func TestAccGlueJob_disappears(t *testing.T) { CheckDestroy: testAccCheckJobDestroy, Steps: []resource.TestStep{ { - Config: testAccJobConfig_Required(rName), + Config: testAccJobConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckJobExists(resourceName, &job), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceJob(), resourceName), @@ -811,7 +811,7 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName) } -func testAccJobConfig_Command(rName, scriptLocation string) string { +func testAccJobConfig_command(rName, scriptLocation string) string { return fmt.Sprintf(` %s @@ -829,7 +829,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName, scriptLocation) } -func testAccJobConfig_DefaultArguments(rName, jobBookmarkOption, jobLanguage string) string { +func testAccJobConfig_defaultArguments(rName, jobBookmarkOption, jobLanguage string) string { return fmt.Sprintf(` %s @@ -852,7 +852,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName, jobBookmarkOption, jobLanguage) } -func testAccJobnonOverridableArgumentsConfig(rName, jobBookmarkOption, jobLanguage string) string { +func testAccJobConfig_nonOverridableArguments(rName, jobBookmarkOption, jobLanguage string) string { return fmt.Sprintf(` %s @@ -875,7 +875,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName, jobBookmarkOption, jobLanguage) } -func testAccJobConfig_Description(rName, description string) string { +func testAccJobConfig_description(rName, description string) string { return fmt.Sprintf(` %s @@ -894,7 +894,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), description, rName) } -func testAccJobConfig_Version_maxCapacity(rName, glueVersion string) string { +func testAccJobConfig_versionMaxCapacity(rName, glueVersion string) string { return fmt.Sprintf(` %s @@ -913,7 +913,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), glueVersion, rName) } -func testAccJobConfig_Version_numberOfWorkers(rName, glueVersion string) string { +func testAccJobConfig_versionNumberOfWorkers(rName, glueVersion string) string { return fmt.Sprintf(` %s @@ -933,7 +933,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), glueVersion, rName) } -func testAccJobConfig_ExecutionProperty(rName string, maxConcurrentRuns int) string { +func testAccJobConfig_executionProperty(rName string, maxConcurrentRuns int) string { return fmt.Sprintf(` %s @@ -955,7 +955,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName, maxConcurrentRuns) } -func testAccJobConfig_MaxRetries(rName string, maxRetries int) string { +func testAccJobConfig_maxRetries(rName string, maxRetries int) string { return fmt.Sprintf(` %s @@ -974,7 +974,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), maxRetries, rName) } -func testAccJobConfig_NotificationProperty(rName string, notifyDelayAfter int) string { +func testAccJobConfig_notificationProperty(rName string, notifyDelayAfter int) string { return fmt.Sprintf(` %s @@ -996,7 +996,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName, notifyDelayAfter) } -func testAccJobConfig_Required(rName string) string { +func testAccJobConfig_required(rName string) string { return fmt.Sprintf(` %s @@ -1014,7 +1014,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName) } -func testAccJobConfig_RequiredStreaming(rName string) string { +func testAccJobConfig_requiredStreaming(rName string) string { return fmt.Sprintf(` %s @@ -1033,7 +1033,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName) } -func testAccJobTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccJobConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccJobConfig_Base(rName) + fmt.Sprintf(` resource "aws_glue_job" "test" { name = %[1]q @@ -1054,7 +1054,7 @@ resource "aws_glue_job" "test" { `, rName, tagKey1, tagValue1) } -func testAccJobTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccJobConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccJobConfig_Base(rName) + fmt.Sprintf(` resource "aws_glue_job" "test" { name = %[1]q @@ -1076,7 +1076,7 @@ resource "aws_glue_job" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccJobConfig_Timeout(rName string, timeout int) string { +func testAccJobConfig_timeout(rName string, timeout int) string { return fmt.Sprintf(` %s @@ -1095,7 +1095,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName, timeout) } -func testAccJobConfig_SecurityConfiguration(rName string, securityConfiguration string) string { +func testAccJobConfig_securityConfiguration(rName string, securityConfiguration string) string { return fmt.Sprintf(` %s @@ -1114,7 +1114,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName, securityConfiguration) } -func testAccJobConfig_WorkerType(rName string, workerType string) string { +func testAccJobConfig_workerType(rName string, workerType string) string { return fmt.Sprintf(` %s @@ -1133,7 +1133,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName, workerType) } -func testAccJobConfig_PythonShell(rName string) string { +func testAccJobConfig_pythonShell(rName string) string { return fmt.Sprintf(` %s @@ -1152,7 +1152,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName) } -func testAccJobConfig_PythonShellWithVersion(rName string, pythonVersion string) string { +func testAccJobConfig_pythonShellVersion(rName string, pythonVersion string) string { return fmt.Sprintf(` %s @@ -1172,7 +1172,7 @@ resource "aws_glue_job" "test" { `, testAccJobConfig_Base(rName), rName, pythonVersion) } -func testAccJobConfig_MaxCapacity(rName string, maxCapacity float64) string { +func testAccJobConfig_maxCapacity(rName string, maxCapacity float64) string { return fmt.Sprintf(` %s diff --git a/internal/service/glue/ml_transform_test.go b/internal/service/glue/ml_transform_test.go index 15955c893ab..0912804d650 100644 --- a/internal/service/glue/ml_transform_test.go +++ b/internal/service/glue/ml_transform_test.go @@ -31,7 +31,7 @@ func TestAccGlueMlTransform_basic(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMLTransformBasicConfig(rName), + Config: testAccMLTransformConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "glue", regexp.MustCompile(`mlTransform/tfm-.+`)), @@ -79,7 +79,7 @@ func TestAccGlueMlTransform_typeFindMatchesFull(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMLTransformTypeFindMatchesFullConfig(rName, true, 0.5), + Config: testAccMLTransformConfig_typeFindMatchesFull(rName, true, 0.5), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "parameters.#", "1"), @@ -97,7 +97,7 @@ func TestAccGlueMlTransform_typeFindMatchesFull(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMLTransformTypeFindMatchesFullConfig(rName, false, 1), + Config: testAccMLTransformConfig_typeFindMatchesFull(rName, false, 1), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "parameters.#", "1"), @@ -110,7 +110,7 @@ func TestAccGlueMlTransform_typeFindMatchesFull(t *testing.T) { ), }, { - Config: testAccMLTransformTypeFindMatchesFullConfig(rName, true, 0.5), + Config: testAccMLTransformConfig_typeFindMatchesFull(rName, true, 0.5), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "parameters.#", "1"), @@ -139,14 +139,14 @@ func TestAccGlueMlTransform_description(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMLTransformDescriptionConfig(rName, "First Description"), + Config: testAccMLTransformConfig_description(rName, "First Description"), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "description", "First Description"), ), }, { - Config: testAccMLTransformDescriptionConfig(rName, "Second Description"), + Config: testAccMLTransformConfig_description(rName, "Second Description"), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "description", "Second Description"), @@ -174,14 +174,14 @@ func TestAccGlueMlTransform_glueVersion(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMlTransformConfig_mLTransformVersion(rName, "0.9"), + Config: testAccMLTransformConfig_version(rName, "0.9"), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "glue_version", "0.9"), ), }, { - Config: testAccMlTransformConfig_mLTransformVersion(rName, "1.0"), + Config: testAccMLTransformConfig_version(rName, "1.0"), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "glue_version", "1.0"), @@ -209,18 +209,18 @@ func TestAccGlueMlTransform_maxRetries(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMLTransformMaxRetriesConfig(rName, 11), + Config: testAccMLTransformConfig_maxRetries(rName, 11), ExpectError: regexp.MustCompile(`expected max_retries to be in the range`), }, { - Config: testAccMLTransformMaxRetriesConfig(rName, 0), + Config: testAccMLTransformConfig_maxRetries(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "max_retries", "0"), ), }, { - Config: testAccMLTransformMaxRetriesConfig(rName, 10), + Config: testAccMLTransformConfig_maxRetries(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "max_retries", "10"), @@ -248,7 +248,7 @@ func TestAccGlueMlTransform_tags(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMLTransformTags1Config(rName, "key1", "value1"), + Config: testAccMLTransformConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -261,7 +261,7 @@ func TestAccGlueMlTransform_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMLTransformTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccMLTransformConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -270,7 +270,7 @@ func TestAccGlueMlTransform_tags(t *testing.T) { ), }, { - Config: testAccMLTransformTags1Config(rName, "key2", "value2"), + Config: testAccMLTransformConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -294,14 +294,14 @@ func TestAccGlueMlTransform_timeout(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMLTransformTimeoutConfig(rName, 1), + Config: testAccMLTransformConfig_timeout(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "timeout", "1"), ), }, { - Config: testAccMLTransformTimeoutConfig(rName, 2), + Config: testAccMLTransformConfig_timeout(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "timeout", "2"), @@ -329,7 +329,7 @@ func TestAccGlueMlTransform_workerType(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMLTransformWorkerTypeConfig(rName, "Standard", 1), + Config: testAccMLTransformConfig_workerType(rName, "Standard", 1), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "worker_type", "Standard"), @@ -337,7 +337,7 @@ func TestAccGlueMlTransform_workerType(t *testing.T) { ), }, { - Config: testAccMLTransformWorkerTypeConfig(rName, "G.1X", 2), + Config: testAccMLTransformConfig_workerType(rName, "G.1X", 2), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "worker_type", "G.1X"), @@ -366,14 +366,14 @@ func TestAccGlueMlTransform_maxCapacity(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMLTransformMaxCapacityConfig(rName, 10), + Config: testAccMLTransformConfig_maxCapacity(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "max_capacity", "10"), ), }, { - Config: testAccMLTransformMaxCapacityConfig(rName, 15), + Config: testAccMLTransformConfig_maxCapacity(rName, 15), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), resource.TestCheckResourceAttr(resourceName, "max_capacity", "15"), @@ -401,7 +401,7 @@ func TestAccGlueMlTransform_disappears(t *testing.T) { CheckDestroy: testAccCheckMLTransformDestroy, Steps: []resource.TestStep{ { - Config: testAccMLTransformBasicConfig(rName), + Config: testAccMLTransformConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMLTransformExists(resourceName, &transform), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceMLTransform(), resourceName), @@ -594,7 +594,7 @@ resource "aws_glue_catalog_table" "test" { `, rName) } -func testAccMLTransformBasicConfig(rName string) string { +func testAccMLTransformConfig_basic(rName string) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q @@ -618,7 +618,7 @@ resource "aws_glue_ml_transform" "test" { `, rName) } -func testAccMLTransformTypeFindMatchesFullConfig(rName string, enforce bool, tradeOff float64) string { +func testAccMLTransformConfig_typeFindMatchesFull(rName string, enforce bool, tradeOff float64) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q @@ -645,7 +645,7 @@ resource "aws_glue_ml_transform" "test" { `, rName, enforce, tradeOff) } -func testAccMLTransformDescriptionConfig(rName, description string) string { +func testAccMLTransformConfig_description(rName, description string) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q @@ -670,7 +670,7 @@ resource "aws_glue_ml_transform" "test" { `, rName, description) } -func testAccMlTransformConfig_mLTransformVersion(rName, glueVersion string) string { +func testAccMLTransformConfig_version(rName, glueVersion string) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q @@ -695,7 +695,7 @@ resource "aws_glue_ml_transform" "test" { `, rName, glueVersion) } -func testAccMLTransformMaxRetriesConfig(rName string, maxRetries int) string { +func testAccMLTransformConfig_maxRetries(rName string, maxRetries int) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q @@ -720,7 +720,7 @@ resource "aws_glue_ml_transform" "test" { `, rName, maxRetries) } -func testAccMLTransformTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccMLTransformConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q @@ -748,7 +748,7 @@ resource "aws_glue_ml_transform" "test" { `, rName, tagKey1, tagValue1) } -func testAccMLTransformTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccMLTransformConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q @@ -777,7 +777,7 @@ resource "aws_glue_ml_transform" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccMLTransformTimeoutConfig(rName string, timeout int) string { +func testAccMLTransformConfig_timeout(rName string, timeout int) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q @@ -802,7 +802,7 @@ resource "aws_glue_ml_transform" "test" { `, rName, timeout) } -func testAccMLTransformWorkerTypeConfig(rName, workerType string, numOfWorkers int) string { +func testAccMLTransformConfig_workerType(rName, workerType string, numOfWorkers int) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q @@ -828,7 +828,7 @@ resource "aws_glue_ml_transform" "test" { `, rName, workerType, numOfWorkers) } -func testAccMLTransformMaxCapacityConfig(rName string, maxCapacity float64) string { +func testAccMLTransformConfig_maxCapacity(rName string, maxCapacity float64) string { return testAccMLTransformBaseConfig(rName) + fmt.Sprintf(` resource "aws_glue_ml_transform" "test" { name = %[1]q diff --git a/internal/service/glue/registry_test.go b/internal/service/glue/registry_test.go index 833d820ecd7..08c9b83a7ce 100644 --- a/internal/service/glue/registry_test.go +++ b/internal/service/glue/registry_test.go @@ -28,7 +28,7 @@ func TestAccGlueRegistry_basic(t *testing.T) { CheckDestroy: testAccCheckRegistryDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryBasicConfig(rName), + Config: testAccRegistryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, ®istry), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("registry/%s", rName)), @@ -59,14 +59,14 @@ func TestAccGlueRegistry_description(t *testing.T) { CheckDestroy: testAccCheckRegistryDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryDescriptionConfig(rName, "First Description"), + Config: testAccRegistryConfig_description(rName, "First Description"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, ®istry), resource.TestCheckResourceAttr(resourceName, "description", "First Description"), ), }, { - Config: testAccRegistryDescriptionConfig(rName, "Second Description"), + Config: testAccRegistryConfig_description(rName, "Second Description"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, ®istry), resource.TestCheckResourceAttr(resourceName, "description", "Second Description"), @@ -93,7 +93,7 @@ func TestAccGlueRegistry_tags(t *testing.T) { CheckDestroy: testAccCheckRegistryDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryTags1Config(rName, "key1", "value1"), + Config: testAccRegistryConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, ®istry), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -106,7 +106,7 @@ func TestAccGlueRegistry_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRegistryTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccRegistryConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, ®istry), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -115,7 +115,7 @@ func TestAccGlueRegistry_tags(t *testing.T) { ), }, { - Config: testAccRegistryTags1Config(rName, "key2", "value2"), + Config: testAccRegistryConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, ®istry), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -139,7 +139,7 @@ func TestAccGlueRegistry_disappears(t *testing.T) { CheckDestroy: testAccCheckRegistryDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryBasicConfig(rName), + Config: testAccRegistryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, ®istry), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceRegistry(), resourceName), @@ -220,7 +220,7 @@ func testAccCheckRegistryDestroy(s *terraform.State) error { return nil } -func testAccRegistryDescriptionConfig(rName, description string) string { +func testAccRegistryConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_glue_registry" "test" { registry_name = %[1]q @@ -229,7 +229,7 @@ resource "aws_glue_registry" "test" { `, rName, description) } -func testAccRegistryBasicConfig(rName string) string { +func testAccRegistryConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_glue_registry" "test" { registry_name = %[1]q @@ -237,7 +237,7 @@ resource "aws_glue_registry" "test" { `, rName) } -func testAccRegistryTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccRegistryConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_glue_registry" "test" { registry_name = %[1]q @@ -249,7 +249,7 @@ resource "aws_glue_registry" "test" { `, rName, tagKey1, tagValue1) } -func testAccRegistryTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccRegistryConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_glue_registry" "test" { registry_name = %[1]q diff --git a/internal/service/glue/resource_policy_test.go b/internal/service/glue/resource_policy_test.go index c6bec974a7d..26ba673ba49 100644 --- a/internal/service/glue/resource_policy_test.go +++ b/internal/service/glue/resource_policy_test.go @@ -24,7 +24,7 @@ func testAccResourcePolicy_basic(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyRequiredConfig("glue:CreateTable"), + Config: testAccResourcePolicyConfig_required("glue:CreateTable"), Check: resource.ComposeTestCheckFunc( testAccResourcePolicy(resourceName, "glue:CreateTable"), ), @@ -47,7 +47,7 @@ func testAccResourcePolicy_hybrid(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyHybridConfig("glue:CreateTable", "TRUE"), + Config: testAccResourcePolicyConfig_hybrid("glue:CreateTable", "TRUE"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "enable_hybrid", "TRUE"), ), @@ -59,13 +59,13 @@ func testAccResourcePolicy_hybrid(t *testing.T) { ImportStateVerifyIgnore: []string{"enable_hybrid"}, }, { - Config: testAccResourcePolicyHybridConfig("glue:CreateTable", "FALSE"), + Config: testAccResourcePolicyConfig_hybrid("glue:CreateTable", "FALSE"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "enable_hybrid", "FALSE"), ), }, { - Config: testAccResourcePolicyHybridConfig("glue:CreateTable", "TRUE"), + Config: testAccResourcePolicyConfig_hybrid("glue:CreateTable", "TRUE"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "enable_hybrid", "TRUE"), ), @@ -82,7 +82,7 @@ func testAccResourcePolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyRequiredConfig("glue:CreateTable"), + Config: testAccResourcePolicyConfig_required("glue:CreateTable"), Check: resource.ComposeTestCheckFunc( testAccResourcePolicy(resourceName, "glue:CreateTable"), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceResourcePolicy(), resourceName), @@ -103,13 +103,13 @@ func testAccResourcePolicy_update(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyRequiredConfig("glue:CreateTable"), + Config: testAccResourcePolicyConfig_required("glue:CreateTable"), Check: resource.ComposeTestCheckFunc( testAccResourcePolicy(resourceName, "glue:CreateTable"), ), }, { - Config: testAccResourcePolicyRequiredConfig("glue:DeleteTable"), + Config: testAccResourcePolicyConfig_required("glue:DeleteTable"), Check: resource.ComposeTestCheckFunc( testAccResourcePolicy(resourceName, "glue:DeleteTable"), ), @@ -133,13 +133,13 @@ func testAccResourcePolicy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyEquivalentConfig(), + Config: testAccResourcePolicyConfig_equivalent(), Check: resource.ComposeTestCheckFunc( testAccResourcePolicy(resourceName, "glue:CreateTable"), ), }, { - Config: testAccResourcePolicyEquivalent2Config(), + Config: testAccResourcePolicyConfig_equivalent2(), PlanOnly: true, }, }, @@ -216,7 +216,7 @@ func CreateTablePolicy(action string) string { }`, action, acctest.Partition(), acctest.Region(), acctest.AccountID()) } -func testAccResourcePolicyRequiredConfig(action string) string { +func testAccResourcePolicyConfig_required(action string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -241,7 +241,7 @@ resource "aws_glue_resource_policy" "test" { `, action) } -func testAccResourcePolicyHybridConfig(action, hybrid string) string { +func testAccResourcePolicyConfig_hybrid(action, hybrid string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -267,7 +267,7 @@ resource "aws_glue_resource_policy" "test" { `, action, hybrid) } -func testAccResourcePolicyEquivalentConfig() string { +func testAccResourcePolicyConfig_equivalent() string { return ` data "aws_caller_identity" "current" {} @@ -293,7 +293,7 @@ resource "aws_glue_resource_policy" "test" { ` } -func testAccResourcePolicyEquivalent2Config() string { +func testAccResourcePolicyConfig_equivalent2() string { return ` data "aws_caller_identity" "current" {} diff --git a/internal/service/glue/schema_test.go b/internal/service/glue/schema_test.go index 4ee29b2b1cf..50922468c8d 100644 --- a/internal/service/glue/schema_test.go +++ b/internal/service/glue/schema_test.go @@ -29,7 +29,7 @@ func TestAccGlueSchema_basic(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaBasicConfig(rName), + Config: testAccSchemaConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("schema/%s/%s", rName, rName)), @@ -68,7 +68,7 @@ func TestAccGlueSchema_json(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaJsonConfig(rName), + Config: testAccSchemaConfig_json(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "data_format", "JSON"), @@ -97,7 +97,7 @@ func TestAccGlueSchema_protobuf(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaProtobufConfig(rName), + Config: testAccSchemaConfig_protobuf(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "data_format", "PROTOBUF"), @@ -126,14 +126,14 @@ func TestAccGlueSchema_description(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaDescriptionConfig(rName, "First Description"), + Config: testAccSchemaConfig_description(rName, "First Description"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "description", "First Description"), ), }, { - Config: testAccSchemaDescriptionConfig(rName, "Second Description"), + Config: testAccSchemaConfig_description(rName, "Second Description"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "description", "Second Description"), @@ -161,14 +161,14 @@ func TestAccGlueSchema_compatibility(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaCompatibillityConfig(rName, "DISABLED"), + Config: testAccSchemaConfig_compatibility(rName, "DISABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "compatibility", "DISABLED"), ), }, { - Config: testAccSchemaCompatibillityConfig(rName, "FULL"), + Config: testAccSchemaConfig_compatibility(rName, "FULL"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "compatibility", "FULL"), @@ -195,7 +195,7 @@ func TestAccGlueSchema_tags(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaTags1Config(rName, "key1", "value1"), + Config: testAccSchemaConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -208,7 +208,7 @@ func TestAccGlueSchema_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSchemaTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccSchemaConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -217,7 +217,7 @@ func TestAccGlueSchema_tags(t *testing.T) { ), }, { - Config: testAccSchemaTags1Config(rName, "key2", "value2"), + Config: testAccSchemaConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -241,7 +241,7 @@ func TestAccGlueSchema_schemaDefUpdated(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaBasicConfig(rName), + Config: testAccSchemaConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "schema_definition", "{\"type\": \"record\", \"name\": \"r1\", \"fields\": [ {\"name\": \"f1\", \"type\": \"int\"}, {\"name\": \"f2\", \"type\": \"string\"} ]}"), @@ -250,7 +250,7 @@ func TestAccGlueSchema_schemaDefUpdated(t *testing.T) { ), }, { - Config: testAccSchemaSchemaDefinitionUpdatedConfig(rName), + Config: testAccSchemaConfig_definitionUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), resource.TestCheckResourceAttr(resourceName, "schema_definition", "{\"type\": \"record\", \"name\": \"r1\", \"fields\": [ {\"name\": \"f1\", \"type\": \"string\"}, {\"name\": \"f2\", \"type\": \"int\"} ]}"), @@ -280,7 +280,7 @@ func TestAccGlueSchema_disappears(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaBasicConfig(rName), + Config: testAccSchemaConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceSchema(), resourceName), @@ -304,7 +304,7 @@ func TestAccGlueSchema_Disappears_registry(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaBasicConfig(rName), + Config: testAccSchemaConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &schema), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceRegistry(), "aws_glue_registry.test"), @@ -393,7 +393,7 @@ resource "aws_glue_registry" "test" { `, rName) } -func testAccSchemaDescriptionConfig(rName, description string) string { +func testAccSchemaConfig_description(rName, description string) string { return testAccSchemaBase(rName) + fmt.Sprintf(` resource "aws_glue_schema" "test" { schema_name = %[1]q @@ -406,7 +406,7 @@ resource "aws_glue_schema" "test" { `, rName, description) } -func testAccSchemaCompatibillityConfig(rName, compat string) string { +func testAccSchemaConfig_compatibility(rName, compat string) string { return testAccSchemaBase(rName) + fmt.Sprintf(` resource "aws_glue_schema" "test" { schema_name = %[1]q @@ -418,7 +418,7 @@ resource "aws_glue_schema" "test" { `, rName, compat) } -func testAccSchemaBasicConfig(rName string) string { +func testAccSchemaConfig_basic(rName string) string { return testAccSchemaBase(rName) + fmt.Sprintf(` resource "aws_glue_schema" "test" { schema_name = %[1]q @@ -430,7 +430,7 @@ resource "aws_glue_schema" "test" { `, rName) } -func testAccSchemaJsonConfig(rName string) string { +func testAccSchemaConfig_json(rName string) string { return testAccSchemaBase(rName) + fmt.Sprintf(` resource "aws_glue_schema" "test" { schema_name = %[1]q @@ -442,7 +442,7 @@ resource "aws_glue_schema" "test" { `, rName) } -func testAccSchemaProtobufConfig(rName string) string { +func testAccSchemaConfig_protobuf(rName string) string { return testAccSchemaBase(rName) + fmt.Sprintf(` resource "aws_glue_schema" "test" { schema_name = %[1]q @@ -454,7 +454,7 @@ resource "aws_glue_schema" "test" { `, rName) } -func testAccSchemaTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccSchemaConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccSchemaBase(rName) + fmt.Sprintf(` resource "aws_glue_schema" "test" { schema_name = %[1]q @@ -470,7 +470,7 @@ resource "aws_glue_schema" "test" { `, rName, tagKey1, tagValue1) } -func testAccSchemaTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSchemaConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccSchemaBase(rName) + fmt.Sprintf(` resource "aws_glue_schema" "test" { schema_name = %[1]q @@ -487,7 +487,7 @@ resource "aws_glue_schema" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccSchemaSchemaDefinitionUpdatedConfig(rName string) string { +func testAccSchemaConfig_definitionUpdated(rName string) string { return testAccSchemaBase(rName) + fmt.Sprintf(` resource "aws_glue_schema" "test" { schema_name = %[1]q diff --git a/internal/service/glue/script_data_source_test.go b/internal/service/glue/script_data_source_test.go index 92eadc11832..d75e1acf0b6 100644 --- a/internal/service/glue/script_data_source_test.go +++ b/internal/service/glue/script_data_source_test.go @@ -18,7 +18,7 @@ func TestAccGlueScriptDataSource_Language_python(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccScriptPythonDataSourceConfig(), + Config: testAccScriptDataSourceConfig_python(), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "python_script", regexp.MustCompile(`from awsglue\.job import Job`)), ), @@ -36,7 +36,7 @@ func TestAccGlueScriptDataSource_Language_scala(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccScriptScalaDataSourceConfig(), + Config: testAccScriptDataSourceConfig_scala(), Check: resource.ComposeAggregateTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "scala_code", regexp.MustCompile(`import com\.amazonaws\.services\.glue\.util\.Job`)), ), @@ -45,7 +45,7 @@ func TestAccGlueScriptDataSource_Language_scala(t *testing.T) { }) } -func testAccScriptPythonDataSourceConfig() string { +func testAccScriptDataSourceConfig_python() string { return ` data "aws_glue_script" "test" { language = "PYTHON" @@ -143,7 +143,7 @@ data "aws_glue_script" "test" { ` } -func testAccScriptScalaDataSourceConfig() string { +func testAccScriptDataSourceConfig_scala() string { return ` data "aws_glue_script" "test" { language = "SCALA" diff --git a/internal/service/glue/security_configuration_test.go b/internal/service/glue/security_configuration_test.go index 7529bc0c1c5..80a642c83aa 100644 --- a/internal/service/glue/security_configuration_test.go +++ b/internal/service/glue/security_configuration_test.go @@ -27,7 +27,7 @@ func TestAccGlueSecurityConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckSecurityConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityConfigurationConfig_Basic(rName), + Config: testAccSecurityConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityConfigurationExists(resourceName, &securityConfiguration), resource.TestCheckResourceAttr(resourceName, "encryption_configuration.#", "1"), @@ -66,7 +66,7 @@ func TestAccGlueSecurityConfiguration_CloudWatchEncryptionCloudWatchEncryptionMo CheckDestroy: testAccCheckSecurityConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityConfigurationConfig_CloudWatchEncryption_CloudWatchEncryptionMode_SSEKMS(rName), + Config: testAccSecurityConfigurationConfig_cloudWatchEncryptionModeSSEKMS(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityConfigurationExists(resourceName, &securityConfiguration), resource.TestCheckResourceAttr(resourceName, "encryption_configuration.#", "1"), @@ -98,7 +98,7 @@ func TestAccGlueSecurityConfiguration_JobBookmarksEncryptionJobBookmarksEncrypti CheckDestroy: testAccCheckSecurityConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityConfigurationConfig_JobBookmarksEncryption_JobBookmarksEncryptionMode_CSEKMS(rName), + Config: testAccSecurityConfigurationConfig_jobBookmarksEncryptionModeCSEKMS(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityConfigurationExists(resourceName, &securityConfiguration), resource.TestCheckResourceAttr(resourceName, "encryption_configuration.#", "1"), @@ -130,7 +130,7 @@ func TestAccGlueSecurityConfiguration_S3EncryptionS3EncryptionMode_sseKMS(t *tes CheckDestroy: testAccCheckSecurityConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityConfigurationConfig_S3Encryption_S3EncryptionMode_SSEKMS(rName), + Config: testAccSecurityConfigurationConfig_s3EncryptionModeSSEKMS(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityConfigurationExists(resourceName, &securityConfiguration), resource.TestCheckResourceAttr(resourceName, "encryption_configuration.#", "1"), @@ -161,7 +161,7 @@ func TestAccGlueSecurityConfiguration_S3EncryptionS3EncryptionMode_sseS3(t *test CheckDestroy: testAccCheckSecurityConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityConfigurationConfig_S3Encryption_S3EncryptionMode_SSES3(rName), + Config: testAccSecurityConfigurationConfig_s3EncryptionModeSSES3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityConfigurationExists(resourceName, &securityConfiguration), resource.TestCheckResourceAttr(resourceName, "encryption_configuration.#", "1"), @@ -241,7 +241,7 @@ func testAccCheckSecurityConfigurationDestroy(s *terraform.State) error { return nil } -func testAccSecurityConfigurationConfig_Basic(rName string) string { +func testAccSecurityConfigurationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_glue_security_configuration" "test" { name = %q @@ -263,7 +263,7 @@ resource "aws_glue_security_configuration" "test" { `, rName) } -func testAccSecurityConfigurationConfig_CloudWatchEncryption_CloudWatchEncryptionMode_SSEKMS(rName string) string { +func testAccSecurityConfigurationConfig_cloudWatchEncryptionModeSSEKMS(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -290,7 +290,7 @@ resource "aws_glue_security_configuration" "test" { `, rName) } -func testAccSecurityConfigurationConfig_JobBookmarksEncryption_JobBookmarksEncryptionMode_CSEKMS(rName string) string { +func testAccSecurityConfigurationConfig_jobBookmarksEncryptionModeCSEKMS(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -317,7 +317,7 @@ resource "aws_glue_security_configuration" "test" { `, rName) } -func testAccSecurityConfigurationConfig_S3Encryption_S3EncryptionMode_SSEKMS(rName string) string { +func testAccSecurityConfigurationConfig_s3EncryptionModeSSEKMS(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -344,7 +344,7 @@ resource "aws_glue_security_configuration" "test" { `, rName) } -func testAccSecurityConfigurationConfig_S3Encryption_S3EncryptionMode_SSES3(rName string) string { +func testAccSecurityConfigurationConfig_s3EncryptionModeSSES3(rName string) string { return fmt.Sprintf(` resource "aws_glue_security_configuration" "test" { name = %q diff --git a/internal/service/glue/trigger_test.go b/internal/service/glue/trigger_test.go index 3a248c3af15..094bdf1b9b0 100644 --- a/internal/service/glue/trigger_test.go +++ b/internal/service/glue/trigger_test.go @@ -28,7 +28,7 @@ func TestAccGlueTrigger_basic(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_OnDemand(rName), + Config: testAccTriggerConfig_onDemand(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "actions.#", "1"), @@ -69,7 +69,7 @@ func TestAccGlueTrigger_crawler(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_Crawler(rName, "SUCCEEDED"), + Config: testAccTriggerConfig_crawler(rName, "SUCCEEDED"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "actions.#", "1"), @@ -82,7 +82,7 @@ func TestAccGlueTrigger_crawler(t *testing.T) { ), }, { - Config: testAccTriggerConfig_Crawler(rName, "FAILED"), + Config: testAccTriggerConfig_crawler(rName, "FAILED"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "actions.#", "1"), @@ -117,14 +117,14 @@ func TestAccGlueTrigger_description(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_Description(rName, "description1"), + Config: testAccTriggerConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "description", "description1"), ), }, { - Config: testAccTriggerConfig_Description(rName, "description2"), + Config: testAccTriggerConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -153,21 +153,21 @@ func TestAccGlueTrigger_enabled(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_Enabled(rName, true), + Config: testAccTriggerConfig_enabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), ), }, { - Config: testAccTriggerConfig_Enabled(rName, false), + Config: testAccTriggerConfig_enabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), ), }, { - Config: testAccTriggerConfig_Enabled(rName, true), + Config: testAccTriggerConfig_enabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), @@ -196,7 +196,7 @@ func TestAccGlueTrigger_predicate(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_Predicate(rName, "SUCCEEDED"), + Config: testAccTriggerConfig_predicate(rName, "SUCCEEDED"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "predicate.#", "1"), @@ -207,7 +207,7 @@ func TestAccGlueTrigger_predicate(t *testing.T) { ), }, { - Config: testAccTriggerConfig_Predicate(rName, "FAILED"), + Config: testAccTriggerConfig_predicate(rName, "FAILED"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "predicate.#", "1"), @@ -240,14 +240,14 @@ func TestAccGlueTrigger_schedule(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_Schedule(rName, "cron(1 2 * * ? *)"), + Config: testAccTriggerConfig_schedule(rName, "cron(1 2 * * ? *)"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "schedule", "cron(1 2 * * ? *)"), ), }, { - Config: testAccTriggerConfig_Schedule(rName, "cron(2 3 * * ? *)"), + Config: testAccTriggerConfig_schedule(rName, "cron(2 3 * * ? *)"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "schedule", "cron(2 3 * * ? *)"), @@ -276,7 +276,7 @@ func TestAccGlueTrigger_startOnCreate(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_ScheduleStart(rName, "cron(1 2 * * ? *)"), + Config: testAccTriggerConfig_scheduleStart(rName, "cron(1 2 * * ? *)"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "schedule", "cron(1 2 * * ? *)"), @@ -305,7 +305,7 @@ func TestAccGlueTrigger_tags(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerTags1Config(rName, "key1", "value1"), + Config: testAccTriggerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -319,7 +319,7 @@ func TestAccGlueTrigger_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"enabled"}, }, { - Config: testAccTriggerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTriggerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -328,7 +328,7 @@ func TestAccGlueTrigger_tags(t *testing.T) { ), }, { - Config: testAccTriggerTags1Config(rName, "key2", "value2"), + Config: testAccTriggerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -352,7 +352,7 @@ func TestAccGlueTrigger_workflowName(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_WorkflowName(rName), + Config: testAccTriggerConfig_workflowName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "workflow_name", rName), @@ -381,7 +381,7 @@ func TestAccGlueTrigger_Actions_notify(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerActionsNotificationConfig(rName, 1), + Config: testAccTriggerConfig_actionsNotification(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "actions.#", "1"), @@ -397,7 +397,7 @@ func TestAccGlueTrigger_Actions_notify(t *testing.T) { ImportStateVerifyIgnore: []string{"enabled"}, }, { - Config: testAccTriggerActionsNotificationConfig(rName, 2), + Config: testAccTriggerConfig_actionsNotification(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "actions.#", "1"), @@ -407,7 +407,7 @@ func TestAccGlueTrigger_Actions_notify(t *testing.T) { ), }, { - Config: testAccTriggerActionsNotificationConfig(rName, 1), + Config: testAccTriggerConfig_actionsNotification(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "actions.#", "1"), @@ -433,7 +433,7 @@ func TestAccGlueTrigger_Actions_security(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerActionsSecurityConfigurationConfig(rName), + Config: testAccTriggerConfig_actionsSecurityConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "actions.#", "1"), @@ -464,7 +464,7 @@ func TestAccGlueTrigger_onDemandDisable(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_OnDemand(rName), + Config: testAccTriggerConfig_onDemand(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), @@ -472,7 +472,7 @@ func TestAccGlueTrigger_onDemandDisable(t *testing.T) { ), }, { - Config: testAccTriggerConfig_OnDemandEnabled(rName, false), + Config: testAccTriggerConfig_onDemandEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -486,7 +486,7 @@ func TestAccGlueTrigger_onDemandDisable(t *testing.T) { ImportStateVerifyIgnore: []string{"enabled"}, }, { - Config: testAccTriggerConfig_OnDemandEnabled(rName, true), + Config: testAccTriggerConfig_onDemandEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), @@ -510,7 +510,7 @@ func TestAccGlueTrigger_eventBatchingCondition(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfigEvent(rName), + Config: testAccTriggerConfig_event(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "event_batching_condition.#", "1"), @@ -526,7 +526,7 @@ func TestAccGlueTrigger_eventBatchingCondition(t *testing.T) { ImportStateVerifyIgnore: []string{"enabled", "start_on_creation"}, }, { - Config: testAccTriggerConfigEventUpdated(rName), + Config: testAccTriggerConfig_eventUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), resource.TestCheckResourceAttr(resourceName, "event_batching_condition.#", "1"), @@ -552,7 +552,7 @@ func TestAccGlueTrigger_disappears(t *testing.T) { CheckDestroy: testAccCheckTriggerDestroy, Steps: []resource.TestStep{ { - Config: testAccTriggerConfig_OnDemand(rName), + Config: testAccTriggerConfig_onDemand(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTriggerExists(resourceName, &trigger), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceTrigger(), resourceName), @@ -622,8 +622,8 @@ func testAccCheckTriggerDestroy(s *terraform.State) error { return nil } -func testAccTriggerConfig_Description(rName, description string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_description(rName, description string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_trigger" "test" { description = %[1]q name = %[2]q @@ -636,8 +636,8 @@ resource "aws_glue_trigger" "test" { `, description, rName)) } -func testAccTriggerConfig_Enabled(rName string, enabled bool) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_enabled(rName string, enabled bool) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_trigger" "test" { enabled = %[1]t name = %[2]q @@ -651,8 +651,8 @@ resource "aws_glue_trigger" "test" { `, enabled, rName)) } -func testAccTriggerConfig_OnDemand(rName string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_onDemand(rName string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_trigger" "test" { name = %[1]q type = "ON_DEMAND" @@ -664,8 +664,8 @@ resource "aws_glue_trigger" "test" { `, rName)) } -func testAccTriggerConfig_OnDemandEnabled(rName string, enabled bool) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_onDemandEnabled(rName string, enabled bool) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_trigger" "test" { name = %[1]q type = "ON_DEMAND" @@ -678,8 +678,8 @@ resource "aws_glue_trigger" "test" { `, rName, enabled)) } -func testAccTriggerConfig_Predicate(rName, state string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_predicate(rName, state string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_job" "test2" { name = "%[1]s2" role_arn = aws_iam_role.test.arn @@ -709,7 +709,7 @@ resource "aws_glue_trigger" "test" { `, rName, state)) } -func testAccTriggerConfig_Crawler(rName, state string) string { +func testAccTriggerConfig_crawler(rName, state string) string { return acctest.ConfigCompose(testAccCrawlerConfig_s3Target(rName, "s3://test_bucket"), fmt.Sprintf(` resource "aws_glue_crawler" "test2" { depends_on = [aws_iam_role_policy_attachment.test-AWSGlueServiceRole] @@ -741,8 +741,8 @@ resource "aws_glue_trigger" "test_trigger" { `, rName, state)) } -func testAccTriggerConfig_Schedule(rName, schedule string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_schedule(rName, schedule string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_trigger" "test" { name = %[1]q schedule = %[2]q @@ -755,8 +755,8 @@ resource "aws_glue_trigger" "test" { `, rName, schedule)) } -func testAccTriggerConfig_ScheduleStart(rName, schedule string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_scheduleStart(rName, schedule string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_trigger" "test" { name = %[1]q schedule = %[2]q @@ -770,8 +770,8 @@ resource "aws_glue_trigger" "test" { `, rName, schedule)) } -func testAccTriggerTags1Config(rName, tagKey1, tagValue1 string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_tags1(rName, tagKey1, tagValue1 string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_trigger" "test" { name = %[1]q type = "ON_DEMAND" @@ -787,8 +787,8 @@ resource "aws_glue_trigger" "test" { `, rName, tagKey1, tagValue1)) } -func testAccTriggerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_trigger" "test" { name = %[1]q type = "ON_DEMAND" @@ -805,8 +805,8 @@ resource "aws_glue_trigger" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccTriggerConfig_WorkflowName(rName string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_workflowName(rName string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_workflow" test { name = %[1]q } @@ -823,8 +823,8 @@ resource "aws_glue_trigger" "test" { `, rName)) } -func testAccTriggerActionsNotificationConfig(rName string, delay int) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_actionsNotification(rName string, delay int) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_trigger" "test" { name = %[1]q type = "ON_DEMAND" @@ -840,8 +840,8 @@ resource "aws_glue_trigger" "test" { `, rName, delay)) } -func testAccTriggerActionsSecurityConfigurationConfig(rName string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_actionsSecurityConfiguration(rName string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_security_configuration" "test" { name = %[1]q @@ -872,8 +872,8 @@ resource "aws_glue_trigger" "test" { `, rName)) } -func testAccTriggerConfigEvent(rName string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_event(rName string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_workflow" test { name = %[1]q } @@ -895,8 +895,8 @@ resource "aws_glue_trigger" "test" { `, rName)) } -func testAccTriggerConfigEventUpdated(rName string) string { - return acctest.ConfigCompose(testAccJobConfig_Required(rName), fmt.Sprintf(` +func testAccTriggerConfig_eventUpdated(rName string) string { + return acctest.ConfigCompose(testAccJobConfig_required(rName), fmt.Sprintf(` resource "aws_glue_workflow" test { name = %[1]q } diff --git a/internal/service/glue/workflow_test.go b/internal/service/glue/workflow_test.go index 9e743ba5f00..26332fa4766 100644 --- a/internal/service/glue/workflow_test.go +++ b/internal/service/glue/workflow_test.go @@ -28,7 +28,7 @@ func TestAccGlueWorkflow_basic(t *testing.T) { CheckDestroy: testAccCheckWorkflowDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkflowConfig_Required(rName), + Config: testAccWorkflowConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "glue", fmt.Sprintf("workflow/%s", rName)), @@ -58,7 +58,7 @@ func TestAccGlueWorkflow_maxConcurrentRuns(t *testing.T) { CheckDestroy: testAccCheckWorkflowDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkflowMaxConcurrentRunsConfig(rName, 1), + Config: testAccWorkflowConfig_maxConcurrentRuns(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), resource.TestCheckResourceAttr(resourceName, "max_concurrent_runs", "1"), @@ -70,14 +70,14 @@ func TestAccGlueWorkflow_maxConcurrentRuns(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccWorkflowMaxConcurrentRunsConfig(rName, 2), + Config: testAccWorkflowConfig_maxConcurrentRuns(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), resource.TestCheckResourceAttr(resourceName, "max_concurrent_runs", "2"), ), }, { - Config: testAccWorkflowMaxConcurrentRunsConfig(rName, 1), + Config: testAccWorkflowConfig_maxConcurrentRuns(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), resource.TestCheckResourceAttr(resourceName, "max_concurrent_runs", "1"), @@ -100,7 +100,7 @@ func TestAccGlueWorkflow_defaultRunProperties(t *testing.T) { CheckDestroy: testAccCheckWorkflowDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkflowConfig_DefaultRunProperties(rName, "firstPropValue", "secondPropValue"), + Config: testAccWorkflowConfig_defaultRunProperties(rName, "firstPropValue", "secondPropValue"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), resource.TestCheckResourceAttr(resourceName, "default_run_properties.%", "2"), @@ -130,14 +130,14 @@ func TestAccGlueWorkflow_description(t *testing.T) { CheckDestroy: testAccCheckWorkflowDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkflowConfig_Description(rName, "First Description"), + Config: testAccWorkflowConfig_description(rName, "First Description"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), resource.TestCheckResourceAttr(resourceName, "description", "First Description"), ), }, { - Config: testAccWorkflowConfig_Description(rName, "Second Description"), + Config: testAccWorkflowConfig_description(rName, "Second Description"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), resource.TestCheckResourceAttr(resourceName, "description", "Second Description"), @@ -164,7 +164,7 @@ func TestAccGlueWorkflow_tags(t *testing.T) { CheckDestroy: testAccCheckWorkflowDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkflowTags1Config(rName, "key1", "value1"), + Config: testAccWorkflowConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -177,7 +177,7 @@ func TestAccGlueWorkflow_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccWorkflowTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccWorkflowConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -186,7 +186,7 @@ func TestAccGlueWorkflow_tags(t *testing.T) { ), }, { - Config: testAccWorkflowTags1Config(rName, "key2", "value2"), + Config: testAccWorkflowConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -210,7 +210,7 @@ func TestAccGlueWorkflow_disappears(t *testing.T) { CheckDestroy: testAccCheckWorkflowDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkflowConfig_Required(rName), + Config: testAccWorkflowConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkflowExists(resourceName, &workflow), acctest.CheckResourceDisappears(acctest.Provider, tfglue.ResourceWorkflow(), resourceName), @@ -299,7 +299,7 @@ func testAccCheckWorkflowDestroy(s *terraform.State) error { return nil } -func testAccWorkflowConfig_DefaultRunProperties(rName, firstPropValue, secondPropValue string) string { +func testAccWorkflowConfig_defaultRunProperties(rName, firstPropValue, secondPropValue string) string { return fmt.Sprintf(` resource "aws_glue_workflow" "test" { name = "%s" @@ -312,7 +312,7 @@ resource "aws_glue_workflow" "test" { `, rName, firstPropValue, secondPropValue) } -func testAccWorkflowConfig_Description(rName, description string) string { +func testAccWorkflowConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_glue_workflow" "test" { description = "%s" @@ -321,7 +321,7 @@ resource "aws_glue_workflow" "test" { `, description, rName) } -func testAccWorkflowConfig_Required(rName string) string { +func testAccWorkflowConfig_required(rName string) string { return fmt.Sprintf(` resource "aws_glue_workflow" "test" { name = "%s" @@ -329,7 +329,7 @@ resource "aws_glue_workflow" "test" { `, rName) } -func testAccWorkflowMaxConcurrentRunsConfig(rName string, runs int) string { +func testAccWorkflowConfig_maxConcurrentRuns(rName string, runs int) string { return fmt.Sprintf(` resource "aws_glue_workflow" "test" { name = %[1]q @@ -338,7 +338,7 @@ resource "aws_glue_workflow" "test" { `, rName, runs) } -func testAccWorkflowTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccWorkflowConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_glue_workflow" "test" { name = %[1]q @@ -350,7 +350,7 @@ resource "aws_glue_workflow" "test" { `, rName, tagKey1, tagValue1) } -func testAccWorkflowTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccWorkflowConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_glue_workflow" "test" { name = %[1]q diff --git a/internal/service/grafana/license_association_test.go b/internal/service/grafana/license_association_test.go index e0d073d76b1..a9cd3bdc081 100644 --- a/internal/service/grafana/license_association_test.go +++ b/internal/service/grafana/license_association_test.go @@ -26,7 +26,7 @@ func testAccLicenseAssociation_freeTrial(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLicenseAssociation(rName, managedgrafana.LicenseTypeEnterpriseFreeTrial), + Config: testAccLicenseAssociationConfig_basic(rName, managedgrafana.LicenseTypeEnterpriseFreeTrial), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLicenseAssociationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "free_trial_expiration"), @@ -38,8 +38,8 @@ func testAccLicenseAssociation_freeTrial(t *testing.T) { }) } -func testAccLicenseAssociation(rName string, licenseType string) string { - return acctest.ConfigCompose(testAccWorkspaceConfigAuthenticationProvider(rName, "SAML"), fmt.Sprintf(` +func testAccLicenseAssociationConfig_basic(rName string, licenseType string) string { + return acctest.ConfigCompose(testAccWorkspaceConfig_authenticationProvider(rName, "SAML"), fmt.Sprintf(` resource "aws_grafana_license_association" "test" { workspace_id = aws_grafana_workspace.test.id license_type = %[1]q diff --git a/internal/service/grafana/role_association_test.go b/internal/service/grafana/role_association_test.go index 4ccdf571a23..6fafd4fcfae 100644 --- a/internal/service/grafana/role_association_test.go +++ b/internal/service/grafana/role_association_test.go @@ -252,7 +252,7 @@ func testAccRoleAssociation_usersAndGroupsEditor(t *testing.T) { } func testAccRoleAssociationConfig_workspaceUsers(rName, role, userID string) string { - return acctest.ConfigCompose(testAccWorkspaceConfigAuthenticationProvider(rName, "AWS_SSO"), fmt.Sprintf(` + return acctest.ConfigCompose(testAccWorkspaceConfig_authenticationProvider(rName, "AWS_SSO"), fmt.Sprintf(` resource "aws_grafana_role_association" "test" { role = %[1]q user_ids = [%[2]q] @@ -262,7 +262,7 @@ resource "aws_grafana_role_association" "test" { } func testAccRoleAssociationConfig_workspaceGroups(rName, role, groupID string) string { - return acctest.ConfigCompose(testAccWorkspaceConfigAuthenticationProvider(rName, "AWS_SSO"), fmt.Sprintf(` + return acctest.ConfigCompose(testAccWorkspaceConfig_authenticationProvider(rName, "AWS_SSO"), fmt.Sprintf(` resource "aws_grafana_role_association" "test" { role = %[1]q group_ids = [%[2]q] @@ -272,7 +272,7 @@ resource "aws_grafana_role_association" "test" { } func testAccRoleAssociationConfig_workspaceUsersAndGroups(rName, role, userID, groupID string) string { - return acctest.ConfigCompose(testAccWorkspaceConfigAuthenticationProvider(rName, "AWS_SSO"), fmt.Sprintf(` + return acctest.ConfigCompose(testAccWorkspaceConfig_authenticationProvider(rName, "AWS_SSO"), fmt.Sprintf(` resource "aws_grafana_role_association" "test" { role = %[1]q user_ids = [%[2]q] diff --git a/internal/service/grafana/status.go b/internal/service/grafana/status.go index 37a6341eb2e..6836fc500d0 100644 --- a/internal/service/grafana/status.go +++ b/internal/service/grafana/status.go @@ -23,7 +23,7 @@ func statusWorkspaceStatus(conn *managedgrafana.ManagedGrafana, id string) resou } } -func statusWorkspaceSamlConfiguration(conn *managedgrafana.ManagedGrafana, id string) resource.StateRefreshFunc { +func statusWorkspaceSAMLConfiguration(conn *managedgrafana.ManagedGrafana, id string) resource.StateRefreshFunc { return func() (interface{}, string, error) { output, err := FindSamlConfigurationByID(conn, id) diff --git a/internal/service/grafana/wait.go b/internal/service/grafana/wait.go index e93ebef4c4c..c5f21397dbd 100644 --- a/internal/service/grafana/wait.go +++ b/internal/service/grafana/wait.go @@ -75,11 +75,11 @@ func waitLicenseAssociationCreated(conn *managedgrafana.ManagedGrafana, id strin return nil, err } -func waitWorkspaceSamlConfigurationCreated(conn *managedgrafana.ManagedGrafana, id string, timeout time.Duration) (*managedgrafana.SamlAuthentication, error) { +func waitWorkspaceSAMLConfigurationCreated(conn *managedgrafana.ManagedGrafana, id string, timeout time.Duration) (*managedgrafana.SamlAuthentication, error) { stateConf := &resource.StateChangeConf{ Pending: []string{managedgrafana.SamlConfigurationStatusNotConfigured}, Target: []string{managedgrafana.SamlConfigurationStatusConfigured}, - Refresh: statusWorkspaceSamlConfiguration(conn, id), + Refresh: statusWorkspaceSAMLConfiguration(conn, id), Timeout: timeout, } diff --git a/internal/service/grafana/workspace_data_source_test.go b/internal/service/grafana/workspace_data_source_test.go index 5d4f69a3616..361bc91b821 100644 --- a/internal/service/grafana/workspace_data_source_test.go +++ b/internal/service/grafana/workspace_data_source_test.go @@ -21,7 +21,7 @@ func testAccWorkspaceDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceDataSourceConfig(rName), + Config: testAccWorkspaceDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkspaceExists(dataSourceName), resource.TestCheckResourceAttrPair(resourceName, "account_access_type", dataSourceName, "account_access_type"), @@ -49,8 +49,8 @@ func testAccWorkspaceDataSource_basic(t *testing.T) { }) } -func testAccWorkspaceDataSourceConfig(rName string) string { - return acctest.ConfigCompose(testAccWorkspaceConfigAuthenticationProvider(rName, "SAML"), ` +func testAccWorkspaceDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccWorkspaceConfig_authenticationProvider(rName, "SAML"), ` data "aws_grafana_workspace" "test" { workspace_id = aws_grafana_workspace.test.id } diff --git a/internal/service/grafana/workspace_saml_configuration.go b/internal/service/grafana/workspace_saml_configuration.go index bb82ef964c9..d45e2364bc7 100644 --- a/internal/service/grafana/workspace_saml_configuration.go +++ b/internal/service/grafana/workspace_saml_configuration.go @@ -13,11 +13,11 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func ResourceWorkspaceSamlConfiguration() *schema.Resource { +func ResourceWorkspaceSAMLConfiguration() *schema.Resource { return &schema.Resource{ - Create: resourceWorkspaceSamlConfigurationUpsert, - Read: resourceWorkspaceSamlConfigurationRead, - Update: resourceWorkspaceSamlConfigurationUpsert, + Create: resourceWorkspaceSAMLConfigurationUpsert, + Read: resourceWorkspaceSAMLConfigurationRead, + Update: resourceWorkspaceSAMLConfigurationUpsert, Delete: schema.Noop, Importer: &schema.ResourceImporter{ @@ -98,7 +98,7 @@ func ResourceWorkspaceSamlConfiguration() *schema.Resource { } } -func resourceWorkspaceSamlConfigurationUpsert(d *schema.ResourceData, meta interface{}) error { +func resourceWorkspaceSAMLConfigurationUpsert(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GrafanaConn d.SetId(d.Get("workspace_id").(string)) @@ -209,14 +209,14 @@ func resourceWorkspaceSamlConfigurationUpsert(d *schema.ResourceData, meta inter return fmt.Errorf("error creating Grafana Saml Configuration: %w", err) } - if _, err := waitWorkspaceSamlConfigurationCreated(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + if _, err := waitWorkspaceSAMLConfigurationCreated(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return fmt.Errorf("error waiting for Grafana Workspace Saml Configuration (%s) create: %w", d.Id(), err) } - return resourceWorkspaceSamlConfigurationRead(d, meta) + return resourceWorkspaceSAMLConfigurationRead(d, meta) } -func resourceWorkspaceSamlConfigurationRead(d *schema.ResourceData, meta interface{}) error { +func resourceWorkspaceSAMLConfigurationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GrafanaConn saml, err := FindSamlConfigurationByID(conn, d.Id()) diff --git a/internal/service/grafana/workspace_saml_configuration_test.go b/internal/service/grafana/workspace_saml_configuration_test.go index 2458e202ebf..e2ec20e7af6 100644 --- a/internal/service/grafana/workspace_saml_configuration_test.go +++ b/internal/service/grafana/workspace_saml_configuration_test.go @@ -13,7 +13,7 @@ import ( tfgrafana "github.com/hashicorp/terraform-provider-aws/internal/service/grafana" ) -func testAccWorkspaceSamlConfiguration_basic(t *testing.T) { +func testAccWorkspaceSAMLConfiguration_basic(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_grafana_workspace_saml_configuration.test" workspaceResourceName := "aws_grafana_workspace.test" @@ -25,9 +25,9 @@ func testAccWorkspaceSamlConfiguration_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceSamlConfigurationConfigProvider_basic(rName), + Config: testAccWorkspaceSAMLConfigurationConfig_providerBasic(rName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckWorkspaceSamlConfigurationExists(resourceName), + testAccCheckWorkspaceSAMLConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "admin_role_values.#", "1"), resource.TestCheckResourceAttr(resourceName, "admin_role_values.0", "admin"), resource.TestCheckResourceAttr(resourceName, "editor_role_values.#", "1"), @@ -41,7 +41,7 @@ func testAccWorkspaceSamlConfiguration_basic(t *testing.T) { }) } -func testAccWorkspaceSamlConfiguration_loginValidity(t *testing.T) { +func testAccWorkspaceSAMLConfiguration_loginValidity(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_grafana_workspace_saml_configuration.test" workspaceResourceName := "aws_grafana_workspace.test" @@ -53,9 +53,9 @@ func testAccWorkspaceSamlConfiguration_loginValidity(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceSamlConfigurationConfigProvider_loginValidity(rName), + Config: testAccWorkspaceSAMLConfigurationConfig_providerLoginValidity(rName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckWorkspaceSamlConfigurationExists(resourceName), + testAccCheckWorkspaceSAMLConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "admin_role_values.#", "1"), resource.TestCheckResourceAttr(resourceName, "admin_role_values.0", "admin"), resource.TestCheckResourceAttr(resourceName, "editor_role_values.#", "1"), @@ -70,7 +70,7 @@ func testAccWorkspaceSamlConfiguration_loginValidity(t *testing.T) { }) } -func testAccWorkspaceSamlConfiguration_assertions(t *testing.T) { +func testAccWorkspaceSAMLConfiguration_assertions(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_grafana_workspace_saml_configuration.test" workspaceResourceName := "aws_grafana_workspace.test" @@ -82,9 +82,9 @@ func testAccWorkspaceSamlConfiguration_assertions(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceSamlConfigurationConfigProvider_assertions(rName), + Config: testAccWorkspaceSAMLConfigurationConfig_providerAssertions(rName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckWorkspaceSamlConfigurationExists(resourceName), + testAccCheckWorkspaceSAMLConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "admin_role_values.#", "1"), resource.TestCheckResourceAttr(resourceName, "admin_role_values.0", "admin"), resource.TestCheckResourceAttr(resourceName, "editor_role_values.#", "1"), @@ -105,8 +105,8 @@ func testAccWorkspaceSamlConfiguration_assertions(t *testing.T) { }) } -func testAccWorkspaceSamlConfigurationConfigProvider_basic(rName string) string { - return acctest.ConfigCompose(testAccWorkspaceConfigAuthenticationProvider(rName, "SAML"), ` +func testAccWorkspaceSAMLConfigurationConfig_providerBasic(rName string) string { + return acctest.ConfigCompose(testAccWorkspaceConfig_authenticationProvider(rName, "SAML"), ` resource "aws_grafana_workspace_saml_configuration" "test" { admin_role_values = ["admin"] editor_role_values = ["editor"] @@ -116,8 +116,8 @@ resource "aws_grafana_workspace_saml_configuration" "test" { `) } -func testAccWorkspaceSamlConfigurationConfigProvider_loginValidity(rName string) string { - return acctest.ConfigCompose(testAccWorkspaceConfigAuthenticationProvider(rName, "SAML"), ` +func testAccWorkspaceSAMLConfigurationConfig_providerLoginValidity(rName string) string { + return acctest.ConfigCompose(testAccWorkspaceConfig_authenticationProvider(rName, "SAML"), ` resource "aws_grafana_workspace_saml_configuration" "test" { admin_role_values = ["admin"] editor_role_values = ["editor"] @@ -128,8 +128,8 @@ resource "aws_grafana_workspace_saml_configuration" "test" { `) } -func testAccWorkspaceSamlConfigurationConfigProvider_assertions(rName string) string { - return acctest.ConfigCompose(testAccWorkspaceConfigAuthenticationProvider(rName, "SAML"), ` +func testAccWorkspaceSAMLConfigurationConfig_providerAssertions(rName string) string { + return acctest.ConfigCompose(testAccWorkspaceConfig_authenticationProvider(rName, "SAML"), ` resource "aws_grafana_workspace_saml_configuration" "test" { admin_role_values = ["admin"] editor_role_values = ["editor"] @@ -145,7 +145,7 @@ resource "aws_grafana_workspace_saml_configuration" "test" { `) } -func testAccCheckWorkspaceSamlConfigurationExists(name string) resource.TestCheckFunc { +func testAccCheckWorkspaceSAMLConfigurationExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { diff --git a/internal/service/grafana/workspace_test.go b/internal/service/grafana/workspace_test.go index 921f28f454d..4bac188a516 100644 --- a/internal/service/grafana/workspace_test.go +++ b/internal/service/grafana/workspace_test.go @@ -34,9 +34,9 @@ func TestAccGrafana_serial(t *testing.T) { "enterpriseFreeTrial": testAccLicenseAssociation_freeTrial, }, "SamlConfiguration": { - "basic": testAccWorkspaceSamlConfiguration_basic, - "loginValidity": testAccWorkspaceSamlConfiguration_loginValidity, - "assertions": testAccWorkspaceSamlConfiguration_assertions, + "basic": testAccWorkspaceSAMLConfiguration_basic, + "loginValidity": testAccWorkspaceSAMLConfiguration_loginValidity, + "assertions": testAccWorkspaceSAMLConfiguration_assertions, }, "RoleAssociation": { "usersAdmin": testAccRoleAssociation_usersAdmin, @@ -73,7 +73,7 @@ func testAccWorkspace_saml(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceConfigAuthenticationProvider(rName, "SAML"), + Config: testAccWorkspaceConfig_authenticationProvider(rName, "SAML"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWorkspaceExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "grafana", regexp.MustCompile(`/workspaces/.+`)), @@ -120,7 +120,7 @@ func testAccWorkspace_sso(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceConfigAuthenticationProvider(rName, "AWS_SSO"), + Config: testAccWorkspaceConfig_authenticationProvider(rName, "AWS_SSO"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWorkspaceExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "grafana", regexp.MustCompile(`/workspaces/.+`)), @@ -162,7 +162,7 @@ func testAccWorkspace_disappears(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceConfigAuthenticationProvider(rName, "SAML"), + Config: testAccWorkspaceConfig_authenticationProvider(rName, "SAML"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWorkspaceExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfgrafana.ResourceWorkspace(), resourceName), @@ -189,7 +189,7 @@ func testAccWorkspace_organization(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceConfigOrganization(rName), + Config: testAccWorkspaceConfig_organization(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "account_access_type", managedgrafana.AccountAccessTypeOrganization), @@ -219,7 +219,7 @@ func testAccWorkspace_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceConfigTags1(rName, "key1", "value1"), + Config: testAccWorkspaceConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -232,7 +232,7 @@ func testAccWorkspace_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccWorkspaceConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccWorkspaceConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -241,7 +241,7 @@ func testAccWorkspace_tags(t *testing.T) { ), }, { - Config: testAccWorkspaceConfigTags1(rName, "key2", "value2"), + Config: testAccWorkspaceConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -264,7 +264,7 @@ func testAccWorkspace_dataSources(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceConfigDataSources(rName), + Config: testAccWorkspaceConfig_dataSources(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWorkspaceExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "grafana", regexp.MustCompile(`/workspaces/.+`)), @@ -308,7 +308,7 @@ func testAccWorkspace_permissionType(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceConfigPermissionType(rName, "CUSTOMER_MANAGED"), + Config: testAccWorkspaceConfig_permissionType(rName, "CUSTOMER_MANAGED"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "permission_type", managedgrafana.PermissionTypeCustomerManaged), @@ -320,7 +320,7 @@ func testAccWorkspace_permissionType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccWorkspaceConfigPermissionType(rName, "SERVICE_MANAGED"), + Config: testAccWorkspaceConfig_permissionType(rName, "SERVICE_MANAGED"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "permission_type", managedgrafana.PermissionTypeServiceManaged), @@ -341,7 +341,7 @@ func testAccWorkspace_notificationDestinations(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkspaceConfigAuthenticationProvider(rName, "SAML"), + Config: testAccWorkspaceConfig_authenticationProvider(rName, "SAML"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWorkspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -350,7 +350,7 @@ func testAccWorkspace_notificationDestinations(t *testing.T) { ), }, { - Config: testAccWorkspaceConfigNotificationDestinations(rName), + Config: testAccWorkspaceConfig_notificationDestinations(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -390,7 +390,7 @@ resource "aws_iam_role" "test" { `, rName) } -func testAccWorkspaceConfigAuthenticationProvider(rName, authenticationProvider string) string { +func testAccWorkspaceConfig_authenticationProvider(rName, authenticationProvider string) string { return acctest.ConfigCompose(testAccWorkspaceRole(rName), fmt.Sprintf(` resource "aws_grafana_workspace" "test" { account_access_type = "CURRENT_ACCOUNT" @@ -401,7 +401,7 @@ resource "aws_grafana_workspace" "test" { `, authenticationProvider)) } -func testAccWorkspaceConfigOrganization(rName string) string { +func testAccWorkspaceConfig_organization(rName string) string { return acctest.ConfigCompose(testAccWorkspaceRole(rName), fmt.Sprintf(` resource "aws_grafana_workspace" "test" { account_access_type = "ORGANIZATION" @@ -420,7 +420,7 @@ resource "aws_organizations_organizational_unit" "test" { `, rName)) } -func testAccWorkspaceConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccWorkspaceConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccWorkspaceRole(rName), fmt.Sprintf(` resource "aws_grafana_workspace" "test" { account_access_type = "CURRENT_ACCOUNT" @@ -437,7 +437,7 @@ resource "aws_grafana_workspace" "test" { `, rName, tagKey1, tagValue1)) } -func testAccWorkspaceConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccWorkspaceConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccWorkspaceRole(rName), fmt.Sprintf(` resource "aws_grafana_workspace" "test" { account_access_type = "CURRENT_ACCOUNT" @@ -455,7 +455,7 @@ resource "aws_grafana_workspace" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccWorkspaceConfigDataSources(rName string) string { +func testAccWorkspaceConfig_dataSources(rName string) string { return acctest.ConfigCompose(testAccWorkspaceRole(rName), fmt.Sprintf(` resource "aws_grafana_workspace" "test" { account_access_type = "CURRENT_ACCOUNT" @@ -469,7 +469,7 @@ resource "aws_grafana_workspace" "test" { `, rName)) } -func testAccWorkspaceConfigPermissionType(rName, permissionType string) string { +func testAccWorkspaceConfig_permissionType(rName, permissionType string) string { return acctest.ConfigCompose(testAccWorkspaceRole(rName), fmt.Sprintf(` resource "aws_grafana_workspace" "test" { account_access_type = "CURRENT_ACCOUNT" @@ -480,7 +480,7 @@ resource "aws_grafana_workspace" "test" { `, permissionType)) } -func testAccWorkspaceConfigNotificationDestinations(rName string) string { +func testAccWorkspaceConfig_notificationDestinations(rName string) string { return acctest.ConfigCompose(testAccWorkspaceRole(rName), fmt.Sprintf(` resource "aws_grafana_workspace" "test" { account_access_type = "CURRENT_ACCOUNT" diff --git a/internal/service/guardduty/detector.go b/internal/service/guardduty/detector.go index f893283f9e0..57a82afb505 100644 --- a/internal/service/guardduty/detector.go +++ b/internal/service/guardduty/detector.go @@ -59,6 +59,29 @@ func ResourceDetector() *schema.Resource { }, }, }, + "kubernetes": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "audit_logs": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enable": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + }, + }, + }, + }, }, }, }, @@ -109,7 +132,7 @@ func resourceDetectorCreate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Creating GuardDuty Detector: %s", input) output, err := conn.CreateDetector(&input) if err != nil { - return fmt.Errorf("Creating GuardDuty Detector failed: %s", err.Error()) + return fmt.Errorf("Creating GuardDuty Detector failed: %w", err) } d.SetId(aws.StringValue(output.DetectorId)) @@ -133,7 +156,7 @@ func resourceDetectorRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return fmt.Errorf("Reading GuardDuty Detector '%s' failed: %s", d.Id(), err.Error()) + return fmt.Errorf("Reading GuardDuty Detector '%s' failed: %w", d.Id(), err) } arn := arn.ARN{ @@ -189,7 +212,7 @@ func resourceDetectorUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Update GuardDuty Detector: %s", input) _, err := conn.UpdateDetector(&input) if err != nil { - return fmt.Errorf("Updating GuardDuty Detector '%s' failed: %s", d.Id(), err.Error()) + return fmt.Errorf("Updating GuardDuty Detector '%s' failed: %w", d.Id(), err) } } @@ -197,7 +220,7 @@ func resourceDetectorUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating GuardDuty Detector (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("error updating GuardDuty Detector (%s) tags: %w", d.Get("arn").(string), err) } } @@ -246,6 +269,9 @@ func expandDataSourceConfigurations(tfMap map[string]interface{}) *guardduty.Dat if v, ok := tfMap["s3_logs"].([]interface{}); ok && len(v) > 0 { apiObject.S3Logs = expandS3LogsConfiguration(v[0].(map[string]interface{})) } + if v, ok := tfMap["kubernetes"].([]interface{}); ok && len(v) > 0 { + apiObject.Kubernetes = expandKubernetesConfiguration(v[0].(map[string]interface{})) + } return apiObject } @@ -264,6 +290,40 @@ func expandS3LogsConfiguration(tfMap map[string]interface{}) *guardduty.S3LogsCo return apiObject } +func expandKubernetesConfiguration(tfMap map[string]interface{}) *guardduty.KubernetesConfiguration { + if tfMap == nil { + return nil + } + + l, ok := tfMap["audit_logs"].([]interface{}) + if !ok || len(l) == 0 { + return nil + } + + m, ok := l[0].(map[string]interface{}) + if !ok { + return nil + } + + return &guardduty.KubernetesConfiguration{ + AuditLogs: expandKubernetesAuditLogsConfiguration(m), + } +} + +func expandKubernetesAuditLogsConfiguration(tfMap map[string]interface{}) *guardduty.KubernetesAuditLogsConfiguration { + if tfMap == nil { + return nil + } + + apiObject := &guardduty.KubernetesAuditLogsConfiguration{} + + if v, ok := tfMap["enable"].(bool); ok { + apiObject.Enable = aws.Bool(v) + } + + return apiObject +} + func flattenDataSourceConfigurationsResult(apiObject *guardduty.DataSourceConfigurationsResult) map[string]interface{} { if apiObject == nil { return nil @@ -275,6 +335,10 @@ func flattenDataSourceConfigurationsResult(apiObject *guardduty.DataSourceConfig tfMap["s3_logs"] = []interface{}{flattenS3LogsConfigurationResult(v)} } + if v := apiObject.Kubernetes; v != nil { + tfMap["kubernetes"] = []interface{}{flattenKubernetesConfiguration(v)} + } + return tfMap } @@ -291,3 +355,31 @@ func flattenS3LogsConfigurationResult(apiObject *guardduty.S3LogsConfigurationRe return tfMap } + +func flattenKubernetesConfiguration(apiObject *guardduty.KubernetesConfigurationResult) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.AuditLogs; v != nil { + tfMap["audit_logs"] = []interface{}{flattenKubernetesAuditLogsConfiguration(v)} + } + + return tfMap +} + +func flattenKubernetesAuditLogsConfiguration(apiObject *guardduty.KubernetesAuditLogsConfigurationResult) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.Status; v != nil { + tfMap["enable"] = aws.StringValue(v) == guardduty.DataSourceStatusEnabled + } + + return tfMap +} diff --git a/internal/service/guardduty/detector_data_source_test.go b/internal/service/guardduty/detector_data_source_test.go index 797d7abea90..1c39bdc0891 100644 --- a/internal/service/guardduty/detector_data_source_test.go +++ b/internal/service/guardduty/detector_data_source_test.go @@ -16,11 +16,11 @@ func testAccDetectorDataSource_basic(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccDetectorBasicResourceConfig(), + Config: testAccDetectorDataSourceConfig_basicResource(), Check: resource.ComposeTestCheckFunc(), }, { - Config: testAccDetectorBasicResourceDataConfig(), + Config: testAccDetectorDataSourceConfig_basicResource2(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair("data.aws_guardduty_detector.test", "id", "aws_guardduty_detector.test", "id"), resource.TestCheckResourceAttr("data.aws_guardduty_detector.test", "status", "ENABLED"), @@ -39,7 +39,7 @@ func testAccDetectorDataSource_ID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDetectorExplicitConfig(), + Config: testAccDetectorDataSourceConfig_explicit(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair("data.aws_guardduty_detector.test", "id", "aws_guardduty_detector.test", "id"), resource.TestCheckResourceAttr("data.aws_guardduty_detector.test", "status", "ENABLED"), @@ -51,13 +51,13 @@ func testAccDetectorDataSource_ID(t *testing.T) { }) } -func testAccDetectorBasicResourceConfig() string { +func testAccDetectorDataSourceConfig_basicResource() string { return ` resource "aws_guardduty_detector" "test" {} ` } -func testAccDetectorBasicResourceDataConfig() string { +func testAccDetectorDataSourceConfig_basicResource2() string { return ` resource "aws_guardduty_detector" "test" {} @@ -65,7 +65,7 @@ data "aws_guardduty_detector" "test" {} ` } -func testAccDetectorExplicitConfig() string { +func testAccDetectorDataSourceConfig_explicit() string { return ` resource "aws_guardduty_detector" "test" {} diff --git a/internal/service/guardduty/detector_test.go b/internal/service/guardduty/detector_test.go index 94f078cc150..b01b376b94b 100644 --- a/internal/service/guardduty/detector_test.go +++ b/internal/service/guardduty/detector_test.go @@ -24,12 +24,15 @@ func testAccDetector_basic(t *testing.T) { CheckDestroy: testAccCheckDetectorDestroy, Steps: []resource.TestStep{ { - Config: testAccDetectorConfig_basic1, - Check: resource.ComposeTestCheckFunc( + Config: testAccDetectorConfig_basic, + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDetectorExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "account_id"), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "guardduty", regexp.MustCompile("detector/.+$")), resource.TestCheckResourceAttr(resourceName, "enable", "true"), + resource.TestCheckResourceAttr(resourceName, "datasources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.0.enable", "true"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.0.enable", "true"), resource.TestCheckResourceAttr(resourceName, "finding_publishing_frequency", "SIX_HOURS"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), @@ -40,22 +43,22 @@ func testAccDetector_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDetectorConfig_basic2, - Check: resource.ComposeTestCheckFunc( + Config: testAccDetectorConfig_disable, + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDetectorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enable", "false"), ), }, { - Config: testAccDetectorConfig_basic3, - Check: resource.ComposeTestCheckFunc( + Config: testAccDetectorConfig_enable, + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDetectorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enable", "true"), ), }, { - Config: testAccDetectorConfig_basic4, - Check: resource.ComposeTestCheckFunc( + Config: testAccDetectorConfig_findingPublishingFrequency, + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDetectorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "finding_publishing_frequency", "FIFTEEN_MINUTES"), ), @@ -75,7 +78,7 @@ func testAccDetector_tags(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccDetectorConfig_tags1("key1", "value1"), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDetectorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), @@ -88,7 +91,7 @@ func testAccDetector_tags(t *testing.T) { }, { Config: testAccDetectorConfig_tags2("key1", "value1updated", "key2", "value2"), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDetectorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), @@ -97,7 +100,7 @@ func testAccDetector_tags(t *testing.T) { }, { Config: testAccDetectorConfig_tags1("key2", "value2"), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDetectorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), @@ -118,7 +121,7 @@ func testAccDetector_datasources_s3logs(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccDetectorConfig_datasourcesS3Logs(true), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDetectorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "datasources.#", "1"), resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.#", "1"), @@ -132,13 +135,111 @@ func testAccDetector_datasources_s3logs(t *testing.T) { }, { Config: testAccDetectorConfig_datasourcesS3Logs(false), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckDetectorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "datasources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.0.enable", "false"), + ), + }, + }, + }) +} + +func testAccDetector_datasources_kubernetes_audit_logs(t *testing.T) { + resourceName := "aws_guardduty_detector.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, guardduty.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckDetectorDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDetectorConfig_datasourcesKubernetesAuditLogs(true), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckDetectorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "datasources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.0.enable", "true"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccDetectorConfig_datasourcesKubernetesAuditLogs(false), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckDetectorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "datasources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.0.enable", "false"), + ), + }, + }, + }) +} + +func testAccDetector_datasources_all(t *testing.T) { + resourceName := "aws_guardduty_detector.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, guardduty.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckDetectorDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDetectorConfig_datasourcesAll(true, false), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckDetectorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "datasources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.0.enable", "true"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.0.enable", "false"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccDetectorConfig_datasourcesAll(true, true), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckDetectorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "datasources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.0.enable", "true"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.0.enable", "true"), + ), + }, + { + Config: testAccDetectorConfig_datasourcesAll(false, false), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDetectorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "datasources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.0.enable", "false"), resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.#", "1"), resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.0.enable", "false"), ), }, + { + Config: testAccDetectorConfig_datasourcesAll(false, true), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckDetectorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "datasources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.kubernetes.0.audit_logs.0.enable", "false"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "datasources.0.s3_logs.0.enable", "true"), + ), + }, }, }) } @@ -171,32 +272,50 @@ func testAccCheckDetectorDestroy(s *terraform.State) error { func testAccCheckDetectorExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { - _, ok := s.RootModule().Resources[name] + rs, ok := s.RootModule().Resources[name] if !ok { return fmt.Errorf("Not found: %s", name) } + if rs.Primary.ID == "" { + return fmt.Errorf("Resource (%s) has empty ID", name) + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn + + output, err := conn.GetDetector(&guardduty.GetDetectorInput{ + DetectorId: aws.String(rs.Primary.ID), + }) + + if err != nil { + return err + } + + if output == nil { + return fmt.Errorf("GuardDuty Detector not found: %s", name) + } + return nil } } -const testAccDetectorConfig_basic1 = ` +const testAccDetectorConfig_basic = ` resource "aws_guardduty_detector" "test" {} ` -const testAccDetectorConfig_basic2 = ` +const testAccDetectorConfig_disable = ` resource "aws_guardduty_detector" "test" { enable = false } ` -const testAccDetectorConfig_basic3 = ` +const testAccDetectorConfig_enable = ` resource "aws_guardduty_detector" "test" { enable = true } ` -const testAccDetectorConfig_basic4 = ` +const testAccDetectorConfig_findingPublishingFrequency = ` resource "aws_guardduty_detector" "test" { finding_publishing_frequency = "FIFTEEN_MINUTES" } @@ -234,3 +353,34 @@ resource "aws_guardduty_detector" "test" { } `, enable) } + +func testAccDetectorConfig_datasourcesKubernetesAuditLogs(enable bool) string { + return fmt.Sprintf(` +resource "aws_guardduty_detector" "test" { + datasources { + kubernetes { + audit_logs { + enable = %[1]t + } + } + } +} +`, enable) +} + +func testAccDetectorConfig_datasourcesAll(enableK8s, enableS3 bool) string { + return fmt.Sprintf(` +resource "aws_guardduty_detector" "test" { + datasources { + kubernetes { + audit_logs { + enable = %[1]t + } + } + s3_logs { + enable = %[2]t + } + } +} +`, enableK8s, enableS3) +} diff --git a/internal/service/guardduty/guardduty_test.go b/internal/service/guardduty/guardduty_test.go index 95f1f646367..6c4317d839d 100644 --- a/internal/service/guardduty/guardduty_test.go +++ b/internal/service/guardduty/guardduty_test.go @@ -8,11 +8,13 @@ import ( func TestAccGuardDuty_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Detector": { - "basic": testAccDetector_basic, - "datasources_s3logs": testAccDetector_datasources_s3logs, - "tags": testAccDetector_tags, - "datasource_basic": testAccDetectorDataSource_basic, - "datasource_id": testAccDetectorDataSource_ID, + "basic": testAccDetector_basic, + "datasources_s3logs": testAccDetector_datasources_s3logs, + "datasources_kubernetes_audit_logs": testAccDetector_datasources_kubernetes_audit_logs, + "datasources_all": testAccDetector_datasources_all, + "tags": testAccDetector_tags, + "datasource_basic": testAccDetectorDataSource_basic, + "datasource_id": testAccDetectorDataSource_ID, }, "Filter": { "basic": testAccFilter_basic, diff --git a/internal/service/guardduty/member_test.go b/internal/service/guardduty/member_test.go index abe977738a6..c527b3d0c8d 100644 --- a/internal/service/guardduty/member_test.go +++ b/internal/service/guardduty/member_test.go @@ -234,7 +234,7 @@ resource "aws_guardduty_member" "test" { detector_id = aws_guardduty_detector.test.id email = "%[3]s" } -`, testAccDetectorConfig_basic1, accountID, email) +`, testAccDetectorConfig_basic, accountID, email) } func testAccMemberConfig_invite(accountID, email string, invite bool) string { @@ -248,7 +248,7 @@ resource "aws_guardduty_member" "test" { email = "%[3]s" invite = %[4]t } -`, testAccDetectorConfig_basic1, accountID, email, invite) +`, testAccDetectorConfig_basic, accountID, email, invite) } func testAccMemberConfig_invitationMessage(accountID, email, invitationMessage string) string { @@ -263,5 +263,5 @@ resource "aws_guardduty_member" "test" { invitation_message = "%[4]s" invite = true } -`, testAccDetectorConfig_basic1, accountID, email, invitationMessage) +`, testAccDetectorConfig_basic, accountID, email, invitationMessage) } diff --git a/internal/service/iam/access_key.go b/internal/service/iam/access_key.go index ac66c0ca005..1791f1982e8 100644 --- a/internal/service/iam/access_key.go +++ b/internal/service/iam/access_key.go @@ -1,18 +1,20 @@ package iam import ( + "context" "crypto/hmac" "crypto/sha256" "encoding/base64" "fmt" + "log" "time" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iam" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func ResourceAccessKey() *schema.Resource { @@ -180,28 +182,29 @@ func resourceAccessKeyCreate(d *schema.ResourceData, meta interface{}) error { func resourceAccessKeyRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).IAMConn - request := &iam.ListAccessKeysInput{ - UserName: aws.String(d.Get("user").(string)), - } + username := d.Get("user").(string) - getResp, err := conn.ListAccessKeys(request) + key, err := FindAccessKey(context.TODO(), conn, username, d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] IAM Access Key (%s) for User (%s) not found, removing from state", d.Id(), username) + d.SetId("") + return nil + } if err != nil { - if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" { // XXX TEST ME - // the user does not exist, so the key can't exist. - d.SetId("") - return nil - } - return fmt.Errorf("Error reading IAM access key: %s", err) + return fmt.Errorf("error reading IAM access key: %w", err) } - for _, key := range getResp.AccessKeyMetadata { - if aws.StringValue(key.AccessKeyId) == d.Id() { - return resourceAccessKeyReadResult(d, key) - } + d.SetId(aws.StringValue(key.AccessKeyId)) + + if key.CreateDate != nil { + d.Set("create_date", aws.TimeValue(key.CreateDate).Format(time.RFC3339)) + } else { + d.Set("create_date", nil) } - // Guess the key isn't around anymore. - d.SetId("") + d.Set("status", key.Status) + d.Set("user", key.UserName) + return nil } diff --git a/internal/service/iam/access_key_test.go b/internal/service/iam/access_key_test.go index 2feb4888c59..fecb4178fb9 100644 --- a/internal/service/iam/access_key_test.go +++ b/internal/service/iam/access_key_test.go @@ -1,13 +1,12 @@ package iam_test import ( + "context" "errors" "fmt" "strings" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/service/iam" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -16,6 +15,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfiam "github.com/hashicorp/terraform-provider-aws/internal/service/iam" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/vault/helper/pgpkeys" ) @@ -31,7 +31,7 @@ func TestAccIAMAccessKey_basic(t *testing.T) { CheckDestroy: testAccCheckAccessKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessKeyConfig(rName), + Config: testAccAccessKeyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessKeyExists(resourceName, &conf), testAccCheckAccessKeyAttributes(&conf, "Active"), @@ -99,7 +99,7 @@ func TestAccIAMAccessKey_status(t *testing.T) { CheckDestroy: testAccCheckAccessKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessKeyConfig_Status(rName, iam.StatusTypeInactive), + Config: testAccAccessKeyConfig_status(rName, iam.StatusTypeInactive), Check: resource.ComposeTestCheckFunc( testAccCheckAccessKeyExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "status", iam.StatusTypeInactive), @@ -112,14 +112,14 @@ func TestAccIAMAccessKey_status(t *testing.T) { ImportStateVerifyIgnore: []string{"encrypted_secret", "key_fingerprint", "pgp_key", "secret", "ses_smtp_password_v4", "encrypted_ses_smtp_password_v4"}, }, { - Config: testAccAccessKeyConfig_Status(rName, iam.StatusTypeActive), + Config: testAccAccessKeyConfig_status(rName, iam.StatusTypeActive), Check: resource.ComposeTestCheckFunc( testAccCheckAccessKeyExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "status", iam.StatusTypeActive), ), }, { - Config: testAccAccessKeyConfig_Status(rName, iam.StatusTypeInactive), + Config: testAccAccessKeyConfig_status(rName, iam.StatusTypeInactive), Check: resource.ComposeTestCheckFunc( testAccCheckAccessKeyExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "status", iam.StatusTypeInactive), @@ -137,25 +137,14 @@ func testAccCheckAccessKeyDestroy(s *terraform.State) error { continue } - // Try to get access key - resp, err := conn.ListAccessKeys(&iam.ListAccessKeysInput{ - UserName: aws.String(rs.Primary.ID), - }) - if err == nil { - if len(resp.AccessKeyMetadata) > 0 { - return fmt.Errorf("still exist.") - } + _, err := tfiam.FindAccessKey(context.TODO(), conn, rs.Primary.Attributes["user"], rs.Primary.ID) + if tfresource.NotFound(err) { return nil } - - // Verify the error is what we want - ec2err, ok := err.(awserr.Error) - if !ok { - return err - } - if ec2err.Code() != "NoSuchEntity" { + if err != nil { return err } + return fmt.Errorf("IAM Access Key (%s) still exists", rs.Primary.ID) } return nil @@ -169,25 +158,17 @@ func testAccCheckAccessKeyExists(n string, res *iam.AccessKeyMetadata) resource. } if rs.Primary.ID == "" { - return fmt.Errorf("No Role name is set") + return fmt.Errorf("No Access Key ID is set") } conn := acctest.Provider.Meta().(*conns.AWSClient).IAMConn - name := rs.Primary.Attributes["user"] - resp, err := conn.ListAccessKeys(&iam.ListAccessKeysInput{ - UserName: aws.String(name), - }) + accessKey, err := tfiam.FindAccessKey(context.TODO(), conn, rs.Primary.Attributes["user"], rs.Primary.ID) if err != nil { return err } - if len(resp.AccessKeyMetadata) != 1 || - *resp.AccessKeyMetadata[0].UserName != name { - return fmt.Errorf("User not found not found") - } - - *res = *resp.AccessKeyMetadata[0] + *res = *accessKey return nil } @@ -239,7 +220,7 @@ func testDecryptSecretKeyAndTest(nAccessKey, key string) resource.TestCheckFunc } } -func testAccAccessKeyConfig(rName string) string { +func testAccAccessKeyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_iam_user" "test" { name = %[1]q @@ -267,7 +248,7 @@ EOF `, rName, key) } -func testAccAccessKeyConfig_Status(rName string, status string) string { +func testAccAccessKeyConfig_status(rName string, status string) string { return fmt.Sprintf(` resource "aws_iam_user" "test" { name = %[1]q @@ -280,7 +261,7 @@ resource "aws_iam_access_key" "test" { `, rName, status) } -func TestSesSmtpPasswordFromSecretKeySigV4(t *testing.T) { +func TestSESSMTPPasswordFromSecretKeySigV4(t *testing.T) { cases := []struct { Region string Input string diff --git a/internal/service/iam/account_alias.go b/internal/service/iam/account_alias.go index 807f4ad77e2..907ac33f739 100644 --- a/internal/service/iam/account_alias.go +++ b/internal/service/iam/account_alias.go @@ -42,7 +42,7 @@ func resourceAccountAliasCreate(d *schema.ResourceData, meta interface{}) error _, err := conn.CreateAccountAlias(params) if err != nil { - return fmt.Errorf("Error creating account alias with name '%s': %s", account_alias, err) + return fmt.Errorf("Error creating account alias with name '%s': %w", account_alias, err) } d.SetId(account_alias) @@ -58,10 +58,10 @@ func resourceAccountAliasRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.ListAccountAliases(params) if err != nil { - return fmt.Errorf("Error listing account aliases: %s", err) + return fmt.Errorf("Error listing account aliases: %w", err) } - if resp == nil || len(resp.AccountAliases) == 0 { + if !d.IsNewResource() && (resp == nil || len(resp.AccountAliases) == 0) { d.SetId("") return nil } diff --git a/internal/service/iam/account_alias_data_source_test.go b/internal/service/iam/account_alias_data_source_test.go index 3fc4a9b2b74..d28f178b008 100644 --- a/internal/service/iam/account_alias_data_source_test.go +++ b/internal/service/iam/account_alias_data_source_test.go @@ -23,7 +23,7 @@ func testAccAccountAliasDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckAccountAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountAliasDataSourceConfig(rName), + Config: testAccAccountAliasDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "account_alias", resourceName, "account_alias"), ), @@ -32,7 +32,7 @@ func testAccAccountAliasDataSource_basic(t *testing.T) { }) } -func testAccAccountAliasDataSourceConfig(rName string) string { +func testAccAccountAliasDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_iam_account_alias" "test" { account_alias = %[1]q diff --git a/internal/service/iam/account_alias_test.go b/internal/service/iam/account_alias_test.go index fe3b86f7acc..6428b3b95df 100644 --- a/internal/service/iam/account_alias_test.go +++ b/internal/service/iam/account_alias_test.go @@ -47,7 +47,7 @@ func testAccAccountAlias_basic(t *testing.T) { CheckDestroy: testAccCheckAccountAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountAliasConfig(rName), + Config: testAccAccountAliasConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAccountAliasExists(resourceName), ), @@ -118,7 +118,7 @@ func testAccCheckAccountAliasExists(n string) resource.TestCheckFunc { } } -func testAccAccountAliasConfig(rName string) string { +func testAccAccountAliasConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_iam_account_alias" "test" { account_alias = %[1]q diff --git a/internal/service/iam/account_password_policy.go b/internal/service/iam/account_password_policy.go index 2a30b2791e7..4136f6f124d 100644 --- a/internal/service/iam/account_password_policy.go +++ b/internal/service/iam/account_password_policy.go @@ -5,8 +5,8 @@ import ( "log" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iam" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -108,10 +108,9 @@ func resourceAccountPasswordPolicyUpdate(d *schema.ResourceData, meta interface{ input.RequireUppercaseCharacters = aws.Bool(v.(bool)) } - log.Printf("[DEBUG] Updating IAM account password policy: %s", input) _, err := conn.UpdateAccountPasswordPolicy(input) if err != nil { - return fmt.Errorf("Error updating IAM Password Policy: %s", err) + return fmt.Errorf("Error updating IAM Password Policy: %w", err) } log.Println("[DEBUG] IAM account password policy updated") @@ -126,17 +125,14 @@ func resourceAccountPasswordPolicyRead(d *schema.ResourceData, meta interface{}) input := &iam.GetAccountPasswordPolicyInput{} resp, err := conn.GetAccountPasswordPolicy(input) if err != nil { - awsErr, ok := err.(awserr.Error) - if ok && awsErr.Code() == "NoSuchEntity" { - log.Printf("[WARN] IAM account password policy is gone (i.e. default)") + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { + log.Printf("[WARN] IAM Account Password Policy not found, removing from state") d.SetId("") return nil } - return fmt.Errorf("Error reading IAM account password policy: %s", err) + return fmt.Errorf("Error reading IAM account password policy: %w", err) } - log.Printf("[DEBUG] Received IAM account password policy: %s", resp) - policy := resp.PasswordPolicy d.Set("allow_users_to_change_password", policy.AllowUsersToChangePassword) @@ -159,7 +155,7 @@ func resourceAccountPasswordPolicyDelete(d *schema.ResourceData, meta interface{ log.Println("[DEBUG] Deleting IAM account password policy") input := &iam.DeleteAccountPasswordPolicyInput{} if _, err := conn.DeleteAccountPasswordPolicy(input); err != nil { - return fmt.Errorf("Error deleting IAM Password Policy: %s", err) + return fmt.Errorf("Error deleting IAM Password Policy: %w", err) } log.Println("[DEBUG] Deleted IAM account password policy") diff --git a/internal/service/iam/account_password_policy_test.go b/internal/service/iam/account_password_policy_test.go index db89a58b229..b985202f644 100644 --- a/internal/service/iam/account_password_policy_test.go +++ b/internal/service/iam/account_password_policy_test.go @@ -23,7 +23,7 @@ func TestAccIAMAccountPasswordPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckAccountPasswordPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountPasswordPolicy, + Config: testAccAccountPasswordPolicyConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckAccountPasswordPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "minimum_password_length", "8"), @@ -35,7 +35,7 @@ func TestAccIAMAccountPasswordPolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAccountPasswordPolicy_modified, + Config: testAccAccountPasswordPolicyConfig_modified, Check: resource.ComposeTestCheckFunc( testAccCheckAccountPasswordPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "minimum_password_length", "7"), @@ -96,7 +96,7 @@ func testAccCheckAccountPasswordPolicyExists(n string, res *iam.GetAccountPasswo } } -const testAccAccountPasswordPolicy = ` +const testAccAccountPasswordPolicyConfig_basic = ` resource "aws_iam_account_password_policy" "test" { allow_users_to_change_password = true minimum_password_length = 8 @@ -104,7 +104,7 @@ resource "aws_iam_account_password_policy" "test" { } ` -const testAccAccountPasswordPolicy_modified = ` +const testAccAccountPasswordPolicyConfig_modified = ` resource "aws_iam_account_password_policy" "test" { allow_users_to_change_password = true minimum_password_length = 7 diff --git a/internal/service/iam/find.go b/internal/service/iam/find.go index 870e07597fa..23044a5a7ca 100644 --- a/internal/service/iam/find.go +++ b/internal/service/iam/find.go @@ -79,16 +79,64 @@ func FindUserAttachedPolicy(conn *iam.IAM, userName string, policyARN string) (* return result, nil } -// FindPolicies returns the FindPolicies corresponding to the specified ARN, name, and/or path-prefix. -func FindPolicies(conn *iam.IAM, arn, name, pathPrefix string) ([]*iam.Policy, error) { - input := &iam.ListPoliciesInput{} +// FindPolicyByARN returns the Policy corresponding to the specified ARN. +func FindPolicyByARN(conn *iam.IAM, arn string) (*iam.Policy, error) { + input := &iam.GetPolicyInput{ + PolicyArn: aws.String(arn), + } + + output, err := conn.GetPolicy(input) + if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + if err != nil { + return nil, err + } + + if output == nil || output.Policy == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.Policy, nil +} +// FindPolicyByName returns the Policy corresponding to the name and/or path-prefix. +func FindPolicyByName(conn *iam.IAM, name, pathPrefix string) (*iam.Policy, error) { + input := &iam.ListPoliciesInput{} if pathPrefix != "" { input.PathPrefix = aws.String(pathPrefix) } + all, err := FindPolicies(conn, input) + if err != nil { + return nil, err + } + var results []*iam.Policy + for _, p := range all { + if name != "" && name != aws.StringValue(p.PolicyName) { + continue + } + + results = append(results, p) + } + + if len(results) == 0 || results[0] == nil { + return nil, tfresource.NewEmptyResultError(nil) + } + if l := len(results); l > 1 { + return nil, tfresource.NewTooManyResultsError(1, nil) + } + return results[0], nil +} + +// FindPolicies returns the Policies matching the parameters in the iam.ListPoliciesInput. +func FindPolicies(conn *iam.IAM, input *iam.ListPoliciesInput) ([]*iam.Policy, error) { + var results []*iam.Policy err := conn.ListPoliciesPages(input, func(page *iam.ListPoliciesOutput, lastPage bool) bool { if page == nil { return !lastPage @@ -99,14 +147,6 @@ func FindPolicies(conn *iam.IAM, arn, name, pathPrefix string) ([]*iam.Policy, e continue } - if arn != "" && arn != aws.StringValue(p.Arn) { - continue - } - - if name != "" && name != aws.StringValue(p.PolicyName) { - continue - } - results = append(results, p) } @@ -306,3 +346,42 @@ func FindSAMLProviderByARN(ctx context.Context, conn *iam.IAM, arn string) (*iam return output, nil } + +func FindAccessKey(ctx context.Context, conn *iam.IAM, username, id string) (*iam.AccessKeyMetadata, error) { + accessKeys, err := FindAccessKeys(ctx, conn, username) + if err != nil { + return nil, err + } + + for _, accessKey := range accessKeys { + if aws.StringValue(accessKey.AccessKeyId) == id { + return accessKey, nil + } + } + + return nil, &resource.NotFoundError{} +} + +func FindAccessKeys(ctx context.Context, conn *iam.IAM, username string) ([]*iam.AccessKeyMetadata, error) { + var accessKeys []*iam.AccessKeyMetadata + input := &iam.ListAccessKeysInput{ + UserName: aws.String(username), + } + err := conn.ListAccessKeysPages(input, func(page *iam.ListAccessKeysOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + accessKeys = append(accessKeys, page.AccessKeyMetadata...) + + return !lastPage + }) + + if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return accessKeys, err +} diff --git a/internal/service/iam/group_data_source_test.go b/internal/service/iam/group_data_source_test.go index 5103daf86cc..39e43b78fda 100644 --- a/internal/service/iam/group_data_source_test.go +++ b/internal/service/iam/group_data_source_test.go @@ -19,7 +19,7 @@ func TestAccIAMGroupDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccGroupDataSourceConfig(groupName), + Config: testAccGroupDataSourceConfig_basic(groupName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_iam_group.test", "group_id"), resource.TestCheckResourceAttr("data.aws_iam_group.test", "path", "/"), @@ -43,7 +43,7 @@ func TestAccIAMGroupDataSource_users(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccGroupWithUserDataSourceConfig(groupName, userName, groupMemberShipName, userCount), + Config: testAccGroupDataSourceConfig_user(groupName, userName, groupMemberShipName, userCount), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_iam_group.test", "group_id"), resource.TestCheckResourceAttr("data.aws_iam_group.test", "path", "/"), @@ -60,7 +60,7 @@ func TestAccIAMGroupDataSource_users(t *testing.T) { }) } -func testAccGroupDataSourceConfig(name string) string { +func testAccGroupDataSourceConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_iam_group" "group" { name = "%s" @@ -73,7 +73,7 @@ data "aws_iam_group" "test" { `, name) } -func testAccGroupWithUserDataSourceConfig(groupName, userName, membershipName string, userCount int) string { +func testAccGroupDataSourceConfig_user(groupName, userName, membershipName string, userCount int) string { return fmt.Sprintf(` resource "aws_iam_group" "group" { name = "%s" diff --git a/internal/service/iam/group_membership_test.go b/internal/service/iam/group_membership_test.go index 59889b744c2..e7c54052bd1 100644 --- a/internal/service/iam/group_membership_test.go +++ b/internal/service/iam/group_membership_test.go @@ -32,7 +32,7 @@ func TestAccIAMGroupMembership_basic(t *testing.T) { CheckDestroy: testAccCheckGroupMembershipDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupMemberConfig(groupName, userName, membershipName), + Config: testAccGroupMembershipConfig_member(groupName, userName, membershipName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupMembershipExists("aws_iam_group_membership.team", &group), testAccCheckGroupMembershipAttributes(&group, groupName, []string{userName}), @@ -40,7 +40,7 @@ func TestAccIAMGroupMembership_basic(t *testing.T) { }, { - Config: testAccGroupMemberUpdateConfig(groupName, userName, userName2, userName3, membershipName), + Config: testAccGroupMembershipConfig_memberUpdate(groupName, userName, userName2, userName3, membershipName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupMembershipExists("aws_iam_group_membership.team", &group), testAccCheckGroupMembershipAttributes(&group, groupName, []string{userName2, userName3}), @@ -48,7 +48,7 @@ func TestAccIAMGroupMembership_basic(t *testing.T) { }, { - Config: testAccGroupMemberUpdateDownConfig(groupName, userName3, membershipName), + Config: testAccGroupMembershipConfig_memberUpdateDown(groupName, userName3, membershipName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupMembershipExists("aws_iam_group_membership.team", &group), testAccCheckGroupMembershipAttributes(&group, groupName, []string{userName3}), @@ -73,7 +73,7 @@ func TestAccIAMGroupMembership_paginatedUserList(t *testing.T) { CheckDestroy: testAccCheckGroupMembershipDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupMemberPaginatedUserListConfig(groupName, membershipName, userNamePrefix), + Config: testAccGroupMembershipConfig_memberPaginatedUserList(groupName, membershipName, userNamePrefix), Check: resource.ComposeTestCheckFunc( testAccCheckGroupMembershipExists("aws_iam_group_membership.team", &group), resource.TestCheckResourceAttr( @@ -162,7 +162,7 @@ func testAccCheckGroupMembershipAttributes(group *iam.GetGroupOutput, groupName } } -func testAccGroupMemberConfig(groupName, userName, membershipName string) string { +func testAccGroupMembershipConfig_member(groupName, userName, membershipName string) string { return fmt.Sprintf(` resource "aws_iam_group" "group" { name = "%s" @@ -180,7 +180,7 @@ resource "aws_iam_group_membership" "team" { `, groupName, userName, membershipName) } -func testAccGroupMemberUpdateConfig(groupName, userName, userName2, userName3, membershipName string) string { +func testAccGroupMembershipConfig_memberUpdate(groupName, userName, userName2, userName3, membershipName string) string { return fmt.Sprintf(` resource "aws_iam_group" "group" { name = "%s" @@ -211,7 +211,7 @@ resource "aws_iam_group_membership" "team" { `, groupName, userName, userName2, userName3, membershipName) } -func testAccGroupMemberUpdateDownConfig(groupName, userName3, membershipName string) string { +func testAccGroupMembershipConfig_memberUpdateDown(groupName, userName3, membershipName string) string { return fmt.Sprintf(` resource "aws_iam_group" "group" { name = "%s" @@ -233,7 +233,7 @@ resource "aws_iam_group_membership" "team" { `, groupName, userName3, membershipName) } -func testAccGroupMemberPaginatedUserListConfig(groupName, membershipName, userNamePrefix string) string { +func testAccGroupMembershipConfig_memberPaginatedUserList(groupName, membershipName, userNamePrefix string) string { return fmt.Sprintf(` resource "aws_iam_group" "group" { name = "%s" diff --git a/internal/service/iam/group_policy_attachment_test.go b/internal/service/iam/group_policy_attachment_test.go index a73e1dd0f40..65f0e7ccadf 100644 --- a/internal/service/iam/group_policy_attachment_test.go +++ b/internal/service/iam/group_policy_attachment_test.go @@ -30,7 +30,7 @@ func TestAccIAMGroupPolicyAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckGroupPolicyAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupPolicyAttachConfig(groupName, policyName), + Config: testAccGroupPolicyAttachmentConfig_attach(groupName, policyName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupPolicyAttachmentExists("aws_iam_group_policy_attachment.test-attach", 1, &out), testAccCheckGroupPolicyAttachmentAttributes([]string{policyName}, &out), @@ -55,7 +55,7 @@ func TestAccIAMGroupPolicyAttachment_basic(t *testing.T) { }, }, { - Config: testAccGroupPolicyAttachUpdateConfig(groupName, policyName, policyName2, policyName3), + Config: testAccGroupPolicyAttachmentConfig_attachUpdate(groupName, policyName, policyName2, policyName3), Check: resource.ComposeTestCheckFunc( testAccCheckGroupPolicyAttachmentExists("aws_iam_group_policy_attachment.test-attach", 2, &out), testAccCheckGroupPolicyAttachmentAttributes([]string{policyName2, policyName3}, &out), @@ -118,7 +118,7 @@ func testAccCheckGroupPolicyAttachmentAttributes(policies []string, out *iam.Lis } } -func testAccGroupPolicyAttachConfig(groupName, policyName string) string { +func testAccGroupPolicyAttachmentConfig_attach(groupName, policyName string) string { return fmt.Sprintf(` resource "aws_iam_group" "group" { name = "%s" @@ -151,7 +151,7 @@ resource "aws_iam_group_policy_attachment" "test-attach" { `, groupName, policyName) } -func testAccGroupPolicyAttachUpdateConfig(groupName, policyName, policyName2, policyName3 string) string { +func testAccGroupPolicyAttachmentConfig_attachUpdate(groupName, policyName, policyName2, policyName3 string) string { return fmt.Sprintf(` resource "aws_iam_group" "group" { name = "%s" diff --git a/internal/service/iam/group_test.go b/internal/service/iam/group_test.go index b98823b9b59..250ccedac32 100644 --- a/internal/service/iam/group_test.go +++ b/internal/service/iam/group_test.go @@ -30,7 +30,7 @@ func TestAccIAMGroup_basic(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(groupName), + Config: testAccGroupConfig_basic(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &conf), testAccCheckGroupAttributes(&conf, groupName, "/"), @@ -42,7 +42,7 @@ func TestAccIAMGroup_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccGroup2Config(groupName2), + Config: testAccGroupConfig_2(groupName2), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName2, &conf), testAccCheckGroupAttributes(&conf, groupName2, "/funnypath/"), @@ -66,14 +66,14 @@ func TestAccIAMGroup_nameChange(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(groupName), + Config: testAccGroupConfig_basic(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &conf), testAccCheckGroupAttributes(&conf, groupName, "/"), ), }, { - Config: testAccGroupConfig(groupName2), + Config: testAccGroupConfig_basic(groupName2), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &conf), testAccCheckGroupAttributes(&conf, groupName2, "/"), @@ -152,7 +152,7 @@ func testAccCheckGroupAttributes(group *iam.GetGroupOutput, name string, path st } } -func testAccGroupConfig(groupName string) string { +func testAccGroupConfig_basic(groupName string) string { return fmt.Sprintf(` resource "aws_iam_group" "test" { name = "%s" @@ -161,7 +161,7 @@ resource "aws_iam_group" "test" { `, groupName) } -func testAccGroup2Config(groupName string) string { +func testAccGroupConfig_2(groupName string) string { return fmt.Sprintf(` resource "aws_iam_group" "test2" { name = "%s" diff --git a/internal/service/iam/instance_profile.go b/internal/service/iam/instance_profile.go index 68f531fe455..476d3b45584 100644 --- a/internal/service/iam/instance_profile.go +++ b/internal/service/iam/instance_profile.go @@ -104,7 +104,7 @@ func resourceInstanceProfileCreate(d *schema.ResourceData, meta interface{}) err response, err := conn.CreateInstanceProfile(request) // Some partitions (i.e., ISO) may not support tag-on-create - if request.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if request.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating IAM Instance Profile (%s) with tags: %s. Trying create without tags.", name, err) request.Tags = nil @@ -135,7 +135,7 @@ func resourceInstanceProfileCreate(d *schema.ResourceData, meta interface{}) err err := instanceProfileUpdateTags(conn, d.Id(), nil, tags) // If default tags only, log and continue. Otherwise, error. - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed adding tags after create for IAM Instance Profile (%s): %s", d.Id(), err) return resourceInstanceProfileUpdate(d, meta) } @@ -228,7 +228,7 @@ func resourceInstanceProfileUpdate(d *schema.ResourceData, meta interface{}) err err := instanceProfileUpdateTags(conn, d.Id(), o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed updating tags for IAM Instance Profile (%s): %s", d.Id(), err) return nil } @@ -249,8 +249,8 @@ func resourceInstanceProfileRead(d *schema.ResourceData, meta interface{}) error } result, err := conn.GetInstanceProfile(request) - if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { - log.Printf("[WARN] IAM Instance Profile %s is already gone", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { + log.Printf("[WARN] IAM Instance Profile (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/iam/instance_profile_data_source_test.go b/internal/service/iam/instance_profile_data_source_test.go index 92e42ab4660..4308b594efb 100644 --- a/internal/service/iam/instance_profile_data_source_test.go +++ b/internal/service/iam/instance_profile_data_source_test.go @@ -22,7 +22,7 @@ func TestAccIAMInstanceProfileDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceProfileDataSourceConfig(roleName, profileName), + Config: testAccInstanceProfileDataSourceConfig_basic(roleName, profileName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_iam_instance_profile.test", "arn"), resource.TestCheckResourceAttr(resourceName, "path", "/testpath/"), @@ -35,7 +35,7 @@ func TestAccIAMInstanceProfileDataSource_basic(t *testing.T) { }) } -func testAccInstanceProfileDataSourceConfig(roleName, profileName string) string { +func testAccInstanceProfileDataSourceConfig_basic(roleName, profileName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = "%s" diff --git a/internal/service/iam/instance_profile_test.go b/internal/service/iam/instance_profile_test.go index ae5ee16cbbb..9b75139c4b7 100644 --- a/internal/service/iam/instance_profile_test.go +++ b/internal/service/iam/instance_profile_test.go @@ -28,7 +28,7 @@ func TestAccIAMInstanceProfile_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceProfileConfig(rName), + Config: testAccInstanceProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceProfileExists(resourceName, &conf), acctest.CheckResourceAttrGlobalARN(resourceName, "arn", "iam", fmt.Sprintf("instance-profile/test-%s", rName)), @@ -57,7 +57,7 @@ func TestAccIAMInstanceProfile_withoutRole(t *testing.T) { CheckDestroy: testAccCheckInstanceProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceProfileWithoutRoleConfig(rName), + Config: testAccInstanceProfileConfig_noRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceProfileExists(resourceName, &conf), ), @@ -84,7 +84,7 @@ func TestAccIAMInstanceProfile_tags(t *testing.T) { CheckDestroy: testAccCheckInstanceProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceProfileTags1Config(rName, "key1", "value1"), + Config: testAccInstanceProfileConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceProfileExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -98,7 +98,7 @@ func TestAccIAMInstanceProfile_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"name_prefix"}, }, { - Config: testAccInstanceProfileTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccInstanceProfileConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceProfileExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -107,7 +107,7 @@ func TestAccIAMInstanceProfile_tags(t *testing.T) { ), }, { - Config: testAccInstanceProfileTags1Config(rName, "key2", "value2"), + Config: testAccInstanceProfileConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceProfileExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -130,7 +130,7 @@ func TestAccIAMInstanceProfile_namePrefix(t *testing.T) { CheckDestroy: testAccCheckInstanceProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceProfilePrefixNameConfig(rName), + Config: testAccInstanceProfileConfig_prefixName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceProfileExists(resourceName, &conf), testAccCheckInstanceProfileGeneratedNamePrefix( @@ -159,7 +159,7 @@ func TestAccIAMInstanceProfile_disappears(t *testing.T) { CheckDestroy: testAccCheckInstanceProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceProfileConfig(rName), + Config: testAccInstanceProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceProfileExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfiam.ResourceInstanceProfile(), resourceName), @@ -182,7 +182,7 @@ func TestAccIAMInstanceProfile_Disappears_role(t *testing.T) { CheckDestroy: testAccCheckInstanceProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceProfileConfig(rName), + Config: testAccInstanceProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceProfileExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfiam.ResourceRole(), "aws_iam_role.test"), @@ -289,7 +289,7 @@ EOF `, rName) } -func testAccInstanceProfileConfig(rName string) string { +func testAccInstanceProfileConfig_basic(rName string) string { return testAccInstanceProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_iam_instance_profile" "test" { name = "test-%[1]s" @@ -298,7 +298,7 @@ resource "aws_iam_instance_profile" "test" { `, rName) } -func testAccInstanceProfileWithoutRoleConfig(rName string) string { +func testAccInstanceProfileConfig_noRole(rName string) string { return fmt.Sprintf(` resource "aws_iam_instance_profile" "test" { name = "test-%s" @@ -306,7 +306,7 @@ resource "aws_iam_instance_profile" "test" { `, rName) } -func testAccInstanceProfilePrefixNameConfig(rName string) string { +func testAccInstanceProfileConfig_prefixName(rName string) string { return testAccInstanceProfileBaseConfig(rName) + ` resource "aws_iam_instance_profile" "test" { name_prefix = "test-" @@ -315,7 +315,7 @@ resource "aws_iam_instance_profile" "test" { ` } -func testAccInstanceProfileTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccInstanceProfileConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccInstanceProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_iam_instance_profile" "test" { name = "test-%[1]s" @@ -328,7 +328,7 @@ resource "aws_iam_instance_profile" "test" { `, rName, tagKey1, tagValue1) } -func testAccInstanceProfileTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccInstanceProfileConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccInstanceProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_iam_instance_profile" "test" { name = "test-%[1]s" diff --git a/internal/service/iam/instance_profiles_data_source_test.go b/internal/service/iam/instance_profiles_data_source_test.go index c506ea85367..4e492bc513f 100644 --- a/internal/service/iam/instance_profiles_data_source_test.go +++ b/internal/service/iam/instance_profiles_data_source_test.go @@ -21,7 +21,7 @@ func TestAccIAMInstanceProfilesDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceProfilesDataSourceConfig(rName), + Config: testAccInstanceProfilesDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "arns.#", "1"), resource.TestCheckResourceAttr(datasourceName, "paths.#", "1"), @@ -35,7 +35,7 @@ func TestAccIAMInstanceProfilesDataSource_basic(t *testing.T) { }) } -func testAccInstanceProfilesDataSourceConfig(rName string) string { +func testAccInstanceProfilesDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q diff --git a/internal/service/iam/openid_connect_provider.go b/internal/service/iam/openid_connect_provider.go index 7d392ff5245..6198d474452 100644 --- a/internal/service/iam/openid_connect_provider.go +++ b/internal/service/iam/openid_connect_provider.go @@ -80,7 +80,7 @@ func resourceOpenIDConnectProviderCreate(d *schema.ResourceData, meta interface{ out, err := conn.CreateOpenIDConnectProvider(input) // Some partitions (i.e., ISO) may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating IAM OIDC Provider with tags: %s. Trying create without tags.", err) input.Tags = nil @@ -98,7 +98,7 @@ func resourceOpenIDConnectProviderCreate(d *schema.ResourceData, meta interface{ err := openIDConnectProviderUpdateTags(conn, d.Id(), nil, tags) // If default tags only, log and continue. Otherwise, error. - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed adding tags after create for IAM OIDC Provider (%s): %s", d.Id(), err) return resourceOpenIDConnectProviderRead(d, meta) } @@ -120,7 +120,7 @@ func resourceOpenIDConnectProviderRead(d *schema.ResourceData, meta interface{}) OpenIDConnectProviderArn: aws.String(d.Id()), } out, err := conn.GetOpenIDConnectProvider(input) - if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { log.Printf("[WARN] IAM OIDC Provider (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -169,7 +169,7 @@ func resourceOpenIDConnectProviderUpdate(d *schema.ResourceData, meta interface{ err := openIDConnectProviderUpdateTags(conn, d.Id(), o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed updating tags for IAM OIDC Provider (%s): %s", d.Id(), err) return resourceOpenIDConnectProviderRead(d, meta) } diff --git a/internal/service/iam/openid_connect_provider_data_source.go b/internal/service/iam/openid_connect_provider_data_source.go index ac648887afd..44689ce2722 100644 --- a/internal/service/iam/openid_connect_provider_data_source.go +++ b/internal/service/iam/openid_connect_provider_data_source.go @@ -107,7 +107,7 @@ func dataSourceGetOpenIDConnectProviderByURL(ctx context.Context, conn *iam.IAM, continue } - arnUrl, err := urlFromOpenIDConnectProviderArn(aws.StringValue(oidcp.Arn)) + arnUrl, err := urlFromOpenIDConnectProviderARN(aws.StringValue(oidcp.Arn)) if err != nil { return nil, err } @@ -120,7 +120,7 @@ func dataSourceGetOpenIDConnectProviderByURL(ctx context.Context, conn *iam.IAM, return result, nil } -func urlFromOpenIDConnectProviderArn(arn string) (string, error) { +func urlFromOpenIDConnectProviderARN(arn string) (string, error) { parts := strings.SplitN(arn, "/", 2) if len(parts) != 2 { return "", fmt.Errorf("error reading OpenID Connect Provider expected the arn to be like: arn:PARTITION:iam::ACCOUNT:oidc-provider/URL but got: %s", arn) diff --git a/internal/service/iam/policy.go b/internal/service/iam/policy.go index 069474eea87..79551af52b6 100644 --- a/internal/service/iam/policy.go +++ b/internal/service/iam/policy.go @@ -115,7 +115,7 @@ func resourcePolicyCreate(d *schema.ResourceData, meta interface{}) error { response, err := conn.CreatePolicy(request) // Some partitions (i.e., ISO) may not support tag-on-create - if request.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if request.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating IAM Policy (%s) with tags: %s. Trying create without tags.", name, err) request.Tags = nil @@ -133,7 +133,7 @@ func resourcePolicyCreate(d *schema.ResourceData, meta interface{}) error { err := policyUpdateTags(conn, d.Id(), nil, tags) // If default tags only, log and continue. Otherwise, error. - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed adding tags after create for IAM Policy (%s): %s", d.Id(), err) return resourcePolicyRead(d, meta) } @@ -176,7 +176,7 @@ func resourcePolicyRead(d *schema.ResourceData, meta interface{}) error { getPolicyResponse, err = conn.GetPolicy(input) } - if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { log.Printf("[WARN] IAM Policy (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -186,7 +186,7 @@ func resourcePolicyRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error reading IAM policy %s: %w", d.Id(), err) } - if getPolicyResponse == nil || getPolicyResponse.Policy == nil { + if !d.IsNewResource() && (getPolicyResponse == nil || getPolicyResponse.Policy == nil) { log.Printf("[WARN] IAM Policy (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -239,8 +239,8 @@ func resourcePolicyRead(d *schema.ResourceData, meta interface{}) error { getPolicyVersionResponse, err = conn.GetPolicyVersion(getPolicyVersionRequest) } - if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { - log.Printf("[WARN] IAM Policy (%s) not found, removing from state", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { + log.Printf("[WARN] IAM Policy (%s) version (%s) not found, removing from state", d.Id(), aws.StringValue(policy.DefaultVersionId)) d.SetId("") return nil } @@ -307,7 +307,7 @@ func resourcePolicyUpdate(d *schema.ResourceData, meta interface{}) error { err := policyUpdateTags(conn, d.Id(), o, n) // Some partitions (i.e., ISO) may not support tagging, giving error - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed updating tags for IAM Policy (%s): %s", d.Id(), err) return resourcePolicyRead(d, meta) } diff --git a/internal/service/iam/policy_attachment.go b/internal/service/iam/policy_attachment.go index dea17583099..1e31e227b27 100644 --- a/internal/service/iam/policy_attachment.go +++ b/internal/service/iam/policy_attachment.go @@ -5,7 +5,6 @@ import ( "log" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iam" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -95,14 +94,12 @@ func resourcePolicyAttachmentRead(d *schema.ResourceData, meta interface{}) erro }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - if awsErr.Code() == "NoSuchEntity" { - log.Printf("[WARN] No such entity found for Policy Attachment (%s)", d.Id()) - d.SetId("") - return nil - } + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { + log.Printf("[WARN] IAM Policy Attachment (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } - return err + return fmt.Errorf("error reading IAM Policy Attachment (%s): %w", d.Id(), err) } ul := make([]string, 0) diff --git a/internal/service/iam/policy_attachment_test.go b/internal/service/iam/policy_attachment_test.go index fce6428e68c..c3082cf75db 100644 --- a/internal/service/iam/policy_attachment_test.go +++ b/internal/service/iam/policy_attachment_test.go @@ -36,14 +36,14 @@ func TestAccIAMPolicyAttachment_basic(t *testing.T) { CheckDestroy: testAccCheckPolicyAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyAttachConfig(userName, roleName, groupName, policyName, attachmentName), + Config: testAccPolicyAttachmentConfig_attach(userName, roleName, groupName, policyName, attachmentName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists("aws_iam_policy_attachment.test-attach", 3, &out), testAccCheckPolicyAttachmentAttributes([]string{userName}, []string{roleName}, []string{groupName}, &out), ), }, { - Config: testAccPolicyAttachUpdateConfig(userName, userName2, userName3, + Config: testAccPolicyAttachmentConfig_attachUpdate(userName, userName2, userName3, roleName, roleName2, roleName3, groupName, groupName2, groupName3, policyName, attachmentName), @@ -72,7 +72,7 @@ func TestAccIAMPolicyAttachment_paginatedEntities(t *testing.T) { CheckDestroy: testAccCheckPolicyAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyPaginatedAttachConfig(userNamePrefix, policyName, attachmentName), + Config: testAccPolicyAttachmentConfig_paginatedAttach(userNamePrefix, policyName, attachmentName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists("aws_iam_policy_attachment.test-paginated-attach", 101, &out), ), @@ -96,14 +96,14 @@ func TestAccIAMPolicyAttachment_Groups_renamedGroup(t *testing.T) { CheckDestroy: testAccCheckPolicyAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyAttachmentGroupsRenamedGroupConfig(rName, groupName1), + Config: testAccPolicyAttachmentConfig_groupsRenamedGroup(rName, groupName1), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName, 1, &out), testAccCheckPolicyAttachmentAttributes([]string{}, []string{}, []string{groupName1}, &out), ), }, { - Config: testAccPolicyAttachmentGroupsRenamedGroupConfig(rName, groupName2), + Config: testAccPolicyAttachmentConfig_groupsRenamedGroup(rName, groupName2), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName, 1, &out), testAccCheckPolicyAttachmentAttributes([]string{}, []string{}, []string{groupName2}, &out), @@ -128,14 +128,14 @@ func TestAccIAMPolicyAttachment_Roles_renamedRole(t *testing.T) { CheckDestroy: testAccCheckPolicyAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyAttachmentRolesRenamedRoleConfig(rName, roleName1), + Config: testAccPolicyAttachmentConfig_rolesRenamedRole(rName, roleName1), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName, 1, &out), testAccCheckPolicyAttachmentAttributes([]string{}, []string{roleName1}, []string{}, &out), ), }, { - Config: testAccPolicyAttachmentRolesRenamedRoleConfig(rName, roleName2), + Config: testAccPolicyAttachmentConfig_rolesRenamedRole(rName, roleName2), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName, 1, &out), testAccCheckPolicyAttachmentAttributes([]string{}, []string{roleName2}, []string{}, &out), @@ -160,14 +160,14 @@ func TestAccIAMPolicyAttachment_Users_renamedUser(t *testing.T) { CheckDestroy: testAccCheckPolicyAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyAttachmentUsersRenamedUserConfig(rName, userName1), + Config: testAccPolicyAttachmentConfig_usersRenamedUser(rName, userName1), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName, 1, &out), testAccCheckPolicyAttachmentAttributes([]string{userName1}, []string{}, []string{}, &out), ), }, { - Config: testAccPolicyAttachmentUsersRenamedUserConfig(rName, userName2), + Config: testAccPolicyAttachmentConfig_usersRenamedUser(rName, userName2), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName, 1, &out), testAccCheckPolicyAttachmentAttributes([]string{userName2}, []string{}, []string{}, &out), @@ -250,7 +250,7 @@ func testAccCheckPolicyAttachmentAttributes(users []string, roles []string, grou } } -func testAccPolicyAttachConfig(userName, roleName, groupName, policyName, attachmentName string) string { +func testAccPolicyAttachmentConfig_attach(userName, roleName, groupName, policyName, attachmentName string) string { return fmt.Sprintf(` resource "aws_iam_user" "user" { name = "%s" @@ -310,7 +310,7 @@ resource "aws_iam_policy_attachment" "test-attach" { `, userName, roleName, groupName, policyName, attachmentName) } -func testAccPolicyAttachUpdateConfig(userName, userName2, userName3, +func testAccPolicyAttachmentConfig_attachUpdate(userName, userName2, userName3, roleName, roleName2, roleName3, groupName, groupName2, groupName3, policyName, attachmentName string) string { @@ -445,7 +445,7 @@ resource "aws_iam_policy_attachment" "test-attach" { policyName, attachmentName) } -func testAccPolicyPaginatedAttachConfig(userNamePrefix, policyName, attachmentName string) string { +func testAccPolicyAttachmentConfig_paginatedAttach(userNamePrefix, policyName, attachmentName string) string { return fmt.Sprintf(` resource "aws_iam_user" "user" { count = 101 @@ -584,7 +584,7 @@ resource "aws_iam_policy_attachment" "test-paginated-attach" { `, userNamePrefix, policyName, attachmentName) } -func testAccPolicyAttachmentGroupsRenamedGroupConfig(rName, groupName string) string { +func testAccPolicyAttachmentConfig_groupsRenamedGroup(rName, groupName string) string { return fmt.Sprintf(` resource "aws_iam_policy" "test" { name = %[1]q @@ -615,7 +615,7 @@ resource "aws_iam_policy_attachment" "test" { `, rName, groupName) } -func testAccPolicyAttachmentRolesRenamedRoleConfig(rName, roleName string) string { +func testAccPolicyAttachmentConfig_rolesRenamedRole(rName, roleName string) string { return fmt.Sprintf(` resource "aws_iam_policy" "test" { name = %[1]q @@ -663,7 +663,7 @@ resource "aws_iam_policy_attachment" "test" { `, rName, roleName) } -func testAccPolicyAttachmentUsersRenamedUserConfig(rName, userName string) string { +func testAccPolicyAttachmentConfig_usersRenamedUser(rName, userName string) string { return fmt.Sprintf(` resource "aws_iam_policy" "test" { name = %[1]q diff --git a/internal/service/iam/policy_data_source.go b/internal/service/iam/policy_data_source.go index bea63341735..349f34ab08d 100644 --- a/internal/service/iam/policy_data_source.go +++ b/internal/service/iam/policy_data_source.go @@ -1,6 +1,7 @@ package iam import ( + "errors" "fmt" "net/url" "strings" @@ -22,27 +23,30 @@ func DataSourcePolicy() *schema.Resource { Schema: map[string]*schema.Schema{ "arn": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: verify.ValidARN, + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: verify.ValidARN, + ConflictsWith: []string{"name", "path_prefix"}, }, "description": { Type: schema.TypeString, Computed: true, }, "name": { - Type: schema.TypeString, - Optional: true, - Computed: true, + Type: schema.TypeString, + Optional: true, + Computed: true, + ConflictsWith: []string{"arn"}, }, "path": { Type: schema.TypeString, Computed: true, }, "path_prefix": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ConflictsWith: []string{"arn"}, }, "policy": { Type: schema.TypeString, @@ -65,46 +69,37 @@ func dataSourcePolicyRead(d *schema.ResourceData, meta interface{}) error { name := d.Get("name").(string) pathPrefix := d.Get("path_prefix").(string) - var results []*iam.Policy - - // Handle IAM eventual consistency - err := resource.Retry(propagationTimeout, func() *resource.RetryError { - var err error - results, err = FindPolicies(conn, arn, name, pathPrefix) + if arn == "" { + raw, err := tfresource.RetryWhenNotFound(propagationTimeout, + func() (interface{}, error) { + return FindPolicyByName(conn, name, pathPrefix) + }, + ) - if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { - return resource.RetryableError(err) + if errors.Is(err, tfresource.ErrEmptyResult) { + return fmt.Errorf("no IAM policy found matching criteria (%s); try different search", PolicySearchDetails(name, pathPrefix)) + } + if errors.Is(err, tfresource.ErrTooManyResults) { + return fmt.Errorf("multiple IAM policies found matching criteria (%s); try different search. %w", PolicySearchDetails(name, pathPrefix), err) } - if err != nil { - return resource.NonRetryableError(err) + return fmt.Errorf("error reading IAM policy (%s): %w", PolicySearchDetails(name, pathPrefix), err) } - return nil - }) - - if tfresource.TimedOut(err) { - results, err = FindPolicies(conn, arn, name, pathPrefix) + arn = aws.StringValue((raw.(*iam.Policy)).Arn) } + // We need to make a call to `iam.GetPolicy` because `iam.ListPolicies` doesn't return all values + policy, err := FindPolicyByARN(conn, arn) if err != nil { - return fmt.Errorf("error reading IAM policy (%s): %w", PolicySearchDetails(arn, name, pathPrefix), err) + return fmt.Errorf("error reading IAM policy (%s): %w", arn, err) } - if len(results) == 0 { - return fmt.Errorf("no IAM policy found matching criteria (%s); try different search", PolicySearchDetails(arn, name, pathPrefix)) - } - - if len(results) > 1 { - return fmt.Errorf("multiple IAM policies found matching criteria (%s); try different search", PolicySearchDetails(arn, name, pathPrefix)) - } - - policy := results[0] policyArn := aws.StringValue(policy.Arn) d.SetId(policyArn) - d.Set("arn", policyArn) + d.Set("description", policy.Description) d.Set("name", policy.PolicyName) d.Set("path", policy.Path) d.Set("policy_id", policy.PolicyId) @@ -113,23 +108,6 @@ func dataSourcePolicyRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting tags: %w", err) } - // Retrieve policy description - policyInput := &iam.GetPolicyInput{ - PolicyArn: policy.Arn, - } - - policyOutput, err := conn.GetPolicy(policyInput) - - if err != nil { - return fmt.Errorf("error reading IAM policy (%s): %w", policyArn, err) - } - - if policyOutput == nil || policyOutput.Policy == nil { - return fmt.Errorf("error reading IAM policy (%s): empty output", policyArn) - } - - d.Set("description", policyOutput.Policy.Description) - // Retrieve policy policyVersionInput := &iam.GetPolicyVersionInput{ PolicyArn: policy.Arn, @@ -181,11 +159,8 @@ func dataSourcePolicyRead(d *schema.ResourceData, meta interface{}) error { } // PolicySearchDetails returns the configured search criteria as a printable string -func PolicySearchDetails(arn, name, pathPrefix string) string { +func PolicySearchDetails(name, pathPrefix string) string { var policyDetails []string - if arn != "" { - policyDetails = append(policyDetails, fmt.Sprintf("ARN: %s", arn)) - } if name != "" { policyDetails = append(policyDetails, fmt.Sprintf("Name: %s", name)) } diff --git a/internal/service/iam/policy_data_source_test.go b/internal/service/iam/policy_data_source_test.go index ae196f5e97e..daae8e388d5 100644 --- a/internal/service/iam/policy_data_source_test.go +++ b/internal/service/iam/policy_data_source_test.go @@ -14,64 +14,35 @@ import ( func TestPolicySearchDetails(t *testing.T) { testCases := []struct { - Arn string Name string PathPrefix string Expected string }{ { - Arn: "", Name: "", PathPrefix: "", Expected: "", }, { - Arn: "arn:aws:iam::aws:policy/TestPolicy", //lintignore:AWSAT005 - Name: "", - PathPrefix: "", - Expected: "ARN: arn:aws:iam::aws:policy/TestPolicy", //lintignore:AWSAT005 - }, - { - Arn: "", Name: "tf-acc-test-policy", PathPrefix: "", Expected: "Name: tf-acc-test-policy", }, { - Arn: "", Name: "", PathPrefix: "/test-prefix/", Expected: "PathPrefix: /test-prefix/", }, { - Arn: "arn:aws:iam::aws:policy/TestPolicy", //lintignore:AWSAT005 - Name: "tf-acc-test-policy", - PathPrefix: "", - Expected: "ARN: arn:aws:iam::aws:policy/TestPolicy, Name: tf-acc-test-policy", //lintignore:AWSAT005 - }, - { - Arn: "arn:aws:iam::aws:policy/TestPolicy", //lintignore:AWSAT005 - Name: "", - PathPrefix: "/test-prefix/", - Expected: "ARN: arn:aws:iam::aws:policy/TestPolicy, PathPrefix: /test-prefix/", //lintignore:AWSAT005 - }, - { - Arn: "", Name: "tf-acc-test-policy", PathPrefix: "/test-prefix/", Expected: "Name: tf-acc-test-policy, PathPrefix: /test-prefix/", }, - { - Arn: "arn:aws:iam::aws:policy/TestPolicy", //lintignore:AWSAT005 - Name: "tf-acc-test-policy", - PathPrefix: "/test-prefix/", - Expected: "ARN: arn:aws:iam::aws:policy/TestPolicy, Name: tf-acc-test-policy, PathPrefix: /test-prefix/", //lintignore:AWSAT005 - }, } for _, testCase := range testCases { t.Run(testCase.Name, func(t *testing.T) { - got := tfiam.PolicySearchDetails(testCase.Arn, testCase.Name, testCase.PathPrefix) + got := tfiam.PolicySearchDetails(testCase.Name, testCase.PathPrefix) if got != testCase.Expected { t.Errorf("got %s, expected %s", got, testCase.Expected) @@ -83,7 +54,7 @@ func TestPolicySearchDetails(t *testing.T) { func TestAccIAMPolicyDataSource_arn(t *testing.T) { datasourceName := "data.aws_iam_policy.test" resourceName := "aws_iam_policy.test" - policyName := fmt.Sprintf("test-policy-%s", sdkacctest.RandString(10)) + policyName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -91,7 +62,33 @@ func TestAccIAMPolicyDataSource_arn(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPolicyDataSourceConfig_ARN(policyName, "/"), + Config: testAccPolicyDataSourceConfig_arn(policyName, "/"), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), + resource.TestCheckResourceAttrPair(datasourceName, "path", resourceName, "path"), + resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), + resource.TestCheckResourceAttrPair(datasourceName, "policy_id", resourceName, "policy_id"), + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + ), + }, + }, + }) +} + +func TestAccIAMPolicyDataSource_arnTags(t *testing.T) { + datasourceName := "data.aws_iam_policy.test" + resourceName := "aws_iam_policy.test" + policyName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, iam.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccPolicyDataSourceConfig_arnTags(policyName, "/"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), @@ -99,7 +96,8 @@ func TestAccIAMPolicyDataSource_arn(t *testing.T) { resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), resource.TestCheckResourceAttrPair(datasourceName, "policy_id", resourceName, "policy_id"), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), - resource.TestCheckResourceAttrPair(datasourceName, "tags", resourceName, "tags"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.key", resourceName, "tags.key"), ), }, }, @@ -109,7 +107,7 @@ func TestAccIAMPolicyDataSource_arn(t *testing.T) { func TestAccIAMPolicyDataSource_name(t *testing.T) { datasourceName := "data.aws_iam_policy.test" resourceName := "aws_iam_policy.test" - policyName := fmt.Sprintf("test-policy-%s", sdkacctest.RandString(10)) + policyName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -117,15 +115,42 @@ func TestAccIAMPolicyDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPolicyDataSourceConfig_Name(policyName, "/"), - Check: resource.ComposeTestCheckFunc( + Config: testAccPolicyDataSourceConfig_name(policyName, "/"), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), + resource.TestCheckResourceAttrPair(datasourceName, "path", resourceName, "path"), + resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), + resource.TestCheckResourceAttrPair(datasourceName, "policy_id", resourceName, "policy_id"), + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + ), + }, + }, + }) +} + +func TestAccIAMPolicyDataSource_nameTags(t *testing.T) { + datasourceName := "data.aws_iam_policy.test" + resourceName := "aws_iam_policy.test" + policyName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, iam.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccPolicyDataSourceConfig_nameTags(policyName, "/"), + Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), resource.TestCheckResourceAttrPair(datasourceName, "path", resourceName, "path"), resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), resource.TestCheckResourceAttrPair(datasourceName, "policy_id", resourceName, "policy_id"), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), - resource.TestCheckResourceAttrPair(datasourceName, "tags", resourceName, "tags"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.key", resourceName, "tags.key"), ), }, }, @@ -136,7 +161,7 @@ func TestAccIAMPolicyDataSource_nameAndPathPrefix(t *testing.T) { datasourceName := "data.aws_iam_policy.test" resourceName := "aws_iam_policy.test" - policyName := fmt.Sprintf("test-policy-%s", sdkacctest.RandString(10)) + policyName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) policyPath := "/test-path/" resource.ParallelTest(t, resource.TestCase{ @@ -145,15 +170,44 @@ func TestAccIAMPolicyDataSource_nameAndPathPrefix(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPolicyDataSourceConfig_PathPrefix(policyName, policyPath), - Check: resource.ComposeTestCheckFunc( + Config: testAccPolicyDataSourceConfig_pathPrefix(policyName, policyPath), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), + resource.TestCheckResourceAttrPair(datasourceName, "path", resourceName, "path"), + resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), + resource.TestCheckResourceAttrPair(datasourceName, "policy_id", resourceName, "policy_id"), + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + ), + }, + }, + }) +} + +func TestAccIAMPolicyDataSource_nameAndPathPrefixTags(t *testing.T) { + datasourceName := "data.aws_iam_policy.test" + resourceName := "aws_iam_policy.test" + + policyName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + policyPath := "/test-path/" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, iam.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccPolicyDataSourceConfig_pathPrefixTags(policyName, policyPath), + Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), resource.TestCheckResourceAttrPair(datasourceName, "path", resourceName, "path"), resource.TestCheckResourceAttrPair(datasourceName, "policy", resourceName, "policy"), resource.TestCheckResourceAttrPair(datasourceName, "policy_id", resourceName, "policy_id"), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), - resource.TestCheckResourceAttrPair(datasourceName, "tags", resourceName, "tags"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.key", resourceName, "tags.key"), ), }, }, @@ -161,7 +215,7 @@ func TestAccIAMPolicyDataSource_nameAndPathPrefix(t *testing.T) { } func TestAccIAMPolicyDataSource_nonExistent(t *testing.T) { - policyName := fmt.Sprintf("test-policy-%s", sdkacctest.RandString(10)) + policyName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) policyPath := "/test-path/" resource.ParallelTest(t, resource.TestCase{ @@ -170,7 +224,7 @@ func TestAccIAMPolicyDataSource_nonExistent(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPolicyDataSourceConfig_NonExistent(policyName, policyPath), + Config: testAccPolicyDataSourceConfig_nonExistent(policyName, policyPath), ExpectError: regexp.MustCompile(`no IAM policy found matching criteria`), }, }, @@ -201,27 +255,71 @@ EOF }`, policyName, policyPath) } -func testAccPolicyDataSourceConfig_ARN(policyName, policyPath string) string { +func testAccPolicyBaseDataSourceTagsConfig(policyName, policyPath string) string { + return fmt.Sprintf(` +resource "aws_iam_policy" "test" { + name = %[1]q + path = %[2]q + description = "My test policy" + + policy = < 0 && v.([]interface{})[0] != nil { - input.DestinationConfiguration.VpcConfiguration = expandVpcDestinationConfiguration(v.([]interface{})[0].(map[string]interface{})) + input.DestinationConfiguration.VpcConfiguration = expandVPCDestinationConfiguration(v.([]interface{})[0].(map[string]interface{})) } log.Printf("[INFO] Creating IoT Topic Rule Destination: %s", input) @@ -154,7 +154,7 @@ func resourceTopicRuleDestinationRead(ctx context.Context, d *schema.ResourceDat d.Set("arn", output.Arn) d.Set("enabled", aws.StringValue(output.Status) == iot.TopicRuleDestinationStatusEnabled) if output.VpcProperties != nil { - if err := d.Set("vpc_configuration", []interface{}{flattenVpcDestinationProperties(output.VpcProperties)}); err != nil { + if err := d.Set("vpc_configuration", []interface{}{flattenVPCDestinationProperties(output.VpcProperties)}); err != nil { return diag.Errorf("setting vpc_configuration: %s", err) } } else { @@ -212,7 +212,7 @@ func resourceTopicRuleDestinationDelete(ctx context.Context, d *schema.ResourceD return nil } -func expandVpcDestinationConfiguration(tfMap map[string]interface{}) *iot.VpcDestinationConfiguration { +func expandVPCDestinationConfiguration(tfMap map[string]interface{}) *iot.VpcDestinationConfiguration { if tfMap == nil { return nil } @@ -238,7 +238,7 @@ func expandVpcDestinationConfiguration(tfMap map[string]interface{}) *iot.VpcDes return apiObject } -func flattenVpcDestinationProperties(apiObject *iot.VpcDestinationProperties) map[string]interface{} { +func flattenVPCDestinationProperties(apiObject *iot.VpcDestinationProperties) map[string]interface{} { if apiObject == nil { return nil } diff --git a/internal/service/iot/topic_rule_destination_test.go b/internal/service/iot/topic_rule_destination_test.go index 322a240e6a3..0f0cab63afd 100644 --- a/internal/service/iot/topic_rule_destination_test.go +++ b/internal/service/iot/topic_rule_destination_test.go @@ -27,7 +27,7 @@ func TestAccIoTTopicRuleDestination_basic(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleDestinationConfig(rName), + Config: testAccTopicRuleDestinationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleDestinationExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "iot", regexp.MustCompile(`ruledestination/vpc/.+`)), @@ -46,7 +46,7 @@ func TestAccIoTTopicRuleDestination_basic(t *testing.T) { }, // Delete everything but the IAM Role assumed by the IoT service. { - Config: testAccTopicRuleRoleConfig(rName), + Config: testAccTopicRuleConfig_destinationRole(rName), }, }, }) @@ -63,7 +63,7 @@ func TestAccIoTTopicRuleDestination_disappears(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleDestinationConfig(rName), + Config: testAccTopicRuleDestinationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleDestinationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfiot.ResourceTopicRuleDestination(), resourceName), @@ -85,7 +85,7 @@ func TestAccIoTTopicRuleDestination_enabled(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleDestinationEnabledConfig(rName, false), + Config: testAccTopicRuleDestinationConfig_enabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleDestinationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -97,14 +97,14 @@ func TestAccIoTTopicRuleDestination_enabled(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTopicRuleDestinationEnabledConfig(rName, true), + Config: testAccTopicRuleDestinationConfig_enabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleDestinationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), ), }, { - Config: testAccTopicRuleDestinationEnabledConfig(rName, false), + Config: testAccTopicRuleDestinationConfig_enabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleDestinationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -112,7 +112,7 @@ func TestAccIoTTopicRuleDestination_enabled(t *testing.T) { }, // Delete everything but the IAM Role assumed by the IoT service. { - Config: testAccTopicRuleRoleConfig(rName), + Config: testAccTopicRuleConfig_destinationRole(rName), }, }, }) @@ -167,8 +167,8 @@ func testAccCheckTopicRuleDestinationExists(n string) resource.TestCheckFunc { func testAccTopicRuleDestinationBaseConfig(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), - testAccTopicRuleRoleConfig(rName), + acctest.ConfigVPCWithSubnets(rName, 2), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -181,7 +181,7 @@ resource "aws_security_group" "test" { `, rName)) } -func testAccTopicRuleDestinationConfig(rName string) string { +func testAccTopicRuleDestinationConfig_basic(rName string) string { return acctest.ConfigCompose(testAccTopicRuleDestinationBaseConfig(rName), ` resource "aws_iot_topic_rule_destination" "test" { vpc_configuration { @@ -194,7 +194,7 @@ resource "aws_iot_topic_rule_destination" "test" { `) } -func testAccTopicRuleDestinationEnabledConfig(rName string, enabled bool) string { +func testAccTopicRuleDestinationConfig_enabled(rName string, enabled bool) string { return acctest.ConfigCompose(testAccTopicRuleDestinationBaseConfig(rName), fmt.Sprintf(` resource "aws_iot_topic_rule_destination" "test" { enabled = %[1]t diff --git a/internal/service/iot/topic_rule_test.go b/internal/service/iot/topic_rule_test.go index 10639813279..47f68ea633f 100644 --- a/internal/service/iot/topic_rule_test.go +++ b/internal/service/iot/topic_rule_test.go @@ -35,7 +35,7 @@ func TestAccIoTTopicRule_basic(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleConfig(rName), + Config: testAccTopicRuleConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "iot", fmt.Sprintf("rule/%s", rName)), @@ -87,7 +87,7 @@ func TestAccIoTTopicRule_disappears(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleConfig(rName), + Config: testAccTopicRuleConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfiot.ResourceTopicRule(), resourceName), @@ -109,7 +109,7 @@ func TestAccIoTTopicRule_tags(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleConfigTags1(rName, "key1", "value1"), + Config: testAccTopicRuleConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -122,7 +122,7 @@ func TestAccIoTTopicRule_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTopicRuleConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTopicRuleConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -131,7 +131,7 @@ func TestAccIoTTopicRule_tags(t *testing.T) { ), }, { - Config: testAccTopicRuleConfigTags1(rName, "key2", "value2"), + Config: testAccTopicRuleConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -153,7 +153,7 @@ func TestAccIoTTopicRule_cloudWatchAlarm(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleCloudWatchAlarmConfig(rName), + Config: testAccTopicRuleConfig_cloudWatchAlarm(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "1"), @@ -204,7 +204,7 @@ func TestAccIoTTopicRule_cloudWatchLogs(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleCloudWatchLogsConfig(rName), + Config: testAccTopicRuleConfig_cloudWatchLogs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -256,7 +256,7 @@ func TestAccIoTTopicRule_cloudWatchMetric(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleCloudWatchMetricConfig(rName), + Config: testAccTopicRuleConfig_cloudWatchMetric(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -307,7 +307,7 @@ func TestAccIoTTopicRule_dynamoDB(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleDynamoDBConfig(rName), + Config: testAccTopicRuleConfig_dynamoDB(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -345,7 +345,7 @@ func TestAccIoTTopicRule_dynamoDB(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTopicRuleDynamoDBRangeKeyConfig(rName), + Config: testAccTopicRuleConfig_dynamoDBRangeKey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -396,7 +396,7 @@ func TestAccIoTTopicRule_dynamoDBv2(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleDynamoDBv2Config(rName), + Config: testAccTopicRuleConfig_dynamoDBv2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -440,7 +440,7 @@ func TestAccIoTTopicRule_elasticSearch(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleElasticsearchConfig(rName), + Config: testAccTopicRuleConfig_elasticSearch(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -490,7 +490,7 @@ func TestAccIoTTopicRule_firehose(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleFirehoseConfig(rName), + Config: testAccTopicRuleConfig_firehose(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -544,7 +544,7 @@ func TestAccIoTTopicRule_Firehose_separator(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleFirehoseSeparatorConfig(rName, "\n"), + Config: testAccTopicRuleConfig_firehoseSeparator(rName, "\n"), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -579,7 +579,7 @@ func TestAccIoTTopicRule_Firehose_separator(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTopicRuleFirehoseSeparatorConfig(rName, ","), + Config: testAccTopicRuleConfig_firehoseSeparator(rName, ","), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -623,7 +623,7 @@ func TestAccIoTTopicRule_http(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleHTTPConfig(rName), + Config: testAccTopicRuleConfig_http(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -659,7 +659,7 @@ func TestAccIoTTopicRule_http(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTopicRuleHTTPConfirmationURLConfig(rName), + Config: testAccTopicRuleConfig_httpConfirmationURL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -690,7 +690,7 @@ func TestAccIoTTopicRule_http(t *testing.T) { ), }, { - Config: testAccTopicRuleHTTPHeadersConfig(rName), + Config: testAccTopicRuleConfig_httpHeaders(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -725,7 +725,7 @@ func TestAccIoTTopicRule_http(t *testing.T) { ), }, { - Config: testAccTopicRuleHTTPErrorActionConfig(rName), + Config: testAccTopicRuleConfig_httpErrorAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -881,7 +881,7 @@ func TestAccIoTTopicRule_kafka(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleKafkaConfig(rName), + Config: testAccTopicRuleConfig_kafka(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -924,7 +924,7 @@ func TestAccIoTTopicRule_kafka(t *testing.T) { }, // Delete everything but the IAM Role assumed by the IoT service. { - Config: testAccTopicRuleRoleConfig(rName), + Config: testAccTopicRuleConfig_destinationRole(rName), }, }, }) @@ -941,7 +941,7 @@ func TestAccIoTTopicRule_kinesis(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleKinesisConfig(rName), + Config: testAccTopicRuleConfig_kinesis(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -989,7 +989,7 @@ func TestAccIoTTopicRule_lambda(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleLambdaConfig(rName), + Config: testAccTopicRuleConfig_lambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1034,7 +1034,7 @@ func TestAccIoTTopicRule_republish(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleRepublishConfig(rName), + Config: testAccTopicRuleConfig_republish(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1083,7 +1083,7 @@ func TestAccIoTTopicRule_republishWithQos(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleRepublishWithQoSConfig(rName), + Config: testAccTopicRuleConfig_republishQoS(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1132,7 +1132,7 @@ func TestAccIoTTopicRule_s3(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleS3Config(rName), + Config: testAccTopicRuleConfig_s3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1182,7 +1182,7 @@ func TestAccIoTTopicRule_sns(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleSNSConfig(rName), + Config: testAccTopicRuleConfig_sns(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1227,7 +1227,7 @@ func TestAccIoTTopicRule_sqs(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleSQSConfig(rName), + Config: testAccTopicRuleConfig_sqs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1276,7 +1276,7 @@ func TestAccIoTTopicRule_Step_functions(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleStepFunctionsConfig(rName), + Config: testAccTopicRuleConfig_stepFunctions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1325,7 +1325,7 @@ func TestAccIoTTopicRule_Timestream(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleTimestreamConfig(rName), + Config: testAccTopicRuleConfig_timestream(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1382,7 +1382,7 @@ func TestAccIoTTopicRule_errorAction(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleErrorActionConfig(rName), + Config: testAccTopicRuleConfig_errorAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1451,7 +1451,7 @@ func TestAccIoTTopicRule_updateKinesisErrorAction(t *testing.T) { CheckDestroy: testAccCheckTopicRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicRuleKinesisConfig(rName), + Config: testAccTopicRuleConfig_kinesis(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1480,7 +1480,7 @@ func TestAccIoTTopicRule_updateKinesisErrorAction(t *testing.T) { ), }, { - Config: testAccTopicRuleErrorActionConfig(rName), + Config: testAccTopicRuleConfig_errorAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cloudwatch_alarm.#", "0"), @@ -1588,7 +1588,7 @@ func testAccTopicRuleName() string { return fmt.Sprintf("tf_acc_test_%[1]s", sdkacctest.RandString(20)) } -func testAccTopicRuleRoleConfig(rName string) string { +func testAccTopicRuleConfig_destinationRole(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -1634,7 +1634,7 @@ resource "aws_iam_policy_attachment" "test" { `, rName) } -func testAccTopicRuleConfig(rName string) string { +func testAccTopicRuleConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1645,7 +1645,7 @@ resource "aws_iot_topic_rule" "test" { `, rName) } -func testAccTopicRuleConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccTopicRuleConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1660,7 +1660,7 @@ resource "aws_iot_topic_rule" "test" { `, rName, tagKey1, tagValue1) } -func testAccTopicRuleConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTopicRuleConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1676,9 +1676,9 @@ resource "aws_iot_topic_rule" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccTopicRuleCloudWatchAlarmConfig(rName string) string { +func testAccTopicRuleConfig_cloudWatchAlarm(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1697,9 +1697,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleCloudWatchLogsConfig(rName string) string { +func testAccTopicRuleConfig_cloudWatchLogs(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1720,9 +1720,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleCloudWatchMetricConfig(rName string) string { +func testAccTopicRuleConfig_cloudWatchMetric(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1741,9 +1741,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleDynamoDBConfig(rName string) string { +func testAccTopicRuleConfig_dynamoDB(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1763,9 +1763,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleDynamoDBRangeKeyConfig(rName string) string { +func testAccTopicRuleConfig_dynamoDBRangeKey(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1789,9 +1789,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleDynamoDBv2Config(rName string) string { +func testAccTopicRuleConfig_dynamoDBv2(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1810,9 +1810,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleElasticsearchConfig(rName string) string { +func testAccTopicRuleConfig_elasticSearch(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` data "aws_region" "current" {} @@ -1833,9 +1833,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleFirehoseConfig(rName string) string { +func testAccTopicRuleConfig_firehose(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1861,9 +1861,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleFirehoseSeparatorConfig(rName, separator string) string { +func testAccTopicRuleConfig_firehoseSeparator(rName, separator string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1881,7 +1881,7 @@ resource "aws_iot_topic_rule" "test" { `, rName, separator)) } -func testAccTopicRuleHTTPConfig(rName string) string { +func testAccTopicRuleConfig_http(rName string) string { return fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1896,7 +1896,7 @@ resource "aws_iot_topic_rule" "test" { `, rName) } -func testAccTopicRuleHTTPConfirmationURLConfig(rName string) string { +func testAccTopicRuleConfig_httpConfirmationURL(rName string) string { return fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1912,7 +1912,7 @@ resource "aws_iot_topic_rule" "test" { `, rName) } -func testAccTopicRuleHTTPHeadersConfig(rName string) string { +func testAccTopicRuleConfig_httpHeaders(rName string) string { return fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1937,7 +1937,7 @@ resource "aws_iot_topic_rule" "test" { `, rName) } -func testAccTopicRuleHTTPErrorActionConfig(rName string) string { +func testAccTopicRuleConfig_httpErrorAction(rName string) string { return fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1960,7 +1960,7 @@ resource "aws_iot_topic_rule" "test" { func testAccTopicRuleConfig_analytics(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1978,7 +1978,7 @@ resource "aws_iot_topic_rule" "test" { func testAccTopicRuleConfig_events(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -1995,9 +1995,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleKafkaConfig(rName string) string { +func testAccTopicRuleConfig_kafka(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleDestinationConfig(rName), + testAccTopicRuleDestinationConfig_basic(rName), fmt.Sprintf(` data "aws_region" "current" {} @@ -2026,9 +2026,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleKinesisConfig(rName string) string { +func testAccTopicRuleConfig_kinesis(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -2044,7 +2044,7 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleLambdaConfig(rName string) string { +func testAccTopicRuleConfig_lambda(rName string) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -2063,9 +2063,9 @@ resource "aws_iot_topic_rule" "test" { `, rName) } -func testAccTopicRuleRepublishConfig(rName string) string { +func testAccTopicRuleConfig_republish(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -2081,9 +2081,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleRepublishWithQoSConfig(rName string) string { +func testAccTopicRuleConfig_republishQoS(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -2100,9 +2100,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleS3Config(rName string) string { +func testAccTopicRuleConfig_s3(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -2120,9 +2120,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleSNSConfig(rName string) string { +func testAccTopicRuleConfig_sns(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` data "aws_region" "current" {} @@ -2140,9 +2140,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleSQSConfig(rName string) string { +func testAccTopicRuleConfig_sqs(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -2159,9 +2159,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleStepFunctionsConfig(rName string) string { +func testAccTopicRuleConfig_stepFunctions(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -2178,9 +2178,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleTimestreamConfig(rName string) string { +func testAccTopicRuleConfig_timestream(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q @@ -2207,9 +2207,9 @@ resource "aws_iot_topic_rule" "test" { `, rName)) } -func testAccTopicRuleErrorActionConfig(rName string) string { +func testAccTopicRuleConfig_errorAction(rName string) string { return acctest.ConfigCompose( - testAccTopicRuleRoleConfig(rName), + testAccTopicRuleConfig_destinationRole(rName), fmt.Sprintf(` resource "aws_iot_topic_rule" "test" { name = %[1]q diff --git a/internal/service/kafka/broker_nodes_data_source_test.go b/internal/service/kafka/broker_nodes_data_source_test.go index 7639e0649ef..b0bca0edac4 100644 --- a/internal/service/kafka/broker_nodes_data_source_test.go +++ b/internal/service/kafka/broker_nodes_data_source_test.go @@ -22,7 +22,7 @@ func TestAccKafkaBrokerNodesDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerNodesDataSourceConfig(rName), + Config: testAccBrokerNodesDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "cluster_arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "node_info_list.#", resourceName, "number_of_broker_nodes"), @@ -34,7 +34,7 @@ func TestAccKafkaBrokerNodesDataSource_basic(t *testing.T) { }, }) } -func testAccBrokerNodesDataSourceConfig(rName string) string { +func testAccBrokerNodesDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q diff --git a/internal/service/kafka/cluster.go b/internal/service/kafka/cluster.go index b111a121112..64dace2a790 100644 --- a/internal/service/kafka/cluster.go +++ b/internal/service/kafka/cluster.go @@ -2,6 +2,7 @@ package kafka import ( "context" + "fmt" "log" "time" @@ -641,6 +642,33 @@ func resourceClusterRead(ctx context.Context, d *schema.ResourceData, meta inter func resourceClusterUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { conn := meta.(*conns.AWSClient).KafkaConn + if d.HasChange("broker_node_group_info.0.instance_type") { + input := &kafka.UpdateBrokerTypeInput{ + ClusterArn: aws.String(d.Id()), + CurrentVersion: aws.String(d.Get("current_version").(string)), + TargetInstanceType: aws.String(d.Get("broker_node_group_info.0.instance_type").(string)), + } + + output, err := conn.UpdateBrokerTypeWithContext(ctx, input) + + if err != nil { + return diag.Errorf("updating MSK Cluster (%s) broker type: %s", d.Id(), err) + } + + clusterOperationARN := aws.StringValue(output.ClusterOperationArn) + + _, err = waitClusterOperationCompleted(ctx, conn, clusterOperationARN, d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return diag.Errorf("waiting for MSK Cluster (%s) operation (%s): %s", d.Id(), clusterOperationARN, err) + } + + // refresh the current_version attribute after each update + if err := refreshClusterVersion(ctx, d, meta); err != nil { + return diag.FromErr(err) + } + } + if d.HasChanges("broker_node_group_info.0.ebs_volume_size", "broker_node_group_info.0.storage_info") { input := &kafka.UpdateBrokerStorageInput{ ClusterArn: aws.String(d.Id()), @@ -688,6 +716,11 @@ func resourceClusterUpdate(ctx context.Context, d *schema.ResourceData, meta int return diag.Errorf("waiting for MSK Cluster (%s) operation (%s): %s", d.Id(), clusterOperationARN, err) } } + + // refresh the current_version attribute after each update + if err := refreshClusterVersion(ctx, d, meta); err != nil { + return diag.FromErr(err) + } } if d.HasChange("broker_node_group_info.0.connectivity_info") { @@ -713,27 +746,10 @@ func resourceClusterUpdate(ctx context.Context, d *schema.ResourceData, meta int if err != nil { return diag.Errorf("waiting for MSK Cluster (%s) operation (%s): %s", d.Id(), clusterOperationARN, err) } - } - - if d.HasChange("broker_node_group_info.0.instance_type") { - input := &kafka.UpdateBrokerTypeInput{ - ClusterArn: aws.String(d.Id()), - CurrentVersion: aws.String(d.Get("current_version").(string)), - TargetInstanceType: aws.String(d.Get("broker_node_group_info.0.instance_type").(string)), - } - output, err := conn.UpdateBrokerTypeWithContext(ctx, input) - - if err != nil { - return diag.Errorf("updating MSK Cluster (%s) broker type: %s", d.Id(), err) - } - - clusterOperationARN := aws.StringValue(output.ClusterOperationArn) - - _, err = waitClusterOperationCompleted(ctx, conn, clusterOperationARN, d.Timeout(schema.TimeoutUpdate)) - - if err != nil { - return diag.Errorf("waiting for MSK Cluster (%s) operation (%s): %s", d.Id(), clusterOperationARN, err) + // refresh the current_version attribute after each update + if err := refreshClusterVersion(ctx, d, meta); err != nil { + return diag.FromErr(err) } } @@ -757,6 +773,11 @@ func resourceClusterUpdate(ctx context.Context, d *schema.ResourceData, meta int if err != nil { return diag.Errorf("waiting for MSK Cluster (%s) operation (%s): %s", d.Id(), clusterOperationARN, err) } + + // refresh the current_version attribute after each update + if err := refreshClusterVersion(ctx, d, meta); err != nil { + return diag.FromErr(err) + } } if d.HasChanges("enhanced_monitoring", "logging_info", "open_monitoring") { @@ -787,6 +808,11 @@ func resourceClusterUpdate(ctx context.Context, d *schema.ResourceData, meta int if err != nil { return diag.Errorf("waiting for MSK Cluster (%s) operation (%s): %s", d.Id(), clusterOperationARN, err) } + + // refresh the current_version attribute after each update + if err := refreshClusterVersion(ctx, d, meta); err != nil { + return diag.FromErr(err) + } } if d.HasChange("configuration_info") && !d.HasChange("kafka_version") { @@ -812,6 +838,11 @@ func resourceClusterUpdate(ctx context.Context, d *schema.ResourceData, meta int if err != nil { return diag.Errorf("waiting for MSK Cluster (%s) operation (%s): %s", d.Id(), clusterOperationARN, err) } + + // refresh the current_version attribute after each update + if err := refreshClusterVersion(ctx, d, meta); err != nil { + return diag.FromErr(err) + } } if d.HasChange("kafka_version") { @@ -840,6 +871,11 @@ func resourceClusterUpdate(ctx context.Context, d *schema.ResourceData, meta int if err != nil { return diag.Errorf("waiting for MSK Cluster (%s) operation (%s): %s", d.Id(), clusterOperationARN, err) } + + // refresh the current_version attribute after each update + if err := refreshClusterVersion(ctx, d, meta); err != nil { + return diag.FromErr(err) + } } if d.HasChanges("encryption_info", "client_authentication") { @@ -879,6 +915,11 @@ func resourceClusterUpdate(ctx context.Context, d *schema.ResourceData, meta int if err != nil { return diag.Errorf("waiting for MSK Cluster (%s) operation (%s): %s", d.Id(), clusterOperationARN, err) } + + // refresh the current_version attribute after each update + if err := refreshClusterVersion(ctx, d, meta); err != nil { + return diag.FromErr(err) + } } if d.HasChange("tags_all") { @@ -932,7 +973,7 @@ func expandBrokerNodeGroupInfo(tfMap map[string]interface{}) *kafka.BrokerNodeGr apiObject.ClientSubnets = flex.ExpandStringSet(v) } - if v, ok := tfMap["connectivity_info"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["connectivity_info"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.ConnectivityInfo = expandConnectivityInfo(v[0].(map[string]interface{})) } @@ -952,7 +993,7 @@ func expandBrokerNodeGroupInfo(tfMap map[string]interface{}) *kafka.BrokerNodeGr } } - if v, ok := tfMap["storage_info"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["storage_info"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.StorageInfo = expandStorageInfo(v[0].(map[string]interface{})) } @@ -966,7 +1007,7 @@ func expandConnectivityInfo(tfMap map[string]interface{}) *kafka.ConnectivityInf apiObject := &kafka.ConnectivityInfo{} - if v, ok := tfMap["public_access"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["public_access"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.PublicAccess = expandPublicAccess(v[0].(map[string]interface{})) } @@ -980,21 +1021,21 @@ func expandStorageInfo(tfMap map[string]interface{}) *kafka.StorageInfo { apiObject := &kafka.StorageInfo{} - if v, ok := tfMap["ebs_storage_info"].([]interface{}); ok && len(v) > 0 { - apiObject.EbsStorageInfo = expandEbsStorageInfo(v[0].(map[string]interface{})) + if v, ok := tfMap["ebs_storage_info"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + apiObject.EbsStorageInfo = expandEBSStorageInfo(v[0].(map[string]interface{})) } return apiObject } -func expandEbsStorageInfo(tfMap map[string]interface{}) *kafka.EBSStorageInfo { +func expandEBSStorageInfo(tfMap map[string]interface{}) *kafka.EBSStorageInfo { if tfMap == nil { return nil } apiObject := &kafka.EBSStorageInfo{} - if v, ok := tfMap["provisioned_throughput"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["provisioned_throughput"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.ProvisionedThroughput = expandProvisionedThroughput(v[0].(map[string]interface{})) } @@ -1044,12 +1085,12 @@ func expandClientAuthentication(tfMap map[string]interface{}) *kafka.ClientAuthe apiObject := &kafka.ClientAuthentication{} - if v, ok := tfMap["sasl"].([]interface{}); ok && len(v) > 0 { - apiObject.Sasl = expandSasl(v[0].(map[string]interface{})) + if v, ok := tfMap["sasl"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + apiObject.Sasl = expandSASL(v[0].(map[string]interface{})) } - if v, ok := tfMap["tls"].([]interface{}); ok && len(v) > 0 { - apiObject.Tls = expandTls(v[0].(map[string]interface{})) + if v, ok := tfMap["tls"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + apiObject.Tls = expandTLS(v[0].(map[string]interface{})) } if v, ok := tfMap["unauthenticated"].(bool); ok { @@ -1061,7 +1102,7 @@ func expandClientAuthentication(tfMap map[string]interface{}) *kafka.ClientAuthe return apiObject } -func expandSasl(tfMap map[string]interface{}) *kafka.Sasl { +func expandSASL(tfMap map[string]interface{}) *kafka.Sasl { if tfMap == nil { return nil } @@ -1083,7 +1124,7 @@ func expandSasl(tfMap map[string]interface{}) *kafka.Sasl { return apiObject } -func expandTls(tfMap map[string]interface{}) *kafka.Tls { +func expandTLS(tfMap map[string]interface{}) *kafka.Tls { if tfMap == nil { return nil } @@ -1125,7 +1166,7 @@ func expandEncryptionInfo(tfMap map[string]interface{}) *kafka.EncryptionInfo { apiObject := &kafka.EncryptionInfo{} - if v, ok := tfMap["encryption_in_transit"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["encryption_in_transit"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.EncryptionInTransit = expandEncryptionInTransit(v[0].(map[string]interface{})) } @@ -1163,7 +1204,7 @@ func expandLoggingInfo(tfMap map[string]interface{}) *kafka.LoggingInfo { apiObject := &kafka.LoggingInfo{} - if v, ok := tfMap["broker_logs"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["broker_logs"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.BrokerLogs = expandBrokerLogs(v[0].(map[string]interface{})) } @@ -1177,15 +1218,15 @@ func expandBrokerLogs(tfMap map[string]interface{}) *kafka.BrokerLogs { apiObject := &kafka.BrokerLogs{} - if v, ok := tfMap["cloudwatch_logs"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["cloudwatch_logs"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.CloudWatchLogs = expandCloudWatchLogs(v[0].(map[string]interface{})) } - if v, ok := tfMap["firehose"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["firehose"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.Firehose = expandFirehose(v[0].(map[string]interface{})) } - if v, ok := tfMap["s3"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["s3"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.S3 = expandS3(v[0].(map[string]interface{})) } @@ -1257,7 +1298,7 @@ func expandOpenMonitoringInfo(tfMap map[string]interface{}) *kafka.OpenMonitorin apiObject := &kafka.OpenMonitoringInfo{} - if v, ok := tfMap["prometheus"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["prometheus"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.Prometheus = expandPrometheusInfo(v[0].(map[string]interface{})) } @@ -1271,11 +1312,11 @@ func expandPrometheusInfo(tfMap map[string]interface{}) *kafka.PrometheusInfo { apiObject := &kafka.PrometheusInfo{} - if v, ok := tfMap["jmx_exporter"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["jmx_exporter"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.JmxExporter = expandJmxExporterInfo(v[0].(map[string]interface{})) } - if v, ok := tfMap["node_exporter"].([]interface{}); ok && len(v) > 0 { + if v, ok := tfMap["node_exporter"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.NodeExporter = expandNodeExporterInfo(v[0].(map[string]interface{})) } @@ -1374,13 +1415,13 @@ func flattenStorageInfo(apiObject *kafka.StorageInfo) []interface{} { tfMap := map[string]interface{}{} if v := apiObject.EbsStorageInfo; v != nil { - tfMap["ebs_storage_info"] = flattenEbsStorageInfo(v) + tfMap["ebs_storage_info"] = flattenEBSStorageInfo(v) } return []interface{}{tfMap} } -func flattenEbsStorageInfo(apiObject *kafka.EBSStorageInfo) []interface{} { +func flattenEBSStorageInfo(apiObject *kafka.EBSStorageInfo) []interface{} { if apiObject == nil { return nil } @@ -1438,11 +1479,11 @@ func flattenClientAuthentication(apiObject *kafka.ClientAuthentication) map[stri tfMap := map[string]interface{}{} if v := apiObject.Sasl; v != nil { - tfMap["sasl"] = []interface{}{flattenSasl(v)} + tfMap["sasl"] = []interface{}{flattenSASL(v)} } if v := apiObject.Tls; v != nil { - tfMap["tls"] = []interface{}{flattenTls(v)} + tfMap["tls"] = []interface{}{flattenTLS(v)} } if v := apiObject.Unauthenticated; v != nil { @@ -1454,7 +1495,7 @@ func flattenClientAuthentication(apiObject *kafka.ClientAuthentication) map[stri return tfMap } -func flattenSasl(apiObject *kafka.Sasl) map[string]interface{} { +func flattenSASL(apiObject *kafka.Sasl) map[string]interface{} { if apiObject == nil { return nil } @@ -1476,7 +1517,7 @@ func flattenSasl(apiObject *kafka.Sasl) map[string]interface{} { return tfMap } -func flattenTls(apiObject *kafka.Tls) map[string]interface{} { +func flattenTLS(apiObject *kafka.Tls) map[string]interface{} { if apiObject == nil { return nil } @@ -1699,3 +1740,17 @@ func flattenNodeExporter(apiObject *kafka.NodeExporter) map[string]interface{} { return tfMap } + +func refreshClusterVersion(ctx context.Context, d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).KafkaConn + + cluster, err := FindClusterByARN(ctx, conn, d.Id()) + + if err != nil { + return fmt.Errorf("reading MSK Cluster (%s): %w", d.Id(), err) + } + + d.Set("current_version", cluster.CurrentVersion) + + return nil +} diff --git a/internal/service/kafka/cluster_data_source_test.go b/internal/service/kafka/cluster_data_source_test.go index de091e2fd0d..407c2b88f35 100644 --- a/internal/service/kafka/cluster_data_source_test.go +++ b/internal/service/kafka/cluster_data_source_test.go @@ -22,7 +22,7 @@ func TestAccKafkaClusterDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterDataSourceConfig(rName), + Config: testAccClusterDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "bootstrap_brokers", resourceName, "bootstrap_brokers"), @@ -44,7 +44,7 @@ func TestAccKafkaClusterDataSource_basic(t *testing.T) { }) } -func testAccClusterDataSourceConfig(rName string) string { +func testAccClusterDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q diff --git a/internal/service/kafka/cluster_test.go b/internal/service/kafka/cluster_test.go index f16f6520120..8fbd6682936 100644 --- a/internal/service/kafka/cluster_test.go +++ b/internal/service/kafka/cluster_test.go @@ -22,27 +22,27 @@ import ( ) const ( - mskClusterPortPlaintext = 9092 - mskClusterPortSaslIam = 9098 - mskClusterPortSaslIamPublic = 9198 - mskClusterPortSaslScram = 9096 - mskClusterPortTls = 9094 + clusterPortPlaintext = 9092 + clusterPortSASLIAM = 9098 + clusterPortSASLIAMPublic = 9198 + clusterPortSASLScram = 9096 + clusterPortTLS = 9094 - mskClusterPortZookeeper = 2181 + clusterPortZookeeper = 2181 ) const ( - mskClusterBrokerRegexpFormat = `^(([-\w]+\.){1,}[\w]+:%[1]d,){2,}([-\w]+\.){1,}[\w]+:%[1]d+$` + clusterBrokerRegexpFormat = `^(([-\w]+\.){1,}[\w]+:%[1]d,){2,}([-\w]+\.){1,}[\w]+:%[1]d+$` ) var ( - mskClusterBoostrapBrokersRegexp = regexp.MustCompile(fmt.Sprintf(mskClusterBrokerRegexpFormat, mskClusterPortPlaintext)) - mskClusterBoostrapBrokersSaslIamRegexp = regexp.MustCompile(fmt.Sprintf(mskClusterBrokerRegexpFormat, mskClusterPortSaslIam)) - mskClusterBoostrapBrokersSaslIamPublicRegexp = regexp.MustCompile(fmt.Sprintf(mskClusterBrokerRegexpFormat, mskClusterPortSaslIamPublic)) - mskClusterBoostrapBrokersSaslScramRegexp = regexp.MustCompile(fmt.Sprintf(mskClusterBrokerRegexpFormat, mskClusterPortSaslScram)) - mskClusterBoostrapBrokersTlsRegexp = regexp.MustCompile(fmt.Sprintf(mskClusterBrokerRegexpFormat, mskClusterPortTls)) + clusterBoostrapBrokersRegexp = regexp.MustCompile(fmt.Sprintf(clusterBrokerRegexpFormat, clusterPortPlaintext)) + clusterBoostrapBrokersSASLIAMRegexp = regexp.MustCompile(fmt.Sprintf(clusterBrokerRegexpFormat, clusterPortSASLIAM)) + clusterBoostrapBrokersSASLIAMPublicRegexp = regexp.MustCompile(fmt.Sprintf(clusterBrokerRegexpFormat, clusterPortSASLIAMPublic)) + clusterBoostrapBrokersSASLScramRegexp = regexp.MustCompile(fmt.Sprintf(clusterBrokerRegexpFormat, clusterPortSASLScram)) + clusterBoostrapBrokersTLSRegexp = regexp.MustCompile(fmt.Sprintf(clusterBrokerRegexpFormat, clusterPortTLS)) - mskClusterZookeeperConnectStringRegexp = regexp.MustCompile(fmt.Sprintf(mskClusterBrokerRegexpFormat, mskClusterPortZookeeper)) + clusterZookeeperConnectStringRegexp = regexp.MustCompile(fmt.Sprintf(clusterBrokerRegexpFormat, clusterPortZookeeper)) ) func TestAccKafkaCluster_basic(t *testing.T) { @@ -57,7 +57,7 @@ func TestAccKafkaCluster_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kafka", regexp.MustCompile(`cluster/.+$`)), @@ -66,7 +66,7 @@ func TestAccKafkaCluster_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_sasl_scram", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_tls", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", mskClusterBoostrapBrokersTlsRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", clusterBoostrapBrokersTLSRegexp), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers_tls"), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.0.az_distribution", kafka.BrokerAZDistributionDefault), @@ -93,7 +93,7 @@ func TestAccKafkaCluster_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "kafka_version", "2.7.1"), resource.TestCheckResourceAttr(resourceName, "number_of_broker_nodes", "3"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestMatchResourceAttr(resourceName, "zookeeper_connect_string", mskClusterZookeeperConnectStringRegexp), + resource.TestMatchResourceAttr(resourceName, "zookeeper_connect_string", clusterZookeeperConnectStringRegexp), testAccCheckResourceAttrIsSortedCSV(resourceName, "zookeeper_connect_string"), testAccCheckResourceAttrIsSortedCSV(resourceName, "zookeeper_connect_string_tls"), ), @@ -122,7 +122,7 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_ebsVolumeSize(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterDeprecatedBrokerNodeGroupInfoEbsVolumeSizeConfig(rName, 11), + Config: testAccClusterConfig_deprecatedBrokerNodeGroupInfoEBSVolumeSize(rName, 11), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), @@ -139,7 +139,7 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_ebsVolumeSize(t *testing.T) { }, { // BadRequestException: The minimum increase in storage size of the cluster should be atleast 100GB - Config: testAccClusterDeprecatedBrokerNodeGroupInfoEbsVolumeSizeConfig(rName, 112), + Config: testAccClusterConfig_deprecatedBrokerNodeGroupInfoEBSVolumeSize(rName, 112), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -165,7 +165,7 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_storageInfo(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterBrokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputNotEnabledConfig(rName, original_volume_size, "kafka.m5.4xlarge"), + Config: testAccClusterConfig_brokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputNotEnabled(rName, original_volume_size, "kafka.m5.4xlarge"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), @@ -187,7 +187,7 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_storageInfo(t *testing.T) { }, { // update broker_node_group_info.0.storage_info.0.ebs_storage_info.0.volume_size - Config: testAccClusterBrokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputEnabledConfig(rName, updated_volume_size, "kafka.m5.4xlarge"), + Config: testAccClusterConfig_brokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputEnabled(rName, updated_volume_size, "kafka.m5.4xlarge"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -205,7 +205,7 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_storageInfo(t *testing.T) { }) } -func TestAccKafkaCluster_BrokerNodeGroupInfo_modifyEbsVolumeSizeToStorageInfo(t *testing.T) { +func TestAccKafkaCluster_BrokerNodeGroupInfo_modifyEBSVolumeSizeToStorageInfo(t *testing.T) { var cluster1, cluster2 kafka.ClusterInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_msk_cluster.test" @@ -220,7 +220,7 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_modifyEbsVolumeSizeToStorageInfo(t Steps: []resource.TestStep{ { // init with the deprecated ebs_volume_size - Config: testAccClusterDeprecatedBrokerNodeGroupInfoEbsVolumeSizeConfig(rName, original_volume_size), + Config: testAccClusterConfig_deprecatedBrokerNodeGroupInfoEBSVolumeSize(rName, original_volume_size), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), @@ -229,23 +229,12 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_modifyEbsVolumeSizeToStorageInfo(t }, { // refactor deprecated ebs_volume_size to storage_info - Config: testAccClusterBrokerNodeGroupInfoStorageInfoVolumeSizeOnlyConfig(rName, original_volume_size, "kafka.m5.large"), + Config: testAccClusterConfig_brokerNodeGroupInfoStorageInfoVolumeSizeOnly(rName, original_volume_size, "kafka.m5.large"), PlanOnly: true, }, { - // upgrade the instance type first. Multiple updates would cause a "The version of the cluster isn’t current. Check the current version and try again." error - Config: testAccClusterBrokerNodeGroupInfoStorageInfoVolumeSizeOnlyConfig(rName, original_volume_size, "kafka.m5.4xlarge"), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckClusterExists(resourceName, &cluster1), - resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), - resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.0.storage_info.#", "1"), - resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.0.storage_info.0.ebs_storage_info.#", "1"), - resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.0.storage_info.0.ebs_storage_info.0.volume_size", strconv.Itoa(original_volume_size)), - ), - }, - { - // update storage and enable provisioned throughput - Config: testAccClusterBrokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputEnabledConfig(rName, updated_volume_size, "kafka.m5.4xlarge"), + // upgrade the instance type, update storage, and enable provisioned throughput + Config: testAccClusterConfig_brokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputEnabled(rName, updated_volume_size, "kafka.m5.4xlarge"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -274,7 +263,7 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_instanceType(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterBrokerNodeGroupInfoInstanceTypeConfig(rName, "kafka.t3.small"), + Config: testAccClusterConfig_brokerNodeGroupInfoInstanceType(rName, "kafka.t3.small"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), @@ -292,7 +281,7 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_instanceType(t *testing.T) { }, }, { - Config: testAccClusterBrokerNodeGroupInfoInstanceTypeConfig(rName, "kafka.m5.large"), + Config: testAccClusterConfig_brokerNodeGroupInfoInstanceType(rName, "kafka.m5.large"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -304,7 +293,7 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_instanceType(t *testing.T) { }) } -func TestAccKafkaCluster_BrokerNodeGroupInfo_publicAccessSaslIam(t *testing.T) { +func TestAccKafkaCluster_BrokerNodeGroupInfo_publicAccessSASLIAM(t *testing.T) { var cluster1 kafka.ClusterInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_msk_cluster.test" @@ -316,14 +305,14 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_publicAccessSaslIam(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterBrokerNodeGroupInfoNoPublicAccessSaslIamConfig(rName), + Config: testAccClusterConfig_brokerNodeGroupInfoNoPublicAccessSASLIAM(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_sasl_iam", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_sasl_scram", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_tls", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_iam", mskClusterBoostrapBrokersSaslIamRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_iam", clusterBoostrapBrokersSASLIAMRegexp), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_tls", ""), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), @@ -336,14 +325,14 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_publicAccessSaslIam(t *testing.T) { ), }, { - Config: testAccClusterBrokerNodeGroupInfoPublicAccessSaslIamConfig(rName, "SERVICE_PROVIDED_EIPS"), + Config: testAccClusterConfig_brokerNodeGroupInfoPublicAccessSASLIAM(rName, "SERVICE_PROVIDED_EIPS"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_public_sasl_iam", mskClusterBoostrapBrokersSaslIamPublicRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_public_sasl_iam", clusterBoostrapBrokersSASLIAMPublicRegexp), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_sasl_scram", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_tls", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_iam", mskClusterBoostrapBrokersSaslIamRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_iam", clusterBoostrapBrokersSASLIAMRegexp), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_tls", ""), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), @@ -353,14 +342,14 @@ func TestAccKafkaCluster_BrokerNodeGroupInfo_publicAccessSaslIam(t *testing.T) { ), }, { - Config: testAccClusterBrokerNodeGroupInfoPublicAccessSaslIamConfig(rName, "DISABLED"), + Config: testAccClusterConfig_brokerNodeGroupInfoPublicAccessSASLIAM(rName, "DISABLED"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_sasl_iam", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_sasl_scram", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_public_tls", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_iam", mskClusterBoostrapBrokersSaslIamRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_iam", clusterBoostrapBrokersSASLIAMRegexp), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_tls", ""), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), @@ -385,7 +374,7 @@ func TestAccKafkaCluster_ClientAuthenticationSASL_scram(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterClientAuthenticationSaslScramConfig(rName, true), + Config: testAccClusterConfig_clientAuthenticationSASLScram(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "client_authentication.#", "1"), @@ -395,7 +384,7 @@ func TestAccKafkaCluster_ClientAuthenticationSASL_scram(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "client_authentication.0.tls.#", "0"), resource.TestCheckResourceAttr(resourceName, "client_authentication.0.unauthenticated", "false"), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", mskClusterBoostrapBrokersSaslScramRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", clusterBoostrapBrokersSASLScramRegexp), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_tls", ""), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers_sasl_scram"), ), @@ -409,7 +398,7 @@ func TestAccKafkaCluster_ClientAuthenticationSASL_scram(t *testing.T) { }, }, { - Config: testAccClusterClientAuthenticationSaslScramConfig(rName, false), + Config: testAccClusterConfig_clientAuthenticationSASLScram(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -421,7 +410,7 @@ func TestAccKafkaCluster_ClientAuthenticationSASL_scram(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "client_authentication.0.unauthenticated", "true"), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", mskClusterBoostrapBrokersTlsRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", clusterBoostrapBrokersTLSRegexp), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers_tls"), ), }, @@ -449,7 +438,7 @@ func TestAccKafkaCluster_ClientAuthenticationSASL_iam(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterClientAuthenticationSaslIamConfig(rName, true), + Config: testAccClusterConfig_clientAuthenticationSASLIAM(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "client_authentication.#", "1"), @@ -459,7 +448,7 @@ func TestAccKafkaCluster_ClientAuthenticationSASL_iam(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "client_authentication.0.tls.#", "0"), resource.TestCheckResourceAttr(resourceName, "client_authentication.0.unauthenticated", "false"), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_iam", mskClusterBoostrapBrokersSaslIamRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_sasl_iam", clusterBoostrapBrokersSASLIAMRegexp), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_tls", ""), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers_sasl_iam"), ), @@ -473,7 +462,7 @@ func TestAccKafkaCluster_ClientAuthenticationSASL_iam(t *testing.T) { }, }, { - Config: testAccClusterClientAuthenticationSaslIamConfig(rName, false), + Config: testAccClusterConfig_clientAuthenticationSASLIAM(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -485,7 +474,7 @@ func TestAccKafkaCluster_ClientAuthenticationSASL_iam(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "client_authentication.0.unauthenticated", "true"), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_iam", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", mskClusterBoostrapBrokersTlsRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", clusterBoostrapBrokersTLSRegexp), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers_tls"), ), }, @@ -517,14 +506,14 @@ func TestAccKafkaCluster_ClientAuthenticationTLS_certificateAuthorityARNs(t *tes Steps: []resource.TestStep{ // We need to create and activate the CA before creating the MSK cluster. { - Config: testAccClusterRootCAConfig(commonName), + Config: testAccClusterConfig_rootCA(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(acmCAResourceName, &ca), acctest.CheckACMPCACertificateAuthorityActivateRootCA(&ca), ), }, { - Config: testAccClusterClientAuthenticationTlsCertificateAuthorityArnsConfig(rName, commonName), + Config: testAccClusterConfig_clientAuthenticationTLSCertificateAuthorityARNs(rName, commonName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "client_authentication.#", "1"), @@ -550,7 +539,7 @@ func TestAccKafkaCluster_ClientAuthenticationTLS_certificateAuthorityARNs(t *tes }, }, { - Config: testAccClusterClientAuthenticationTlsCertificateAuthorityArnsConfig(rName, commonName), + Config: testAccClusterConfig_clientAuthenticationTLSCertificateAuthorityARNs(rName, commonName), Check: resource.ComposeTestCheckFunc( // CA must be DISABLED for deletion. acctest.CheckACMPCACertificateAuthorityDisableCA(&ca), @@ -577,14 +566,14 @@ func TestAccKafkaCluster_ClientAuthenticationTLS_initiallyNoAuthentication(t *te Steps: []resource.TestStep{ // We need to create and activate the CA before creating the MSK cluster. { - Config: testAccClusterRootCAConfig(commonName), + Config: testAccClusterConfig_rootCA(commonName), Check: resource.ComposeTestCheckFunc( acctest.CheckACMPCACertificateAuthorityExists(acmCAResourceName, &ca), acctest.CheckACMPCACertificateAuthorityActivateRootCA(&ca), ), }, { - Config: testAccClusterRootCANoClientAuthenticationConfig(rName, commonName), + Config: testAccClusterConfig_rootCANoClientAuthentication(rName, commonName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "client_authentication.#", "0"), @@ -603,7 +592,7 @@ func TestAccKafkaCluster_ClientAuthenticationTLS_initiallyNoAuthentication(t *te }, }, { - Config: testAccClusterClientAuthenticationTlsCertificateAuthorityArnsConfig(rName, commonName), + Config: testAccClusterConfig_clientAuthenticationTLSCertificateAuthorityARNs(rName, commonName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -622,7 +611,7 @@ func TestAccKafkaCluster_ClientAuthenticationTLS_initiallyNoAuthentication(t *te ), }, { - Config: testAccClusterClientAuthenticationTlsCertificateAuthorityArnsConfig(rName, commonName), + Config: testAccClusterConfig_clientAuthenticationTLSCertificateAuthorityARNs(rName, commonName), Check: resource.ComposeTestCheckFunc( // CA must be DISABLED for deletion. acctest.CheckACMPCACertificateAuthorityDisableCA(&ca), @@ -647,7 +636,7 @@ func TestAccKafkaCluster_Info_revision(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfigurationInfoRevision1Config(rName), + Config: testAccClusterConfig_configurationInfoRevision1(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "configuration_info.#", "1"), @@ -664,7 +653,7 @@ func TestAccKafkaCluster_Info_revision(t *testing.T) { }, }, { - Config: testAccClusterConfigurationInfoRevision2Config(rName), + Config: testAccClusterConfig_configurationInfoRevision2(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -689,7 +678,7 @@ func TestAccKafkaCluster_EncryptionInfo_encryptionAtRestKMSKeyARN(t *testing.T) CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEncryptionInfoEncryptionAtRestKmsKeyArnConfig(rName), + Config: testAccClusterConfig_encryptionInfoEncryptionAtRestKMSKeyARN(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttrPair(resourceName, "encryption_info.0.encryption_at_rest_kms_key_arn", "aws_kms_key.example_key", "arn"), @@ -719,13 +708,13 @@ func TestAccKafkaCluster_EncryptionInfoEncryptionInTransit_clientBroker(t *testi CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEncryptionInfoEncryptionInTransitClientBrokerConfig(rName, "PLAINTEXT"), + Config: testAccClusterConfig_encryptionInfoEncryptionInTransitClientBroker(rName, "PLAINTEXT"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "encryption_info.#", "1"), resource.TestCheckResourceAttr(resourceName, "encryption_info.0.encryption_in_transit.#", "1"), resource.TestCheckResourceAttr(resourceName, "encryption_info.0.encryption_in_transit.0.client_broker", "PLAINTEXT"), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers", mskClusterBoostrapBrokersRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers", clusterBoostrapBrokersRegexp), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_tls", ""), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers"), @@ -755,7 +744,7 @@ func TestAccKafkaCluster_EncryptionInfoEncryptionInTransit_inCluster(t *testing. CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEncryptionInfoEncryptionInTransitInClusterConfig(rName, false), + Config: testAccClusterConfig_encryptionInfoEncryptionInTransitIn(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "encryption_info.#", "1"), @@ -787,7 +776,7 @@ func TestAccKafkaCluster_enhancedMonitoring(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEnhancedMonitoringConfig(rName, "PER_BROKER"), + Config: testAccClusterConfig_enhancedMonitoring(rName, "PER_BROKER"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "enhanced_monitoring", kafka.EnhancedMonitoringPerBroker), @@ -802,7 +791,7 @@ func TestAccKafkaCluster_enhancedMonitoring(t *testing.T) { }, }, { - Config: testAccClusterEnhancedMonitoringConfig(rName, "PER_TOPIC_PER_BROKER"), + Config: testAccClusterConfig_enhancedMonitoring(rName, "PER_TOPIC_PER_BROKER"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -825,12 +814,12 @@ func TestAccKafkaCluster_numberOfBrokerNodes(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterNumberOfBrokerNodesConfig(rName, 3), + Config: testAccClusterConfig_numberOfBrokerNodes(rName, 3), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", mskClusterBoostrapBrokersTlsRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", clusterBoostrapBrokersTLSRegexp), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.0.client_subnets.#", "3"), resource.TestCheckTypeSetElemAttrPair(resourceName, "broker_node_group_info.0.client_subnets.*", "aws_subnet.example_subnet_az1", "id"), @@ -849,13 +838,13 @@ func TestAccKafkaCluster_numberOfBrokerNodes(t *testing.T) { }, }, { - Config: testAccClusterNumberOfBrokerNodesConfig(rName, 6), + Config: testAccClusterConfig_numberOfBrokerNodes(rName, 6), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", mskClusterBoostrapBrokersTlsRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", clusterBoostrapBrokersTLSRegexp), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.0.client_subnets.#", "3"), resource.TestCheckTypeSetElemAttrPair(resourceName, "broker_node_group_info.0.client_subnets.*", "aws_subnet.example_subnet_az1", "id"), @@ -881,7 +870,7 @@ func TestAccKafkaCluster_openMonitoring(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterOpenMonitoringConfig(rName, false, false), + Config: testAccClusterConfig_openMonitoring(rName, false, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "open_monitoring.#", "1"), @@ -901,7 +890,7 @@ func TestAccKafkaCluster_openMonitoring(t *testing.T) { }, }, { - Config: testAccClusterOpenMonitoringConfig(rName, true, false), + Config: testAccClusterConfig_openMonitoring(rName, true, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -929,7 +918,7 @@ func TestAccKafkaCluster_loggingInfo(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterLoggingInfoConfig(rName, false, false, false), + Config: testAccClusterConfig_loggingInfo(rName, false, false, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "logging_info.#", "1"), @@ -951,7 +940,7 @@ func TestAccKafkaCluster_loggingInfo(t *testing.T) { }, }, { - Config: testAccClusterLoggingInfoConfig(rName, true, true, true), + Config: testAccClusterConfig_loggingInfo(rName, true, true, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterNotRecreated(&cluster1, &cluster2), @@ -1023,9 +1012,9 @@ func TestAccKafkaCluster_kafkaVersionDowngrade(t *testing.T) { Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster1), resource.TestCheckResourceAttr(resourceName, "kafka_version", "2.8.0"), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers", mskClusterBoostrapBrokersRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers", clusterBoostrapBrokersRegexp), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", mskClusterBoostrapBrokersTlsRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", clusterBoostrapBrokersTLSRegexp), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers"), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers_tls"), ), @@ -1044,9 +1033,9 @@ func TestAccKafkaCluster_kafkaVersionDowngrade(t *testing.T) { testAccCheckClusterExists(resourceName, &cluster2), testAccCheckClusterRecreated(&cluster1, &cluster2), resource.TestCheckResourceAttr(resourceName, "kafka_version", "2.7.1"), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers", mskClusterBoostrapBrokersRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers", clusterBoostrapBrokersRegexp), resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers_sasl_scram", ""), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", mskClusterBoostrapBrokersTlsRegexp), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", clusterBoostrapBrokersTLSRegexp), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers"), testAccCheckResourceAttrIsSortedCSV(resourceName, "bootstrap_brokers_tls"), ), @@ -1113,7 +1102,7 @@ func TestAccKafkaCluster_tags(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfigTags1(rName, "key1", "value1"), + Config: testAccClusterConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1129,7 +1118,7 @@ func TestAccKafkaCluster_tags(t *testing.T) { }, }, { - Config: testAccClusterConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccClusterConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -1138,7 +1127,7 @@ func TestAccKafkaCluster_tags(t *testing.T) { ), }, { - Config: testAccClusterConfigTags1(rName, "key2", "value2"), + Config: testAccClusterConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClusterExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1424,7 +1413,7 @@ resource "aws_route_table_association" "route_tbl_assoc_3" { `, rName)) } -func testAccClusterConfig(rName string) string { +func testAccClusterConfig_basic(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1441,7 +1430,7 @@ resource "aws_msk_cluster" "test" { `, rName)) } -func testAccClusterDeprecatedBrokerNodeGroupInfoEbsVolumeSizeConfig(rName string, ebsVolumeSize int) string { +func testAccClusterConfig_deprecatedBrokerNodeGroupInfoEBSVolumeSize(rName string, ebsVolumeSize int) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1458,7 +1447,7 @@ resource "aws_msk_cluster" "test" { `, rName, ebsVolumeSize)) } -func testAccClusterBrokerNodeGroupInfoStorageInfoVolumeSizeOnlyConfig(rName string, ebsVolumeSize int, instanceType string) string { +func testAccClusterConfig_brokerNodeGroupInfoStorageInfoVolumeSizeOnly(rName string, ebsVolumeSize int, instanceType string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1479,7 +1468,7 @@ resource "aws_msk_cluster" "test" { `, rName, ebsVolumeSize, instanceType)) } -func testAccClusterBrokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputNotEnabledConfig(rName string, ebsVolumeSize int, instanceType string) string { +func testAccClusterConfig_brokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputNotEnabled(rName string, ebsVolumeSize int, instanceType string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1503,7 +1492,7 @@ resource "aws_msk_cluster" "test" { `, rName, ebsVolumeSize, instanceType)) } -func testAccClusterBrokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputEnabledConfig(rName string, ebsVolumeSize int, instanceType string) string { +func testAccClusterConfig_brokerNodeGroupInfoStorageInfoVolumeSizeSetAndProvThroughputEnabled(rName string, ebsVolumeSize int, instanceType string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1528,7 +1517,7 @@ resource "aws_msk_cluster" "test" { `, rName, ebsVolumeSize, instanceType)) } -func testAccClusterBrokerNodeGroupInfoInstanceTypeConfig(rName string, t string) string { +func testAccClusterConfig_brokerNodeGroupInfoInstanceType(rName string, t string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1545,7 +1534,7 @@ resource "aws_msk_cluster" "test" { `, rName, t)) } -func testAccConfigurationAllowEveryoneNoAclFoundFalse(rName string) string { +func testAccConfigurationAllowEveryoneNoACLFoundFalse(rName string) string { return fmt.Sprintf(` resource "aws_msk_configuration" "test" { kafka_versions = ["2.7.1"] @@ -1557,10 +1546,10 @@ resource "aws_msk_configuration" "test" { }`, rName) } -func testAccClusterBrokerNodeGroupInfoNoPublicAccessSaslIamConfig(rName string) string { +func testAccClusterConfig_brokerNodeGroupInfoNoPublicAccessSASLIAM(rName string) string { return acctest.ConfigCompose( testAccClusterBasePublicAccessConfig(rName), - testAccConfigurationAllowEveryoneNoAclFoundFalse(rName), + testAccConfigurationAllowEveryoneNoACLFoundFalse(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1588,10 +1577,10 @@ resource "aws_msk_cluster" "test" { `, rName)) } -func testAccClusterBrokerNodeGroupInfoPublicAccessSaslIamConfig(rName string, pa string) string { +func testAccClusterConfig_brokerNodeGroupInfoPublicAccessSASLIAM(rName string, pa string) string { return acctest.ConfigCompose( testAccClusterBasePublicAccessConfig(rName), - testAccConfigurationAllowEveryoneNoAclFoundFalse(rName), + testAccConfigurationAllowEveryoneNoACLFoundFalse(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1625,7 +1614,7 @@ resource "aws_msk_cluster" "test" { `, rName, pa)) } -func testAccClusterRootCAConfig(commonName string) string { +func testAccClusterConfig_rootCA(commonName string) string { return fmt.Sprintf(` resource "aws_acmpca_certificate_authority" "test" { permanent_deletion_time_in_days = 7 @@ -1643,10 +1632,10 @@ resource "aws_acmpca_certificate_authority" "test" { `, commonName) } -func testAccClusterClientAuthenticationTlsCertificateAuthorityArnsConfig(rName, commonName string) string { +func testAccClusterConfig_clientAuthenticationTLSCertificateAuthorityARNs(rName, commonName string) string { return acctest.ConfigCompose( testAccClusterBaseConfig(rName), - testAccClusterRootCAConfig(commonName), + testAccClusterConfig_rootCA(commonName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1680,10 +1669,10 @@ resource "aws_msk_cluster" "test" { `, rName, commonName)) } -func testAccClusterRootCANoClientAuthenticationConfig(rName, commonName string) string { +func testAccClusterConfig_rootCANoClientAuthentication(rName, commonName string) string { return acctest.ConfigCompose( testAccClusterBaseConfig(rName), - testAccClusterRootCAConfig(commonName), + testAccClusterConfig_rootCA(commonName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1707,7 +1696,7 @@ resource "aws_msk_cluster" "test" { `, rName, commonName)) } -func testAccClusterClientAuthenticationSaslScramConfig(rName string, scramEnabled bool) string { +func testAccClusterConfig_clientAuthenticationSASLScram(rName string, scramEnabled bool) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1732,7 +1721,7 @@ resource "aws_msk_cluster" "test" { `, rName, scramEnabled, !scramEnabled)) } -func testAccClusterClientAuthenticationSaslIamConfig(rName string, saslEnabled bool) string { +func testAccClusterConfig_clientAuthenticationSASLIAM(rName string, saslEnabled bool) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1757,7 +1746,7 @@ resource "aws_msk_cluster" "test" { `, rName, saslEnabled, !saslEnabled)) } -func testAccClusterConfigurationInfoRevision1Config(rName string) string { +func testAccClusterConfig_configurationInfoRevision1(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_configuration" "test1" { kafka_versions = ["2.7.1"] @@ -1788,7 +1777,7 @@ resource "aws_msk_cluster" "test" { `, rName)) } -func testAccClusterConfigurationInfoRevision2Config(rName string) string { +func testAccClusterConfig_configurationInfoRevision2(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_configuration" "test1" { kafka_versions = ["2.7.1"] @@ -1828,7 +1817,7 @@ resource "aws_msk_cluster" "test" { `, rName)) } -func testAccClusterEncryptionInfoEncryptionAtRestKmsKeyArnConfig(rName string) string { +func testAccClusterConfig_encryptionInfoEncryptionAtRestKMSKeyARN(rName string) string { // nosemgrep:msk-in-func-name return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_key" "example_key" { description = %[1]q @@ -1858,7 +1847,7 @@ resource "aws_msk_cluster" "test" { } -func testAccClusterEncryptionInfoEncryptionInTransitClientBrokerConfig(rName, clientBroker string) string { +func testAccClusterConfig_encryptionInfoEncryptionInTransitClientBroker(rName, clientBroker string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1881,7 +1870,7 @@ resource "aws_msk_cluster" "test" { `, rName, clientBroker)) } -func testAccClusterEncryptionInfoEncryptionInTransitInClusterConfig(rName string, inCluster bool) string { +func testAccClusterConfig_encryptionInfoEncryptionInTransitIn(rName string, inCluster bool) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1904,7 +1893,7 @@ resource "aws_msk_cluster" "test" { `, rName, inCluster)) } -func testAccClusterEnhancedMonitoringConfig(rName, enhancedMonitoring string) string { +func testAccClusterConfig_enhancedMonitoring(rName, enhancedMonitoring string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1923,7 +1912,7 @@ resource "aws_msk_cluster" "test" { } -func testAccClusterNumberOfBrokerNodesConfig(rName string, brokerCount int) string { +func testAccClusterConfig_numberOfBrokerNodes(rName string, brokerCount int) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1941,7 +1930,7 @@ resource "aws_msk_cluster" "test" { } -func testAccClusterOpenMonitoringConfig(rName string, jmxExporterEnabled bool, nodeExporterEnabled bool) string { +func testAccClusterConfig_openMonitoring(rName string, jmxExporterEnabled bool, nodeExporterEnabled bool) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -1970,7 +1959,7 @@ resource "aws_msk_cluster" "test" { `, rName, jmxExporterEnabled, nodeExporterEnabled)) } -func testAccClusterLoggingInfoConfig(rName string, cloudwatchLogsEnabled bool, firehoseEnabled bool, s3Enabled bool) string { +func testAccClusterConfig_loggingInfo(rName string, cloudwatchLogsEnabled bool, firehoseEnabled bool, s3Enabled bool) string { cloudwatchLogsLogGroup := "\"\"" firehoseDeliveryStream := "\"\"" s3Bucket := "\"\"" @@ -2143,7 +2132,7 @@ resource "aws_msk_cluster" "test" { `, rName, kafkaVersion, configResourceName)) } -func testAccClusterConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccClusterConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q @@ -2164,7 +2153,7 @@ resource "aws_msk_cluster" "test" { `, rName, tagKey1, tagValue1)) } -func testAccClusterConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccClusterConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(rName), fmt.Sprintf(` resource "aws_msk_cluster" "test" { cluster_name = %[1]q diff --git a/internal/service/kafka/configuration_data_source_test.go b/internal/service/kafka/configuration_data_source_test.go index c65f18f4293..b4fe568548e 100644 --- a/internal/service/kafka/configuration_data_source_test.go +++ b/internal/service/kafka/configuration_data_source_test.go @@ -22,7 +22,7 @@ func TestAccKafkaConfigurationDataSource_name(t *testing.T) { CheckDestroy: testAccCheckConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationDataSourceNameConfig(rName), + Config: testAccConfigurationDataSourceConfig_name(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "description", dataSourceName, "description"), @@ -36,7 +36,7 @@ func TestAccKafkaConfigurationDataSource_name(t *testing.T) { }) } -func testAccConfigurationDataSourceNameConfig(rName string) string { +func testAccConfigurationDataSourceConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_msk_configuration" "test" { kafka_versions = ["2.1.0"] diff --git a/internal/service/kafka/configuration_test.go b/internal/service/kafka/configuration_test.go index 89db5fe309a..380ca687dcf 100644 --- a/internal/service/kafka/configuration_test.go +++ b/internal/service/kafka/configuration_test.go @@ -28,7 +28,7 @@ func TestAccKafkaConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationConfig(rName), + Config: testAccConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationExists(resourceName, &configuration1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kafka", regexp.MustCompile(`configuration/.+`)), @@ -60,7 +60,7 @@ func TestAccKafkaConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationConfig(rName), + Config: testAccConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationExists(resourceName, &configuration1), acctest.CheckResourceDisappears(acctest.Provider, tfkafka.ResourceConfiguration(), resourceName), @@ -83,7 +83,7 @@ func TestAccKafkaConfiguration_description(t *testing.T) { CheckDestroy: testAccCheckConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationConfigDescription(rName, "description1"), + Config: testAccConfigurationConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationExists(resourceName, &configuration1), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -95,7 +95,7 @@ func TestAccKafkaConfiguration_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationConfigDescription(rName, "description2"), + Config: testAccConfigurationConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationExists(resourceName, &configuration2), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -149,7 +149,7 @@ func TestAccKafkaConfiguration_serverProperties(t *testing.T) { CheckDestroy: testAccCheckConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationConfigServerProperties(rName, serverProperty1), + Config: testAccConfigurationConfig_serverProperties(rName, serverProperty1), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationExists(resourceName, &configuration1), resource.TestMatchResourceAttr(resourceName, "server_properties", regexp.MustCompile(serverProperty1)), @@ -161,7 +161,7 @@ func TestAccKafkaConfiguration_serverProperties(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationConfigServerProperties(rName, serverProperty2), + Config: testAccConfigurationConfig_serverProperties(rName, serverProperty2), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationExists(resourceName, &configuration2), resource.TestCheckResourceAttr(resourceName, "latest_revision", "2"), @@ -231,7 +231,7 @@ func testAccCheckConfigurationExists(resourceName string, configuration *kafka.D } } -func testAccConfigurationConfig(rName string) string { +func testAccConfigurationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_msk_configuration" "test" { name = %[1]q @@ -244,7 +244,7 @@ PROPERTIES `, rName) } -func testAccConfigurationConfigDescription(rName, description string) string { +func testAccConfigurationConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_msk_configuration" "test" { description = %[2]q @@ -270,7 +270,7 @@ PROPERTIES `, rName) } -func testAccConfigurationConfigServerProperties(rName string, serverProperty string) string { +func testAccConfigurationConfig_serverProperties(rName string, serverProperty string) string { return fmt.Sprintf(` resource "aws_msk_configuration" "test" { name = %[1]q diff --git a/internal/service/kafka/kafka_version_data_source_test.go b/internal/service/kafka/kafka_version_data_source_test.go index 82260142d33..34000e178bd 100644 --- a/internal/service/kafka/kafka_version_data_source_test.go +++ b/internal/service/kafka/kafka_version_data_source_test.go @@ -21,7 +21,7 @@ func TestAccKafkaKafkaVersionDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccVersionBasicDataSourceConfig(version), + Config: testAccVersionDataSourceConfig_basic(version), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "version", version), resource.TestCheckResourceAttrSet(dataSourceName, "status"), @@ -41,7 +41,7 @@ func TestAccKafkaKafkaVersionDataSource_preferred(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccVersionPreferredDataSourceConfig(), + Config: testAccVersionDataSourceConfig_preferred(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "version", "2.4.1.1"), resource.TestCheckResourceAttrSet(dataSourceName, "status"), @@ -67,7 +67,7 @@ func testAccVersionPreCheck(t *testing.T) { } } -func testAccVersionBasicDataSourceConfig(version string) string { +func testAccVersionDataSourceConfig_basic(version string) string { return fmt.Sprintf(` data "aws_msk_kafka_version" "test" { version = %[1]q @@ -75,7 +75,7 @@ data "aws_msk_kafka_version" "test" { `, version) } -func testAccVersionPreferredDataSourceConfig() string { +func testAccVersionDataSourceConfig_preferred() string { return ` data "aws_msk_kafka_version" "test" { preferred_versions = ["2.4.1.1", "2.4.1", "2.2.1"] diff --git a/internal/service/kafka/scram_secret_association.go b/internal/service/kafka/scram_secret_association.go index 9e3dab0ff1c..bdef515785f 100644 --- a/internal/service/kafka/scram_secret_association.go +++ b/internal/service/kafka/scram_secret_association.go @@ -54,7 +54,7 @@ func resourceScramSecretAssociationCreate(d *schema.ResourceData, meta interface clusterArn := d.Get("cluster_arn").(string) secretArnList := flex.ExpandStringSet(d.Get("secret_arn_list").(*schema.Set)) - output, err := associateMSKClusterSecrets(conn, clusterArn, secretArnList) + output, err := associateClusterSecrets(conn, clusterArn, secretArnList) if err != nil { return fmt.Errorf("error associating scram secret(s) to MSK cluster (%s): %w", clusterArn, err) } @@ -98,7 +98,7 @@ func resourceScramSecretAssociationUpdate(d *schema.ResourceData, meta interface if newSet.Len() > 0 { if newSecrets := newSet.Difference(oldSet); newSecrets.Len() > 0 { - output, err := associateMSKClusterSecrets(conn, d.Id(), flex.ExpandStringSet(newSecrets)) + output, err := associateClusterSecrets(conn, d.Id(), flex.ExpandStringSet(newSecrets)) if err != nil { return fmt.Errorf("error associating scram secret(s) with MSK cluster (%s): %w", d.Id(), err) } @@ -111,7 +111,7 @@ func resourceScramSecretAssociationUpdate(d *schema.ResourceData, meta interface if oldSet.Len() > 0 { if deleteSecrets := oldSet.Difference(newSet); deleteSecrets.Len() > 0 { - output, err := disassociateMSKClusterSecrets(conn, d.Id(), flex.ExpandStringSet(deleteSecrets)) + output, err := disassociateClusterSecrets(conn, d.Id(), flex.ExpandStringSet(deleteSecrets)) if err != nil { return fmt.Errorf("error disassociating scram secret(s) from MSK cluster (%s): %w", d.Id(), err) } @@ -138,7 +138,7 @@ func resourceScramSecretAssociationDelete(d *schema.ResourceData, meta interface } if len(secretArnList) > 0 { - output, err := disassociateMSKClusterSecrets(conn, d.Id(), secretArnList) + output, err := disassociateClusterSecrets(conn, d.Id(), secretArnList) if err != nil { if tfawserr.ErrCodeEquals(err, kafka.ErrCodeNotFoundException) { return nil @@ -153,7 +153,7 @@ func resourceScramSecretAssociationDelete(d *schema.ResourceData, meta interface return nil } -func associateMSKClusterSecrets(conn *kafka.Kafka, clusterArn string, secretArnList []*string) (*kafka.BatchAssociateScramSecretOutput, error) { +func associateClusterSecrets(conn *kafka.Kafka, clusterArn string, secretArnList []*string) (*kafka.BatchAssociateScramSecretOutput, error) { output := &kafka.BatchAssociateScramSecretOutput{} for i := 0; i < len(secretArnList); i += ScramSecretBatchSize { @@ -176,7 +176,7 @@ func associateMSKClusterSecrets(conn *kafka.Kafka, clusterArn string, secretArnL return output, nil } -func disassociateMSKClusterSecrets(conn *kafka.Kafka, clusterArn string, secretArnList []*string) (*kafka.BatchDisassociateScramSecretOutput, error) { +func disassociateClusterSecrets(conn *kafka.Kafka, clusterArn string, secretArnList []*string) (*kafka.BatchDisassociateScramSecretOutput, error) { output := &kafka.BatchDisassociateScramSecretOutput{} for i := 0; i < len(secretArnList); i += ScramSecretBatchSize { diff --git a/internal/service/kafka/scram_secret_association_test.go b/internal/service/kafka/scram_secret_association_test.go index 660850ba958..b5f1f1cf00d 100644 --- a/internal/service/kafka/scram_secret_association_test.go +++ b/internal/service/kafka/scram_secret_association_test.go @@ -28,7 +28,7 @@ func TestAccKafkaScramSecretAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckScramSecretAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccScramSecretAssociation_basic(rName, 1), + Config: testAccScramSecretAssociationConfig_basic(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckScramSecretAssociationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "cluster_arn", clusterResourceName, "arn"), @@ -59,13 +59,13 @@ func TestAccKafkaScramSecretAssociation_update(t *testing.T) { CheckDestroy: testAccCheckScramSecretAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccScramSecretAssociation_basic(rName, 1), + Config: testAccScramSecretAssociationConfig_basic(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckScramSecretAssociationExists(resourceName), ), }, { - Config: testAccScramSecretAssociation_basic(rName, 3), + Config: testAccScramSecretAssociationConfig_basic(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckScramSecretAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "secret_arn_list.#", "3"), @@ -75,7 +75,7 @@ func TestAccKafkaScramSecretAssociation_update(t *testing.T) { ), }, { - Config: testAccScramSecretAssociation_basic(rName, 2), + Config: testAccScramSecretAssociationConfig_basic(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckScramSecretAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "secret_arn_list.#", "2"), @@ -103,7 +103,7 @@ func TestAccKafkaScramSecretAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckScramSecretAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccScramSecretAssociation_basic(rName, 1), + Config: testAccScramSecretAssociationConfig_basic(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckScramSecretAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfkafka.ResourceScramSecretAssociation(), resourceName), @@ -126,7 +126,7 @@ func TestAccKafkaScramSecretAssociation_Disappears_cluster(t *testing.T) { CheckDestroy: testAccCheckScramSecretAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccScramSecretAssociation_basic(rName, 1), + Config: testAccScramSecretAssociationConfig_basic(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckScramSecretAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfkafka.ResourceCluster(), clusterResourceName), @@ -240,7 +240,7 @@ POLICY `, rName, count) } -func testAccScramSecretAssociation_basic(rName string, count int) string { +func testAccScramSecretAssociationConfig_basic(rName string, count int) string { return acctest.ConfigCompose( testAccClusterBaseConfig(rName), testAccScramSecretAssociationBaseConfig(rName, count), ` diff --git a/internal/service/kafkaconnect/connector.go b/internal/service/kafkaconnect/connector.go index e5b3b037a57..6e529fb977d 100644 --- a/internal/service/kafkaconnect/connector.go +++ b/internal/service/kafkaconnect/connector.go @@ -762,13 +762,13 @@ func expandApacheCluster(tfMap map[string]interface{}) *kafkaconnect.ApacheKafka } if v, ok := tfMap["vpc"].([]interface{}); ok && len(v) > 0 { - apiObject.Vpc = expandVpc(v[0].(map[string]interface{})) + apiObject.Vpc = expandVPC(v[0].(map[string]interface{})) } return apiObject } -func expandVpc(tfMap map[string]interface{}) *kafkaconnect.Vpc { +func expandVPC(tfMap map[string]interface{}) *kafkaconnect.Vpc { if tfMap == nil { return nil } @@ -1104,13 +1104,13 @@ func flattenApacheClusterDescription(apiObject *kafkaconnect.ApacheKafkaClusterD } if v := apiObject.Vpc; v != nil { - tfMap["vpc"] = []interface{}{flattenVpcDescription(v)} + tfMap["vpc"] = []interface{}{flattenVPCDescription(v)} } return tfMap } -func flattenVpcDescription(apiObject *kafkaconnect.VpcDescription) map[string]interface{} { +func flattenVPCDescription(apiObject *kafkaconnect.VpcDescription) map[string]interface{} { if apiObject == nil { return nil } diff --git a/internal/service/kafkaconnect/connector_data_source_test.go b/internal/service/kafkaconnect/connector_data_source_test.go index 297434ae61b..e435d914393 100644 --- a/internal/service/kafkaconnect/connector_data_source_test.go +++ b/internal/service/kafkaconnect/connector_data_source_test.go @@ -21,7 +21,7 @@ func TestAccKafkaConnectConnectorDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectorDataSourceConfig(rName), + Config: testAccConnectorDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "description", dataSourceName, "description"), @@ -33,8 +33,8 @@ func TestAccKafkaConnectConnectorDataSource_basic(t *testing.T) { }) } -func testAccConnectorDataSourceConfig(rName string) string { - return acctest.ConfigCompose(testAccConnectorConfig(rName), ` +func testAccConnectorDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccConnectorConfig_basic(rName), ` data "aws_mskconnect_connector" "test" { name = aws_mskconnect_connector.test.name } diff --git a/internal/service/kafkaconnect/connector_test.go b/internal/service/kafkaconnect/connector_test.go index 6adf5e76728..47c2a410401 100644 --- a/internal/service/kafkaconnect/connector_test.go +++ b/internal/service/kafkaconnect/connector_test.go @@ -26,7 +26,7 @@ func TestAccKafkaConnectConnector_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectorConfig(rName), + Config: testAccConnectorConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectorExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -87,7 +87,7 @@ func TestAccKafkaConnectConnector_disappears(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectorConfig(rName), + Config: testAccConnectorConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectorExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfkafkaconnect.ResourceConnector(), resourceName), @@ -109,7 +109,7 @@ func TestAccKafkaConnectConnector_update(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectorAllAttributesConfig(rName), + Config: testAccConnectorConfig_allAttributes(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectorExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -169,7 +169,7 @@ func TestAccKafkaConnectConnector_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConnectorAllAttributesCapacityUpdatedConfig(rName), + Config: testAccConnectorConfig_allAttributesCapacityUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectorExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -404,9 +404,9 @@ resource "aws_msk_cluster" "test" { `, rName)) } -func testAccConnectorConfig(rName string) string { +func testAccConnectorConfig_basic(rName string) string { return acctest.ConfigCompose( - testAccCustomPluginConfig(rName), + testAccCustomPluginConfig_basic(rName), testAccConnectorBaseConfig(rName), fmt.Sprintf(` resource "aws_mskconnect_connector" "test" { @@ -460,10 +460,10 @@ resource "aws_mskconnect_connector" "test" { `, rName)) } -func testAccConnectorAllAttributesConfig(rName string) string { +func testAccConnectorConfig_allAttributes(rName string) string { return acctest.ConfigCompose( - testAccCustomPluginConfig(rName), - testAccWorkerConfigurationConfig(rName), + testAccCustomPluginConfig_basic(rName), + testAccWorkerConfigurationConfig_basic(rName), testAccConnectorBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { @@ -552,10 +552,10 @@ resource "aws_mskconnect_connector" "test" { `, rName)) } -func testAccConnectorAllAttributesCapacityUpdatedConfig(rName string) string { +func testAccConnectorConfig_allAttributesCapacityUpdated(rName string) string { return acctest.ConfigCompose( - testAccCustomPluginConfig(rName), - testAccWorkerConfigurationConfig(rName), + testAccCustomPluginConfig_basic(rName), + testAccWorkerConfigurationConfig_basic(rName), testAccConnectorBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { diff --git a/internal/service/kafkaconnect/custom_plugin_data_source_test.go b/internal/service/kafkaconnect/custom_plugin_data_source_test.go index 4efbadb6407..9906706307a 100644 --- a/internal/service/kafkaconnect/custom_plugin_data_source_test.go +++ b/internal/service/kafkaconnect/custom_plugin_data_source_test.go @@ -22,7 +22,7 @@ func TestAccKafkaConnectCustomPluginDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCustomPluginDataSourceConfig(rName), + Config: testAccCustomPluginDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "description", dataSourceName, "description"), @@ -35,7 +35,7 @@ func TestAccKafkaConnectCustomPluginDataSource_basic(t *testing.T) { }) } -func testAccCustomPluginDataSourceConfig(rName string) string { +func testAccCustomPluginDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(testAccCustomPluginBaseConfig(rName, false), fmt.Sprintf(` resource "aws_mskconnect_custom_plugin" "test" { name = %[1]q diff --git a/internal/service/kafkaconnect/custom_plugin_test.go b/internal/service/kafkaconnect/custom_plugin_test.go index dec45acf3c6..65f34064c8d 100644 --- a/internal/service/kafkaconnect/custom_plugin_test.go +++ b/internal/service/kafkaconnect/custom_plugin_test.go @@ -26,7 +26,7 @@ func TestAccKafkaConnectCustomPlugin_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCustomPluginConfig(rName), + Config: testAccCustomPluginConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCustomPluginExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -62,7 +62,7 @@ func TestAccKafkaConnectCustomPlugin_disappears(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCustomPluginConfig(rName), + Config: testAccCustomPluginConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCustomPluginExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfkafkaconnect.ResourceCustomPlugin(), resourceName), @@ -84,7 +84,7 @@ func TestAccKafkaConnectCustomPlugin_description(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCustomPluginConfigDescription(rName), + Config: testAccCustomPluginConfig_description(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCustomPluginExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "testing"), @@ -110,7 +110,7 @@ func TestAccKafkaConnectCustomPlugin_objectVersion(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCustomPluginConfigObjectVersion(rName), + Config: testAccCustomPluginConfig_objectVersion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCustomPluginExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "location.0.s3.0.object_version"), @@ -200,7 +200,7 @@ resource "aws_s3_object" "test" { `, rName, s3BucketVersioning) } -func testAccCustomPluginConfig(rName string) string { +func testAccCustomPluginConfig_basic(rName string) string { return acctest.ConfigCompose(testAccCustomPluginBaseConfig(rName, false), fmt.Sprintf(` resource "aws_mskconnect_custom_plugin" "test" { name = %[1]q @@ -216,7 +216,7 @@ resource "aws_mskconnect_custom_plugin" "test" { `, rName)) } -func testAccCustomPluginConfigDescription(rName string) string { +func testAccCustomPluginConfig_description(rName string) string { return acctest.ConfigCompose(testAccCustomPluginBaseConfig(rName, false), fmt.Sprintf(` resource "aws_mskconnect_custom_plugin" "test" { name = %[1]q @@ -233,7 +233,7 @@ resource "aws_mskconnect_custom_plugin" "test" { `, rName)) } -func testAccCustomPluginConfigObjectVersion(rName string) string { +func testAccCustomPluginConfig_objectVersion(rName string) string { return acctest.ConfigCompose(testAccCustomPluginBaseConfig(rName, true), fmt.Sprintf(` resource "aws_mskconnect_custom_plugin" "test" { name = %[1]q diff --git a/internal/service/kafkaconnect/worker_configuration_data_source_test.go b/internal/service/kafkaconnect/worker_configuration_data_source_test.go index bdd26cc7f9d..621bb7193cd 100644 --- a/internal/service/kafkaconnect/worker_configuration_data_source_test.go +++ b/internal/service/kafkaconnect/worker_configuration_data_source_test.go @@ -22,7 +22,7 @@ func TestAccKafkaConnectWorkerConfigurationDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkerConfigurationDataSourceConfig(rName), + Config: testAccWorkerConfigurationDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "description", dataSourceName, "description"), @@ -35,7 +35,7 @@ func TestAccKafkaConnectWorkerConfigurationDataSource_basic(t *testing.T) { }) } -func testAccWorkerConfigurationDataSourceConfig(rName string) string { +func testAccWorkerConfigurationDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_mskconnect_worker_configuration" "test" { name = %[1]q diff --git a/internal/service/kafkaconnect/worker_configuration_test.go b/internal/service/kafkaconnect/worker_configuration_test.go index 12f6382b615..23b81c7507c 100644 --- a/internal/service/kafkaconnect/worker_configuration_test.go +++ b/internal/service/kafkaconnect/worker_configuration_test.go @@ -25,7 +25,7 @@ func TestAccKafkaConnectWorkerConfiguration_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkerConfigurationConfig(rName), + Config: testAccWorkerConfigurationConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckWorkerConfigurationExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -54,7 +54,7 @@ func TestAccKafkaConnectWorkerConfiguration_description(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccWorkerConfigurationDescriptionConfig(rName), + Config: testAccWorkerConfigurationConfig_description(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkerConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "testing"), @@ -92,7 +92,7 @@ func testAccCheckWorkerConfigurationExists(n string) resource.TestCheckFunc { } } -func testAccWorkerConfigurationConfig(rName string) string { +func testAccWorkerConfigurationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_mskconnect_worker_configuration" "test" { name = %[1]q @@ -105,7 +105,7 @@ EOF `, rName) } -func testAccWorkerConfigurationDescriptionConfig(rName string) string { +func testAccWorkerConfigurationConfig_description(rName string) string { return fmt.Sprintf(` resource "aws_mskconnect_worker_configuration" "test" { name = %[1]q diff --git a/internal/service/kendra/experience.go b/internal/service/kendra/experience.go new file mode 100644 index 00000000000..ee4d0938071 --- /dev/null +++ b/internal/service/kendra/experience.go @@ -0,0 +1,576 @@ +package kendra + +import ( + "context" + "errors" + "fmt" + "log" + "regexp" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/kendra" + "github.com/aws/aws-sdk-go-v2/service/kendra/types" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceExperience() *schema.Resource { + return &schema.Resource{ + CreateWithoutTimeout: resourceExperienceCreate, + ReadWithoutTimeout: resourceExperienceRead, + UpdateWithoutTimeout: resourceExperienceUpdate, + DeleteWithoutTimeout: resourceExperienceDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Update: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "configuration": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "content_source_configuration": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + AtLeastOneOf: []string{ + "configuration.0.content_source_configuration", + "configuration.0.user_identity_configuration", + }, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "data_source_ids": { + Type: schema.TypeSet, + Optional: true, + MinItems: 1, + MaxItems: 100, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9_\-]*`), ""), + }, + }, + "direct_put_content": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "faq_ids": { + Type: schema.TypeSet, + Optional: true, + MinItems: 1, + MaxItems: 100, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9_\-]*`), ""), + }, + }, + }, + }, + }, + "user_identity_configuration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + AtLeastOneOf: []string{ + "configuration.0.user_identity_configuration", + "configuration.0.content_source_configuration", + }, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "identity_attribute_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9_\-]*`), ""), + }, + }, + }, + }, + }, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(0, 1000), + }, + "endpoints": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "endpoint": { + Type: schema.TypeString, + Computed: true, + }, + "endpoint_type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "experience_id": { + Type: schema.TypeString, + Computed: true, + }, + "index_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9-]*`), ""), + }, + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 1000), + validation.StringMatch(regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9_\-]*`), ""), + ), + }, + "role_arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidARN, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + }, + + CustomizeDiff: customdiff.Sequence( + customdiff.ForceNewIfChange("description", func(_ context.Context, old, new, meta interface{}) bool { + // Any existing value cannot be cleared. + return new.(string) == "" + }), + ), + } +} + +func resourceExperienceCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + in := &kendra.CreateExperienceInput{ + ClientToken: aws.String(resource.UniqueId()), + IndexId: aws.String(d.Get("index_id").(string)), + Name: aws.String(d.Get("name").(string)), + RoleArn: aws.String(d.Get("role_arn").(string)), + } + + if v, ok := d.GetOk("description"); ok { + in.Description = aws.String(v.(string)) + } + + if v, ok := d.GetOk("configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + in.Configuration = expandConfiguration(v.([]interface{})) + } + + out, err := conn.CreateExperience(ctx, in) + if err != nil { + return diag.Errorf("creating Amazon Kendra Experience (%s): %s", d.Get("name").(string), err) + } + + if out == nil { + return diag.Errorf("creating Amazon Kendra Experience (%s): empty output", d.Get("name").(string)) + } + + id := aws.ToString(out.Id) + indexId := d.Get("index_id").(string) + + d.SetId(fmt.Sprintf("%s/%s", id, indexId)) + + if err := waitExperienceCreated(ctx, conn, id, indexId, d.Timeout(schema.TimeoutCreate)); err != nil { + return diag.Errorf("waiting for Amazon Kendra Experience (%s) create: %s", d.Id(), err) + } + + return resourceExperienceRead(ctx, d, meta) +} + +func resourceExperienceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + id, indexId, err := ExperienceParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + out, err := FindExperienceByID(ctx, conn, id, indexId) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Kendra Experience (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return diag.Errorf("reading Kendra Experience (%s): %s", d.Id(), err) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Region: meta.(*conns.AWSClient).Region, + Service: "kendra", + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("index/%s/experience/%s", indexId, id), + }.String() + + d.Set("arn", arn) + d.Set("index_id", out.IndexId) + d.Set("description", out.Description) + d.Set("experience_id", out.Id) + d.Set("name", out.Name) + d.Set("role_arn", out.RoleArn) + d.Set("status", out.Status) + + if err := d.Set("endpoints", flattenEndpoints(out.Endpoints)); err != nil { + return diag.Errorf("setting endpoints argument: %s", err) + } + + if err := d.Set("configuration", flattenConfiguration(out.Configuration)); err != nil { + return diag.Errorf("setting configuration argument: %s", err) + } + + return nil +} + +func resourceExperienceUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + id, indexId, err := ExperienceParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + in := &kendra.UpdateExperienceInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + } + + if d.HasChange("configuration") { + in.Configuration = expandConfiguration(d.Get("configuration").([]interface{})) + } + + if d.HasChange("description") { + in.Description = aws.String(d.Get("description").(string)) + } + + if d.HasChange("name") { + in.Name = aws.String(d.Get("name").(string)) + } + + if d.HasChange("role_arn") { + in.RoleArn = aws.String(d.Get("role_arn").(string)) + } + + log.Printf("[DEBUG] Updating Kendra Experience (%s): %#v", d.Id(), in) + _, err = conn.UpdateExperience(ctx, in) + if err != nil { + return diag.Errorf("updating Kendra Experience (%s): %s", d.Id(), err) + } + + if err := waitExperienceUpdated(ctx, conn, id, indexId, d.Timeout(schema.TimeoutUpdate)); err != nil { + return diag.Errorf("waiting for Kendra Experience (%s) update: %s", d.Id(), err) + } + + return resourceExperienceRead(ctx, d, meta) +} + +func resourceExperienceDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + log.Printf("[INFO] Deleting Kendra Experience %s", d.Id()) + + id, indexId, err := ExperienceParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + _, err = conn.DeleteExperience(ctx, &kendra.DeleteExperienceInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + }) + + var resourceNotFoundException *types.ResourceNotFoundException + if errors.As(err, &resourceNotFoundException) { + return nil + } + + if err != nil { + return diag.Errorf("deleting Kendra Experience (%s): %s", d.Id(), err) + } + + if err := waitExperienceDeleted(ctx, conn, id, indexId, d.Timeout(schema.TimeoutDelete)); err != nil { + return diag.Errorf("waiting for Kendra Experience (%s) to be deleted: %s", d.Id(), err) + } + + return nil +} + +func waitExperienceCreated(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{string(types.ExperienceStatusCreating)}, + Target: []string{string(types.ExperienceStatusActive)}, + Refresh: statusExperience(ctx, conn, id, indexId), + Timeout: timeout, + NotFoundChecks: 20, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + if out, ok := outputRaw.(*kendra.DescribeExperienceOutput); ok { + if out.Status == types.ExperienceStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(out.ErrorMessage))) + } + } + + return err +} + +func waitExperienceUpdated(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{}, + Target: []string{string(types.ExperienceStatusActive)}, + Refresh: statusExperience(ctx, conn, id, indexId), + Timeout: timeout, + NotFoundChecks: 20, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + if out, ok := outputRaw.(*kendra.DescribeExperienceOutput); ok { + if out.Status == types.ExperienceStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(out.ErrorMessage))) + } + } + + return err +} + +func waitExperienceDeleted(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{string(types.ExperienceStatusDeleting)}, + Target: []string{}, + Refresh: statusExperience(ctx, conn, id, indexId), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + if out, ok := outputRaw.(*kendra.DescribeExperienceOutput); ok { + if out.Status == types.ExperienceStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(out.ErrorMessage))) + } + } + + return err +} + +func statusExperience(ctx context.Context, conn *kendra.Client, id, indexId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + out, err := FindExperienceByID(ctx, conn, id, indexId) + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return out, string(out.Status), nil + } +} + +func FindExperienceByID(ctx context.Context, conn *kendra.Client, id, indexId string) (*kendra.DescribeExperienceOutput, error) { + in := &kendra.DescribeExperienceInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + } + + out, err := conn.DescribeExperience(ctx, in) + var resourceNotFoundException *types.ResourceNotFoundException + + if errors.As(err, &resourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: in, + } + } + + if err != nil { + return nil, err + } + + if out == nil { + return nil, tfresource.NewEmptyResultError(in) + } + + return out, nil +} + +func flattenConfiguration(apiObject *types.ExperienceConfiguration) []interface{} { + if apiObject == nil { + return nil + } + + m := map[string]interface{}{} + + if v := apiObject.ContentSourceConfiguration; v != nil { + m["content_source_configuration"] = flattenContentSourceConfiguration(v) + } + + if v := apiObject.UserIdentityConfiguration; v != nil { + m["user_identity_configuration"] = flattenUserIdentityConfiguration(v) + } + + return []interface{}{m} +} + +func flattenContentSourceConfiguration(apiObject *types.ContentSourceConfiguration) []interface{} { + if apiObject == nil { + return nil + } + + m := map[string]interface{}{ + "direct_put_content": apiObject.DirectPutContent, + } + + if v := apiObject.DataSourceIds; len(v) > 0 { + m["data_source_ids"] = v + } + + if v := apiObject.FaqIds; len(v) > 0 { + m["faq_ids"] = v + } + return []interface{}{m} +} + +func flattenEndpoints(apiObjects []types.ExperienceEndpoint) []interface{} { + if len(apiObjects) == 0 { + return nil + } + + l := make([]interface{}, 0, len(apiObjects)) + + for _, apiObject := range apiObjects { + m := make(map[string]interface{}) + + if v := apiObject.Endpoint; v != nil { + m["endpoint"] = aws.ToString(v) + } + + if v := string(apiObject.EndpointType); v != "" { + m["endpoint_type"] = v + } + + l = append(l, m) + } + + return l + +} + +func flattenUserIdentityConfiguration(apiObject *types.UserIdentityConfiguration) []interface{} { + if apiObject == nil { + return nil + } + + m := make(map[string]interface{}) + + if v := apiObject.IdentityAttributeName; v != nil { + m["identity_attribute_name"] = aws.ToString(v) + } + + return []interface{}{m} +} + +func expandConfiguration(tfList []interface{}) *types.ExperienceConfiguration { + if len(tfList) == 0 || tfList[0] == nil { + return nil + } + + tfMap, ok := tfList[0].(map[string]interface{}) + if !ok { + return nil + } + + result := &types.ExperienceConfiguration{} + + if v, ok := tfMap["content_source_configuration"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + result.ContentSourceConfiguration = expandContentSourceConfiguration(v[0].(map[string]interface{})) + } + + if v, ok := tfMap["user_identity_configuration"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + result.UserIdentityConfiguration = expandUserIdentityConfiguration(v[0].(map[string]interface{})) + } + + return result +} + +func expandContentSourceConfiguration(tfMap map[string]interface{}) *types.ContentSourceConfiguration { + if tfMap == nil { + return nil + } + + result := &types.ContentSourceConfiguration{} + + if v, ok := tfMap["data_source_ids"].(*schema.Set); ok && v.Len() > 0 { + result.DataSourceIds = expandStringList(v.List()) + } + + if v, ok := tfMap["direct_put_content"].(bool); ok { + result.DirectPutContent = v + } + + if v, ok := tfMap["faq_ids"].(*schema.Set); ok && v.Len() > 0 { + result.FaqIds = expandStringList(v.List()) + } + + return result +} + +func expandUserIdentityConfiguration(tfMap map[string]interface{}) *types.UserIdentityConfiguration { + if tfMap == nil { + return nil + } + + result := &types.UserIdentityConfiguration{} + + if v, ok := tfMap["identity_attribute_name"].(string); ok && v != "" { + result.IdentityAttributeName = aws.String(v) + } + + return result +} + +func expandStringList(tfList []interface{}) []string { + var result []string + + for _, rawVal := range tfList { + if v, ok := rawVal.(string); ok && v != "" { + result = append(result, v) + } + } + + return result +} diff --git a/internal/service/kendra/experience_test.go b/internal/service/kendra/experience_test.go new file mode 100644 index 00000000000..f649dc2e9fe --- /dev/null +++ b/internal/service/kendra/experience_test.go @@ -0,0 +1,954 @@ +package kendra_test + +import ( + "context" + "fmt" + "os" + "regexp" + "testing" + + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfkendra "github.com/hashicorp/terraform-provider-aws/internal/service/kendra" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func testAccExperience_basic(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kendra", regexp.MustCompile(`index/.+/experience/.+$`)), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "0"), + resource.TestCheckResourceAttr(resourceName, "endpoints.#", "1"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttrPair(resourceName, "index_id", "aws_kendra_index.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test", "arn"), + resource.TestCheckResourceAttrSet(resourceName, "status"), + resource.TestCheckResourceAttrSet(resourceName, "experience_id"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccExperience_disappears(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfkendra.ResourceExperience(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccExperience_Description(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_description(rName, "description1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description1"), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccExperienceConfig_description(rName, "description2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description2"), + // Update should return a default "configuration" block + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "false"), + ), + }, + { + // Removing the description should force a new resource as + // the update to an empty value is not currently supported + Config: testAccExperienceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "0"), + ), + }, + }, + }) +} + +func testAccExperience_Name(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_basic(rName1), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", rName1), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "0"), + ), + }, + { + Config: testAccExperienceConfig_name(rName1, rName2), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", rName2), + // Update should return a default "configuration" block + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "false"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccExperience_roleARN(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test", "arn"), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "0"), + ), + }, + { + Config: testAccExperienceConfig_roleARN(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test2", "arn"), + // Update should return a default "configuration" block + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "false"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccExperience_Configuration_ContentSourceConfiguration_DirectPutContent(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_configuration_contentSourceConfiguration_empty(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "false"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccExperienceConfig_configuration_contentSourceConfiguration_directPutContent(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "true"), + ), + }, + { + Config: testAccExperienceConfig_configuration_contentSourceConfiguration_directPutContent(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "false"), + ), + }, + }, + }) +} + +func testAccExperience_Configuration_ContentSourceConfiguration_FaqIDs(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_configuration_contentSourceConfiguration_faqIDs(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "false"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.faq_ids.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "configuration.0.content_source_configuration.0.faq_ids.*", "aws_kendra_faq.test", "faq_id"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccExperience_Configuration_ContentSourceConfiguration_updateFaqIDs(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_configuration_contentSourceConfiguration_faqIDs(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "false"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.faq_ids.#", "1"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "configuration.0.content_source_configuration.0.faq_ids.*", "aws_kendra_faq.test", "faq_id"), + ), + }, + { + Config: testAccExperienceConfig_configuration_contentSourceConfiguration_empty(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "false"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.faq_ids.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccExperience_Configuration_UserIdentityConfiguration(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + userId := os.Getenv("AWS_IDENTITY_STORE_USER_ID") + if userId == "" { + t.Skip("Environment variable AWS_IDENTITY_STORE_USER_ID is not set") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_configuration_userIdentityConfiguration(rName, userId), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.user_identity_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.user_identity_configuration.0.identity_attribute_name", userId), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccExperience_Configuration_ContentSourceConfigurationAndUserIdentityConfiguration(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + userId := os.Getenv("AWS_IDENTITY_STORE_USER_ID") + if userId == "" { + t.Skip("Environment variable AWS_IDENTITY_STORE_USER_ID is not set") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_configuration_contentSourceConfigurationAndUserIdentityConfiguration(rName, userId), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "true"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.user_identity_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.user_identity_configuration.0.identity_attribute_name", userId), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccExperience_Configuration_ContentSourceConfigurationWithUserIdentityConfigurationRemoved(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + userId := os.Getenv("AWS_IDENTITY_STORE_USER_ID") + if userId == "" { + t.Skip("Environment variable AWS_IDENTITY_STORE_USER_ID is not set") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_configuration_contentSourceConfigurationAndUserIdentityConfiguration(rName, userId), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "true"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.user_identity_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.user_identity_configuration.0.identity_attribute_name", userId), + ), + }, + { + Config: testAccExperienceConfig_configuration_contentSourceConfiguration_directPutContent(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "true"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.user_identity_configuration.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccExperience_Configuration_UserIdentityConfigurationWithContentSourceConfigurationRemoved(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + userId := os.Getenv("AWS_IDENTITY_STORE_USER_ID") + if userId == "" { + t.Skip("Environment variable AWS_IDENTITY_STORE_USER_ID is not set") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_experience.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckOrganizationManagementAccount(t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckExperienceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccExperienceConfig_configuration_contentSourceConfigurationAndUserIdentityConfiguration(rName, userId), + Check: resource.ComposeTestCheckFunc( + testAccCheckExperienceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.content_source_configuration.0.direct_put_content", "true"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.user_identity_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "configuration.0.user_identity_configuration.0.identity_attribute_name", userId), + ), + }, + { + // Since configuration.content_source_configuration is Optional+Computed, removal in the test config should not trigger changes + PlanOnly: true, + Config: testAccExperienceConfig_configuration_userIdentityConfiguration(rName, userId), + ExpectNonEmptyPlan: false, + }, + }, + }) +} + +func testAccCheckExperienceDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_kendra_experience" { + continue + } + + id, indexId, err := tfkendra.ExperienceParseResourceID(rs.Primary.ID) + if err != nil { + return err + } + + _, err = tfkendra.FindExperienceByID(context.TODO(), conn, id, indexId) + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + } + + return nil +} + +func testAccCheckExperienceExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Kendra Experience is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + id, indexId, err := tfkendra.ExperienceParseResourceID(rs.Primary.ID) + if err != nil { + return err + } + + _, err = tfkendra.FindExperienceByID(context.TODO(), conn, id, indexId) + if err != nil { + return err + } + + return nil + } +} + +func testAccExperienceBaseConfig(rName string) string { + return fmt.Sprintf(` +data "aws_caller_identity" "current" {} + +data "aws_partition" "current" {} + +data "aws_region" "current" {} + +data "aws_iam_policy_document" "assume_role" { + statement { + actions = ["sts:AssumeRole"] + effect = "Allow" + principals { + type = "Service" + identifiers = ["kendra.${data.aws_partition.current.dns_suffix}"] + } + } +} + +resource "aws_iam_role" "test" { + name = %[1]q + path = "/" + assume_role_policy = data.aws_iam_policy_document.assume_role.json +} + +data "aws_iam_policy_document" "test" { + statement { + effect = "Allow" + actions = [ + "cloudwatch:PutMetricData" + ] + resources = [ + "*" + ] + condition { + test = "StringEquals" + variable = "cloudwatch:namespace" + values = ["Kendra"] + } + } + statement { + effect = "Allow" + actions = [ + "logs:DescribeLogGroups" + ] + resources = [ + "*" + ] + } + statement { + effect = "Allow" + actions = [ + "logs:CreateLogGroup" + ] + resources = [ + "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*" + ] + } + statement { + effect = "Allow" + actions = [ + "logs:DescribeLogStreams", + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + resources = [ + "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*:log-stream:*" + ] + } +} + +resource "aws_iam_policy" "test" { + name = %[1]q + description = "Allow Kendra to access cloudwatch logs" + policy = data.aws_iam_policy_document.test.json +} + +data "aws_iam_policy_document" "experience" { + statement { + sid = "AllowsKendraSearchAppToCallKendraApi" + effect = "Allow" + actions = [ + "kendra:GetQuerySuggestions", + "kendra:Query", + "kendra:DescribeIndex", + "kendra:ListFaqs", + "kendra:DescribeDataSource", + "kendra:ListDataSources", + "kendra:DescribeFaq" + ] + resources = [ + "arn:${data.aws_partition.current.partition}:kendra:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:index/${aws_kendra_index.test.id}" + ] + } +} + +resource "aws_iam_policy" "experience" { + name = "%[1]s-experience" + description = "Allow Kendra to search app access" + policy = data.aws_iam_policy_document.experience.json +} + +resource "aws_iam_role_policy_attachment" "test" { + role = aws_iam_role.test.name + policy_arn = aws_iam_policy.test.arn +} + +resource "aws_iam_role_policy_attachment" "experience" { + role = aws_iam_role.test.name + policy_arn = aws_iam_policy.experience.arn +} + +resource "aws_kendra_index" "test" { + depends_on = [aws_iam_role_policy_attachment.test] + + name = %[1]q + role_arn = aws_iam_role.test.arn +} +`, rName) +} + +func testAccExperienceConfig_basic(rName string) string { + return acctest.ConfigCompose( + testAccExperienceBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_experience" "test" { + depends_on = [aws_iam_role_policy_attachment.experience] + + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn +} +`, rName)) +} + +func testAccExperienceConfig_description(rName, description string) string { + return acctest.ConfigCompose( + testAccExperienceBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_experience" "test" { + depends_on = [aws_iam_role_policy_attachment.experience] + + index_id = aws_kendra_index.test.id + description = %[2]q + name = %[1]q + role_arn = aws_iam_role.test.arn +} +`, rName, description)) +} + +func testAccExperienceConfig_name(rName, name string) string { + return acctest.ConfigCompose( + testAccExperienceBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_experience" "test" { + depends_on = [aws_iam_role_policy_attachment.experience] + + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn +} +`, name)) +} + +func testAccExperienceConfig_roleARN(rName string) string { + return acctest.ConfigCompose( + testAccExperienceBaseConfig(rName), + fmt.Sprintf(` +resource "aws_iam_role" "test2" { + name = "%[1]s-2" + path = "/" + assume_role_policy = data.aws_iam_policy_document.assume_role.json +} + +resource "aws_iam_policy" "experience2" { + name = "%[1]s-experience-2" + description = "Allow Kendra to search app access" + policy = data.aws_iam_policy_document.experience.json +} + +resource "aws_iam_role_policy_attachment" "experience2" { + role = aws_iam_role.test2.name + policy_arn = aws_iam_policy.experience2.arn +} + +resource "aws_kendra_experience" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test2.arn +} +`, rName)) +} + +func testAccExperienceConfig_configuration_contentSourceConfiguration_empty(rName string) string { + return acctest.ConfigCompose( + testAccExperienceBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_experience" "test" { + depends_on = [aws_iam_role_policy_attachment.experience] + + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + configuration { + content_source_configuration {} + } +} +`, rName)) +} + +func testAccExperienceConfig_configuration_contentSourceConfiguration_directPutContent(rName string, directPutContent bool) string { + return acctest.ConfigCompose( + testAccExperienceBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_experience" "test" { + depends_on = [aws_iam_role_policy_attachment.experience] + + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + configuration { + content_source_configuration { + direct_put_content = %[2]t + } + } +} +`, rName, directPutContent)) +} + +func testAccExperienceConfig_configuration_contentSourceConfiguration_faqIDs(rName string) string { + return acctest.ConfigCompose( + testAccExperienceBaseConfig(rName), + fmt.Sprintf(` +resource "aws_s3_bucket" "test" { + bucket = %[1]q + force_destroy = true +} + +resource "aws_s3_object" "test" { + bucket = aws_s3_bucket.test.bucket + source = "test-fixtures/basic.csv" + key = "test/basic.csv" +} + +data "aws_iam_policy_document" "faq" { + statement { + sid = "AllowKendraToAccessS3" + effect = "Allow" + actions = [ + "s3:GetObject" + ] + resources = [ + "${aws_s3_bucket.test.arn}/*" + ] + } +} + +resource "aws_iam_policy" "faq" { + name = "%[1]s-faq" + description = "Allow Kendra to access S3" + policy = data.aws_iam_policy_document.faq.json +} + +resource "aws_iam_role_policy_attachment" "faq" { + role = aws_iam_role.test.name + policy_arn = aws_iam_policy.faq.arn +} + +resource "aws_kendra_faq" "test" { + depends_on = [aws_iam_role_policy_attachment.faq] + + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} + +resource "aws_kendra_experience" "test" { + depends_on = [aws_iam_role_policy_attachment.experience] + + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + configuration { + content_source_configuration { + faq_ids = [aws_kendra_faq.test.faq_id] + } + } +} +`, rName)) +} + +func testAccExperienceConfig_configuration_userIdentityConfiguration(rName, userId string) string { + return acctest.ConfigCompose( + testAccExperienceBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_experience" "test" { + depends_on = [aws_iam_role_policy_attachment.experience] + + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + configuration { + user_identity_configuration { + identity_attribute_name = %[2]q + } + } +} +`, rName, userId)) +} + +func testAccExperienceConfig_configuration_contentSourceConfigurationAndUserIdentityConfiguration(rName, userId string) string { + return acctest.ConfigCompose( + testAccExperienceBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_experience" "test" { + depends_on = [aws_iam_role_policy_attachment.experience] + + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + configuration { + content_source_configuration { + direct_put_content = true + } + user_identity_configuration { + identity_attribute_name = %[2]q + } + } +} +`, rName, userId)) +} diff --git a/internal/service/kendra/faq.go b/internal/service/kendra/faq.go new file mode 100644 index 00000000000..7787fc00132 --- /dev/null +++ b/internal/service/kendra/faq.go @@ -0,0 +1,445 @@ +package kendra + +import ( + "context" + "errors" + "fmt" + "log" + "regexp" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/kendra" + "github.com/aws/aws-sdk-go-v2/service/kendra/types" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "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" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceFaq() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceFaqCreate, + ReadContext: resourceFaqRead, + UpdateContext: resourceFaqUpdate, + DeleteContext: resourceFaqDelete, + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + CustomizeDiff: verify.SetTagsDiff, + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "created_at": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 1000), + }, + "error_message": { + Type: schema.TypeString, + Computed: true, + }, + "faq_id": { + Type: schema.TypeString, + Computed: true, + }, + "file_format": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(faqFileFormatValues(types.FaqFileFormat("").Values()...), false), + }, + "index_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9-]{35}`), + "Starts with an alphanumeric character. Subsequently, can contain alphanumeric characters and hyphens. Fixed length of 36.", + ), + }, + "language_code": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: validation.All( + validation.StringLenBetween(2, 10), + validation.StringMatch( + regexp.MustCompile(`[a-zA-Z-]*`), + "Must have alphanumeric characters or hyphens.", + ), + ), + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 100), + validation.StringMatch( + regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9_-]*`), + "Starts with an alphanumeric character. Subsequently, the name must consist of alphanumerics, hyphens or underscores.", + ), + ), + }, + "role_arn": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: verify.ValidARN, + }, + "s3_path": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "bucket": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "key": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_at": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + } +} + +func resourceFaqCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + name := d.Get("name").(string) + + input := &kendra.CreateFaqInput{ + ClientToken: aws.String(resource.UniqueId()), + IndexId: aws.String(d.Get("index_id").(string)), + Name: aws.String(name), + RoleArn: aws.String(d.Get("role_arn").(string)), + S3Path: expandS3Path(d.Get("s3_path").([]interface{})), + } + + if v, ok := d.GetOk("description"); ok { + input.Description = aws.String(v.(string)) + } + + if v, ok := d.GetOk("file_format"); ok { + input.FileFormat = types.FaqFileFormat(v.(string)) + } + + if v, ok := d.GetOk("language_code"); ok { + input.LanguageCode = aws.String(v.(string)) + } + + if len(tags) > 0 { + input.Tags = Tags(tags.IgnoreAWS()) + } + + log.Printf("[DEBUG] Creating Kendra Faq %#v", input) + + outputRaw, err := tfresource.RetryWhen( + propagationTimeout, + func() (interface{}, error) { + return conn.CreateFaq(ctx, input) + }, + func(err error) (bool, error) { + var validationException *types.ValidationException + + if errors.As(err, &validationException) && strings.Contains(validationException.ErrorMessage(), validationExceptionMessage) { + return true, err + } + + return false, err + }, + ) + + if err != nil { + return diag.Errorf("creating Kendra Faq (%s): %s", name, err) + } + + if outputRaw == nil { + return diag.Errorf("creating Kendra Faq (%s): empty output", name) + } + + output := outputRaw.(*kendra.CreateFaqOutput) + + id := aws.ToString(output.Id) + indexId := d.Get("index_id").(string) + + d.SetId(fmt.Sprintf("%s/%s", id, indexId)) + + if _, err := waitFaqCreated(ctx, conn, id, indexId, d.Timeout(schema.TimeoutCreate)); err != nil { + return diag.Errorf("waiting for Faq (%s) creation: %s", d.Id(), err) + } + + return resourceFaqRead(ctx, d, meta) +} + +func resourceFaqRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + id, indexId, err := FaqParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + resp, err := FindFaqByID(ctx, conn, id, indexId) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Kendra Faq (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return diag.Errorf("getting Kendra Faq (%s): %s", d.Id(), err) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: "kendra", + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("index/%s/faq/%s", indexId, id), + }.String() + + d.Set("arn", arn) + d.Set("created_at", aws.ToTime(resp.CreatedAt).Format(time.RFC3339)) + d.Set("description", resp.Description) + d.Set("error_message", resp.ErrorMessage) + d.Set("faq_id", resp.Id) + d.Set("file_format", resp.FileFormat) + d.Set("index_id", resp.IndexId) + d.Set("language_code", resp.LanguageCode) + d.Set("name", resp.Name) + d.Set("role_arn", resp.RoleArn) + d.Set("status", resp.Status) + d.Set("updated_at", aws.ToTime(resp.UpdatedAt).Format(time.RFC3339)) + + if err := d.Set("s3_path", flattenS3Path(resp.S3Path)); err != nil { + return diag.FromErr(err) + } + + tags, err := ListTags(ctx, conn, arn) + if err != nil { + return diag.Errorf("listing tags for resource (%s): %s", arn, err) + } + tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return diag.Errorf("setting tags: %s", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return diag.Errorf("setting tags_all: %s", err) + } + + return nil +} + +func resourceFaqUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(ctx, conn, d.Get("arn").(string), o, n); err != nil { + return diag.FromErr(fmt.Errorf("updating Kendra Faq (%s) tags: %s", d.Id(), err)) + } + } + + return resourceFaqRead(ctx, d, meta) +} + +func resourceFaqDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + log.Printf("[INFO] Deleting Kendra Faq %s", d.Id()) + + id, indexId, err := FaqParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + _, err = conn.DeleteFaq(ctx, &kendra.DeleteFaqInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + }) + + var resourceNotFoundException *types.ResourceNotFoundException + if errors.As(err, &resourceNotFoundException) { + return nil + } + + if err != nil { + return diag.Errorf("deleting Kendra Faq (%s): %s", d.Id(), err) + } + + if _, err := waitFaqDeleted(ctx, conn, id, indexId, d.Timeout(schema.TimeoutDelete)); err != nil { + return diag.Errorf("waiting for Kendra Faq (%s) delete: %s", d.Id(), err) + } + + return nil +} + +func waitFaqCreated(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) (*kendra.DescribeFaqOutput, error) { + + stateConf := &resource.StateChangeConf{ + Pending: FaqStatusValues(types.FaqStatusCreating, "PENDING_CREATION"), // API currently returns PENDING_CREATION instead of CREATING + Target: FaqStatusValues(types.FaqStatusActive), + Timeout: timeout, + Refresh: statusFaq(ctx, conn, id, indexId), + NotFoundChecks: 20, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*kendra.DescribeFaqOutput); ok { + if output.Status == types.FaqStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.ErrorMessage))) + } + return output, err + } + + return nil, err +} + +func waitFaqDeleted(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) (*kendra.DescribeFaqOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: FaqStatusValues(types.FaqStatusDeleting, "PENDING_DELETION"), // API currently returns PENDING_DELETION instead of DELETING + Target: []string{}, + Timeout: timeout, + Refresh: statusFaq(ctx, conn, id, indexId), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*kendra.DescribeFaqOutput); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.ErrorMessage))) + + return output, err + } + + return nil, err +} + +func statusFaq(ctx context.Context, conn *kendra.Client, id, indexId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindFaqByID(ctx, conn, id, indexId) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status), nil + } +} + +func expandS3Path(tfList []interface{}) *types.S3Path { + if len(tfList) == 0 || tfList[0] == nil { + return nil + } + + tfMap, ok := tfList[0].(map[string]interface{}) + if !ok { + return nil + } + + result := &types.S3Path{} + + if v, ok := tfMap["bucket"].(string); ok && v != "" { + result.Bucket = aws.String(v) + } + + if v, ok := tfMap["key"].(string); ok && v != "" { + result.Key = aws.String(v) + } + + return result +} + +func flattenS3Path(apiObject *types.S3Path) []interface{} { + if apiObject == nil { + return nil + } + + m := map[string]interface{}{} + + if v := apiObject.Bucket; v != nil { + m["bucket"] = aws.ToString(v) + } + + if v := apiObject.Key; v != nil { + m["key"] = aws.ToString(v) + } + + return []interface{}{m} +} + +// Helpers added. Could be generated or somehow use go 1.18 generics? +func faqFileFormatValues(input ...types.FaqFileFormat) []string { + var output []string + + for _, v := range input { + output = append(output, string(v)) + } + + return output +} + +func FaqStatusValues(input ...types.FaqStatus) []string { + var output []string + + for _, v := range input { + output = append(output, string(v)) + } + + output = append(output, "PENDING_CREATION") + output = append(output, "PENDING_DELETION") + + return output +} diff --git a/internal/service/kendra/faq_data_source.go b/internal/service/kendra/faq_data_source.go new file mode 100644 index 00000000000..7681ea24f87 --- /dev/null +++ b/internal/service/kendra/faq_data_source.go @@ -0,0 +1,157 @@ +package kendra + +import ( + "context" + "fmt" + "regexp" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" +) + +func DataSourceFaq() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceFaqRead, + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "created_at": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "error_message": { + Type: schema.TypeString, + Computed: true, + }, + "faq_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 100), + validation.StringMatch( + regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9_-]*`), + "Starts with an alphanumeric character. Subsequently, can contain alphanumeric characters and hyphens.", + ), + ), + }, + "file_format": { + Type: schema.TypeString, + Computed: true, + }, + "index_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9-]{35}`), + "Starts with an alphanumeric character. Subsequently, can contain alphanumeric characters and hyphens. Fixed length of 36.", + ), + }, + "language_code": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "role_arn": { + Type: schema.TypeString, + Computed: true, + }, + "s3_path": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "bucket": { + Type: schema.TypeString, + Computed: true, + }, + "key": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_at": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tftags.TagsSchemaComputed(), + }, + } +} + +func dataSourceFaqRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + id := d.Get("faq_id").(string) + indexId := d.Get("index_id").(string) + + resp, err := FindFaqByID(ctx, conn, id, indexId) + + if err != nil { + return diag.Errorf("getting Kendra Faq (%s): %s", d.Id(), err) + } + + if resp == nil { + return diag.Errorf("getting Kendra Faq (%s): empty response", id) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: "kendra", + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("index/%s/faq/%s", indexId, id), + }.String() + + d.Set("arn", arn) + d.Set("created_at", aws.ToTime(resp.CreatedAt).Format(time.RFC3339)) + d.Set("description", resp.Description) + d.Set("error_message", resp.ErrorMessage) + d.Set("faq_id", resp.Id) + d.Set("file_format", resp.FileFormat) + d.Set("index_id", resp.IndexId) + d.Set("language_code", resp.LanguageCode) + d.Set("name", resp.Name) + d.Set("role_arn", resp.RoleArn) + d.Set("status", resp.Status) + d.Set("updated_at", aws.ToTime(resp.UpdatedAt).Format(time.RFC3339)) + + if err := d.Set("s3_path", flattenS3Path(resp.S3Path)); err != nil { + return diag.FromErr(err) + } + + tags, err := ListTags(ctx, conn, arn) + if err != nil { + return diag.Errorf("error listing tags for resource (%s): %s", arn, err) + } + tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + if err := d.Set("tags", tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return diag.Errorf("error setting tags: %s", err) + } + + d.SetId(fmt.Sprintf("%s/%s", id, indexId)) + + return nil +} diff --git a/internal/service/kendra/faq_data_source_test.go b/internal/service/kendra/faq_data_source_test.go new file mode 100644 index 00000000000..8646d0dabbe --- /dev/null +++ b/internal/service/kendra/faq_data_source_test.go @@ -0,0 +1,90 @@ +package kendra_test + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/backup" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" +) + +func TestAccKendraFaqDataSource_basic(t *testing.T) { + datasourceName := "data.aws_kendra_faq.test" + resourceName := "aws_kendra_faq.test" + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName4 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName5 := sdkacctest.RandomWithPrefix("resource-test-terraform") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, backup.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccFaqDataSourceConfig_nonExistent, + ExpectError: regexp.MustCompile(`getting Kendra Faq`), + }, + { + Config: testAccFaqDataSourceConfig_basic(rName, rName2, rName3, rName4, rName5), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "created_at", resourceName, "created_at"), + resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), + resource.TestCheckResourceAttrPair(datasourceName, "faq_id", resourceName, "faq_id"), + resource.TestCheckResourceAttrPair(datasourceName, "file_format", resourceName, "file_format"), + resource.TestCheckResourceAttrPair(datasourceName, "index_id", resourceName, "index_id"), + resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrPair(datasourceName, "language_code", resourceName, "language_code"), + resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(datasourceName, "role_arn", resourceName, "role_arn"), + resource.TestCheckResourceAttrPair(datasourceName, "s3_path.#", resourceName, "s3_path.#"), + resource.TestCheckResourceAttrPair(datasourceName, "s3_path.0.bucket", resourceName, "s3_path.0.bucket"), + resource.TestCheckResourceAttrPair(datasourceName, "s3_path.0.key", resourceName, "s3_path.0.key"), + resource.TestCheckResourceAttrPair(datasourceName, "status", resourceName, "status"), + resource.TestCheckResourceAttrPair(datasourceName, "updated_at", resourceName, "updated_at"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.Key1", resourceName, "tags.Key1")), + }, + }, + }) +} + +const testAccFaqDataSourceConfig_nonExistent = ` +data "aws_kendra_faq" "test" { + faq_id = "tf-acc-test-does-not-exist-kendra-faq-id" + index_id = "tf-acc-test-does-not-exist-kendra-id" +} +` + +func testAccFaqDataSourceConfig_basic(rName, rName2, rName3, rName4, rName5 string) string { + return acctest.ConfigCompose( + testAccFaqConfigBase(rName, rName2, rName3, rName4), + fmt.Sprintf(` +resource "aws_kendra_faq" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + file_format = "CSV" + language_code = "en" + role_arn = aws_iam_role.test_faq.arn + + s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } + + tags = { + "Key1" = "Value1" + } +} + +data "aws_kendra_faq" "test" { + faq_id = aws_kendra_faq.test.faq_id + index_id = aws_kendra_index.test.id +} +`, rName5)) +} diff --git a/internal/service/kendra/faq_test.go b/internal/service/kendra/faq_test.go new file mode 100644 index 00000000000..65cfa750c26 --- /dev/null +++ b/internal/service/kendra/faq_test.go @@ -0,0 +1,548 @@ +package kendra_test + +import ( + "context" + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go-v2/service/kendra/types" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfkendra "github.com/hashicorp/terraform-provider-aws/internal/service/kendra" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func testAccFaq_basic(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName4 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName5 := sdkacctest.RandomWithPrefix("resource-test-terraform") + resourceName := "aws_kendra_faq.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckFaqDestroy, + Steps: []resource.TestStep{ + { + Config: testAccFaqConfig_basic(rName, rName2, rName3, rName4, rName5), + Check: resource.ComposeTestCheckFunc( + testAccCheckFaqExists(resourceName), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kendra", regexp.MustCompile(`index/.+/faq/.+$`)), + resource.TestCheckResourceAttrSet(resourceName, "created_at"), + resource.TestCheckResourceAttrSet(resourceName, "faq_id"), + resource.TestCheckResourceAttrPair(resourceName, "index_id", "aws_kendra_index.test", "id"), + resource.TestCheckResourceAttr(resourceName, "language_code", "en"), + resource.TestCheckResourceAttr(resourceName, "name", rName5), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test_faq", "arn"), + resource.TestCheckResourceAttr(resourceName, "s3_path.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "s3_path.0.bucket", "aws_s3_bucket.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "s3_path.0.key", "aws_s3_object.test", "id"), + resource.TestCheckResourceAttr(resourceName, "status", string(types.FaqStatusActive)), + resource.TestCheckResourceAttrSet(resourceName, "updated_at"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccFaq_description(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName4 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName5 := sdkacctest.RandomWithPrefix("resource-test-terraform") + description := "example description for kendra faq" + resourceName := "aws_kendra_faq.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckFaqDestroy, + Steps: []resource.TestStep{ + { + Config: testAccFaqConfig_description(rName, rName2, rName3, rName4, rName5, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckFaqExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", description), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccFaq_fileFormat(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName4 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName5 := sdkacctest.RandomWithPrefix("resource-test-terraform") + fileFormat := string(types.FaqFileFormatCsv) + resourceName := "aws_kendra_faq.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckFaqDestroy, + Steps: []resource.TestStep{ + { + Config: testAccFaqConfig_fileFormat(rName, rName2, rName3, rName4, rName5, fileFormat), + Check: resource.ComposeTestCheckFunc( + testAccCheckFaqExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "file_format", fileFormat), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccFaq_languageCode(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName4 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName5 := sdkacctest.RandomWithPrefix("resource-test-terraform") + languageCode := "en" + resourceName := "aws_kendra_faq.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckFaqDestroy, + Steps: []resource.TestStep{ + { + Config: testAccFaqConfig_languageCode(rName, rName2, rName3, rName4, rName5, languageCode), + Check: resource.ComposeTestCheckFunc( + testAccCheckFaqExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "language_code", languageCode), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccFaq_tags(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName4 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName5 := sdkacctest.RandomWithPrefix("resource-test-terraform") + resourceName := "aws_kendra_faq.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckFaqDestroy, + Steps: []resource.TestStep{ + { + Config: testAccFaqConfig_tags1(rName, rName2, rName3, rName4, rName5, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckFaqExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccFaqConfig_tags2(rName, rName2, rName3, rName4, rName5, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckFaqExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccFaqConfig_tags1(rName, rName2, rName3, rName4, rName5, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckFaqExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func testAccFaq_disappears(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName4 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName5 := sdkacctest.RandomWithPrefix("resource-test-terraform") + resourceName := "aws_kendra_faq.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckFaqDestroy, + Steps: []resource.TestStep{ + { + Config: testAccFaqConfig_basic(rName, rName2, rName3, rName4, rName5), + Check: resource.ComposeTestCheckFunc( + testAccCheckFaqExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfkendra.ResourceFaq(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckFaqDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_kendra_faq" { + continue + } + + id, indexId, err := tfkendra.FaqParseResourceID(rs.Primary.ID) + if err != nil { + return err + } + _, err = tfkendra.FindFaqByID(context.TODO(), conn, id, indexId) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + } + + return nil +} + +func testAccCheckFaqExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Kendra Faq is set") + } + + id, indexId, err := tfkendra.FaqParseResourceID(rs.Primary.ID) + if err != nil { + return err + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + _, err = tfkendra.FindFaqByID(context.TODO(), conn, id, indexId) + + if err != nil { + return fmt.Errorf("Error describing Kendra Faq: %s", err.Error()) + } + + return nil + } +} + +func testAccFaqConfigBase(rName, rName2, rName3, rName4 string) string { + // Kendra IAM policies: https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html + return fmt.Sprintf(` +data "aws_region" "current" {} +data "aws_caller_identity" "current" {} +data "aws_partition" "current" {} +data "aws_kms_key" "this" { + key_id = "alias/aws/kendra" +} +data "aws_iam_policy_document" "test" { + statement { + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["kendra.amazonaws.com"] + } + } +} +data "aws_iam_policy_document" "test_faq" { + statement { + effect = "Allow" + actions = [ + "s3:GetObject" + ] + resources = [ + "${aws_s3_bucket.test.arn}/*" + ] + } +} +data "aws_iam_policy_document" "test_index" { + statement { + effect = "Allow" + actions = [ + "cloudwatch:PutMetricData" + ] + resources = ["*"] + condition { + test = "StringEquals" + variable = "cloudwatch:namespace" + + values = [ + "Kendra" + ] + } + } + + statement { + effect = "Allow" + actions = [ + "logs:DescribeLogGroups" + ] + resources = ["*"] + } + + statement { + effect = "Allow" + actions = [ + "logs:CreateLogGroup" + ] + resources = [ + "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*" + ] + } + + statement { + effect = "Allow" + actions = [ + "logs:DescribeLogStreams", + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + resources = [ + "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*:log-stream:*" + ] + } +} + +resource "aws_iam_policy" "test_faq" { + name = %[1]q + description = "Allow Kendra to access S3" + policy = data.aws_iam_policy_document.test_faq.json +} + +resource "aws_iam_policy" "test_index" { + name = %[2]q + description = "Kendra Index IAM permissions" + policy = data.aws_iam_policy_document.test_index.json +} + +resource "aws_iam_role_policy_attachment" "test_faq" { + role = aws_iam_role.test_faq.name + policy_arn = aws_iam_policy.test_faq.arn +} + +resource "aws_iam_role_policy_attachment" "test_index" { + role = aws_iam_role.test_index.name + policy_arn = aws_iam_policy.test_index.arn +} + +resource "aws_iam_role" "test_faq" { + name = %[1]q + assume_role_policy = data.aws_iam_policy_document.test.json +} + +resource "aws_iam_role" "test_index" { + name = %[2]q + assume_role_policy = data.aws_iam_policy_document.test.json +} + +resource "aws_kendra_index" "test" { + depends_on = [aws_iam_role_policy_attachment.test_index] + name = %[3]q + role_arn = aws_iam_role.test_index.arn +} + +resource "aws_s3_bucket" "test" { + bucket = %[4]q + force_destroy = true +} + +resource "aws_s3_object" "test" { + bucket = aws_s3_bucket.test.bucket + source = "test-fixtures/basic.csv" + key = "test/basic.csv" +} +`, rName, rName2, rName3, rName4) +} + +func testAccFaqConfig_basic(rName, rName2, rName3, rName4, rName5 string) string { + return acctest.ConfigCompose( + testAccFaqConfigBase(rName, rName2, rName3, rName4), + fmt.Sprintf(` +resource "aws_kendra_faq" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test_faq.arn + + s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, rName5)) +} + +func testAccFaqConfig_description(rName, rName2, rName3, rName4, rName5, description string) string { + return acctest.ConfigCompose( + testAccFaqConfigBase(rName, rName2, rName3, rName4), + fmt.Sprintf(` +resource "aws_kendra_faq" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + description = %[2]q + role_arn = aws_iam_role.test_faq.arn + + s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, rName5, description)) +} + +func testAccFaqConfig_fileFormat(rName, rName2, rName3, rName4, rName5, fileFormat string) string { + return acctest.ConfigCompose( + testAccFaqConfigBase(rName, rName2, rName3, rName4), + fmt.Sprintf(` +resource "aws_kendra_faq" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + file_format = %[2]q + role_arn = aws_iam_role.test_faq.arn + + s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, rName5, fileFormat)) +} + +func testAccFaqConfig_languageCode(rName, rName2, rName3, rName4, rName5, languageCode string) string { + return acctest.ConfigCompose( + testAccFaqConfigBase(rName, rName2, rName3, rName4), + fmt.Sprintf(` +resource "aws_kendra_faq" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + language_code = %[2]q + role_arn = aws_iam_role.test_faq.arn + + s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, rName5, languageCode)) +} + +func testAccFaqConfig_tags1(rName, rName2, rName3, rName4, rName5, tag, value string) string { + return acctest.ConfigCompose( + testAccFaqConfigBase(rName, rName2, rName3, rName4), + fmt.Sprintf(` +resource "aws_kendra_faq" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test_faq.arn + + s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } + + tags = { + %[2]q = %[3]q + } +} +`, rName5, tag, value)) +} + +func testAccFaqConfig_tags2(rName, rName2, rName3, rName4, rName5, tag1, value1, tag2, value2 string) string { + return acctest.ConfigCompose( + testAccFaqConfigBase(rName, rName2, rName3, rName4), + fmt.Sprintf(` +resource "aws_kendra_faq" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test_faq.arn + + s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName5, tag1, value1, tag2, value2)) +} diff --git a/internal/service/kendra/find.go b/internal/service/kendra/find.go new file mode 100644 index 00000000000..c471ffea62b --- /dev/null +++ b/internal/service/kendra/find.go @@ -0,0 +1,93 @@ +package kendra + +import ( + "context" + "errors" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kendra" + "github.com/aws/aws-sdk-go-v2/service/kendra/types" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func FindFaqByID(ctx context.Context, conn *kendra.Client, id, indexId string) (*kendra.DescribeFaqOutput, error) { + in := &kendra.DescribeFaqInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + } + + out, err := conn.DescribeFaq(ctx, in) + + var resourceNotFoundException *types.ResourceNotFoundException + if errors.As(err, &resourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: in, + } + } + + if err != nil { + return nil, err + } + + if out == nil { + return nil, tfresource.NewEmptyResultError(in) + } + + return out, nil +} + +func FindQuerySuggestionsBlockListByID(ctx context.Context, conn *kendra.Client, id, indexId string) (*kendra.DescribeQuerySuggestionsBlockListOutput, error) { + in := &kendra.DescribeQuerySuggestionsBlockListInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + } + + out, err := conn.DescribeQuerySuggestionsBlockList(ctx, in) + if err != nil { + var resourceNotFoundException *types.ResourceNotFoundException + + if errors.As(err, &resourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: in, + } + } + + return nil, err + } + + if out == nil { + return nil, tfresource.NewEmptyResultError(in) + } + + return out, nil +} + +func FindThesaurusByID(ctx context.Context, conn *kendra.Client, id, indexId string) (*kendra.DescribeThesaurusOutput, error) { + in := &kendra.DescribeThesaurusInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + } + + out, err := conn.DescribeThesaurus(ctx, in) + + var resourceNotFoundException *types.ResourceNotFoundException + if errors.As(err, &resourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: in, + } + } + + if err != nil { + return nil, err + } + + if out == nil { + return nil, tfresource.NewEmptyResultError(in) + } + + return out, nil +} diff --git a/internal/service/kendra/flex.go b/internal/service/kendra/flex.go new file mode 100644 index 00000000000..7e80eb972e7 --- /dev/null +++ b/internal/service/kendra/flex.go @@ -0,0 +1,47 @@ +package kendra + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kendra/types" +) + +func expandSourceS3Path(tfList []interface{}) *types.S3Path { + if len(tfList) == 0 || tfList[0] == nil { + return nil + } + + tfMap, ok := tfList[0].(map[string]interface{}) + if !ok { + return nil + } + + result := &types.S3Path{} + + if v, ok := tfMap["bucket"].(string); ok && v != "" { + result.Bucket = aws.String(v) + } + + if v, ok := tfMap["key"].(string); ok && v != "" { + result.Key = aws.String(v) + } + + return result +} + +func flattenSourceS3Path(apiObject *types.S3Path) []interface{} { + if apiObject == nil { + return nil + } + + m := map[string]interface{}{} + + if v := apiObject.Bucket; v != nil { + m["bucket"] = aws.ToString(v) + } + + if v := apiObject.Key; v != nil { + m["key"] = aws.ToString(v) + } + + return []interface{}{m} +} diff --git a/internal/service/kendra/id.go b/internal/service/kendra/id.go new file mode 100644 index 00000000000..ba2d1756de1 --- /dev/null +++ b/internal/service/kendra/id.go @@ -0,0 +1,46 @@ +package kendra + +import ( + "fmt" + "strings" +) + +func ExperienceParseResourceID(id string) (string, string, error) { + parts := strings.Split(id, "/") + + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", fmt.Errorf("please make sure ID is in format EXPERIENCE_ID/INDEX_ID") + } + + return parts[0], parts[1], nil +} + +func FaqParseResourceID(id string) (string, string, error) { + parts := strings.Split(id, "/") + + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", fmt.Errorf("please make sure ID is in format FAQ_ID/INDEX_ID") + } + + return parts[0], parts[1], nil +} + +func QuerySuggestionsBlockListParseResourceID(id string) (string, string, error) { + parts := strings.Split(id, "/") + + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", fmt.Errorf("please make sure ID is in format QUERY_SUGGESTIONS_BLOCK_LIST_ID/INDEX_ID") + } + + return parts[0], parts[1], nil +} + +func ThesaurusParseResourceID(id string) (string, string, error) { + parts := strings.Split(id, "/") + + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", fmt.Errorf("please make sure ID is in format THESAURUS_ID/INDEX_ID") + } + + return parts[0], parts[1], nil +} diff --git a/internal/service/kendra/id_test.go b/internal/service/kendra/id_test.go new file mode 100644 index 00000000000..7e5eb25eef2 --- /dev/null +++ b/internal/service/kendra/id_test.go @@ -0,0 +1,211 @@ +package kendra_test + +import ( + "testing" + + tfkendra "github.com/hashicorp/terraform-provider-aws/internal/service/kendra" +) + +func TestExperienceParseResourceID(t *testing.T) { + testCases := []struct { + TestName string + Input string + ExpectedId string + ExpectedIndexId string + Error bool + }{ + { + TestName: "empty", + Input: "", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Invalid ID", + Input: "abcdefg12345678/", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Invalid ID separator", + Input: "abcdefg12345678:qwerty09876", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Invalid ID with more than 1 separator", + Input: "abcdefg12345678/qwerty09876/zxcvbnm123456", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Valid ID", + Input: "abcdefg12345678/qwerty09876", + ExpectedId: "abcdefg12345678", + ExpectedIndexId: "qwerty09876", + Error: false, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.TestName, func(t *testing.T) { + gotId, gotIndexId, err := tfkendra.ExperienceParseResourceID(testCase.Input) + + if err != nil && !testCase.Error { + t.Errorf("got error (%s), expected no error", err) + } + + if err == nil && testCase.Error { + t.Errorf("got (Id: %s, IndexId: %s) and no error, expected error", gotId, gotIndexId) + } + + if gotId != testCase.ExpectedId { + t.Errorf("got %s, expected %s", gotId, testCase.ExpectedIndexId) + } + + if gotIndexId != testCase.ExpectedIndexId { + t.Errorf("got %s, expected %s", gotIndexId, testCase.ExpectedIndexId) + } + }) + } +} + +func TestQuerySuggestionsBlockListParseID(t *testing.T) { + testCases := []struct { + TestName string + Input string + ExpectedId string + ExpectedIndexId string + Error bool + }{ + { + TestName: "empty", + Input: "", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Invalid ID", + Input: "abcdefg12345678/", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Invalid ID separator", + Input: "abcdefg12345678:qwerty09876", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Invalid ID with more than 1 separator", + Input: "abcdefg12345678/qwerty09876/zxcvbnm123456", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Valid ID", + Input: "abcdefg12345678/qwerty09876", + ExpectedId: "abcdefg12345678", + ExpectedIndexId: "qwerty09876", + Error: false, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.TestName, func(t *testing.T) { + gotId, gotIndexId, err := tfkendra.QuerySuggestionsBlockListParseResourceID(testCase.Input) + + if err != nil && !testCase.Error { + t.Errorf("got error (%s), expected no error", err) + } + + if err == nil && testCase.Error { + t.Errorf("got (Id: %s, IndexId: %s) and no error, expected error", gotId, gotIndexId) + } + + if gotId != testCase.ExpectedId { + t.Errorf("got %s, expected %s", gotId, testCase.ExpectedIndexId) + } + + if gotIndexId != testCase.ExpectedIndexId { + t.Errorf("got %s, expected %s", gotIndexId, testCase.ExpectedIndexId) + } + }) + } +} + +func TestThesaurusParseResourceID(t *testing.T) { + testCases := []struct { + TestName string + Input string + ExpectedId string + ExpectedIndexId string + Error bool + }{ + { + TestName: "empty", + Input: "", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Invalid ID", + Input: "abcdefg12345678/", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Invalid ID separator", + Input: "abcdefg12345678:qwerty09876", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Invalid ID with more than 1 separator", + Input: "abcdefg12345678/qwerty09876/zxcvbnm123456", + ExpectedId: "", + ExpectedIndexId: "", + Error: true, + }, + { + TestName: "Valid ID", + Input: "abcdefg12345678/qwerty09876", + ExpectedId: "abcdefg12345678", + ExpectedIndexId: "qwerty09876", + Error: false, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.TestName, func(t *testing.T) { + gotId, gotIndexId, err := tfkendra.ThesaurusParseResourceID(testCase.Input) + + if err != nil && !testCase.Error { + t.Errorf("got error (%s), expected no error", err) + } + + if err == nil && testCase.Error { + t.Errorf("got (Id: %s, IndexId: %s) and no error, expected error", gotId, gotIndexId) + } + + if gotId != testCase.ExpectedId { + t.Errorf("got %s, expected %s", gotId, testCase.ExpectedIndexId) + } + + if gotIndexId != testCase.ExpectedIndexId { + t.Errorf("got %s, expected %s", gotIndexId, testCase.ExpectedIndexId) + } + }) + } +} diff --git a/internal/service/kendra/index.go b/internal/service/kendra/index.go new file mode 100644 index 00000000000..c3ab1ebdb15 --- /dev/null +++ b/internal/service/kendra/index.go @@ -0,0 +1,1091 @@ +package kendra + +import ( + "context" + "errors" + "fmt" + "log" + "regexp" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/kendra" + "github.com/aws/aws-sdk-go-v2/service/kendra/types" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "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" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +const ( + // Allow IAM role to become visible to the index + propagationTimeout = 2 * time.Minute + + // validationExceptionMessage describes the error returned when the IAM role has not yet propagated + validationExceptionMessage = "Please make sure your role exists and has `kendra.amazonaws.com` as trusted entity" +) + +func ResourceIndex() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIndexCreate, + ReadContext: resourceIndexRead, + UpdateContext: resourceIndexUpdate, + DeleteContext: resourceIndexDelete, + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(60 * time.Minute), + Update: schema.DefaultTimeout(60 * time.Minute), + Delete: schema.DefaultTimeout(60 * time.Minute), + }, + CustomizeDiff: verify.SetTagsDiff, + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "capacity_units": { + Type: schema.TypeList, + Computed: true, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "query_capacity_units": { + Type: schema.TypeInt, + Computed: true, + Optional: true, + ValidateFunc: validation.IntAtLeast(0), + }, + "storage_capacity_units": { + Type: schema.TypeInt, + Computed: true, + Optional: true, + ValidateFunc: validation.IntAtLeast(0), + }, + }, + }, + }, + "created_at": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(1, 1000), + }, + "document_metadata_configuration_updates": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + }, + "relevance": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "duration": { + Type: schema.TypeString, + Computed: true, + }, + "freshness": { + Type: schema.TypeBool, + Computed: true, + }, + "importance": { + Type: schema.TypeInt, + Computed: true, + }, + "rank_order": { + Type: schema.TypeString, + Computed: true, + }, + "values_importance_map": { + Type: schema.TypeMap, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeInt}, + }, + }, + }, + }, + "search": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "displayable": { + Type: schema.TypeBool, + Computed: true, + }, + "facetable": { + Type: schema.TypeBool, + Computed: true, + }, + "searchable": { + Type: schema.TypeBool, + Computed: true, + }, + "sortable": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "edition": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: string(types.IndexEditionEnterpriseEdition), + ValidateFunc: validation.StringInSlice(indexEditionValues(types.IndexEdition("").Values()...), false), + }, + "error_message": { + Type: schema.TypeString, + Computed: true, + }, + "index_statistics": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "faq_statistics": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "indexed_question_answers_count": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "text_document_statistics": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "indexed_text_bytes": { + Type: schema.TypeInt, + Computed: true, + }, + "indexed_text_documents_count": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 1000), + validation.StringMatch( + regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9_-]*`), + "The name must consist of alphanumerics, hyphens or underscores.", + ), + ), + }, + "role_arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidARN, + }, + "server_side_encryption_configuration": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "kms_key_id": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 2048), + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_at": { + Type: schema.TypeString, + Computed: true, + }, + "user_context_policy": { + Type: schema.TypeString, + Optional: true, + Default: string(types.UserContextPolicyAttributeFilter), + ValidateFunc: validation.StringInSlice(userContextPolicyValues(types.UserContextPolicy("").Values()...), false), + }, + "user_group_resolution_configuration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "user_group_resolution_mode": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(userGroupResolutionModeValues(types.UserGroupResolutionMode("").Values()...), false), + }, + }, + }, + }, + "user_token_configurations": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "json_token_type_configuration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "group_attribute_field": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 2048), + }, + "user_name_attribute_field": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 2048), + }, + }, + }, + }, + "jwt_token_type_configuration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "claim_regex": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(1, 100), + }, + "group_attribute_field": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(1, 100), + }, + "issuer": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(1, 65), + }, + "key_location": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(keyLocationValues(types.KeyLocation("").Values()...), false), + }, + "secrets_manager_arn": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: verify.ValidARN, + }, + "url": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 2048), + validation.StringMatch( + regexp.MustCompile(`^(https?|ftp|file):\/\/([^\s]*)`), + "Must be valid URL", + ), + ), + }, + "user_name_attribute_field": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(1, 100), + }, + }, + }, + }, + }, + }, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + } +} + +func resourceIndexCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + name := d.Get("name").(string) + + input := &kendra.CreateIndexInput{ + ClientToken: aws.String(resource.UniqueId()), + Name: aws.String(name), + RoleArn: aws.String(d.Get("role_arn").(string)), + } + + if v, ok := d.GetOk("description"); ok { + input.Description = aws.String(v.(string)) + } + + if v, ok := d.GetOk("edition"); ok { + input.Edition = types.IndexEdition(v.(string)) + } + + if v, ok := d.GetOk("server_side_encryption_configuration"); ok { + input.ServerSideEncryptionConfiguration = expandServerSideEncryptionConfiguration(v.([]interface{})) + } + + if v, ok := d.GetOk("user_context_policy"); ok { + input.UserContextPolicy = types.UserContextPolicy(v.(string)) + } + + if v, ok := d.GetOk("user_group_resolution_configuration"); ok { + input.UserGroupResolutionConfiguration = expandUserGroupResolutionConfiguration(v.([]interface{})) + } + + if v, ok := d.GetOk("user_token_configurations"); ok { + input.UserTokenConfigurations = expandUserTokenConfigurations(v.([]interface{})) + } + + if len(tags) > 0 { + input.Tags = Tags(tags.IgnoreAWS()) + } + + log.Printf("[DEBUG] Creating Kendra Index %#v", input) + + outputRaw, err := tfresource.RetryWhen( + propagationTimeout, + func() (interface{}, error) { + return conn.CreateIndex(ctx, input) + }, + func(err error) (bool, error) { + var validationException *types.ValidationException + + if errors.As(err, &validationException) && strings.Contains(validationException.ErrorMessage(), validationExceptionMessage) { + return true, err + } + + return false, err + }, + ) + + if err != nil { + return diag.Errorf("error creating Kendra Index (%s): %s", name, err) + } + + if outputRaw == nil { + return diag.Errorf("error creating Kendra Index (%s): empty output", name) + } + + output := outputRaw.(*kendra.CreateIndexOutput) + + d.SetId(aws.ToString(output.Id)) + + // waiter since the status changes from CREATING to either ACTIVE or FAILED + if _, err := waitIndexCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return diag.Errorf("error waiting for Index (%s) creation: %s", d.Id(), err) + } + + // CreateIndex API does not support capacity_units but UpdateIndex does + if v, ok := d.GetOk("capacity_units"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + return resourceIndexUpdate(ctx, d, meta) + } + + return resourceIndexRead(ctx, d, meta) +} + +func resourceIndexRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + resp, err := findIndexByID(ctx, conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Kendra Index (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return diag.Errorf("error getting Kendra Index (%s): %s", d.Id(), err) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: "kendra", + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("index/%s", d.Id()), + }.String() + + d.Set("arn", arn) + d.Set("created_at", aws.ToTime(resp.CreatedAt).Format(time.RFC3339)) + d.Set("description", resp.Description) + d.Set("edition", resp.Edition) + d.Set("error_message", resp.ErrorMessage) + d.Set("name", resp.Name) + d.Set("role_arn", resp.RoleArn) + d.Set("status", resp.Status) + d.Set("updated_at", aws.ToTime(resp.UpdatedAt).Format(time.RFC3339)) + d.Set("user_context_policy", resp.UserContextPolicy) + + if err := d.Set("capacity_units", flattenCapacityUnits(resp.CapacityUnits)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("document_metadata_configuration_updates", flattenDocumentMetadataConfigurations(resp.DocumentMetadataConfigurations)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("index_statistics", flattenIndexStatistics(resp.IndexStatistics)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("server_side_encryption_configuration", flattenServerSideEncryptionConfiguration(resp.ServerSideEncryptionConfiguration)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("user_group_resolution_configuration", flattenUserGroupResolutionConfiguration(resp.UserGroupResolutionConfiguration)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("user_token_configurations", flattenUserTokenConfigurations(resp.UserTokenConfigurations)); err != nil { + return diag.FromErr(err) + } + + tags, err := ListTags(ctx, conn, d.Get("arn").(string)) + if err != nil { + return diag.Errorf("error listing tags for resource (%s): %s", d.Get("arn").(string), err) + } + tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return diag.Errorf("error setting tags: %s", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return diag.Errorf("error setting tags_all: %s", err) + } + + return nil +} + +func resourceIndexUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + id := d.Id() + + if d.HasChanges("capacity_units", "description", "name", "role_arn", "user_context_policy", "user_group_resolution_configuration", "user_token_configurations") { + input := &kendra.UpdateIndexInput{ + Id: aws.String(id), + } + if d.HasChange("capacity_units") { + input.CapacityUnits = expandCapacityUnits(d.Get("capacity_units").([]interface{})) + } + if d.HasChange("description") { + input.Description = aws.String(d.Get("description").(string)) + } + if d.HasChange("name") { + input.Name = aws.String(d.Get("name").(string)) + } + if d.HasChange("role_arn") { + input.RoleArn = aws.String(d.Get("role_arn").(string)) + } + if d.HasChange("user_context_policy") { + input.UserContextPolicy = types.UserContextPolicy(d.Get("user_context_policy").(string)) + } + if d.HasChange("user_group_resolution_configuration") { + input.UserGroupResolutionConfiguration = expandUserGroupResolutionConfiguration(d.Get("user_group_resolution_configuration").([]interface{})) + } + if d.HasChange("user_token_configurations") { + input.UserTokenConfigurations = expandUserTokenConfigurations(d.Get("user_token_configurations").([]interface{})) + } + + _, err := tfresource.RetryWhen( + propagationTimeout, + func() (interface{}, error) { + return conn.UpdateIndex(ctx, input) + }, + func(err error) (bool, error) { + var validationException *types.ValidationException + + if errors.As(err, &validationException) && strings.Contains(validationException.ErrorMessage(), validationExceptionMessage) { + return true, err + } + + return false, err + }, + ) + + if err != nil { + return diag.Errorf("error updating Index (%s): %s", d.Id(), err) + } + + // waiter since the status changes from UPDATING to either ACTIVE or FAILED + if _, err := waitIndexUpdated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return diag.Errorf("error waiting for Index (%s) update: %s", d.Id(), err) + } + } + + if !d.IsNewResource() && d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + if err := UpdateTags(ctx, conn, d.Get("arn").(string), o, n); err != nil { + return diag.Errorf("error updating tags: %s", err) + } + } + + return resourceIndexRead(ctx, d, meta) +} + +func resourceIndexDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + id := d.Id() + + _, err := conn.DeleteIndex(ctx, &kendra.DeleteIndexInput{ + Id: aws.String(id), + }) + + if err != nil { + return diag.Errorf("error deleting Index (%s): %s", d.Id(), err) + } + + if _, err := waitIndexDeleted(ctx, conn, id, d.Timeout(schema.TimeoutDelete)); err != nil { + return diag.Errorf("error waiting for Index (%s) delete: %s", d.Id(), err) + } + + return nil +} + +func findIndexByID(ctx context.Context, conn *kendra.Client, id string) (*kendra.DescribeIndexOutput, error) { + input := &kendra.DescribeIndexInput{ + Id: aws.String(id), + } + + output, err := conn.DescribeIndex(ctx, input) + + if err != nil { + var resourceNotFoundException *types.ResourceNotFoundException + + if errors.As(err, &resourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} + +func statusIndex(ctx context.Context, conn *kendra.Client, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findIndexByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status), nil + } +} + +func waitIndexCreated(ctx context.Context, conn *kendra.Client, id string, timeout time.Duration) (*kendra.DescribeIndexOutput, error) { + + stateConf := &resource.StateChangeConf{ + Pending: IndexStatusValues(types.IndexStatusCreating), + Target: IndexStatusValues(types.IndexStatusActive), + Timeout: timeout, + Refresh: statusIndex(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*kendra.DescribeIndexOutput); ok { + if output.Status == types.IndexStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.ErrorMessage))) + } + return output, err + } + + return nil, err +} + +func waitIndexUpdated(ctx context.Context, conn *kendra.Client, id string, timeout time.Duration) (*kendra.DescribeIndexOutput, error) { + + stateConf := &resource.StateChangeConf{ + Pending: IndexStatusValues(types.IndexStatusUpdating), + Target: IndexStatusValues(types.IndexStatusActive), + Timeout: timeout, + Refresh: statusIndex(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*kendra.DescribeIndexOutput); ok { + if output.Status == types.IndexStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.ErrorMessage))) + } + return output, err + } + + return nil, err +} + +func waitIndexDeleted(ctx context.Context, conn *kendra.Client, id string, timeout time.Duration) (*kendra.DescribeIndexOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: IndexStatusValues(types.IndexStatusDeleting), + Target: []string{}, + Timeout: timeout, + Refresh: statusIndex(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*kendra.DescribeIndexOutput); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.ErrorMessage))) + + return output, err + } + + return nil, err +} + +func expandCapacityUnits(capacityUnits []interface{}) *types.CapacityUnitsConfiguration { + if len(capacityUnits) == 0 || capacityUnits[0] == nil { + return nil + } + + tfMap, ok := capacityUnits[0].(map[string]interface{}) + if !ok { + return nil + } + + result := &types.CapacityUnitsConfiguration{ + QueryCapacityUnits: aws.Int32(int32(tfMap["query_capacity_units"].(int))), + StorageCapacityUnits: aws.Int32(int32(tfMap["storage_capacity_units"].(int))), + } + + return result +} + +func expandServerSideEncryptionConfiguration(serverSideEncryptionConfiguration []interface{}) *types.ServerSideEncryptionConfiguration { + if len(serverSideEncryptionConfiguration) == 0 || serverSideEncryptionConfiguration[0] == nil { + return nil + } + + tfMap, ok := serverSideEncryptionConfiguration[0].(map[string]interface{}) + if !ok { + return nil + } + + result := &types.ServerSideEncryptionConfiguration{} + + if v, ok := tfMap["kms_key_id"].(string); ok && v != "" { + result.KmsKeyId = aws.String(v) + } + + return result +} + +func expandUserGroupResolutionConfiguration(userGroupResolutionConfiguration []interface{}) *types.UserGroupResolutionConfiguration { + if len(userGroupResolutionConfiguration) == 0 || userGroupResolutionConfiguration[0] == nil { + return nil + } + + tfMap, ok := userGroupResolutionConfiguration[0].(map[string]interface{}) + if !ok { + return nil + } + + result := &types.UserGroupResolutionConfiguration{ + UserGroupResolutionMode: types.UserGroupResolutionMode(tfMap["user_group_resolution_mode"].(string)), + } + + return result +} + +func expandUserTokenConfigurations(userTokenConfigurations []interface{}) []types.UserTokenConfiguration { + if len(userTokenConfigurations) == 0 { + return nil + } + + userTokenConfigurationsConfigs := []types.UserTokenConfiguration{} + + for _, userTokenConfiguration := range userTokenConfigurations { + tfMap := userTokenConfiguration.(map[string]interface{}) + userTokenConfigurationConfig := types.UserTokenConfiguration{} + + if v, ok := tfMap["json_token_type_configuration"].([]interface{}); ok && len(v) > 0 { + userTokenConfigurationConfig.JsonTokenTypeConfiguration = expandJSONTokenTypeConfiguration(v) + } + + if v, ok := tfMap["jwt_token_type_configuration"].([]interface{}); ok && len(v) > 0 { + userTokenConfigurationConfig.JwtTokenTypeConfiguration = expandJwtTokenTypeConfiguration(v) + } + + userTokenConfigurationsConfigs = append(userTokenConfigurationsConfigs, userTokenConfigurationConfig) + } + + return userTokenConfigurationsConfigs +} + +func expandJSONTokenTypeConfiguration(jsonTokenTypeConfiguration []interface{}) *types.JsonTokenTypeConfiguration { + if len(jsonTokenTypeConfiguration) == 0 || jsonTokenTypeConfiguration[0] == nil { + return nil + } + + tfMap, ok := jsonTokenTypeConfiguration[0].(map[string]interface{}) + if !ok { + return nil + } + + result := &types.JsonTokenTypeConfiguration{ + GroupAttributeField: aws.String(tfMap["group_attribute_field"].(string)), + UserNameAttributeField: aws.String(tfMap["user_name_attribute_field"].(string)), + } + + return result +} + +func expandJwtTokenTypeConfiguration(jwtTokenTypeConfiguration []interface{}) *types.JwtTokenTypeConfiguration { + if len(jwtTokenTypeConfiguration) == 0 || jwtTokenTypeConfiguration[0] == nil { + return nil + } + + tfMap, ok := jwtTokenTypeConfiguration[0].(map[string]interface{}) + if !ok { + return nil + } + + result := &types.JwtTokenTypeConfiguration{ + KeyLocation: types.KeyLocation(tfMap["key_location"].(string)), + } + + if v, ok := tfMap["claim_regex"].(string); ok && v != "" { + result.ClaimRegex = aws.String(v) + } + + if v, ok := tfMap["group_attribute_field"].(string); ok && v != "" { + result.GroupAttributeField = aws.String(v) + } + + if v, ok := tfMap["issuer"].(string); ok && v != "" { + result.Issuer = aws.String(v) + } + + if v, ok := tfMap["secrets_manager_arn"].(string); ok && v != "" { + result.SecretManagerArn = aws.String(v) + } + + if v, ok := tfMap["url"].(string); ok && v != "" { + result.URL = aws.String(v) + } + + if v, ok := tfMap["user_name_attribute_field"].(string); ok && v != "" { + result.UserNameAttributeField = aws.String(v) + } + + return result +} + +func flattenCapacityUnits(capacityUnits *types.CapacityUnitsConfiguration) []interface{} { + if capacityUnits == nil { + return []interface{}{} + } + + values := map[string]interface{}{ + "query_capacity_units": aws.ToInt32(capacityUnits.QueryCapacityUnits), + "storage_capacity_units": aws.ToInt32(capacityUnits.StorageCapacityUnits), + } + + return []interface{}{values} +} + +func flattenDocumentMetadataConfigurations(documentMetadataConfigurations []types.DocumentMetadataConfiguration) []interface{} { + documentMetadataConfigurationsList := []interface{}{} + + for _, documentMetadataConfiguration := range documentMetadataConfigurations { + values := map[string]interface{}{ + "name": documentMetadataConfiguration.Name, + "relevance": flattenRelevance(documentMetadataConfiguration.Relevance), + "search": flattenSearch(documentMetadataConfiguration.Search), + "type": documentMetadataConfiguration.Type, + } + + documentMetadataConfigurationsList = append(documentMetadataConfigurationsList, values) + } + + return documentMetadataConfigurationsList +} + +func flattenRelevance(relevance *types.Relevance) []interface{} { + if relevance == nil { + return []interface{}{} + } + + values := map[string]interface{}{ + "rank_order": relevance.RankOrder, + } + + if v := relevance.Duration; v != nil { + values["duration"] = aws.ToString(v) + } + + if v := relevance.Freshness; v != nil { + values["freshness"] = aws.ToBool(v) + } + + if v := relevance.Importance; v != nil { + values["importance"] = aws.ToInt32(v) + } + + if v := relevance.ValueImportanceMap; v != nil { + values["values_importance_map"] = v + } + + return []interface{}{values} +} + +func flattenSearch(search *types.Search) []interface{} { + if search == nil { + return []interface{}{} + } + + values := map[string]interface{}{ + "displayable": search.Displayable, + "facetable": search.Facetable, + "searchable": search.Searchable, + "sortable": search.Sortable, + } + + return []interface{}{values} +} + +func flattenIndexStatistics(indexStatistics *types.IndexStatistics) []interface{} { + if indexStatistics == nil { + return []interface{}{} + } + + values := map[string]interface{}{ + "faq_statistics": flattenFaqStatistics(indexStatistics.FaqStatistics), + "text_document_statistics": flattenTextDocumentStatistics(indexStatistics.TextDocumentStatistics), + } + + return []interface{}{values} +} + +func flattenFaqStatistics(faqStatistics *types.FaqStatistics) []interface{} { + if faqStatistics == nil { + return []interface{}{} + } + + values := map[string]interface{}{ + "indexed_question_answers_count": aws.ToInt32(&faqStatistics.IndexedQuestionAnswersCount), + } + + return []interface{}{values} +} + +func flattenTextDocumentStatistics(textDocumentStatistics *types.TextDocumentStatistics) []interface{} { + if textDocumentStatistics == nil { + return []interface{}{} + } + + values := map[string]interface{}{ + "indexed_text_bytes": aws.ToInt64(&textDocumentStatistics.IndexedTextBytes), + "indexed_text_documents_count": aws.ToInt32(&textDocumentStatistics.IndexedTextDocumentsCount), + } + + return []interface{}{values} +} + +func flattenServerSideEncryptionConfiguration(serverSideEncryptionConfiguration *types.ServerSideEncryptionConfiguration) []interface{} { + if serverSideEncryptionConfiguration == nil { + return []interface{}{} + } + + values := map[string]interface{}{} + + if v := serverSideEncryptionConfiguration.KmsKeyId; v != nil { + values["kms_key_id"] = aws.ToString(v) + } + + return []interface{}{values} +} + +func flattenUserGroupResolutionConfiguration(userGroupResolutionConfiguration *types.UserGroupResolutionConfiguration) []interface{} { + if userGroupResolutionConfiguration == nil { + return []interface{}{} + } + + values := map[string]interface{}{ + "user_group_resolution_configuration": userGroupResolutionConfiguration.UserGroupResolutionMode, + } + + return []interface{}{values} +} + +func flattenUserTokenConfigurations(userTokenConfigurations []types.UserTokenConfiguration) []interface{} { + userTokenConfigurationsList := []interface{}{} + + for _, userTokenConfiguration := range userTokenConfigurations { + values := map[string]interface{}{} + + if v := userTokenConfiguration.JsonTokenTypeConfiguration; v != nil { + values["json_token_type_configuration"] = flattenJSONTokenTypeConfiguration(v) + } + + if v := userTokenConfiguration.JwtTokenTypeConfiguration; v != nil { + values["jwt_token_type_configuration"] = flattenJwtTokenTypeConfiguration(v) + } + + userTokenConfigurationsList = append(userTokenConfigurationsList, values) + } + + return userTokenConfigurationsList +} + +func flattenJSONTokenTypeConfiguration(jsonTokenTypeConfiguration *types.JsonTokenTypeConfiguration) []interface{} { + if jsonTokenTypeConfiguration == nil { + return []interface{}{} + } + + values := map[string]interface{}{ + "group_attribute_field": jsonTokenTypeConfiguration.GroupAttributeField, + "user_name_attribute_field": jsonTokenTypeConfiguration.UserNameAttributeField, + } + + return []interface{}{values} +} + +func flattenJwtTokenTypeConfiguration(jwtTokenTypeConfiguration *types.JwtTokenTypeConfiguration) []interface{} { + if jwtTokenTypeConfiguration == nil { + return []interface{}{} + } + + values := map[string]interface{}{ + "key_location": jwtTokenTypeConfiguration.KeyLocation, + } + + if v := jwtTokenTypeConfiguration.ClaimRegex; v != nil { + values["claim_regex"] = aws.ToString(v) + } + + if v := jwtTokenTypeConfiguration.GroupAttributeField; v != nil { + values["group_attribute_field"] = aws.ToString(v) + } + + if v := jwtTokenTypeConfiguration.Issuer; v != nil { + values["issuer"] = aws.ToString(v) + } + + if v := jwtTokenTypeConfiguration.SecretManagerArn; v != nil { + values["secrets_manager_arn"] = aws.ToString(v) + } + + if v := jwtTokenTypeConfiguration.URL; v != nil { + values["url"] = aws.ToString(v) + } + + if v := jwtTokenTypeConfiguration.UserNameAttributeField; v != nil { + values["user_name_attribute_field"] = aws.ToString(v) + } + + return []interface{}{values} +} + +// Helpers added. Could be generated or somehow use go 1.18 generics? +func indexEditionValues(input ...types.IndexEdition) []string { + var output []string + + for _, v := range input { + output = append(output, string(v)) + } + + return output +} + +func userContextPolicyValues(input ...types.UserContextPolicy) []string { + var output []string + + for _, v := range input { + output = append(output, string(v)) + } + + return output +} + +func userGroupResolutionModeValues(input ...types.UserGroupResolutionMode) []string { + var output []string + + for _, v := range input { + output = append(output, string(v)) + } + + return output +} + +func keyLocationValues(input ...types.KeyLocation) []string { + var output []string + + for _, v := range input { + output = append(output, string(v)) + } + + return output +} + +func IndexStatusValues(input ...types.IndexStatus) []string { + var output []string + + for _, v := range input { + output = append(output, string(v)) + } + + return output +} diff --git a/internal/service/kendra/index_data_source.go b/internal/service/kendra/index_data_source.go new file mode 100644 index 00000000000..5c33edf8df9 --- /dev/null +++ b/internal/service/kendra/index_data_source.go @@ -0,0 +1,352 @@ +package kendra + +import ( + "context" + "fmt" + "regexp" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" +) + +func DataSourceIndex() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIndexRead, + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "capacity_units": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "query_capacity_units": { + Type: schema.TypeInt, + Computed: true, + }, + "storage_capacity_units": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "created_at": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "document_metadata_configuration_updates": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + }, + "relevance": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "duration": { + Type: schema.TypeString, + Computed: true, + }, + "freshness": { + Type: schema.TypeBool, + Computed: true, + }, + "importance": { + Type: schema.TypeInt, + Computed: true, + }, + "rank_order": { + Type: schema.TypeString, + Computed: true, + }, + "values_importance_map": { + Type: schema.TypeMap, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeInt}, + }, + }, + }, + }, + "search": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "displayable": { + Type: schema.TypeBool, + Computed: true, + }, + "facetable": { + Type: schema.TypeBool, + Computed: true, + }, + "searchable": { + Type: schema.TypeBool, + Computed: true, + }, + "sortable": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "edition": { + Type: schema.TypeString, + Computed: true, + }, + "error_message": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile(`[a-zA-Z0-9][a-zA-Z0-9-]{35}`), + "Starts with an alphanumeric character. Subsequently, can contain alphanumeric characters and hyphens. Fixed length of 36.", + ), + }, + "index_statistics": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "faq_statistics": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "indexed_question_answers_count": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "text_document_statistics": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "indexed_text_bytes": { + Type: schema.TypeInt, + Computed: true, + }, + "indexed_text_documents_count": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "role_arn": { + Type: schema.TypeString, + Computed: true, + }, + "server_side_encryption_configuration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "kms_key_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_at": { + Type: schema.TypeString, + Computed: true, + }, + "user_context_policy": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_resolution_configuration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "user_group_resolution_mode": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "user_token_configurations": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "json_token_type_configuration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "group_attribute_field": { + Type: schema.TypeString, + Computed: true, + }, + "user_name_attribute_field": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "jwt_token_type_configuration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "claim_regex": { + Type: schema.TypeString, + Computed: true, + }, + "group_attribute_field": { + Type: schema.TypeString, + Computed: true, + }, + "issuer": { + Type: schema.TypeString, + Computed: true, + }, + "key_location": { + Type: schema.TypeString, + Computed: true, + }, + "secrets_manager_arn": { + Type: schema.TypeString, + Computed: true, + }, + "url": { + Type: schema.TypeString, + Computed: true, + }, + "user_name_attribute_field": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "tags": tftags.TagsSchemaComputed(), + }, + } +} + +func dataSourceIndexRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + id := d.Get("id").(string) + + resp, err := findIndexByID(ctx, conn, id) + + if err != nil { + return diag.Errorf("error getting Kendra Index (%s): %s", id, err) + } + + if resp == nil { + return diag.Errorf("error getting Kendra Index (%s): empty response", id) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: "kendra", + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("index/%s", id), + }.String() + + d.Set("arn", arn) + d.Set("created_at", aws.ToTime(resp.CreatedAt).Format(time.RFC3339)) + d.Set("description", resp.Description) + d.Set("edition", resp.Edition) + d.Set("error_message", resp.ErrorMessage) + d.Set("name", resp.Name) + d.Set("role_arn", resp.RoleArn) + d.Set("status", resp.Status) + d.Set("updated_at", aws.ToTime(resp.UpdatedAt).Format(time.RFC3339)) + d.Set("user_context_policy", resp.UserContextPolicy) + + if err := d.Set("capacity_units", flattenCapacityUnits(resp.CapacityUnits)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("document_metadata_configuration_updates", flattenDocumentMetadataConfigurations(resp.DocumentMetadataConfigurations)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("index_statistics", flattenIndexStatistics(resp.IndexStatistics)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("server_side_encryption_configuration", flattenServerSideEncryptionConfiguration(resp.ServerSideEncryptionConfiguration)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("user_group_resolution_configuration", flattenUserGroupResolutionConfiguration(resp.UserGroupResolutionConfiguration)); err != nil { + return diag.FromErr(err) + } + + if err := d.Set("user_token_configurations", flattenUserTokenConfigurations(resp.UserTokenConfigurations)); err != nil { + return diag.FromErr(err) + } + + tags, err := ListTags(ctx, conn, arn) + if err != nil { + return diag.Errorf("error listing tags for resource (%s): %s", arn, err) + } + tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + if err := d.Set("tags", tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return diag.Errorf("error setting tags: %s", err) + } + + d.SetId(id) + + return nil +} diff --git a/internal/service/kendra/index_data_source_test.go b/internal/service/kendra/index_data_source_test.go new file mode 100644 index 00000000000..cc473db8336 --- /dev/null +++ b/internal/service/kendra/index_data_source_test.go @@ -0,0 +1,103 @@ +package kendra_test + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/backup" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" +) + +func TestAccKendraIndexDataSource_basic(t *testing.T) { + datasourceName := "data.aws_kendra_index.test" + resourceName := "aws_kendra_index.test" + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, backup.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccIndexDataSourceConfig_nonExistent, + ExpectError: regexp.MustCompile(`error getting Kendra Index`), + }, + { + Config: testAccIndexDataSourceConfig_userTokenJSON(rName, rName2, rName3), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(datasourceName, "capacity_units.#", resourceName, "capacity_units.#"), + resource.TestCheckResourceAttrPair(datasourceName, "capacity_units.0.query_capacity_units", resourceName, "capacity_units.0.query_capacity_units"), + resource.TestCheckResourceAttrPair(datasourceName, "capacity_units.0.storage_capacity_units", resourceName, "capacity_units.0.storage_capacity_units"), + resource.TestCheckResourceAttrPair(datasourceName, "created_at", resourceName, "created_at"), + resource.TestCheckResourceAttrPair(datasourceName, "description", resourceName, "description"), + resource.TestCheckResourceAttrPair(datasourceName, "document_metadata_configuration_updates.#", resourceName, "document_metadata_configuration_updates.#"), + resource.TestCheckResourceAttrPair(datasourceName, "edition", resourceName, "edition"), + resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrPair(datasourceName, "index_statistics.#", resourceName, "index_statistics.#"), + resource.TestCheckResourceAttrPair(datasourceName, "index_statistics.0.faq_statistics.#", resourceName, "index_statistics.0.faq_statistics.#"), + resource.TestCheckResourceAttrPair(datasourceName, "index_statistics.0.faq_statistics.0.indexed_question_answers_count", resourceName, "index_statistics.0.faq_statistics.0.indexed_question_answers_count"), + resource.TestCheckResourceAttrPair(datasourceName, "index_statistics.0.text_document_statistics.#", resourceName, "index_statistics.0.text_document_statistics.#"), + resource.TestCheckResourceAttrPair(datasourceName, "index_statistics.0.text_document_statistics.0.indexed_text_bytes", resourceName, "index_statistics.0.text_document_statistics.0.indexed_text_bytes"), + resource.TestCheckResourceAttrPair(datasourceName, "index_statistics.0.text_document_statistics.0.indexed_text_documents_count", resourceName, "index_statistics.0.text_document_statistics.0.indexed_text_documents_count"), + resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(datasourceName, "role_arn", resourceName, "role_arn"), + resource.TestCheckResourceAttrPair(datasourceName, "server_side_encryption_configuration.#", resourceName, "server_side_encryption_configuration.#"), + resource.TestCheckResourceAttrPair(datasourceName, "server_side_encryption_configuration.0.kms_key_id", resourceName, "server_side_encryption_configuration.0.kms_key_id"), + resource.TestCheckResourceAttrPair(datasourceName, "status", resourceName, "status"), + resource.TestCheckResourceAttrPair(datasourceName, "updated_at", resourceName, "updated_at"), + resource.TestCheckResourceAttrPair(datasourceName, "user_context_policy", resourceName, "user_context_policy"), + resource.TestCheckResourceAttrPair(datasourceName, "user_group_resolution_configuration.#", resourceName, "user_group_resolution_configuration.#"), + resource.TestCheckResourceAttrPair(datasourceName, "user_token_configurations.#", resourceName, "user_token_configurations.#"), + resource.TestCheckResourceAttrPair(datasourceName, "user_token_configurations.0.json_token_type_configuration.#", resourceName, "user_token_configurations.0.json_token_type_configuration.#"), + resource.TestCheckResourceAttrPair(datasourceName, "user_token_configurations.0.json_token_type_configuration.0.group_attribute_field", resourceName, "user_token_configurations.0.json_token_type_configuration.0.group_attribute_field"), + resource.TestCheckResourceAttrPair(datasourceName, "user_token_configurations.0.json_token_type_configuration.0.user_name_attribute_field", resourceName, "user_token_configurations.0.json_token_type_configuration.0.user_name_attribute_field"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(datasourceName, "tags.Key1", resourceName, "tags.Key1"), + ), + }, + }, + }) +} + +const testAccIndexDataSourceConfig_nonExistent = ` +data "aws_kendra_index" "test" { + id = "tf-acc-test-does-not-exist-kendra-id" +} +` + +func testAccIndexDataSourceConfig_userTokenJSON(rName, rName2, rName3 string) string { + return acctest.ConfigCompose( + testAccIndexConfigBase(rName, rName2), + fmt.Sprintf(` +resource "aws_kendra_index" "test" { + name = %[1]q + description = "example" + role_arn = aws_iam_role.access_cw.arn + + server_side_encryption_configuration { + kms_key_id = data.aws_kms_key.this.arn + } + + user_token_configurations { + json_token_type_configuration { + group_attribute_field = "groups" + user_name_attribute_field = "username" + } + } + + tags = { + "Key1" = "Value1" + } +} + +data "aws_kendra_index" "test" { + id = aws_kendra_index.test.id +} +`, rName3)) +} diff --git a/internal/service/kendra/index_test.go b/internal/service/kendra/index_test.go new file mode 100644 index 00000000000..34be7c31a30 --- /dev/null +++ b/internal/service/kendra/index_test.go @@ -0,0 +1,708 @@ +package kendra_test + +import ( + "context" + "fmt" + "strconv" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kendra" + "github.com/aws/aws-sdk-go-v2/service/kendra/types" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfkendra "github.com/hashicorp/terraform-provider-aws/internal/service/kendra" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func testAccPreCheck(t *testing.T) { + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + input := &kendra.ListIndicesInput{} + + _, err := conn.ListIndices(context.TODO(), input) + + if acctest.PreCheckSkipError(err) { + t.Skipf("skipping acceptance testing: %s", err) + } + + if err != nil { + t.Fatalf("unexpected PreCheck error: %s", err) + } +} + +func testAccIndex_basic(t *testing.T) { + var index kendra.DescribeIndexOutput + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + description := "basic" + resourceName := "aws_kendra_index.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIndexConfig_basic(rName, rName2, rName3, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttrSet(resourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "capacity_units.#", "1"), + resource.TestCheckResourceAttr(resourceName, "capacity_units.0.query_capacity_units", "0"), + resource.TestCheckResourceAttr(resourceName, "capacity_units.0.storage_capacity_units", "0"), + resource.TestCheckResourceAttrSet(resourceName, "created_at"), + resource.TestCheckResourceAttr(resourceName, "description", description), + resource.TestCheckResourceAttr(resourceName, "document_metadata_configuration_updates.#", "13"), + resource.TestCheckResourceAttr(resourceName, "edition", string(types.IndexEditionEnterpriseEdition)), + resource.TestCheckResourceAttr(resourceName, "index_statistics.#", "1"), + resource.TestCheckResourceAttr(resourceName, "index_statistics.0.faq_statistics.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "index_statistics.0.faq_statistics.0.indexed_question_answers_count"), + resource.TestCheckResourceAttr(resourceName, "index_statistics.0.text_document_statistics.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "index_statistics.0.text_document_statistics.0.indexed_text_bytes"), + resource.TestCheckResourceAttrSet(resourceName, "index_statistics.0.text_document_statistics.0.indexed_text_documents_count"), + resource.TestCheckResourceAttr(resourceName, "name", rName3), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.access_cw", "arn"), + resource.TestCheckResourceAttr(resourceName, "status", string(types.IndexStatusActive)), + resource.TestCheckResourceAttrSet(resourceName, "updated_at"), + resource.TestCheckResourceAttr(resourceName, "user_context_policy", "ATTRIBUTE_FILTER"), + resource.TestCheckResourceAttr(resourceName, "user_group_resolution_configuration.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Key1", "Value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccIndex_serverSideEncryption(t *testing.T) { + var index kendra.DescribeIndexOutput + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + resourceName := "aws_kendra_index.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIndexConfig_serverSideEncryption(rName, rName2, rName3), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "server_side_encryption_configuration.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "server_side_encryption_configuration.0.kms_key_id", "data.aws_kms_key.this", "arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccIndex_updateCapacityUnits(t *testing.T) { + var index kendra.DescribeIndexOutput + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + originalQueryCapacityUnits := 2 + updatedQueryCapacityUnits := 3 + originalStorageCapacityUnits := 1 + updatedStorageCapacityUnits := 2 + resourceName := "aws_kendra_index.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIndexConfig_capacityUnits(rName, rName2, rName3, originalQueryCapacityUnits, originalStorageCapacityUnits), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "capacity_units.#", "1"), + resource.TestCheckResourceAttr(resourceName, "capacity_units.0.query_capacity_units", strconv.Itoa(originalQueryCapacityUnits)), + resource.TestCheckResourceAttr(resourceName, "capacity_units.0.storage_capacity_units", strconv.Itoa(originalStorageCapacityUnits)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccIndexConfig_capacityUnits(rName, rName2, rName3, updatedQueryCapacityUnits, updatedStorageCapacityUnits), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "capacity_units.#", "1"), + resource.TestCheckResourceAttr(resourceName, "capacity_units.0.query_capacity_units", strconv.Itoa(updatedQueryCapacityUnits)), + resource.TestCheckResourceAttr(resourceName, "capacity_units.0.storage_capacity_units", strconv.Itoa(updatedStorageCapacityUnits)), + ), + }, + }, + }) +} +func testAccIndex_updateDescription(t *testing.T) { + var index kendra.DescribeIndexOutput + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + originalDescription := "original description" + updatedDescription := "updated description" + resourceName := "aws_kendra_index.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIndexConfig_basic(rName, rName2, rName3, originalDescription), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "description", originalDescription), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccIndexConfig_basic(rName, rName2, rName3, updatedDescription), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "description", updatedDescription), + ), + }, + }, + }) +} + +func testAccIndex_updateName(t *testing.T) { + var index kendra.DescribeIndexOutput + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName4 := sdkacctest.RandomWithPrefix("resource-test-terraform") + description := "description" + resourceName := "aws_kendra_index.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIndexConfig_basic(rName, rName2, rName3, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "name", rName3), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccIndexConfig_basic(rName, rName2, rName4, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "name", rName4), + ), + }, + }, + }) +} + +func testAccIndex_updateUserTokenJSON(t *testing.T) { + var index kendra.DescribeIndexOutput + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + originalGroupAttributeField := "groups" + originalUserNameAttributeField := "username" + updatedGroupAttributeField := "groupings" + updatedUserNameAttributeField := "usernames" + resourceName := "aws_kendra_index.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIndexConfig_userTokenJSON(rName, rName2, rName3, originalGroupAttributeField, originalUserNameAttributeField), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.#", "1"), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.0.json_token_type_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.0.json_token_type_configuration.0.group_attribute_field", originalGroupAttributeField), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.0.json_token_type_configuration.0.user_name_attribute_field", originalUserNameAttributeField), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccIndexConfig_userTokenJSON(rName, rName2, rName3, updatedGroupAttributeField, originalUserNameAttributeField), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.#", "1"), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.0.json_token_type_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.0.json_token_type_configuration.0.group_attribute_field", updatedGroupAttributeField), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.0.json_token_type_configuration.0.user_name_attribute_field", originalUserNameAttributeField), + ), + }, + { + Config: testAccIndexConfig_userTokenJSON(rName, rName2, rName3, updatedGroupAttributeField, updatedUserNameAttributeField), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.#", "1"), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.0.json_token_type_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.0.json_token_type_configuration.0.group_attribute_field", updatedGroupAttributeField), + resource.TestCheckResourceAttr(resourceName, "user_token_configurations.0.json_token_type_configuration.0.user_name_attribute_field", updatedUserNameAttributeField), + ), + }, + }, + }) +} + +func testAccIndex_updateTags(t *testing.T) { + var index kendra.DescribeIndexOutput + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + description := "description" + resourceName := "aws_kendra_index.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIndexConfig_basic(rName, rName2, rName3, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Key1", "Value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccIndexConfig_tags(rName, rName2, rName3, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.Key1", "Value1"), + resource.TestCheckResourceAttr(resourceName, "tags.Key2", "Value2a"), + ), + }, + { + Config: testAccIndexConfig_tagsUpdated(rName, rName2, rName3, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), + resource.TestCheckResourceAttr(resourceName, "tags.Key1", "Value1"), + resource.TestCheckResourceAttr(resourceName, "tags.Key2", "Value2b"), + resource.TestCheckResourceAttr(resourceName, "tags.Key3", "Value3"), + ), + }, + }, + }) +} + +func testAccIndex_updateRoleARN(t *testing.T) { + var index kendra.DescribeIndexOutput + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + description := "description" + resourceName := "aws_kendra_index.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIndexConfig_basic(rName, rName2, rName3, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.access_cw", "arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccIndexConfig_secretsManagerRole(rName, rName2, rName3, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.access_sm", "arn"), + ), + }, + }, + }) +} + +func testAccIndex_disappears(t *testing.T) { + var index kendra.DescribeIndexOutput + + rName := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName2 := sdkacctest.RandomWithPrefix("resource-test-terraform") + rName3 := sdkacctest.RandomWithPrefix("resource-test-terraform") + description := "disappears" + resourceName := "aws_kendra_index.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIndexConfig_basic(rName, rName2, rName3, description), + Check: resource.ComposeTestCheckFunc( + testAccCheckIndexExists(resourceName, &index), + acctest.CheckResourceDisappears(acctest.Provider, tfkendra.ResourceIndex(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckIndexDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_kendra_index" { + continue + } + + input := &kendra.DescribeIndexInput{ + Id: aws.String(rs.Primary.ID), + } + + resp, err := conn.DescribeIndex(context.TODO(), input) + + if err == nil { + if aws.ToString(resp.Id) == rs.Primary.ID { + return fmt.Errorf("Index '%s' was not deleted properly", rs.Primary.ID) + } + } + } + + return nil +} + +func testAccCheckIndexExists(name string, index *kendra.DescribeIndexOutput) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + input := &kendra.DescribeIndexInput{ + Id: aws.String(rs.Primary.ID), + } + resp, err := conn.DescribeIndex(context.TODO(), input) + + if err != nil { + return err + } + + *index = *resp + + return nil + } +} + +func testAccIndexConfigBase(rName, rName2 string) string { + // Kendra IAM policies: https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html + return fmt.Sprintf(` +data "aws_region" "current" {} +data "aws_caller_identity" "current" {} +data "aws_partition" "current" {} +data "aws_kms_key" "this" { + key_id = "alias/aws/kendra" +} +data "aws_iam_policy_document" "test" { + statement { + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["kendra.amazonaws.com"] + } + } +} + +resource "aws_iam_role" "access_cw" { + name = %[1]q + assume_role_policy = data.aws_iam_policy_document.test.json + + inline_policy { + name = "access_cw" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Action = ["cloudwatch:PutMetricData"] + Effect = "Allow" + Resource = "*" + Condition = { + StringEquals = { + "cloudwatch:namespace" = "Kendra" + } + } + }, + { + Action = ["logs:DescribeLogGroups"] + Effect = "Allow" + Resource = "*" + }, + { + Action = ["logs:CreateLogGroup"] + Effect = "Allow" + Resource = "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*" + }, + { + Action = [ + "logs:DescribeLogStreams", + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + Effect = "Allow" + Resource = "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*:log-stream:*" + }, + ] + }) + } +} + +resource "aws_iam_role" "access_sm" { + name = %[2]q + assume_role_policy = data.aws_iam_policy_document.test.json + + inline_policy { + name = "access_sm" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Action = ["cloudwatch:PutMetricData"] + Effect = "Allow" + Resource = "*" + Condition = { + StringEquals = { + "cloudwatch:namespace" = "Kendra" + } + } + }, + { + Action = ["logs:DescribeLogGroups"] + Effect = "Allow" + Resource = "*" + }, + { + Action = ["logs:CreateLogGroup"] + Effect = "Allow" + Resource = "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*" + }, + { + Action = [ + "logs:DescribeLogStreams", + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + Effect = "Allow" + Resource = "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*:log-stream:*" + }, + { + Action = ["secretsmanager:GetSecretValue"] + Effect = "Allow" + Resource = "arn:${data.aws_partition.current.partition}:secretsmanager:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:secret:example" + }, + { + Action = ["kms:Decrypt"] + Effect = "Allow" + Resource = "arn:${data.aws_partition.current.partition}:kms:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:key/example" + Condition = { + StringLike = { + "kms:ViaService" = ["secretsmanager.*.amazonaws.com"] + } + } + } + ] + }) + } +} +`, rName, rName2) +} + +func testAccIndexConfig_basic(rName, rName2, rName3, description string) string { + return acctest.ConfigCompose( + testAccIndexConfigBase(rName, rName2), + fmt.Sprintf(` +resource "aws_kendra_index" "test" { + name = %[1]q + description = %[2]q + role_arn = aws_iam_role.access_cw.arn + + tags = { + "Key1" = "Value1" + } +} +`, rName3, description)) +} + +func testAccIndexConfig_capacityUnits(rName, rName2, rName3 string, queryCapacityUnits, storageCapacityUnits int) string { + return acctest.ConfigCompose( + testAccIndexConfigBase(rName, rName2), + fmt.Sprintf(` +resource "aws_kendra_index" "test" { + name = %[1]q + role_arn = aws_iam_role.access_cw.arn + + capacity_units { + query_capacity_units = %[2]d + storage_capacity_units = %[3]d + } + + tags = { + "Key1" = "Value1" + } +} +`, rName3, queryCapacityUnits, storageCapacityUnits)) +} + +func testAccIndexConfig_secretsManagerRole(rName, rName2, rName3, description string) string { + return acctest.ConfigCompose( + testAccIndexConfigBase(rName, rName2), + fmt.Sprintf(` +resource "aws_kendra_index" "test" { + name = %[1]q + description = %[2]q + role_arn = aws_iam_role.access_sm.arn + + tags = { + "Key1" = "Value1" + } +} +`, rName3, description)) +} + +func testAccIndexConfig_serverSideEncryption(rName, rName2, rName3 string) string { + return acctest.ConfigCompose( + testAccIndexConfigBase(rName, rName2), + fmt.Sprintf(` +resource "aws_kendra_index" "test" { + name = %[1]q + role_arn = aws_iam_role.access_cw.arn + + server_side_encryption_configuration { + kms_key_id = data.aws_kms_key.this.arn + } +} +`, rName3)) +} + +func testAccIndexConfig_userTokenJSON(rName, rName2, rName3, groupAttributeField, userNameAttributeField string) string { + return acctest.ConfigCompose( + testAccIndexConfigBase(rName, rName2), + fmt.Sprintf(` +resource "aws_kendra_index" "test" { + name = %[1]q + role_arn = aws_iam_role.access_cw.arn + + user_token_configurations { + json_token_type_configuration { + group_attribute_field = %[2]q + user_name_attribute_field = %[3]q + } + } +} +`, rName3, groupAttributeField, userNameAttributeField)) +} + +func testAccIndexConfig_tags(rName, rName2, rName3, description string) string { + return acctest.ConfigCompose( + testAccIndexConfigBase(rName, rName2), + fmt.Sprintf(` +resource "aws_kendra_index" "test" { + name = %[1]q + description = %[2]q + role_arn = aws_iam_role.access_cw.arn + + tags = { + "Key1" = "Value1" + "Key2" = "Value2a", + } +} +`, rName3, description)) +} + +func testAccIndexConfig_tagsUpdated(rName, rName2, rName3, description string) string { + return acctest.ConfigCompose( + testAccIndexConfigBase(rName, rName2), + fmt.Sprintf(` +resource "aws_kendra_index" "test" { + name = %[1]q + description = %[2]q + role_arn = aws_iam_role.access_cw.arn + + tags = { + "Key1" = "Value1", + "Key2" = "Value2b" + "Key3" = "Value3" + } +} +`, rName3, description)) +} diff --git a/internal/service/kendra/kendra_test.go b/internal/service/kendra/kendra_test.go new file mode 100644 index 00000000000..04d8988f670 --- /dev/null +++ b/internal/service/kendra/kendra_test.go @@ -0,0 +1,72 @@ +package kendra_test + +import "testing" + +// Serialize to limit service quota exceeded errors. +func TestAccKendra_serial(t *testing.T) { + testCases := map[string]map[string]func(t *testing.T){ + "Experience": { + "basic": testAccExperience_basic, + "disappears": testAccExperience_disappears, + "Description": testAccExperience_Description, + "Name": testAccExperience_Name, + "RoleARN": testAccExperience_roleARN, + "Configuration_ContentSourceConfiguration_DirectPutContent": testAccExperience_Configuration_ContentSourceConfiguration_DirectPutContent, + "Configuration_ContentSourceConfiguration_FaqIDs": testAccExperience_Configuration_ContentSourceConfiguration_FaqIDs, + "Configuration_ContentSourceConfiguration_updateFaqIDs": testAccExperience_Configuration_ContentSourceConfiguration_updateFaqIDs, + "Configuration_UserIdentityConfiguration": testAccExperience_Configuration_UserIdentityConfiguration, + "Configuration_ContentSourceConfigurationAndUserIdentityConfiguration": testAccExperience_Configuration_ContentSourceConfigurationAndUserIdentityConfiguration, + "Configuration_ContentSourceConfigurationWithUserIdentityConfigurationRemoved": testAccExperience_Configuration_ContentSourceConfigurationWithUserIdentityConfigurationRemoved, + "Configuration_UserIdentityConfigurationWithContentSourceConfigurationRemoved": testAccExperience_Configuration_UserIdentityConfigurationWithContentSourceConfigurationRemoved, + }, + "Faq": { + "basic": testAccFaq_basic, + "disappears": testAccFaq_disappears, + "tags": testAccFaq_tags, + "Description": testAccFaq_description, + "FileFormat": testAccFaq_fileFormat, + "LanguageCode": testAccFaq_languageCode, + }, + "Index": { + "basic": testAccIndex_basic, + "disappears": testAccIndex_disappears, + "tags": testAccIndex_updateTags, + "CapacityUnits": testAccIndex_updateCapacityUnits, + "Description": testAccIndex_updateDescription, + "Name": testAccIndex_updateName, + "RoleARN": testAccIndex_updateRoleARN, + "ServerSideEncryption": testAccIndex_serverSideEncryption, + "UserTokenJSON": testAccIndex_updateUserTokenJSON, + }, + "QuerySuggestionsBlockList": { + "basic": testAccQuerySuggestionsBlockList_basic, + "disappears": testAccQuerySuggestionsBlockList_disappears, + "tags": testAccQuerySuggestionsBlockList_tags, + "Description": testAccQuerySuggestionsBlockList_Description, + "Name": testAccQuerySuggestionsBlockList_Name, + "RoleARN": testAccQuerySuggestionsBlockList_RoleARN, + "SourceS3Path": testAccQuerySuggestionsBlockList_SourceS3Path, + }, + "Thesaurus": { + "basic": testAccThesaurus_basic, + "disappears": testAccThesaurus_disappears, + "tags": testAccThesaurus_tags, + "Description": testAccThesaurus_description, + "Name": testAccThesaurus_name, + "RoleARN": testAccThesaurus_roleARN, + "SourceS3Path": testAccThesaurus_sourceS3Path, + }, + } + + for group, m := range testCases { + m := m + t.Run(group, func(t *testing.T) { + for name, tc := range m { + tc := tc + t.Run(name, func(t *testing.T) { + tc(t) + }) + } + }) + } +} diff --git a/internal/service/kendra/query_suggestions_block_list.go b/internal/service/kendra/query_suggestions_block_list.go new file mode 100644 index 00000000000..a48285ab67e --- /dev/null +++ b/internal/service/kendra/query_suggestions_block_list.go @@ -0,0 +1,392 @@ +package kendra + +import ( + "context" + "errors" + "fmt" + "log" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/kendra" + "github.com/aws/aws-sdk-go-v2/service/kendra/types" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceQuerySuggestionsBlockList() *schema.Resource { + return &schema.Resource{ + CreateWithoutTimeout: resourceQuerySuggestionsBlockListCreate, + ReadWithoutTimeout: resourceQuerySuggestionsBlockListRead, + UpdateWithoutTimeout: resourceQuerySuggestionsBlockListUpdate, + DeleteWithoutTimeout: resourceQuerySuggestionsBlockListDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Update: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "index_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + }, + "query_suggestions_block_list_id": { + Type: schema.TypeString, + Computed: true, + }, + "role_arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidARN, + }, + "source_s3_path": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "bucket": { + Type: schema.TypeString, + Required: true, + }, + "key": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourceQuerySuggestionsBlockListCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + in := &kendra.CreateQuerySuggestionsBlockListInput{ + ClientToken: aws.String(resource.UniqueId()), + IndexId: aws.String(d.Get("index_id").(string)), + Name: aws.String(d.Get("name").(string)), + RoleArn: aws.String(d.Get("role_arn").(string)), + SourceS3Path: expandSourceS3Path(d.Get("source_s3_path").([]interface{})), + } + + if v, ok := d.GetOk("description"); ok { + in.Description = aws.String(v.(string)) + } + + if len(tags) > 0 { + in.Tags = Tags(tags.IgnoreAWS()) + } + + outputRaw, err := tfresource.RetryWhen( + propagationTimeout, + func() (interface{}, error) { + return conn.CreateQuerySuggestionsBlockList(ctx, in) + + }, + func(err error) (bool, error) { + var validationException *types.ValidationException + + if errors.As(err, &validationException) && strings.Contains(validationException.ErrorMessage(), validationExceptionMessage) { + return true, err + } + + return false, err + }, + ) + + if err != nil { + return diag.Errorf("creating Amazon Kendra QuerySuggestionsBlockList (%s): %s", d.Get("name").(string), err) + } + + out, ok := outputRaw.(*kendra.CreateQuerySuggestionsBlockListOutput) + if !ok || out == nil { + return diag.Errorf("creating Amazon Kendra QuerySuggestionsBlockList (%s): empty output", d.Get("name").(string)) + } + + id := aws.ToString(out.Id) + indexId := d.Get("index_id").(string) + + d.SetId(fmt.Sprintf("%s/%s", id, indexId)) + + if _, err := waitQuerySuggestionsBlockListCreated(ctx, conn, id, indexId, d.Timeout(schema.TimeoutCreate)); err != nil { + return diag.Errorf("waiting for Amazon Kendra QuerySuggestionsBlockList (%s) create: %s", d.Id(), err) + } + + return resourceQuerySuggestionsBlockListRead(ctx, d, meta) +} + +func resourceQuerySuggestionsBlockListRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + id, indexId, err := QuerySuggestionsBlockListParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + out, err := FindQuerySuggestionsBlockListByID(ctx, conn, id, indexId) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Kendra QuerySuggestionsBlockList (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return diag.Errorf("reading Kendra QuerySuggestionsBlockList (%s): %s", d.Id(), err) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Region: meta.(*conns.AWSClient).Region, + Service: "kendra", + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("index/%s/query-suggestions-block-list/%s", indexId, id), + }.String() + + d.Set("arn", arn) + d.Set("description", out.Description) + d.Set("index_id", out.IndexId) + d.Set("name", out.Name) + d.Set("query_suggestions_block_list_id", id) + d.Set("role_arn", out.RoleArn) + d.Set("status", out.Status) + + if err := d.Set("source_s3_path", flattenSourceS3Path(out.SourceS3Path)); err != nil { + return diag.Errorf("setting complex argument: %s", err) + } + + tags, err := ListTags(ctx, conn, arn) + if err != nil { + return diag.Errorf("listing tags for Kendra QuerySuggestionsBlockList (%s): %s", d.Id(), err) + } + + tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return diag.Errorf("setting tags: %s", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return diag.Errorf("setting tags_all: %s", err) + } + + return nil +} + +func resourceQuerySuggestionsBlockListUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + if d.HasChangesExcept("tags", "tags_all") { + id, indexId, err := QuerySuggestionsBlockListParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + input := &kendra.UpdateQuerySuggestionsBlockListInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + } + + if d.HasChange("description") { + input.Description = aws.String(d.Get("description").(string)) + } + + if d.HasChange("name") { + input.Name = aws.String(d.Get("name").(string)) + } + + if d.HasChange("role_arn") { + input.RoleArn = aws.String(d.Get("role_arn").(string)) + } + + if d.HasChange("source_s3_path") { + input.SourceS3Path = expandSourceS3Path(d.Get("source_s3_path").([]interface{})) + } + + log.Printf("[DEBUG] Updating Kendra QuerySuggestionsBlockList (%s): %#v", d.Id(), input) + + _, err = tfresource.RetryWhen( + propagationTimeout, + func() (interface{}, error) { + return conn.UpdateQuerySuggestionsBlockList(ctx, input) + + }, + func(err error) (bool, error) { + var validationException *types.ValidationException + + if errors.As(err, &validationException) && strings.Contains(validationException.ErrorMessage(), validationExceptionMessage) { + return true, err + } + + return false, err + }, + ) + + if err != nil { + return diag.Errorf("updating Kendra QuerySuggestionsBlockList (%s): %s", d.Id(), err) + } + + if _, err := waitQuerySuggestionsBlockListUpdated(ctx, conn, id, indexId, d.Timeout(schema.TimeoutUpdate)); err != nil { + return diag.Errorf("waiting for Kendra QuerySuggestionsBlockList (%s) update: %s", d.Id(), err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(ctx, conn, d.Get("arn").(string), o, n); err != nil { + return diag.FromErr(fmt.Errorf("error updating Kendra QuerySuggestionsBlockList (%s) tags: %s", d.Id(), err)) + } + } + + return resourceQuerySuggestionsBlockListRead(ctx, d, meta) +} + +func resourceQuerySuggestionsBlockListDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + log.Printf("[INFO] Deleting Kendra QuerySuggestionsBlockList %s", d.Id()) + + id, indexId, err := QuerySuggestionsBlockListParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + _, err = conn.DeleteQuerySuggestionsBlockList(ctx, &kendra.DeleteQuerySuggestionsBlockListInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + }) + + var notFound *types.ResourceNotFoundException + + if errors.As(err, ¬Found) { + return nil + } + + if err != nil { + return diag.Errorf("deleting Kendra QuerySuggestionsBlockList (%s): %s", d.Id(), err) + } + + if _, err := waitQuerySuggestionsBlockListDeleted(ctx, conn, id, indexId, d.Timeout(schema.TimeoutDelete)); err != nil { + return diag.Errorf("waiting for Kendra QuerySuggestionsBlockList (%s) to be deleted: %s", d.Id(), err) + } + + return nil +} + +func statusQuerySuggestionsBlockList(ctx context.Context, conn *kendra.Client, id, indexId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + out, err := FindQuerySuggestionsBlockListByID(ctx, conn, id, indexId) + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return out, string(out.Status), nil + } +} + +func waitQuerySuggestionsBlockListCreated(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) (*kendra.DescribeQuerySuggestionsBlockListOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{string(types.QuerySuggestionsBlockListStatusCreating)}, + Target: []string{string(types.QuerySuggestionsBlockListStatusActive)}, + Refresh: statusQuerySuggestionsBlockList(ctx, conn, id, indexId), + Timeout: timeout, + NotFoundChecks: 20, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + if out, ok := outputRaw.(*kendra.DescribeQuerySuggestionsBlockListOutput); ok { + if out.Status == types.QuerySuggestionsBlockListStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(out.ErrorMessage))) + } + return out, err + } + + return nil, err +} + +func waitQuerySuggestionsBlockListUpdated(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) (*kendra.DescribeQuerySuggestionsBlockListOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{string(types.QuerySuggestionsBlockListStatusUpdating)}, + Target: []string{string(types.QuerySuggestionsBlockListStatusActive)}, + Refresh: statusQuerySuggestionsBlockList(ctx, conn, id, indexId), + Timeout: timeout, + NotFoundChecks: 20, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + if out, ok := outputRaw.(*kendra.DescribeQuerySuggestionsBlockListOutput); ok { + if out.Status == types.QuerySuggestionsBlockListStatusActiveButUpdateFailed || out.Status == types.QuerySuggestionsBlockListStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(out.ErrorMessage))) + } + return out, err + } + + return nil, err +} + +func waitQuerySuggestionsBlockListDeleted(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) (*kendra.DescribeQuerySuggestionsBlockListOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{string(types.QuerySuggestionsBlockListStatusDeleting)}, + Target: []string{}, + Refresh: statusQuerySuggestionsBlockList(ctx, conn, id, indexId), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + if out, ok := outputRaw.(*kendra.DescribeQuerySuggestionsBlockListOutput); ok { + if out.Status == types.QuerySuggestionsBlockListStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(out.ErrorMessage))) + } + return out, err + } + + return nil, err +} diff --git a/internal/service/kendra/query_suggestions_block_list_test.go b/internal/service/kendra/query_suggestions_block_list_test.go new file mode 100644 index 00000000000..f9917cc0c4f --- /dev/null +++ b/internal/service/kendra/query_suggestions_block_list_test.go @@ -0,0 +1,591 @@ +package kendra_test + +import ( + "context" + "fmt" + "regexp" + "testing" + + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfkendra "github.com/hashicorp/terraform-provider-aws/internal/service/kendra" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func testAccQuerySuggestionsBlockList_basic(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_query_suggestions_block_list.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckQuerySuggestionsBlockListDestroy, + Steps: []resource.TestStep{ + { + Config: testAccQuerySuggestionsBlockListConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "index_id", "aws_kendra_index.test", "id"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test", "arn"), + resource.TestCheckResourceAttr(resourceName, "source_s3_path.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.bucket", "aws_s3_bucket.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.key", "aws_s3_object.test", "key"), + resource.TestCheckResourceAttrSet(resourceName, "status"), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kendra", regexp.MustCompile(`index/.+/query-suggestions-block-list/.+$`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccQuerySuggestionsBlockList_Description(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_query_suggestions_block_list.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckQuerySuggestionsBlockListDestroy, + Steps: []resource.TestStep{ + { + Config: testAccQuerySuggestionsBlockListConfig_description(rName, "description1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description1"), + ), + }, + { + Config: testAccQuerySuggestionsBlockListConfig_description(rName, "description2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccQuerySuggestionsBlockListConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", ""), + ), + }, + }, + }) +} + +func testAccQuerySuggestionsBlockList_Name(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_query_suggestions_block_list.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckQuerySuggestionsBlockListDestroy, + Steps: []resource.TestStep{ + { + Config: testAccQuerySuggestionsBlockListConfig_basic(rName1), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", rName1), + ), + }, + { + Config: testAccQuerySuggestionsBlockListConfig_name(rName1, rName2), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", rName2), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccQuerySuggestionsBlockList_RoleARN(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_query_suggestions_block_list.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckQuerySuggestionsBlockListDestroy, + Steps: []resource.TestStep{ + { + Config: testAccQuerySuggestionsBlockListConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test", "arn"), + ), + }, + { + Config: testAccQuerySuggestionsBlockListConfig_roleARN(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test2", "arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccQuerySuggestionsBlockList_SourceS3Path(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_query_suggestions_block_list.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckQuerySuggestionsBlockListDestroy, + Steps: []resource.TestStep{ + { + Config: testAccQuerySuggestionsBlockListConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "source_s3_path.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.bucket", "aws_s3_bucket.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.key", "aws_s3_object.test", "key")), + }, + { + Config: testAccQuerySuggestionsBlockListConfig_sourceS3Path(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "source_s3_path.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.bucket", "aws_s3_bucket.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.key", "aws_s3_object.test2", "key")), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccQuerySuggestionsBlockList_disappears(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_query_suggestions_block_list.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckQuerySuggestionsBlockListDestroy, + Steps: []resource.TestStep{ + { + Config: testAccQuerySuggestionsBlockListConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfkendra.ResourceQuerySuggestionsBlockList(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccQuerySuggestionsBlockList_tags(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_query_suggestions_block_list.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckQuerySuggestionsBlockListDestroy, + Steps: []resource.TestStep{ + { + Config: testAccQuerySuggestionsBlockListConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccQuerySuggestionsBlockListConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccQuerySuggestionsBlockListConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckQuerySuggestionsBlockListExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func testAccCheckQuerySuggestionsBlockListDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_kendra_query_suggestions_block_list" { + continue + } + + id, indexId, err := tfkendra.QuerySuggestionsBlockListParseResourceID(rs.Primary.ID) + if err != nil { + return err + } + + _, err = tfkendra.FindQuerySuggestionsBlockListByID(context.TODO(), conn, id, indexId) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("Expected Kendra QuerySuggestionsBlockList to be destroyed, %s found", rs.Primary.ID) + } + + return nil +} + +func testAccCheckQuerySuggestionsBlockListExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Kendra QuerySuggestionsBlockList is set") + } + + id, indexId, err := tfkendra.QuerySuggestionsBlockListParseResourceID(rs.Primary.ID) + if err != nil { + return err + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + _, err = tfkendra.FindQuerySuggestionsBlockListByID(context.TODO(), conn, id, indexId) + + if err != nil { + return fmt.Errorf("Error describing Kendra QuerySuggestionsBlockList: %s", err.Error()) + } + + return nil + } +} + +func testAccQuerySuggestionsBlockListBaseConfig(rName string) string { + return fmt.Sprintf(` +data "aws_partition" "current" {} + +resource "aws_s3_bucket" "test" { + bucket = %[1]q + force_destroy = true +} + +resource "aws_s3_object" "test" { + bucket = aws_s3_bucket.test.bucket + content = "test" + key = "test/suggestions.txt" +} + +data "aws_iam_policy_document" "assume_role" { + statement { + actions = ["sts:AssumeRole"] + effect = "Allow" + principals { + type = "Service" + identifiers = ["kendra.${data.aws_partition.current.dns_suffix}"] + } + } +} + +resource "aws_iam_role" "test" { + name = %[1]q + path = "/" + assume_role_policy = data.aws_iam_policy_document.assume_role.json +} + +data "aws_iam_policy_document" "test" { + statement { + effect = "Allow" + actions = [ + "kendra:*", + "s3:GetBucketLocation", + "s3:GetObject", + "s3:ListBucket" + ] + resources = [ + aws_s3_bucket.test.arn, + "${aws_s3_bucket.test.arn}/*" + ] + } +} + +resource "aws_iam_policy" "test" { + name = %[1]q + description = "Allow Kendra to access S3" + policy = data.aws_iam_policy_document.test.json +} + +resource "aws_iam_role_policy_attachment" "test" { + role = aws_iam_role.test.name + policy_arn = aws_iam_policy.test.arn +} + +resource "aws_kendra_index" "test" { + depends_on = [aws_iam_role_policy_attachment.test] + + name = %[1]q + role_arn = aws_iam_role.test.arn +} +`, rName) +} + +func testAccQuerySuggestionsBlockListConfig_basic(rName string) string { + return acctest.ConfigCompose( + testAccQuerySuggestionsBlockListBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_query_suggestions_block_list" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, rName)) +} + +func testAccQuerySuggestionsBlockListConfig_description(rName, description string) string { + return acctest.ConfigCompose( + testAccQuerySuggestionsBlockListBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_query_suggestions_block_list" "test" { + description = %[1]q + index_id = aws_kendra_index.test.id + name = %[2]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, description, rName)) +} + +func testAccQuerySuggestionsBlockListConfig_name(rName, name string) string { + return acctest.ConfigCompose( + testAccQuerySuggestionsBlockListBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_query_suggestions_block_list" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, name)) +} + +func testAccQuerySuggestionsBlockListConfig_roleARN(rName string) string { + return acctest.ConfigCompose( + testAccQuerySuggestionsBlockListBaseConfig(rName), + fmt.Sprintf(` +resource "aws_iam_role" "test2" { + name = "%[1]s-2" + path = "/" + assume_role_policy = data.aws_iam_policy_document.assume_role.json +} + +resource "aws_iam_policy" "test2" { + name = "%[1]s-2" + description = "Allow Kendra to access S3" + policy = data.aws_iam_policy_document.test.json +} + +resource "aws_iam_role_policy_attachment" "test2" { + role = aws_iam_role.test2.name + policy_arn = aws_iam_policy.test2.arn +} + +resource "aws_kendra_query_suggestions_block_list" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test2.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, rName)) +} + +func testAccQuerySuggestionsBlockListConfig_sourceS3Path(rName string) string { + return acctest.ConfigCompose( + testAccQuerySuggestionsBlockListBaseConfig(rName), + fmt.Sprintf(` +resource "aws_s3_object" "test2" { + bucket = aws_s3_bucket.test.bucket + content = "test2" + key = "test/new_suggestions.txt" +} + +resource "aws_kendra_query_suggestions_block_list" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test2.key + } +} +`, rName)) +} + +func testAccQuerySuggestionsBlockListConfig_tags1(rName, tag, value string) string { + return acctest.ConfigCompose( + testAccQuerySuggestionsBlockListBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_query_suggestions_block_list" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } + + tags = { + %[2]q = %[3]q + } +} +`, rName, tag, value)) +} + +func testAccQuerySuggestionsBlockListConfig_tags2(rName, tag1, value1, tag2, value2 string) string { + return acctest.ConfigCompose( + testAccQuerySuggestionsBlockListBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_query_suggestions_block_list" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tag1, value1, tag2, value2)) +} diff --git a/internal/service/kendra/tags.go b/internal/service/kendra/tags.go new file mode 100644 index 00000000000..a091dd1fcd1 --- /dev/null +++ b/internal/service/kendra/tags.go @@ -0,0 +1,96 @@ +// Custom Kendra tag service update functions using the same format as generated code. +// Modified to support AWS Go SDK v2. + +package kendra + +import ( + "context" + "fmt" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kendra" + "github.com/aws/aws-sdk-go-v2/service/kendra/types" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" +) + +// ListTags lists kendra service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func ListTags(ctx context.Context, conn *kendra.Client, identifier string) (tftags.KeyValueTags, error) { + input := &kendra.ListTagsForResourceInput{ + ResourceARN: aws.String(identifier), + } + + output, err := conn.ListTagsForResource(ctx, input) + + if err != nil { + return tftags.New(nil), err + } + + return KeyValueTags(output.Tags), nil +} + +// []*SERVICE.Tag handling + +// Tags returns kendra service tags. +func Tags(tags tftags.KeyValueTags) []types.Tag { + result := make([]types.Tag, 0, len(tags)) + + for k, v := range tags.Map() { + tag := types.Tag{ + Key: aws.String(k), + Value: aws.String(v), + } + + result = append(result, tag) + } + + return result +} + +// KeyValueTags creates tftags.KeyValueTags from kendra service tags. +func KeyValueTags(tags []types.Tag) tftags.KeyValueTags { + m := make(map[string]*string, len(tags)) + + for _, tag := range tags { + m[aws.ToString(tag.Key)] = tag.Value + } + + return tftags.New(m) +} + +// UpdateTags updates kendra service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func UpdateTags(ctx context.Context, conn *kendra.Client, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error { + oldTags := tftags.New(oldTagsMap) + newTags := tftags.New(newTagsMap) + + if removedTags := oldTags.Removed(newTags); len(removedTags) > 0 { + input := &kendra.UntagResourceInput{ + ResourceARN: aws.String(identifier), + TagKeys: removedTags.IgnoreAWS().Keys(), + } + + _, err := conn.UntagResource(ctx, input) + + if err != nil { + return fmt.Errorf("error untagging resource (%s): %w", identifier, err) + } + } + + if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 { + input := &kendra.TagResourceInput{ + ResourceARN: aws.String(identifier), + Tags: Tags(updatedTags.IgnoreAWS()), + } + + _, err := conn.TagResource(ctx, input) + + if err != nil { + return fmt.Errorf("error tagging resource (%s): %w", identifier, err) + } + } + + return nil +} diff --git a/internal/service/kendra/test-fixtures/basic.csv b/internal/service/kendra/test-fixtures/basic.csv new file mode 100644 index 00000000000..6a5807c5c0b --- /dev/null +++ b/internal/service/kendra/test-fixtures/basic.csv @@ -0,0 +1,2 @@ +How many free clinics are in Spokane WA?, 13, https://www.freeclinics.com/ +How many free clinics are there in Mountain View Missouri?, 7, https://www.freeclinics.com/ \ No newline at end of file diff --git a/internal/service/kendra/thesaurus.go b/internal/service/kendra/thesaurus.go new file mode 100644 index 00000000000..4cbb9cb6bd8 --- /dev/null +++ b/internal/service/kendra/thesaurus.go @@ -0,0 +1,390 @@ +package kendra + +import ( + "context" + "errors" + "fmt" + "log" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/kendra" + "github.com/aws/aws-sdk-go-v2/service/kendra/types" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceThesaurus() *schema.Resource { + return &schema.Resource{ + CreateWithoutTimeout: resourceThesaurusCreate, + ReadWithoutTimeout: resourceThesaurusRead, + UpdateWithoutTimeout: resourceThesaurusUpdate, + DeleteWithoutTimeout: resourceThesaurusDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Update: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "index_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + }, + "role_arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidARN, + }, + "source_s3_path": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "bucket": { + Type: schema.TypeString, + Required: true, + }, + "key": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "thesaurus_id": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourceThesaurusCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + input := &kendra.CreateThesaurusInput{ + ClientToken: aws.String(resource.UniqueId()), + IndexId: aws.String(d.Get("index_id").(string)), + Name: aws.String(d.Get("name").(string)), + RoleArn: aws.String(d.Get("role_arn").(string)), + SourceS3Path: expandSourceS3Path(d.Get("source_s3_path").([]interface{})), + } + + if v, ok := d.GetOk("description"); ok { + input.Description = aws.String(v.(string)) + } + + if len(tags) > 0 { + input.Tags = Tags(tags.IgnoreAWS()) + } + + outputRaw, err := tfresource.RetryWhen( + propagationTimeout, + func() (interface{}, error) { + return conn.CreateThesaurus(ctx, input) + }, + func(err error) (bool, error) { + var validationException *types.ValidationException + + if errors.As(err, &validationException) && strings.Contains(validationException.ErrorMessage(), validationExceptionMessage) { + return true, err + } + + return false, err + }, + ) + + if err != nil { + return diag.Errorf("creating Amazon Kendra Thesaurus (%s): %s", d.Get("name").(string), err) + } + + if outputRaw == nil { + return diag.Errorf("creating Amazon Kendra Thesaurus (%s): empty output", d.Get("name").(string)) + } + + output := outputRaw.(*kendra.CreateThesaurusOutput) + + id := aws.ToString(output.Id) + indexId := d.Get("index_id").(string) + + d.SetId(fmt.Sprintf("%s/%s", id, indexId)) + + if _, err := waitThesaurusCreated(ctx, conn, id, indexId, d.Timeout(schema.TimeoutCreate)); err != nil { + return diag.Errorf("waiting for Amazon Kendra Thesaurus (%s) create: %s", d.Id(), err) + } + + return resourceThesaurusRead(ctx, d, meta) +} + +func resourceThesaurusRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + id, indexId, err := ThesaurusParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + out, err := FindThesaurusByID(ctx, conn, id, indexId) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Kendra Thesaurus (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return diag.Errorf("reading Kendra Thesaurus (%s): %s", d.Id(), err) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Region: meta.(*conns.AWSClient).Region, + Service: "kendra", + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("index/%s/thesaurus/%s", indexId, id), + }.String() + + d.Set("arn", arn) + d.Set("description", out.Description) + d.Set("index_id", out.IndexId) + d.Set("name", out.Name) + d.Set("role_arn", out.RoleArn) + d.Set("status", out.Status) + d.Set("thesaurus_id", out.Id) + + if err := d.Set("source_s3_path", flattenSourceS3Path(out.SourceS3Path)); err != nil { + return diag.Errorf("setting complex argument: %s", err) + } + + tags, err := ListTags(ctx, conn, arn) + if err != nil { + return diag.Errorf("listing tags for Kendra Thesaurus (%s): %s", d.Id(), err) + } + + tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return diag.Errorf("setting tags: %s", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return diag.Errorf("setting tags_all: %s", err) + } + + return nil +} + +func resourceThesaurusUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + if d.HasChangesExcept("tags", "tags_all") { + id, indexId, err := ThesaurusParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + input := &kendra.UpdateThesaurusInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + } + + if d.HasChange("description") { + input.Description = aws.String(d.Get("description").(string)) + } + + if d.HasChange("name") { + input.Name = aws.String(d.Get("name").(string)) + } + + if d.HasChange("role_arn") { + input.RoleArn = aws.String(d.Get("role_arn").(string)) + } + + if d.HasChange("source_s3_path") { + input.SourceS3Path = expandSourceS3Path(d.Get("source_s3_path").([]interface{})) + } + + log.Printf("[DEBUG] Updating Kendra Thesaurus (%s): %#v", d.Id(), input) + + _, err = tfresource.RetryWhen( + propagationTimeout, + func() (interface{}, error) { + return conn.UpdateThesaurus(ctx, input) + }, + func(err error) (bool, error) { + var validationException *types.ValidationException + + if errors.As(err, &validationException) && strings.Contains(validationException.ErrorMessage(), validationExceptionMessage) { + return true, err + } + + return false, err + }, + ) + + if err != nil { + return diag.Errorf("updating Kendra Thesaurus(%s): %s", d.Id(), err) + } + + if _, err := waitThesaurusUpdated(ctx, conn, id, indexId, d.Timeout(schema.TimeoutUpdate)); err != nil { + return diag.Errorf("waiting for Kendra Thesaurus (%s) update: %s", d.Id(), err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(ctx, conn, d.Get("arn").(string), o, n); err != nil { + return diag.FromErr(fmt.Errorf("error updating Kendra Thesaurus (%s) tags: %s", d.Id(), err)) + } + } + + return resourceThesaurusRead(ctx, d, meta) +} + +func resourceThesaurusDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).KendraConn + + log.Printf("[INFO] Deleting Kendra Thesaurus %s", d.Id()) + + id, indexId, err := ThesaurusParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + _, err = conn.DeleteThesaurus(ctx, &kendra.DeleteThesaurusInput{ + Id: aws.String(id), + IndexId: aws.String(indexId), + }) + + var resourceNotFoundException *types.ResourceNotFoundException + if errors.As(err, &resourceNotFoundException) { + return nil + } + + if err != nil { + return diag.Errorf("deleting Kendra Thesaurus (%s): %s", d.Id(), err) + } + + if _, err := waitThesaurusDeleted(ctx, conn, id, indexId, d.Timeout(schema.TimeoutDelete)); err != nil { + return diag.Errorf("waiting for Kendra Thesaurus (%s) to be deleted: %s", d.Id(), err) + } + + return nil +} + +func statusThesaurus(ctx context.Context, conn *kendra.Client, id, indexId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + out, err := FindThesaurusByID(ctx, conn, id, indexId) + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return out, string(out.Status), nil + } +} + +func waitThesaurusCreated(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) (*kendra.DescribeThesaurusOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{string(types.ThesaurusStatusCreating)}, + Target: []string{string(types.ThesaurusStatusActive)}, + Refresh: statusThesaurus(ctx, conn, id, indexId), + Timeout: timeout, + NotFoundChecks: 20, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + if out, ok := outputRaw.(*kendra.DescribeThesaurusOutput); ok { + if out.Status == types.ThesaurusStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(out.ErrorMessage))) + } + return out, err + } + + return nil, err +} + +func waitThesaurusUpdated(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) (*kendra.DescribeThesaurusOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{string(types.QuerySuggestionsBlockListStatusUpdating)}, + Target: []string{string(types.QuerySuggestionsBlockListStatusActive)}, + Refresh: statusThesaurus(ctx, conn, id, indexId), + Timeout: timeout, + NotFoundChecks: 20, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + if out, ok := outputRaw.(*kendra.DescribeThesaurusOutput); ok { + if out.Status == types.ThesaurusStatusActiveButUpdateFailed || out.Status == types.ThesaurusStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(out.ErrorMessage))) + } + return out, err + } + + return nil, err +} + +func waitThesaurusDeleted(ctx context.Context, conn *kendra.Client, id, indexId string, timeout time.Duration) (*kendra.DescribeThesaurusOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{string(types.QuerySuggestionsBlockListStatusDeleting)}, + Target: []string{}, + Refresh: statusThesaurus(ctx, conn, id, indexId), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + if out, ok := outputRaw.(*kendra.DescribeThesaurusOutput); ok { + if out.Status == types.ThesaurusStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(out.ErrorMessage))) + } + return out, err + } + + return nil, err +} diff --git a/internal/service/kendra/thesaurus_test.go b/internal/service/kendra/thesaurus_test.go new file mode 100644 index 00000000000..5c8dd8809e3 --- /dev/null +++ b/internal/service/kendra/thesaurus_test.go @@ -0,0 +1,590 @@ +package kendra_test + +import ( + "context" + "fmt" + "regexp" + "testing" + + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfkendra "github.com/hashicorp/terraform-provider-aws/internal/service/kendra" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func testAccThesaurus_basic(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_thesaurus.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckThesaurusDestroy, + Steps: []resource.TestStep{ + { + Config: testAccThesaurusConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "index_id", "aws_kendra_index.test", "id"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test", "arn"), + resource.TestCheckResourceAttr(resourceName, "source_s3_path.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.bucket", "aws_s3_bucket.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.key", "aws_s3_object.test", "key"), + resource.TestCheckResourceAttrSet(resourceName, "status"), + resource.TestCheckResourceAttrSet(resourceName, "thesaurus_id"), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kendra", regexp.MustCompile(`index/.+/thesaurus/.+$`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccThesaurus_disappears(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_thesaurus.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckThesaurusDestroy, + Steps: []resource.TestStep{ + { + Config: testAccThesaurusConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfkendra.ResourceThesaurus(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccThesaurus_tags(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_thesaurus.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckThesaurusDestroy, + Steps: []resource.TestStep{ + { + Config: testAccThesaurusConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccThesaurusConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccThesaurusConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func testAccThesaurus_description(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_thesaurus.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckThesaurusDestroy, + Steps: []resource.TestStep{ + { + Config: testAccThesaurusConfig_description(rName, "description1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description1"), + ), + }, + { + Config: testAccThesaurusConfig_description(rName, "description2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccThesaurusConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", ""), + ), + }, + }, + }) +} + +func testAccThesaurus_name(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_thesaurus.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckThesaurusDestroy, + Steps: []resource.TestStep{ + { + Config: testAccThesaurusConfig_basic(rName1), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", rName1), + ), + }, + { + Config: testAccThesaurusConfig_name(rName1, rName2), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", rName2), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccThesaurus_roleARN(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_thesaurus.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckThesaurusDestroy, + Steps: []resource.TestStep{ + { + Config: testAccThesaurusConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test", "arn"), + ), + }, + { + Config: testAccThesaurusConfig_roleARN(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test2", "arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccThesaurus_sourceS3Path(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_kendra_thesaurus.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(names.KendraEndpointID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, names.KendraEndpointID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckThesaurusDestroy, + Steps: []resource.TestStep{ + { + Config: testAccThesaurusConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "source_s3_path.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.bucket", "aws_s3_bucket.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.key", "aws_s3_object.test", "key")), + }, + { + Config: testAccThesaurusConfig_sourceS3Path(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckThesaurusExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "source_s3_path.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.bucket", "aws_s3_bucket.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "source_s3_path.0.key", "aws_s3_object.test2", "key")), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckThesaurusDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_kendra_thesaurus" { + continue + } + + id, indexId, err := tfkendra.ThesaurusParseResourceID(rs.Primary.ID) + if err != nil { + return err + } + + _, err = tfkendra.FindThesaurusByID(context.TODO(), conn, id, indexId) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + } + + return nil +} + +func testAccCheckThesaurusExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Kendra Thesaurus is set") + } + + id, indexId, err := tfkendra.ThesaurusParseResourceID(rs.Primary.ID) + if err != nil { + return err + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).KendraConn + + _, err = tfkendra.FindThesaurusByID(context.TODO(), conn, id, indexId) + + if err != nil { + return fmt.Errorf("Error describing Kendra Thesaurus: %s", err.Error()) + } + + return nil + } +} + +func testAccThesaurusBaseConfig(rName string) string { + return fmt.Sprintf(` +data "aws_partition" "current" {} + +data "aws_iam_policy_document" "assume_role" { + statement { + actions = ["sts:AssumeRole"] + effect = "Allow" + principals { + type = "Service" + identifiers = ["kendra.${data.aws_partition.current.dns_suffix}"] + } + } +} + +resource "aws_iam_role" "test" { + name = %[1]q + path = "/" + assume_role_policy = data.aws_iam_policy_document.assume_role.json +} + +data "aws_iam_policy_document" "test" { + statement { + effect = "Allow" + actions = [ + "kendra:*", + "s3:GetBucketLocation", + "s3:GetObject", + "s3:ListBucket" + ] + resources = [ + aws_s3_bucket.test.arn, + "${aws_s3_bucket.test.arn}/*" + ] + } +} + +resource "aws_iam_policy" "test" { + name = %[1]q + description = "Allow Kendra to access S3" + policy = data.aws_iam_policy_document.test.json +} + +resource "aws_iam_role_policy_attachment" "test" { + role = aws_iam_role.test.name + policy_arn = aws_iam_policy.test.arn +} + +resource "aws_kendra_index" "test" { + depends_on = [aws_iam_role_policy_attachment.test] + + name = %[1]q + role_arn = aws_iam_role.test.arn +} + +resource "aws_s3_bucket" "test" { + bucket = %[1]q + force_destroy = true +} + +resource "aws_s3_object" "test" { + bucket = aws_s3_bucket.test.bucket + content = "test" + key = "test/thesaurus.txt" +} +`, rName) +} + +func testAccThesaurusConfig_basic(rName string) string { + return acctest.ConfigCompose( + testAccThesaurusBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_thesaurus" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, rName)) +} + +func testAccThesaurusConfig_tags1(rName, tag, value string) string { + return acctest.ConfigCompose( + testAccThesaurusBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_thesaurus" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } + + tags = { + %[2]q = %[3]q + } +} +`, rName, tag, value)) +} + +func testAccThesaurusConfig_tags2(rName, tag1, value1, tag2, value2 string) string { + return acctest.ConfigCompose( + testAccThesaurusBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_thesaurus" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tag1, value1, tag2, value2)) +} + +func testAccThesaurusConfig_description(rName, description string) string { + return acctest.ConfigCompose( + testAccThesaurusBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_thesaurus" "test" { + description = %[1]q + index_id = aws_kendra_index.test.id + name = %[2]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, description, rName)) +} + +func testAccThesaurusConfig_name(rName, name string) string { + return acctest.ConfigCompose( + testAccThesaurusBaseConfig(rName), + fmt.Sprintf(` +resource "aws_kendra_thesaurus" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, name)) +} + +func testAccThesaurusConfig_roleARN(rName string) string { + return acctest.ConfigCompose( + testAccThesaurusBaseConfig(rName), + fmt.Sprintf(` +resource "aws_iam_role" "test2" { + name = "%[1]s-2" + path = "/" + assume_role_policy = data.aws_iam_policy_document.assume_role.json +} + +resource "aws_iam_policy" "test2" { + name = "%[1]s-2" + description = "Allow Kendra to access S3" + policy = data.aws_iam_policy_document.test.json +} + +resource "aws_iam_role_policy_attachment" "test2" { + role = aws_iam_role.test2.name + policy_arn = aws_iam_policy.test2.arn +} + +resource "aws_kendra_thesaurus" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test2.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test.key + } +} +`, rName)) +} + +func testAccThesaurusConfig_sourceS3Path(rName string) string { + return acctest.ConfigCompose( + testAccThesaurusBaseConfig(rName), + fmt.Sprintf(` +resource "aws_s3_object" "test2" { + bucket = aws_s3_bucket.test.bucket + content = "test2" + key = "test/new_suggestions.txt" +} + +resource "aws_kendra_thesaurus" "test" { + index_id = aws_kendra_index.test.id + name = %[1]q + role_arn = aws_iam_role.test.arn + + source_s3_path { + bucket = aws_s3_bucket.test.id + key = aws_s3_object.test2.key + } +} +`, rName)) +} diff --git a/internal/service/keyspaces/keyspace_test.go b/internal/service/keyspaces/keyspace_test.go index a24b1f593dd..72c691c5f87 100644 --- a/internal/service/keyspaces/keyspace_test.go +++ b/internal/service/keyspaces/keyspace_test.go @@ -31,7 +31,7 @@ func TestAccKeyspacesKeyspace_basic(t *testing.T) { CheckDestroy: testAccCheckKeyspaceDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyspaceConfig(rName), + Config: testAccKeyspaceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyspaceExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "cassandra", "/keyspace/"+rName+"/"), @@ -59,7 +59,7 @@ func TestAccKeyspacesKeyspace_disappears(t *testing.T) { CheckDestroy: testAccCheckKeyspaceDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyspaceConfig(rName), + Config: testAccKeyspaceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyspaceExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfkeyspaces.ResourceKeyspace(), resourceName), @@ -81,7 +81,7 @@ func TestAccKeyspacesKeyspace_tags(t *testing.T) { CheckDestroy: testAccCheckKeyspaceDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyspaceConfigTags1(rName, "key1", "value1"), + Config: testAccKeyspaceConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -94,7 +94,7 @@ func TestAccKeyspacesKeyspace_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccKeyspaceConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccKeyspaceConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -103,7 +103,7 @@ func TestAccKeyspacesKeyspace_tags(t *testing.T) { ), }, { - Config: testAccKeyspaceConfigTags1(rName, "key2", "value2"), + Config: testAccKeyspaceConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyspaceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -161,7 +161,7 @@ func testAccCheckKeyspaceExists(n string) resource.TestCheckFunc { } } -func testAccKeyspaceConfig(rName string) string { +func testAccKeyspaceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_keyspaces_keyspace" "test" { name = %[1]q @@ -169,7 +169,7 @@ resource "aws_keyspaces_keyspace" "test" { `, rName) } -func testAccKeyspaceConfigTags1(rName, tag1Key, tag1Value string) string { +func testAccKeyspaceConfig_tags1(rName, tag1Key, tag1Value string) string { return fmt.Sprintf(` resource "aws_keyspaces_keyspace" "test" { name = %[1]q @@ -181,7 +181,7 @@ resource "aws_keyspaces_keyspace" "test" { `, rName, tag1Key, tag1Value) } -func testAccKeyspaceConfigTags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccKeyspaceConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return fmt.Sprintf(` resource "aws_keyspaces_keyspace" "test" { name = %[1]q diff --git a/internal/service/keyspaces/table.go b/internal/service/keyspaces/table.go index ca5d5785744..99c4a477ad5 100644 --- a/internal/service/keyspaces/table.go +++ b/internal/service/keyspaces/table.go @@ -210,8 +210,8 @@ func ResourceTable() *schema.Resource { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringMatch( - regexp.MustCompile(`^[a-z0-9]+$`), - "The type must consist of lower case alphanumerics.", + regexp.MustCompile(`^[a-z0-9]+(\<[a-z0-9]+(, *[a-z0-9]+){0,1}\>)?$`), + "The type must consist of lower case alphanumerics and an optional list of upto two lower case alphanumerics enclosed in angle brackets '<>'.", ), }, }, diff --git a/internal/service/keyspaces/table_test.go b/internal/service/keyspaces/table_test.go index df25e824bd7..7f86a2e67ea 100644 --- a/internal/service/keyspaces/table_test.go +++ b/internal/service/keyspaces/table_test.go @@ -30,7 +30,7 @@ func TestAccKeyspacesTable_basic(t *testing.T) { CheckDestroy: testAccCheckTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTableConfig(rName1, rName2), + Config: testAccTableConfig_basic(rName1, rName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "cassandra", fmt.Sprintf("/keyspace/%s/table/%s", rName1, rName2)), @@ -83,7 +83,7 @@ func TestAccKeyspacesTable_disappears(t *testing.T) { CheckDestroy: testAccCheckTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTableConfig(rName1, rName2), + Config: testAccTableConfig_basic(rName1, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckTableExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfkeyspaces.ResourceTable(), resourceName), @@ -107,7 +107,7 @@ func TestAccKeyspacesTable_tags(t *testing.T) { CheckDestroy: testAccCheckTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTableConfigTags1(rName1, rName2, "key1", "value1"), + Config: testAccTableConfig_tags1(rName1, rName2, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -120,7 +120,7 @@ func TestAccKeyspacesTable_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTableConfigTags2(rName1, rName2, "key1", "value1updated", "key2", "value2"), + Config: testAccTableConfig_tags2(rName1, rName2, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -129,7 +129,7 @@ func TestAccKeyspacesTable_tags(t *testing.T) { ), }, { - Config: testAccTableConfigTags1(rName1, rName2, "key2", "value2"), + Config: testAccTableConfig_tags1(rName1, rName2, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -153,7 +153,7 @@ func TestAccKeyspacesTable_multipleColumns(t *testing.T) { CheckDestroy: testAccCheckTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTableMultipleColumnsConfig(rName1, rName2), + Config: testAccTableConfig_multipleColumns(rName1, rName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "schema_definition.#", "1"), @@ -166,7 +166,7 @@ func TestAccKeyspacesTable_multipleColumns(t *testing.T) { "name": "region", "order_by": "DESC", }), - resource.TestCheckResourceAttr(resourceName, "schema_definition.0.column.#", "9"), + resource.TestCheckResourceAttr(resourceName, "schema_definition.0.column.#", "11"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "schema_definition.0.column.*", map[string]string{ "name": "id", "type": "text", @@ -203,6 +203,14 @@ func TestAccKeyspacesTable_multipleColumns(t *testing.T) { "name": "manager_id", "type": "text", }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "schema_definition.0.column.*", map[string]string{ + "name": "nicknames", + "type": "list", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "schema_definition.0.column.*", map[string]string{ + "name": "tags", + "type": "map", + }), resource.TestCheckResourceAttr(resourceName, "schema_definition.0.partition_key.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "schema_definition.0.partition_key.*", map[string]string{ "name": "id", @@ -239,7 +247,7 @@ func TestAccKeyspacesTable_update(t *testing.T) { CheckDestroy: testAccCheckTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTableAllAttributesConfig(rName1, rName2), + Config: testAccTableConfig_allAttributes(rName1, rName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v1), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "cassandra", fmt.Sprintf("/keyspace/%s/table/%s", rName1, rName2)), @@ -269,7 +277,7 @@ func TestAccKeyspacesTable_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTableAllAttributesUpdatedConfig(rName1, rName2), + Config: testAccTableConfig_allAttributesUpdated(rName1, rName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v2), testAccCheckTableNotRecreated(&v1, &v2), @@ -311,7 +319,7 @@ func TestAccKeyspacesTable_addColumns(t *testing.T) { CheckDestroy: testAccCheckTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTableConfig(rName1, rName2), + Config: testAccTableConfig_basic(rName1, rName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "schema_definition.#", "1"), @@ -334,7 +342,7 @@ func TestAccKeyspacesTable_addColumns(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTableNewColumnsConfig(rName1, rName2), + Config: testAccTableConfig_newColumns(rName1, rName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v2), testAccCheckTableNotRecreated(&v1, &v2), @@ -377,7 +385,7 @@ func TestAccKeyspacesTable_delColumns(t *testing.T) { CheckDestroy: testAccCheckTableDestroy, Steps: []resource.TestStep{ { - Config: testAccTableNewColumnsConfig(rName1, rName2), + Config: testAccTableConfig_newColumns(rName1, rName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "schema_definition.#", "1"), @@ -408,7 +416,7 @@ func TestAccKeyspacesTable_delColumns(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTableConfig(rName1, rName2), + Config: testAccTableConfig_basic(rName1, rName2), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTableExists(resourceName, &v2), testAccCheckTableRecreated(&v1, &v2), @@ -511,7 +519,7 @@ func testAccCheckTableRecreated(i, j *keyspaces.GetTableOutput) resource.TestChe } } -func testAccTableConfig(rName1, rName2 string) string { +func testAccTableConfig_basic(rName1, rName2 string) string { return fmt.Sprintf(` resource "aws_keyspaces_keyspace" "test" { name = %[1]q @@ -535,7 +543,7 @@ resource "aws_keyspaces_table" "test" { `, rName1, rName2) } -func testAccTableConfigTags1(rName1, rName2, tagKey1, tagValue1 string) string { +func testAccTableConfig_tags1(rName1, rName2, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_keyspaces_keyspace" "test" { name = %[1]q @@ -563,7 +571,7 @@ resource "aws_keyspaces_table" "test" { `, rName1, rName2, tagKey1, tagValue1) } -func testAccTableConfigTags2(rName1, rName2, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTableConfig_tags2(rName1, rName2, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_keyspaces_keyspace" "test" { name = %[1]q @@ -592,7 +600,7 @@ resource "aws_keyspaces_table" "test" { `, rName1, rName2, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccTableMultipleColumnsConfig(rName1, rName2 string) string { +func testAccTableConfig_multipleColumns(rName1, rName2 string) string { return fmt.Sprintf(` resource "aws_keyspaces_keyspace" "test" { name = %[1]q @@ -648,6 +656,16 @@ resource "aws_keyspaces_table" "test" { type = "text" } + column { + name = "nicknames" + type = "list" + } + + column { + name = "tags" + type = "map" + } + partition_key { name = "id" } @@ -674,7 +692,7 @@ resource "aws_keyspaces_table" "test" { `, rName1, rName2) } -func testAccTableAllAttributesConfig(rName1, rName2 string) string { +func testAccTableConfig_allAttributes(rName1, rName2 string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -727,7 +745,7 @@ resource "aws_keyspaces_table" "test" { `, rName1, rName2) } -func testAccTableAllAttributesUpdatedConfig(rName1, rName2 string) string { +func testAccTableConfig_allAttributesUpdated(rName1, rName2 string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -777,7 +795,7 @@ resource "aws_keyspaces_table" "test" { `, rName1, rName2) } -func testAccTableNewColumnsConfig(rName1, rName2 string) string { +func testAccTableConfig_newColumns(rName1, rName2 string) string { return fmt.Sprintf(` resource "aws_keyspaces_keyspace" "test" { name = %[1]q diff --git a/internal/service/kinesis/stream_consumer_data_source_test.go b/internal/service/kinesis/stream_consumer_data_source_test.go index ee19c8debbc..476981db013 100644 --- a/internal/service/kinesis/stream_consumer_data_source_test.go +++ b/internal/service/kinesis/stream_consumer_data_source_test.go @@ -23,7 +23,7 @@ func TestAccKinesisStreamConsumerDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccStreamConsumerDataSourceConfig(rName), + Config: testAccStreamConsumerDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), @@ -49,7 +49,7 @@ func TestAccKinesisStreamConsumerDataSource_name(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccStreamConsumerNameDataSourceConfig(rName), + Config: testAccStreamConsumerDataSourceConfig_name(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), @@ -75,7 +75,7 @@ func TestAccKinesisStreamConsumerDataSource_arn(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccStreamConsumerARNDataSourceConfig(rName), + Config: testAccStreamConsumerDataSourceConfig_arn(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), @@ -97,7 +97,7 @@ resource "aws_kinesis_stream" "test" { `, rName) } -func testAccStreamConsumerDataSourceConfig(rName string) string { +func testAccStreamConsumerDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( testAccStreamConsumerBaseDataSourceConfig(rName), fmt.Sprintf(` @@ -112,7 +112,7 @@ resource "aws_kinesis_stream_consumer" "test" { `, rName)) } -func testAccStreamConsumerNameDataSourceConfig(rName string) string { +func testAccStreamConsumerDataSourceConfig_name(rName string) string { return acctest.ConfigCompose( testAccStreamConsumerBaseDataSourceConfig(rName), fmt.Sprintf(` @@ -128,7 +128,7 @@ resource "aws_kinesis_stream_consumer" "test" { `, rName)) } -func testAccStreamConsumerARNDataSourceConfig(rName string) string { +func testAccStreamConsumerDataSourceConfig_arn(rName string) string { return acctest.ConfigCompose( testAccStreamConsumerBaseDataSourceConfig(rName), fmt.Sprintf(` diff --git a/internal/service/kinesis/stream_data_source_test.go b/internal/service/kinesis/stream_data_source_test.go index 6b81eaa3acc..e6e049ce406 100644 --- a/internal/service/kinesis/stream_data_source_test.go +++ b/internal/service/kinesis/stream_data_source_test.go @@ -21,7 +21,7 @@ func TestAccKinesisStreamDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckStreamDataSourceConfig(rName, 2), + Config: testAccStreamDataSourceConfig_basic(rName, 2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "arn"), resource.TestCheckResourceAttrSet(dataSourceName, "creation_timestamp"), @@ -36,7 +36,7 @@ func TestAccKinesisStreamDataSource_basic(t *testing.T) { ), }, { - Config: testAccCheckStreamDataSourceConfig(rName, 3), + Config: testAccStreamDataSourceConfig_basic(rName, 3), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "closed_shards.#", "4"), resource.TestCheckResourceAttr(dataSourceName, "open_shards.#", "3"), @@ -46,7 +46,7 @@ func TestAccKinesisStreamDataSource_basic(t *testing.T) { }) } -func testAccCheckStreamDataSourceConfig(rName string, shardCount int) string { +func testAccStreamDataSourceConfig_basic(rName string, shardCount int) string { return fmt.Sprintf(` resource "aws_kinesis_stream" "test" { name = %[1]q diff --git a/internal/service/kinesis/stream_test.go b/internal/service/kinesis/stream_test.go index 0e384a2eb59..0783dee0a7a 100644 --- a/internal/service/kinesis/stream_test.go +++ b/internal/service/kinesis/stream_test.go @@ -552,17 +552,17 @@ func TestAccKinesisStream_failOnBadStreamCountAndStreamModeCombination(t *testin Steps: []resource.TestStep{ // Check that we can't create an invalid combination { - Config: testAccStreamConfig_FailOnBadCountAndStreamModeCombination_nothingSet(rName), + Config: testAccStreamConfig_failOnBadCountAndModeCombinationNothingSet(rName), ExpectError: regexp.MustCompile(`shard_count must be at least 1 when stream_mode is PROVISIONED`), }, // Check that we can't create an invalid combination { - Config: testAccStreamConfig_FailOnBadCountAndStreamModeCombination_shardCountWhenOnDemand(rName), + Config: testAccStreamConfig_failOnBadCountAndModeCombinationShardCountWhenOnDemand(rName), ExpectError: regexp.MustCompile(`shard_count must not be set when stream_mode is ON_DEMAND`), }, // Prepare for updates... { - Config: testAccStreamConfig_failOnBadCountAndStreamModeCombination(rName), + Config: testAccStreamConfig_failOnBadCountAndModeCombination(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStreamExists(resourceName, &stream), resource.TestCheckResourceAttr(resourceName, "shard_count", "1"), @@ -571,12 +571,12 @@ func TestAccKinesisStream_failOnBadStreamCountAndStreamModeCombination(t *testin }, // Check that we can't update to an invalid combination { - Config: testAccStreamConfig_FailOnBadCountAndStreamModeCombination_nothingSet(rName), + Config: testAccStreamConfig_failOnBadCountAndModeCombinationNothingSet(rName), ExpectError: regexp.MustCompile(`shard_count must be at least 1 when stream_mode is PROVISIONED`), }, // Check that we can't update to an invalid combination { - Config: testAccStreamConfig_FailOnBadCountAndStreamModeCombination_shardCountWhenOnDemand(rName), + Config: testAccStreamConfig_failOnBadCountAndModeCombinationShardCountWhenOnDemand(rName), ExpectError: regexp.MustCompile(`shard_count must not be set when stream_mode is ON_DEMAND`), }, }, @@ -872,7 +872,7 @@ resource "aws_kinesis_stream" "test" { `, rName) } -func testAccStreamConfig_FailOnBadCountAndStreamModeCombination_nothingSet(rName string) string { +func testAccStreamConfig_failOnBadCountAndModeCombinationNothingSet(rName string) string { return fmt.Sprintf(` resource "aws_kinesis_stream" "test" { name = %[1]q @@ -880,7 +880,7 @@ resource "aws_kinesis_stream" "test" { `, rName) } -func testAccStreamConfig_FailOnBadCountAndStreamModeCombination_shardCountWhenOnDemand(rName string) string { +func testAccStreamConfig_failOnBadCountAndModeCombinationShardCountWhenOnDemand(rName string) string { return fmt.Sprintf(` resource "aws_kinesis_stream" "test" { name = %[1]q @@ -893,7 +893,7 @@ resource "aws_kinesis_stream" "test" { `, rName) } -func testAccStreamConfig_failOnBadCountAndStreamModeCombination(rName string) string { +func testAccStreamConfig_failOnBadCountAndModeCombination(rName string) string { return fmt.Sprintf(` resource "aws_kinesis_stream" "test" { name = %[1]q diff --git a/internal/service/kinesisanalyticsv2/application_snapshot_test.go b/internal/service/kinesisanalyticsv2/application_snapshot_test.go index 1b5aedf2371..ebab162b01d 100644 --- a/internal/service/kinesisanalyticsv2/application_snapshot_test.go +++ b/internal/service/kinesisanalyticsv2/application_snapshot_test.go @@ -27,7 +27,7 @@ func TestAccKinesisAnalyticsV2ApplicationSnapshot_basic(t *testing.T) { CheckDestroy: testAccCheckApplicationSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationSnapshotConfig(rName), + Config: testAccApplicationSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationSnapshotExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "application_name", applicationResourceName, "name"), @@ -57,7 +57,7 @@ func TestAccKinesisAnalyticsV2ApplicationSnapshot_disappears(t *testing.T) { CheckDestroy: testAccCheckApplicationSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationSnapshotConfig(rName), + Config: testAccApplicationSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationSnapshotExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfkinesisanalyticsv2.ResourceApplicationSnapshot(), resourceName), @@ -81,7 +81,7 @@ func TestAccKinesisAnalyticsV2ApplicationSnapshot_Disappears_application(t *test CheckDestroy: testAccCheckApplicationSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationSnapshotConfig(rName), + Config: testAccApplicationSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationSnapshotExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfkinesisanalyticsv2.ResourceApplication(), applicationResourceName), @@ -140,6 +140,6 @@ func testAccCheckApplicationSnapshotExists(n string, v *kinesisanalyticsv2.Snaps } } -func testAccApplicationSnapshotConfig(rName string) string { - return testAccApplicationConfigStartSnapshotableFlinkApplication(rName, "SKIP_RESTORE_FROM_SNAPSHOT", "", false) +func testAccApplicationSnapshotConfig_basic(rName string) string { + return testAccApplicationConfig_startSnapshotableFlink(rName, "SKIP_RESTORE_FROM_SNAPSHOT", "", false) } diff --git a/internal/service/kinesisanalyticsv2/application_test.go b/internal/service/kinesisanalyticsv2/application_test.go index bafef88213f..2548971ebf7 100644 --- a/internal/service/kinesisanalyticsv2/application_test.go +++ b/internal/service/kinesisanalyticsv2/application_test.go @@ -28,7 +28,7 @@ func TestAccKinesisAnalyticsV2Application_basicFlinkApplication(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigBasicFlinkApplication(rName, "FLINK-1_6"), + Config: testAccApplicationConfig_basicFlink(rName, "FLINK-1_6"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -70,7 +70,7 @@ func TestAccKinesisAnalyticsV2Application_basicFlinkApplication(t *testing.T) { ), }, { - Config: testAccApplicationConfigBasicFlinkApplication(rName, "FLINK-1_8"), + Config: testAccApplicationConfig_basicFlink(rName, "FLINK-1_8"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -112,7 +112,7 @@ func TestAccKinesisAnalyticsV2Application_basicFlinkApplication(t *testing.T) { ), }, { - Config: testAccApplicationConfigBasicFlinkApplication(rName, "FLINK-1_11"), + Config: testAccApplicationConfig_basicFlink(rName, "FLINK-1_11"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -154,7 +154,7 @@ func TestAccKinesisAnalyticsV2Application_basicFlinkApplication(t *testing.T) { ), }, { - Config: testAccApplicationConfigBasicFlinkApplication(rName, "FLINK-1_13"), + Config: testAccApplicationConfig_basicFlink(rName, "FLINK-1_13"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -217,7 +217,7 @@ func TestAccKinesisAnalyticsV2Application_basicSQLApplication(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigBasicSQLApplication(rName), + Config: testAccApplicationConfig_basicSQL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "0"), @@ -257,7 +257,7 @@ func TestAccKinesisAnalyticsV2Application_disappears(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigBasicSQLApplication(rName), + Config: testAccApplicationConfig_basicSQL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfkinesisanalyticsv2.ResourceApplication(), resourceName), @@ -280,7 +280,7 @@ func TestAccKinesisAnalyticsV2Application_tags(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigTags1(rName, "key1", "value1"), + Config: testAccApplicationConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -294,7 +294,7 @@ func TestAccKinesisAnalyticsV2Application_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccApplicationConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccApplicationConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -304,7 +304,7 @@ func TestAccKinesisAnalyticsV2Application_tags(t *testing.T) { ), }, { - Config: testAccApplicationConfigTags1(rName, "key2", "value2"), + Config: testAccApplicationConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -329,7 +329,7 @@ func TestAccKinesisAnalyticsV2Application_ApplicationCode_update(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigApplicationCodeConfiguration(rName, "SELECT 1;\n"), + Config: testAccApplicationConfig_applicationCodeConfiguration(rName, "SELECT 1;\n"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -360,7 +360,7 @@ func TestAccKinesisAnalyticsV2Application_ApplicationCode_update(t *testing.T) { ), }, { - Config: testAccApplicationConfigApplicationCodeConfiguration(rName, "SELECT 2;\n"), + Config: testAccApplicationConfig_applicationCodeConfiguration(rName, "SELECT 2;\n"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -413,7 +413,7 @@ func TestAccKinesisAnalyticsV2Application_CloudWatchLoggingOptions_add(t *testin CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigBasicSQLApplication(rName), + Config: testAccApplicationConfig_basicSQL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "0"), @@ -433,7 +433,7 @@ func TestAccKinesisAnalyticsV2Application_CloudWatchLoggingOptions_add(t *testin ), }, { - Config: testAccApplicationConfigCloudWatchLoggingOptions(rName, 0), + Config: testAccApplicationConfig_cloudWatchLoggingOptions(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "0"), @@ -476,7 +476,7 @@ func TestAccKinesisAnalyticsV2Application_CloudWatchLoggingOptions_delete(t *tes CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigCloudWatchLoggingOptions(rName, 0), + Config: testAccApplicationConfig_cloudWatchLoggingOptions(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "0"), @@ -497,7 +497,7 @@ func TestAccKinesisAnalyticsV2Application_CloudWatchLoggingOptions_delete(t *tes ), }, { - Config: testAccApplicationConfigBasicSQLApplication(rName), + Config: testAccApplicationConfig_basicSQL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "0"), @@ -540,7 +540,7 @@ func TestAccKinesisAnalyticsV2Application_CloudWatchLoggingOptions_update(t *tes CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigCloudWatchLoggingOptions(rName, 0), + Config: testAccApplicationConfig_cloudWatchLoggingOptions(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "0"), @@ -561,7 +561,7 @@ func TestAccKinesisAnalyticsV2Application_CloudWatchLoggingOptions_update(t *tes ), }, { - Config: testAccApplicationConfigCloudWatchLoggingOptions(rName, 1), + Config: testAccApplicationConfig_cloudWatchLoggingOptions(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "0"), @@ -605,7 +605,7 @@ func TestAccKinesisAnalyticsV2Application_EnvironmentProperties_update(t *testin CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigEnvironmentProperties(rName), + Config: testAccApplicationConfig_environmentProperties(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -666,7 +666,7 @@ func TestAccKinesisAnalyticsV2Application_EnvironmentProperties_update(t *testin ), }, { - Config: testAccApplicationConfigEnvironmentPropertiesUpdated(rName), + Config: testAccApplicationConfig_environmentPropertiesUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -735,7 +735,7 @@ func TestAccKinesisAnalyticsV2Application_EnvironmentProperties_update(t *testin ImportStateVerify: true, }, { - Config: testAccApplicationConfigEnvironmentPropertiesNotSpecified(rName), + Config: testAccApplicationConfig_environmentPropertiesNotSpecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -802,7 +802,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplication_update(t *testing.T) CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigFlinkApplicationConfiguration(rName, ""), + Config: testAccApplicationConfig_flinkConfiguration(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -850,7 +850,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplication_update(t *testing.T) ), }, { - Config: testAccApplicationConfigFlinkApplicationConfigurationUpdated(rName, ""), + Config: testAccApplicationConfig_flinkConfigurationUpdated(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -923,7 +923,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplicationEnvironmentProperties_ CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigFlinkApplicationConfigurationEnvironmentProperties(rName), + Config: testAccApplicationConfig_flinkConfigurationEnvironmentProperties(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -985,7 +985,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplicationEnvironmentProperties_ ), }, { - Config: testAccApplicationConfigFlinkApplicationConfigurationEnvironmentPropertiesUpdated(rName), + Config: testAccApplicationConfig_flinkConfigurationEnvironmentPropertiesUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1075,7 +1075,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplication_restoreFromSnapshot(t CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigStartSnapshotableFlinkApplication(rName, "RESTORE_FROM_LATEST_SNAPSHOT", "", false), + Config: testAccApplicationConfig_startSnapshotableFlink(rName, "RESTORE_FROM_LATEST_SNAPSHOT", "", false), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1139,7 +1139,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplication_restoreFromSnapshot(t ), }, { - Config: testAccApplicationConfigStopSnapshotableFlinkApplication(rName, false), + Config: testAccApplicationConfig_stopSnapshotableFlink(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1204,7 +1204,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplication_restoreFromSnapshot(t ImportStateVerifyIgnore: []string{"force_stop", "start_application"}, }, { - Config: testAccApplicationConfigStartSnapshotableFlinkApplication(rName, "RESTORE_FROM_CUSTOM_SNAPSHOT", rName, false), + Config: testAccApplicationConfig_startSnapshotableFlink(rName, "RESTORE_FROM_CUSTOM_SNAPSHOT", rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1268,7 +1268,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplication_restoreFromSnapshot(t ), }, { - Config: testAccApplicationConfigStopSnapshotableFlinkApplication(rName, true), + Config: testAccApplicationConfig_stopSnapshotableFlink(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1345,7 +1345,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplicationStartApplication_onCre CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigFlinkApplicationConfiguration(rName, "true"), + Config: testAccApplicationConfig_flinkConfiguration(rName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1421,7 +1421,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplicationStartApplication_onUpd CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigFlinkApplicationConfiguration(rName, "false"), + Config: testAccApplicationConfig_flinkConfiguration(rName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1475,7 +1475,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplicationStartApplication_onUpd ImportStateVerifyIgnore: []string{"start_application"}, }, { - Config: testAccApplicationConfigFlinkApplicationConfiguration(rName, "true"), + Config: testAccApplicationConfig_flinkConfiguration(rName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1527,7 +1527,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplicationStartApplication_onUpd ), }, { - Config: testAccApplicationConfigFlinkApplicationConfiguration(rName, "false"), + Config: testAccApplicationConfig_flinkConfiguration(rName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1594,7 +1594,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplication_updateRunning(t *test CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigFlinkApplicationConfiguration(rName, "true"), + Config: testAccApplicationConfig_flinkConfiguration(rName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1652,7 +1652,7 @@ func TestAccKinesisAnalyticsV2Application_FlinkApplication_updateRunning(t *test ImportStateVerifyIgnore: []string{"start_application"}, }, { - Config: testAccApplicationConfigFlinkApplicationConfigurationUpdated(rName, "true"), + Config: testAccApplicationConfig_flinkConfigurationUpdated(rName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1721,7 +1721,7 @@ func TestAccKinesisAnalyticsV2Application_ServiceExecutionRole_update(t *testing CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigBasicSQLApplicationPlusDescription(rName), + Config: testAccApplicationConfig_basicSQLPlusDescription(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "0"), @@ -1741,7 +1741,7 @@ func TestAccKinesisAnalyticsV2Application_ServiceExecutionRole_update(t *testing ), }, { - Config: testAccApplicationConfigBasicSQLApplicationServiceExecutionRoleUpdated(rName), + Config: testAccApplicationConfig_basicSQLServiceExecutionRoleUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "0"), @@ -1783,7 +1783,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInput_add(t *testing.T) CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationNotSpecified(rName), + Config: testAccApplicationConfig_sqlConfigurationNotSpecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1814,7 +1814,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInput_add(t *testing.T) ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationInput(rName), + Config: testAccApplicationConfig_sqlConfigurationInput(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1894,7 +1894,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInput_update(t *testing. CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationInput(rName), + Config: testAccApplicationConfig_sqlConfigurationInput(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -1951,7 +1951,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInput_update(t *testing. ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationInputUpdated(rName), + Config: testAccApplicationConfig_sqlConfigurationInputUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2034,7 +2034,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInputProcessing_add(t *t CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationInput(rName), + Config: testAccApplicationConfig_sqlConfigurationInput(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2091,7 +2091,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInputProcessing_add(t *t ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationInputProcessingConfiguration(rName, 0), + Config: testAccApplicationConfig_sqlConfigurationInputProcessingConfiguration(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2173,7 +2173,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInputProcessing_delete(t CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationInputProcessingConfiguration(rName, 0), + Config: testAccApplicationConfig_sqlConfigurationInputProcessingConfiguration(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2232,7 +2232,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInputProcessing_delete(t ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationInput(rName), + Config: testAccApplicationConfig_sqlConfigurationInput(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2313,7 +2313,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInputProcessing_update(t CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationInputProcessingConfiguration(rName, 0), + Config: testAccApplicationConfig_sqlConfigurationInputProcessingConfiguration(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2372,7 +2372,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationInputProcessing_update(t ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationInputProcessingConfiguration(rName, 1), + Config: testAccApplicationConfig_sqlConfigurationInputProcessingConfiguration(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2458,7 +2458,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationMultiple_update(t *testi CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationMultiple(rName, "", ""), + Config: testAccApplicationConfig_sqlConfigurationMultiple(rName, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2528,7 +2528,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationMultiple_update(t *testi ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationMultipleUpdated(rName, "", ""), + Config: testAccApplicationConfig_sqlConfigurationMultipleUpdated(rName, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2649,7 +2649,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationOutput_update(t *testing CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationOutput(rName), + Config: testAccApplicationConfig_sqlConfigurationOutput(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2692,7 +2692,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationOutput_update(t *testing ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationOutputUpdated(rName), + Config: testAccApplicationConfig_sqlConfigurationOutputUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2749,7 +2749,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationOutput_update(t *testing ImportStateVerify: true, }, { - Config: testAccApplicationConfigSQLApplicationConfigurationNotSpecified(rName), + Config: testAccApplicationConfig_sqlConfigurationNotSpecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2797,7 +2797,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationReferenceDataSource_add( CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationNotSpecified(rName), + Config: testAccApplicationConfig_sqlConfigurationNotSpecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2828,7 +2828,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationReferenceDataSource_add( ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationReferenceDataSource(rName), + Config: testAccApplicationConfig_sqlConfigurationReferenceDataSource(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2901,7 +2901,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationReferenceDataSource_dele CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationReferenceDataSource(rName), + Config: testAccApplicationConfig_sqlConfigurationReferenceDataSource(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -2952,7 +2952,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationReferenceDataSource_dele ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationNotSpecified(rName), + Config: testAccApplicationConfig_sqlConfigurationNotSpecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3005,7 +3005,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationReferenceDataSource_upda CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationReferenceDataSource(rName), + Config: testAccApplicationConfig_sqlConfigurationReferenceDataSource(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3056,7 +3056,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationReferenceDataSource_upda ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationReferenceDataSourceUpdated(rName), + Config: testAccApplicationConfig_sqlConfigurationReferenceDataSourceUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3132,7 +3132,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationStartApplication_onCreat CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationStartApplication(rName, true), + Config: testAccApplicationConfig_sqlConfigurationStart(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3212,7 +3212,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationStartApplication_onUpdat CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationStartApplication(rName, false), + Config: testAccApplicationConfig_sqlConfigurationStart(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3275,7 +3275,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationStartApplication_onUpdat ImportStateVerifyIgnore: []string{"start_application"}, }, { - Config: testAccApplicationConfigSQLApplicationConfigurationStartApplication(rName, true), + Config: testAccApplicationConfig_sqlConfigurationStart(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3332,7 +3332,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationStartApplication_onUpdat ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationStartApplication(rName, false), + Config: testAccApplicationConfig_sqlConfigurationStart(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3411,7 +3411,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplication_updateRunning(t *testin CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigSQLApplicationConfigurationMultiple(rName, "true", "LAST_STOPPED_POINT"), + Config: testAccApplicationConfig_sqlConfigurationMultiple(rName, "true", "LAST_STOPPED_POINT"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3481,7 +3481,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplication_updateRunning(t *testin ), }, { - Config: testAccApplicationConfigSQLApplicationConfigurationMultipleUpdated(rName, "true", "LAST_STOPPED_POINT"), + Config: testAccApplicationConfig_sqlConfigurationMultipleUpdated(rName, "true", "LAST_STOPPED_POINT"), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3603,7 +3603,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationVPC_add(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigVPCConfigurationNotSpecified(rName), + Config: testAccApplicationConfig_vpcConfigurationNotSpecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3651,7 +3651,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationVPC_add(t *testing.T) { ), }, { - Config: testAccApplicationConfigVPCConfiguration(rName), + Config: testAccApplicationConfig_vpcConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3727,7 +3727,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationVPC_delete(t *testing.T) CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigVPCConfiguration(rName), + Config: testAccApplicationConfig_vpcConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3779,7 +3779,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationVPC_delete(t *testing.T) ), }, { - Config: testAccApplicationConfigVPCConfigurationNotSpecified(rName), + Config: testAccApplicationConfig_vpcConfigurationNotSpecified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3851,7 +3851,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationVPC_update(t *testing.T) CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigVPCConfiguration(rName), + Config: testAccApplicationConfig_vpcConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3903,7 +3903,7 @@ func TestAccKinesisAnalyticsV2Application_SQLApplicationVPC_update(t *testing.T) ), }, { - Config: testAccApplicationConfigVPCConfigurationUpdated(rName), + Config: testAccApplicationConfig_vpcConfigurationUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -3979,7 +3979,7 @@ func TestAccKinesisAnalyticsV2Application_RunConfiguration_Update(t *testing.T) CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationConfigStartSnapshotableFlinkApplication(rName, "RESTORE_FROM_LATEST_SNAPSHOT", "", false), + Config: testAccApplicationConfig_startSnapshotableFlink(rName, "RESTORE_FROM_LATEST_SNAPSHOT", "", false), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -4042,7 +4042,7 @@ func TestAccKinesisAnalyticsV2Application_RunConfiguration_Update(t *testing.T) ), }, { - Config: testAccApplicationConfigStartSnapshotableFlinkApplication(rName, "RESTORE_FROM_CUSTOM_SNAPSHOT", rName, true), + Config: testAccApplicationConfig_startSnapshotableFlink(rName, "RESTORE_FROM_CUSTOM_SNAPSHOT", rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "application_configuration.#", "1"), @@ -4179,7 +4179,7 @@ func testAccPreCheck(t *testing.T) { } } -func testAccApplicationConfigBaseServiceExecutionIamRole(rName string) string { +func testAccApplicationConfig_baseServiceExecutionIAMRole(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { count = 2 @@ -4339,9 +4339,9 @@ resource "aws_security_group" "test" { `, rName)) } -func testAccApplicationConfigBasicFlinkApplication(rName, runtimeEnvironment string) string { +func testAccApplicationConfig_basicFlink(rName, runtimeEnvironment string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { name = %[1]q @@ -4351,9 +4351,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, runtimeEnvironment)) } -func testAccApplicationConfigBasicSQLApplication(rName string) string { +func testAccApplicationConfig_basicSQL(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { name = %[1]q @@ -4363,9 +4363,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigBasicSQLApplicationPlusDescription(rName string) string { +func testAccApplicationConfig_basicSQLPlusDescription(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { name = %[1]q @@ -4376,9 +4376,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigBasicSQLApplicationServiceExecutionRoleUpdated(rName string) string { +func testAccApplicationConfig_basicSQLServiceExecutionRoleUpdated(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { name = %[1]q @@ -4389,9 +4389,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigApplicationCodeConfiguration(rName, textContent string) string { +func testAccApplicationConfig_applicationCodeConfiguration(rName, textContent string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { name = %[1]q @@ -4411,9 +4411,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, textContent)) } -func testAccApplicationConfigCloudWatchLoggingOptions(rName string, streamIndex int) string { +func testAccApplicationConfig_cloudWatchLoggingOptions(rName string, streamIndex int) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = %[1]q @@ -4438,9 +4438,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, streamIndex)) } -func testAccApplicationConfigEnvironmentProperties(rName string) string { +func testAccApplicationConfig_environmentProperties(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -4485,9 +4485,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigEnvironmentPropertiesUpdated(rName string) string { +func testAccApplicationConfig_environmentPropertiesUpdated(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -4538,9 +4538,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigEnvironmentPropertiesNotSpecified(rName string) string { +func testAccApplicationConfig_environmentPropertiesNotSpecified(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -4564,13 +4564,13 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigFlinkApplicationConfiguration(rName, startApplication string) string { +func testAccApplicationConfig_flinkConfiguration(rName, startApplication string) string { if startApplication == "" { startApplication = "null" } return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -4620,13 +4620,13 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, startApplication)) } -func testAccApplicationConfigFlinkApplicationConfigurationUpdated(rName, startApplication string) string { +func testAccApplicationConfig_flinkConfigurationUpdated(rName, startApplication string) string { if startApplication == "" { startApplication = "null" } return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -4676,9 +4676,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, startApplication)) } -func testAccApplicationConfigFlinkApplicationConfigurationEnvironmentProperties(rName string) string { +func testAccApplicationConfig_flinkConfigurationEnvironmentProperties(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -4751,9 +4751,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigFlinkApplicationConfigurationEnvironmentPropertiesUpdated(rName string) string { +func testAccApplicationConfig_flinkConfigurationEnvironmentPropertiesUpdated(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -4833,7 +4833,7 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigStartSnapshotableFlinkApplication(rName, applicationRestoreType, snapshotName string, allowNonRestoredState bool) string { +func testAccApplicationConfig_startSnapshotableFlink(rName, applicationRestoreType, snapshotName string, allowNonRestoredState bool) string { if snapshotName == "" { snapshotName = "null" } else { @@ -4841,7 +4841,7 @@ func testAccApplicationConfigStartSnapshotableFlinkApplication(rName, applicatio } return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` data "aws_region" "current" {} @@ -4929,9 +4929,9 @@ resource "aws_kinesisanalyticsv2_application_snapshot" "test" { `, rName, applicationRestoreType, snapshotName, allowNonRestoredState)) } -func testAccApplicationConfigStopSnapshotableFlinkApplication(rName string, forceStop bool) string { +func testAccApplicationConfig_stopSnapshotableFlink(rName string, forceStop bool) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` data "aws_region" "current" {} @@ -5010,9 +5010,9 @@ resource "aws_kinesisanalyticsv2_application_snapshot" "test" { `, rName, forceStop)) } -func testAccApplicationConfigSQLApplicationConfigurationNotSpecified(rName string) string { +func testAccApplicationConfig_sqlConfigurationNotSpecified(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5033,9 +5033,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigSQLApplicationConfigurationInput(rName string) string { +func testAccApplicationConfig_sqlConfigurationInput(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5084,9 +5084,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigSQLApplicationConfigurationInputUpdated(rName string) string { +func testAccApplicationConfig_sqlConfigurationInputUpdated(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5147,9 +5147,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigSQLApplicationConfigurationInputProcessingConfiguration(rName string, lambdaIndex int) string { +func testAccApplicationConfig_sqlConfigurationInputProcessingConfiguration(rName string, lambdaIndex int) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5204,7 +5204,7 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, lambdaIndex)) } -func testAccApplicationConfigSQLApplicationConfigurationMultiple(rName, startApplication, startingPosition string) string { +func testAccApplicationConfig_sqlConfigurationMultiple(rName, startApplication, startingPosition string) string { if startApplication == "" { startApplication = "null" } @@ -5215,7 +5215,7 @@ func testAccApplicationConfigSQLApplicationConfigurationMultiple(rName, startApp } return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { @@ -5305,7 +5305,7 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, startApplication, startingPosition)) } -func testAccApplicationConfigSQLApplicationConfigurationMultipleUpdated(rName, startApplication, startingPosition string) string { +func testAccApplicationConfig_sqlConfigurationMultipleUpdated(rName, startApplication, startingPosition string) string { if startApplication == "" { startApplication = "null" } @@ -5316,7 +5316,7 @@ func testAccApplicationConfigSQLApplicationConfigurationMultipleUpdated(rName, s } return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5439,9 +5439,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, startApplication, startingPosition)) } -func testAccApplicationConfigSQLApplicationConfigurationOutput(rName string) string { +func testAccApplicationConfig_sqlConfigurationOutput(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5476,9 +5476,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigSQLApplicationConfigurationOutputUpdated(rName string) string { +func testAccApplicationConfig_sqlConfigurationOutputUpdated(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5525,9 +5525,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigSQLApplicationConfigurationReferenceDataSource(rName string) string { +func testAccApplicationConfig_sqlConfigurationReferenceDataSource(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5577,9 +5577,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigSQLApplicationConfigurationReferenceDataSourceUpdated(rName string) string { +func testAccApplicationConfig_sqlConfigurationReferenceDataSourceUpdated(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5637,9 +5637,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigSQLApplicationConfigurationStartApplication(rName string, start bool) string { +func testAccApplicationConfig_sqlConfigurationStart(rName string, start bool) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseSQLApplication(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { @@ -5694,9 +5694,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, start)) } -func testAccApplicationConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccApplicationConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { name = %[1]q @@ -5710,9 +5710,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, tagKey1, tagValue1)) } -func testAccApplicationConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccApplicationConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), fmt.Sprintf(` resource "aws_kinesisanalyticsv2_application" "test" { name = %[1]q @@ -5727,9 +5727,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccApplicationConfigVPCConfiguration(rName string) string { +func testAccApplicationConfig_vpcConfiguration(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseVPC(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` @@ -5759,9 +5759,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigVPCConfigurationUpdated(rName string) string { +func testAccApplicationConfig_vpcConfigurationUpdated(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseVPC(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` @@ -5791,9 +5791,9 @@ resource "aws_kinesisanalyticsv2_application" "test" { `, rName)) } -func testAccApplicationConfigVPCConfigurationNotSpecified(rName string) string { +func testAccApplicationConfig_vpcConfigurationNotSpecified(rName string) string { return acctest.ConfigCompose( - testAccApplicationConfigBaseServiceExecutionIamRole(rName), + testAccApplicationConfig_baseServiceExecutionIAMRole(rName), testAccApplicationConfigBaseVPC(rName), testAccApplicationConfigBaseFlinkApplication(rName), fmt.Sprintf(` diff --git a/internal/service/kinesisvideo/stream.go b/internal/service/kinesisvideo/stream.go index 4b55b6251cd..ab8a3baf8e0 100644 --- a/internal/service/kinesisvideo/stream.go +++ b/internal/service/kinesisvideo/stream.go @@ -152,13 +152,13 @@ func resourceStreamRead(d *schema.ResourceData, meta interface{}) error { } resp, err := conn.DescribeStream(descOpts) - if tfawserr.ErrCodeEquals(err, kinesisvideo.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, kinesisvideo.ErrCodeResourceNotFoundException) { log.Printf("[WARN] Kinesis Video Stream (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("Error describing Kinesis Video Stream (%s): %s", d.Id(), err) + return fmt.Errorf("Error describing Kinesis Video Stream (%s): %w", d.Id(), err) } d.Set("name", resp.StreamInfo.StreamName) @@ -168,14 +168,14 @@ func resourceStreamRead(d *schema.ResourceData, meta interface{}) error { d.Set("media_type", resp.StreamInfo.MediaType) d.Set("arn", resp.StreamInfo.StreamARN) if err := d.Set("creation_time", resp.StreamInfo.CreationTime.Format(time.RFC3339)); err != nil { - return fmt.Errorf("error setting creation_time: %s", err) + return fmt.Errorf("error setting creation_time: %w", err) } d.Set("version", resp.StreamInfo.Version) tags, err := ListTags(conn, d.Id()) if err != nil { - return fmt.Errorf("error listing tags for Kinesis Video Stream (%s): %s", d.Id(), err) + return fmt.Errorf("error listing tags for Kinesis Video Stream (%s): %w", d.Id(), err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -209,19 +209,14 @@ func resourceStreamUpdate(d *schema.ResourceData, meta interface{}) error { } if _, err := conn.UpdateStream(updateOpts); err != nil { - if tfawserr.ErrCodeEquals(err, kinesisvideo.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] Kinesis Video Stream (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error updating Kinesis Video Stream (%s): %s", d.Id(), err) + return fmt.Errorf("Error updating Kinesis Video Stream (%s): %w", d.Id(), err) } if d.HasChange("tags_all") { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating Kinesis Video Stream (%s) tags: %s", d.Id(), err) + return fmt.Errorf("error updating Kinesis Video Stream (%s) tags: %w", d.Id(), err) } } @@ -235,7 +230,7 @@ func resourceStreamUpdate(d *schema.ResourceData, meta interface{}) error { } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for updating Kinesis Video Stream (%s): %s", d.Id(), err) + return fmt.Errorf("Error waiting for updating Kinesis Video Stream (%s): %w", d.Id(), err) } return resourceStreamRead(d, meta) @@ -251,7 +246,7 @@ func resourceStreamDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, kinesisvideo.ErrCodeResourceNotFoundException) { return nil } - return fmt.Errorf("Error deleting Kinesis Video Stream (%s): %s", d.Id(), err) + return fmt.Errorf("Error deleting Kinesis Video Stream (%s): %w", d.Id(), err) } stateConf := &resource.StateChangeConf{ @@ -264,7 +259,7 @@ func resourceStreamDelete(d *schema.ResourceData, meta interface{}) error { } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for deleting Kinesis Video Stream (%s): %s", d.Id(), err) + return fmt.Errorf("Error waiting for deleting Kinesis Video Stream (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/kms/alias_data_source_test.go b/internal/service/kms/alias_data_source_test.go index 453318aac58..139c93c8328 100644 --- a/internal/service/kms/alias_data_source_test.go +++ b/internal/service/kms/alias_data_source_test.go @@ -21,7 +21,7 @@ func TestAccKMSAliasDataSource_service(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAliasDataSourceConfig(rName), + Config: testAccAliasDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "kms", rName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -44,7 +44,7 @@ func TestAccKMSAliasDataSource_cmk(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAliasCMKDataSourceConfig(rName), + Config: testAccAliasDataSourceConfig_cmk(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceAliasResourceName, "arn", aliasResourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceAliasResourceName, "target_key_arn", aliasResourceName, "target_key_arn"), @@ -55,7 +55,7 @@ func TestAccKMSAliasDataSource_cmk(t *testing.T) { }) } -func testAccAliasDataSourceConfig(rName string) string { +func testAccAliasDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_kms_alias" "test" { name = %[1]q @@ -63,7 +63,7 @@ data "aws_kms_alias" "test" { `, rName) } -func testAccAliasCMKDataSourceConfig(rName string) string { +func testAccAliasDataSourceConfig_cmk(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q diff --git a/internal/service/kms/alias_test.go b/internal/service/kms/alias_test.go index f31ec500b70..818949d28c0 100644 --- a/internal/service/kms/alias_test.go +++ b/internal/service/kms/alias_test.go @@ -29,7 +29,7 @@ func TestAccKMSAlias_basic(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasNameConfig(rName), + Config: testAccAliasConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &alias), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kms", regexp.MustCompile(`alias/.+`)), @@ -59,7 +59,7 @@ func TestAccKMSAlias_disappears(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasNameConfig(rName), + Config: testAccAliasConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &alias), acctest.CheckResourceDisappears(acctest.Provider, tfkms.ResourceAlias(), resourceName), @@ -82,7 +82,7 @@ func TestAccKMSAlias_Name_generated(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasNameGeneratedConfig(rName), + Config: testAccAliasConfig_nameGenerated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &alias), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile(fmt.Sprintf("%s[[:xdigit:]]{%d}", tfkms.AliasNamePrefix, resource.UniqueIDSuffixLength))), @@ -110,7 +110,7 @@ func TestAccKMSAlias_namePrefix(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasNamePrefixConfig(rName, tfkms.AliasNamePrefix+"tf-acc-test-prefix-"), + Config: testAccAliasConfig_namePrefix(rName, tfkms.AliasNamePrefix+"tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &alias), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", tfkms.AliasNamePrefix+"tf-acc-test-prefix-"), @@ -140,7 +140,7 @@ func TestAccKMSAlias_updateKeyID(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasNameConfig(rName), + Config: testAccAliasConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &alias), resource.TestCheckResourceAttrPair(resourceName, "target_key_arn", key1ResourceName, "arn"), @@ -148,7 +148,7 @@ func TestAccKMSAlias_updateKeyID(t *testing.T) { ), }, { - Config: testAccAliasUpdatedKeyIDConfig(rName), + Config: testAccAliasConfig_updatedKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &alias), resource.TestCheckResourceAttrPair(resourceName, "target_key_arn", key2ResourceName, "arn"), @@ -178,7 +178,7 @@ func TestAccKMSAlias_multipleAliasesForSameKey(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasMultipleConfig(rName), + Config: testAccAliasConfig_multiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &alias), resource.TestCheckResourceAttrPair(resourceName, "target_key_arn", keyResourceName, "arn"), @@ -209,7 +209,7 @@ func TestAccKMSAlias_arnDiffSuppress(t *testing.T) { CheckDestroy: testAccCheckAliasDestroy, Steps: []resource.TestStep{ { - Config: testAccAliasDiffSuppressConfig(rName), + Config: testAccAliasConfig_diffSuppress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAliasExists(resourceName, &alias), resource.TestCheckResourceAttrSet(resourceName, "target_key_arn"), @@ -223,7 +223,7 @@ func TestAccKMSAlias_arnDiffSuppress(t *testing.T) { { ExpectNonEmptyPlan: false, PlanOnly: true, - Config: testAccAliasDiffSuppressConfig(rName), + Config: testAccAliasConfig_diffSuppress(rName), }, }, }) @@ -278,7 +278,7 @@ func testAccCheckAliasExists(name string, v *kms.AliasListEntry) resource.TestCh } } -func testAccAliasNameConfig(rName string) string { +func testAccAliasConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -292,7 +292,7 @@ resource "aws_kms_alias" "test" { `, rName) } -func testAccAliasNameGeneratedConfig(rName string) string { +func testAccAliasConfig_nameGenerated(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -305,7 +305,7 @@ resource "aws_kms_alias" "test" { `, rName) } -func testAccAliasNamePrefixConfig(rName, namePrefix string) string { +func testAccAliasConfig_namePrefix(rName, namePrefix string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -319,7 +319,7 @@ resource "aws_kms_alias" "test" { `, rName, namePrefix) } -func testAccAliasUpdatedKeyIDConfig(rName string) string { +func testAccAliasConfig_updatedKeyID(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -338,7 +338,7 @@ resource "aws_kms_alias" "test" { `, rName) } -func testAccAliasMultipleConfig(rName string) string { +func testAccAliasConfig_multiple(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -357,7 +357,7 @@ resource "aws_kms_alias" "test2" { `, rName) } -func testAccAliasDiffSuppressConfig(rName string) string { +func testAccAliasConfig_diffSuppress(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q diff --git a/internal/service/kms/ciphertext_data_source_test.go b/internal/service/kms/ciphertext_data_source_test.go index 33ad1c5f220..e9cda811f84 100644 --- a/internal/service/kms/ciphertext_data_source_test.go +++ b/internal/service/kms/ciphertext_data_source_test.go @@ -49,7 +49,7 @@ func TestAccKMSCiphertextDataSource_Validate_withContext(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCiphertextDataSourceConfig_validate_withContext, + Config: testAccCiphertextDataSourceConfig_validateContext, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( "data.aws_kms_ciphertext.foo", "ciphertext_blob"), @@ -85,7 +85,7 @@ data "aws_kms_ciphertext" "foo" { } ` -const testAccCiphertextDataSourceConfig_validate_withContext = ` +const testAccCiphertextDataSourceConfig_validateContext = ` resource "aws_kms_key" "foo" { description = "tf-test-acc-data-source-aws-kms-ciphertext-validate-with-context" is_enabled = true diff --git a/internal/service/kms/ciphertext_test.go b/internal/service/kms/ciphertext_test.go index 38a52fb0892..4390189e03c 100644 --- a/internal/service/kms/ciphertext_test.go +++ b/internal/service/kms/ciphertext_test.go @@ -16,7 +16,7 @@ func TestAccKMSCiphertext_Resource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccResourceCiphertextConfig_basic, + Config: testAccCiphertextConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( "aws_kms_ciphertext.foo", "ciphertext_blob"), @@ -37,7 +37,7 @@ func TestAccKMSCiphertext_Resource_validate(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccResourceCiphertextConfig_validate, + Config: testAccCiphertextConfig_validate, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "ciphertext_blob"), resource.TestCheckResourceAttrPair(resourceName, "plaintext", kmsSecretsDataSource, "plaintext.plaintext"), @@ -58,7 +58,7 @@ func TestAccKMSCiphertext_ResourceValidate_withContext(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccResourceCiphertextConfig_validate_withContext, + Config: testAccCiphertextConfig_validateContext, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "ciphertext_blob"), resource.TestCheckResourceAttrPair(resourceName, "plaintext", kmsSecretsDataSource, "plaintext.plaintext"), @@ -68,7 +68,7 @@ func TestAccKMSCiphertext_ResourceValidate_withContext(t *testing.T) { }) } -const testAccResourceCiphertextConfig_basic = ` +const testAccCiphertextConfig_basic = ` resource "aws_kms_key" "foo" { description = "tf-test-acc-data-source-aws-kms-ciphertext-basic" is_enabled = true @@ -81,7 +81,7 @@ resource "aws_kms_ciphertext" "foo" { } ` -const testAccResourceCiphertextConfig_validate = ` +const testAccCiphertextConfig_validate = ` resource "aws_kms_key" "foo" { description = "tf-test-acc-data-source-aws-kms-ciphertext-validate" is_enabled = true @@ -101,7 +101,7 @@ data "aws_kms_secrets" "foo" { } ` -const testAccResourceCiphertextConfig_validate_withContext = ` +const testAccCiphertextConfig_validateContext = ` resource "aws_kms_key" "foo" { description = "tf-test-acc-data-source-aws-kms-ciphertext-validate-with-context" is_enabled = true diff --git a/internal/service/kms/external_key_test.go b/internal/service/kms/external_key_test.go index aabc4dbc5a2..8867505882f 100644 --- a/internal/service/kms/external_key_test.go +++ b/internal/service/kms/external_key_test.go @@ -29,7 +29,7 @@ func TestAccKMSExternalKey_basic(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyConfig(), + Config: testAccExternalKeyConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kms", regexp.MustCompile(`key/.+`)), @@ -71,7 +71,7 @@ func TestAccKMSExternalKey_disappears(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyConfig(), + Config: testAccExternalKeyConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key), acctest.CheckResourceDisappears(acctest.Provider, tfkms.ResourceExternalKey(), resourceName), @@ -94,7 +94,7 @@ func TestAccKMSExternalKey_multiRegion(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyMultiRegionConfig(rName), + Config: testAccExternalKeyConfig_multiRegion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "multi_region", "true"), @@ -126,7 +126,7 @@ func TestAccKMSExternalKey_deletionWindowInDays(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyDeletionWindowInDaysConfig(rName, 8), + Config: testAccExternalKeyConfig_deletionWindowInDays(rName, 8), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key1), resource.TestCheckResourceAttr(resourceName, "deletion_window_in_days", "8"), @@ -143,7 +143,7 @@ func TestAccKMSExternalKey_deletionWindowInDays(t *testing.T) { }, }, { - Config: testAccExternalKeyDeletionWindowInDaysConfig(rName, 7), + Config: testAccExternalKeyConfig_deletionWindowInDays(rName, 7), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key2), testAccCheckExternalKeyNotRecreated(&key1, &key2), @@ -166,7 +166,7 @@ func TestAccKMSExternalKey_description(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyDescriptionConfig(rName + "-1"), + Config: testAccExternalKeyConfig_description(rName + "-1"), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key1), resource.TestCheckResourceAttr(resourceName, "description", rName+"-1"), @@ -183,7 +183,7 @@ func TestAccKMSExternalKey_description(t *testing.T) { }, }, { - Config: testAccExternalKeyDescriptionConfig(rName + "-2"), + Config: testAccExternalKeyConfig_description(rName + "-2"), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key2), testAccCheckExternalKeyNotRecreated(&key1, &key2), @@ -206,7 +206,7 @@ func TestAccKMSExternalKey_enabled(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyEnabledConfig(rName, false), + Config: testAccExternalKeyConfig_enabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key1), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -223,7 +223,7 @@ func TestAccKMSExternalKey_enabled(t *testing.T) { }, }, { - Config: testAccExternalKeyEnabledConfig(rName, true), + Config: testAccExternalKeyConfig_enabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key2), testAccCheckExternalKeyNotRecreated(&key1, &key2), @@ -231,7 +231,7 @@ func TestAccKMSExternalKey_enabled(t *testing.T) { ), }, { - Config: testAccExternalKeyEnabledConfig(rName, false), + Config: testAccExternalKeyConfig_enabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key3), testAccCheckExternalKeyNotRecreated(&key2, &key3), @@ -255,7 +255,7 @@ func TestAccKMSExternalKey_keyMaterialBase64(t *testing.T) { Steps: []resource.TestStep{ { // ACCEPTANCE TESTING ONLY -- NEVER EXPOSE YOUR KEY MATERIAL - Config: testAccExternalKeyKeyMaterialBase64Config(rName, "Wblj06fduthWggmsT0cLVoIMOkeLbc2kVfMud77i/JY="), + Config: testAccExternalKeyConfig_materialBase64(rName, "Wblj06fduthWggmsT0cLVoIMOkeLbc2kVfMud77i/JY="), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key1), resource.TestCheckResourceAttr(resourceName, "key_material_base64", "Wblj06fduthWggmsT0cLVoIMOkeLbc2kVfMud77i/JY="), @@ -273,7 +273,7 @@ func TestAccKMSExternalKey_keyMaterialBase64(t *testing.T) { }, { // ACCEPTANCE TESTING ONLY -- NEVER EXPOSE YOUR KEY MATERIAL - Config: testAccExternalKeyKeyMaterialBase64Config(rName, "O1zsg06cKRCsZnoT5oizMlwHEtnk0HoOmBLkFtwh2Vw="), + Config: testAccExternalKeyConfig_materialBase64(rName, "O1zsg06cKRCsZnoT5oizMlwHEtnk0HoOmBLkFtwh2Vw="), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key2), testAccCheckExternalKeyRecreated(&key1, &key2), @@ -298,7 +298,7 @@ func TestAccKMSExternalKey_policy(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyPolicyConfig(rName, policy1), + Config: testAccExternalKeyConfig_policy(rName, policy1), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key1), testAccCheckExternalKeyHasPolicy(resourceName, policy1), @@ -315,7 +315,7 @@ func TestAccKMSExternalKey_policy(t *testing.T) { }, }, { - Config: testAccExternalKeyPolicyConfig(rName, policy2), + Config: testAccExternalKeyConfig_policy(rName, policy2), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key2), testAccCheckExternalKeyNotRecreated(&key1, &key2), @@ -339,7 +339,7 @@ func TestAccKMSExternalKey_policyBypass(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyPolicyBypassConfig(rName, policy), + Config: testAccExternalKeyConfig_policyBypass(rName, policy), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key), testAccCheckExternalKeyHasPolicy(resourceName, policy), @@ -372,7 +372,7 @@ func TestAccKMSExternalKey_tags(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyTags1Config(rName, "key1", "value1"), + Config: testAccExternalKeyConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -390,7 +390,7 @@ func TestAccKMSExternalKey_tags(t *testing.T) { }, }, { - Config: testAccExternalKeyTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccExternalKeyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key2), testAccCheckExternalKeyNotRecreated(&key1, &key2), @@ -400,7 +400,7 @@ func TestAccKMSExternalKey_tags(t *testing.T) { ), }, { - Config: testAccExternalKeyTags1Config(rName, "key2", "value2"), + Config: testAccExternalKeyConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key3), testAccCheckExternalKeyNotRecreated(&key2, &key3), @@ -426,7 +426,7 @@ func TestAccKMSExternalKey_validTo(t *testing.T) { CheckDestroy: testAccCheckExternalKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccExternalKeyValidToConfig(rName, validTo1), + Config: testAccExternalKeyConfig_validTo(rName, validTo1), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key1), resource.TestCheckResourceAttr(resourceName, "expiration_model", "KEY_MATERIAL_EXPIRES"), @@ -444,7 +444,7 @@ func TestAccKMSExternalKey_validTo(t *testing.T) { }, }, { - Config: testAccExternalKeyEnabledConfig(rName, true), + Config: testAccExternalKeyConfig_enabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key2), testAccCheckExternalKeyNotRecreated(&key1, &key2), @@ -453,7 +453,7 @@ func TestAccKMSExternalKey_validTo(t *testing.T) { ), }, { - Config: testAccExternalKeyValidToConfig(rName, validTo1), + Config: testAccExternalKeyConfig_validTo(rName, validTo1), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key3), testAccCheckExternalKeyNotRecreated(&key2, &key3), @@ -462,7 +462,7 @@ func TestAccKMSExternalKey_validTo(t *testing.T) { ), }, { - Config: testAccExternalKeyValidToConfig(rName, validTo2), + Config: testAccExternalKeyConfig_validTo(rName, validTo2), Check: resource.ComposeTestCheckFunc( testAccCheckExternalKeyExists(resourceName, &key4), testAccCheckExternalKeyNotRecreated(&key3, &key4), @@ -579,13 +579,13 @@ func testAccCheckExternalKeyRecreated(i, j *kms.KeyMetadata) resource.TestCheckF } } -func testAccExternalKeyConfig() string { +func testAccExternalKeyConfig_basic() string { return ` resource "aws_kms_external_key" "test" {} ` } -func testAccExternalKeyMultiRegionConfig(rName string) string { +func testAccExternalKeyConfig_multiRegion(rName string) string { return fmt.Sprintf(` resource "aws_kms_external_key" "test" { description = %[1]q @@ -596,7 +596,7 @@ resource "aws_kms_external_key" "test" { `, rName) } -func testAccExternalKeyDeletionWindowInDaysConfig(rName string, deletionWindowInDays int) string { +func testAccExternalKeyConfig_deletionWindowInDays(rName string, deletionWindowInDays int) string { return fmt.Sprintf(` resource "aws_kms_external_key" "test" { description = %[1]q @@ -605,7 +605,7 @@ resource "aws_kms_external_key" "test" { `, rName, deletionWindowInDays) } -func testAccExternalKeyDescriptionConfig(rName string) string { +func testAccExternalKeyConfig_description(rName string) string { return fmt.Sprintf(` resource "aws_kms_external_key" "test" { description = %[1]q @@ -614,7 +614,7 @@ resource "aws_kms_external_key" "test" { `, rName) } -func testAccExternalKeyEnabledConfig(rName string, enabled bool) string { +func testAccExternalKeyConfig_enabled(rName string, enabled bool) string { return fmt.Sprintf(` # ACCEPTANCE TESTING ONLY -- NEVER EXPOSE YOUR KEY MATERIAL resource "aws_kms_external_key" "test" { @@ -626,7 +626,7 @@ resource "aws_kms_external_key" "test" { `, rName, enabled) } -func testAccExternalKeyKeyMaterialBase64Config(rName, keyMaterialBase64 string) string { +func testAccExternalKeyConfig_materialBase64(rName, keyMaterialBase64 string) string { return fmt.Sprintf(` resource "aws_kms_external_key" "test" { description = %[1]q @@ -636,7 +636,7 @@ resource "aws_kms_external_key" "test" { `, rName, keyMaterialBase64) } -func testAccExternalKeyPolicyConfig(rName, policy string) string { +func testAccExternalKeyConfig_policy(rName, policy string) string { return fmt.Sprintf(` resource "aws_kms_external_key" "test" { description = %[1]q @@ -647,7 +647,7 @@ resource "aws_kms_external_key" "test" { `, rName, policy) } -func testAccExternalKeyPolicyBypassConfig(rName, policy string) string { +func testAccExternalKeyConfig_policyBypass(rName, policy string) string { return fmt.Sprintf(` resource "aws_kms_external_key" "test" { description = %[1]q @@ -660,7 +660,7 @@ resource "aws_kms_external_key" "test" { `, rName, policy) } -func testAccExternalKeyTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccExternalKeyConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_kms_external_key" "test" { description = %[1]q @@ -673,7 +673,7 @@ resource "aws_kms_external_key" "test" { `, rName, tagKey1, tagValue1) } -func testAccExternalKeyTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccExternalKeyConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_kms_external_key" "test" { description = %[1]q @@ -687,7 +687,7 @@ resource "aws_kms_external_key" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccExternalKeyValidToConfig(rName, validTo string) string { +func testAccExternalKeyConfig_validTo(rName, validTo string) string { return fmt.Sprintf(` # ACCEPTANCE TESTING ONLY -- NEVER EXPOSE YOUR KEY MATERIAL resource "aws_kms_external_key" "test" { diff --git a/internal/service/kms/grant_test.go b/internal/service/kms/grant_test.go index 7b73c092f78..e4f837fe071 100644 --- a/internal/service/kms/grant_test.go +++ b/internal/service/kms/grant_test.go @@ -25,7 +25,7 @@ func TestAccKMSGrant_basic(t *testing.T) { CheckDestroy: testAccCheckGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccGrant_Basic(rName, "\"Encrypt\", \"Decrypt\""), + Config: testAccGrantConfig_basic(rName, "\"Encrypt\", \"Decrypt\""), Check: resource.ComposeTestCheckFunc( testAccCheckGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -57,7 +57,7 @@ func TestAccKMSGrant_withConstraints(t *testing.T) { CheckDestroy: testAccCheckGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccGrant_withConstraints(rName, "encryption_context_equals", `foo = "bar" + Config: testAccGrantConfig_constraints(rName, "encryption_context_equals", `foo = "bar" baz = "kaz"`), Check: resource.ComposeTestCheckFunc( testAccCheckGrantExists(resourceName), @@ -77,7 +77,7 @@ func TestAccKMSGrant_withConstraints(t *testing.T) { ImportStateVerifyIgnore: []string{"grant_token", "retire_on_delete"}, }, { - Config: testAccGrant_withConstraints(rName, "encryption_context_subset", `foo = "bar" + Config: testAccGrantConfig_constraints(rName, "encryption_context_subset", `foo = "bar" baz = "kaz"`), Check: resource.ComposeTestCheckFunc( testAccCheckGrantExists(resourceName), @@ -105,7 +105,7 @@ func TestAccKMSGrant_withRetiringPrincipal(t *testing.T) { CheckDestroy: testAccCheckGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccGrant_withRetiringPrincipal(rName), + Config: testAccGrantConfig_retiringPrincipal(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGrantExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "retiring_principal"), @@ -132,7 +132,7 @@ func TestAccKMSGrant_bare(t *testing.T) { CheckDestroy: testAccCheckGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccGrant_bare(rName), + Config: testAccGrantConfig_bare(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGrantExists(resourceName), resource.TestCheckNoResourceAttr(resourceName, "name"), @@ -161,7 +161,7 @@ func TestAccKMSGrant_arn(t *testing.T) { CheckDestroy: testAccCheckGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccGrant_ARN(rName, "\"Encrypt\", \"Decrypt\""), + Config: testAccGrantConfig_arn(rName, "\"Encrypt\", \"Decrypt\""), Check: resource.ComposeTestCheckFunc( testAccCheckGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -193,7 +193,7 @@ func TestAccKMSGrant_asymmetricKey(t *testing.T) { CheckDestroy: testAccCheckGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccGrant_AsymmetricKey(rName), + Config: testAccGrantConfig_asymmetricKey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGrantExists(resourceName), ), @@ -219,7 +219,7 @@ func TestAccKMSGrant_disappears(t *testing.T) { CheckDestroy: testAccCheckGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccGrant_Basic(rName, "\"Encrypt\", \"Decrypt\""), + Config: testAccGrantConfig_basic(rName, "\"Encrypt\", \"Decrypt\""), Check: resource.ComposeTestCheckFunc( testAccCheckGrantExists(resourceName), testAccCheckGrantDisappears(resourceName), @@ -302,7 +302,7 @@ resource "aws_iam_role" "test" { `, rName) } -func testAccGrant_Basic(rName string, operations string) string { +func testAccGrantConfig_basic(rName string, operations string) string { return acctest.ConfigCompose(testAccGrantBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_grant" "test" { name = %[1]q @@ -313,7 +313,7 @@ resource "aws_kms_grant" "test" { `, rName, operations)) } -func testAccGrant_withConstraints(rName string, constraintName string, encryptionContext string) string { +func testAccGrantConfig_constraints(rName string, constraintName string, encryptionContext string) string { return acctest.ConfigCompose(testAccGrantBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_grant" "test" { name = %[1]q @@ -330,7 +330,7 @@ resource "aws_kms_grant" "test" { `, rName, constraintName, encryptionContext)) } -func testAccGrant_withRetiringPrincipal(rName string) string { +func testAccGrantConfig_retiringPrincipal(rName string) string { return acctest.ConfigCompose(testAccGrantBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_grant" "test" { name = %[1]q @@ -342,7 +342,7 @@ resource "aws_kms_grant" "test" { `, rName)) } -func testAccGrant_bare(rName string) string { +func testAccGrantConfig_bare(rName string) string { return acctest.ConfigCompose(testAccGrantBaseConfig(rName), ` resource "aws_kms_grant" "test" { key_id = aws_kms_key.test.key_id @@ -352,7 +352,7 @@ resource "aws_kms_grant" "test" { `) } -func testAccGrant_ARN(rName string, operations string) string { +func testAccGrantConfig_arn(rName string, operations string) string { return acctest.ConfigCompose(testAccGrantBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_grant" "test" { name = %[1]q @@ -363,7 +363,7 @@ resource "aws_kms_grant" "test" { `, rName, operations)) } -func testAccGrant_AsymmetricKey(rName string) string { +func testAccGrantConfig_asymmetricKey(rName string) string { return fmt.Sprintf(` resource "aws_kms_grant" "test" { name = %[1]q diff --git a/internal/service/kms/key_data_source_test.go b/internal/service/kms/key_data_source_test.go index b8695a15d30..af78c5f1f10 100644 --- a/internal/service/kms/key_data_source_test.go +++ b/internal/service/kms/key_data_source_test.go @@ -21,7 +21,7 @@ func TestAccKMSKeyDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccKeyDataSourceConfig(rName), + Config: testAccKeyDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), acctest.CheckResourceAttrAccountID(dataSourceName, "aws_account_id"), @@ -55,7 +55,7 @@ func TestAccKMSKeyDataSource_grantToken(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccKeyDataSourceGrantTokenConfig(rName), + Config: testAccKeyDataSourceConfig_grantToken(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), acctest.CheckResourceAttrAccountID(dataSourceName, "aws_account_id"), @@ -89,7 +89,7 @@ func TestAccKMSKeyDataSource_multiRegionConfiguration(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccKeyDataSourceMultiRegionConfig(rName), + Config: testAccKeyDataSourceConfig_multiRegion(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), acctest.CheckResourceAttrAccountID(dataSourceName, "aws_account_id"), @@ -117,7 +117,7 @@ func TestAccKMSKeyDataSource_multiRegionConfiguration(t *testing.T) { }) } -func testAccKeyDataSourceConfig(rName string) string { +func testAccKeyDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -130,7 +130,7 @@ data "aws_kms_key" "test" { `, rName) } -func testAccKeyDataSourceGrantTokenConfig(rName string) string { +func testAccKeyDataSourceConfig_grantToken(rName string) string { return acctest.ConfigCompose(testAccGrantBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_grant" "test" { name = %[1]q @@ -146,7 +146,7 @@ data "aws_kms_key" "test" { `, rName)) } -func testAccKeyDataSourceMultiRegionConfig(rName string) string { +func testAccKeyDataSourceConfig_multiRegion(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q diff --git a/internal/service/kms/key_test.go b/internal/service/kms/key_test.go index 1ee909695ae..c4d6a547666 100644 --- a/internal/service/kms/key_test.go +++ b/internal/service/kms/key_test.go @@ -28,7 +28,7 @@ func TestAccKMSKey_basic(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyConfig(), + Config: testAccKeyConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "customer_master_key_spec", "SYMMETRIC_DEFAULT"), @@ -59,7 +59,7 @@ func TestAccKMSKey_disappears(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyNameConfig(rName), + Config: testAccKeyConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), acctest.CheckResourceDisappears(acctest.Provider, tfkms.ResourceKey(), resourceName), @@ -82,7 +82,7 @@ func TestAccKMSKey_multiRegion(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKey_multiRegion(rName), + Config: testAccKeyConfig_multiRegion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "multi_region", "true"), @@ -110,7 +110,7 @@ func TestAccKMSKey_asymmetricKey(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKey_asymmetric(rName), + Config: testAccKeyConfig_asymmetric(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "customer_master_key_spec", "ECC_NIST_P384"), @@ -134,7 +134,7 @@ func TestAccKMSKey_Policy_basic(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKey_policy(rName), + Config: testAccKeyConfig_policy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), testAccCheckKeyHasPolicy(resourceName, expectedPolicyText), @@ -147,7 +147,7 @@ func TestAccKMSKey_Policy_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"deletion_window_in_days", "bypass_policy_lockout_safety_check"}, }, { - Config: testAccKey_removedPolicy(rName), + Config: testAccKeyConfig_removedPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), @@ -168,11 +168,11 @@ func TestAccKMSKey_Policy_bypass(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKey_policyBypass(rName, false), + Config: testAccKeyConfig_policyBypass(rName, false), ExpectError: regexp.MustCompile(`The new key policy will not allow you to update the key policy in the future`), }, { - Config: testAccKey_policyBypass(rName, true), + Config: testAccKeyConfig_policyBypass(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "bypass_policy_lockout_safety_check", "true"), @@ -200,14 +200,14 @@ func TestAccKMSKey_Policy_bypassUpdate(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyNameConfig(rName), + Config: testAccKeyConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "bypass_policy_lockout_safety_check", "false"), ), }, { - Config: testAccKey_policyBypass(rName, true), + Config: testAccKeyConfig_policyBypass(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "bypass_policy_lockout_safety_check", "true"), @@ -229,7 +229,7 @@ func TestAccKMSKey_Policy_iamRole(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyPolicyIAMRoleConfig(rName), + Config: testAccKeyConfig_policyIAMRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), @@ -256,13 +256,13 @@ func TestAccKMSKey_Policy_iamRoleUpdate(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKey_policy(rName), + Config: testAccKeyConfig_policy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), }, { - Config: testAccKeyPolicyIAMRoleConfig(rName), + Config: testAccKeyConfig_policyIAMRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), @@ -284,27 +284,27 @@ func TestAccKMSKey_Policy_iamRoleOrder(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyPolicyIAMMultiRoleConfig(rName), + Config: testAccKeyConfig_policyIAMMultiRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), }, { - Config: testAccKeyPolicyIAMMultiRoleConfig(rName), + Config: testAccKeyConfig_policyIAMMultiRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), PlanOnly: true, }, { - Config: testAccKeyPolicyIAMMultiRoleConfig(rName), + Config: testAccKeyConfig_policyIAMMultiRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), PlanOnly: true, }, { - Config: testAccKeyPolicyIAMMultiRoleConfig(rName), + Config: testAccKeyConfig_policyIAMMultiRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), @@ -327,7 +327,7 @@ func TestAccKMSKey_Policy_iamServiceLinkedRole(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyPolicyIAMServiceLinkedRoleConfig(rName), + Config: testAccKeyConfig_policyIAMServiceLinkedRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), @@ -354,7 +354,7 @@ func TestAccKMSKey_Policy_booleanCondition(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyPolicyBooleanConditionConfig(rName), + Config: testAccKeyConfig_policyBooleanCondition(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), @@ -375,7 +375,7 @@ func TestAccKMSKey_isEnabled(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKey_enabledRotation(rName), + Config: testAccKeyConfig_enabledRotation(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key1), resource.TestCheckResourceAttr(resourceName, "is_enabled", "true"), @@ -389,7 +389,7 @@ func TestAccKMSKey_isEnabled(t *testing.T) { ImportStateVerifyIgnore: []string{"deletion_window_in_days", "bypass_policy_lockout_safety_check"}, }, { - Config: testAccKey_disabled(rName), + Config: testAccKeyConfig_disabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key2), resource.TestCheckResourceAttr(resourceName, "is_enabled", "false"), @@ -397,7 +397,7 @@ func TestAccKMSKey_isEnabled(t *testing.T) { ), }, { - Config: testAccKey_enabled(rName), + Config: testAccKeyConfig_enabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key3), resource.TestCheckResourceAttr(resourceName, "is_enabled", "true"), @@ -420,7 +420,7 @@ func TestAccKMSKey_tags(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeyTags1Config(rName, "key1", "value1"), + Config: testAccKeyConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -434,7 +434,7 @@ func TestAccKMSKey_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"deletion_window_in_days", "bypass_policy_lockout_safety_check"}, }, { - Config: testAccKeyTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccKeyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -443,7 +443,7 @@ func TestAccKMSKey_tags(t *testing.T) { ), }, { - Config: testAccKeyTags1Config(rName, "key2", "value2"), + Config: testAccKeyConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -541,13 +541,13 @@ func testAccCheckKeyExists(name string, key *kms.KeyMetadata) resource.TestCheck } } -func testAccKeyConfig() string { +func testAccKeyConfig_basic() string { return ` resource "aws_kms_key" "test" {} ` } -func testAccKeyNameConfig(rName string) string { +func testAccKeyConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -556,7 +556,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKey_multiRegion(rName string) string { +func testAccKeyConfig_multiRegion(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -568,7 +568,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKey_asymmetric(rName string) string { +func testAccKeyConfig_asymmetric(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -580,7 +580,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKey_policy(rName string) string { +func testAccKeyConfig_policy(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -603,7 +603,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKey_policyBypass(rName string, bypassFlag bool) string { +func testAccKeyConfig_policyBypass(rName string, bypassFlag bool) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -641,7 +641,7 @@ resource "aws_kms_key" "test" { `, rName, bypassFlag) } -func testAccKeyPolicyIAMRoleConfig(rName string) string { +func testAccKeyConfig_policyIAMRole(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -700,7 +700,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKeyPolicyIAMMultiRoleConfig(rName string) string { +func testAccKeyConfig_policyIAMMultiRole(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -825,7 +825,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKeyPolicyIAMServiceLinkedRoleConfig(rName string) string { +func testAccKeyConfig_policyIAMServiceLinkedRole(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -874,7 +874,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKeyPolicyBooleanConditionConfig(rName string) string { +func testAccKeyConfig_policyBooleanCondition(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -926,7 +926,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKey_removedPolicy(rName string) string { +func testAccKeyConfig_removedPolicy(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -935,7 +935,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKey_enabledRotation(rName string) string { +func testAccKeyConfig_enabledRotation(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -945,7 +945,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKey_disabled(rName string) string { +func testAccKeyConfig_disabled(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -956,7 +956,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKey_enabled(rName string) string { +func testAccKeyConfig_enabled(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -967,7 +967,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccKeyTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccKeyConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -979,7 +979,7 @@ resource "aws_kms_key" "test" { `, rName, tagKey1, tagValue1) } -func testAccKeyTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccKeyConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q diff --git a/internal/service/kms/public_key_data_source_test.go b/internal/service/kms/public_key_data_source_test.go index d47d2ce26dc..57afad59cf2 100644 --- a/internal/service/kms/public_key_data_source_test.go +++ b/internal/service/kms/public_key_data_source_test.go @@ -22,7 +22,7 @@ func TestAccKMSPublicKeyDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPublicKeyDataSourceConfig(rName), + Config: testAccPublicKeyDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccPublicKeyCheckDataSource(datasourceName), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), @@ -48,7 +48,7 @@ func TestAccKMSPublicKeyDataSource_encrypt(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPublicKeyEncryptDataSourceConfig(rName), + Config: testAccPublicKeyDataSourceConfig_encrypt(rName), Check: resource.ComposeTestCheckFunc( testAccPublicKeyCheckDataSource(datasourceName), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), @@ -74,7 +74,7 @@ func testAccPublicKeyCheckDataSource(name string) resource.TestCheckFunc { } } -func testAccPublicKeyDataSourceConfig(rName string) string { +func testAccPublicKeyDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -89,7 +89,7 @@ data "aws_kms_public_key" "test" { `, rName) } -func testAccPublicKeyEncryptDataSourceConfig(rName string) string { +func testAccPublicKeyDataSourceConfig_encrypt(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q diff --git a/internal/service/kms/replica_external_key_test.go b/internal/service/kms/replica_external_key_test.go index 8357d1ab142..d324e492ba0 100644 --- a/internal/service/kms/replica_external_key_test.go +++ b/internal/service/kms/replica_external_key_test.go @@ -29,7 +29,7 @@ func TestAccKMSReplicaExternalKey_basic(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaExternalKeyConfig(rName), + Config: testAccReplicaExternalKeyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kms", regexp.MustCompile(`key/.+`)), @@ -80,7 +80,7 @@ func TestAccKMSReplicaExternalKey_descriptionAndEnabled(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaExternalKeyDescriptionAndEnabledConfig(rName1, rName2, false), + Config: testAccReplicaExternalKeyConfig_descriptionAndEnabled(rName1, rName2, false), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "description", rName2), @@ -98,7 +98,7 @@ func TestAccKMSReplicaExternalKey_descriptionAndEnabled(t *testing.T) { }, }, { - Config: testAccReplicaExternalKeyDescriptionAndEnabledConfig(rName1, rName3, true), + Config: testAccReplicaExternalKeyConfig_descriptionAndEnabled(rName1, rName3, true), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "description", rName3), @@ -106,7 +106,7 @@ func TestAccKMSReplicaExternalKey_descriptionAndEnabled(t *testing.T) { ), }, { - Config: testAccReplicaExternalKeyDescriptionAndEnabledConfig(rName1, rName4, false), + Config: testAccReplicaExternalKeyConfig_descriptionAndEnabled(rName1, rName4, false), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "description", rName4), @@ -135,7 +135,7 @@ func TestAccKMSReplicaExternalKey_policy(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaExternalKeyPolicyConfig(rName, policy1, false), + Config: testAccReplicaExternalKeyConfig_policy(rName, policy1, false), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "bypass_policy_lockout_safety_check", "false"), @@ -153,7 +153,7 @@ func TestAccKMSReplicaExternalKey_policy(t *testing.T) { }, }, { - Config: testAccReplicaExternalKeyPolicyConfig(rName, policy2, true), + Config: testAccReplicaExternalKeyConfig_policy(rName, policy2, true), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "bypass_policy_lockout_safety_check", "true"), @@ -180,7 +180,7 @@ func TestAccKMSReplicaExternalKey_tags(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaExternalKeyTags1Config(rName, "key1", "value1"), + Config: testAccReplicaExternalKeyConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -198,7 +198,7 @@ func TestAccKMSReplicaExternalKey_tags(t *testing.T) { }, }, { - Config: testAccReplicaExternalKeyTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccReplicaExternalKeyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -207,7 +207,7 @@ func TestAccKMSReplicaExternalKey_tags(t *testing.T) { ), }, { - Config: testAccReplicaExternalKeyTags1Config(rName, "key2", "value2"), + Config: testAccReplicaExternalKeyConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -218,7 +218,7 @@ func TestAccKMSReplicaExternalKey_tags(t *testing.T) { }) } -func testAccReplicaExternalKeyConfig(rName string) string { +func testAccReplicaExternalKeyConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` # ACCEPTANCE TESTING ONLY -- NEVER EXPOSE YOUR KEY MATERIAL resource "aws_kms_external_key" "test" { @@ -237,7 +237,7 @@ resource "aws_kms_replica_external_key" "test" { `, rName)) } -func testAccReplicaExternalKeyDescriptionAndEnabledConfig(rName, description string, enabled bool) string { +func testAccReplicaExternalKeyConfig_descriptionAndEnabled(rName, description string, enabled bool) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` # ACCEPTANCE TESTING ONLY -- NEVER EXPOSE YOUR KEY MATERIAL resource "aws_kms_external_key" "test" { @@ -264,7 +264,7 @@ resource "aws_kms_replica_external_key" "test" { `, rName, description, enabled)) } -func testAccReplicaExternalKeyPolicyConfig(rName, policy string, bypassLockoutCheck bool) string { +func testAccReplicaExternalKeyConfig_policy(rName, policy string, bypassLockoutCheck bool) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` # ACCEPTANCE TESTING ONLY -- NEVER EXPOSE YOUR KEY MATERIAL resource "aws_kms_external_key" "test" { @@ -295,7 +295,7 @@ resource "aws_kms_replica_external_key" "test" { `, rName, policy, bypassLockoutCheck)) } -func testAccReplicaExternalKeyTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccReplicaExternalKeyConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` # ACCEPTANCE TESTING ONLY -- NEVER EXPOSE YOUR KEY MATERIAL resource "aws_kms_external_key" "test" { @@ -330,7 +330,7 @@ resource "aws_kms_replica_external_key" "test" { `, rName, tagKey1, tagValue1)) } -func testAccReplicaExternalKeyTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccReplicaExternalKeyConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` # ACCEPTANCE TESTING ONLY -- NEVER EXPOSE YOUR KEY MATERIAL resource "aws_kms_external_key" "test" { diff --git a/internal/service/kms/replica_key_test.go b/internal/service/kms/replica_key_test.go index b8bf3edbf90..0ebf50c14f8 100644 --- a/internal/service/kms/replica_key_test.go +++ b/internal/service/kms/replica_key_test.go @@ -30,7 +30,7 @@ func TestAccKMSReplicaKey_basic(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaKeyConfig(rName), + Config: testAccReplicaKeyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "kms", regexp.MustCompile(`key/.+`)), @@ -71,7 +71,7 @@ func TestAccKMSReplicaKey_disappears(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaKeyConfig(rName), + Config: testAccReplicaKeyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), acctest.CheckResourceDisappears(acctest.Provider, tfkms.ResourceReplicaKey(), resourceName), @@ -101,7 +101,7 @@ func TestAccKMSReplicaKey_descriptionAndEnabled(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaKeyDescriptionAndEnabledConfig(rName1, rName2, false), + Config: testAccReplicaKeyConfig_descriptionAndEnabled(rName1, rName2, false), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "description", rName2), @@ -115,7 +115,7 @@ func TestAccKMSReplicaKey_descriptionAndEnabled(t *testing.T) { ImportStateVerifyIgnore: []string{"deletion_window_in_days", "bypass_policy_lockout_safety_check"}, }, { - Config: testAccReplicaKeyDescriptionAndEnabledConfig(rName1, rName3, true), + Config: testAccReplicaKeyConfig_descriptionAndEnabled(rName1, rName3, true), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "description", rName3), @@ -123,7 +123,7 @@ func TestAccKMSReplicaKey_descriptionAndEnabled(t *testing.T) { ), }, { - Config: testAccReplicaKeyDescriptionAndEnabledConfig(rName1, rName4, false), + Config: testAccReplicaKeyConfig_descriptionAndEnabled(rName1, rName4, false), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "description", rName4), @@ -152,7 +152,7 @@ func TestAccKMSReplicaKey_policy(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaKeyPolicyConfig(rName, policy1, false), + Config: testAccReplicaKeyConfig_policy(rName, policy1, false), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "bypass_policy_lockout_safety_check", "false"), @@ -166,7 +166,7 @@ func TestAccKMSReplicaKey_policy(t *testing.T) { ImportStateVerifyIgnore: []string{"deletion_window_in_days", "bypass_policy_lockout_safety_check"}, }, { - Config: testAccReplicaKeyPolicyConfig(rName, policy2, true), + Config: testAccReplicaKeyConfig_policy(rName, policy2, true), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "bypass_policy_lockout_safety_check", "true"), @@ -193,7 +193,7 @@ func TestAccKMSReplicaKey_tags(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaKeyTags1Config(rName, "key1", "value1"), + Config: testAccReplicaKeyConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -207,7 +207,7 @@ func TestAccKMSReplicaKey_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"deletion_window_in_days", "bypass_policy_lockout_safety_check"}, }, { - Config: testAccReplicaKeyTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccReplicaKeyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -216,7 +216,7 @@ func TestAccKMSReplicaKey_tags(t *testing.T) { ), }, { - Config: testAccReplicaKeyTags1Config(rName, "key2", "value2"), + Config: testAccReplicaKeyConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -243,7 +243,7 @@ func TestAccKMSReplicaKey_twoReplicas(t *testing.T) { CheckDestroy: testAccCheckKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccReplicaKeyTwoReplicasConfig(rName), + Config: testAccReplicaKeyConfig_two(rName), Check: resource.ComposeTestCheckFunc( testAccCheckKeyExists(resourceName, &key), ), @@ -252,7 +252,7 @@ func TestAccKMSReplicaKey_twoReplicas(t *testing.T) { }) } -func testAccReplicaKeyConfig(rName string) string { +func testAccReplicaKeyConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` resource "aws_kms_key" "test" { provider = awsalternate @@ -267,7 +267,7 @@ resource "aws_kms_replica_key" "test" { `, rName)) } -func testAccReplicaKeyDescriptionAndEnabledConfig(rName, description string, enabled bool) string { +func testAccReplicaKeyConfig_descriptionAndEnabled(rName, description string, enabled bool) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` resource "aws_kms_key" "test" { provider = awsalternate @@ -288,7 +288,7 @@ resource "aws_kms_replica_key" "test" { `, rName, description, enabled)) } -func testAccReplicaKeyPolicyConfig(rName, policy string, bypassLockoutCheck bool) string { +func testAccReplicaKeyConfig_policy(rName, policy string, bypassLockoutCheck bool) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` resource "aws_kms_key" "test" { provider = awsalternate @@ -312,7 +312,7 @@ resource "aws_kms_replica_key" "test" { `, rName, policy, bypassLockoutCheck)) } -func testAccReplicaKeyTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccReplicaKeyConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` resource "aws_kms_key" "test" { provider = awsalternate @@ -340,7 +340,7 @@ resource "aws_kms_replica_key" "test" { `, rName, tagKey1, tagValue1)) } -func testAccReplicaKeyTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccReplicaKeyConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` resource "aws_kms_key" "test" { provider = awsalternate @@ -369,7 +369,7 @@ resource "aws_kms_replica_key" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccReplicaKeyTwoReplicasConfig(rName string) string { +func testAccReplicaKeyConfig_two(rName string) string { return acctest.ConfigCompose(acctest.ConfigMultipleRegionProvider(3), fmt.Sprintf(` resource "aws_kms_key" "test" { provider = awsalternate diff --git a/internal/service/kms/secret_data_source_test.go b/internal/service/kms/secret_data_source_test.go index 8eb5a183dd4..552695fc40f 100644 --- a/internal/service/kms/secret_data_source_test.go +++ b/internal/service/kms/secret_data_source_test.go @@ -17,14 +17,14 @@ func TestAccKMSSecretDataSource_removed(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecretDataSourceConfig, + Config: testAccSecretDataSourceConfig_basic, ExpectError: regexp.MustCompile(tfkms.SecretRemovedMessage), }, }, }) } -const testAccSecretDataSourceConfig = ` +const testAccSecretDataSourceConfig_basic = ` data "aws_kms_secret" "testing" { secret { name = "secret_name" diff --git a/internal/service/kms/secrets_data_source_test.go b/internal/service/kms/secrets_data_source_test.go index 0b022908467..54093632480 100644 --- a/internal/service/kms/secrets_data_source_test.go +++ b/internal/service/kms/secrets_data_source_test.go @@ -72,7 +72,7 @@ func testAccSecretsDecryptDataSource(t *testing.T, plaintext string, encryptedPa ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckSecretsSecretDataSource(*encryptedPayload), + Config: testAccSecretsDataSourceConfig_secret(*encryptedPayload), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "plaintext.%", "1"), resource.TestCheckResourceAttr(dataSourceName, "plaintext.secret1", plaintext), @@ -92,7 +92,7 @@ resource "aws_kms_key" "test" { } ` -func testAccCheckSecretsSecretDataSource(payload string) string { +func testAccSecretsDataSourceConfig_secret(payload string) string { return testAccSecretsDataSourceConfig_key + fmt.Sprintf(` data "aws_kms_secrets" "test" { secret { diff --git a/internal/service/lakeformation/filter.go b/internal/service/lakeformation/filter.go index d2c60486dc8..d37dcc0dced 100644 --- a/internal/service/lakeformation/filter.go +++ b/internal/service/lakeformation/filter.go @@ -31,6 +31,14 @@ func FilterPermissions(input *lakeformation.ListPermissionsInput, tableType stri return FilterDatabasePermissions(input.Principal.DataLakePrincipalIdentifier, allPermissions) } + if input.Resource.LFTag != nil { + return FilterLFTagPermissions(input.Principal.DataLakePrincipalIdentifier, allPermissions) + } + + if input.Resource.LFTagPolicy != nil { + return FilterLFTagPolicyPermissions(input.Principal.DataLakePrincipalIdentifier, allPermissions) + } + if tableType == TableTypeTableWithColumns { return FilterTableWithColumnsPermissions(input.Principal.DataLakePrincipalIdentifier, input.Resource.Table, columnNames, excludedColumnNames, columnWildcard, allPermissions) } @@ -176,3 +184,35 @@ func FilterDatabasePermissions(principal *string, allPermissions []*lakeformatio return cleanPermissions } + +func FilterLFTagPermissions(principal *string, allPermissions []*lakeformation.PrincipalResourcePermissions) []*lakeformation.PrincipalResourcePermissions { + var cleanPermissions []*lakeformation.PrincipalResourcePermissions + + for _, perm := range allPermissions { + if aws.StringValue(principal) != aws.StringValue(perm.Principal.DataLakePrincipalIdentifier) { + continue + } + + if perm.Resource.LFTag != nil { + cleanPermissions = append(cleanPermissions, perm) + } + } + + return cleanPermissions +} + +func FilterLFTagPolicyPermissions(principal *string, allPermissions []*lakeformation.PrincipalResourcePermissions) []*lakeformation.PrincipalResourcePermissions { + var cleanPermissions []*lakeformation.PrincipalResourcePermissions + + for _, perm := range allPermissions { + if aws.StringValue(principal) != aws.StringValue(perm.Principal.DataLakePrincipalIdentifier) { + continue + } + + if perm.Resource.LFTagPolicy != nil { + cleanPermissions = append(cleanPermissions, perm) + } + } + + return cleanPermissions +} diff --git a/internal/service/lakeformation/lakeformation_test.go b/internal/service/lakeformation/lakeformation_test.go index a705abdac44..aa690a1fe20 100644 --- a/internal/service/lakeformation/lakeformation_test.go +++ b/internal/service/lakeformation/lakeformation_test.go @@ -19,11 +19,15 @@ func TestAccLakeFormation_serial(t *testing.T) { "databaseMultiple": testAccPermissions_databaseMultiple, "dataLocation": testAccPermissions_dataLocation, "disappears": testAccPermissions_disappears, + "lfTag": testAccPermissions_lfTag, + "lfTagPolicy": testAccPermissions_lfTagPolicy, }, "PermissionsDataSource": { "basic": testAccPermissionsDataSource_basic, "database": testAccPermissionsDataSource_database, "dataLocation": testAccPermissionsDataSource_dataLocation, + "lfTag": testAccPermissionsDataSource_lfTag, + "lfTagPolicy": testAccPermissionsDataSource_lfTagPolicy, "table": testAccPermissionsDataSource_table, "tableWithColumns": testAccPermissionsDataSource_tableWithColumns, }, @@ -45,6 +49,11 @@ func TestAccLakeFormation_serial(t *testing.T) { "wildcardSelectOnly": testAccPermissions_twcWildcardSelectOnly, "wildcardSelectPlus": testAccPermissions_twcWildcardSelectPlus, }, + "LFTags": { + "basic": testAccLFTag_basic, + "disappears": testAccLFTag_disappears, + "values": testAccLFTag_values, + }, } for group, m := range testCases { diff --git a/internal/service/lakeformation/lf_tag.go b/internal/service/lakeformation/lf_tag.go new file mode 100644 index 00000000000..69ec68a97ef --- /dev/null +++ b/internal/service/lakeformation/lf_tag.go @@ -0,0 +1,187 @@ +package lakeformation + +import ( + "fmt" + "log" + "regexp" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/lakeformation" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" +) + +func ResourceLFTag() *schema.Resource { + return &schema.Resource{ + Create: resourceLFTagCreate, + Read: resourceLFTagRead, + Update: resourceLFTagUpdate, + Delete: resourceLFTagDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "catalog_id": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + Computed: true, + }, + "key": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "values": { + Type: schema.TypeSet, + Required: true, + MinItems: 1, + MaxItems: 15, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateLFTagValues(), + }, + Set: schema.HashString, + }, + }, + } +} + +func resourceLFTagCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LakeFormationConn + + tagKey := d.Get("key").(string) + tagValues := d.Get("values").(*schema.Set) + + var catalogID string + if v, ok := d.GetOk("catalog_id"); ok { + catalogID = v.(string) + } else { + catalogID = meta.(*conns.AWSClient).AccountID + } + + input := &lakeformation.CreateLFTagInput{ + CatalogId: aws.String(catalogID), + TagKey: aws.String(tagKey), + TagValues: flex.ExpandStringSet(tagValues), + } + + _, err := conn.CreateLFTag(input) + if err != nil { + return fmt.Errorf("error creating Lake Formation LF-Tag: %w", err) + } + + d.SetId(fmt.Sprintf("%s:%s", catalogID, tagKey)) + + return resourceLFTagRead(d, meta) +} + +func resourceLFTagRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LakeFormationConn + + catalogID, tagKey, err := ReadLFTagID(d.Id()) + if err != nil { + return err + } + + input := &lakeformation.GetLFTagInput{ + CatalogId: aws.String(catalogID), + TagKey: aws.String(tagKey), + } + + output, err := conn.GetLFTag(input) + if !d.IsNewResource() { + if tfawserr.ErrCodeEquals(err, lakeformation.ErrCodeEntityNotFoundException) { + log.Printf("[WARN] Lake Formation LF-Tag (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + } + + if err != nil { + return fmt.Errorf("error reading Lake Formation LF-Tag: %s", err.Error()) + } + + d.Set("key", output.TagKey) + d.Set("values", flex.FlattenStringSet(output.TagValues)) + d.Set("catalog_id", output.CatalogId) + + return nil +} + +func resourceLFTagUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LakeFormationConn + + catalogID, tagKey, err := ReadLFTagID(d.Id()) + if err != nil { + return err + } + + o, n := d.GetChange("values") + os := o.(*schema.Set) + ns := n.(*schema.Set) + toAdd := flex.ExpandStringSet(ns.Difference(os)) + toDelete := flex.ExpandStringSet(os.Difference(ns)) + + input := &lakeformation.UpdateLFTagInput{ + CatalogId: aws.String(catalogID), + TagKey: aws.String(tagKey), + } + + if len(toAdd) > 0 { + input.TagValuesToAdd = toAdd + } + + if len(toDelete) > 0 { + input.TagValuesToDelete = toDelete + } + + _, err = conn.UpdateLFTag(input) + if err != nil { + return fmt.Errorf("error updating Lake Formation LF-Tag (%s): %w", d.Id(), err) + } + + return resourceLFTagRead(d, meta) +} + +func resourceLFTagDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LakeFormationConn + + catalogID, tagKey, err := ReadLFTagID(d.Id()) + if err != nil { + return err + } + + input := &lakeformation.DeleteLFTagInput{ + CatalogId: aws.String(catalogID), + TagKey: aws.String(tagKey), + } + + _, err = conn.DeleteLFTag(input) + if err != nil { + return fmt.Errorf("error deleting Lake Formation LF-Tag (%s): %w", d.Id(), err) + } + + return nil +} + +func ReadLFTagID(id string) (catalogID string, tagKey string, err error) { + idParts := strings.Split(id, ":") + if len(idParts) != 2 { + return "", "", fmt.Errorf("unexpected format of ID (%q), expected CATALOG-ID:TAG-KEY", id) + } + return idParts[0], idParts[1], nil +} + +func validateLFTagValues() schema.SchemaValidateFunc { + return validation.All( + validation.StringLenBetween(1, 255), + validation.StringMatch(regexp.MustCompile(`^([\p{L}\p{Z}\p{N}_.:\*\/=+\-@%]*)$`), ""), + ) +} diff --git a/internal/service/lakeformation/lf_tag_test.go b/internal/service/lakeformation/lf_tag_test.go new file mode 100644 index 00000000000..8d93a2dca95 --- /dev/null +++ b/internal/service/lakeformation/lf_tag_test.go @@ -0,0 +1,221 @@ +package lakeformation_test + +import ( + "fmt" + "strconv" + "strings" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/lakeformation" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tflakeformation "github.com/hashicorp/terraform-provider-aws/internal/service/lakeformation" +) + +func testAccLFTag_basic(t *testing.T) { + resourceName := "aws_lakeformation_lf_tag.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(lakeformation.EndpointsID, t) }, + ErrorCheck: acctest.ErrorCheck(t, lakeformation.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLFTagsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLFTagConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckLFTagExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "key", rName), + resource.TestCheckResourceAttr(resourceName, "values.0", "value"), + acctest.CheckResourceAttrAccountID(resourceName, "catalog_id"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccLFTag_disappears(t *testing.T) { + resourceName := "aws_lakeformation_lf_tag.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(lakeformation.EndpointsID, t) }, + ErrorCheck: acctest.ErrorCheck(t, lakeformation.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLFTagsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLFTagConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckLFTagExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tflakeformation.ResourceLFTag(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccLFTag_values(t *testing.T) { + resourceName := "aws_lakeformation_lf_tag.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(lakeformation.EndpointsID, t) }, + ErrorCheck: acctest.ErrorCheck(t, lakeformation.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckLFTagsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccLFTagConfig_values(rName, []string{"value1", "value2"}), + Destroy: false, + Check: resource.ComposeTestCheckFunc( + testAccCheckLFTagExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "key", rName), + resource.TestCheckResourceAttr(resourceName, "values.0", "value1"), + acctest.CheckResourceAttrAccountID(resourceName, "catalog_id"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + // Test an update that adds, removes and retains a tag value + Config: testAccLFTagConfig_values(rName, []string{"value1", "value3"}), + Check: resource.ComposeTestCheckFunc( + testAccCheckLFTagExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "key", rName), + resource.TestCheckResourceAttr(resourceName, "values.0", "value1"), + resource.TestCheckResourceAttr(resourceName, "values.1", "value3"), + acctest.CheckResourceAttrAccountID(resourceName, "catalog_id"), + ), + }, + }, + }) +} + +func testAccCheckLFTagsDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).LakeFormationConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_lakeformation_lf_tag" { + continue + } + + catalogID, tagKey, err := tflakeformation.ReadLFTagID(rs.Primary.ID) + if err != nil { + return err + } + + input := &lakeformation.GetLFTagInput{ + CatalogId: aws.String(catalogID), + TagKey: aws.String(tagKey), + } + + if _, err := conn.GetLFTag(input); err != nil { + if tfawserr.ErrCodeEquals(err, lakeformation.ErrCodeEntityNotFoundException) { + continue + } + // If the lake formation admin has been revoked, there will be access denied instead of entity not found + if tfawserr.ErrCodeEquals(err, lakeformation.ErrCodeAccessDeniedException) { + continue + } + return err + } + return fmt.Errorf("Lake Formation LF-Tag (%s) still exists", rs.Primary.ID) + } + + return nil +} + +func testAccCheckLFTagExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("no ID is set") + } + + catalogID, tagKey, err := tflakeformation.ReadLFTagID(rs.Primary.ID) + if err != nil { + return err + } + + input := &lakeformation.GetLFTagInput{ + CatalogId: aws.String(catalogID), + TagKey: aws.String(tagKey), + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).LakeFormationConn + _, err = conn.GetLFTag(input) + + if err != nil { + return err + } + + return nil + } +} + +func testAccLFTagConfig_basic(rName string) string { + return fmt.Sprintf(` +data "aws_caller_identity" "current" {} + +data "aws_iam_session_context" "current" { + arn = data.aws_caller_identity.current.arn +} + +resource "aws_lakeformation_data_lake_settings" "test" { + admins = [data.aws_iam_session_context.current.issuer_arn] +} + +resource "aws_lakeformation_lf_tag" "test" { + key = %[1]q + values = ["value"] + # for consistency, ensure that admins are setup before testing + depends_on = [aws_lakeformation_data_lake_settings.test] +} +`, rName) +} + +func testAccLFTagConfig_values(rName string, values []string) string { + quotedValues := make([]string, len(values)) + for i, v := range values { + quotedValues[i] = strconv.Quote(v) + } + + return fmt.Sprintf(` +data "aws_caller_identity" "current" {} + +data "aws_iam_session_context" "current" { + arn = data.aws_caller_identity.current.arn +} + +resource "aws_lakeformation_data_lake_settings" "test" { + admins = [data.aws_iam_session_context.current.issuer_arn] +} + +resource "aws_lakeformation_lf_tag" "test" { + key = %[1]q + values = [%s] + # for consistency, ensure that admins are setup before testing + depends_on = [aws_lakeformation_data_lake_settings.test] +} +`, rName, strings.Join(quotedValues, ",")) +} diff --git a/internal/service/lakeformation/permissions.go b/internal/service/lakeformation/permissions.go index bafbccbbe97..78f10f73557 100644 --- a/internal/service/lakeformation/permissions.go +++ b/internal/service/lakeformation/permissions.go @@ -4,6 +4,7 @@ import ( "fmt" "log" "reflect" + "sort" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/lakeformation" @@ -40,6 +41,8 @@ func ResourcePermissions() *schema.Resource { "catalog_resource", "data_location", "database", + "lf_tag", + "lf_tag_policy", "table", "table_with_columns", }, @@ -54,6 +57,8 @@ func ResourcePermissions() *schema.Resource { "catalog_resource", "data_location", "database", + "lf_tag", + "lf_tag_policy", "table", "table_with_columns", }, @@ -85,6 +90,8 @@ func ResourcePermissions() *schema.Resource { "catalog_resource", "data_location", "database", + "lf_tag", + "lf_tag_policy", "table", "table_with_columns", }, @@ -105,6 +112,104 @@ func ResourcePermissions() *schema.Resource { }, }, }, + "lf_tag": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + ExactlyOneOf: []string{ + "catalog_resource", + "data_location", + "database", + "lf_tag", + "lf_tag_policy", + "table", + "table_with_columns", + }, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "values": { + Type: schema.TypeSet, + Required: true, + MinItems: 1, + MaxItems: 15, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateLFTagValues(), + }, + Set: schema.HashString, + }, + "catalog_id": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + Computed: true, + }, + }, + }, + }, + "lf_tag_policy": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + ExactlyOneOf: []string{ + "catalog_resource", + "data_location", + "database", + "lf_tag", + "lf_tag_policy", + "table", + "table_with_columns", + }, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "catalog_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: verify.ValidAccountID, + }, + "expression": { + Type: schema.TypeList, + Required: true, + MinItems: 1, + MaxItems: 5, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "values": { + Type: schema.TypeSet, + Required: true, + MinItems: 1, + MaxItems: 15, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateLFTagValues(), + }, + Set: schema.HashString, + }, + }, + }, + }, + "resource_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(lakeformation.ResourceType_Values(), false), + }, + }, + }, + }, "permissions": { Type: schema.TypeList, ForceNew: true, @@ -141,6 +246,8 @@ func ResourcePermissions() *schema.Resource { "catalog_resource", "data_location", "database", + "lf_tag", + "lf_tag_policy", "table", "table_with_columns", }, @@ -191,6 +298,8 @@ func ResourcePermissions() *schema.Resource { "catalog_resource", "data_location", "database", + "lf_tag", + "lf_tag_policy", "table", "table_with_columns", }, @@ -296,6 +405,14 @@ func resourcePermissionsCreate(d *schema.ResourceData, meta interface{}) error { input.Resource.Database = ExpandDatabaseResource(v.([]interface{})[0].(map[string]interface{})) } + if v, ok := d.GetOk("lf_tag"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.Resource.LFTag = ExpandLFTagKeyResource(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("lf_tag_policy"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.Resource.LFTagPolicy = ExpandLFTagPolicyResource(v.([]interface{})[0].(map[string]interface{})) + } + if v, ok := d.GetOk("table"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { input.Resource.Table = ExpandTableResource(v.([]interface{})[0].(map[string]interface{})) } @@ -373,6 +490,14 @@ func resourcePermissionsRead(d *schema.ResourceData, meta interface{}) error { input.Resource.Database = ExpandDatabaseResource(v.([]interface{})[0].(map[string]interface{})) } + if v, ok := d.GetOk("lf_tag"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.Resource.LFTag = ExpandLFTagKeyResource(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("lf_tag_policy"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.Resource.LFTagPolicy = ExpandLFTagPolicyResource(v.([]interface{})[0].(map[string]interface{})) + } + tableType := "" if v, ok := d.GetOk("table"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { @@ -444,6 +569,8 @@ func resourcePermissionsRead(d *schema.ResourceData, meta interface{}) error { d.Set("catalog_resource", false) d.Set("data_location", nil) d.Set("database", nil) + d.Set("lf_tag", nil) + d.Set("lf_tag_policy", nil) d.Set("table_with_columns", nil) d.Set("table", nil) return nil @@ -479,6 +606,22 @@ func resourcePermissionsRead(d *schema.ResourceData, meta interface{}) error { d.Set("database", nil) } + if cleanPermissions[0].Resource.LFTag != nil { + if err := d.Set("lf_tag", []interface{}{flattenLFTagKeyResource(cleanPermissions[0].Resource.LFTag)}); err != nil { + return fmt.Errorf("error setting database: %w", err) + } + } else { + d.Set("lf_tag", nil) + } + + if cleanPermissions[0].Resource.LFTagPolicy != nil { + if err := d.Set("lf_tag_policy", []interface{}{flattenLFTagPolicyResource(cleanPermissions[0].Resource.LFTagPolicy)}); err != nil { + return fmt.Errorf("error setting database: %w", err) + } + } else { + d.Set("lf_tag_policy", nil) + } + tableSet := false if v, ok := d.GetOk("table"); ok && len(v.([]interface{})) > 0 { @@ -560,6 +703,14 @@ func resourcePermissionsDelete(d *schema.ResourceData, meta interface{}) error { input.Resource.Database = ExpandDatabaseResource(v.([]interface{})[0].(map[string]interface{})) } + if v, ok := d.GetOk("lf_tag"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.Resource.LFTag = ExpandLFTagKeyResource(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("lf_tag_policy"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.Resource.LFTagPolicy = ExpandLFTagPolicyResource(v.([]interface{})[0].(map[string]interface{})) + } + if v, ok := d.GetOk("table"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { input.Resource.Table = ExpandTableResource(v.([]interface{})[0].(map[string]interface{})) } @@ -719,6 +870,131 @@ func flattenDatabaseResource(apiObject *lakeformation.DatabaseResource) map[stri return tfMap } +func ExpandLFTagPolicyResource(tfMap map[string]interface{}) *lakeformation.LFTagPolicyResource { + if tfMap == nil { + return nil + } + + apiObject := &lakeformation.LFTagPolicyResource{} + + if v, ok := tfMap["catalog_id"].(string); ok && v != "" { + apiObject.CatalogId = aws.String(v) + } + + if v, ok := tfMap["expression"]; ok && v != nil { + apiObject.Expression = ExpandLFTagExpression(v.([]interface{})) + } + + if v, ok := tfMap["resource_type"].(string); ok && v != "" { + apiObject.ResourceType = aws.String(v) + } + + return apiObject +} + +func ExpandLFTagExpression(expression []interface{}) []*lakeformation.LFTag { + tagSlice := []*lakeformation.LFTag{} + for _, element := range expression { + elementMap := element.(map[string]interface{}) + + tag := &lakeformation.LFTag{ + TagKey: aws.String(elementMap["key"].(string)), + TagValues: flex.ExpandStringSet(elementMap["values"].(*schema.Set)), + } + + tagSlice = append(tagSlice, tag) + } + + return tagSlice +} + +func flattenLFTagPolicyResource(apiObject *lakeformation.LFTagPolicyResource) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.CatalogId; v != nil { + tfMap["catalog_id"] = aws.StringValue(v) + } + + if v := apiObject.Expression; v != nil { + tfMap["expression"] = flattenLFTagExpression(v) + } + + if v := apiObject.ResourceType; v != nil { + tfMap["resource_type"] = aws.StringValue(v) + } + + return tfMap +} + +func flattenLFTagExpression(ts []*lakeformation.LFTag) []map[string]interface{} { + tagSlice := make([]map[string]interface{}, len(ts)) + if len(ts) > 0 { + for i, t := range ts { + tag := make(map[string]interface{}) + + if v := aws.StringValue(t.TagKey); v != "" { + tag["key"] = v + } + + if v := flex.FlattenStringList(t.TagValues); v != nil { + tag["values"] = v + } + + tagSlice[i] = tag + } + } + + return tagSlice +} + +func ExpandLFTagKeyResource(tfMap map[string]interface{}) *lakeformation.LFTagKeyResource { + if tfMap == nil { + return nil + } + + apiObject := &lakeformation.LFTagKeyResource{} + + if v, ok := tfMap["catalog_id"].(string); ok && v != "" { + apiObject.CatalogId = aws.String(v) + } + + if v, ok := tfMap["key"].(string); ok && v != "" { + apiObject.TagKey = aws.String(v) + } + + if v, ok := tfMap["values"].(*schema.Set); ok && v != nil { + apiObject.TagValues = flex.ExpandStringSet(v) + } + + return apiObject +} + +func flattenLFTagKeyResource(apiObject *lakeformation.LFTagKeyResource) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.CatalogId; v != nil { + tfMap["catalog_id"] = aws.StringValue(v) + } + + if v := apiObject.TagKey; v != nil { + tfMap["key"] = aws.StringValue(v) + } + + if v := apiObject.TagValues; v != nil { + tfMap["values"] = flex.FlattenStringSet(v) + } + + return tfMap +} + func ExpandTableResource(tfMap map[string]interface{}) *lakeformation.TableResource { if tfMap == nil { return nil @@ -904,6 +1180,8 @@ func flattenPermissions(apiObjects []*lakeformation.PrincipalResourcePermissions } } + sort.Strings(tfList) + return tfList } @@ -920,5 +1198,7 @@ func flattenGrantPermissions(apiObjects []*lakeformation.PrincipalResourcePermis } } + sort.Strings(tfList) + return tfList } diff --git a/internal/service/lakeformation/permissions_data_source.go b/internal/service/lakeformation/permissions_data_source.go index d769d7ae608..efd8d49edb8 100644 --- a/internal/service/lakeformation/permissions_data_source.go +++ b/internal/service/lakeformation/permissions_data_source.go @@ -84,6 +84,84 @@ func DataSourcePermissions() *schema.Resource { Type: schema.TypeString, }, }, + "lf_tag": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "values": { + Type: schema.TypeSet, + Required: true, + MinItems: 1, + MaxItems: 15, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateLFTagValues(), + }, + Set: schema.HashString, + }, + "catalog_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + }, + }, + "lf_tag_policy": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "catalog_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: verify.ValidAccountID, + }, + "expression": { + Type: schema.TypeList, + Required: true, + MinItems: 1, + MaxItems: 5, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "values": { + Type: schema.TypeSet, + Required: true, + MinItems: 1, + MaxItems: 15, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateLFTagValues(), + }, + Set: schema.HashString, + }, + }, + }, + }, + "resource_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(lakeformation.ResourceType_Values(), false), + }, + }, + }, + }, "principal": { Type: schema.TypeString, Required: true, @@ -195,6 +273,14 @@ func dataSourcePermissionsRead(d *schema.ResourceData, meta interface{}) error { input.Resource.Database = ExpandDatabaseResource(v.([]interface{})[0].(map[string]interface{})) } + if v, ok := d.GetOk("lf_tag"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.Resource.LFTag = ExpandLFTagKeyResource(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("lf_tag_policy"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.Resource.LFTagPolicy = ExpandLFTagPolicyResource(v.([]interface{})[0].(map[string]interface{})) + } + tableType := "" if v, ok := d.GetOk("table"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { @@ -273,6 +359,22 @@ func dataSourcePermissionsRead(d *schema.ResourceData, meta interface{}) error { d.Set("database", nil) } + if cleanPermissions[0].Resource.LFTag != nil { + if err := d.Set("lf_tag", []interface{}{flattenLFTagKeyResource(cleanPermissions[0].Resource.LFTag)}); err != nil { + return fmt.Errorf("error setting LF-tag: %w", err) + } + } else { + d.Set("lf_tag", nil) + } + + if cleanPermissions[0].Resource.LFTagPolicy != nil { + if err := d.Set("lf_tag_policy", []interface{}{flattenLFTagPolicyResource(cleanPermissions[0].Resource.LFTagPolicy)}); err != nil { + return fmt.Errorf("error setting LF-tag policy: %w", err) + } + } else { + d.Set("lf_tag_policy", nil) + } + tableSet := false if v, ok := d.GetOk("table"); ok && len(v.([]interface{})) > 0 { diff --git a/internal/service/lakeformation/permissions_data_source_test.go b/internal/service/lakeformation/permissions_data_source_test.go index 45689abb383..79f8da4e375 100644 --- a/internal/service/lakeformation/permissions_data_source_test.go +++ b/internal/service/lakeformation/permissions_data_source_test.go @@ -88,6 +88,68 @@ func testAccPermissionsDataSource_database(t *testing.T) { }) } +func testAccPermissionsDataSource_lfTag(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lakeformation_permissions.test" + dataSourceName := "data.aws_lakeformation_permissions.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(lakeformation.EndpointsID, t) }, + ErrorCheck: acctest.ErrorCheck(t, lakeformation.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckPermissionsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccPermissionsDataSourceConfig_lfTag(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(resourceName, "principal", dataSourceName, "principal"), + resource.TestCheckResourceAttrPair(resourceName, "lf_tag.#", dataSourceName, "lf_tag.#"), + resource.TestCheckResourceAttrPair(resourceName, "lf_tag.0.key", dataSourceName, "lf_tag.0.key"), + resource.TestCheckResourceAttrPair(resourceName, "lf_tag.0.values", dataSourceName, "lf_tag.0.values"), + resource.TestCheckResourceAttrPair(resourceName, "permissions.#", dataSourceName, "permissions.#"), + resource.TestCheckResourceAttrPair(resourceName, "permissions.0", dataSourceName, "permissions.0"), + resource.TestCheckResourceAttrPair(resourceName, "permissions.1", dataSourceName, "permissions.1"), + resource.TestCheckResourceAttrPair(resourceName, "permissions_with_grant_option.#", dataSourceName, "permissions_with_grant_option.#"), + resource.TestCheckResourceAttrPair(resourceName, "permissions_with_grant_option.0", dataSourceName, "permissions_with_grant_option.0"), + resource.TestCheckResourceAttrPair(resourceName, "permissions_with_grant_option.1", dataSourceName, "permissions_with_grant_option.1"), + ), + }, + }, + }) +} + +func testAccPermissionsDataSource_lfTagPolicy(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lakeformation_permissions.test" + dataSourceName := "data.aws_lakeformation_permissions.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(lakeformation.EndpointsID, t) }, + ErrorCheck: acctest.ErrorCheck(t, lakeformation.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckPermissionsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccPermissionsDataSourceConfig_lfTagPolicy(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(resourceName, "principal", dataSourceName, "principal"), + resource.TestCheckResourceAttrPair(resourceName, "lf_tag_policy.#", dataSourceName, "lf_tag_policy.#"), + resource.TestCheckResourceAttrPair(resourceName, "lf_tag_policy.0.resource_type", dataSourceName, "lf_tag_policy.0.resource_type"), + resource.TestCheckResourceAttrPair(resourceName, "lf_tag_policy.0.expression.#", dataSourceName, "lf_tag_policy.0.expression.#"), + resource.TestCheckResourceAttrPair(resourceName, "lf_tag_policy.0.expression.0.key", dataSourceName, "lf_tag_policy.0.expression.0.key"), + resource.TestCheckResourceAttrPair(resourceName, "lf_tag_policy.0.expression.0.values", dataSourceName, "lf_tag_policy.0.expression.0.values"), + resource.TestCheckResourceAttrPair(resourceName, "permissions.#", dataSourceName, "permissions.#"), + resource.TestCheckResourceAttrPair(resourceName, "permissions.0", dataSourceName, "permissions.0"), + resource.TestCheckResourceAttrPair(resourceName, "permissions.1", dataSourceName, "permissions.1"), + resource.TestCheckResourceAttrPair(resourceName, "permissions.2", dataSourceName, "permissions.2"), + resource.TestCheckResourceAttrPair(resourceName, "permissions_with_grant_option.#", dataSourceName, "permissions_with_grant_option.#"), + resource.TestCheckResourceAttrPair(resourceName, "permissions_with_grant_option.0", dataSourceName, "permissions_with_grant_option.0"), + ), + }, + }, + }) +} + func testAccPermissionsDataSource_table(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_lakeformation_permissions.test" @@ -316,6 +378,149 @@ data "aws_lakeformation_permissions" "test" { `, rName) } +func testAccPermissionsDataSourceConfig_lfTag(rName string) string { + return fmt.Sprintf(` +data "aws_partition" "current" {} +resource "aws_iam_role" "test" { + name = %[1]q + path = "/" + assume_role_policy = < 0 { + input.Tags = Tags(tags.IgnoreAWS()) + } + + _, err := conn.CreateContainerServiceWithContext(ctx, input) + if err != nil { + return diag.Errorf("error creating Lightsail Container Service (%s): %s", serviceName, err) + } + + d.SetId(serviceName) + + if err := waitContainerServiceCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return diag.Errorf("error waiting for Lightsail Container Service (%s) creation: %s", d.Id(), err) + } + + // once container service creation and/or deployment successful (now enabled by default), disable it if "is_disabled" is true + if v, ok := d.GetOk("is_disabled"); ok && v.(bool) { + input := &lightsail.UpdateContainerServiceInput{ + ServiceName: aws.String(d.Id()), + IsDisabled: aws.Bool(true), + } + + _, err := conn.UpdateContainerServiceWithContext(ctx, input) + if err != nil { + return diag.Errorf("error disabling Lightsail Container Service (%s): %s", d.Id(), err) + } + + if err := waitContainerServiceDisabled(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return diag.Errorf("error waiting for Lightsail Container Service (%s) to be disabled: %s", d.Id(), err) + } + } + + return resourceContainerServiceRead(ctx, d, meta) +} + +func resourceContainerServiceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).LightsailConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + cs, err := FindContainerServiceByName(ctx, conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Lightsail Container Service (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return diag.Errorf("error reading Lightsail Container Service (%s): %s", d.Id(), err) + } + + d.Set("name", cs.ContainerServiceName) + d.Set("power", cs.Power) + d.Set("scale", cs.Scale) + d.Set("is_disabled", cs.IsDisabled) + + if err := d.Set("public_domain_names", flattenContainerServicePublicDomainNames(cs.PublicDomainNames)); err != nil { + return diag.Errorf("error setting public_domain_names for Lightsail Container Service (%s): %s", d.Id(), err) + } + d.Set("arn", cs.Arn) + d.Set("availability_zone", cs.Location.AvailabilityZone) + d.Set("created_at", aws.TimeValue(cs.CreatedAt).Format(time.RFC3339)) + d.Set("power_id", cs.PowerId) + d.Set("principal_arn", cs.PrincipalArn) + d.Set("private_domain_name", cs.PrivateDomainName) + d.Set("resource_type", cs.ResourceType) + d.Set("state", cs.State) + d.Set("url", cs.Url) + + tags := KeyValueTags(cs.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return diag.Errorf("error setting tags: %s", err) + } + if err := d.Set("tags_all", tags.Map()); err != nil { + return diag.Errorf("error setting tags_all: %s", err) + } + + return nil +} + +func resourceContainerServiceUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).LightsailConn + + if d.HasChangesExcept("tags", "tags_all") { + publicDomainNames, _ := containerServicePublicDomainNamesChanged(d) + + input := &lightsail.UpdateContainerServiceInput{ + ServiceName: aws.String(d.Id()), + IsDisabled: aws.Bool(d.Get("is_disabled").(bool)), + Power: aws.String(d.Get("power").(string)), + PublicDomainNames: publicDomainNames, + Scale: aws.Int64(int64(d.Get("scale").(int))), + } + + _, err := conn.UpdateContainerServiceWithContext(ctx, input) + if err != nil { + return diag.Errorf("error updating Lightsail Container Service (%s): %s", d.Id(), err) + } + + if d.HasChange("is_disabled") && d.Get("is_disabled").(bool) { + if err := waitContainerServiceDisabled(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return diag.Errorf("error waiting for Lightsail Container Service (%s) update: %s", d.Id(), err) + } + } else { + if err := waitContainerServiceUpdated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return diag.Errorf("error waiting for Lightsail Container Service (%s) update: %s", d.Id(), err) + } + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Id(), o, n); err != nil { + return diag.Errorf("error updating Lightsail Container Service (%s) tags: %s", d.Id(), err) + } + } + + return resourceContainerServiceRead(ctx, d, meta) +} + +func resourceContainerServiceDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).LightsailConn + + input := &lightsail.DeleteContainerServiceInput{ + ServiceName: aws.String(d.Id()), + } + + _, err := conn.DeleteContainerServiceWithContext(ctx, input) + + if tfawserr.ErrCodeEquals(err, lightsail.ErrCodeNotFoundException) { + return nil + } + + if err != nil { + return diag.Errorf("error deleting Lightsail Container Service (%s): %s", d.Id(), err) + } + + if err := waitContainerServiceDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + return diag.Errorf("error waiting for Lightsail Container Service (%s) deletion: %s", d.Id(), err) + } + + return nil +} + +func expandContainerServicePublicDomainNames(rawPublicDomainNames []interface{}) map[string][]*string { + if len(rawPublicDomainNames) == 0 { + return nil + } + + resultMap := make(map[string][]*string) + + for _, rpdn := range rawPublicDomainNames { + rpdnMap := rpdn.(map[string]interface{}) + + rawCertificates := rpdnMap["certificate"].(*schema.Set).List() + + for _, rc := range rawCertificates { + rcMap := rc.(map[string]interface{}) + + var domainNames []*string + for _, rawDomainName := range rcMap["domain_names"].([]interface{}) { + domainNames = append(domainNames, aws.String(rawDomainName.(string))) + } + + certificateName := rcMap["certificate_name"].(string) + + resultMap[certificateName] = domainNames + } + } + + return resultMap +} + +func flattenContainerServicePublicDomainNames(domainNames map[string][]*string) []interface{} { + if domainNames == nil { + return []interface{}{} + } + + var rawCertificates []interface{} + + for certName, domains := range domainNames { + rawCertificate := map[string]interface{}{ + "certificate_name": certName, + "domain_names": aws.StringValueSlice(domains), + } + + rawCertificates = append(rawCertificates, rawCertificate) + } + + return []interface{}{ + map[string]interface{}{ + "certificate": rawCertificates, + }, + } +} + +func containerServicePublicDomainNamesChanged(d *schema.ResourceData) (map[string][]*string, bool) { + o, n := d.GetChange("public_domain_names") + oldPublicDomainNames := expandContainerServicePublicDomainNames(o.([]interface{})) + newPublicDomainNames := expandContainerServicePublicDomainNames(n.([]interface{})) + + changed := !reflect.DeepEqual(oldPublicDomainNames, newPublicDomainNames) + if changed { + if newPublicDomainNames == nil { + newPublicDomainNames = map[string][]*string{} + } + + // if the change is to detach a certificate, in .tf, a certificate block is removed + // however, an empty []*string entry must be added to tell Lightsail that we want none of the domain names + // under the certificate, effectively detaching the certificate + for certificateName := range oldPublicDomainNames { + if _, ok := newPublicDomainNames[certificateName]; !ok { + newPublicDomainNames[certificateName] = []*string{} + } + } + } + + return newPublicDomainNames, changed +} diff --git a/internal/service/lightsail/container_service_deployment_version.go b/internal/service/lightsail/container_service_deployment_version.go new file mode 100644 index 00000000000..e637c67b59d --- /dev/null +++ b/internal/service/lightsail/container_service_deployment_version.go @@ -0,0 +1,390 @@ +package lightsail + +import ( + "context" + "fmt" + "log" + "strconv" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func ResourceContainerServiceDeploymentVersion() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceContainerServiceDeploymentVersionCreate, + ReadContext: resourceContainerServiceDeploymentVersionRead, + DeleteContext: resourceContainerServiceDeploymentVersionDelete, + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "container": { + Type: schema.TypeSet, + Required: true, + ForceNew: true, + MaxItems: 53, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "container_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringIsNotWhiteSpace, + }, + "image": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "command": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "environment": { + Type: schema.TypeMap, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "ports": { + Type: schema.TypeMap, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(lightsail.ContainerServiceProtocol_Values(), false), + }}, + }, + }, + }, + "created_at": { + Type: schema.TypeString, + Computed: true, + }, + "public_endpoint": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "container_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "container_port": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + "health_check": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "healthy_threshold": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 2, + }, + "interval_seconds": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 5, + ValidateFunc: validation.IntBetween(5, 300), + }, + "path": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: "/", + }, + "success_codes": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: "200-499", + }, + "timeout_seconds": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 2, + ValidateFunc: validation.IntBetween(2, 60), + }, + "unhealthy_threshold": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 2, + }, + }, + }, + }, + }, + }, + }, + "service_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "state": { + Type: schema.TypeString, + Computed: true, + }, + "version": { + Type: schema.TypeInt, + Computed: true, + }, + }, + } +} + +func resourceContainerServiceDeploymentVersionCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).LightsailConn + serviceName := d.Get("service_name").(string) + + input := &lightsail.CreateContainerServiceDeploymentInput{ + ServiceName: aws.String(serviceName), + } + + if v, ok := d.GetOk("container"); ok && v.(*schema.Set).Len() > 0 { + input.Containers = expandContainerServiceDeploymentContainers(v.(*schema.Set).List()) + } + + if v, ok := d.GetOk("public_endpoint"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.PublicEndpoint = expandContainerServiceDeploymentPublicEndpoint(v.([]interface{})) + } + + output, err := conn.CreateContainerServiceDeploymentWithContext(ctx, input) + if err != nil { + return diag.Errorf("error creating Lightsail Container Service (%s) Deployment Version: %s", serviceName, err) + } + + if output == nil || output.ContainerService == nil || output.ContainerService.NextDeployment == nil { + return diag.Errorf("error creating Lightsail Container Service (%s) Deployment Version: empty output", serviceName) + } + + version := int(aws.Int64Value(output.ContainerService.NextDeployment.Version)) + + d.SetId(fmt.Sprintf("%s/%d", serviceName, version)) + + if err := waitContainerServiceDeploymentVersionActive(ctx, conn, serviceName, version, d.Timeout(schema.TimeoutCreate)); err != nil { + return diag.Errorf("error waiting for Lightsail Container Service (%s) Deployment Version (%d): %s", serviceName, version, err) + } + + return resourceContainerServiceDeploymentVersionRead(ctx, d, meta) +} + +func resourceContainerServiceDeploymentVersionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := meta.(*conns.AWSClient).LightsailConn + + serviceName, version, err := ContainerServiceDeploymentVersionParseResourceID(d.Id()) + if err != nil { + return diag.FromErr(err) + } + + deployment, err := FindContainerServiceDeploymentByVersion(ctx, conn, serviceName, version) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Lightsail Container Service (%s) Deployment Version (%d) not found, removing from state", serviceName, version) + d.SetId("") + return nil + } + + if err != nil { + return diag.Errorf("error reading Lightsail Container Service (%s) Deployment Version (%d): %s", serviceName, version, err) + } + + d.Set("created_at", aws.TimeValue(deployment.CreatedAt).Format(time.RFC3339)) + d.Set("service_name", serviceName) + d.Set("state", deployment.State) + d.Set("version", deployment.Version) + + if err := d.Set("container", flattenContainerServiceDeploymentContainers(deployment.Containers)); err != nil { + return diag.Errorf("error setting container for Lightsail Container Service (%s) Deployment Version (%d): %s", serviceName, version, err) + } + + if err := d.Set("public_endpoint", flattenContainerServiceDeploymentPublicEndpoint(deployment.PublicEndpoint)); err != nil { + return diag.Errorf("error setting public_endpoint for Lightsail Container Service (%s) Deployment Version (%d): %s", serviceName, version, err) + } + + return nil +} + +func resourceContainerServiceDeploymentVersionDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + log.Printf("[WARN] Cannot destroy Lightsail Container Service Deployment Version. Terraform will remove this resource from the state file, however resources may remain.") + return nil +} + +func ContainerServiceDeploymentVersionParseResourceID(id string) (string, int, error) { + parts := strings.Split(id, "/") + + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", 0, fmt.Errorf("unexpected format for ID (%[1]s), expected SERVICE_NAME/VERSION", id) + } + + version, err := strconv.Atoi(parts[1]) + if err != nil { + return "", 0, err + } + + return parts[0], version, nil +} + +func expandContainerServiceDeploymentContainers(tfList []interface{}) map[string]*lightsail.Container { + if len(tfList) == 0 { + return map[string]*lightsail.Container{} + } + + result := make(map[string]*lightsail.Container) + + for _, tfListRaw := range tfList { + tfMap, ok := tfListRaw.(map[string]interface{}) + if !ok { + continue + } + + containerName := tfMap["container_name"].(string) + + container := &lightsail.Container{ + Image: aws.String(tfMap["image"].(string)), + } + + if v, ok := tfMap["command"].([]interface{}); ok && len(v) > 0 { + container.Command = flex.ExpandStringList(v) + } + + if v, ok := tfMap["environment"].(map[string]interface{}); ok && len(v) > 0 { + container.Environment = flex.ExpandStringMap(v) + } + + if v, ok := tfMap["ports"].(map[string]interface{}); ok && len(v) > 0 { + container.Ports = flex.ExpandStringMap(v) + } + + result[containerName] = container + } + + return result +} + +func expandContainerServiceDeploymentPublicEndpoint(tfList []interface{}) *lightsail.EndpointRequest { + if len(tfList) == 0 || tfList[0] == nil { + return nil + } + + tfMap, ok := tfList[0].(map[string]interface{}) + if !ok { + return nil + } + + endpoint := &lightsail.EndpointRequest{ + ContainerName: aws.String(tfMap["container_name"].(string)), + ContainerPort: aws.Int64(int64(tfMap["container_port"].(int))), + } + + if v, ok := tfMap["health_check"].([]interface{}); ok && len(v) > 0 { + endpoint.HealthCheck = expandContainerServiceDeploymentPublicEndpointHealthCheck(v) + } + + return endpoint +} + +func expandContainerServiceDeploymentPublicEndpointHealthCheck(tfList []interface{}) *lightsail.ContainerServiceHealthCheckConfig { + if len(tfList) == 0 || tfList[0] == nil { + return nil + } + + tfMap, ok := tfList[0].(map[string]interface{}) + if !ok { + return nil + } + + healthCheck := &lightsail.ContainerServiceHealthCheckConfig{ + HealthyThreshold: aws.Int64(int64(tfMap["healthy_threshold"].(int))), + IntervalSeconds: aws.Int64(int64(tfMap["interval_seconds"].(int))), + Path: aws.String(tfMap["path"].(string)), + SuccessCodes: aws.String(tfMap["success_codes"].(string)), + TimeoutSeconds: aws.Int64(int64(tfMap["timeout_seconds"].(int))), + UnhealthyThreshold: aws.Int64(int64(tfMap["unhealthy_threshold"].(int))), + } + + return healthCheck +} + +func flattenContainerServiceDeploymentContainers(containers map[string]*lightsail.Container) []interface{} { + if len(containers) == 0 { + return nil + } + + var rawContainers []interface{} + for containerName, container := range containers { + rawContainer := map[string]interface{}{ + "container_name": containerName, + "image": aws.StringValue(container.Image), + "command": aws.StringValueSlice(container.Command), + "environment": aws.StringValueMap(container.Environment), + "ports": aws.StringValueMap(container.Ports), + } + + rawContainers = append(rawContainers, rawContainer) + } + + return rawContainers +} + +func flattenContainerServiceDeploymentPublicEndpoint(endpoint *lightsail.ContainerServiceEndpoint) []interface{} { + if endpoint == nil { + return []interface{}{} + } + + return []interface{}{ + map[string]interface{}{ + "container_name": aws.StringValue(endpoint.ContainerName), + "container_port": int(aws.Int64Value(endpoint.ContainerPort)), + "health_check": flattenContainerServiceDeploymentPublicEndpointHealthCheck(endpoint.HealthCheck), + }, + } +} + +func flattenContainerServiceDeploymentPublicEndpointHealthCheck(healthCheck *lightsail.ContainerServiceHealthCheckConfig) []interface{} { + if healthCheck == nil { + return []interface{}{} + } + + return []interface{}{ + map[string]interface{}{ + "healthy_threshold": int(aws.Int64Value(healthCheck.HealthyThreshold)), + "interval_seconds": int(aws.Int64Value(healthCheck.IntervalSeconds)), + "path": aws.StringValue(healthCheck.Path), + "success_codes": aws.StringValue(healthCheck.SuccessCodes), + "timeout_seconds": int(aws.Int64Value(healthCheck.TimeoutSeconds)), + "unhealthy_threshold": int(aws.Int64Value(healthCheck.UnhealthyThreshold)), + }, + } +} diff --git a/internal/service/lightsail/container_service_deployment_version_test.go b/internal/service/lightsail/container_service_deployment_version_test.go new file mode 100644 index 00000000000..b35d19cee34 --- /dev/null +++ b/internal/service/lightsail/container_service_deployment_version_test.go @@ -0,0 +1,713 @@ +package lightsail_test + +import ( + "context" + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/lightsail" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tflightsail "github.com/hashicorp/terraform-provider-aws/internal/service/lightsail" +) + +const ( + helloWorldImage = "amazon/amazon-lightsail:hello-world" + redisImage = "redis:latest" +) + +func TestContainerServiceDeploymentVersionParseResourceID(t *testing.T) { + testCases := []struct { + TestName string + Input string + ExpectedServiceName string + ExpectedVersion int + Error bool + }{ + { + TestName: "empty", + Input: "", + ExpectedServiceName: "", + ExpectedVersion: 0, + Error: true, + }, + { + TestName: "Invalid ID", + Input: "abcdefg12345678/", + ExpectedServiceName: "", + ExpectedVersion: 0, + Error: true, + }, + { + TestName: "Invalid ID separator", + Input: "abcdefg12345678:1", + ExpectedServiceName: "", + ExpectedVersion: 0, + Error: true, + }, + { + TestName: "Invalid ID with more than 1 separator", + Input: "abcdefg12345678/qwerty09876/1", + ExpectedServiceName: "", + ExpectedVersion: 0, + Error: true, + }, + { + TestName: "Valid ID", + Input: "abcdefg12345678/1", + ExpectedServiceName: "abcdefg12345678", + ExpectedVersion: 1, + Error: false, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.TestName, func(t *testing.T) { + gotServiceName, gotVersion, err := tflightsail.ContainerServiceDeploymentVersionParseResourceID(testCase.Input) + + if err != nil && !testCase.Error { + t.Errorf("got error (%s), expected no error", err) + } + + if err == nil && testCase.Error { + t.Errorf("got (ServiceName: %s, Version: %d) and no error, expected error", gotServiceName, gotVersion) + } + + if gotServiceName != testCase.ExpectedServiceName { + t.Errorf("got %s, expected %s", gotServiceName, testCase.ExpectedServiceName) + } + + if gotVersion != testCase.ExpectedVersion { + t.Errorf("got %d, expected %d", gotVersion, testCase.ExpectedVersion) + } + }) + } +} + +func TestAccLightsailContainerServiceDeploymentVersion_Container_Basic(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + containerName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service_deployment_version.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_basic(rName, containerName, helloWorldImage), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "created_at"), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "1"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.container_name", containerName), + resource.TestCheckResourceAttr(resourceName, "container.0.image", helloWorldImage), + resource.TestCheckResourceAttr(resourceName, "container.0.command.#", "0"), + resource.TestCheckResourceAttr(resourceName, "container.0.environment.%", "0"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.%", "0"), + resource.TestCheckResourceAttrPair(resourceName, "service_name", "aws_lightsail_container_service.test", "name"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccLightsailContainerServiceDeploymentVersion_Container_Multiple(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + containerName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + containerName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service_deployment_version.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_multiple(rName, containerName1, helloWorldImage, containerName2, redisImage), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "1"), + resource.TestCheckResourceAttr(resourceName, "container.#", "2"), + resource.TestCheckResourceAttr(resourceName, "container.0.container_name", containerName1), + resource.TestCheckResourceAttr(resourceName, "container.0.image", helloWorldImage), + resource.TestCheckResourceAttr(resourceName, "container.1.container_name", containerName2), + resource.TestCheckResourceAttr(resourceName, "container.1.image", redisImage), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccLightsailContainerServiceDeploymentVersion_Container_Environment(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + containerName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service_deployment_version.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_environment1(rName, containerName, "A", "a"), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "1"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.environment.%", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.environment.A", "a"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_environment1(rName, containerName, "B", "b"), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "2"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.environment.%", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.environment.B", "b"), + ), + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_environment2(rName, containerName, "A", "a", "B", "b"), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "3"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.environment.%", "2"), + resource.TestCheckResourceAttr(resourceName, "container.0.environment.A", "a"), + resource.TestCheckResourceAttr(resourceName, "container.0.environment.B", "b"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_basic(rName, containerName, helloWorldImage), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "4"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.environment.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccLightsailContainerServiceDeploymentVersion_Container_Ports(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + containerName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service_deployment_version.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_ports1(rName, containerName, "80", lightsail.ContainerServiceProtocolHttp), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "1"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.%", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.80", lightsail.ContainerServiceProtocolHttp), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_ports1(rName, containerName, "90", lightsail.ContainerServiceProtocolTcp), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "2"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.%", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.90", lightsail.ContainerServiceProtocolTcp), + ), + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_ports2(rName, containerName, "80", lightsail.ContainerServiceProtocolHttp, "90", lightsail.ContainerServiceProtocolTcp), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "3"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.%", "2"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.80", lightsail.ContainerServiceProtocolHttp), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.90", lightsail.ContainerServiceProtocolTcp), + ), + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_basic(rName, containerName, helloWorldImage), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "4"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccLightsailContainerServiceDeploymentVersion_Container_PublicEndpoint(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + containerName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + containerName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resourceName := "aws_lightsail_container_service_deployment_version.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_publicEndpoint(rName, containerName1), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "1"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.%", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.ports.80", lightsail.ContainerServiceProtocolHttp), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.container_name", containerName1), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.container_port", "80"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.healthy_threshold", "2"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.interval_seconds", "5"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.path", "/"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.success_codes", "200-499"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.timeout_seconds", "2"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.unhealthy_threshold", "2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_publicEndpointCompleteHealthCheck(rName, containerName2), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "2"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.container_name", containerName2), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.container_port", "80"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.healthy_threshold", "3"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.interval_seconds", "6"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.path", "/."), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.success_codes", "200"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.timeout_seconds", "3"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.unhealthy_threshold", "3"), + ), + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_publicEndpointMinimalHealthCheck(rName, containerName2), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "3"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.container_name", containerName2), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.container_port", "80"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.healthy_threshold", "4"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.interval_seconds", "5"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.path", "/"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.success_codes", "200-499"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.timeout_seconds", "2"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.unhealthy_threshold", "2"), + ), + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_publicEndpoint(rName, containerName2), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "4"), + resource.TestCheckResourceAttr(resourceName, "container.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.container_name", containerName2), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.container_port", "80"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.#", "1"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.healthy_threshold", "2"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.interval_seconds", "5"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.path", "/"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.success_codes", "200-499"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.timeout_seconds", "2"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.0.health_check.0.unhealthy_threshold", "2"), + ), + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_basic(rName, containerName1, helloWorldImage), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "5"), + resource.TestCheckResourceAttr(resourceName, "public_endpoint.#", "0"), + ), + }, + }, + }) +} + +func TestAccLightsailContainerServiceDeploymentVersion_Container_EnableService(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + containerName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service_deployment_version.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_withDisabledService(rName, containerName, true), + ExpectError: regexp.MustCompile(`disabled and cannot be deployed to`), + }, + { + Config: testAccContainerServiceDeploymentVersionConfig_Container_withDisabledService(rName, containerName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceDeploymentVersionExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "state", lightsail.ContainerServiceDeploymentStateActive), + resource.TestCheckResourceAttr(resourceName, "version", "1"), + resource.TestCheckResourceAttr(resourceName, "container.0.container_name", containerName), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckContainerServiceDeploymentVersionExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Not found: %s", resourceName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("no Lightsail Container Service Deployment Version ID is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).LightsailConn + + serviceName, version, err := tflightsail.ContainerServiceDeploymentVersionParseResourceID(rs.Primary.ID) + if err != nil { + return err + } + + _, err = tflightsail.FindContainerServiceDeploymentByVersion(context.TODO(), conn, serviceName, version) + if err != nil { + return err + } + + return nil + } +} + +func testAccContainerServiceDeploymentVersionBaseConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_lightsail_container_service" "test" { + name = %[1]q + power = "nano" + scale = 1 +} +`, rName) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_basic(rName, containerName, image string) string { + return acctest.ConfigCompose( + testAccContainerServiceDeploymentVersionBaseConfig(rName), + fmt.Sprintf(` +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[1]q + image = %[2]q + } + + service_name = aws_lightsail_container_service.test.name +} +`, containerName, image)) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_multiple(rName, containerName1, image1, containerName2, image2 string) string { + return acctest.ConfigCompose( + testAccContainerServiceDeploymentVersionBaseConfig(rName), + fmt.Sprintf(` +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[1]q + image = %[2]q + } + + container { + container_name = %[3]q + image = %[4]q + } + + service_name = aws_lightsail_container_service.test.name +} +`, containerName1, image1, containerName2, image2)) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_environment1(rName, containerName, envKey, envValue string) string { + return acctest.ConfigCompose( + testAccContainerServiceDeploymentVersionBaseConfig(rName), + fmt.Sprintf(` +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[1]q + image = "amazon/amazon-lightsail:hello-world" + environment = { + %[2]q = %[3]q + } + } + + service_name = aws_lightsail_container_service.test.name +} +`, containerName, envKey, envValue)) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_environment2(rName, containerName, envKey1, envValue1, envKey2, envValue2 string) string { + return acctest.ConfigCompose( + testAccContainerServiceDeploymentVersionBaseConfig(rName), + fmt.Sprintf(` +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[1]q + image = "amazon/amazon-lightsail:hello-world" + environment = { + %[2]q = %[3]q + %[4]q = %[5]q + } + } + + service_name = aws_lightsail_container_service.test.name +} +`, containerName, envKey1, envValue1, envKey2, envValue2)) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_ports1(rName, containerName, portKey, portValue string) string { + return acctest.ConfigCompose( + testAccContainerServiceDeploymentVersionBaseConfig(rName), + fmt.Sprintf(` +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[1]q + image = "amazon/amazon-lightsail:hello-world" + ports = { + %[2]q = %[3]q + } + } + + service_name = aws_lightsail_container_service.test.name +} +`, containerName, portKey, portValue)) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_ports2(rName, containerName, portKey1, portValue1, portKey2, portValue2 string) string { + return acctest.ConfigCompose( + testAccContainerServiceDeploymentVersionBaseConfig(rName), + fmt.Sprintf(` +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[1]q + image = "amazon/amazon-lightsail:hello-world" + ports = { + %[2]q = %[3]q + %[4]q = %[5]q + } + } + + service_name = aws_lightsail_container_service.test.name +} +`, containerName, portKey1, portValue1, portKey2, portValue2)) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_publicEndpoint(rName, containerName string) string { + return acctest.ConfigCompose( + testAccContainerServiceDeploymentVersionBaseConfig(rName), + fmt.Sprintf(` +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[1]q + image = "amazon/amazon-lightsail:hello-world" + ports = { + 80 = "HTTP" + } + } + + public_endpoint { + container_name = %[1]q + container_port = 80 + health_check {} + } + + service_name = aws_lightsail_container_service.test.name +} +`, containerName)) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_publicEndpointCompleteHealthCheck(rName, containerName string) string { + return acctest.ConfigCompose( + testAccContainerServiceDeploymentVersionBaseConfig(rName), + fmt.Sprintf(` +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[1]q + image = "amazon/amazon-lightsail:hello-world" + ports = { + 80 = "HTTP" + } + } + + public_endpoint { + container_name = %[1]q + container_port = 80 + health_check { + healthy_threshold = 3 + interval_seconds = 6 + path = "/." + success_codes = "200" + timeout_seconds = 3 + unhealthy_threshold = 3 + } + } + + service_name = aws_lightsail_container_service.test.name +} +`, containerName)) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_publicEndpointMinimalHealthCheck(rName, containerName string) string { + return acctest.ConfigCompose( + testAccContainerServiceDeploymentVersionBaseConfig(rName), + fmt.Sprintf(` +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[1]q + image = "amazon/amazon-lightsail:hello-world" + ports = { + 80 = "HTTP" + } + } + public_endpoint { + container_name = %[1]q + container_port = 80 + health_check { + healthy_threshold = 4 + } + } + + service_name = aws_lightsail_container_service.test.name +} +`, containerName)) +} + +func testAccContainerServiceDeploymentVersionConfig_Container_withDisabledService(rName, containerName string, isDisabled bool) string { + return fmt.Sprintf(` +resource "aws_lightsail_container_service" "test" { + name = %[1]q + power = "nano" + scale = 1 + is_disabled = %[2]t +} + +resource "aws_lightsail_container_service_deployment_version" "test" { + container { + container_name = %[3]q + image = "amazon/amazon-lightsail:hello-world" + } + + service_name = aws_lightsail_container_service.test.name +} +`, rName, isDisabled, containerName) +} diff --git a/internal/service/lightsail/container_service_test.go b/internal/service/lightsail/container_service_test.go new file mode 100644 index 00000000000..2ca88e655ca --- /dev/null +++ b/internal/service/lightsail/container_service_test.go @@ -0,0 +1,425 @@ +package lightsail_test + +import ( + "context" + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/lightsail" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tflightsail "github.com/hashicorp/terraform-provider-aws/internal/service/lightsail" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccLightsailContainerService_basic(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "created_at"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "power", lightsail.ContainerServicePowerNameNano), + resource.TestCheckResourceAttr(resourceName, "scale", "1"), + resource.TestCheckResourceAttr(resourceName, "is_disabled", "false"), + resource.TestCheckResourceAttrSet(resourceName, "arn"), + resource.TestCheckResourceAttrSet(resourceName, "availability_zone"), + resource.TestCheckResourceAttrSet(resourceName, "power_id"), + resource.TestCheckResourceAttrSet(resourceName, "principal_arn"), + resource.TestCheckResourceAttrSet(resourceName, "private_domain_name"), + resource.TestCheckResourceAttr(resourceName, "resource_type", "ContainerService"), + resource.TestCheckResourceAttr(resourceName, "state", "READY"), + resource.TestCheckResourceAttrSet(resourceName, "url"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccContainerServiceConfig_scale(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "scale", "2"), + ), + }, + }, + }) +} + +func TestAccLightsailContainerService_disappears(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tflightsail.ResourceContainerService(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccLightsailContainerService_Name(t *testing.T) { + rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceConfig_basic(rName1), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", rName1), + ), + }, + { + Config: testAccContainerServiceConfig_basic(rName2), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", rName2), + ), + }, + }, + }) +} + +func TestAccLightsailContainerService_IsDisabled(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "is_disabled", "false"), + ), + }, + { + Config: testAccContainerServiceConfig_disabled(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "is_disabled", "true"), + ), + }, + }, + }) +} + +func TestAccLightsailContainerService_Power(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "power", lightsail.ContainerServicePowerNameNano), + ), + }, + { + Config: testAccContainerServiceConfig_power(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "power", lightsail.ContainerServicePowerNameMicro), + ), + }, + }, + }) +} + +func TestAccLightsailContainerService_PublicDomainNames(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceConfig_publicDomainNames(rName), + ExpectError: regexp.MustCompile(`do not exist`), + }, + }, + }) +} + +func TestAccLightsailContainerService_Scale(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "scale", "1"), + ), + }, + { + Config: testAccContainerServiceConfig_scale(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "scale", "2"), + ), + }, + }, + }) + +} + +func TestAccLightsailContainerService_tags(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_lightsail_container_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService(lightsail.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, lightsail.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckContainerServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccContainerServiceConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccContainerServiceConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccContainerServiceConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckContainerServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func testAccCheckContainerServiceDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).LightsailConn + + for _, r := range s.RootModule().Resources { + if r.Type != "aws_lightsail_container_service" { + continue + } + + _, err := tflightsail.FindContainerServiceByName(context.TODO(), conn, r.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + } + + return nil +} + +func testAccCheckContainerServiceExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("not finding Lightsail Container Service (%s)", resourceName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("no Lightsail Container Service ID is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).LightsailConn + + _, err := tflightsail.FindContainerServiceByName(context.TODO(), conn, rs.Primary.ID) + if err != nil { + return err + } + + return nil + } +} + +func testAccContainerServiceConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_lightsail_container_service" "test" { + name = %q + power = "nano" + scale = 1 +} +`, rName) +} + +func testAccContainerServiceConfig_disabled(rName string) string { + return fmt.Sprintf(` +resource "aws_lightsail_container_service" "test" { + name = %q + power = "nano" + scale = 1 + is_disabled = true +} +`, rName) +} + +func testAccContainerServiceConfig_power(rName string) string { + return fmt.Sprintf(` +resource "aws_lightsail_container_service" "test" { + name = %q + power = "micro" + scale = 1 +} +`, rName) +} + +func testAccContainerServiceConfig_publicDomainNames(rName string) string { + return fmt.Sprintf(` +resource "aws_lightsail_container_service" "test" { + name = %q + power = "nano" + scale = 1 + + public_domain_names { + certificate { + certificate_name = "NonExsitingCertificate" + domain_names = [ + "nonexisting1.com", + "nonexisting2.com", + ] + } + } +} +`, rName) +} + +func testAccContainerServiceConfig_scale(rName string) string { + return fmt.Sprintf(` +resource "aws_lightsail_container_service" "test" { + name = %q + power = "nano" + scale = 2 +} +`, rName) +} + +func testAccContainerServiceConfig_tags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_lightsail_container_service" "test" { + name = %[1]q + power = "nano" + scale = 1 + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccContainerServiceConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_lightsail_container_service" "test" { + name = %q + power = "nano" + scale = 1 + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/internal/service/lightsail/find.go b/internal/service/lightsail/find.go new file mode 100644 index 00000000000..fe299b42f06 --- /dev/null +++ b/internal/service/lightsail/find.go @@ -0,0 +1,85 @@ +package lightsail + +import ( + "context" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func FindContainerServiceByName(ctx context.Context, conn *lightsail.Lightsail, serviceName string) (*lightsail.ContainerService, error) { + input := &lightsail.GetContainerServicesInput{ + ServiceName: aws.String(serviceName), + } + + output, err := conn.GetContainerServicesWithContext(ctx, input) + + if tfawserr.ErrCodeEquals(err, lightsail.ErrCodeNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || len(output.ContainerServices) == 0 { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output.ContainerServices); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output.ContainerServices[0], nil +} + +func FindContainerServiceDeploymentByVersion(ctx context.Context, conn *lightsail.Lightsail, serviceName string, version int) (*lightsail.ContainerServiceDeployment, error) { + input := &lightsail.GetContainerServiceDeploymentsInput{ + ServiceName: aws.String(serviceName), + } + + output, err := conn.GetContainerServiceDeploymentsWithContext(ctx, input) + + if tfawserr.ErrCodeEquals(err, lightsail.ErrCodeNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || len(output.Deployments) == 0 { + return nil, tfresource.NewEmptyResultError(input) + } + + var result *lightsail.ContainerServiceDeployment + + for _, deployment := range output.Deployments { + if deployment == nil { + continue + } + + if int(aws.Int64Value(deployment.Version)) == version { + result = deployment + break + } + } + + if result == nil { + return nil, &resource.NotFoundError{ + Message: "Empty result", + LastRequest: input, + } + } + + return result, nil +} diff --git a/internal/service/lightsail/status.go b/internal/service/lightsail/status.go new file mode 100644 index 00000000000..3f7cc01365e --- /dev/null +++ b/internal/service/lightsail/status.go @@ -0,0 +1,42 @@ +package lightsail + +import ( + "context" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func statusContainerService(ctx context.Context, conn *lightsail.Lightsail, serviceName string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + containerService, err := FindContainerServiceByName(ctx, conn, serviceName) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return containerService, aws.StringValue(containerService.State), nil + } +} + +func statusContainerServiceDeploymentVersion(ctx context.Context, conn *lightsail.Lightsail, serviceName string, version int) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + deployment, err := FindContainerServiceDeploymentByVersion(ctx, conn, serviceName, version) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return deployment, aws.StringValue(deployment.State), nil + } +} diff --git a/internal/service/lightsail/sweep.go b/internal/service/lightsail/sweep.go index 65d9c012fe5..64bccb5903b 100644 --- a/internal/service/lightsail/sweep.go +++ b/internal/service/lightsail/sweep.go @@ -4,6 +4,7 @@ package lightsail import ( + "context" "fmt" "log" @@ -16,6 +17,11 @@ import ( ) func init() { + resource.AddTestSweepers("aws_lightsail_container_service", &resource.Sweeper{ + Name: "aws_lightsail_container_service", + F: sweepContainerServices, + }) + resource.AddTestSweepers("aws_lightsail_instance", &resource.Sweeper{ Name: "aws_lightsail_instance", F: sweepInstances, @@ -27,6 +33,56 @@ func init() { }) } +func sweepContainerServices(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + if err != nil { + return fmt.Errorf("Error getting client: %s", err) + } + conn := client.(*conns.AWSClient).LightsailConn + + input := &lightsail.GetContainerServicesInput{} + var sweeperErrs *multierror.Error + sweepResources := make([]*sweep.SweepResource, 0) + + output, err := conn.GetContainerServicesWithContext(context.TODO(), input) + + if sweep.SkipSweepError(err) { + log.Printf("[WARN] Skipping Lightsail Container Service sweep for %s: %s", region, err) + return nil + } + + if err != nil { + return fmt.Errorf("Error retrieving Lightsail Container Services: %s", err) + } + + for _, service := range output.ContainerServices { + if service == nil { + continue + } + + r := ResourceContainerService() + d := r.Data(nil) + d.SetId(aws.StringValue(service.ContainerServiceName)) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + if sweep.SkipSweepError(err) { + log.Printf("[WARN] Skipping Lightsail Container Services sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() + } + + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing Lightsail Container Services for %s: %w", region, err)) + } + + if err := sweep.SweepOrchestrator(sweepResources); err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping Lightsail Container Services for %s: %w", region, err)) + } + + return sweeperErrs.ErrorOrNil() +} + func sweepInstances(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { diff --git a/internal/service/lightsail/wait.go b/internal/service/lightsail/wait.go new file mode 100644 index 00000000000..11710894be3 --- /dev/null +++ b/internal/service/lightsail/wait.go @@ -0,0 +1,128 @@ +package lightsail + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func waitContainerServiceCreated(ctx context.Context, conn *lightsail.Lightsail, serviceName string, timeout time.Duration) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{lightsail.ContainerServiceStatePending}, + Target: []string{lightsail.ContainerServiceStateReady}, + Refresh: statusContainerService(ctx, conn, serviceName), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*lightsail.ContainerService); ok { + if detail := output.StateDetail; detail != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.StringValue(detail.Code), aws.StringValue(detail.Message))) + } + + return err + } + + return err +} + +func waitContainerServiceDisabled(ctx context.Context, conn *lightsail.Lightsail, serviceName string, timeout time.Duration) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{lightsail.ContainerServiceStateUpdating}, + Target: []string{lightsail.ContainerServiceStateDisabled}, + Refresh: statusContainerService(ctx, conn, serviceName), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*lightsail.ContainerService); ok { + if detail := output.StateDetail; detail != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.StringValue(detail.Code), aws.StringValue(detail.Message))) + } + + return err + } + + return err +} + +func waitContainerServiceUpdated(ctx context.Context, conn *lightsail.Lightsail, serviceName string, timeout time.Duration) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{lightsail.ContainerServiceStateUpdating}, + Target: []string{lightsail.ContainerServiceStateReady, lightsail.ContainerServiceStateRunning}, + Refresh: statusContainerService(ctx, conn, serviceName), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*lightsail.ContainerService); ok { + if detail := output.StateDetail; detail != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.StringValue(detail.Code), aws.StringValue(detail.Message))) + } + + return err + } + + return err +} + +func waitContainerServiceDeleted(ctx context.Context, conn *lightsail.Lightsail, serviceName string, timeout time.Duration) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{lightsail.ContainerServiceStateDeleting}, + Target: []string{}, + Refresh: statusContainerService(ctx, conn, serviceName), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*lightsail.ContainerService); ok { + if detail := output.StateDetail; detail != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.StringValue(detail.Code), aws.StringValue(detail.Message))) + } + + return err + } + + return err +} + +func waitContainerServiceDeploymentVersionActive(ctx context.Context, conn *lightsail.Lightsail, serviceName string, version int, timeout time.Duration) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{lightsail.ContainerServiceDeploymentStateActivating}, + Target: []string{lightsail.ContainerServiceDeploymentStateActive}, + Refresh: statusContainerServiceDeploymentVersion(ctx, conn, serviceName, version), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*lightsail.ContainerServiceDeployment); ok { + if aws.StringValue(output.State) == lightsail.ContainerServiceDeploymentStateFailed { + tfresource.SetLastError(err, errors.New("The deployment failed. Use the GetContainerLog action to view the log events for the containers in the deployment to try to determine the reason for the failure.")) + } + + return err + } + + return err +} diff --git a/internal/service/location/map_data_source_test.go b/internal/service/location/map_data_source_test.go index c21bd249f59..c970dd46771 100644 --- a/internal/service/location/map_data_source_test.go +++ b/internal/service/location/map_data_source_test.go @@ -22,7 +22,7 @@ func TestAccLocationMapDataSource_mapName(t *testing.T) { CheckDestroy: testAccCheckMapDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigMapDataSource_mapName(rName), + Config: testAccMapDataSourceConfig_name(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "configuration.#", resourceName, "configuration.#"), resource.TestCheckResourceAttrPair(dataSourceName, "configuration.0.style", resourceName, "configuration.0.style"), @@ -38,7 +38,7 @@ func TestAccLocationMapDataSource_mapName(t *testing.T) { }) } -func testAccConfigMapDataSource_mapName(rName string) string { +func testAccMapDataSourceConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_location_map" "test" { configuration { diff --git a/internal/service/location/map_test.go b/internal/service/location/map_test.go index a0b76d1270b..0811b69bebd 100644 --- a/internal/service/location/map_test.go +++ b/internal/service/location/map_test.go @@ -26,7 +26,7 @@ func TestAccLocationMap_basic(t *testing.T) { CheckDestroy: testAccCheckMapDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigMap_basic(rName), + Config: testAccMapConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMapExists(resourceName), resource.TestCheckResourceAttr(resourceName, "configuration.#", "1"), @@ -59,7 +59,7 @@ func TestAccLocationMap_disappears(t *testing.T) { CheckDestroy: testAccCheckMapDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigMap_basic(rName), + Config: testAccMapConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMapExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tflocation.ResourceMap(), resourceName), @@ -81,7 +81,7 @@ func TestAccLocationMap_description(t *testing.T) { CheckDestroy: testAccCheckMapDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigMap_description(rName, "description1"), + Config: testAccMapConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckMapExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -93,7 +93,7 @@ func TestAccLocationMap_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigMap_description(rName, "description2"), + Config: testAccMapConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckMapExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -114,7 +114,7 @@ func TestAccLocationMap_tags(t *testing.T) { CheckDestroy: testAccCheckMapDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigMap_tags1(rName, "key1", "value1"), + Config: testAccMapConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckMapExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -127,7 +127,7 @@ func TestAccLocationMap_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigMap_tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccMapConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckMapExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -136,7 +136,7 @@ func TestAccLocationMap_tags(t *testing.T) { ), }, { - Config: testAccConfigMap_tags1(rName, "key2", "value2"), + Config: testAccMapConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckMapExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -201,7 +201,7 @@ func testAccCheckMapExists(resourceName string) resource.TestCheckFunc { } } -func testAccConfigMap_basic(rName string) string { +func testAccMapConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_location_map" "test" { configuration { @@ -213,7 +213,7 @@ resource "aws_location_map" "test" { `, rName) } -func testAccConfigMap_description(rName, description string) string { +func testAccMapConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_location_map" "test" { configuration { @@ -226,7 +226,7 @@ resource "aws_location_map" "test" { `, rName, description) } -func testAccConfigMap_tags1(rName, tagKey1, tagValue1 string) string { +func testAccMapConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_location_map" "test" { configuration { @@ -242,7 +242,7 @@ resource "aws_location_map" "test" { `, rName, tagKey1, tagValue1) } -func testAccConfigMap_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccMapConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_location_map" "test" { configuration { diff --git a/internal/service/location/place_index.go b/internal/service/location/place_index.go new file mode 100644 index 00000000000..2f8fcaaf71a --- /dev/null +++ b/internal/service/location/place_index.go @@ -0,0 +1,256 @@ +package location + +import ( + "fmt" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/locationservice" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "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" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourcePlaceIndex() *schema.Resource { + return &schema.Resource{ + Create: resourcePlaceIndexCreate, + Read: resourcePlaceIndexRead, + Update: resourcePlaceIndexUpdate, + Delete: resourcePlaceIndexDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "create_time": { + Type: schema.TypeString, + Computed: true, + }, + "data_source": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "data_source_configuration": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "intended_use": { + Type: schema.TypeString, + Optional: true, + Default: locationservice.IntendedUseSingleUse, + ValidateFunc: validation.StringInSlice(locationservice.IntendedUse_Values(), false), + }, + }, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(0, 1000), + }, + "index_arn": { + Type: schema.TypeString, + Computed: true, + }, + "index_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 100), + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourcePlaceIndexCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LocationConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + input := &locationservice.CreatePlaceIndexInput{} + + if v, ok := d.GetOk("data_source"); ok { + input.DataSource = aws.String(v.(string)) + } + + if v, ok := d.GetOk("data_source_configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.DataSourceConfiguration = expandDataSourceConfiguration(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("description"); ok { + input.Description = aws.String(v.(string)) + } + + if v, ok := d.GetOk("index_name"); ok { + input.IndexName = aws.String(v.(string)) + } + + if len(tags) > 0 { + input.Tags = Tags(tags.IgnoreAWS()) + } + + output, err := conn.CreatePlaceIndex(input) + + if err != nil { + return fmt.Errorf("error creating place index: %w", err) + } + + if output == nil { + return fmt.Errorf("error creating place index: empty result") + } + + d.SetId(aws.StringValue(output.IndexName)) + + return resourcePlaceIndexRead(d, meta) +} + +func resourcePlaceIndexRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LocationConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + input := &locationservice.DescribePlaceIndexInput{ + IndexName: aws.String(d.Id()), + } + + output, err := conn.DescribePlaceIndex(input) + + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, locationservice.ErrCodeResourceNotFoundException) { + log.Printf("[WARN] Location Service Place Index (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error getting Location Service Place Index (%s): %w", d.Id(), err) + } + + if output == nil { + return fmt.Errorf("error getting Location Service Place Index (%s): empty response", d.Id()) + } + + d.Set("create_time", aws.TimeValue(output.CreateTime).Format(time.RFC3339)) + d.Set("data_source", output.DataSource) + + if output.DataSourceConfiguration != nil { + d.Set("data_source_configuration", []interface{}{flattenDataSourceConfiguration(output.DataSourceConfiguration)}) + } else { + d.Set("data_source_configuration", nil) + } + + d.Set("description", output.Description) + d.Set("index_arn", output.IndexArn) + d.Set("index_name", output.IndexName) + + tags := KeyValueTags(output.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %w", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return fmt.Errorf("error setting tags_all: %w", err) + } + + d.Set("update_time", aws.TimeValue(output.UpdateTime).Format(time.RFC3339)) + + return nil +} + +func resourcePlaceIndexUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LocationConn + + if d.HasChanges("data_source_configuration", "description") { + input := &locationservice.UpdatePlaceIndexInput{ + IndexName: aws.String(d.Id()), + // Deprecated but still required by the API + PricingPlan: aws.String(locationservice.PricingPlanRequestBasedUsage), + } + + if v, ok := d.GetOk("data_source_configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.DataSourceConfiguration = expandDataSourceConfiguration(v.([]interface{})[0].(map[string]interface{})) + } + + if v, ok := d.GetOk("description"); ok { + input.Description = aws.String(v.(string)) + } + + _, err := conn.UpdatePlaceIndex(input) + + if err != nil { + return fmt.Errorf("error updating Location Service Place Index (%s): %w", d.Id(), err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Get("index_arn").(string), o, n); err != nil { + return fmt.Errorf("error updating tags for Location Service Place Index (%s): %w", d.Id(), err) + } + } + + return resourcePlaceIndexRead(d, meta) +} + +func resourcePlaceIndexDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LocationConn + + input := &locationservice.DeletePlaceIndexInput{ + IndexName: aws.String(d.Id()), + } + + _, err := conn.DeletePlaceIndex(input) + + if tfawserr.ErrCodeEquals(err, locationservice.ErrCodeResourceNotFoundException) { + return nil + } + + if err != nil { + return fmt.Errorf("error deleting Location Service Place Index (%s): %w", d.Id(), err) + } + + return nil +} + +func expandDataSourceConfiguration(tfMap map[string]interface{}) *locationservice.DataSourceConfiguration { + if tfMap == nil { + return nil + } + + apiObject := &locationservice.DataSourceConfiguration{} + + if v, ok := tfMap["intended_use"].(string); ok && v != "" { + apiObject.IntendedUse = aws.String(v) + } + + return apiObject +} + +func flattenDataSourceConfiguration(apiObject *locationservice.DataSourceConfiguration) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.IntendedUse; v != nil { + tfMap["intended_use"] = aws.StringValue(v) + } + + return tfMap +} diff --git a/internal/service/location/place_index_data_source.go b/internal/service/location/place_index_data_source.go new file mode 100644 index 00000000000..6b00754dca1 --- /dev/null +++ b/internal/service/location/place_index_data_source.go @@ -0,0 +1,97 @@ +package location + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/locationservice" + "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" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" +) + +func DataSourcePlaceIndex() *schema.Resource { + return &schema.Resource{ + Read: dataSourcePlaceIndexRead, + Schema: map[string]*schema.Schema{ + "create_time": { + Type: schema.TypeString, + Computed: true, + }, + "data_source": { + Type: schema.TypeString, + Computed: true, + }, + "data_source_configuration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "intended_use": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "index_arn": { + Type: schema.TypeString, + Computed: true, + }, + "index_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 100), + }, + "tags": tftags.TagsSchemaComputed(), + "update_time": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourcePlaceIndexRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LocationConn + + input := &locationservice.DescribePlaceIndexInput{} + + if v, ok := d.GetOk("index_name"); ok { + input.IndexName = aws.String(v.(string)) + } + + output, err := conn.DescribePlaceIndex(input) + + if err != nil { + return fmt.Errorf("error getting Location Service Place Index: %w", err) + } + + if output == nil { + return fmt.Errorf("error getting Location Service Place Index: empty response") + } + + d.SetId(aws.StringValue(output.IndexName)) + d.Set("create_time", aws.TimeValue(output.CreateTime).Format(time.RFC3339)) + d.Set("data_source", output.DataSource) + + if output.DataSourceConfiguration != nil { + d.Set("data_source_configuration", []interface{}{flattenDataSourceConfiguration(output.DataSourceConfiguration)}) + } else { + d.Set("data_source_configuration", nil) + } + + d.Set("description", output.Description) + d.Set("index_arn", output.IndexArn) + d.Set("index_name", output.IndexName) + d.Set("tags", KeyValueTags(output.Tags).IgnoreAWS().IgnoreConfig(meta.(*conns.AWSClient).IgnoreTagsConfig).Map()) + d.Set("update_time", aws.TimeValue(output.UpdateTime).Format(time.RFC3339)) + + return nil +} diff --git a/internal/service/location/place_index_data_source_test.go b/internal/service/location/place_index_data_source_test.go new file mode 100644 index 00000000000..5c6ac7fff4b --- /dev/null +++ b/internal/service/location/place_index_data_source_test.go @@ -0,0 +1,53 @@ +package location_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/locationservice" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" +) + +func TestAccLocationPlaceIndexDataSource_indexName(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + dataSourceName := "data.aws_location_place_index.test" + resourceName := "aws_location_place_index.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckPlaceIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccPlaceIndexDataSourceConfig_indexName(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "create_time", resourceName, "create_time"), + resource.TestCheckResourceAttrPair(dataSourceName, "data_source", resourceName, "data_source"), + resource.TestCheckResourceAttrPair(dataSourceName, "data_source_configuration.#", resourceName, "data_source_configuration.#"), + resource.TestCheckResourceAttrPair(dataSourceName, "data_source_configuration.0.intended_use", resourceName, "data_source_configuration.0.intended_use"), + resource.TestCheckResourceAttrPair(dataSourceName, "description", resourceName, "description"), + resource.TestCheckResourceAttrPair(dataSourceName, "index_arn", resourceName, "index_arn"), + resource.TestCheckResourceAttrPair(dataSourceName, "index_name", resourceName, "index_name"), + resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(dataSourceName, "update_time", resourceName, "update_time"), + ), + }, + }, + }) +} + +func testAccPlaceIndexDataSourceConfig_indexName(rName string) string { + return fmt.Sprintf(` +resource "aws_location_place_index" "test" { + data_source = "Here" + index_name = %[1]q +} + +data "aws_location_place_index" "test" { + index_name = aws_location_place_index.test.index_name +} +`, rName) +} diff --git a/internal/service/location/place_index_test.go b/internal/service/location/place_index_test.go new file mode 100644 index 00000000000..2dfa8d0ccc3 --- /dev/null +++ b/internal/service/location/place_index_test.go @@ -0,0 +1,298 @@ +package location_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/locationservice" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tflocation "github.com/hashicorp/terraform-provider-aws/internal/service/location" +) + +func TestAccLocationPlaceIndex_basic(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_place_index.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckPlaceIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccPlaceIndexConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckPlaceIndexExists(resourceName), + acctest.CheckResourceAttrRFC3339(resourceName, "create_time"), + resource.TestCheckResourceAttr(resourceName, "data_source", "Here"), + resource.TestCheckResourceAttr(resourceName, "data_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "data_source_configuration.0.intended_use", locationservice.IntendedUseSingleUse), + resource.TestCheckResourceAttr(resourceName, "description", ""), + acctest.CheckResourceAttrRegionalARN(resourceName, "index_arn", "geo", fmt.Sprintf("place-index/%s", rName)), + resource.TestCheckResourceAttr(resourceName, "index_name", rName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + acctest.CheckResourceAttrRFC3339(resourceName, "update_time"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccLocationPlaceIndex_disappears(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_place_index.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckPlaceIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccPlaceIndexConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckPlaceIndexExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tflocation.ResourcePlaceIndex(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccLocationPlaceIndex_dataSourceConfigurationIntendedUse(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_place_index.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckPlaceIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccPlaceIndexConfig_configurationIntendedUse(rName, locationservice.IntendedUseSingleUse), + Check: resource.ComposeTestCheckFunc( + testAccCheckPlaceIndexExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "data_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "data_source_configuration.0.intended_use", locationservice.IntendedUseSingleUse), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccPlaceIndexConfig_configurationIntendedUse(rName, locationservice.IntendedUseStorage), + Check: resource.ComposeTestCheckFunc( + testAccCheckPlaceIndexExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "data_source_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "data_source_configuration.0.intended_use", locationservice.IntendedUseStorage), + ), + }, + }, + }) +} + +func TestAccLocationPlaceIndex_description(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_place_index.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckPlaceIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccPlaceIndexConfig_description(rName, "description1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckPlaceIndexExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccPlaceIndexConfig_description(rName, "description2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckPlaceIndexExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description2"), + ), + }, + }, + }) +} + +func TestAccLocationPlaceIndex_tags(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_place_index.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckPlaceIndexDestroy, + Steps: []resource.TestStep{ + { + Config: testAccPlaceIndexConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckPlaceIndexExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccPlaceIndexConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckPlaceIndexExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccPlaceIndexConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckPlaceIndexExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func testAccCheckPlaceIndexDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).LocationConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_location_place_index" { + continue + } + + input := &locationservice.DescribePlaceIndexInput{ + IndexName: aws.String(rs.Primary.ID), + } + + output, err := conn.DescribePlaceIndex(input) + + if tfawserr.ErrCodeEquals(err, locationservice.ErrCodeResourceNotFoundException) { + continue + } + + if err != nil { + return fmt.Errorf("error getting Location Service Place Index (%s): %w", rs.Primary.ID, err) + } + + if output != nil { + return fmt.Errorf("Location Service Place Index (%s) still exists", rs.Primary.ID) + } + } + + return nil +} + +func testAccCheckPlaceIndexExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + + if !ok { + return fmt.Errorf("resource not found: %s", resourceName) + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).LocationConn + + input := &locationservice.DescribePlaceIndexInput{ + IndexName: aws.String(rs.Primary.ID), + } + + _, err := conn.DescribePlaceIndex(input) + + if err != nil { + return fmt.Errorf("error getting Location Service Place Index (%s): %w", rs.Primary.ID, err) + } + + return nil + } +} + +func testAccPlaceIndexConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_location_place_index" "test" { + data_source = "Here" + index_name = %[1]q +} +`, rName) +} + +func testAccPlaceIndexConfig_configurationIntendedUse(rName, intendedUse string) string { + return fmt.Sprintf(` +resource "aws_location_place_index" "test" { + data_source = "Here" + + data_source_configuration { + intended_use = %[2]q + } + + index_name = %[1]q +} +`, rName, intendedUse) +} + +func testAccPlaceIndexConfig_description(rName, description string) string { + return fmt.Sprintf(` +resource "aws_location_place_index" "test" { + data_source = "Here" + description = %[2]q + index_name = %[1]q +} +`, rName, description) +} + +func testAccPlaceIndexConfig_tags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_location_place_index" "test" { + data_source = "Here" + index_name = %[1]q + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccPlaceIndexConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_location_place_index" "test" { + data_source = "Here" + index_name = %[1]q + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/internal/service/location/sweep.go b/internal/service/location/sweep.go new file mode 100644 index 00000000000..7b95e0725dc --- /dev/null +++ b/internal/service/location/sweep.go @@ -0,0 +1,122 @@ +//go:build sweep +// +build sweep + +package location + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/locationservice" + "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" +) + +func init() { + resource.AddTestSweepers("aws_location_map", &resource.Sweeper{ + Name: "aws_location_map", + F: sweepMaps, + }) + + resource.AddTestSweepers("aws_location_place_index", &resource.Sweeper{ + Name: "aws_location_place_index", + F: sweepPlaceIndexes, + }) +} + +func sweepMaps(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + + conn := client.(*conns.AWSClient).LocationConn + sweepResources := make([]*sweep.SweepResource, 0) + var errs *multierror.Error + + input := &locationservice.ListMapsInput{} + + err = conn.ListMapsPages(input, func(page *locationservice.ListMapsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, entry := range page.Entries { + r := ResourceMap() + d := r.Data(nil) + + id := aws.StringValue(entry.MapName) + d.SetId(id) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + return !lastPage + }) + + if err != nil { + errs = multierror.Append(errs, fmt.Errorf("error listing Location Service Map for %s: %w", region, err)) + } + + if err := sweep.SweepOrchestrator(sweepResources); err != nil { + errs = multierror.Append(errs, fmt.Errorf("error sweeping Location Service Map for %s: %w", region, err)) + } + + if sweep.SkipSweepError(err) { + log.Printf("[WARN] Skipping Location Service Map sweep for %s: %s", region, errs) + return nil + } + + return errs.ErrorOrNil() +} + +func sweepPlaceIndexes(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + + conn := client.(*conns.AWSClient).LocationConn + sweepResources := make([]*sweep.SweepResource, 0) + var errs *multierror.Error + + input := &locationservice.ListPlaceIndexesInput{} + + err = conn.ListPlaceIndexesPages(input, func(page *locationservice.ListPlaceIndexesOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, entry := range page.Entries { + r := ResourceMap() + d := r.Data(nil) + + id := aws.StringValue(entry.IndexName) + d.SetId(id) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + return !lastPage + }) + + if err != nil { + errs = multierror.Append(errs, fmt.Errorf("error listing Location Service Place Index for %s: %w", region, err)) + } + + if err := sweep.SweepOrchestrator(sweepResources); err != nil { + errs = multierror.Append(errs, fmt.Errorf("error sweeping Location Service Place Index for %s: %w", region, err)) + } + + if sweep.SkipSweepError(err) { + log.Printf("[WARN] Skipping Location Service Place Index sweep for %s: %s", region, errs) + return nil + } + + return errs.ErrorOrNil() +} diff --git a/internal/service/location/tracker.go b/internal/service/location/tracker.go new file mode 100644 index 00000000000..43e29b208a4 --- /dev/null +++ b/internal/service/location/tracker.go @@ -0,0 +1,210 @@ +package location + +import ( + "fmt" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/locationservice" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "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" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceTracker() *schema.Resource { + return &schema.Resource{ + Create: resourceTrackerCreate, + Read: resourceTrackerRead, + Update: resourceTrackerUpdate, + Delete: resourceTrackerDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "create_time": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(0, 1000), + }, + "kms_key_id": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 2048), + }, + "position_filtering": { + Type: schema.TypeString, + Optional: true, + Default: locationservice.PositionFilteringTimeBased, + ValidateFunc: validation.StringInSlice(locationservice.PositionFiltering_Values(), false), + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + "tracker_arn": { + Type: schema.TypeString, + Computed: true, + }, + "tracker_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 100), + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + }, + }, + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourceTrackerCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LocationConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + input := &locationservice.CreateTrackerInput{} + + if v, ok := d.GetOk("description"); ok { + input.Description = aws.String(v.(string)) + } + + if v, ok := d.GetOk("kms_key_id"); ok { + input.KmsKeyId = aws.String(v.(string)) + } + + if v, ok := d.GetOk("position_filtering"); ok { + input.PositionFiltering = aws.String(v.(string)) + } + + if len(tags) > 0 { + input.Tags = Tags(tags.IgnoreAWS()) + } + + if v, ok := d.GetOk("tracker_name"); ok { + input.TrackerName = aws.String(v.(string)) + } + + output, err := conn.CreateTracker(input) + + if err != nil { + return fmt.Errorf("error creating Location Service Tracker: %w", err) + } + + if output == nil { + return fmt.Errorf("error creating Location Service Tracker: empty result") + } + + d.SetId(aws.StringValue(output.TrackerName)) + + return resourceTrackerRead(d, meta) +} + +func resourceTrackerRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LocationConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + input := &locationservice.DescribeTrackerInput{ + TrackerName: aws.String(d.Id()), + } + + output, err := conn.DescribeTracker(input) + + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, locationservice.ErrCodeResourceNotFoundException) { + log.Printf("[WARN] Location Service Tracker (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error getting Location Service Tracker (%s): %w", d.Id(), err) + } + + if output == nil { + return fmt.Errorf("error getting Location Service Map (%s): empty response", d.Id()) + } + + d.Set("create_time", aws.TimeValue(output.CreateTime).Format(time.RFC3339)) + d.Set("description", output.Description) + d.Set("kms_key_id", output.KmsKeyId) + d.Set("position_filtering", output.PositionFiltering) + + tags := KeyValueTags(output.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %w", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return fmt.Errorf("error setting tags_all: %w", err) + } + + d.Set("tracker_arn", output.TrackerArn) + d.Set("tracker_name", output.TrackerName) + d.Set("update_time", aws.TimeValue(output.UpdateTime).Format(time.RFC3339)) + + return nil +} + +func resourceTrackerUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LocationConn + + if d.HasChanges("description", "position_filtering") { + input := &locationservice.UpdateTrackerInput{ + TrackerName: aws.String(d.Id()), + } + + if v, ok := d.GetOk("description"); ok { + input.Description = aws.String(v.(string)) + } + + if v, ok := d.GetOk("position_filtering"); ok { + input.PositionFiltering = aws.String(v.(string)) + } + + _, err := conn.UpdateTracker(input) + + if err != nil { + return fmt.Errorf("error updating Location Service Tracker (%s): %w", d.Id(), err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Get("tracker_arn").(string), o, n); err != nil { + return fmt.Errorf("error updating tags for Location Service Tracker (%s): %w", d.Id(), err) + } + } + + return resourceTrackerRead(d, meta) +} + +func resourceTrackerDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).LocationConn + + input := &locationservice.DeleteTrackerInput{ + TrackerName: aws.String(d.Id()), + } + + _, err := conn.DeleteTracker(input) + + if tfawserr.ErrCodeEquals(err, locationservice.ErrCodeResourceNotFoundException) { + return nil + } + + if err != nil { + return fmt.Errorf("error deleting Location Service Tracker (%s): %w", d.Id(), err) + } + + return nil +} diff --git a/internal/service/location/tracker_test.go b/internal/service/location/tracker_test.go new file mode 100644 index 00000000000..929549c2a2b --- /dev/null +++ b/internal/service/location/tracker_test.go @@ -0,0 +1,324 @@ +package location_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/locationservice" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tflocation "github.com/hashicorp/terraform-provider-aws/internal/service/location" +) + +func TestAccLocationTracker_basic(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_tracker.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckTrackerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccTrackerConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + acctest.CheckResourceAttrRFC3339(resourceName, "create_time"), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), + resource.TestCheckResourceAttr(resourceName, "position_filtering", locationservice.PositionFilteringTimeBased), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + acctest.CheckResourceAttrRegionalARN(resourceName, "tracker_arn", "geo", fmt.Sprintf("tracker/%s", rName)), + resource.TestCheckResourceAttr(resourceName, "tracker_name", rName), + acctest.CheckResourceAttrRFC3339(resourceName, "update_time"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccLocationTracker_disappears(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_tracker.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckTrackerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccTrackerConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tflocation.ResourceTracker(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccLocationTracker_description(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_tracker.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckTrackerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccTrackerConfig_description(rName, "description1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccTrackerConfig_description(rName, "description2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "description2"), + ), + }, + }, + }) +} + +func TestAccLocationTracker_kmsKeyID(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_tracker.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckTrackerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccTrackerConfig_kmsKeyID(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", "aws_kms_key.test", "arn"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccLocationTracker_positionFiltering(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_tracker.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckTrackerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccTrackerConfig_positionFiltering(rName, locationservice.PositionFilteringAccuracyBased), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "position_filtering", locationservice.PositionFilteringAccuracyBased), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccTrackerConfig_positionFiltering(rName, locationservice.PositionFilteringDistanceBased), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "position_filtering", locationservice.PositionFilteringDistanceBased), + ), + }, + }, + }) +} + +func TestAccLocationTracker_tags(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_location_tracker.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, locationservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckTrackerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccTrackerConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccTrackerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccTrackerConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckTrackerExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} +func testAccCheckTrackerDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).LocationConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_location_tracker" { + continue + } + + input := &locationservice.DescribeTrackerInput{ + TrackerName: aws.String(rs.Primary.ID), + } + + output, err := conn.DescribeTracker(input) + + if tfawserr.ErrCodeEquals(err, locationservice.ErrCodeResourceNotFoundException) { + continue + } + + if err != nil { + return fmt.Errorf("error getting Location Service Tracker (%s): %w", rs.Primary.ID, err) + } + + if output != nil { + return fmt.Errorf("Location Service Tracker (%s) still exists", rs.Primary.ID) + } + } + + return nil +} + +func testAccCheckTrackerExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + + if !ok { + return fmt.Errorf("resource not found: %s", resourceName) + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).LocationConn + + input := &locationservice.DescribeTrackerInput{ + TrackerName: aws.String(rs.Primary.ID), + } + + _, err := conn.DescribeTracker(input) + + if err != nil { + return fmt.Errorf("error getting Location Service Tracker (%s): %w", rs.Primary.ID, err) + } + + return nil + } +} + +func testAccTrackerConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_location_tracker" "test" { + tracker_name = %[1]q +} +`, rName) +} + +func testAccTrackerConfig_description(rName, description string) string { + return fmt.Sprintf(` +resource "aws_location_tracker" "test" { + tracker_name = %[1]q + description = %[2]q +} +`, rName, description) +} + +func testAccTrackerConfig_kmsKeyID(rName string) string { + return fmt.Sprintf(` +resource "aws_kms_key" "test" { + deletion_window_in_days = 7 +} + +resource "aws_location_tracker" "test" { + tracker_name = %[1]q + kms_key_id = aws_kms_key.test.arn +} +`, rName) +} + +func testAccTrackerConfig_positionFiltering(rName, positionFiltering string) string { + return fmt.Sprintf(` +resource "aws_location_tracker" "test" { + tracker_name = %[1]q + position_filtering = %[2]q +} +`, rName, positionFiltering) +} + +func testAccTrackerConfig_tags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_location_tracker" "test" { + tracker_name = %[1]q + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccTrackerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_location_tracker" "test" { + tracker_name = %[1]q + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/internal/service/logs/destination_policy_test.go b/internal/service/logs/destination_policy_test.go index 3523c352c8f..919a07a03bd 100644 --- a/internal/service/logs/destination_policy_test.go +++ b/internal/service/logs/destination_policy_test.go @@ -25,7 +25,7 @@ func TestAccLogsDestinationPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckDestinationPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccDestinationPolicyConfig(rName), + Config: testAccDestinationPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDestinationPolicyExists(resourceName, &destination), resource.TestCheckResourceAttrPair(resourceName, "destination_name", "aws_cloudwatch_log_destination.test", "name"), @@ -38,7 +38,7 @@ func TestAccLogsDestinationPolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDestinationPolicyForceUpdateConfig(rName), + Config: testAccDestinationPolicyConfig_forceUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDestinationPolicyExists(resourceName, &destination), resource.TestCheckResourceAttrPair(resourceName, "destination_name", "aws_cloudwatch_log_destination.test", "name"), @@ -189,7 +189,7 @@ data "aws_iam_policy_document" "access" { `, rName) } -func testAccDestinationPolicyConfig(rName string) string { +func testAccDestinationPolicyConfig_basic(rName string) string { return testAccDestinationPolicyBaseConfig(rName) + ` resource "aws_cloudwatch_log_destination_policy" "test" { destination_name = aws_cloudwatch_log_destination.test.name @@ -198,7 +198,7 @@ resource "aws_cloudwatch_log_destination_policy" "test" { ` } -func testAccDestinationPolicyForceUpdateConfig(rName string) string { +func testAccDestinationPolicyConfig_forceUpdate(rName string) string { return testAccDestinationPolicyBaseConfig(rName) + ` data "aws_iam_policy_document" "access2" { statement { diff --git a/internal/service/logs/destination_test.go b/internal/service/logs/destination_test.go index d36f6a9e62f..3d751281d4a 100644 --- a/internal/service/logs/destination_test.go +++ b/internal/service/logs/destination_test.go @@ -28,7 +28,7 @@ func TestAccLogsDestination_basic(t *testing.T) { CheckDestroy: testAccCheckDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccDestinationConfig(rstring), + Config: testAccDestinationConfig_basic(rstring), Check: resource.ComposeTestCheckFunc( testAccCheckDestinationExists(resourceName, &destination), resource.TestCheckResourceAttrPair(resourceName, "target_arn", streamResourceName, "arn"), @@ -58,7 +58,7 @@ func TestAccLogsDestination_disappears(t *testing.T) { CheckDestroy: testAccCheckDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccDestinationConfig(rstring), + Config: testAccDestinationConfig_basic(rstring), Check: resource.ComposeTestCheckFunc( testAccCheckDestinationExists(resourceName, &destination), acctest.CheckResourceDisappears(acctest.Provider, tflogs.ResourceDestination(), resourceName), @@ -113,7 +113,7 @@ func testAccCheckDestinationExists(n string, d *cloudwatchlogs.Destination) reso } } -func testAccDestinationConfig(rstring string) string { +func testAccDestinationConfig_basic(rstring string) string { return fmt.Sprintf(` resource "aws_kinesis_stream" "test" { name = "RootAccess_%[1]s" diff --git a/internal/service/logs/group_data_source_test.go b/internal/service/logs/group_data_source_test.go index 0629c32bbe0..729778db101 100644 --- a/internal/service/logs/group_data_source_test.go +++ b/internal/service/logs/group_data_source_test.go @@ -20,7 +20,7 @@ func TestAccLogsGroupDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckGroupDataSourceConfig(rName), + Config: testAccGroupDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "name", "aws_cloudwatch_log_group.test", "name"), resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_cloudwatch_log_group.test", "arn"), @@ -42,7 +42,7 @@ func TestAccLogsGroupDataSource_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckGroupTagsDataSourceConfig(rName), + Config: testAccGroupDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "name", "aws_cloudwatch_log_group.test", "name"), resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_cloudwatch_log_group.test", "arn"), @@ -64,7 +64,7 @@ func TestAccLogsGroupDataSource_kms(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckGroupKMSDataSourceConfig(rName), + Config: testAccGroupDataSourceConfig_kms(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "name", "aws_cloudwatch_log_group.test", "name"), resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_cloudwatch_log_group.test", "arn"), @@ -87,7 +87,7 @@ func TestAccLogsGroupDataSource_retention(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckGroupRetentionDataSourceConfig(rName), + Config: testAccGroupDataSourceConfig_retention(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "name", "aws_cloudwatch_log_group.test", "name"), resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_cloudwatch_log_group.test", "arn"), @@ -100,7 +100,7 @@ func TestAccLogsGroupDataSource_retention(t *testing.T) { }) } -func testAccCheckGroupDataSourceConfig(rName string) string { +func testAccGroupDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource aws_cloudwatch_log_group "test" { name = "%s" @@ -112,7 +112,7 @@ data aws_cloudwatch_log_group "test" { `, rName) } -func testAccCheckGroupTagsDataSourceConfig(rName string) string { +func testAccGroupDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` resource aws_cloudwatch_log_group "test" { name = "%s" @@ -130,7 +130,7 @@ data aws_cloudwatch_log_group "test" { `, rName) } -func testAccCheckGroupKMSDataSourceConfig(rName string) string { +func testAccGroupDataSourceConfig_kms(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "foo" { description = "Terraform acc test %s" @@ -166,7 +166,7 @@ data aws_cloudwatch_log_group "test" { `, rName, rName) } -func testAccCheckGroupRetentionDataSourceConfig(rName string) string { +func testAccGroupDataSourceConfig_retention(rName string) string { return fmt.Sprintf(` resource aws_cloudwatch_log_group "test" { name = "%s" diff --git a/internal/service/logs/group_test.go b/internal/service/logs/group_test.go index e9ac962d83d..88197581068 100644 --- a/internal/service/logs/group_test.go +++ b/internal/service/logs/group_test.go @@ -26,7 +26,7 @@ func TestAccLogsGroup_basic(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(rInt), + Config: testAccGroupConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "logs", fmt.Sprintf("log-group:foo-bar-%d", rInt)), @@ -56,7 +56,7 @@ func TestAccLogsGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroup_namePrefix, + Config: testAccGroupConfig_namePrefix, Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile("^tf-test-")), @@ -84,7 +84,7 @@ func TestAccLogsGroup_NamePrefix_retention(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroup_namePrefix_retention(rName, 365), + Config: testAccGroupConfig_namePrefixRetention(rName, 365), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile("^tf-test-")), @@ -98,7 +98,7 @@ func TestAccLogsGroup_NamePrefix_retention(t *testing.T) { ImportStateVerifyIgnore: []string{"retention_in_days", "name_prefix"}, }, { - Config: testAccGroup_namePrefix_retention(rName, 7), + Config: testAccGroupConfig_namePrefixRetention(rName, 7), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile("^tf-test-")), @@ -120,7 +120,7 @@ func TestAccLogsGroup_generatedName(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroup_generatedName, + Config: testAccGroupConfig_generatedName, Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), ), @@ -147,7 +147,7 @@ func TestAccLogsGroup_retentionPolicy(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig_withRetention(rInt), + Config: testAccGroupConfig_retention(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestCheckResourceAttr(resourceName, "retention_in_days", "365"), @@ -160,7 +160,7 @@ func TestAccLogsGroup_retentionPolicy(t *testing.T) { ImportStateVerifyIgnore: []string{"retention_in_days"}, }, { - Config: testAccGroupModifiedConfig_withRetention(rInt), + Config: testAccGroupConfig_modifiedRetention(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestCheckResourceAttr(resourceName, "retention_in_days", "0"), @@ -214,7 +214,7 @@ func TestAccLogsGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(rInt), + Config: testAccGroupConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), testAccCheckGroupDisappears(&lg), @@ -237,7 +237,7 @@ func TestAccLogsGroup_tagging(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupWithTagsConfig(rInt), + Config: testAccGroupConfig_tags(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -253,7 +253,7 @@ func TestAccLogsGroup_tagging(t *testing.T) { ImportStateVerifyIgnore: []string{"retention_in_days"}, }, { - Config: testAccGroupWithTagsAddedConfig(rInt), + Config: testAccGroupConfig_tagsAdded(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestCheckResourceAttr(resourceName, "tags.%", "4"), @@ -264,7 +264,7 @@ func TestAccLogsGroup_tagging(t *testing.T) { ), }, { - Config: testAccGroupWithTagsUpdatedConfig(rInt), + Config: testAccGroupConfig_tagsUpdated(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestCheckResourceAttr(resourceName, "tags.%", "4"), @@ -275,7 +275,7 @@ func TestAccLogsGroup_tagging(t *testing.T) { ), }, { - Config: testAccGroupWithTagsConfig(rInt), + Config: testAccGroupConfig_tags(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -300,7 +300,7 @@ func TestAccLogsGroup_kmsKey(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(rInt), + Config: testAccGroupConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), ), @@ -312,7 +312,7 @@ func TestAccLogsGroup_kmsKey(t *testing.T) { ImportStateVerifyIgnore: []string{"retention_in_days"}, }, { - Config: testAccGroupWithKMSKeyIDConfig(rInt), + Config: testAccGroupConfig_kmsKeyID(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &lg), resource.TestCheckResourceAttrSet(resourceName, "kms_key_id"), @@ -377,7 +377,7 @@ func testAccCheckGroupDestroy(s *terraform.State) error { return nil } -func testAccGroupConfig(rInt int) string { +func testAccGroupConfig_basic(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = "foo-bar-%d" @@ -385,7 +385,7 @@ resource "aws_cloudwatch_log_group" "test" { `, rInt) } -func testAccGroupWithTagsConfig(rInt int) string { +func testAccGroupConfig_tags(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = "foo-bar-%d" @@ -399,7 +399,7 @@ resource "aws_cloudwatch_log_group" "test" { `, rInt) } -func testAccGroupWithTagsAddedConfig(rInt int) string { +func testAccGroupConfig_tagsAdded(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = "foo-bar-%d" @@ -414,7 +414,7 @@ resource "aws_cloudwatch_log_group" "test" { `, rInt) } -func testAccGroupWithTagsUpdatedConfig(rInt int) string { +func testAccGroupConfig_tagsUpdated(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = "foo-bar-%d" @@ -429,7 +429,7 @@ resource "aws_cloudwatch_log_group" "test" { `, rInt) } -func testAccGroupConfig_withRetention(rInt int) string { +func testAccGroupConfig_retention(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = "foo-bar-%d" @@ -438,7 +438,7 @@ resource "aws_cloudwatch_log_group" "test" { `, rInt) } -func testAccGroupModifiedConfig_withRetention(rInt int) string { +func testAccGroupConfig_modifiedRetention(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = "foo-bar-%d" @@ -464,7 +464,7 @@ resource "aws_cloudwatch_log_group" "charlie" { `, rInt, rInt+1, rInt+2) } -func testAccGroupWithKMSKeyIDConfig(rInt int) string { +func testAccGroupConfig_kmsKeyID(rInt int) string { return fmt.Sprintf(` resource "aws_kms_key" "foo" { description = "Terraform acc test %d" @@ -496,13 +496,13 @@ resource "aws_cloudwatch_log_group" "test" { `, rInt, rInt) } -const testAccGroup_namePrefix = ` +const testAccGroupConfig_namePrefix = ` resource "aws_cloudwatch_log_group" "test" { name_prefix = "tf-test-" } ` -func testAccGroup_namePrefix_retention(rName string, retention int) string { +func testAccGroupConfig_namePrefixRetention(rName string, retention int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name_prefix = "tf-test-%s" @@ -511,6 +511,6 @@ resource "aws_cloudwatch_log_group" "test" { `, rName, retention) } -const testAccGroup_generatedName = ` +const testAccGroupConfig_generatedName = ` resource "aws_cloudwatch_log_group" "test" {} ` diff --git a/internal/service/logs/groups_data_source.go b/internal/service/logs/groups_data_source.go index e48b2873b11..6ac2fe023c6 100644 --- a/internal/service/logs/groups_data_source.go +++ b/internal/service/logs/groups_data_source.go @@ -21,7 +21,7 @@ func DataSourceGroups() *schema.Resource { }, "log_group_name_prefix": { Type: schema.TypeString, - Required: true, + Optional: true, }, "log_group_names": { Type: schema.TypeSet, @@ -35,8 +35,10 @@ func DataSourceGroups() *schema.Resource { func dataSourceGroupsRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).LogsConn - input := &cloudwatchlogs.DescribeLogGroupsInput{ - LogGroupNamePrefix: aws.String(d.Get("log_group_name_prefix").(string)), + input := &cloudwatchlogs.DescribeLogGroupsInput{} + + if v, ok := d.GetOk("log_group_name_prefix"); ok { + input.LogGroupNamePrefix = aws.String(v.(string)) } var results []*cloudwatchlogs.LogGroup diff --git a/internal/service/logs/groups_data_source_test.go b/internal/service/logs/groups_data_source_test.go index 07031ebae86..2b312bbe1bb 100644 --- a/internal/service/logs/groups_data_source_test.go +++ b/internal/service/logs/groups_data_source_test.go @@ -20,7 +20,7 @@ func TestAccLogsGroupsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckGroupsDataSourceConfig(rName), + Config: testAccGroupsDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "arns.#", "2"), resource.TestCheckTypeSetElemAttrPair(resourceName, "arns.*", "aws_cloudwatch_log_group.test1", "arn"), @@ -34,7 +34,29 @@ func TestAccLogsGroupsDataSource_basic(t *testing.T) { }) } -func testAccCheckGroupsDataSourceConfig(rName string) string { +func TestAccLogsGroupsDataSource_noPrefix(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "data.aws_cloudwatch_log_groups.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, cloudwatchlogs.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccGroupsDataSourceConfig_noPrefix(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckTypeSetElemAttrPair(resourceName, "arns.*", "aws_cloudwatch_log_group.test1", "arn"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "arns.*", "aws_cloudwatch_log_group.test2", "arn"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "log_group_names.*", "aws_cloudwatch_log_group.test1", "name"), + resource.TestCheckTypeSetElemAttrPair(resourceName, "log_group_names.*", "aws_cloudwatch_log_group.test2", "name"), + ), + }, + }, + }) +} + +func testAccGroupsDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource aws_cloudwatch_log_group "test1" { name = "%[1]s/1" @@ -51,3 +73,19 @@ data aws_cloudwatch_log_groups "test" { } `, rName) } + +func testAccGroupsDataSourceConfig_noPrefix(rName string) string { + return fmt.Sprintf(` +resource aws_cloudwatch_log_group "test1" { + name = "%[1]s/1" +} + +resource aws_cloudwatch_log_group "test2" { + name = "%[1]s/2" +} + +data aws_cloudwatch_log_groups "test" { + depends_on = [aws_cloudwatch_log_group.test1,aws_cloudwatch_log_group.test2] +} +`, rName) +} diff --git a/internal/service/logs/metric_filter_test.go b/internal/service/logs/metric_filter_test.go index 6c1a300d7e6..228d4b17b88 100644 --- a/internal/service/logs/metric_filter_test.go +++ b/internal/service/logs/metric_filter_test.go @@ -26,7 +26,7 @@ func TestAccLogsMetricFilter_basic(t *testing.T) { CheckDestroy: testAccCheckMetricFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricFilterConfig(rInt), + Config: testAccMetricFilterConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMetricFilterExists(resourceName, &mf), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("MyAppAccessCount-%d", rInt)), @@ -52,7 +52,7 @@ func TestAccLogsMetricFilter_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMetricFilterModifiedConfig(rInt), + Config: testAccMetricFilterConfig_modified(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMetricFilterExists(resourceName, &mf), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("MyAppAccessCount-%d", rInt)), @@ -74,7 +74,7 @@ func TestAccLogsMetricFilter_basic(t *testing.T) { ), }, { - Config: testAccMetricFilterModifiedWithDimensionsConfig(rInt), + Config: testAccMetricFilterConfig_modifiedDimensions(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMetricFilterExists(resourceName, &mf), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("MyAppAccessCount-%d", rInt)), @@ -100,7 +100,7 @@ func TestAccLogsMetricFilter_basic(t *testing.T) { ), }, { - Config: testAccMetricFilterManyConfig(rInt), + Config: testAccMetricFilterConfig_many(rInt), Check: testAccCheckMetricFilterManyExist("aws_cloudwatch_log_metric_filter.test", &mf), }, }, @@ -119,7 +119,7 @@ func TestAccLogsMetricFilter_disappears(t *testing.T) { CheckDestroy: testAccCheckMetricFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricFilterConfig(rInt), + Config: testAccMetricFilterConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMetricFilterExists(resourceName, &mf), acctest.CheckResourceDisappears(acctest.Provider, tflogs.ResourceMetricFilter(), resourceName), @@ -142,7 +142,7 @@ func TestAccLogsMetricFilter_Disappears_logGroup(t *testing.T) { CheckDestroy: testAccCheckMetricFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccMetricFilterConfig(rInt), + Config: testAccMetricFilterConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMetricFilterExists(resourceName, &mf), acctest.CheckResourceDisappears(acctest.Provider, tflogs.ResourceGroup(), "aws_cloudwatch_log_group.test"), @@ -280,7 +280,7 @@ func testAccCheckMetricFilterManyExist(basename string, mf *cloudwatchlogs.Metri } } -func testAccMetricFilterConfig(rInt int) string { +func testAccMetricFilterConfig_basic(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_metric_filter" "test" { name = "MyAppAccessCount-%d" @@ -300,7 +300,7 @@ resource "aws_cloudwatch_log_group" "test" { `, rInt, rInt) } -func testAccMetricFilterModifiedConfig(rInt int) string { +func testAccMetricFilterConfig_modified(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_metric_filter" "test" { name = "MyAppAccessCount-%d" @@ -326,7 +326,7 @@ resource "aws_cloudwatch_log_group" "test" { `, rInt, rInt) } -func testAccMetricFilterModifiedWithDimensionsConfig(rInt int) string { +func testAccMetricFilterConfig_modifiedDimensions(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_metric_filter" "test" { name = "MyAppAccessCount-%d" @@ -355,7 +355,7 @@ resource "aws_cloudwatch_log_group" "test" { `, rInt, rInt) } -func testAccMetricFilterManyConfig(rInt int) string { +func testAccMetricFilterConfig_many(rInt int) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_metric_filter" "test" { count = 15 diff --git a/internal/service/logs/query_definition_test.go b/internal/service/logs/query_definition_test.go index 3b9584c2727..ebc3f127f11 100644 --- a/internal/service/logs/query_definition_test.go +++ b/internal/service/logs/query_definition_test.go @@ -35,7 +35,7 @@ func TestAccLogsQueryDefinition_basic(t *testing.T) { CheckDestroy: testAccCheckQueryDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccQueryDefinitionConfig_Basic(queryName), + Config: testAccQueryDefinitionConfig_basic(queryName), Check: resource.ComposeTestCheckFunc( testAccCheckQueryDefinitionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", queryName), @@ -80,7 +80,7 @@ func TestAccLogsQueryDefinition_disappears(t *testing.T) { CheckDestroy: testAccCheckQueryDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccQueryDefinitionConfig_Basic(queryName), + Config: testAccQueryDefinitionConfig_basic(queryName), Check: resource.ComposeTestCheckFunc( testAccCheckQueryDefinitionExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tflogs.ResourceQueryDefinition(), resourceName), @@ -104,14 +104,14 @@ func TestAccLogsQueryDefinition_rename(t *testing.T) { CheckDestroy: testAccCheckQueryDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccQueryDefinitionConfig_Basic(queryName), + Config: testAccQueryDefinitionConfig_basic(queryName), Check: resource.ComposeTestCheckFunc( testAccCheckQueryDefinitionExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "name", queryName), ), }, { - Config: testAccQueryDefinitionConfig_Basic(updatedQueryName), + Config: testAccQueryDefinitionConfig_basic(updatedQueryName), Check: resource.ComposeTestCheckFunc( testAccCheckQueryDefinitionExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "name", updatedQueryName), @@ -139,7 +139,7 @@ func TestAccLogsQueryDefinition_logGroups(t *testing.T) { CheckDestroy: testAccCheckQueryDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccQueryDefinitionConfig_LogGroups(queryName, 1), + Config: testAccQueryDefinitionConfig_logGroups(queryName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckQueryDefinitionExists(resourceName, &v1), resource.TestCheckResourceAttr(resourceName, "name", queryName), @@ -148,7 +148,7 @@ func TestAccLogsQueryDefinition_logGroups(t *testing.T) { ), }, { - Config: testAccQueryDefinitionConfig_LogGroups(queryName, 5), + Config: testAccQueryDefinitionConfig_logGroups(queryName, 5), Check: resource.ComposeTestCheckFunc( testAccCheckQueryDefinitionExists(resourceName, &v2), resource.TestCheckResourceAttr(resourceName, "name", queryName), @@ -212,7 +212,7 @@ func testAccCheckQueryDefinitionDestroy(s *terraform.State) error { return nil } -func testAccQueryDefinitionConfig_Basic(rName string) string { +func testAccQueryDefinitionConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_query_definition" "test" { name = %[1]q @@ -226,7 +226,7 @@ EOF `, rName) } -func testAccQueryDefinitionConfig_LogGroups(rName string, count int) string { +func testAccQueryDefinitionConfig_logGroups(rName string, count int) string { return fmt.Sprintf(` resource "aws_cloudwatch_query_definition" "test" { name = %[1]q diff --git a/internal/service/logs/resource_policy_test.go b/internal/service/logs/resource_policy_test.go index 61f8023c7d2..31477a1c477 100644 --- a/internal/service/logs/resource_policy_test.go +++ b/internal/service/logs/resource_policy_test.go @@ -25,7 +25,7 @@ func TestAccLogsResourcePolicy_basic(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckResourcePolicyResourceBasic1Config(rName), + Config: testAccResourcePolicyConfig_basic1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicy(resourceName, &resourcePolicy), resource.TestCheckResourceAttr(resourceName, "policy_name", rName), @@ -38,7 +38,7 @@ func TestAccLogsResourcePolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCheckResourcePolicyResourceBasic2Config(rName), + Config: testAccResourcePolicyConfig_basic2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicy(resourceName, &resourcePolicy), resource.TestCheckResourceAttr(resourceName, "policy_name", rName), @@ -61,7 +61,7 @@ func TestAccLogsResourcePolicy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckResourcePolicyResourceOrderConfig(rName), + Config: testAccResourcePolicyConfig_order(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicy(resourceName, &resourcePolicy), resource.TestCheckResourceAttr(resourceName, "policy_name", rName), @@ -69,7 +69,7 @@ func TestAccLogsResourcePolicy_ignoreEquivalent(t *testing.T) { ), }, { - Config: testAccCheckResourcePolicyResourceNewOrderConfig(rName), + Config: testAccResourcePolicyConfig_newOrder(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicy(resourceName, &resourcePolicy), resource.TestCheckResourceAttr(resourceName, "policy_name", rName), @@ -128,7 +128,7 @@ func testAccCheckResourcePolicyDestroy(s *terraform.State) error { return nil } -func testAccCheckResourcePolicyResourceBasic1Config(rName string) string { +func testAccResourcePolicyConfig_basic1(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -155,7 +155,7 @@ resource "aws_cloudwatch_log_resource_policy" "test" { `, rName) } -func testAccCheckResourcePolicyResourceBasic2Config(rName string) string { +func testAccResourcePolicyConfig_basic2(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -182,7 +182,7 @@ resource "aws_cloudwatch_log_resource_policy" "test" { `, rName) } -func testAccCheckResourcePolicyResourceOrderConfig(rName string) string { +func testAccResourcePolicyConfig_order(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -210,7 +210,7 @@ resource "aws_cloudwatch_log_resource_policy" "test" { `, rName) } -func testAccCheckResourcePolicyResourceNewOrderConfig(rName string) string { +func testAccResourcePolicyConfig_newOrder(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/logs/stream_test.go b/internal/service/logs/stream_test.go index e68d89b6624..9d4ee94cfdd 100644 --- a/internal/service/logs/stream_test.go +++ b/internal/service/logs/stream_test.go @@ -26,7 +26,7 @@ func TestAccLogsStream_basic(t *testing.T) { CheckDestroy: testAccCheckStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccStreamConfig(rName), + Config: testAccStreamConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStreamExists(resourceName, &ls), ), @@ -53,7 +53,7 @@ func TestAccLogsStream_disappears(t *testing.T) { CheckDestroy: testAccCheckStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccStreamConfig(rName), + Config: testAccStreamConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStreamExists(resourceName, &ls), acctest.CheckResourceDisappears(acctest.Provider, tflogs.ResourceStream(), resourceName), @@ -78,7 +78,7 @@ func TestAccLogsStream_Disappears_logGroup(t *testing.T) { CheckDestroy: testAccCheckStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccStreamConfig(rName), + Config: testAccStreamConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStreamExists(resourceName, &ls), testAccCheckGroupExists(logGroupResourceName, &lg), @@ -179,7 +179,7 @@ func TestValidateStreamName(t *testing.T) { } } -func testAccStreamConfig(rName string) string { +func testAccStreamConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = %[1]q diff --git a/internal/service/logs/subscription_filter_test.go b/internal/service/logs/subscription_filter_test.go index 9db6fc57074..2166b92f9cd 100644 --- a/internal/service/logs/subscription_filter_test.go +++ b/internal/service/logs/subscription_filter_test.go @@ -29,7 +29,7 @@ func TestAccLogsSubscriptionFilter_basic(t *testing.T) { CheckDestroy: testAccCheckSubscriptionFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccSubscriptionFilterDestinationARNLambdaConfig(rName), + Config: testAccSubscriptionFilterConfig_destinationARNLambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubscriptionFilterExists(resourceName, &filter), resource.TestCheckResourceAttrPair(resourceName, "destination_arn", lambdaFunctionResourceName, "arn"), @@ -62,7 +62,7 @@ func TestAccLogsSubscriptionFilter_many(t *testing.T) { CheckDestroy: testAccCheckSubscriptionFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccSubscriptionFilterDestinationARNLambdaConfigMany(rName), + Config: testAccSubscriptionFilterConfig_destinationARNLambdaMany(rName), Check: testAccCheckSubscriptionFilterManyExists(resourceName, &sf), }, }, @@ -82,7 +82,7 @@ func TestAccLogsSubscriptionFilter_disappears(t *testing.T) { CheckDestroy: testAccCheckSubscriptionFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccSubscriptionFilterDestinationARNLambdaConfig(rName), + Config: testAccSubscriptionFilterConfig_destinationARNLambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubscriptionFilterExists(resourceName, &filter), acctest.CheckResourceDisappears(acctest.Provider, tflogs.ResourceSubscriptionFilter(), resourceName), @@ -108,7 +108,7 @@ func TestAccLogsSubscriptionFilter_Disappears_logGroup(t *testing.T) { CheckDestroy: testAccCheckSubscriptionFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccSubscriptionFilterDestinationARNLambdaConfig(rName), + Config: testAccSubscriptionFilterConfig_destinationARNLambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubscriptionFilterExists(resourceName, &filter), testAccCheckGroupExists(logGroupResourceName, &logGroup), @@ -134,7 +134,7 @@ func TestAccLogsSubscriptionFilter_DestinationARN_kinesisDataFirehose(t *testing CheckDestroy: testAccCheckSubscriptionFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccSubscriptionFilterDestinationARNKinesisDataFirehoseConfig(rName), + Config: testAccSubscriptionFilterConfig_destinationARNKinesisDataFirehose(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubscriptionFilterExists(resourceName, &filter), resource.TestCheckResourceAttrPair(resourceName, "destination_arn", firehoseResourceName, "arn"), @@ -164,7 +164,7 @@ func TestAccLogsSubscriptionFilter_DestinationARN_kinesisStream(t *testing.T) { CheckDestroy: testAccCheckSubscriptionFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccSubscriptionFilterDestinationARNKinesisStreamConfig(rName), + Config: testAccSubscriptionFilterConfig_destinationARNKinesisStream(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubscriptionFilterExists(resourceName, &filter), resource.TestCheckResourceAttrPair(resourceName, "destination_arn", kinesisStream, "arn"), @@ -193,7 +193,7 @@ func TestAccLogsSubscriptionFilter_distribution(t *testing.T) { CheckDestroy: testAccCheckSubscriptionFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccSubscriptionFilterDistributionConfig(rName, "Random"), + Config: testAccSubscriptionFilterConfig_distribution(rName, "Random"), Check: resource.ComposeTestCheckFunc( testAccCheckSubscriptionFilterExists(resourceName, &filter), resource.TestCheckResourceAttr(resourceName, "distribution", "Random"), @@ -206,7 +206,7 @@ func TestAccLogsSubscriptionFilter_distribution(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubscriptionFilterDistributionConfig(rName, "ByLogStream"), + Config: testAccSubscriptionFilterConfig_distribution(rName, "ByLogStream"), Check: resource.ComposeTestCheckFunc( testAccCheckSubscriptionFilterExists(resourceName, &filter), resource.TestCheckResourceAttr(resourceName, "distribution", "ByLogStream"), @@ -231,7 +231,7 @@ func TestAccLogsSubscriptionFilter_roleARN(t *testing.T) { CheckDestroy: testAccCheckSubscriptionFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccSubscriptionFilterRoleARN1Config(rName), + Config: testAccSubscriptionFilterConfig_roleARN1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubscriptionFilterExists(resourceName, &filter), resource.TestCheckResourceAttrPair(resourceName, "role_arn", iamRoleResourceName1, "arn"), @@ -244,7 +244,7 @@ func TestAccLogsSubscriptionFilter_roleARN(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubscriptionFilterRoleARN2Config(rName), + Config: testAccSubscriptionFilterConfig_roleARN2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubscriptionFilterExists(resourceName, &filter), resource.TestCheckResourceAttrPair(resourceName, "role_arn", iamRoleResourceName2, "arn"), @@ -641,7 +641,7 @@ resource "aws_lambda_permission" "test" { `, rName) } -func testAccSubscriptionFilterDestinationARNKinesisDataFirehoseConfig(rName string) string { +func testAccSubscriptionFilterConfig_destinationARNKinesisDataFirehose(rName string) string { return testAccSubscriptionFilterKinesisDataFirehoseBaseConfig(rName) + fmt.Sprintf(` resource "aws_cloudwatch_log_subscription_filter" "test" { destination_arn = aws_kinesis_firehose_delivery_stream.test.arn @@ -653,7 +653,7 @@ resource "aws_cloudwatch_log_subscription_filter" "test" { `, rName) } -func testAccSubscriptionFilterDestinationARNKinesisStreamConfig(rName string) string { +func testAccSubscriptionFilterConfig_destinationARNKinesisStream(rName string) string { return testAccSubscriptionFilterKinesisStreamBaseConfig(rName) + fmt.Sprintf(` resource "aws_cloudwatch_log_subscription_filter" "test" { destination_arn = aws_kinesis_stream.test.arn @@ -665,7 +665,7 @@ resource "aws_cloudwatch_log_subscription_filter" "test" { `, rName) } -func testAccSubscriptionFilterDestinationARNLambdaConfig(rName string) string { +func testAccSubscriptionFilterConfig_destinationARNLambda(rName string) string { return testAccSubscriptionFilterLambdaBaseConfig(rName) + fmt.Sprintf(` resource "aws_cloudwatch_log_subscription_filter" "test" { destination_arn = aws_lambda_function.test.arn @@ -676,7 +676,7 @@ resource "aws_cloudwatch_log_subscription_filter" "test" { `, rName) } -func testAccSubscriptionFilterDistributionConfig(rName, distribution string) string { +func testAccSubscriptionFilterConfig_distribution(rName, distribution string) string { return testAccSubscriptionFilterLambdaBaseConfig(rName) + fmt.Sprintf(` resource "aws_cloudwatch_log_subscription_filter" "test" { destination_arn = aws_lambda_function.test.arn @@ -688,7 +688,7 @@ resource "aws_cloudwatch_log_subscription_filter" "test" { `, rName, distribution) } -func testAccSubscriptionFilterDestinationARNLambdaConfigMany(rName string) string { +func testAccSubscriptionFilterConfig_destinationARNLambdaMany(rName string) string { return testAccSubscriptionFilterLambdaConfigMany(rName) + fmt.Sprintf(` resource "aws_cloudwatch_log_subscription_filter" "test" { count = 2 # This is the default limit of subscription filters on an account @@ -701,7 +701,7 @@ resource "aws_cloudwatch_log_subscription_filter" "test" { `, rName) } -func testAccSubscriptionFilterRoleARN1Config(rName string) string { +func testAccSubscriptionFilterConfig_roleARN1(rName string) string { return testAccSubscriptionFilterKinesisStreamBaseConfig(rName) + fmt.Sprintf(` resource "aws_cloudwatch_log_subscription_filter" "test" { destination_arn = aws_kinesis_stream.test.arn @@ -713,7 +713,7 @@ resource "aws_cloudwatch_log_subscription_filter" "test" { `, rName) } -func testAccSubscriptionFilterRoleARN2Config(rName string) string { +func testAccSubscriptionFilterConfig_roleARN2(rName string) string { return testAccSubscriptionFilterKinesisStreamBaseConfig(rName) + fmt.Sprintf(` resource "aws_iam_role" "test2" { name = "%[1]s-2" diff --git a/internal/service/mediaconvert/queue.go b/internal/service/mediaconvert/queue.go index c5cf62b486c..d948c260058 100644 --- a/internal/service/mediaconvert/queue.go +++ b/internal/service/mediaconvert/queue.go @@ -122,7 +122,7 @@ func resourceQueueCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateQueue(createOpts) if err != nil { - return fmt.Errorf("Error creating Media Convert Queue: %s", err) + return fmt.Errorf("Error creating Media Convert Queue: %w", err) } d.SetId(aws.StringValue(resp.Queue.Name)) @@ -133,7 +133,7 @@ func resourceQueueCreate(d *schema.ResourceData, meta interface{}) error { func resourceQueueRead(d *schema.ResourceData, meta interface{}) error { conn, err := GetAccountClient(meta.(*conns.AWSClient)) if err != nil { - return fmt.Errorf("Error getting Media Convert Account Client: %s", err) + return fmt.Errorf("Error getting Media Convert Account Client: %w", err) } defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig @@ -144,13 +144,13 @@ func resourceQueueRead(d *schema.ResourceData, meta interface{}) error { } resp, err := conn.GetQueue(getOpts) - if tfawserr.ErrCodeEquals(err, mediaconvert.ErrCodeNotFoundException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, mediaconvert.ErrCodeNotFoundException) { log.Printf("[WARN] Media Convert Queue (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("Error getting Media Convert Queue: %s", err) + return fmt.Errorf("Error getting Media Convert Queue: %w", err) } d.Set("arn", resp.Queue.Arn) @@ -160,13 +160,13 @@ func resourceQueueRead(d *schema.ResourceData, meta interface{}) error { d.Set("status", resp.Queue.Status) if err := d.Set("reservation_plan_settings", flattenReservationPlan(resp.Queue.ReservationPlan)); err != nil { - return fmt.Errorf("Error setting Media Convert Queue reservation_plan_settings: %s", err) + return fmt.Errorf("error setting Media Convert Queue reservation_plan_settings: %w", err) } tags, err := ListTags(conn, aws.StringValue(resp.Queue.Arn)) if err != nil { - return fmt.Errorf("error listing tags for Media Convert Queue (%s): %s", d.Id(), err) + return fmt.Errorf("error listing tags for Media Convert Queue (%s): %w", d.Id(), err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -186,7 +186,7 @@ func resourceQueueRead(d *schema.ResourceData, meta interface{}) error { func resourceQueueUpdate(d *schema.ResourceData, meta interface{}) error { conn, err := GetAccountClient(meta.(*conns.AWSClient)) if err != nil { - return fmt.Errorf("Error getting Media Convert Account Client: %s", err) + return fmt.Errorf("Error getting Media Convert Account Client: %w", err) } if d.HasChanges("description", "reservation_plan_settings", "status") { @@ -206,20 +206,15 @@ func resourceQueueUpdate(d *schema.ResourceData, meta interface{}) error { } _, err = conn.UpdateQueue(updateOpts) - if tfawserr.ErrCodeEquals(err, mediaconvert.ErrCodeNotFoundException) { - log.Printf("[WARN] Media Convert Queue (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } if err != nil { - return fmt.Errorf("Error updating Media Convert Queue: %s", err) + return fmt.Errorf("Error updating Media Convert Queue (%s): %w", d.Id(), err) } } if d.HasChange("tags_all") { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating tags: %s", err) + return fmt.Errorf("error updating tags: %w", err) } } @@ -229,7 +224,7 @@ func resourceQueueUpdate(d *schema.ResourceData, meta interface{}) error { func resourceQueueDelete(d *schema.ResourceData, meta interface{}) error { conn, err := GetAccountClient(meta.(*conns.AWSClient)) if err != nil { - return fmt.Errorf("Error getting Media Convert Account Client: %s", err) + return fmt.Errorf("Error getting Media Convert Account Client: %w", err) } delOpts := &mediaconvert.DeleteQueueInput{ @@ -241,7 +236,7 @@ func resourceQueueDelete(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("Error deleting Media Convert Queue: %s", err) + return fmt.Errorf("Error deleting Media Convert Queue (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/memorydb/acl_data_source_test.go b/internal/service/memorydb/acl_data_source_test.go index 740e6a1e2f8..dcbfb6d2a88 100644 --- a/internal/service/memorydb/acl_data_source_test.go +++ b/internal/service/memorydb/acl_data_source_test.go @@ -23,7 +23,7 @@ func TestAccMemoryDBACLDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccACLDataSourceConfig(rName, userName1, userName2), + Config: testAccACLDataSourceConfig_basic(rName, userName1, userName2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "minimum_engine_version", resourceName, "minimum_engine_version"), @@ -39,7 +39,7 @@ func TestAccMemoryDBACLDataSource_basic(t *testing.T) { }) } -func testAccACLDataSourceConfig(rName, userName1, userName2 string) string { +func testAccACLDataSourceConfig_basic(rName, userName1, userName2 string) string { return acctest.ConfigCompose( testAccACLConfigUsers(userName1, userName2), fmt.Sprintf(` diff --git a/internal/service/memorydb/acl_test.go b/internal/service/memorydb/acl_test.go index 05daa298433..6ff8a30b69b 100644 --- a/internal/service/memorydb/acl_test.go +++ b/internal/service/memorydb/acl_test.go @@ -28,7 +28,7 @@ func TestAccMemoryDBACL_basic(t *testing.T) { CheckDestroy: testAccCheckACLDestroy, Steps: []resource.TestStep{ { - Config: testAccACLConfig(rName, []string{user1}, []string{user1}), + Config: testAccACLConfig_basic(rName, []string{user1}, []string{user1}), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "memorydb", "acl/"+rName), @@ -60,7 +60,7 @@ func TestAccMemoryDBACL_disappears(t *testing.T) { CheckDestroy: testAccCheckACLDestroy, Steps: []resource.TestStep{ { - Config: testAccACLConfig(rName, nil, nil), + Config: testAccACLConfig_basic(rName, nil, nil), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfmemorydb.ResourceACL(), resourceName), @@ -81,7 +81,7 @@ func TestAccMemoryDBACL_nameGenerated(t *testing.T) { CheckDestroy: testAccCheckACLDestroy, Steps: []resource.TestStep{ { - Config: testAccACLConfig_withNoName(), + Config: testAccACLConfig_noName(), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -102,7 +102,7 @@ func TestAccMemoryDBACL_namePrefix(t *testing.T) { CheckDestroy: testAccCheckACLDestroy, Steps: []resource.TestStep{ { - Config: testAccACLConfig_withNamePrefix("tftest-"), + Config: testAccACLConfig_namePrefix("tftest-"), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tftest-"), @@ -124,7 +124,7 @@ func TestAccMemoryDBACL_update_tags(t *testing.T) { CheckDestroy: testAccCheckACLDestroy, Steps: []resource.TestStep{ { - Config: testAccACLConfig_withTags0(rName), + Config: testAccACLConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -137,7 +137,7 @@ func TestAccMemoryDBACL_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccACLConfig_withTags2(rName, "Key1", "value1", "Key2", "value2"), + Config: testAccACLConfig_tags2(rName, "Key1", "value1", "Key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -154,7 +154,7 @@ func TestAccMemoryDBACL_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccACLConfig_withTags1(rName, "Key1", "value1"), + Config: testAccACLConfig_tags1(rName, "Key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -169,7 +169,7 @@ func TestAccMemoryDBACL_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccACLConfig_withTags0(rName), + Config: testAccACLConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -200,7 +200,7 @@ func TestAccMemoryDBACL_update_userNames(t *testing.T) { Steps: []resource.TestStep{ { // Empty ACL. - Config: testAccACLConfig(rName, []string{}, []string{}), + Config: testAccACLConfig_basic(rName, []string{}, []string{}), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "user_names.#", "0"), @@ -213,7 +213,7 @@ func TestAccMemoryDBACL_update_userNames(t *testing.T) { }, { // Adding users. - Config: testAccACLConfig(rName, []string{user1, user2}, []string{user1, user2}), + Config: testAccACLConfig_basic(rName, []string{user1, user2}, []string{user1, user2}), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "user_names.#", "2"), @@ -228,7 +228,7 @@ func TestAccMemoryDBACL_update_userNames(t *testing.T) { }, { // Removing and adding a user. - Config: testAccACLConfig(rName, []string{user1, user2, user3}, []string{user1, user3}), + Config: testAccACLConfig_basic(rName, []string{user1, user2, user3}, []string{user1, user3}), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "user_names.#", "2"), @@ -243,7 +243,7 @@ func TestAccMemoryDBACL_update_userNames(t *testing.T) { }, { // Removing a user. - Config: testAccACLConfig(rName, []string{user1, user2, user3}, []string{user1}), + Config: testAccACLConfig_basic(rName, []string{user1, user2, user3}, []string{user1}), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "user_names.#", "1"), @@ -256,7 +256,7 @@ func TestAccMemoryDBACL_update_userNames(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccACLConfig(rName, []string{user1, user2}, []string{user1, user2}), + Config: testAccACLConfig_basic(rName, []string{user1, user2}, []string{user1, user2}), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "user_names.#", "2"), @@ -271,7 +271,7 @@ func TestAccMemoryDBACL_update_userNames(t *testing.T) { }, { // Deleting a user before disassociating it. - Config: testAccACLConfig(rName, []string{user1}, []string{user1}), + Config: testAccACLConfig_basic(rName, []string{user1}, []string{user1}), Check: resource.ComposeTestCheckFunc( testAccCheckACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "user_names.#", "1"), @@ -361,7 +361,7 @@ resource "aws_memorydb_user" "test" { `, userNames) } -func testAccACLConfig(rName string, userNames []string, usersInACL []string) string { +func testAccACLConfig_basic(rName string, userNames []string, usersInACL []string) string { var userNamesInACL string for i, userName := range usersInACL { if i > 0 { @@ -387,13 +387,13 @@ resource "aws_memorydb_acl" "test" { ) } -func testAccACLConfig_withNoName() string { +func testAccACLConfig_noName() string { return ` resource "aws_memorydb_acl" "test" {} ` } -func testAccACLConfig_withNamePrefix(namePrefix string) string { +func testAccACLConfig_namePrefix(namePrefix string) string { return fmt.Sprintf(` resource "aws_memorydb_acl" "test" { name_prefix = %[1]q @@ -401,7 +401,7 @@ resource "aws_memorydb_acl" "test" { `, namePrefix) } -func testAccACLConfig_withTags0(rName string) string { +func testAccACLConfig_tags0(rName string) string { return fmt.Sprintf(` resource "aws_memorydb_acl" "test" { name = %[1]q @@ -409,7 +409,7 @@ resource "aws_memorydb_acl" "test" { `, rName) } -func testAccACLConfig_withTags1(rName, tagKey1, tagValue1 string) string { +func testAccACLConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_memorydb_acl" "test" { name = %[1]q @@ -421,7 +421,7 @@ resource "aws_memorydb_acl" "test" { `, rName, tagKey1, tagValue1) } -func testAccACLConfig_withTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccACLConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_memorydb_acl" "test" { name = %[1]q diff --git a/internal/service/memorydb/cluster_data_source_test.go b/internal/service/memorydb/cluster_data_source_test.go index 2b7735fb66e..d7d87cdedb2 100644 --- a/internal/service/memorydb/cluster_data_source_test.go +++ b/internal/service/memorydb/cluster_data_source_test.go @@ -21,7 +21,7 @@ func TestAccMemoryDBClusterDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccClusterDataSourceConfig(rName), + Config: testAccClusterDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "acl_name", resourceName, "acl_name"), resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), @@ -64,9 +64,9 @@ func TestAccMemoryDBClusterDataSource_basic(t *testing.T) { }) } -func testAccClusterDataSourceConfig(rName string) string { +func testAccClusterDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), testAccClusterConfigBaseUserAndACL(rName), fmt.Sprintf(` resource "aws_security_group" "test" { diff --git a/internal/service/memorydb/cluster_test.go b/internal/service/memorydb/cluster_test.go index e80449b39dc..75c371c753b 100644 --- a/internal/service/memorydb/cluster_test.go +++ b/internal/service/memorydb/cluster_test.go @@ -158,7 +158,7 @@ func TestAccMemoryDBCluster_nameGenerated(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withNoName(rName), + Config: testAccClusterConfig_noName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -180,7 +180,7 @@ func TestAccMemoryDBCluster_namePrefix(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withNamePrefix(rName, "tftest-"), + Config: testAccClusterConfig_namePrefix(rName, "tftest-"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tftest-"), @@ -204,7 +204,7 @@ func TestAccMemoryDBCluster_create_noTLS(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withNoTLS(rName), + Config: testAccClusterConfig_noTLS(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tls_enabled", "false"), @@ -230,7 +230,7 @@ func TestAccMemoryDBCluster_create_withKMS(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withKMS(rName), + Config: testAccClusterConfig_kms(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "kms_key_arn", "aws_kms_key.test", "arn"), @@ -256,7 +256,7 @@ func TestAccMemoryDBCluster_create_withPort(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withPort(rName, 9999), + Config: testAccClusterConfig_port(rName, 9999), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cluster_endpoint.0.port", "9999"), @@ -283,7 +283,7 @@ func TestAccMemoryDBCluster_create_fromSnapshot(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withSnapshotFromCluster(rName1, rName2), + Config: testAccClusterConfig_snapshotFrom(rName1, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists("aws_memorydb_cluster.test1"), testAccCheckClusterExists("aws_memorydb_cluster.test2"), @@ -304,7 +304,7 @@ func TestAccMemoryDBCluster_delete_withFinalSnapshot(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withFinalSnapshotName(rName, rName+"-1"), + Config: testAccClusterConfig_finalSnapshotName(rName, rName+"-1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "final_snapshot_name", rName+"-1"), @@ -317,7 +317,7 @@ func TestAccMemoryDBCluster_delete_withFinalSnapshot(t *testing.T) { ImportStateVerifyIgnore: []string{"final_snapshot_name"}, }, { - Config: testAccClusterConfig_withFinalSnapshotName(rName, rName), + Config: testAccClusterConfig_finalSnapshotName(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "final_snapshot_name", rName), @@ -330,7 +330,7 @@ func TestAccMemoryDBCluster_delete_withFinalSnapshot(t *testing.T) { ImportStateVerifyIgnore: []string{"final_snapshot_name"}, }, { - Config: testAccClusterConfigBaseNetwork(rName), // empty Config not supported + Config: testAccClusterConfig_baseNetwork(rName), // empty Config not supported Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExistsByName(rName), ), @@ -339,7 +339,7 @@ func TestAccMemoryDBCluster_delete_withFinalSnapshot(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_aclName(t *testing.T) { +func TestAccMemoryDBCluster_Update_aclName(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -350,7 +350,7 @@ func TestAccMemoryDBCluster_update_aclName(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withACLName(rName, rName), + Config: testAccClusterConfig_aclName(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acl_name", rName), @@ -362,7 +362,7 @@ func TestAccMemoryDBCluster_update_aclName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withACLName(rName, "open-access"), + Config: testAccClusterConfig_aclName(rName, "open-access"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acl_name", "open-access"), @@ -377,7 +377,7 @@ func TestAccMemoryDBCluster_update_aclName(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_description(t *testing.T) { +func TestAccMemoryDBCluster_Update_description(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -388,7 +388,7 @@ func TestAccMemoryDBCluster_update_description(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withDescription(rName, "Test 1"), + Config: testAccClusterConfig_description(rName, "Test 1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "Test 1"), @@ -400,7 +400,7 @@ func TestAccMemoryDBCluster_update_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withDescription(rName, "Test 2"), + Config: testAccClusterConfig_description(rName, "Test 2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "Test 2"), @@ -412,7 +412,7 @@ func TestAccMemoryDBCluster_update_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withDescription(rName, ""), + Config: testAccClusterConfig_description(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -427,7 +427,7 @@ func TestAccMemoryDBCluster_update_description(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_engineVersion(t *testing.T) { +func TestAccMemoryDBCluster_Update_engineVersion(t *testing.T) { // As of writing, 6.2 is the one and only MemoryDB engine version available, // so we cannot check upgrade behaviour. // @@ -444,7 +444,7 @@ func TestAccMemoryDBCluster_update_engineVersion(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withEngineVersionNull(rName), + Config: testAccClusterConfig_engineVersionNull(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "engine_version", "6.2"), @@ -456,7 +456,7 @@ func TestAccMemoryDBCluster_update_engineVersion(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withEngineVersion(rName, "6.2"), + Config: testAccClusterConfig_engineVersion(rName, "6.2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "engine_version", "6.2"), @@ -471,7 +471,7 @@ func TestAccMemoryDBCluster_update_engineVersion(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_maintenanceWindow(t *testing.T) { +func TestAccMemoryDBCluster_Update_maintenanceWindow(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -482,7 +482,7 @@ func TestAccMemoryDBCluster_update_maintenanceWindow(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withMaintenanceWindow(rName, "thu:09:00-thu:10:00"), + Config: testAccClusterConfig_maintenanceWindow(rName, "thu:09:00-thu:10:00"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "maintenance_window", "thu:09:00-thu:10:00"), @@ -494,7 +494,7 @@ func TestAccMemoryDBCluster_update_maintenanceWindow(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withMaintenanceWindow(rName, "fri:09:00-fri:10:00"), + Config: testAccClusterConfig_maintenanceWindow(rName, "fri:09:00-fri:10:00"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "maintenance_window", "fri:09:00-fri:10:00"), @@ -509,7 +509,7 @@ func TestAccMemoryDBCluster_update_maintenanceWindow(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_nodeType(t *testing.T) { +func TestAccMemoryDBCluster_Update_nodeType(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -520,7 +520,7 @@ func TestAccMemoryDBCluster_update_nodeType(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withNodeType(rName, "db.t4g.small"), + Config: testAccClusterConfig_nodeType(rName, "db.t4g.small"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "node_type", "db.t4g.small"), @@ -532,7 +532,7 @@ func TestAccMemoryDBCluster_update_nodeType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withNodeType(rName, "db.t4g.medium"), + Config: testAccClusterConfig_nodeType(rName, "db.t4g.medium"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "node_type", "db.t4g.medium"), @@ -547,7 +547,7 @@ func TestAccMemoryDBCluster_update_nodeType(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_numShards_scaleUp(t *testing.T) { +func TestAccMemoryDBCluster_Update_numShards_scaleUp(t *testing.T) { // As updating MemoryDB clusters can be slow, scaling up and down have been // split into separate tests for timeout management @@ -561,7 +561,7 @@ func TestAccMemoryDBCluster_update_numShards_scaleUp(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withNumShards(rName, 1), + Config: testAccClusterConfig_numShards(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "num_shards", "1"), @@ -573,7 +573,7 @@ func TestAccMemoryDBCluster_update_numShards_scaleUp(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withNumShards(rName, 2), + Config: testAccClusterConfig_numShards(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "num_shards", "2"), @@ -583,7 +583,7 @@ func TestAccMemoryDBCluster_update_numShards_scaleUp(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_numShards_scaleDown(t *testing.T) { +func TestAccMemoryDBCluster_Update_numShards_scaleDown(t *testing.T) { // As updating MemoryDB clusters can be slow, scaling up and down have been // split into separate tests for timeout management @@ -597,7 +597,7 @@ func TestAccMemoryDBCluster_update_numShards_scaleDown(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withNumShards(rName, 2), + Config: testAccClusterConfig_numShards(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "num_shards", "2"), @@ -609,7 +609,7 @@ func TestAccMemoryDBCluster_update_numShards_scaleDown(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withNumShards(rName, 1), + Config: testAccClusterConfig_numShards(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "num_shards", "1"), @@ -619,7 +619,7 @@ func TestAccMemoryDBCluster_update_numShards_scaleDown(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_numReplicasPerShard_scaleUp(t *testing.T) { +func TestAccMemoryDBCluster_Update_numReplicasPerShard_scaleUp(t *testing.T) { // As updating MemoryDB clusters can be slow, scaling up and down have been // split into separate tests for timeout management @@ -633,7 +633,7 @@ func TestAccMemoryDBCluster_update_numReplicasPerShard_scaleUp(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withNumReplicasPerShard(rName, 1), + Config: testAccClusterConfig_numReplicasPerShard(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "num_replicas_per_shard", "1"), @@ -645,7 +645,7 @@ func TestAccMemoryDBCluster_update_numReplicasPerShard_scaleUp(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withNumReplicasPerShard(rName, 2), + Config: testAccClusterConfig_numReplicasPerShard(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "num_replicas_per_shard", "2"), @@ -655,7 +655,7 @@ func TestAccMemoryDBCluster_update_numReplicasPerShard_scaleUp(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_numReplicasPerShard_scaleDown(t *testing.T) { +func TestAccMemoryDBCluster_Update_numReplicasPerShard_scaleDown(t *testing.T) { // As updating MemoryDB clusters can be slow, scaling up and down have been // split into separate tests for timeout management @@ -669,7 +669,7 @@ func TestAccMemoryDBCluster_update_numReplicasPerShard_scaleDown(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withNumReplicasPerShard(rName, 1), + Config: testAccClusterConfig_numReplicasPerShard(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "num_replicas_per_shard", "1"), @@ -681,7 +681,7 @@ func TestAccMemoryDBCluster_update_numReplicasPerShard_scaleDown(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withNumReplicasPerShard(rName, 0), + Config: testAccClusterConfig_numReplicasPerShard(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "num_replicas_per_shard", "0"), @@ -691,7 +691,7 @@ func TestAccMemoryDBCluster_update_numReplicasPerShard_scaleDown(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_parameterGroup(t *testing.T) { +func TestAccMemoryDBCluster_Update_parameterGroup(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -702,7 +702,7 @@ func TestAccMemoryDBCluster_update_parameterGroup(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withParameterGroup(rName, "default.memorydb-redis6"), + Config: testAccClusterConfig_parameterGroup(rName, "default.memorydb-redis6"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter_group_name", "default.memorydb-redis6"), @@ -714,14 +714,14 @@ func TestAccMemoryDBCluster_update_parameterGroup(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withParameterGroup(rName, rName), + Config: testAccClusterConfig_parameterGroup(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter_group_name", rName), ), }, { - Config: testAccClusterConfig_withParameterGroup(rName, "default.memorydb-redis6"), + Config: testAccClusterConfig_parameterGroup(rName, "default.memorydb-redis6"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter_group_name", "default.memorydb-redis6"), @@ -736,7 +736,7 @@ func TestAccMemoryDBCluster_update_parameterGroup(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_securityGroupIds(t *testing.T) { +func TestAccMemoryDBCluster_Update_securityGroupIds(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -747,7 +747,7 @@ func TestAccMemoryDBCluster_update_securityGroupIds(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withSecurityGroups(rName, 2, 1), + Config: testAccClusterConfig_securityGroups(rName, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), @@ -760,7 +760,7 @@ func TestAccMemoryDBCluster_update_securityGroupIds(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withSecurityGroups(rName, 2, 2), + Config: testAccClusterConfig_securityGroups(rName, 2, 2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "2"), // add one @@ -774,11 +774,11 @@ func TestAccMemoryDBCluster_update_securityGroupIds(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withSecurityGroups(rName, 2, 0), // attempt to remove all + Config: testAccClusterConfig_securityGroups(rName, 2, 0), // attempt to remove all ExpectError: regexp.MustCompile(`removing all security groups is not possible`), }, { - Config: testAccClusterConfig_withSecurityGroups(rName, 2, 1), + Config: testAccClusterConfig_securityGroups(rName, 2, 1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), // remove one @@ -794,7 +794,7 @@ func TestAccMemoryDBCluster_update_securityGroupIds(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_snapshotRetentionLimit(t *testing.T) { +func TestAccMemoryDBCluster_Update_snapshotRetentionLimit(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -805,7 +805,7 @@ func TestAccMemoryDBCluster_update_snapshotRetentionLimit(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withSnapshotRetentionLimit(rName, 2), + Config: testAccClusterConfig_snapshotRetentionLimit(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "snapshot_retention_limit", "2"), @@ -817,7 +817,7 @@ func TestAccMemoryDBCluster_update_snapshotRetentionLimit(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withSnapshotRetentionLimit(rName, 35), + Config: testAccClusterConfig_snapshotRetentionLimit(rName, 35), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "snapshot_retention_limit", "35"), @@ -829,7 +829,7 @@ func TestAccMemoryDBCluster_update_snapshotRetentionLimit(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withSnapshotRetentionLimit(rName, 0), + Config: testAccClusterConfig_snapshotRetentionLimit(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "snapshot_retention_limit", "0"), @@ -844,7 +844,7 @@ func TestAccMemoryDBCluster_update_snapshotRetentionLimit(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_snapshotWindow(t *testing.T) { +func TestAccMemoryDBCluster_Update_snapshotWindow(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -855,7 +855,7 @@ func TestAccMemoryDBCluster_update_snapshotWindow(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withSnapshotWindow(rName, "00:30-01:30"), + Config: testAccClusterConfig_snapshotWindow(rName, "00:30-01:30"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "snapshot_window", "00:30-01:30"), @@ -867,7 +867,7 @@ func TestAccMemoryDBCluster_update_snapshotWindow(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withSnapshotWindow(rName, "02:30-03:30"), + Config: testAccClusterConfig_snapshotWindow(rName, "02:30-03:30"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "snapshot_window", "02:30-03:30"), @@ -882,7 +882,7 @@ func TestAccMemoryDBCluster_update_snapshotWindow(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_snsTopicArn(t *testing.T) { +func TestAccMemoryDBCluster_Update_snsTopicARN(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -893,7 +893,7 @@ func TestAccMemoryDBCluster_update_snsTopicArn(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withSnsTopic(rName), + Config: testAccClusterConfig_snsTopic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "sns_topic_arn", "aws_sns_topic.test", "arn"), @@ -905,7 +905,7 @@ func TestAccMemoryDBCluster_update_snsTopicArn(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withSnsTopicNull(rName), + Config: testAccClusterConfig_snsTopicNull(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "sns_topic_arn", ""), @@ -917,7 +917,7 @@ func TestAccMemoryDBCluster_update_snsTopicArn(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withSnsTopic(rName), + Config: testAccClusterConfig_snsTopic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "sns_topic_arn", "aws_sns_topic.test", "arn"), @@ -932,7 +932,7 @@ func TestAccMemoryDBCluster_update_snsTopicArn(t *testing.T) { }) } -func TestAccMemoryDBCluster_update_tags(t *testing.T) { +func TestAccMemoryDBCluster_Update_tags(t *testing.T) { rName := "tf-test-" + sdkacctest.RandString(8) resourceName := "aws_memorydb_cluster.test" @@ -943,7 +943,7 @@ func TestAccMemoryDBCluster_update_tags(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_withTags0(rName), + Config: testAccClusterConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -956,7 +956,7 @@ func TestAccMemoryDBCluster_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withTags2(rName, "Key1", "value1", "Key2", "value2"), + Config: testAccClusterConfig_tags2(rName, "Key1", "value1", "Key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -973,7 +973,7 @@ func TestAccMemoryDBCluster_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withTags1(rName, "Key1", "value1"), + Config: testAccClusterConfig_tags1(rName, "Key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -988,7 +988,7 @@ func TestAccMemoryDBCluster_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterConfig_withTags0(rName), + Config: testAccClusterConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -1069,9 +1069,9 @@ func testAccCheckSnapshotExistsByName(snapshotName string) resource.TestCheckFun } } -func testAccClusterConfigBaseNetwork(rName string) string { +func testAccClusterConfig_baseNetwork(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), ` resource "aws_memorydb_subnet_group" "test" { subnet_ids = aws_subnet.test.*.id @@ -1101,7 +1101,7 @@ resource "aws_memorydb_acl" "test" { func testAccClusterConfig_basic(rName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), testAccClusterConfigBaseUserAndACL(rName), fmt.Sprintf(` resource "aws_security_group" "test" { @@ -1140,9 +1140,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withNoName(rName string) string { +func testAccClusterConfig_noName(rName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), ` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1155,9 +1155,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withNamePrefix(rName, prefix string) string { +func testAccClusterConfig_namePrefix(rName, prefix string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1171,9 +1171,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withNoTLS(rName string) string { +func testAccClusterConfig_noTLS(rName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1188,9 +1188,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withACLName(rName, aclName string) string { +func testAccClusterConfig_aclName(rName, aclName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), testAccClusterConfigBaseUserAndACL(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { @@ -1206,9 +1206,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withDescription(rName, description string) string { +func testAccClusterConfig_description(rName, description string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1221,9 +1221,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withEngineVersionNull(rName string) string { +func testAccClusterConfig_engineVersionNull(rName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1237,9 +1237,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withEngineVersion(rName, engineVersion string) string { +func testAccClusterConfig_engineVersion(rName, engineVersion string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1254,9 +1254,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withFinalSnapshotName(rName, finalSnapshotName string) string { +func testAccClusterConfig_finalSnapshotName(rName, finalSnapshotName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1271,9 +1271,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withKMS(rName string) string { +func testAccClusterConfig_kms(rName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_kms_key" "test" {} @@ -1290,9 +1290,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withMaintenanceWindow(rName, maintenanceWindow string) string { +func testAccClusterConfig_maintenanceWindow(rName, maintenanceWindow string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1307,9 +1307,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withNodeType(rName, nodeType string) string { +func testAccClusterConfig_nodeType(rName, nodeType string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1323,9 +1323,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withNumReplicasPerShard(rName string, numReplicasPerShard int) string { +func testAccClusterConfig_numReplicasPerShard(rName string, numReplicasPerShard int) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1338,9 +1338,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withNumShards(rName string, numShards int) string { +func testAccClusterConfig_numShards(rName string, numShards int) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1353,9 +1353,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withParameterGroup(rName, parameterGroup string) string { +func testAccClusterConfig_parameterGroup(rName, parameterGroup string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_parameter_group" "test" { name = %[1]q @@ -1386,9 +1386,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withPort(rName string, port int) string { +func testAccClusterConfig_port(rName string, port int) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1403,9 +1403,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withSecurityGroups(rName string, sgCount, sgCountInCluster int) string { +func testAccClusterConfig_securityGroups(rName string, sgCount, sgCountInCluster int) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_security_group" "test" { count = %[2]d @@ -1425,9 +1425,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withSnapshotRetentionLimit(rName string, retentionLimit int) string { +func testAccClusterConfig_snapshotRetentionLimit(rName string, retentionLimit int) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1442,9 +1442,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withSnapshotFromCluster(rName1, rName2 string) string { +func testAccClusterConfig_snapshotFrom(rName1, rName2 string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName1), + testAccClusterConfig_baseNetwork(rName1), fmt.Sprintf(` resource "aws_memorydb_cluster" "test1" { acl_name = "open-access" @@ -1472,9 +1472,9 @@ resource "aws_memorydb_cluster" "test2" { ) } -func testAccClusterConfig_withSnapshotWindow(rName, snapshotWindow string) string { +func testAccClusterConfig_snapshotWindow(rName, snapshotWindow string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1490,9 +1490,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withSnsTopicNull(rName string) string { +func testAccClusterConfig_snsTopicNull(rName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -1512,9 +1512,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withSnsTopic(rName string) string { +func testAccClusterConfig_snsTopic(rName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -1535,9 +1535,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withTags0(rName string) string { +func testAccClusterConfig_tags0(rName string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1551,9 +1551,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withTags1(rName, tag1Key, tag1Value string) string { +func testAccClusterConfig_tags1(rName, tag1Key, tag1Value string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" @@ -1571,9 +1571,9 @@ resource "aws_memorydb_cluster" "test" { ) } -func testAccClusterConfig_withTags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccClusterConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return acctest.ConfigCompose( - testAccClusterConfigBaseNetwork(rName), + testAccClusterConfig_baseNetwork(rName), fmt.Sprintf(` resource "aws_memorydb_cluster" "test" { acl_name = "open-access" diff --git a/internal/service/memorydb/parameter_group_data_source_test.go b/internal/service/memorydb/parameter_group_data_source_test.go index 3e774a8df41..aa75b9ca67e 100644 --- a/internal/service/memorydb/parameter_group_data_source_test.go +++ b/internal/service/memorydb/parameter_group_data_source_test.go @@ -21,7 +21,7 @@ func TestAccMemoryDBParameterGroupDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccParameterGroupDataSourceConfig(rName), + Config: testAccParameterGroupDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "description", resourceName, "description"), @@ -46,7 +46,7 @@ func TestAccMemoryDBParameterGroupDataSource_basic(t *testing.T) { }) } -func testAccParameterGroupDataSourceConfig(rName string) string { +func testAccParameterGroupDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_memorydb_parameter_group" "test" { name = %[1]q diff --git a/internal/service/memorydb/parameter_group_test.go b/internal/service/memorydb/parameter_group_test.go index 78081f5085b..1ad3db7cbed 100644 --- a/internal/service/memorydb/parameter_group_test.go +++ b/internal/service/memorydb/parameter_group_test.go @@ -29,7 +29,7 @@ func TestAccMemoryDBParameterGroup_basic(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig(rName), + Config: testAccParameterGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "memorydb", "parametergroup/"+rName), @@ -70,7 +70,7 @@ func TestAccMemoryDBParameterGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig(rName), + Config: testAccParameterGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfmemorydb.ResourceParameterGroup(), resourceName), @@ -92,7 +92,7 @@ func TestAccMemoryDBParameterGroup_update_parameters(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig_withParameter0(rName), + Config: testAccParameterGroupConfig_none(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter.#", "0"), @@ -104,7 +104,7 @@ func TestAccMemoryDBParameterGroup_update_parameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupConfig_withParameter1(rName, "timeout", "0"), // 0 is the default value + Config: testAccParameterGroupConfig_one(rName, "timeout", "0"), // 0 is the default value Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -123,7 +123,7 @@ func TestAccMemoryDBParameterGroup_update_parameters(t *testing.T) { ImportStateVerifyIgnore: []string{"parameter"}, }, { - Config: testAccParameterGroupConfig_withParameter1(rName, "timeout", "20"), + Config: testAccParameterGroupConfig_one(rName, "timeout", "20"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -139,7 +139,7 @@ func TestAccMemoryDBParameterGroup_update_parameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupConfig_withParameter2(rName, "timeout", "20", "activerehashing", "no"), + Config: testAccParameterGroupConfig_multiple(rName, "timeout", "20", "activerehashing", "no"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter.#", "2"), @@ -159,7 +159,7 @@ func TestAccMemoryDBParameterGroup_update_parameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupConfig_withParameter1(rName, "timeout", "20"), + Config: testAccParameterGroupConfig_one(rName, "timeout", "20"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -175,7 +175,7 @@ func TestAccMemoryDBParameterGroup_update_parameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupConfig_withParameter0(rName), + Config: testAccParameterGroupConfig_none(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter.#", "0"), @@ -201,7 +201,7 @@ func TestAccMemoryDBParameterGroup_update_tags(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig_withTags0(rName), + Config: testAccParameterGroupConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -214,7 +214,7 @@ func TestAccMemoryDBParameterGroup_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupConfig_withTags2(rName, "Key1", "value1", "Key2", "value2"), + Config: testAccParameterGroupConfig_tags2(rName, "Key1", "value1", "Key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -231,7 +231,7 @@ func TestAccMemoryDBParameterGroup_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupConfig_withTags1(rName, "Key1", "value1"), + Config: testAccParameterGroupConfig_tags1(rName, "Key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -246,7 +246,7 @@ func TestAccMemoryDBParameterGroup_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupConfig_withTags0(rName), + Config: testAccParameterGroupConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -309,7 +309,7 @@ func testAccCheckParameterGroupExists(n string) resource.TestCheckFunc { } } -func testAccParameterGroupConfig(rName string) string { +func testAccParameterGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_memorydb_parameter_group" "test" { name = %[1]q @@ -332,7 +332,7 @@ resource "aws_memorydb_parameter_group" "test" { `, rName) } -func testAccParameterGroupConfig_withParameter0(rName string) string { +func testAccParameterGroupConfig_none(rName string) string { return fmt.Sprintf(` resource "aws_memorydb_parameter_group" "test" { name = %[1]q @@ -341,7 +341,7 @@ resource "aws_memorydb_parameter_group" "test" { `, rName) } -func testAccParameterGroupConfig_withParameter1(rName, paramName1, paramValue1 string) string { +func testAccParameterGroupConfig_one(rName, paramName1, paramValue1 string) string { return fmt.Sprintf(` resource "aws_memorydb_parameter_group" "test" { name = %[1]q @@ -355,7 +355,7 @@ resource "aws_memorydb_parameter_group" "test" { `, rName, paramName1, paramValue1) } -func testAccParameterGroupConfig_withParameter2(rName, paramName1, paramValue1, paramName2, paramValue2 string) string { +func testAccParameterGroupConfig_multiple(rName, paramName1, paramValue1, paramName2, paramValue2 string) string { return fmt.Sprintf(` resource "aws_memorydb_parameter_group" "test" { name = %[1]q @@ -374,7 +374,7 @@ resource "aws_memorydb_parameter_group" "test" { `, rName, paramName1, paramValue1, paramName2, paramValue2) } -func testAccParameterGroupConfig_withTags0(rName string) string { +func testAccParameterGroupConfig_tags0(rName string) string { return fmt.Sprintf(` resource "aws_memorydb_parameter_group" "test" { name = %[1]q @@ -383,7 +383,7 @@ resource "aws_memorydb_parameter_group" "test" { `, rName) } -func testAccParameterGroupConfig_withTags1(rName, tagKey1, tagValue1 string) string { +func testAccParameterGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_memorydb_parameter_group" "test" { name = %[1]q @@ -396,7 +396,7 @@ resource "aws_memorydb_parameter_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccParameterGroupConfig_withTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccParameterGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_memorydb_parameter_group" "test" { name = %[1]q diff --git a/internal/service/memorydb/snapshot_data_source_test.go b/internal/service/memorydb/snapshot_data_source_test.go index f5f9d532c93..de31372255f 100644 --- a/internal/service/memorydb/snapshot_data_source_test.go +++ b/internal/service/memorydb/snapshot_data_source_test.go @@ -21,7 +21,7 @@ func TestAccMemoryDBSnapshotDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSnapshotDataSourceConfig(rName), + Config: testAccSnapshotDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckTypeSetElemAttrPair(dataSourceName, "cluster_configuration.0.description", resourceName, "cluster_configuration.0.description"), @@ -49,7 +49,7 @@ func TestAccMemoryDBSnapshotDataSource_basic(t *testing.T) { }) } -func testAccSnapshotDataSourceConfig(rName string) string { +func testAccSnapshotDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( testAccSnapshotConfigBase(rName), fmt.Sprintf(` diff --git a/internal/service/memorydb/snapshot_test.go b/internal/service/memorydb/snapshot_test.go index 63a692eeacb..bd51e995bf7 100644 --- a/internal/service/memorydb/snapshot_test.go +++ b/internal/service/memorydb/snapshot_test.go @@ -93,7 +93,7 @@ func TestAccMemoryDBSnapshot_nameGenerated(t *testing.T) { CheckDestroy: testAccCheckSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotConfig_withNoName(rName), + Config: testAccSnapshotConfig_noName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -115,7 +115,7 @@ func TestAccMemoryDBSnapshot_namePrefix(t *testing.T) { CheckDestroy: testAccCheckSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotConfig_withNamePrefix(rName, "tftest-"), + Config: testAccSnapshotConfig_namePrefix(rName, "tftest-"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tftest-"), @@ -137,7 +137,7 @@ func TestAccMemoryDBSnapshot_create_withKMS(t *testing.T) { CheckDestroy: testAccCheckSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotConfig_withKMS(rName), + Config: testAccSnapshotConfig_kms(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName), resource.TestCheckTypeSetElemAttrPair(resourceName, "kms_key_arn", "aws_kms_key.test", "arn"), @@ -163,7 +163,7 @@ func TestAccMemoryDBSnapshot_update_tags(t *testing.T) { CheckDestroy: testAccCheckSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotConfig_withTags0(rName), + Config: testAccSnapshotConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -176,7 +176,7 @@ func TestAccMemoryDBSnapshot_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSnapshotConfig_withTags2(rName, "Key1", "value1", "Key2", "value2"), + Config: testAccSnapshotConfig_tags2(rName, "Key1", "value1", "Key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -193,7 +193,7 @@ func TestAccMemoryDBSnapshot_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSnapshotConfig_withTags1(rName, "Key1", "value1"), + Config: testAccSnapshotConfig_tags1(rName, "Key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -208,7 +208,7 @@ func TestAccMemoryDBSnapshot_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSnapshotConfig_withTags0(rName), + Config: testAccSnapshotConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -273,7 +273,7 @@ func testAccCheckSnapshotExists(n string) resource.TestCheckFunc { func testAccSnapshotConfigBase(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_memorydb_subnet_group" "test" { subnet_ids = aws_subnet.test.*.id @@ -315,7 +315,7 @@ resource "aws_memorydb_snapshot" "test" { ) } -func testAccSnapshotConfig_withKMS(rName string) string { +func testAccSnapshotConfig_kms(rName string) string { return acctest.ConfigCompose( testAccSnapshotConfigBase(rName), fmt.Sprintf(` @@ -330,7 +330,7 @@ resource "aws_memorydb_snapshot" "test" { ) } -func testAccSnapshotConfig_withNoName(rName string) string { +func testAccSnapshotConfig_noName(rName string) string { return acctest.ConfigCompose( testAccSnapshotConfigBase(rName), ` @@ -341,7 +341,7 @@ resource "aws_memorydb_snapshot" "test" { ) } -func testAccSnapshotConfig_withNamePrefix(rName, prefix string) string { +func testAccSnapshotConfig_namePrefix(rName, prefix string) string { return acctest.ConfigCompose( testAccSnapshotConfigBase(rName), fmt.Sprintf(` @@ -357,7 +357,7 @@ resource "aws_memorydb_snapshot" "test" { ) } -func testAccSnapshotConfig_withTags0(rName string) string { +func testAccSnapshotConfig_tags0(rName string) string { return acctest.ConfigCompose( testAccSnapshotConfigBase(rName), fmt.Sprintf(` @@ -369,7 +369,7 @@ resource "aws_memorydb_snapshot" "test" { ) } -func testAccSnapshotConfig_withTags1(rName, tag1Key, tag1Value string) string { +func testAccSnapshotConfig_tags1(rName, tag1Key, tag1Value string) string { return acctest.ConfigCompose( testAccSnapshotConfigBase(rName), fmt.Sprintf(` @@ -385,7 +385,7 @@ resource "aws_memorydb_snapshot" "test" { ) } -func testAccSnapshotConfig_withTags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccSnapshotConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return acctest.ConfigCompose( testAccSnapshotConfigBase(rName), fmt.Sprintf(` diff --git a/internal/service/memorydb/subnet_group_data_source_test.go b/internal/service/memorydb/subnet_group_data_source_test.go index 0c07f7f35ac..be894fb9223 100644 --- a/internal/service/memorydb/subnet_group_data_source_test.go +++ b/internal/service/memorydb/subnet_group_data_source_test.go @@ -21,7 +21,7 @@ func TestAccMemoryDBSubnetGroupDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupDataSourceConfig(rName), + Config: testAccSubnetGroupDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "description", resourceName, "description"), @@ -38,9 +38,9 @@ func TestAccMemoryDBSubnetGroupDataSource_basic(t *testing.T) { }) } -func testAccSubnetGroupDataSourceConfig(rName string) string { +func testAccSubnetGroupDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_memorydb_subnet_group" "test" { name = %[1]q diff --git a/internal/service/memorydb/subnet_group_test.go b/internal/service/memorydb/subnet_group_test.go index aa2791a9106..7fb0ba5f3c2 100644 --- a/internal/service/memorydb/subnet_group_test.go +++ b/internal/service/memorydb/subnet_group_test.go @@ -37,7 +37,7 @@ func TestAccMemoryDBSubnetGroup_basic(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig(rName), + Config: testAccSubnetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "memorydb", "subnetgroup/"+rName), @@ -71,7 +71,7 @@ func TestAccMemoryDBSubnetGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig(rName), + Config: testAccSubnetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfmemorydb.ResourceSubnetGroup(), resourceName), @@ -93,7 +93,7 @@ func TestAccMemoryDBSubnetGroup_nameGenerated(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig_withNoName(rName), + Config: testAccSubnetGroupConfig_noName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -115,7 +115,7 @@ func TestAccMemoryDBSubnetGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig_withNamePrefix(rName, "tftest-"), + Config: testAccSubnetGroupConfig_namePrefix(rName, "tftest-"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tftest-"), @@ -137,7 +137,7 @@ func TestAccMemoryDBSubnetGroup_update_description(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig(rName), + Config: testAccSubnetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), @@ -149,7 +149,7 @@ func TestAccMemoryDBSubnetGroup_update_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetGroupConfig_withDescription(rName, "Updated Description"), + Config: testAccSubnetGroupConfig_description(rName, "Updated Description"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "Updated Description"), @@ -175,7 +175,7 @@ func TestAccMemoryDBSubnetGroup_update_subnetIds(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig_withSubnetCount(rName, 1), + Config: testAccSubnetGroupConfig_count(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "1"), @@ -188,7 +188,7 @@ func TestAccMemoryDBSubnetGroup_update_subnetIds(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetGroupConfig_withSubnetCount(rName, 3), + Config: testAccSubnetGroupConfig_count(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "3"), @@ -203,7 +203,7 @@ func TestAccMemoryDBSubnetGroup_update_subnetIds(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetGroupConfig_withSubnetCount(rName, 2), + Config: testAccSubnetGroupConfig_count(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), @@ -231,7 +231,7 @@ func TestAccMemoryDBSubnetGroup_update_tags(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig_withTags0(rName), + Config: testAccSubnetGroupConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -244,7 +244,7 @@ func TestAccMemoryDBSubnetGroup_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetGroupConfig_withTags2(rName, "Key1", "value1", "Key2", "value2"), + Config: testAccSubnetGroupConfig_tags2(rName, "Key1", "value1", "Key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -261,7 +261,7 @@ func TestAccMemoryDBSubnetGroup_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetGroupConfig_withTags1(rName, "Key1", "value1"), + Config: testAccSubnetGroupConfig_tags1(rName, "Key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -276,7 +276,7 @@ func TestAccMemoryDBSubnetGroup_update_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSubnetGroupConfig_withTags0(rName), + Config: testAccSubnetGroupConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -339,9 +339,9 @@ func testAccCheckSubnetGroupExists(n string) resource.TestCheckFunc { } } -func testAccSubnetGroupConfig(rName string) string { +func testAccSubnetGroupConfig_basic(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_memorydb_subnet_group" "test" { name = %[1]q @@ -355,9 +355,9 @@ resource "aws_memorydb_subnet_group" "test" { ) } -func testAccSubnetGroupConfig_withNoName(rName string) string { +func testAccSubnetGroupConfig_noName(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), ` resource "aws_memorydb_subnet_group" "test" { subnet_ids = aws_subnet.test.*.id @@ -366,9 +366,9 @@ resource "aws_memorydb_subnet_group" "test" { ) } -func testAccSubnetGroupConfig_withNamePrefix(rName, rNamePrefix string) string { +func testAccSubnetGroupConfig_namePrefix(rName, rNamePrefix string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_memorydb_subnet_group" "test" { name_prefix = %[1]q @@ -378,9 +378,9 @@ resource "aws_memorydb_subnet_group" "test" { ) } -func testAccSubnetGroupConfig_withDescription(rName, description string) string { +func testAccSubnetGroupConfig_description(rName, description string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_memorydb_subnet_group" "test" { name = %[1]q @@ -391,9 +391,9 @@ resource "aws_memorydb_subnet_group" "test" { ) } -func testAccSubnetGroupConfig_withSubnetCount(rName string, subnetCount int) string { +func testAccSubnetGroupConfig_count(rName string, subnetCount int) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, subnetCount), + acctest.ConfigVPCWithSubnets(rName, subnetCount), fmt.Sprintf(` resource "aws_memorydb_subnet_group" "test" { name = %[1]q @@ -403,9 +403,9 @@ resource "aws_memorydb_subnet_group" "test" { ) } -func testAccSubnetGroupConfig_withTags0(rName string) string { +func testAccSubnetGroupConfig_tags0(rName string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_memorydb_subnet_group" "test" { name = %[1]q @@ -415,9 +415,9 @@ resource "aws_memorydb_subnet_group" "test" { ) } -func testAccSubnetGroupConfig_withTags1(rName, tag1Key, tag1Value string) string { +func testAccSubnetGroupConfig_tags1(rName, tag1Key, tag1Value string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_memorydb_subnet_group" "test" { name = %[1]q @@ -431,9 +431,9 @@ resource "aws_memorydb_subnet_group" "test" { ) } -func testAccSubnetGroupConfig_withTags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccSubnetGroupConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_memorydb_subnet_group" "test" { name = %[1]q diff --git a/internal/service/memorydb/user_data_source_test.go b/internal/service/memorydb/user_data_source_test.go index cb64894b481..8312f407f1d 100644 --- a/internal/service/memorydb/user_data_source_test.go +++ b/internal/service/memorydb/user_data_source_test.go @@ -21,7 +21,7 @@ func TestAccMemoryDBUserDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccUserDataSourceConfig(rName), + Config: testAccUserDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "access_string", resourceName, "access_string"), resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), @@ -37,7 +37,7 @@ func TestAccMemoryDBUserDataSource_basic(t *testing.T) { }) } -func testAccUserDataSourceConfig(rName string) string { +func testAccUserDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_memorydb_user" "test" { access_string = "on ~* &* +@all" diff --git a/internal/service/memorydb/user_test.go b/internal/service/memorydb/user_test.go index eb4f4aa2996..2c8e2513271 100644 --- a/internal/service/memorydb/user_test.go +++ b/internal/service/memorydb/user_test.go @@ -26,7 +26,7 @@ func TestAccMemoryDBUser_basic(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfig(rName), + Config: testAccUserConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "access_string", "on ~* &* +@all"), @@ -62,7 +62,7 @@ func TestAccMemoryDBUser_disappears(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfig(rName), + Config: testAccUserConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfmemorydb.ResourceUser(), resourceName), @@ -84,7 +84,7 @@ func TestAccMemoryDBUser_update_accessString(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfig_withAccessString(rName, "on ~* &* +@all"), + Config: testAccUserConfig_accessString(rName, "on ~* &* +@all"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "access_string", "on ~* &* +@all"), @@ -97,7 +97,7 @@ func TestAccMemoryDBUser_update_accessString(t *testing.T) { ImportStateVerifyIgnore: []string{"authentication_mode.0.passwords"}, }, { - Config: testAccUserConfig_withAccessString(rName, "off ~* &* +@all"), + Config: testAccUserConfig_accessString(rName, "off ~* &* +@all"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "access_string", "off ~* &* +@all"), @@ -118,7 +118,7 @@ func TestAccMemoryDBUser_update_passwords(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfig_withPasswords2(rName, "aaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbb"), + Config: testAccUserConfig_passwords2(rName, "aaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbb"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "authentication_mode.0.password_count", "2"), @@ -131,7 +131,7 @@ func TestAccMemoryDBUser_update_passwords(t *testing.T) { ImportStateVerifyIgnore: []string{"authentication_mode.0.passwords"}, }, { - Config: testAccUserConfig_withPasswords1(rName, "aaaaaaaaaaaaaaaa"), + Config: testAccUserConfig_passwords1(rName, "aaaaaaaaaaaaaaaa"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "authentication_mode.0.password_count", "1"), @@ -144,7 +144,7 @@ func TestAccMemoryDBUser_update_passwords(t *testing.T) { ImportStateVerifyIgnore: []string{"authentication_mode.0.passwords"}, }, { - Config: testAccUserConfig_withPasswords2(rName, "cccccccccccccccc", "dddddddddddddddd"), + Config: testAccUserConfig_passwords2(rName, "cccccccccccccccc", "dddddddddddddddd"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "authentication_mode.0.password_count", "2"), @@ -171,7 +171,7 @@ func TestAccMemoryDBUser_update_tags(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfig_withTags0(rName), + Config: testAccUserConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -185,7 +185,7 @@ func TestAccMemoryDBUser_update_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"authentication_mode.0.passwords"}, }, { - Config: testAccUserConfig_withTags2(rName, "Key1", "value1", "Key2", "value2"), + Config: testAccUserConfig_tags2(rName, "Key1", "value1", "Key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -203,7 +203,7 @@ func TestAccMemoryDBUser_update_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"authentication_mode.0.passwords"}, }, { - Config: testAccUserConfig_withTags1(rName, "Key1", "value1"), + Config: testAccUserConfig_tags1(rName, "Key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -219,7 +219,7 @@ func TestAccMemoryDBUser_update_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"authentication_mode.0.passwords"}, }, { - Config: testAccUserConfig_withTags0(rName), + Config: testAccUserConfig_tags0(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -283,7 +283,7 @@ func testAccCheckUserExists(n string) resource.TestCheckFunc { } } -func testAccUserConfig(rName string) string { +func testAccUserConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_memorydb_user" "test" { access_string = "on ~* &* +@all" @@ -301,7 +301,7 @@ resource "aws_memorydb_user" "test" { `, rName) } -func testAccUserConfig_withAccessString(rName, accessString string) string { +func testAccUserConfig_accessString(rName, accessString string) string { return fmt.Sprintf(` resource "aws_memorydb_user" "test" { access_string = %[2]q @@ -315,7 +315,7 @@ resource "aws_memorydb_user" "test" { `, rName, accessString) } -func testAccUserConfig_withPasswords1(rName, password1 string) string { +func testAccUserConfig_passwords1(rName, password1 string) string { return fmt.Sprintf(` resource "aws_memorydb_user" "test" { access_string = "on ~* &* +@all" @@ -329,7 +329,7 @@ resource "aws_memorydb_user" "test" { `, rName, password1) } -func testAccUserConfig_withPasswords2(rName, password1, password2 string) string { +func testAccUserConfig_passwords2(rName, password1, password2 string) string { return fmt.Sprintf(` resource "aws_memorydb_user" "test" { access_string = "on ~* &* +@all" @@ -343,7 +343,7 @@ resource "aws_memorydb_user" "test" { `, rName, password1, password2) } -func testAccUserConfig_withTags0(rName string) string { +func testAccUserConfig_tags0(rName string) string { return fmt.Sprintf(` resource "aws_memorydb_user" "test" { access_string = "on ~* &* +@all" @@ -357,7 +357,7 @@ resource "aws_memorydb_user" "test" { `, rName) } -func testAccUserConfig_withTags1(rName, tagKey1, tagValue1 string) string { +func testAccUserConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_memorydb_user" "test" { access_string = "on ~* &* +@all" @@ -375,7 +375,7 @@ resource "aws_memorydb_user" "test" { `, rName, tagKey1, tagValue1) } -func testAccUserConfig_withTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccUserConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_memorydb_user" "test" { access_string = "on ~* &* +@all" diff --git a/internal/service/meta/arn_data_source_test.go b/internal/service/meta/arn_data_source_test.go index ba9b22ccc86..291adda5f72 100644 --- a/internal/service/meta/arn_data_source_test.go +++ b/internal/service/meta/arn_data_source_test.go @@ -29,7 +29,7 @@ func TestAccMetaARNDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccARNDataSourceConfig(testARN.String()), + Config: testAccARNDataSourceConfig_basic(testARN.String()), Check: resource.ComposeTestCheckFunc( testAccARNDataSource(resourceName), resource.TestCheckResourceAttr(resourceName, "account", testARN.AccountID), @@ -54,7 +54,7 @@ func testAccARNDataSource(name string) resource.TestCheckFunc { } } -func testAccARNDataSourceConfig(arn string) string { +func testAccARNDataSourceConfig_basic(arn string) string { return fmt.Sprintf(` data "aws_arn" "test" { arn = %q diff --git a/internal/service/meta/billing_service_account_data_source_test.go b/internal/service/meta/billing_service_account_data_source_test.go index 3743178de3a..0b22803ba1a 100644 --- a/internal/service/meta/billing_service_account_data_source_test.go +++ b/internal/service/meta/billing_service_account_data_source_test.go @@ -19,7 +19,7 @@ func TestAccMetaBillingServiceAccountDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccBillingServiceAccountConfig_basic, + Config: testAccBillingServiceAccountDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", billingAccountID), acctest.CheckResourceAttrGlobalARNAccountID(dataSourceName, "arn", billingAccountID, "iam", "root"), @@ -29,6 +29,6 @@ func TestAccMetaBillingServiceAccountDataSource_basic(t *testing.T) { }) } -const testAccBillingServiceAccountConfig_basic = ` +const testAccBillingServiceAccountDataSourceConfig_basic = ` data "aws_billing_service_account" "main" {} ` diff --git a/internal/service/meta/default_tags_data_source_test.go b/internal/service/meta/default_tags_data_source_test.go index f0608ea9ab3..b49588997c0 100644 --- a/internal/service/meta/default_tags_data_source_test.go +++ b/internal/service/meta/default_tags_data_source_test.go @@ -23,7 +23,7 @@ func TestAccMetaDefaultTagsDataSource_basic(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("first", "value"), - testAccDefaultTagsDataSource(), + testAccDefaultTagsDataSourceConfig_basic(), ), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "tags.%", "1"), @@ -48,7 +48,7 @@ func TestAccMetaDefaultTagsDataSource_empty(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags0(), - testAccDefaultTagsDataSource(), + testAccDefaultTagsDataSourceConfig_basic(), ), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "tags.%", "0"), @@ -72,7 +72,7 @@ func TestAccMetaDefaultTagsDataSource_multiple(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags2("nuera", "hijo", "escalofrios", "calambres"), - testAccDefaultTagsDataSource(), + testAccDefaultTagsDataSourceConfig_basic(), ), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "tags.%", "2"), @@ -98,7 +98,7 @@ func TestAccMetaDefaultTagsDataSource_ignore(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultTags_Tags1("Tabac", "Louis Chiron"), - testAccDefaultTagsDataSource(), + testAccDefaultTagsDataSourceConfig_basic(), ), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "tags.%", "1"), @@ -108,7 +108,7 @@ func TestAccMetaDefaultTagsDataSource_ignore(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigDefaultAndIgnoreTagsKeys1("Tabac", "Louis Chiron"), - testAccDefaultTagsDataSource(), + testAccDefaultTagsDataSourceConfig_basic(), ), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "tags.%", "0"), @@ -118,6 +118,6 @@ func TestAccMetaDefaultTagsDataSource_ignore(t *testing.T) { }) } -func testAccDefaultTagsDataSource() string { +func testAccDefaultTagsDataSourceConfig_basic() string { return `data "aws_default_tags" "test" {}` } diff --git a/internal/service/meta/ip_ranges_data_source_test.go b/internal/service/meta/ip_ranges_data_source_test.go index 07c63fb8192..b547cd659e8 100644 --- a/internal/service/meta/ip_ranges_data_source_test.go +++ b/internal/service/meta/ip_ranges_data_source_test.go @@ -22,7 +22,7 @@ func TestAccMetaIPRangesDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccIPRangesConfig, + Config: testAccIPRangesDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( testAccIPRangesCheckAttributes("data.aws_ip_ranges.some"), testAccIPRangesCheckCIDRBlocksAttribute("data.aws_ip_ranges.some", "cidr_blocks"), @@ -42,7 +42,7 @@ func TestAccMetaIPRangesDataSource_url(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccIPRangesURLConfig, + Config: testAccIPRangesDataSourceConfig_url, Check: resource.ComposeTestCheckFunc( testAccIPRangesCheckAttributes("data.aws_ip_ranges.some"), testAccIPRangesCheckCIDRBlocksAttribute("data.aws_ip_ranges.some", "cidr_blocks"), @@ -160,7 +160,7 @@ func testAccIPRangesCheckCIDRBlocksAttribute(name, attribute string) resource.Te } // lintignore:AWSAT003 -const testAccIPRangesConfig = ` +const testAccIPRangesDataSourceConfig_basic = ` data "aws_ip_ranges" "some" { regions = ["eu-west-1", "eu-central-1"] services = ["ec2"] @@ -173,7 +173,7 @@ data "aws_ip_ranges" "none" { ` // lintignore:AWSAT003 -const testAccIPRangesURLConfig = ` +const testAccIPRangesDataSourceConfig_url = ` data "aws_ip_ranges" "some" { regions = ["eu-west-1", "eu-central-1"] services = ["ec2"] diff --git a/internal/service/meta/partition_data_source_test.go b/internal/service/meta/partition_data_source_test.go index a4549f7da57..32d6ce5f9e0 100644 --- a/internal/service/meta/partition_data_source_test.go +++ b/internal/service/meta/partition_data_source_test.go @@ -18,7 +18,7 @@ func TestAccMetaPartitionDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPartitionConfig_basic, + Config: testAccPartitionDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckPartition("data.aws_partition.current"), testAccCheckDNSSuffix("data.aws_partition.current"), @@ -65,6 +65,6 @@ func testAccCheckDNSSuffix(n string) resource.TestCheckFunc { } } -const testAccPartitionConfig_basic = ` +const testAccPartitionDataSourceConfig_basic = ` data "aws_partition" "current" {} ` diff --git a/internal/service/meta/region_data_source_test.go b/internal/service/meta/region_data_source_test.go index c3312f1e782..6989564b4c6 100644 --- a/internal/service/meta/region_data_source_test.go +++ b/internal/service/meta/region_data_source_test.go @@ -11,7 +11,7 @@ import ( tfmeta "github.com/hashicorp/terraform-provider-aws/internal/service/meta" ) -func TestFindRegionByEc2Endpoint(t *testing.T) { +func TestFindRegionByEC2Endpoint(t *testing.T) { var testCases = []struct { Value string ErrCount int diff --git a/internal/service/meta/regions_data_source_test.go b/internal/service/meta/regions_data_source_test.go index b5b0f64539c..cd09d6d8441 100644 --- a/internal/service/meta/regions_data_source_test.go +++ b/internal/service/meta/regions_data_source_test.go @@ -39,7 +39,7 @@ func TestAccMetaRegionsDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRegionsDataSourceConfig_allRegionsFiltered("opt-in-not-required"), + Config: testAccRegionsDataSourceConfig_allFiltered("opt-in-not-required"), Check: resource.ComposeTestCheckFunc( testAccRegionsCheckDataSource(resourceName), ), @@ -57,7 +57,7 @@ func TestAccMetaRegionsDataSource_allRegions(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRegionsDataSourceConfig_allRegions(), + Config: testAccRegionsDataSourceConfig_all(), Check: resource.ComposeTestCheckFunc( testAccRegionsCheckDataSource(resourceAllRegions), resource.TestCheckResourceAttr(resourceAllRegions, "all_regions", "true"), @@ -102,7 +102,7 @@ data "aws_regions" "empty" {} ` } -func testAccRegionsDataSourceConfig_allRegions() string { +func testAccRegionsDataSourceConfig_all() string { return ` data "aws_regions" "all_regions" { all_regions = "true" @@ -110,7 +110,7 @@ data "aws_regions" "all_regions" { ` } -func testAccRegionsDataSourceConfig_allRegionsFiltered(filter string) string { +func testAccRegionsDataSourceConfig_allFiltered(filter string) string { return fmt.Sprintf(` data "aws_regions" "opt_in_status" { filter { diff --git a/internal/service/meta/service_data_source_test.go b/internal/service/meta/service_data_source_test.go index 3bafe616934..725b82bc0e0 100644 --- a/internal/service/meta/service_data_source_test.go +++ b/internal/service/meta/service_data_source_test.go @@ -56,7 +56,7 @@ func TestAccMetaService_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckServiceConfig_basic(), + Config: testAccServiceDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "dns_name", fmt.Sprintf("%s.%s.%s", ec2.EndpointsID, acctest.Region(), "amazonaws.com")), resource.TestCheckResourceAttr(dataSourceName, "partition", acctest.Partition()), @@ -80,7 +80,7 @@ func TestAccMetaService_byReverseDNSName(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckServiceConfig_byReverseDNSName(), + Config: testAccServiceDataSourceConfig_byReverseDNSName(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "region", endpoints.CnNorth1RegionID), resource.TestCheckResourceAttr(dataSourceName, "reverse_dns_name", fmt.Sprintf("%s.%s.%s", "cn.com.amazonaws", endpoints.CnNorth1RegionID, s3.EndpointsID)), @@ -102,7 +102,7 @@ func TestAccMetaService_byDNSName(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckServiceConfig_byDNSName(), + Config: testAccServiceDataSourceConfig_byDNSName(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "region", endpoints.UsEast1RegionID), resource.TestCheckResourceAttr(dataSourceName, "reverse_dns_name", fmt.Sprintf("%s.%s.%s", "com.amazonaws", endpoints.UsEast1RegionID, rds.EndpointsID)), @@ -124,7 +124,7 @@ func TestAccMetaService_byParts(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckServiceConfig_byPart(), + Config: testAccServiceDataSourceConfig_byPart(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "dns_name", fmt.Sprintf("%s.%s.%s", s3.EndpointsID, acctest.Region(), "amazonaws.com")), resource.TestCheckResourceAttr(dataSourceName, "reverse_dns_name", fmt.Sprintf("%s.%s.%s", "com.amazonaws", acctest.Region(), s3.EndpointsID)), @@ -144,7 +144,7 @@ func TestAccMetaService_unsupported(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckServiceConfig_unsupported(), + Config: testAccServiceDataSourceConfig_unsupported(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "dns_name", fmt.Sprintf("%s.%s.%s", waf.EndpointsID, endpoints.UsGovWest1RegionID, "amazonaws.com")), resource.TestCheckResourceAttr(dataSourceName, "partition", endpoints.AwsUsGovPartitionID), @@ -159,7 +159,7 @@ func TestAccMetaService_unsupported(t *testing.T) { }) } -func testAccCheckServiceConfig_basic() string { +func testAccServiceDataSourceConfig_basic() string { return fmt.Sprintf(` data "aws_service" "default" { service_id = %[1]q @@ -167,7 +167,7 @@ data "aws_service" "default" { `, ec2.EndpointsID) } -func testAccCheckServiceConfig_byReverseDNSName() string { +func testAccServiceDataSourceConfig_byReverseDNSName() string { // lintignore:AWSAT003 return ` data "aws_service" "test" { @@ -176,7 +176,7 @@ data "aws_service" "test" { ` } -func testAccCheckServiceConfig_byDNSName() string { +func testAccServiceDataSourceConfig_byDNSName() string { // lintignore:AWSAT003 return ` data "aws_service" "test" { @@ -185,7 +185,7 @@ data "aws_service" "test" { ` } -func testAccCheckServiceConfig_byPart() string { +func testAccServiceDataSourceConfig_byPart() string { return ` data "aws_region" "current" {} @@ -197,7 +197,7 @@ data "aws_service" "test" { ` } -func testAccCheckServiceConfig_unsupported() string { +func testAccServiceDataSourceConfig_unsupported() string { // lintignore:AWSAT003 return ` data "aws_service" "test" { diff --git a/internal/service/mq/broker_instance_type_offerings_data_source_test.go b/internal/service/mq/broker_instance_type_offerings_data_source_test.go index 823c48df4e3..c8c82bf7712 100644 --- a/internal/service/mq/broker_instance_type_offerings_data_source_test.go +++ b/internal/service/mq/broker_instance_type_offerings_data_source_test.go @@ -15,7 +15,7 @@ func TestAccMQBrokerInstanceTypeOfferingsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccBrokerDataSourceInstanceTypeOfferingsConfig(), + Config: testAccBrokerInstanceTypeOfferingsDataSourceConfig_basic(), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_mq_broker_instance_type_offerings.empty", "broker_instance_options.#"), resource.TestCheckTypeSetElemNestedAttrs("data.aws_mq_broker_instance_type_offerings.empty", "broker_instance_options.*", map[string]string{ @@ -45,7 +45,7 @@ func TestAccMQBrokerInstanceTypeOfferingsDataSource_basic(t *testing.T) { }) } -func testAccBrokerDataSourceInstanceTypeOfferingsConfig() string { +func testAccBrokerInstanceTypeOfferingsDataSourceConfig_basic() string { return ` data "aws_mq_broker_instance_type_offerings" "empty" {} diff --git a/internal/service/mq/broker_test.go b/internal/service/mq/broker_test.go index 6d68276c5de..c452de59150 100644 --- a/internal/service/mq/broker_test.go +++ b/internal/service/mq/broker_test.go @@ -245,7 +245,7 @@ func TestAccMQBroker_basic(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfig(rName, testAccBrokerVersionNewer), + Config: testAccBrokerConfig_basic(rName, testAccBrokerVersionNewer), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), @@ -322,7 +322,7 @@ func TestAccMQBroker_throughputOptimized(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerEBSConfig(rName, testAccBrokerVersionNewer), + Config: testAccBrokerConfig_ebs(rName, testAccBrokerVersionNewer), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), @@ -405,7 +405,7 @@ func TestAccMQBroker_AllFields_defaultVPC(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfig_allFieldsDefaultVpc(rName, testAccBrokerVersionNewer, rName, cfgBodyBefore), + Config: testAccBrokerConfig_allFieldsDefaultVPC(rName, testAccBrokerVersionNewer, rName, cfgBodyBefore), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "true"), @@ -476,7 +476,7 @@ func TestAccMQBroker_AllFields_defaultVPC(t *testing.T) { }, { // Update configuration in-place - Config: testAccBrokerConfig_allFieldsDefaultVpc(rName, testAccBrokerVersionNewer, rName, cfgBodyAfter), + Config: testAccBrokerConfig_allFieldsDefaultVPC(rName, testAccBrokerVersionNewer, rName, cfgBodyAfter), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "broker_name", rName), @@ -487,7 +487,7 @@ func TestAccMQBroker_AllFields_defaultVPC(t *testing.T) { }, { // Replace configuration - Config: testAccBrokerConfig_allFieldsDefaultVpc(rName, testAccBrokerVersionNewer, rNameUpdated, cfgBodyAfter), + Config: testAccBrokerConfig_allFieldsDefaultVPC(rName, testAccBrokerVersionNewer, rNameUpdated, cfgBodyAfter), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "broker_name", rName), @@ -533,7 +533,7 @@ func TestAccMQBroker_AllFields_customVPC(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfig_allFieldsCustomVpc(rName, testAccBrokerVersionNewer, rName, cfgBodyBefore, "CET"), + Config: testAccBrokerConfig_allFieldsCustomVPC(rName, testAccBrokerVersionNewer, rName, cfgBodyBefore, "CET"), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "true"), @@ -604,7 +604,7 @@ func TestAccMQBroker_AllFields_customVPC(t *testing.T) { }, { // Update configuration in-place - Config: testAccBrokerConfig_allFieldsCustomVpc(rName, testAccBrokerVersionNewer, rName, cfgBodyAfter, "GMT"), + Config: testAccBrokerConfig_allFieldsCustomVPC(rName, testAccBrokerVersionNewer, rName, cfgBodyAfter, "GMT"), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "broker_name", rName), @@ -619,7 +619,7 @@ func TestAccMQBroker_AllFields_customVPC(t *testing.T) { }, { // Replace configuration - Config: testAccBrokerConfig_allFieldsCustomVpc(rName, testAccBrokerVersionNewer, rNameUpdated, cfgBodyAfter, "GMT"), + Config: testAccBrokerConfig_allFieldsCustomVPC(rName, testAccBrokerVersionNewer, rNameUpdated, cfgBodyAfter, "GMT"), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "broker_name", rName), @@ -653,7 +653,7 @@ func TestAccMQBroker_EncryptionOptions_kmsKeyID(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfigEncryptionOptionsKmsKeyId(rName, testAccBrokerVersionNewer), + Config: testAccBrokerConfig_encryptionOptionsKMSKeyID(rName, testAccBrokerVersionNewer), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "encryption_options.#", "1"), @@ -842,7 +842,7 @@ func TestAccMQBroker_Update_tags(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfigTags1(rName, testAccBrokerVersionNewer, "key1", "value1"), + Config: testAccBrokerConfig_tags1(rName, testAccBrokerVersionNewer, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -856,7 +856,7 @@ func TestAccMQBroker_Update_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, }, { - Config: testAccBrokerConfigTags2(rName, testAccBrokerVersionNewer, "key1", "value1updated", "key2", "value2"), + Config: testAccBrokerConfig_tags2(rName, testAccBrokerVersionNewer, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -865,7 +865,7 @@ func TestAccMQBroker_Update_tags(t *testing.T) { ), }, { - Config: testAccBrokerConfigTags1(rName, testAccBrokerVersionNewer, "key2", "value2"), + Config: testAccBrokerConfig_tags1(rName, testAccBrokerVersionNewer, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -896,7 +896,7 @@ func TestAccMQBroker_Update_securityGroup(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfig(rName, testAccBrokerVersionNewer), + Config: testAccBrokerConfig_basic(rName, testAccBrokerVersionNewer), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "security_groups.#", "1"), @@ -953,7 +953,7 @@ func TestAccMQBroker_Update_engineVersion(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfig(rName, testAccBrokerVersionOlder), + Config: testAccBrokerConfig_basic(rName, testAccBrokerVersionOlder), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "engine_version", testAccBrokerVersionOlder), @@ -966,7 +966,7 @@ func TestAccMQBroker_Update_engineVersion(t *testing.T) { ImportStateVerifyIgnore: []string{"apply_immediately", "user"}, }, { - Config: testAccBrokerEngineVersionUpdateConfig(rName, testAccBrokerVersionNewer), + Config: testAccBrokerConfig_engineVersionUpdate(rName, testAccBrokerVersionNewer), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "engine_version", testAccBrokerVersionNewer), @@ -996,14 +996,14 @@ func TestAccMQBroker_Update_hostInstanceType(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfigInstanceType(rName, testAccBrokerVersionNewer, "mq.t2.micro"), + Config: testAccBrokerConfig_instanceType(rName, testAccBrokerVersionNewer, "mq.t2.micro"), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker1), resource.TestCheckResourceAttr(resourceName, "host_instance_type", "mq.t2.micro"), ), }, { - Config: testAccBrokerConfigInstanceType(rName, testAccBrokerVersionNewer, "mq.t3.micro"), + Config: testAccBrokerConfig_instanceType(rName, testAccBrokerVersionNewer, "mq.t3.micro"), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker2), testAccCheckBrokerNotRecreated(&broker1, &broker2), @@ -1034,7 +1034,7 @@ func TestAccMQBroker_disappears(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfig(rName, testAccBrokerVersionNewer), + Config: testAccBrokerConfig_basic(rName, testAccBrokerVersionNewer), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), acctest.CheckResourceDisappears(acctest.Provider, tfmq.ResourceBroker(), resourceName), @@ -1065,7 +1065,7 @@ func TestAccMQBroker_RabbitMQ_basic(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfigRabbit(rName, testAccRabbitVersion), + Config: testAccBrokerConfig_rabbit(rName, testAccRabbitVersion), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "configuration.#", "0"), @@ -1110,7 +1110,7 @@ func TestAccMQBroker_RabbitMQ_logs(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfigRabbitLogs(rName, testAccRabbitVersion), + Config: testAccBrokerConfig_rabbitLogs(rName, testAccRabbitVersion), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "configuration.#", "0"), @@ -1155,13 +1155,13 @@ func TestAccMQBroker_RabbitMQ_validationAuditLog(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccBrokerConfigRabbitAuditLog(rName, testAccRabbitVersion, true), + Config: testAccBrokerConfig_rabbitAuditLog(rName, testAccRabbitVersion, true), ExpectError: regexp.MustCompile(`logs.audit: Can not be configured when engine is RabbitMQ`), }, { // Special case: allow explicitly setting logs.0.audit to false, // though the AWS API does not accept the parameter. - Config: testAccBrokerConfigRabbitAuditLog(rName, testAccRabbitVersion, false), + Config: testAccBrokerConfig_rabbitAuditLog(rName, testAccRabbitVersion, false), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "logs.#", "1"), @@ -1193,7 +1193,7 @@ func TestAccMQBroker_RabbitMQ_cluster(t *testing.T) { CheckDestroy: testAccCheckBrokerDestroy, Steps: []resource.TestStep{ { - Config: testAccRabbitClusterBrokerConfig(rName, testAccRabbitVersion), + Config: testAccBrokerConfig_rabbitCluster(rName, testAccRabbitVersion), Check: resource.ComposeTestCheckFunc( testAccCheckBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), @@ -1361,7 +1361,7 @@ func testAccCheckBrokerNotRecreated(before, after *mq.DescribeBrokerResponse) re } } -func testAccBrokerConfig(rName, version string) string { +func testAccBrokerConfig_basic(rName, version string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -1388,7 +1388,7 @@ resource "aws_mq_broker" "test" { `, rName, version) } -func testAccBrokerEBSConfig(rName, version string) string { +func testAccBrokerConfig_ebs(rName, version string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -1414,7 +1414,7 @@ resource "aws_mq_broker" "test" { `, rName, version) } -func testAccBrokerEngineVersionUpdateConfig(rName, version string) string { +func testAccBrokerConfig_engineVersionUpdate(rName, version string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -1440,7 +1440,7 @@ resource "aws_mq_broker" "test" { `, rName, version) } -func testAccBrokerConfig_allFieldsDefaultVpc(rName, version, cfgName, cfgBody string) string { +func testAccBrokerConfig_allFieldsDefaultVPC(rName, version, cfgName, cfgBody string) string { return fmt.Sprintf(` resource "aws_security_group" "mq1" { name = %[1]q @@ -1500,7 +1500,7 @@ resource "aws_mq_broker" "test" { `, rName, version, cfgName, cfgBody) } -func testAccBrokerConfig_allFieldsCustomVpc(rName, version, cfgName, cfgBody, tz string) string { +func testAccBrokerConfig_allFieldsCustomVPC(rName, version, cfgName, cfgBody, tz string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1633,7 +1633,7 @@ resource "aws_mq_broker" "test" { `, rName, version, cfgName, cfgBody, tz) } -func testAccBrokerConfigEncryptionOptionsKmsKeyId(rName, version string) string { +func testAccBrokerConfig_encryptionOptionsKMSKeyID(rName, version string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -1770,7 +1770,7 @@ resource "aws_mq_broker" "test" { `, rName, version) } -func testAccBrokerConfigTags1(rName, version, tagKey1, tagValue1 string) string { +func testAccBrokerConfig_tags1(rName, version, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -1796,7 +1796,7 @@ resource "aws_mq_broker" "test" { `, rName, version, tagKey1, tagValue1) } -func testAccBrokerConfigTags2(rName, version, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccBrokerConfig_tags2(rName, version, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -1883,7 +1883,7 @@ resource "aws_mq_broker" "test" { `, rName, version) } -func testAccBrokerConfigRabbit(rName, version string) string { +func testAccBrokerConfig_rabbit(rName, version string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -1904,7 +1904,7 @@ resource "aws_mq_broker" "test" { `, rName, version) } -func testAccBrokerConfigRabbitLogs(rName, version string) string { +func testAccBrokerConfig_rabbitLogs(rName, version string) string { return fmt.Sprintf(` resource "aws_mq_broker" "test" { broker_name = %[1]q @@ -1929,7 +1929,7 @@ resource "aws_security_group" "test" { `, rName, version) } -func testAccBrokerConfigRabbitAuditLog(rName, version string, enabled bool) string { +func testAccBrokerConfig_rabbitAuditLog(rName, version string, enabled bool) string { return fmt.Sprintf(` resource "aws_mq_broker" "test" { broker_name = %[1]q @@ -1955,7 +1955,7 @@ resource "aws_security_group" "test" { `, rName, version, enabled) } -func testAccRabbitClusterBrokerConfig(rName, version string) string { +func testAccBrokerConfig_rabbitCluster(rName, version string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -2019,7 +2019,7 @@ resource "aws_mq_broker" "test" { `, rName, version, ldapUsername) } -func testAccBrokerConfigInstanceType(rName, version, instanceType string) string { +func testAccBrokerConfig_instanceType(rName, version, instanceType string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q diff --git a/internal/service/mq/forge_test.go b/internal/service/mq/forge_test.go index 48ada57e01f..e6c466d0f3f 100644 --- a/internal/service/mq/forge_test.go +++ b/internal/service/mq/forge_test.go @@ -15,17 +15,17 @@ func TestCanonicalXML(t *testing.T) { }{ { Name: "Config sample from MSDN", - Config: testExampleXML_from_msdn, - Expected: testExampleXML_from_msdn, + Config: testAccForgeConfig_testExampleXMLFromMsdn, + Expected: testAccForgeConfig_testExampleXMLFromMsdn, }, { Name: "Config sample from MSDN, modified", - Config: testExampleXML_from_msdn, + Config: testAccForgeConfig_testExampleXMLFromMsdn, Expected: testExampleXML_from_msdn_modified, }, { Name: "Config sample from MSDN, flaw", - Config: testExampleXML_from_msdn, + Config: testAccForgeConfig_testExampleXMLFromMsdn, Expected: testExampleXML_from_msdn_flawed, ExpectError: true, }, @@ -78,7 +78,7 @@ func TestCanonicalXML(t *testing.T) { } } -const testExampleXML_from_msdn = ` +const testAccForgeConfig_testExampleXMLFromMsdn = ` diff --git a/internal/service/mwaa/environment_test.go b/internal/service/mwaa/environment_test.go index e00ad5e0c76..83ef44e4fe4 100644 --- a/internal/service/mwaa/environment_test.go +++ b/internal/service/mwaa/environment_test.go @@ -28,7 +28,7 @@ func TestAccMWAAEnvironment_basic(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentBasicConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), resource.TestCheckResourceAttrSet(resourceName, "airflow_version"), @@ -91,7 +91,7 @@ func TestAccMWAAEnvironment_disappears(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentBasicConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), acctest.CheckResourceDisappears(acctest.Provider, tfmwaa.ResourceEnvironment(), resourceName), @@ -115,7 +115,7 @@ func TestAccMWAAEnvironment_airflowOptions(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentAirflowConfigurationOptionsConfig(rName, "1", "16"), + Config: testAccEnvironmentConfig_airflowOptions(rName, "1", "16"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), resource.TestCheckResourceAttr(resourceName, "airflow_configuration_options.%", "2"), @@ -129,7 +129,7 @@ func TestAccMWAAEnvironment_airflowOptions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEnvironmentAirflowConfigurationOptionsConfig(rName, "2", "32"), + Config: testAccEnvironmentConfig_airflowOptions(rName, "2", "32"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), resource.TestCheckResourceAttr(resourceName, "airflow_configuration_options.%", "2"), @@ -138,7 +138,7 @@ func TestAccMWAAEnvironment_airflowOptions(t *testing.T) { ), }, { - Config: testAccEnvironmentBasicConfig(rName), + Config: testAccEnvironmentConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), resource.TestCheckResourceAttr(resourceName, "airflow_configuration_options.%", "0"), @@ -161,7 +161,7 @@ func TestAccMWAAEnvironment_log(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentLoggingConfigurationConfig(rName, "true", mwaa.LoggingLevelCritical), + Config: testAccEnvironmentConfig_logging(rName, "true", mwaa.LoggingLevelCritical), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), resource.TestCheckResourceAttr(resourceName, "logging_configuration.#", "1"), @@ -198,7 +198,7 @@ func TestAccMWAAEnvironment_log(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEnvironmentLoggingConfigurationConfig(rName, "false", mwaa.LoggingLevelInfo), + Config: testAccEnvironmentConfig_logging(rName, "false", mwaa.LoggingLevelInfo), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), resource.TestCheckResourceAttr(resourceName, "logging_configuration.#", "1"), @@ -246,7 +246,7 @@ func TestAccMWAAEnvironment_full(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentFullConfig(rName), + Config: testAccEnvironmentConfig_full(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), resource.TestCheckResourceAttr(resourceName, "airflow_configuration_options.%", "2"), @@ -322,7 +322,7 @@ func TestAccMWAAEnvironment_pluginsS3ObjectVersion(t *testing.T) { CheckDestroy: testAccCheckEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccEnvironmentPluginsS3ObjectVersionConfig(rName, "test"), + Config: testAccEnvironmentConfig_pluginsS3ObjectVersion(rName, "test"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), resource.TestCheckResourceAttrPair(resourceName, "plugins_s3_object_version", s3ObjectResourceName, "version_id"), @@ -334,7 +334,7 @@ func TestAccMWAAEnvironment_pluginsS3ObjectVersion(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEnvironmentPluginsS3ObjectVersionConfig(rName, "test-updated"), + Config: testAccEnvironmentConfig_pluginsS3ObjectVersion(rName, "test-updated"), Check: resource.ComposeTestCheckFunc( testAccCheckEnvironmentExists(resourceName, &environment), resource.TestCheckResourceAttrPair(resourceName, "plugins_s3_object_version", s3ObjectResourceName, "version_id"), @@ -595,7 +595,7 @@ POLICY `, rName) } -func testAccEnvironmentBasicConfig(rName string) string { +func testAccEnvironmentConfig_basic(rName string) string { return testAccEnvironmentBase(rName) + fmt.Sprintf(` resource "aws_mwaa_environment" "test" { dag_s3_path = aws_s3_object.dags.key @@ -612,7 +612,7 @@ resource "aws_mwaa_environment" "test" { `, rName) } -func testAccEnvironmentAirflowConfigurationOptionsConfig(rName, retries, parallelism string) string { +func testAccEnvironmentConfig_airflowOptions(rName, retries, parallelism string) string { return testAccEnvironmentBase(rName) + fmt.Sprintf(` resource "aws_mwaa_environment" "test" { airflow_configuration_options = { @@ -634,7 +634,7 @@ resource "aws_mwaa_environment" "test" { `, rName, retries, parallelism) } -func testAccEnvironmentLoggingConfigurationConfig(rName, logEnabled, logLevel string) string { +func testAccEnvironmentConfig_logging(rName, logEnabled, logLevel string) string { return testAccEnvironmentBase(rName) + fmt.Sprintf(` resource "aws_mwaa_environment" "test" { dag_s3_path = aws_s3_object.dags.key @@ -679,7 +679,7 @@ resource "aws_mwaa_environment" "test" { `, rName, logEnabled, logLevel) } -func testAccEnvironmentFullConfig(rName string) string { +func testAccEnvironmentConfig_full(rName string) string { return testAccEnvironmentBase(rName) + fmt.Sprintf(` resource "aws_mwaa_environment" "test" { airflow_configuration_options = { @@ -790,7 +790,7 @@ resource "aws_s3_object" "requirements" { `, rName) } -func testAccEnvironmentPluginsS3ObjectVersionConfig(rName, content string) string { +func testAccEnvironmentConfig_pluginsS3ObjectVersion(rName, content string) string { return testAccEnvironmentBase(rName) + fmt.Sprintf(` resource "aws_mwaa_environment" "test" { dag_s3_path = aws_s3_object.dags.key diff --git a/internal/service/neptune/cluster.go b/internal/service/neptune/cluster.go index 33e22f8fe81..dd3248d45dc 100644 --- a/internal/service/neptune/cluster.go +++ b/internal/service/neptune/cluster.go @@ -25,7 +25,7 @@ const ( // A constant for the supported CloudwatchLogsExports types // is not currently available in the AWS sdk-for-go // https://docs.aws.amazon.com/sdk-for-go/api/service/neptune/#pkg-constants - CloudwatchLogsExportsAudit = "audit" + cloudWatchLogsExportsAudit = "audit" DefaultPort = 8182 ) @@ -47,6 +47,14 @@ func ResourceCluster() *schema.Resource { Schema: map[string]*schema.Schema{ + // allow_major_version_upgrade is used to indicate whether upgrades between different major versions + // are allowed. + "allow_major_version_upgrade": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + // apply_immediately is used to determine when the update modifications // take place. "apply_immediately": { @@ -122,7 +130,7 @@ func ResourceCluster() *schema.Resource { Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: validation.StringInSlice([]string{ - CloudwatchLogsExportsAudit, + cloudWatchLogsExportsAudit, }, false), }, Set: schema.HashString, @@ -560,8 +568,9 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { requestUpdate := false req := &neptune.ModifyDBClusterInput{ - ApplyImmediately: aws.Bool(d.Get("apply_immediately").(bool)), - DBClusterIdentifier: aws.String(d.Id()), + AllowMajorVersionUpgrade: aws.Bool(d.Get("allow_major_version_upgrade").(bool)), + ApplyImmediately: aws.Bool(d.Get("apply_immediately").(bool)), + DBClusterIdentifier: aws.String(d.Id()), } if d.HasChange("copy_tags_to_snapshot") { diff --git a/internal/service/neptune/cluster_endpoint_test.go b/internal/service/neptune/cluster_endpoint_test.go index 4dede97b0e6..e96b95007d4 100644 --- a/internal/service/neptune/cluster_endpoint_test.go +++ b/internal/service/neptune/cluster_endpoint_test.go @@ -29,7 +29,7 @@ func TestAccNeptuneClusterEndpoint_basic(t *testing.T) { CheckDestroy: testAccCheckClusterEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEndpointConfig(rName), + Config: testAccClusterEndpointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(resourceName, &dbCluster), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "rds", regexp.MustCompile(`cluster-endpoint:.+`)), @@ -66,7 +66,7 @@ func TestAccNeptuneClusterEndpoint_tags(t *testing.T) { CheckDestroy: testAccCheckClusterEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEndpointTags1Config(rName, "key1", "value1"), + Config: testAccClusterEndpointConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -79,7 +79,7 @@ func TestAccNeptuneClusterEndpoint_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterEndpointTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccClusterEndpointConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -88,7 +88,7 @@ func TestAccNeptuneClusterEndpoint_tags(t *testing.T) { ), }, { - Config: testAccClusterEndpointTags1Config(rName, "key2", "value2"), + Config: testAccClusterEndpointConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -111,7 +111,7 @@ func TestAccNeptuneClusterEndpoint_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEndpointConfig(rName), + Config: testAccClusterEndpointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(resourceName, &dbCluster), acctest.CheckResourceDisappears(acctest.Provider, tfneptune.ResourceClusterEndpoint(), resourceName), @@ -134,7 +134,7 @@ func TestAccNeptuneClusterEndpoint_Disappears_cluster(t *testing.T) { CheckDestroy: testAccCheckClusterEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEndpointConfig(rName), + Config: testAccClusterEndpointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(resourceName, &dbCluster), acctest.CheckResourceDisappears(acctest.Provider, tfneptune.ResourceCluster(), "aws_neptune_cluster.test"), @@ -215,7 +215,7 @@ resource "aws_neptune_cluster" "test" { `, rName)) } -func testAccClusterEndpointConfig(rName string) string { +func testAccClusterEndpointConfig_basic(rName string) string { return acctest.ConfigCompose(testAccClusterEndpointBaseConfig(rName), fmt.Sprintf(` resource "aws_neptune_cluster_endpoint" "test" { cluster_identifier = aws_neptune_cluster.test.cluster_identifier @@ -225,7 +225,7 @@ resource "aws_neptune_cluster_endpoint" "test" { `, rName)) } -func testAccClusterEndpointTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccClusterEndpointConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccClusterEndpointBaseConfig(rName), fmt.Sprintf(` resource "aws_neptune_cluster_endpoint" "test" { cluster_identifier = aws_neptune_cluster.test.cluster_identifier @@ -239,7 +239,7 @@ resource "aws_neptune_cluster_endpoint" "test" { `, rName, tagKey1, tagValue1)) } -func testAccClusterEndpointTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccClusterEndpointConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccClusterEndpointBaseConfig(rName), fmt.Sprintf(` resource "aws_neptune_cluster_endpoint" "test" { cluster_identifier = aws_neptune_cluster.test.cluster_identifier diff --git a/internal/service/neptune/cluster_instance_test.go b/internal/service/neptune/cluster_instance_test.go index 254167c83a9..1d75c928486 100644 --- a/internal/service/neptune/cluster_instance_test.go +++ b/internal/service/neptune/cluster_instance_test.go @@ -34,7 +34,7 @@ func TestAccNeptuneClusterInstance_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceConfig(clusterInstanceName, rInt), + Config: testAccClusterInstanceConfig_basic(clusterInstanceName, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &v), testAccCheckClusterInstanceAttributes(&v), @@ -61,7 +61,7 @@ func TestAccNeptuneClusterInstance_basic(t *testing.T) { ), }, { - Config: testAccClusterInstanceModifiedConfig(clusterInstanceName, rInt), + Config: testAccClusterInstanceConfig_modified(clusterInstanceName, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &v), testAccCheckClusterInstanceAttributes(&v), @@ -138,7 +138,7 @@ func TestAccNeptuneClusterInstance_withSubnetGroup(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceConfig_withSubnetGroup(rInt), + Config: testAccClusterInstanceConfig_subnetGroup(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &v), testAccCheckClusterInstanceAttributes(&v), @@ -187,7 +187,7 @@ func TestAccNeptuneClusterInstance_kmsKey(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceKMSKeyConfig(rInt), + Config: testAccClusterInstanceConfig_kmsKey(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "kms_key_arn", kmsKeyResourceName, "arn"), @@ -262,7 +262,7 @@ func testAccCheckClusterAddress(v *neptune.DBInstance, resourceName string, port } } -func testAccClusterInstanceConfig(instanceName string, n int) string { +func testAccClusterInstanceConfig_basic(instanceName string, n int) string { return acctest.ConfigCompose( testAccClusterBaseConfig(), fmt.Sprintf(` @@ -305,7 +305,7 @@ resource "aws_neptune_parameter_group" "test" { `, instanceName, n)) } -func testAccClusterInstanceModifiedConfig(instanceName string, n int) string { +func testAccClusterInstanceConfig_modified(instanceName string, n int) string { return acctest.ConfigCompose( testAccClusterBaseConfig(), fmt.Sprintf(` @@ -393,7 +393,7 @@ resource "aws_neptune_parameter_group" "test" { `, n)) } -func testAccClusterInstanceConfig_withSubnetGroup(n int) string { +func testAccClusterInstanceConfig_subnetGroup(n int) string { return acctest.ConfigCompose( testAccClusterBaseConfig(), fmt.Sprintf(` @@ -572,7 +572,7 @@ resource "aws_neptune_subnet_group" "test" { `, n)) } -func testAccClusterInstanceKMSKeyConfig(n int) string { +func testAccClusterInstanceConfig_kmsKey(n int) string { return acctest.ConfigCompose( testAccClusterBaseConfig(), fmt.Sprintf(` diff --git a/internal/service/neptune/cluster_parameter_group_test.go b/internal/service/neptune/cluster_parameter_group_test.go index 6a4f6e2d444..578ecd519dc 100644 --- a/internal/service/neptune/cluster_parameter_group_test.go +++ b/internal/service/neptune/cluster_parameter_group_test.go @@ -30,7 +30,7 @@ func TestAccNeptuneClusterParameterGroup_basic(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupConfig(parameterGroupName), + Config: testAccClusterParameterGroupConfig_basic(parameterGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -63,7 +63,7 @@ func TestAccNeptuneClusterParameterGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupConfig_namePrefix, + Config: testAccClusterParameterGroupConfig_namePrefixEmpty, Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile("^tf-test-")), @@ -119,7 +119,7 @@ func TestAccNeptuneClusterParameterGroup_description(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupConfig_Description(parameterGroupName, "custom description"), + Config: testAccClusterParameterGroupConfig_description(parameterGroupName, "custom description"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -149,7 +149,7 @@ func TestAccNeptuneClusterParameterGroup_NamePrefix_parameter(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupConfig_NamePrefix_Parameter(prefix, "neptune_enable_audit_log", "1"), + Config: testAccClusterParameterGroupConfig_namePrefix(prefix, "neptune_enable_audit_log", "1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -167,7 +167,7 @@ func TestAccNeptuneClusterParameterGroup_NamePrefix_parameter(t *testing.T) { ImportStateVerifyIgnore: []string{"name_prefix"}, }, { - Config: testAccClusterParameterGroupConfig_NamePrefix_Parameter(prefix, "neptune_enable_audit_log", "0"), + Config: testAccClusterParameterGroupConfig_namePrefix(prefix, "neptune_enable_audit_log", "0"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), @@ -196,7 +196,7 @@ func TestAccNeptuneClusterParameterGroup_parameter(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupConfig_Parameter(parameterGroupName, "neptune_enable_audit_log", "1"), + Config: testAccClusterParameterGroupConfig_one(parameterGroupName, "neptune_enable_audit_log", "1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -214,7 +214,7 @@ func TestAccNeptuneClusterParameterGroup_parameter(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterParameterGroupConfig_Parameter(parameterGroupName, "neptune_enable_audit_log", "0"), + Config: testAccClusterParameterGroupConfig_one(parameterGroupName, "neptune_enable_audit_log", "0"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -244,7 +244,7 @@ func TestAccNeptuneClusterParameterGroup_tags(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupConfig_Tags(parameterGroupName, "key1", "value1"), + Config: testAccClusterParameterGroupConfig_tags(parameterGroupName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -258,7 +258,7 @@ func TestAccNeptuneClusterParameterGroup_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterParameterGroupConfig_Tags(parameterGroupName, "key1", "value2"), + Config: testAccClusterParameterGroupConfig_tags(parameterGroupName, "key1", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -267,7 +267,7 @@ func TestAccNeptuneClusterParameterGroup_tags(t *testing.T) { ), }, { - Config: testAccClusterParameterGroupConfig_Tags(parameterGroupName, "key2", "value2"), + Config: testAccClusterParameterGroupConfig_tags(parameterGroupName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -358,7 +358,7 @@ func testAccCheckClusterParameterGroupExists(n string, v *neptune.DBClusterParam } } -func testAccClusterParameterGroupConfig_Description(name, description string) string { +func testAccClusterParameterGroupConfig_description(name, description string) string { return fmt.Sprintf(` resource "aws_neptune_cluster_parameter_group" "test" { description = "%s" @@ -368,7 +368,7 @@ resource "aws_neptune_cluster_parameter_group" "test" { `, description, name) } -func testAccClusterParameterGroupConfig_Parameter(name, pName, pValue string) string { +func testAccClusterParameterGroupConfig_one(name, pName, pValue string) string { return fmt.Sprintf(` resource "aws_neptune_cluster_parameter_group" "test" { family = "neptune1" @@ -382,7 +382,7 @@ resource "aws_neptune_cluster_parameter_group" "test" { `, name, pName, pValue) } -func testAccClusterParameterGroupConfig_NamePrefix_Parameter(namePrefix, pName, pValue string) string { +func testAccClusterParameterGroupConfig_namePrefix(namePrefix, pName, pValue string) string { return fmt.Sprintf(` resource "aws_neptune_cluster_parameter_group" "test" { family = "neptune1" @@ -396,7 +396,7 @@ resource "aws_neptune_cluster_parameter_group" "test" { `, namePrefix, pName, pValue) } -func testAccClusterParameterGroupConfig_Tags(name, tKey, tValue string) string { +func testAccClusterParameterGroupConfig_tags(name, tKey, tValue string) string { return fmt.Sprintf(` resource "aws_neptune_cluster_parameter_group" "test" { family = "neptune1" @@ -409,7 +409,7 @@ resource "aws_neptune_cluster_parameter_group" "test" { `, name, tKey, tValue) } -func testAccClusterParameterGroupConfig(name string) string { +func testAccClusterParameterGroupConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_neptune_cluster_parameter_group" "test" { family = "neptune1" @@ -418,7 +418,7 @@ resource "aws_neptune_cluster_parameter_group" "test" { `, name) } -const testAccClusterParameterGroupConfig_namePrefix = ` +const testAccClusterParameterGroupConfig_namePrefixEmpty = ` resource "aws_neptune_cluster_parameter_group" "test" { family = "neptune1" name_prefix = "tf-test-" diff --git a/internal/service/neptune/cluster_snapshot_test.go b/internal/service/neptune/cluster_snapshot_test.go index b047ce3bdb4..1415704c096 100644 --- a/internal/service/neptune/cluster_snapshot_test.go +++ b/internal/service/neptune/cluster_snapshot_test.go @@ -27,7 +27,7 @@ func TestAccNeptuneClusterSnapshot_basic(t *testing.T) { CheckDestroy: testAccCheckClusterSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterSnapshotConfig(rName), + Config: testAccClusterSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterSnapshotExists(resourceName, &dbClusterSnapshot), resource.TestCheckResourceAttrSet(resourceName, "allocated_storage"), @@ -114,7 +114,7 @@ func testAccCheckClusterSnapshotExists(resourceName string, dbClusterSnapshot *n } } -func testAccClusterSnapshotConfig(rName string) string { +func testAccClusterSnapshotConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q diff --git a/internal/service/neptune/cluster_test.go b/internal/service/neptune/cluster_test.go index 442a60956a6..2ec72d6882f 100644 --- a/internal/service/neptune/cluster_test.go +++ b/internal/service/neptune/cluster_test.go @@ -31,7 +31,7 @@ func TestAccNeptuneCluster_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "rds", regexp.MustCompile(`cluster:.+`)), @@ -55,6 +55,7 @@ func TestAccNeptuneCluster_basic(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -73,7 +74,7 @@ func TestAccNeptuneCluster_copyTagsToSnapshot(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterCopyTagsConfig(rName, true), + Config: testAccClusterConfig_copyTags(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_snapshot", "true"), @@ -88,17 +89,18 @@ func TestAccNeptuneCluster_copyTagsToSnapshot(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, { - Config: testAccClusterCopyTagsConfig(rName, false), + Config: testAccClusterConfig_copyTags(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_snapshot", "false"), ), }, { - Config: testAccClusterCopyTagsConfig(rName, true), + Config: testAccClusterConfig_copyTags(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_snapshot", "true"), @@ -135,6 +137,7 @@ func TestAccNeptuneCluster_namePrefix(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -153,7 +156,7 @@ func TestAccNeptuneCluster_takeFinalSnapshot(t *testing.T) { CheckDestroy: testAccCheckClusterSnapshot(rName), Steps: []resource.TestStep{ { - Config: testAccClusterWithFinalSnapshotConfig(rName), + Config: testAccClusterConfig_finalSnapshot(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), ), @@ -167,6 +170,7 @@ func TestAccNeptuneCluster_takeFinalSnapshot(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -185,7 +189,7 @@ func TestAccNeptuneCluster_tags(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterTags1Config(rName, "key1", "value1"), + Config: testAccClusterConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -201,10 +205,11 @@ func TestAccNeptuneCluster_tags(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, { - Config: testAccClusterTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccClusterConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -213,7 +218,7 @@ func TestAccNeptuneCluster_tags(t *testing.T) { ), }, { - Config: testAccClusterTags1Config(rName, "key2", "value2"), + Config: testAccClusterConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -236,20 +241,20 @@ func TestAccNeptuneCluster_updateIAMRoles(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterIncludingIAMRolesConfig(rName), + Config: testAccClusterConfig_includingIAMRoles(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), ), }, { - Config: testAccClusterAddIAMRolesConfig(rName), + Config: testAccClusterConfig_addIAMRoles(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "iam_roles.#", "2"), ), }, { - Config: testAccClusterRemoveIAMRolesConfig(rName), + Config: testAccClusterConfig_removeIAMRoles(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "iam_roles.#", "1"), @@ -264,6 +269,7 @@ func TestAccNeptuneCluster_updateIAMRoles(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -298,6 +304,7 @@ func TestAccNeptuneCluster_kmsKey(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -331,6 +338,7 @@ func TestAccNeptuneCluster_encrypted(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -375,6 +383,7 @@ func TestAccNeptuneCluster_backupsUpdate(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -408,6 +417,7 @@ func TestAccNeptuneCluster_iamAuth(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -426,7 +436,7 @@ func TestAccNeptuneCluster_updateCloudWatchLogsExports(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckNoResourceAttr(resourceName, "enable_cloudwatch_logs_exports.#"), @@ -441,7 +451,7 @@ func TestAccNeptuneCluster_updateCloudWatchLogsExports(t *testing.T) { ), }, { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "enable_cloudwatch_logs_exports.#", "0"), @@ -456,6 +466,7 @@ func TestAccNeptuneCluster_updateCloudWatchLogsExports(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -489,6 +500,7 @@ func TestAccNeptuneCluster_updateEngineVersion(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, { @@ -507,6 +519,60 @@ func TestAccNeptuneCluster_updateEngineVersion(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", + }, + }, + }, + }) +} + +func TestAccNeptuneCluster_updateEngineMajorVersion(t *testing.T) { + var dbCluster neptune.DBCluster + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_neptune_cluster.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, neptune.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccClusterConfig_engineVersion(rName, "1.0.2.1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckClusterExists(resourceName, &dbCluster), + resource.TestCheckResourceAttr(resourceName, "engine_version", "1.0.2.1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "apply_immediately", + "cluster_identifier_prefix", + "final_snapshot_identifier", + "skip_final_snapshot", + "allow_major_version_upgrade", + }, + }, + { + Config: testAccClusterConfig_engineMajorVersionUpdate(rName, "1.1.1.0"), + Check: resource.ComposeTestCheckFunc( + testAccCheckClusterExists(resourceName, &dbCluster), + resource.TestCheckResourceAttr(resourceName, "engine_version", "1.1.1.0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "apply_immediately", + "cluster_identifier_prefix", + "final_snapshot_identifier", + "skip_final_snapshot", + "allow_major_version_upgrade", }, }, }, @@ -525,7 +591,7 @@ func TestAccNeptuneCluster_deleteProtection(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "false"), @@ -540,17 +606,18 @@ func TestAccNeptuneCluster_deleteProtection(t *testing.T) { "cluster_identifier_prefix", "final_snapshot_identifier", "skip_final_snapshot", + "allow_major_version_upgrade", }, }, { - Config: testAccClusterDeleteProtectionConfig(rName, true), + Config: testAccClusterConfig_deleteProtection(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "true"), ), }, { - Config: testAccClusterDeleteProtectionConfig(rName, false), + Config: testAccClusterConfig_deleteProtection(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "false"), @@ -572,7 +639,7 @@ func TestAccNeptuneCluster_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), acctest.CheckResourceDisappears(acctest.Provider, tfneptune.ResourceCluster(), resourceName), @@ -713,7 +780,7 @@ locals { `) } -func testAccClusterConfig(rName string) string { +func testAccClusterConfig_basic(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %q @@ -725,7 +792,7 @@ resource "aws_neptune_cluster" "test" { `, rName)) } -func testAccClusterCopyTagsConfig(rName string, copy bool) string { +func testAccClusterConfig_copyTags(rName string, copy bool) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q @@ -738,7 +805,7 @@ resource "aws_neptune_cluster" "test" { `, rName, copy)) } -func testAccClusterDeleteProtectionConfig(rName string, isProtected bool) string { +func testAccClusterConfig_deleteProtection(rName string, isProtected bool) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %q @@ -762,7 +829,7 @@ resource "aws_neptune_cluster" "test" { `, rName) } -func testAccClusterWithFinalSnapshotConfig(rName string) string { +func testAccClusterConfig_finalSnapshot(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q @@ -773,7 +840,7 @@ resource "aws_neptune_cluster" "test" { `, rName)) } -func testAccClusterTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccClusterConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q @@ -789,7 +856,7 @@ resource "aws_neptune_cluster" "test" { `, rName, tagKey1, tagValue1)) } -func testAccClusterTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccClusterConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q @@ -806,7 +873,7 @@ resource "aws_neptune_cluster" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccClusterIncludingIAMRolesConfig(rName string) string { +func testAccClusterConfig_includingIAMRoles(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -893,7 +960,7 @@ resource "aws_neptune_cluster" "test" { `, rName)) } -func testAccClusterAddIAMRolesConfig(rName string) string { +func testAccClusterConfig_addIAMRoles(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -980,7 +1047,7 @@ resource "aws_neptune_cluster" "test" { `, rName)) } -func testAccClusterRemoveIAMRolesConfig(rName string) string { +func testAccClusterConfig_removeIAMRoles(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -1127,17 +1194,8 @@ resource "aws_neptune_cluster" "test" { `, rName)) } -func testAccClusterConfig_engineVersion(rName, engineVersion string) string { +func testAccClusterConfig_engineVersionBase(rName string) string { return acctest.ConfigCompose(testAccClusterBaseConfig(), fmt.Sprintf(` -resource "aws_neptune_cluster" "test" { - cluster_identifier = %[1]q - apply_immediately = true - availability_zones = local.availability_zone_names - engine_version = %[2]q - neptune_cluster_parameter_group_name = "default.neptune1" - skip_final_snapshot = true -} - data "aws_neptune_orderable_db_instance" "test" { engine = "neptune" engine_version = aws_neptune_cluster.test.engine_version @@ -1154,5 +1212,32 @@ resource "aws_neptune_cluster_instance" "test" { neptune_parameter_group_name = aws_neptune_cluster.test.neptune_cluster_parameter_group_name promotion_tier = "3" } +`, rName)) +} + +func testAccClusterConfig_engineVersion(rName, engineVersion string) string { + return acctest.ConfigCompose(testAccClusterConfig_engineVersionBase(rName), fmt.Sprintf(` +resource "aws_neptune_cluster" "test" { + cluster_identifier = %[1]q + apply_immediately = true + availability_zones = local.availability_zone_names + engine_version = %[2]q + neptune_cluster_parameter_group_name = "default.neptune1" + skip_final_snapshot = true +} +`, rName, engineVersion)) +} + +func testAccClusterConfig_engineMajorVersionUpdate(rName, engineVersion string) string { + return acctest.ConfigCompose(testAccClusterConfig_engineVersionBase(rName), fmt.Sprintf(` +resource "aws_neptune_cluster" "test" { + cluster_identifier = %[1]q + apply_immediately = true + availability_zones = local.availability_zone_names + engine_version = %[2]q + neptune_cluster_parameter_group_name = "default.neptune1" + skip_final_snapshot = true + allow_major_version_upgrade = true +} `, rName, engineVersion)) } diff --git a/internal/service/neptune/engine_version_data_source_test.go b/internal/service/neptune/engine_version_data_source_test.go index 7bc66aae23d..f72c05bc24d 100644 --- a/internal/service/neptune/engine_version_data_source_test.go +++ b/internal/service/neptune/engine_version_data_source_test.go @@ -23,7 +23,7 @@ func TestAccNeptuneEngineVersionDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccEngineVersionBasicDataSourceConfig(version), + Config: testAccEngineVersionDataSourceConfig_basic(version), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "engine", "neptune"), resource.TestCheckResourceAttr(dataSourceName, "version", version), @@ -51,7 +51,7 @@ func TestAccNeptuneEngineVersionDataSource_preferred(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccEngineVersionPreferredDataSourceConfig(), + Config: testAccEngineVersionDataSourceConfig_preferred(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "engine", "neptune"), resource.TestCheckResourceAttr(dataSourceName, "version", "1.0.3.0"), @@ -71,7 +71,7 @@ func TestAccNeptuneEngineVersionDataSource_defaultOnly(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccEngineVersionDefaultOnlyDataSourceConfig(), + Config: testAccEngineVersionDataSourceConfig_defaultOnly(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "engine", "neptune"), resource.TestCheckResourceAttrSet(dataSourceName, "version"), @@ -100,7 +100,7 @@ func testAccEngineVersionPreCheck(t *testing.T) { } } -func testAccEngineVersionBasicDataSourceConfig(version string) string { +func testAccEngineVersionDataSourceConfig_basic(version string) string { return fmt.Sprintf(` data "aws_neptune_engine_version" "test" { engine = "neptune" @@ -109,7 +109,7 @@ data "aws_neptune_engine_version" "test" { `, version) } -func testAccEngineVersionPreferredDataSourceConfig() string { +func testAccEngineVersionDataSourceConfig_preferred() string { return ` data "aws_neptune_engine_version" "test" { preferred_versions = ["85.9.12", "1.0.3.0", "1.0.2.2"] @@ -117,7 +117,7 @@ data "aws_neptune_engine_version" "test" { ` } -func testAccEngineVersionDefaultOnlyDataSourceConfig() string { +func testAccEngineVersionDataSourceConfig_defaultOnly() string { return ` data "aws_neptune_engine_version" "test" {} ` diff --git a/internal/service/neptune/event_subscription_test.go b/internal/service/neptune/event_subscription_test.go index 8e1848e2ed1..5b10666d2b3 100644 --- a/internal/service/neptune/event_subscription_test.go +++ b/internal/service/neptune/event_subscription_test.go @@ -29,7 +29,7 @@ func TestAccNeptuneEventSubscription_basic(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionConfig(rName, rInt), + Config: testAccEventSubscriptionConfig_basic(rName, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("es:%s", rName)), @@ -41,7 +41,7 @@ func TestAccNeptuneEventSubscription_basic(t *testing.T) { ), }, { - Config: testAccEventSubscriptionUpdateConfig(rName, rInt), + Config: testAccEventSubscriptionConfig_update(rName, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -73,7 +73,7 @@ func TestAccNeptuneEventSubscription_withPrefix(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionWithPrefixConfig(rInt), + Config: testAccEventSubscriptionConfig_prefix(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestMatchResourceAttr(resourceName, "name", startsWithPrefix), @@ -102,7 +102,7 @@ func TestAccNeptuneEventSubscription_withSourceIDs(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionWithSourceIDsConfig(rInt), + Config: testAccEventSubscriptionConfig_sourceIDs(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "source_type", "db-parameter-group"), @@ -110,7 +110,7 @@ func TestAccNeptuneEventSubscription_withSourceIDs(t *testing.T) { ), }, { - Config: testAccEventSubscriptionUpdateSourceIDsConfig(rInt), + Config: testAccEventSubscriptionConfig_updateSourceIDs(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "source_type", "db-parameter-group"), @@ -140,7 +140,7 @@ func TestAccNeptuneEventSubscription_withCategories(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionConfig(rName, rInt), + Config: testAccEventSubscriptionConfig_basic(rName, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "source_type", "db-instance"), @@ -148,7 +148,7 @@ func TestAccNeptuneEventSubscription_withCategories(t *testing.T) { ), }, { - Config: testAccEventSubscriptionUpdateCategoriesConfig(rName, rInt), + Config: testAccEventSubscriptionConfig_updateCategories(rName, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "source_type", "db-instance"), @@ -228,7 +228,7 @@ func testAccCheckEventSubscriptionDestroy(s *terraform.State) error { return nil } -func testAccEventSubscriptionConfig(subscriptionName string, rInt int) string { +func testAccEventSubscriptionConfig_basic(subscriptionName string, rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" @@ -254,7 +254,7 @@ resource "aws_neptune_event_subscription" "test" { `, rInt, subscriptionName) } -func testAccEventSubscriptionUpdateConfig(subscriptionName string, rInt int) string { +func testAccEventSubscriptionConfig_update(subscriptionName string, rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" @@ -277,7 +277,7 @@ resource "aws_neptune_event_subscription" "test" { `, rInt, subscriptionName) } -func testAccEventSubscriptionWithPrefixConfig(rInt int) string { +func testAccEventSubscriptionConfig_prefix(rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { name = "tf-acc-test-neptune-event-subs-sns-topic-%d" @@ -303,7 +303,7 @@ resource "aws_neptune_event_subscription" "test" { `, rInt) } -func testAccEventSubscriptionWithSourceIDsConfig(rInt int) string { +func testAccEventSubscriptionConfig_sourceIDs(rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" @@ -332,7 +332,7 @@ resource "aws_neptune_event_subscription" "test" { `, rInt) } -func testAccEventSubscriptionUpdateSourceIDsConfig(rInt int) string { +func testAccEventSubscriptionConfig_updateSourceIDs(rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" @@ -367,7 +367,7 @@ resource "aws_neptune_event_subscription" "test" { `, rInt) } -func testAccEventSubscriptionUpdateCategoriesConfig(subscriptionName string, rInt int) string { +func testAccEventSubscriptionConfig_updateCategories(subscriptionName string, rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" diff --git a/internal/service/neptune/orderable_db_instance_data_source_test.go b/internal/service/neptune/orderable_db_instance_data_source_test.go index ad85a91e7a6..6f2df278a3c 100644 --- a/internal/service/neptune/orderable_db_instance_data_source_test.go +++ b/internal/service/neptune/orderable_db_instance_data_source_test.go @@ -25,7 +25,7 @@ func TestAccNeptuneOrderableDBInstanceDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOrderableDBInstanceBasicDataSourceConfig(class, engine, engineVersion, licenseModel), + Config: testAccOrderableDBInstanceDataSourceConfig_basic(class, engine, engineVersion, licenseModel), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "engine", engine), resource.TestCheckResourceAttr(dataSourceName, "engine_version", engineVersion), @@ -51,7 +51,7 @@ func TestAccNeptuneOrderableDBInstanceDataSource_preferred(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOrderableDBInstancePreferredDataSourceConfig(engine, engineVersion, licenseModel, preferredOption), + Config: testAccOrderableDBInstanceDataSourceConfig_preferred(engine, engineVersion, licenseModel, preferredOption), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "engine", engine), resource.TestCheckResourceAttr(dataSourceName, "engine_version", engineVersion), @@ -81,7 +81,7 @@ func testAccPreCheckOrderableDBInstance(t *testing.T) { } } -func testAccOrderableDBInstanceBasicDataSourceConfig(class, engine, version, license string) string { +func testAccOrderableDBInstanceDataSourceConfig_basic(class, engine, version, license string) string { return fmt.Sprintf(` data "aws_neptune_orderable_db_instance" "test" { instance_class = %q @@ -92,7 +92,7 @@ data "aws_neptune_orderable_db_instance" "test" { `, class, engine, version, license) } -func testAccOrderableDBInstancePreferredDataSourceConfig(engine, version, license, preferredOption string) string { +func testAccOrderableDBInstanceDataSourceConfig_preferred(engine, version, license, preferredOption string) string { return fmt.Sprintf(` data "aws_neptune_orderable_db_instance" "test" { engine = %q diff --git a/internal/service/neptune/parameter_group_test.go b/internal/service/neptune/parameter_group_test.go index 6637cd257c1..ca55f208481 100644 --- a/internal/service/neptune/parameter_group_test.go +++ b/internal/service/neptune/parameter_group_test.go @@ -27,7 +27,7 @@ func TestAccNeptuneParameterGroup_basic(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig_Required(rName), + Config: testAccParameterGroupConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, rName), @@ -60,7 +60,7 @@ func TestAccNeptuneParameterGroup_description(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig_Description(rName, "description1"), + Config: testAccParameterGroupConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, rName), @@ -88,7 +88,7 @@ func TestAccNeptuneParameterGroup_parameter(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig_Parameter(rName, "neptune_query_timeout", "25", "pending-reboot"), + Config: testAccParameterGroupConfig_basic(rName, "neptune_query_timeout", "25", "pending-reboot"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, rName), @@ -107,12 +107,12 @@ func TestAccNeptuneParameterGroup_parameter(t *testing.T) { }, // This test should be updated with a dynamic parameter when available { - Config: testAccParameterGroupConfig_Parameter(rName, "neptune_query_timeout", "25", "immediate"), + Config: testAccParameterGroupConfig_basic(rName, "neptune_query_timeout", "25", "immediate"), ExpectError: regexp.MustCompile(`cannot use immediate apply method for static parameter`), }, // Test removing the configuration { - Config: testAccParameterGroupConfig_Required(rName), + Config: testAccParameterGroupConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, rName), @@ -136,7 +136,7 @@ func TestAccNeptuneParameterGroup_tags(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig_Tags_SingleTag(rName, "key1", "value1"), + Config: testAccParameterGroupConfig_tagsSingle(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -149,7 +149,7 @@ func TestAccNeptuneParameterGroup_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupConfig_Tags_SingleTag(rName, "key1", "value2"), + Config: testAccParameterGroupConfig_tagsSingle(rName, "key1", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -157,7 +157,7 @@ func TestAccNeptuneParameterGroup_tags(t *testing.T) { ), }, { - Config: testAccParameterGroupConfig_Tags_MultipleTags(rName, "key2", "value2", "key3", "value3"), + Config: testAccParameterGroupConfig_tagsMultiple(rName, "key2", "value2", "key3", "value3"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -246,7 +246,7 @@ func testAccCheckParameterGroupExists(n string, v *neptune.DBParameterGroup) res } } -func testAccParameterGroupConfig_Parameter(rName, pName, pValue, pApplyMethod string) string { +func testAccParameterGroupConfig_basic(rName, pName, pValue, pApplyMethod string) string { return fmt.Sprintf(` resource "aws_neptune_parameter_group" "test" { family = "neptune1" @@ -261,7 +261,7 @@ resource "aws_neptune_parameter_group" "test" { `, rName, pApplyMethod, pName, pValue) } -func testAccParameterGroupConfig_Description(rName, description string) string { +func testAccParameterGroupConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_neptune_parameter_group" "test" { description = %q @@ -271,7 +271,7 @@ resource "aws_neptune_parameter_group" "test" { `, description, rName) } -func testAccParameterGroupConfig_Required(rName string) string { +func testAccParameterGroupConfig_required(rName string) string { return fmt.Sprintf(` resource "aws_neptune_parameter_group" "test" { family = "neptune1" @@ -280,7 +280,7 @@ resource "aws_neptune_parameter_group" "test" { `, rName) } -func testAccParameterGroupConfig_Tags_SingleTag(name, tKey, tValue string) string { +func testAccParameterGroupConfig_tagsSingle(name, tKey, tValue string) string { return fmt.Sprintf(` resource "aws_neptune_parameter_group" "test" { family = "neptune1" @@ -293,7 +293,7 @@ resource "aws_neptune_parameter_group" "test" { `, name, tKey, tValue) } -func testAccParameterGroupConfig_Tags_MultipleTags(name, tKey1, tValue1, tKey2, tValue2 string) string { +func testAccParameterGroupConfig_tagsMultiple(name, tKey1, tValue1, tKey2, tValue2 string) string { return fmt.Sprintf(` resource "aws_neptune_parameter_group" "test" { family = "neptune1" diff --git a/internal/service/networkfirewall/firewall_policy_test.go b/internal/service/networkfirewall/firewall_policy_test.go index 255728c355c..52ba9bb49a2 100644 --- a/internal/service/networkfirewall/firewall_policy_test.go +++ b/internal/service/networkfirewall/firewall_policy_test.go @@ -28,7 +28,7 @@ func TestAccNetworkFirewallFirewallPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "network-firewall", fmt.Sprintf("firewall-policy/%s", rName)), @@ -63,7 +63,7 @@ func TestAccNetworkFirewallFirewallPolicy_statefulDefaultActions(t *testing.T) { CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statefulDefaultActions(rName), + Config: testAccFirewallPolicyConfig_statefulDefaultActions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -92,7 +92,7 @@ func TestAccNetworkFirewallFirewallPolicy_statefulEngineOption(t *testing.T) { CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statefulEngineOptions(rName, "STRICT_ORDER"), + Config: testAccFirewallPolicyConfig_statefulEngineOptions(rName, "STRICT_ORDER"), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -121,7 +121,7 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatefulEngineOption(t *testing. CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statefulEngineOptions(rName, "DEFAULT_ACTION_ORDER"), + Config: testAccFirewallPolicyConfig_statefulEngineOptions(rName, "DEFAULT_ACTION_ORDER"), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy1), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -130,7 +130,7 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatefulEngineOption(t *testing. ), }, { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy2), testAccCheckFirewallPolicyNotRecreated(&firewallPolicy1, &firewallPolicy2), @@ -138,7 +138,7 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatefulEngineOption(t *testing. ), }, { - Config: testAccFirewallPolicy_statefulEngineOptions(rName, "STRICT_ORDER"), + Config: testAccFirewallPolicyConfig_statefulEngineOptions(rName, "STRICT_ORDER"), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy3), testAccCheckFirewallPolicyRecreated(&firewallPolicy2, &firewallPolicy3), @@ -169,7 +169,7 @@ func TestAccNetworkFirewallFirewallPolicy_statefulRuleGroupReference(t *testing. CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statefulRuleGroupReference(rName), + Config: testAccFirewallPolicyConfig_statefulRuleGroupReference(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -200,7 +200,7 @@ func TestAccNetworkFirewallFirewallPolicy_statefulRuleGroupReferenceManaged(t *t CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statefulRuleGroupReferenceManaged(rName), + Config: testAccFirewallPolicyConfig_statefulRuleGroupReferenceManaged(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), ), @@ -227,13 +227,13 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatefulRuleGroupReference(t *te CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), ), }, { - Config: testAccFirewallPolicy_statefulRuleGroupReference(rName), + Config: testAccFirewallPolicyConfig_statefulRuleGroupReference(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -242,7 +242,7 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatefulRuleGroupReference(t *te ), }, { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), ), @@ -270,7 +270,7 @@ func TestAccNetworkFirewallFirewallPolicy_multipleStatefulRuleGroupReferences(t CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_multipleStatefulRuleGroupReferences(rName), + Config: testAccFirewallPolicyConfig_multipleStatefulRuleGroupReferences(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -280,7 +280,7 @@ func TestAccNetworkFirewallFirewallPolicy_multipleStatefulRuleGroupReferences(t ), }, { - Config: testAccFirewallPolicy_singleStatefulRuleGroupReference(rName), + Config: testAccFirewallPolicyConfig_singleStatefulRuleGroupReference(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -310,7 +310,7 @@ func TestAccNetworkFirewallFirewallPolicy_statefulRuleGroupPriorityReference(t * CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statefulRuleGroupPriorityReference(rName, "1"), + Config: testAccFirewallPolicyConfig_statefulRuleGroupPriorityReference(rName, "1"), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -341,7 +341,7 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatefulRuleGroupPriorityReferen CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statefulRuleGroupPriorityReference(rName, "1"), + Config: testAccFirewallPolicyConfig_statefulRuleGroupPriorityReference(rName, "1"), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy1), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -351,7 +351,7 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatefulRuleGroupPriorityReferen ), }, { - Config: testAccFirewallPolicy_statefulRuleGroupPriorityReference(rName, "2"), + Config: testAccFirewallPolicyConfig_statefulRuleGroupPriorityReference(rName, "2"), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy2), testAccCheckFirewallPolicyNotRecreated(&firewallPolicy1, &firewallPolicy2), @@ -383,7 +383,7 @@ func TestAccNetworkFirewallFirewallPolicy_statelessRuleGroupReference(t *testing CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statelessRuleGroupReference(rName, 20), + Config: testAccFirewallPolicyConfig_statelessRuleGroupReference(rName, 20), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -395,7 +395,7 @@ func TestAccNetworkFirewallFirewallPolicy_statelessRuleGroupReference(t *testing ), }, { - Config: testAccFirewallPolicy_statelessRuleGroupReference(rName, 1), + Config: testAccFirewallPolicyConfig_statelessRuleGroupReference(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -427,13 +427,13 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatelessRuleGroupReference(t *t CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), ), }, { - Config: testAccFirewallPolicy_statelessRuleGroupReference(rName, 20), + Config: testAccFirewallPolicyConfig_statelessRuleGroupReference(rName, 20), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -444,7 +444,7 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatelessRuleGroupReference(t *t ), }, { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -474,7 +474,7 @@ func TestAccNetworkFirewallFirewallPolicy_multipleStatelessRuleGroupReferences(t CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_multipleStatelessRuleGroupReferences(rName), + Config: testAccFirewallPolicyConfig_multipleStatelessRuleGroupReferences(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -490,7 +490,7 @@ func TestAccNetworkFirewallFirewallPolicy_multipleStatelessRuleGroupReferences(t ), }, { - Config: testAccFirewallPolicy_singleStatelessRuleGroupReference(rName), + Config: testAccFirewallPolicyConfig_singleStatelessRuleGroupReference(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -522,7 +522,7 @@ func TestAccNetworkFirewallFirewallPolicy_statelessCustomAction(t *testing.T) { CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statelessCustomAction(rName), + Config: testAccFirewallPolicyConfig_statelessCustomAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -556,13 +556,13 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatelessCustomAction(t *testing CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy1), ), }, { - Config: testAccFirewallPolicy_statelessCustomAction(rName), + Config: testAccFirewallPolicyConfig_statelessCustomAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy2), testAccCheckFirewallPolicyRecreated(&firewallPolicy1, &firewallPolicy2), @@ -577,7 +577,7 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatelessCustomAction(t *testing ), }, { - Config: testAccFirewallPolicy_updateStatelessCustomAction(rName), + Config: testAccFirewallPolicyConfig_updateStatelessCustomAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy3), testAccCheckFirewallPolicyRecreated(&firewallPolicy2, &firewallPolicy3), @@ -592,7 +592,7 @@ func TestAccNetworkFirewallFirewallPolicy_updateStatelessCustomAction(t *testing ), }, { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy4), testAccCheckFirewallPolicyRecreated(&firewallPolicy3, &firewallPolicy4), @@ -620,7 +620,7 @@ func TestAccNetworkFirewallFirewallPolicy_multipleStatelessCustomActions(t *test CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_multipleStatelessCustomActions(rName), + Config: testAccFirewallPolicyConfig_multipleStatelessCustomActions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy1), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -640,7 +640,7 @@ func TestAccNetworkFirewallFirewallPolicy_multipleStatelessCustomActions(t *test ), }, { - Config: testAccFirewallPolicy_statelessCustomAction(rName), + Config: testAccFirewallPolicyConfig_statelessCustomAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy2), testAccCheckFirewallPolicyRecreated(&firewallPolicy1, &firewallPolicy2), @@ -676,7 +676,7 @@ func TestAccNetworkFirewallFirewallPolicy_statefulRuleGroupReferenceAndCustomAct CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_statefulRuleGroupReferenceAndStatelessCustomAction(rName), + Config: testAccFirewallPolicyConfig_statefulRuleGroupReferenceAndStatelessCustomAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -691,7 +691,7 @@ func TestAccNetworkFirewallFirewallPolicy_statefulRuleGroupReferenceAndCustomAct ), }, { - Config: testAccFirewallPolicy_statefulRuleGroupReference(rName), + Config: testAccFirewallPolicyConfig_statefulRuleGroupReference(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "firewall_policy.#", "1"), @@ -720,7 +720,7 @@ func TestAccNetworkFirewallFirewallPolicy_tags(t *testing.T) { CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_oneTag(rName), + Config: testAccFirewallPolicyConfig_oneTag(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -728,7 +728,7 @@ func TestAccNetworkFirewallFirewallPolicy_tags(t *testing.T) { ), }, { - Config: testAccFirewallPolicy_twoTags(rName), + Config: testAccFirewallPolicyConfig_twoTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -737,7 +737,7 @@ func TestAccNetworkFirewallFirewallPolicy_tags(t *testing.T) { ), }, { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -764,7 +764,7 @@ func TestAccNetworkFirewallFirewallPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckFirewallPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccFirewallPolicy_basic(rName), + Config: testAccFirewallPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFirewallPolicyExists(resourceName, &firewallPolicy), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkfirewall.ResourceFirewallPolicy(), resourceName), @@ -934,7 +934,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, count, rName) } -func testAccFirewallPolicy_basic(rName string) string { +func testAccFirewallPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_firewall_policy" "test" { name = %q @@ -946,7 +946,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName) } -func testAccFirewallPolicy_oneTag(rName string) string { +func testAccFirewallPolicyConfig_oneTag(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_firewall_policy" "test" { name = %[1]q @@ -961,7 +961,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName) } -func testAccFirewallPolicy_twoTags(rName string) string { +func testAccFirewallPolicyConfig_twoTags(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_firewall_policy" "test" { name = %[1]q @@ -977,7 +977,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName) } -func testAccFirewallPolicy_statefulEngineOptions(rName, rule_order string) string { +func testAccFirewallPolicyConfig_statefulEngineOptions(rName, rule_order string) string { return fmt.Sprintf(` resource "aws_networkfirewall_firewall_policy" "test" { name = %[1]q @@ -992,7 +992,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName, rule_order) } -func testAccFirewallPolicy_statefulDefaultActions(rName string) string { +func testAccFirewallPolicyConfig_statefulDefaultActions(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_firewall_policy" "test" { name = %[1]q @@ -1008,7 +1008,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName) } -func testAccFirewallPolicy_statefulRuleGroupReference(rName string) string { +func testAccFirewallPolicyConfig_statefulRuleGroupReference(rName string) string { return acctest.ConfigCompose( testAccFirewallPolicyStatefulRuleGroupDependencies(rName, 1), fmt.Sprintf(` @@ -1025,7 +1025,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName)) } -func testAccFirewallPolicy_statefulRuleGroupReferenceManaged(rName string) string { +func testAccFirewallPolicyConfig_statefulRuleGroupReferenceManaged(rName string) string { return acctest.ConfigCompose( testAccFirewallPolicyStatefulRuleGroupDependencies(rName, 1), fmt.Sprintf(` @@ -1047,7 +1047,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName)) } -func testAccFirewallPolicy_multipleStatefulRuleGroupReferences(rName string) string { +func testAccFirewallPolicyConfig_multipleStatefulRuleGroupReferences(rName string) string { return acctest.ConfigCompose( testAccFirewallPolicyStatefulRuleGroupDependencies(rName, 2), fmt.Sprintf(` @@ -1067,7 +1067,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName)) } -func testAccFirewallPolicy_statefulRuleGroupPriorityReference(rName, priority string) string { +func testAccFirewallPolicyConfig_statefulRuleGroupPriorityReference(rName, priority string) string { return acctest.ConfigCompose( testAccFirewallPolicyStatefulRuleGroupStrictDependencies(rName, 1), fmt.Sprintf(` @@ -1088,7 +1088,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName, priority)) } -func testAccFirewallPolicy_singleStatefulRuleGroupReference(rName string) string { +func testAccFirewallPolicyConfig_singleStatefulRuleGroupReference(rName string) string { return acctest.ConfigCompose( testAccFirewallPolicyStatefulRuleGroupDependencies(rName, 2), fmt.Sprintf(` @@ -1105,7 +1105,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName)) } -func testAccFirewallPolicy_statelessRuleGroupReference(rName string, priority int) string { +func testAccFirewallPolicyConfig_statelessRuleGroupReference(rName string, priority int) string { return acctest.ConfigCompose( testAccFirewallPolicyStatelessRuleGroupDependencies(rName, 1), fmt.Sprintf(` @@ -1123,7 +1123,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName, priority)) } -func testAccFirewallPolicy_multipleStatelessRuleGroupReferences(rName string) string { +func testAccFirewallPolicyConfig_multipleStatelessRuleGroupReferences(rName string) string { return acctest.ConfigCompose( testAccFirewallPolicyStatelessRuleGroupDependencies(rName, 2), fmt.Sprintf(` @@ -1145,7 +1145,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName)) } -func testAccFirewallPolicy_singleStatelessRuleGroupReference(rName string) string { +func testAccFirewallPolicyConfig_singleStatelessRuleGroupReference(rName string) string { return acctest.ConfigCompose( testAccFirewallPolicyStatelessRuleGroupDependencies(rName, 2), fmt.Sprintf(` @@ -1163,7 +1163,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName)) } -func testAccFirewallPolicy_statelessCustomAction(rName string) string { +func testAccFirewallPolicyConfig_statelessCustomAction(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_firewall_policy" "test" { name = %[1]q @@ -1185,7 +1185,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName) } -func testAccFirewallPolicy_updateStatelessCustomAction(rName string) string { +func testAccFirewallPolicyConfig_updateStatelessCustomAction(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_firewall_policy" "test" { name = %[1]q @@ -1207,7 +1207,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName) } -func testAccFirewallPolicy_multipleStatelessCustomActions(rName string) string { +func testAccFirewallPolicyConfig_multipleStatelessCustomActions(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_firewall_policy" "test" { name = %[1]q @@ -1239,7 +1239,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName) } -func testAccFirewallPolicy_statefulRuleGroupReferenceAndStatelessCustomAction(rName string) string { +func testAccFirewallPolicyConfig_statefulRuleGroupReferenceAndStatelessCustomAction(rName string) string { return acctest.ConfigCompose( testAccFirewallPolicyStatefulRuleGroupDependencies(rName, 1), fmt.Sprintf(` diff --git a/internal/service/networkfirewall/logging_configuration_test.go b/internal/service/networkfirewall/logging_configuration_test.go index 40a9793fc91..9b076e56459 100644 --- a/internal/service/networkfirewall/logging_configuration_test.go +++ b/internal/service/networkfirewall/logging_configuration_test.go @@ -294,7 +294,7 @@ func TestAccNetworkFirewallLoggingConfiguration_S3LogDestination_prefix(t *testi ), }, { - Config: testAccLoggingConfigurationConfig_S3_updatePrefix(bucketName, rName, networkfirewall.LogDestinationTypeS3, networkfirewall.LogTypeFlow), + Config: testAccLoggingConfigurationConfig_s3UpdatePrefix(bucketName, rName, networkfirewall.LogDestinationTypeS3, networkfirewall.LogTypeFlow), Check: resource.ComposeTestCheckFunc( testAccCheckLoggingConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "logging_configuration.#", "1"), @@ -335,7 +335,7 @@ func TestAccNetworkFirewallLoggingConfiguration_updateFirewallARN(t *testing.T) }, { // ForceNew Firewall i.e. LoggingConfiguration Resource - Config: testAccLoggingConfigurationConfig_S3_updateFirewallARN(bucketName, rName, networkfirewall.LogDestinationTypeS3, networkfirewall.LogTypeFlow), + Config: testAccLoggingConfigurationConfig_s3UpdateFirewallARN(bucketName, rName, networkfirewall.LogDestinationTypeS3, networkfirewall.LogTypeFlow), Check: resource.ComposeTestCheckFunc( testAccCheckLoggingConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "firewall_arn", firewallResourceName, "arn"), @@ -897,7 +897,7 @@ resource "aws_networkfirewall_logging_configuration" "test" { `, rName, destinationType, logType)) } -func testAccLoggingConfigurationConfig_S3_updateFirewallARN(bucketName, rName, destinationType, logType string) string { +func testAccLoggingConfigurationConfig_s3UpdateFirewallARN(bucketName, rName, destinationType, logType string) string { return acctest.ConfigCompose( testAccLoggingConfigurationBaseConfig_updateFirewall(rName), testAccLoggingConfigurationS3BucketDependencyConfig(bucketName), @@ -918,7 +918,7 @@ resource "aws_networkfirewall_logging_configuration" "test" { `, rName, destinationType, logType)) } -func testAccLoggingConfigurationConfig_S3_updatePrefix(bucketName, rName, destinationType, logType string) string { +func testAccLoggingConfigurationConfig_s3UpdatePrefix(bucketName, rName, destinationType, logType string) string { return acctest.ConfigCompose( testAccLoggingConfigurationBaseConfig(rName), testAccLoggingConfigurationS3BucketDependencyConfig(bucketName), diff --git a/internal/service/networkfirewall/resource_policy_test.go b/internal/service/networkfirewall/resource_policy_test.go index 26dc6100d80..763ecebf192 100644 --- a/internal/service/networkfirewall/resource_policy_test.go +++ b/internal/service/networkfirewall/resource_policy_test.go @@ -27,7 +27,7 @@ func TestAccNetworkFirewallResourcePolicy_basic(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyConfig(rName), + Config: testAccResourcePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_networkfirewall_firewall_policy.test", "arn"), @@ -54,7 +54,7 @@ func TestAccNetworkFirewallResourcePolicy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyConfig(rName), + Config: testAccResourcePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_networkfirewall_firewall_policy.test", "arn"), @@ -62,7 +62,7 @@ func TestAccNetworkFirewallResourcePolicy_ignoreEquivalent(t *testing.T) { ), }, { - Config: testAccResourcePolicyEquivalentConfig(rName), + Config: testAccResourcePolicyConfig_equivalent(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(`"Action":\["network-firewall:CreateFirewall","network-firewall:UpdateFirewall","network-firewall:AssociateFirewallPolicy","network-firewall:ListFirewallPolicies"\]`)), @@ -83,7 +83,7 @@ func TestAccNetworkFirewallResourcePolicy_ruleGroup(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicy_ruleGroup(rName), + Config: testAccResourcePolicyConfig_ruleGroup(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "resource_arn", "aws_networkfirewall_rule_group.test", "arn"), @@ -92,7 +92,7 @@ func TestAccNetworkFirewallResourcePolicy_ruleGroup(t *testing.T) { }, { // Update the policy's Actions - Config: testAccResourcePolicy_ruleGroup_updatePolicy(rName), + Config: testAccResourcePolicyConfig_ruleGroupUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(`"Action":\["network-firewall:CreateFirewallPolicy","network-firewall:UpdateFirewallPolicy","network-firewall:ListRuleGroups"\]`)), @@ -118,7 +118,7 @@ func TestAccNetworkFirewallResourcePolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyConfig(rName), + Config: testAccResourcePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkfirewall.ResourceResourcePolicy(), resourceName), @@ -140,7 +140,7 @@ func TestAccNetworkFirewallResourcePolicy_Disappears_firewallPolicy(t *testing.T CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicyConfig(rName), + Config: testAccResourcePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkfirewall.ResourceFirewallPolicy(), "aws_networkfirewall_firewall_policy.test"), @@ -162,7 +162,7 @@ func TestAccNetworkFirewallResourcePolicy_Disappears_ruleGroup(t *testing.T) { CheckDestroy: testAccCheckResourcePolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccResourcePolicy_ruleGroup(rName), + Config: testAccResourcePolicyConfig_ruleGroup(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourcePolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkfirewall.ResourceRuleGroup(), "aws_networkfirewall_rule_group.test"), @@ -237,7 +237,7 @@ resource "aws_networkfirewall_firewall_policy" "test" { `, rName) } -func testAccResourcePolicyConfig(rName string) string { +func testAccResourcePolicyConfig_basic(rName string) string { return acctest.ConfigCompose( testAccResourcePolicyFirewallPolicyBaseConfig(rName), ` resource "aws_networkfirewall_resource_policy" "test" { @@ -263,7 +263,7 @@ resource "aws_networkfirewall_resource_policy" "test" { `) } -func testAccResourcePolicyEquivalentConfig(rName string) string { +func testAccResourcePolicyConfig_equivalent(rName string) string { return acctest.ConfigCompose( testAccResourcePolicyFirewallPolicyBaseConfig(rName), ` resource "aws_networkfirewall_resource_policy" "test" { @@ -312,7 +312,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccResourcePolicy_ruleGroup(rName string) string { +func testAccResourcePolicyConfig_ruleGroup(rName string) string { return acctest.ConfigCompose( testAccResourcePolicyRuleGroupBaseConfig(rName), ` resource "aws_networkfirewall_resource_policy" "test" { @@ -337,7 +337,7 @@ resource "aws_networkfirewall_resource_policy" "test" { `) } -func testAccResourcePolicy_ruleGroup_updatePolicy(rName string) string { +func testAccResourcePolicyConfig_ruleGroupUpdate(rName string) string { return acctest.ConfigCompose( testAccResourcePolicyRuleGroupBaseConfig(rName), ` resource "aws_networkfirewall_resource_policy" "test" { diff --git a/internal/service/networkfirewall/rule_group_test.go b/internal/service/networkfirewall/rule_group_test.go index 18ad8c76fc4..6e74451cc82 100644 --- a/internal/service/networkfirewall/rule_group_test.go +++ b/internal/service/networkfirewall/rule_group_test.go @@ -28,7 +28,7 @@ func TestAccNetworkFirewallRuleGroup_Basic_rulesSourceList(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_rulesSourceList(rName), + Config: testAccRuleGroupConfig_basicSourceList(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "network-firewall", fmt.Sprintf("stateful-rulegroup/%s", rName)), @@ -68,7 +68,7 @@ func TestAccNetworkFirewallRuleGroup_Basic_statefulRule(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_statefulRule(rName), + Config: testAccRuleGroupConfig_basicStateful(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "network-firewall", fmt.Sprintf("stateful-rulegroup/%s", rName)), @@ -117,7 +117,7 @@ func TestAccNetworkFirewallRuleGroup_Basic_statelessRule(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_statelessRule(rName), + Config: testAccRuleGroupConfig_basicStateless(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "network-firewall", fmt.Sprintf("stateless-rulegroup/%s", rName)), @@ -161,7 +161,7 @@ func TestAccNetworkFirewallRuleGroup_Basic_rules(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_rules(rName, rules), + Config: testAccRuleGroupConfig_basic(rName, rules), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "network-firewall", fmt.Sprintf("stateful-rulegroup/%s", rName)), @@ -199,7 +199,7 @@ func TestAccNetworkFirewallRuleGroup_statefulRuleOptions(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_statefulRuleOptions(rName, rules, "STRICT_ORDER"), + Config: testAccRuleGroupConfig_statefulOptions(rName, rules, "STRICT_ORDER"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.stateful_rule_options.#", "1"), @@ -228,7 +228,7 @@ func TestAccNetworkFirewallRuleGroup_updateStatefulRuleOptions(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_statefulRuleOptions(rName, rules, "STRICT_ORDER"), + Config: testAccRuleGroupConfig_statefulOptions(rName, rules, "STRICT_ORDER"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup1), resource.TestCheckResourceAttr(resourceName, "rule_group.0.stateful_rule_options.#", "1"), @@ -236,7 +236,7 @@ func TestAccNetworkFirewallRuleGroup_updateStatefulRuleOptions(t *testing.T) { ), }, { - Config: testAccRuleGroupConfig_statefulRuleOptions(rName, rules, "DEFAULT_ACTION_ORDER"), + Config: testAccRuleGroupConfig_statefulOptions(rName, rules, "DEFAULT_ACTION_ORDER"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup2), testAccCheckRuleGroupRecreated(&ruleGroup1, &ruleGroup2), @@ -245,7 +245,7 @@ func TestAccNetworkFirewallRuleGroup_updateStatefulRuleOptions(t *testing.T) { ), }, { - Config: testAccRuleGroupConfig_rulesSourceRulesString(rName, rules), + Config: testAccRuleGroupConfig_sourceString(rName, rules), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup3), testAccCheckRuleGroupNotRecreated(&ruleGroup2, &ruleGroup3), @@ -273,7 +273,7 @@ func TestAccNetworkFirewallRuleGroup_statelessRuleWithCustomAction(t *testing.T) CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_statelessRuleCustomAction(rName), + Config: testAccRuleGroupConfig_statelessCustomAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "network-firewall", fmt.Sprintf("stateless-rulegroup/%s", rName)), @@ -326,13 +326,13 @@ func TestAccNetworkFirewallRuleGroup_updateRules(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_rules(rName, rules), + Config: testAccRuleGroupConfig_basic(rName, rules), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), ), }, { - Config: testAccRuleGroupConfig_Basic_rules(rName, updatedRules), + Config: testAccRuleGroupConfig_basic(rName, updatedRules), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rules", updatedRules), @@ -364,13 +364,13 @@ func TestAccNetworkFirewallRuleGroup_updateRulesSourceList(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_rulesSourceList(rName), + Config: testAccRuleGroupConfig_basicSourceList(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), ), }, { - Config: testAccRuleGroupConfig_updateRulesSourceList(rName), + Config: testAccRuleGroupConfig_updateSourceList(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "network-firewall", fmt.Sprintf("stateful-rulegroup/%s", rName)), @@ -410,7 +410,7 @@ func TestAccNetworkFirewallRuleGroup_rulesSourceAndRuleVariables(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_RulesSourceList_ruleVariables(rName), + Config: testAccRuleGroupConfig_sourceListVariables(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.#", "1"), @@ -427,7 +427,7 @@ func TestAccNetworkFirewallRuleGroup_rulesSourceAndRuleVariables(t *testing.T) { ), }, { - Config: testAccRuleGroupConfig_RulesSourceList_updateRuleVariables(rName), + Config: testAccRuleGroupConfig_sourceListUpdateVariables(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.#", "1"), @@ -459,7 +459,7 @@ func TestAccNetworkFirewallRuleGroup_rulesSourceAndRuleVariables(t *testing.T) { ), }, { - Config: testAccRuleGroupConfig_Basic_rulesSourceList(rName), + Config: testAccRuleGroupConfig_basicSourceList(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.#", "1"), @@ -490,13 +490,13 @@ func TestAccNetworkFirewallRuleGroup_updateStatefulRule(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_statefulRule(rName), + Config: testAccRuleGroupConfig_basicStateful(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), ), }, { - Config: testAccRuleGroupConfig_updateStatefulRule(rName), + Config: testAccRuleGroupConfig_updateStateful(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.rules_source.0.stateful_rule.#", "1"), @@ -537,14 +537,14 @@ func TestAccNetworkFirewallRuleGroup_updateMultipleStatefulRules(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_statefulRule(rName), + Config: testAccRuleGroupConfig_basicStateful(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.rules_source.0.stateful_rule.#", "1"), ), }, { - Config: testAccRuleGroupConfig_multipleStatefulRules(rName), + Config: testAccRuleGroupConfig_multipleStateful(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.rules_source.0.stateful_rule.#", "2"), @@ -578,7 +578,7 @@ func TestAccNetworkFirewallRuleGroup_updateMultipleStatefulRules(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRuleGroupConfig_updateStatefulRule(rName), + Config: testAccRuleGroupConfig_updateStateful(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.rules_source.0.stateful_rule.#", "1"), @@ -619,7 +619,7 @@ func TestAccNetworkFirewallRuleGroup_StatefulRule_action(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_StatefulRule_action(rName, networkfirewall.StatefulActionAlert), + Config: testAccRuleGroupConfig_statefulAction(rName, networkfirewall.StatefulActionAlert), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.rules_source.0.stateful_rule.#", "1"), @@ -634,7 +634,7 @@ func TestAccNetworkFirewallRuleGroup_StatefulRule_action(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRuleGroupConfig_StatefulRule_action(rName, networkfirewall.StatefulActionPass), + Config: testAccRuleGroupConfig_statefulAction(rName, networkfirewall.StatefulActionPass), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.rules_source.0.stateful_rule.#", "1"), @@ -649,7 +649,7 @@ func TestAccNetworkFirewallRuleGroup_StatefulRule_action(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRuleGroupConfig_StatefulRule_action(rName, networkfirewall.StatefulActionDrop), + Config: testAccRuleGroupConfig_statefulAction(rName, networkfirewall.StatefulActionDrop), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.rules_source.0.stateful_rule.#", "1"), @@ -680,7 +680,7 @@ func TestAccNetworkFirewallRuleGroup_StatefulRule_header(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_StatefulRule_header(rName, "1990", "1994"), + Config: testAccRuleGroupConfig_statefulHeader(rName, "1990", "1994"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.rules_source.0.stateful_rule.#", "1"), @@ -703,7 +703,7 @@ func TestAccNetworkFirewallRuleGroup_StatefulRule_header(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRuleGroupConfig_StatefulRule_header(rName, "ANY", "ANY"), + Config: testAccRuleGroupConfig_statefulHeader(rName, "ANY", "ANY"), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "rule_group.0.rules_source.0.stateful_rule.#", "1"), @@ -741,13 +741,13 @@ func TestAccNetworkFirewallRuleGroup_updateStatelessRule(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_statelessRule(rName), + Config: testAccRuleGroupConfig_basicStateless(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), ), }, { - Config: testAccRuleGroupConfig_updateStatelessRule(rName), + Config: testAccRuleGroupConfig_updateStateless(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule_group.0.rules_source.0.stateless_rules_and_custom_actions.0.stateless_rule.*", map[string]string{ @@ -808,7 +808,7 @@ func TestAccNetworkFirewallRuleGroup_tags(t *testing.T) { ), }, { - Config: testAccRuleGroupConfig_Basic_rulesSourceList(rName), + Config: testAccRuleGroupConfig_basicSourceList(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -835,7 +835,7 @@ func TestAccNetworkFirewallRuleGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckRuleGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRuleGroupConfig_Basic_rulesSourceList(rName), + Config: testAccRuleGroupConfig_basicSourceList(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRuleGroupExists(resourceName, &ruleGroup), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkfirewall.ResourceRuleGroup(), resourceName), @@ -913,7 +913,7 @@ func testAccCheckRuleGroupRecreated(i, j *networkfirewall.DescribeRuleGroupOutpu } } -func testAccRuleGroupConfig_Basic_rulesSourceList(rName string) string { +func testAccRuleGroupConfig_basicSourceList(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -932,7 +932,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccRuleGroupConfig_RulesSourceList_ruleVariables(rName string) string { +func testAccRuleGroupConfig_sourceListVariables(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -959,7 +959,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccRuleGroupConfig_RulesSourceList_updateRuleVariables(rName string) string { +func testAccRuleGroupConfig_sourceListUpdateVariables(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -998,7 +998,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccRuleGroupConfig_updateRulesSourceList(rName string) string { +func testAccRuleGroupConfig_updateSourceList(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1017,7 +1017,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccRuleGroupConfig_Basic_statefulRule(rName string) string { +func testAccRuleGroupConfig_basicStateful(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1046,7 +1046,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccRuleGroupConfig_StatefulRule_action(rName, action string) string { +func testAccRuleGroupConfig_statefulAction(rName, action string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1075,7 +1075,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName, action) } -func testAccRuleGroupConfig_StatefulRule_header(rName, dstPort, srcPort string) string { +func testAccRuleGroupConfig_statefulHeader(rName, dstPort, srcPort string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1104,7 +1104,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName, dstPort, srcPort) } -func testAccRuleGroupConfig_updateStatefulRule(rName string) string { +func testAccRuleGroupConfig_updateStateful(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1132,7 +1132,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccRuleGroupConfig_multipleStatefulRules(rName string) string { +func testAccRuleGroupConfig_multipleStateful(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1174,7 +1174,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccRuleGroupConfig_Basic_statelessRule(rName string) string { +func testAccRuleGroupConfig_basicStateless(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1204,7 +1204,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccRuleGroupConfig_updateStatelessRule(rName string) string { +func testAccRuleGroupConfig_updateStateless(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1247,7 +1247,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName) } -func testAccRuleGroupConfig_Basic_rules(rName, rules string) string { +func testAccRuleGroupConfig_basic(rName, rules string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1258,7 +1258,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName, rules) } -func testAccRuleGroupConfig_rulesSourceRulesString(rName, rules string) string { +func testAccRuleGroupConfig_sourceString(rName, rules string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1273,7 +1273,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName, rules) } -func testAccRuleGroupConfig_statefulRuleOptions(rName, rules, ruleOrder string) string { +func testAccRuleGroupConfig_statefulOptions(rName, rules, ruleOrder string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 @@ -1291,7 +1291,7 @@ resource "aws_networkfirewall_rule_group" "test" { `, rName, rules, ruleOrder) } -func testAccRuleGroupConfig_statelessRuleCustomAction(rName string) string { +func testAccRuleGroupConfig_statelessCustomAction(rName string) string { return fmt.Sprintf(` resource "aws_networkfirewall_rule_group" "test" { capacity = 100 diff --git a/internal/service/networkmanager/connection_data_source_test.go b/internal/service/networkmanager/connection_data_source_test.go index 3bee8495395..0898b243f9b 100644 --- a/internal/service/networkmanager/connection_data_source_test.go +++ b/internal/service/networkmanager/connection_data_source_test.go @@ -20,7 +20,7 @@ func TestAccNetworkManagerConnectionDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectionDataSourceConfig(rName), + Config: testAccConnectionDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "connected_device_id", resourceName, "connected_device_id"), @@ -36,8 +36,8 @@ func TestAccNetworkManagerConnectionDataSource_basic(t *testing.T) { }) } -func testAccConnectionDataSourceConfig(rName string) string { - return acctest.ConfigCompose(testAccConnectionDescriptionAndLinksConfig(rName), ` +func testAccConnectionDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccConnectionConfig_descriptionAndLinks(rName), ` data "aws_networkmanager_connection" "test" { global_network_id = aws_networkmanager_global_network.test.id connection_id = aws_networkmanager_connection.test.id diff --git a/internal/service/networkmanager/connection_test.go b/internal/service/networkmanager/connection_test.go index a4d96044bce..4975d9fcd28 100644 --- a/internal/service/networkmanager/connection_test.go +++ b/internal/service/networkmanager/connection_test.go @@ -42,7 +42,7 @@ func testAccConnection_basic(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig(rName), + Config: testAccConnectionConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -73,7 +73,7 @@ func testAccConnection_disappears(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfig(rName), + Config: testAccConnectionConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkmanager.ResourceConnection(), resourceName), @@ -95,7 +95,7 @@ func testAccConnection_tags(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionConfigTags1(rName, "key1", "value1"), + Config: testAccConnectionConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -109,7 +109,7 @@ func testAccConnection_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConnectionConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccConnectionConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -118,7 +118,7 @@ func testAccConnection_tags(t *testing.T) { ), }, { - Config: testAccConnectionConfigTags1(rName, "key2", "value2"), + Config: testAccConnectionConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckConnectionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -142,7 +142,7 @@ func testAccConnection_descriptionAndLinks(t *testing.T) { CheckDestroy: testAccCheckConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccConnectionDescriptionAndLinksConfig(rName), + Config: testAccConnectionConfig_descriptionAndLinks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName), resource.TestCheckResourceAttr(resourceName, "connected_link_id", ""), @@ -157,7 +157,7 @@ func testAccConnection_descriptionAndLinks(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConnectionDescriptionAndLinksUpdatedConfig(rName), + Config: testAccConnectionConfig_descriptionAndLinksUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckConnectionExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "connected_link_id", link2ResourceName, "id"), @@ -265,7 +265,7 @@ resource "aws_networkmanager_device" "test2" { `, rName) } -func testAccConnectionConfig(rName string) string { +func testAccConnectionConfig_basic(rName string) string { return acctest.ConfigCompose(testAccConnectionBaseConfig(rName), ` resource "aws_networkmanager_connection" "test" { global_network_id = aws_networkmanager_global_network.test.id @@ -275,7 +275,7 @@ resource "aws_networkmanager_connection" "test" { `) } -func testAccConnectionConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccConnectionConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccConnectionBaseConfig(rName), fmt.Sprintf(` resource "aws_networkmanager_connection" "test" { global_network_id = aws_networkmanager_global_network.test.id @@ -289,7 +289,7 @@ resource "aws_networkmanager_connection" "test" { `, rName, tagKey1, tagValue1)) } -func testAccConnectionConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccConnectionConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccConnectionBaseConfig(rName), fmt.Sprintf(` resource "aws_networkmanager_connection" "test" { global_network_id = aws_networkmanager_global_network.test.id @@ -355,7 +355,7 @@ resource "aws_networkmanager_link_association" "test2" { `, rName)) } -func testAccConnectionDescriptionAndLinksConfig(rName string) string { +func testAccConnectionConfig_descriptionAndLinks(rName string) string { return acctest.ConfigCompose(testAccConnectionDescriptionAndLinksBaseConfig(rName), fmt.Sprintf(` resource "aws_networkmanager_connection" "test" { global_network_id = aws_networkmanager_global_network.test.id @@ -375,7 +375,7 @@ resource "aws_networkmanager_connection" "test" { `, rName)) } -func testAccConnectionDescriptionAndLinksUpdatedConfig(rName string) string { +func testAccConnectionConfig_descriptionAndLinksUpdated(rName string) string { return acctest.ConfigCompose(testAccConnectionDescriptionAndLinksBaseConfig(rName), fmt.Sprintf(` resource "aws_networkmanager_connection" "test" { global_network_id = aws_networkmanager_global_network.test.id diff --git a/internal/service/networkmanager/connections_data_source_test.go b/internal/service/networkmanager/connections_data_source_test.go index 0dbaaac284d..f3eef703736 100644 --- a/internal/service/networkmanager/connections_data_source_test.go +++ b/internal/service/networkmanager/connections_data_source_test.go @@ -21,7 +21,7 @@ func TestAccNetworkManagerConnectionsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccConnectionsDataSourceConfig(rName), + Config: testAccConnectionsDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceAllName, "ids.#", "1"), resource.TestCheckResourceAttr(dataSourceByTagsName, "ids.#", "1"), @@ -31,7 +31,7 @@ func TestAccNetworkManagerConnectionsDataSource_basic(t *testing.T) { }) } -func testAccConnectionsDataSourceConfig(rName string) string { +func testAccConnectionsDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { description = %[1]q diff --git a/internal/service/networkmanager/core_network_policy_document_data_source_test.go b/internal/service/networkmanager/core_network_policy_document_data_source_test.go index 37e8369612e..98ce77bf041 100644 --- a/internal/service/networkmanager/core_network_policy_document_data_source_test.go +++ b/internal/service/networkmanager/core_network_policy_document_data_source_test.go @@ -18,7 +18,7 @@ func TestAccNetworkManagerCoreNetworkPolicyDocumentDataSource_basic(t *testing.T ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCoreNetworkPolicyDocumentBasic, + Config: testAccCoreNetworkPolicyDocumentDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.aws_networkmanager_core_network_policy_document.test", "json", testAccPolicyDocumentExpectedJSON(), @@ -30,7 +30,7 @@ func TestAccNetworkManagerCoreNetworkPolicyDocumentDataSource_basic(t *testing.T } //lintignore:AWSAT003 -var testAccCoreNetworkPolicyDocumentBasic = ` +var testAccCoreNetworkPolicyDocumentDataSourceConfig_basic = ` data "aws_networkmanager_core_network_policy_document" "test" { core_network_configuration { vpn_ecmp_support = false diff --git a/internal/service/networkmanager/customer_gateway_association_test.go b/internal/service/networkmanager/customer_gateway_association_test.go index 0bf6bf4249c..dc9f134c388 100644 --- a/internal/service/networkmanager/customer_gateway_association_test.go +++ b/internal/service/networkmanager/customer_gateway_association_test.go @@ -42,7 +42,7 @@ func testAccCustomerGatewayAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayAssociationConfig(rName), + Config: testAccCustomerGatewayAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayAssociationExists(resourceName), ), @@ -67,7 +67,7 @@ func testAccCustomerGatewayAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayAssociationConfig(rName), + Config: testAccCustomerGatewayAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkmanager.ResourceCustomerGatewayAssociation(), resourceName), @@ -91,7 +91,7 @@ func testAccCustomerGatewayAssociation_Disappears_customerGateway(t *testing.T) CheckDestroy: testAccCheckCustomerGatewayAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayAssociationConfig(rName), + Config: testAccCustomerGatewayAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGatewayAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceVPNConnection(), vpnConnectionResourceName), @@ -162,7 +162,7 @@ func testAccCheckCustomerGatewayAssociationExists(n string) resource.TestCheckFu } } -func testAccCustomerGatewayAssociationConfig(rName string) string { +func testAccCustomerGatewayAssociationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/device_data_source_test.go b/internal/service/networkmanager/device_data_source_test.go index 13f0c11be54..73ee792d29e 100644 --- a/internal/service/networkmanager/device_data_source_test.go +++ b/internal/service/networkmanager/device_data_source_test.go @@ -21,7 +21,7 @@ func TestAccNetworkManagerDeviceDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDeviceDataSourceConfig(rName), + Config: testAccDeviceDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "aws_location.#", resourceName, "aws_location.#"), @@ -40,7 +40,7 @@ func TestAccNetworkManagerDeviceDataSource_basic(t *testing.T) { }) } -func testAccDeviceDataSourceConfig(rName string) string { +func testAccDeviceDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/device_test.go b/internal/service/networkmanager/device_test.go index ff4f282fd74..1418f9a0e5b 100644 --- a/internal/service/networkmanager/device_test.go +++ b/internal/service/networkmanager/device_test.go @@ -26,7 +26,7 @@ func TestAccNetworkManagerDevice_basic(t *testing.T) { CheckDestroy: testAccCheckDeviceDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceConfig(rName), + Config: testAccDeviceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDeviceExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -62,7 +62,7 @@ func TestAccNetworkManagerDevice_disappears(t *testing.T) { CheckDestroy: testAccCheckDeviceDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceConfig(rName), + Config: testAccDeviceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDeviceExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkmanager.ResourceDevice(), resourceName), @@ -84,7 +84,7 @@ func TestAccNetworkManagerDevice_tags(t *testing.T) { CheckDestroy: testAccCheckDeviceDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceConfigTags1(rName, "key1", "value1"), + Config: testAccDeviceConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -98,7 +98,7 @@ func TestAccNetworkManagerDevice_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeviceConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDeviceConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -107,7 +107,7 @@ func TestAccNetworkManagerDevice_tags(t *testing.T) { ), }, { - Config: testAccDeviceConfigTags1(rName, "key2", "value2"), + Config: testAccDeviceConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -131,7 +131,7 @@ func TestAccNetworkManagerDevice_allAttributes(t *testing.T) { CheckDestroy: testAccCheckDeviceDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceAllAttributesConfig(rName), + Config: testAccDeviceConfig_allAttributes(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDeviceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -153,7 +153,7 @@ func TestAccNetworkManagerDevice_allAttributes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeviceAllAttributesUpdatedConfig(rName), + Config: testAccDeviceConfig_allAttributesUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDeviceExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -258,7 +258,7 @@ func testAccCheckDeviceExists(n string) resource.TestCheckFunc { } } -func testAccDeviceConfig(rName string) string { +func testAccDeviceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -272,7 +272,7 @@ resource "aws_networkmanager_device" "test" { `, rName) } -func testAccDeviceConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccDeviceConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -290,7 +290,7 @@ resource "aws_networkmanager_device" "test" { `, rName, tagKey1, tagValue1) } -func testAccDeviceConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDeviceConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -309,7 +309,7 @@ resource "aws_networkmanager_device" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccDeviceAllAttributesConfig(rName string) string { +func testAccDeviceConfig_allAttributes(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -356,7 +356,7 @@ resource "aws_networkmanager_device" "test" { `, rName) } -func testAccDeviceAllAttributesUpdatedConfig(rName string) string { +func testAccDeviceConfig_allAttributesUpdated(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/devices_data_source_test.go b/internal/service/networkmanager/devices_data_source_test.go index 9f59f3e9841..970c652b475 100644 --- a/internal/service/networkmanager/devices_data_source_test.go +++ b/internal/service/networkmanager/devices_data_source_test.go @@ -21,7 +21,7 @@ func TestAccNetworkManagerDevicesDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDevicesDataSourceConfig(rName), + Config: testAccDevicesDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceAllName, "ids.#", "1"), resource.TestCheckResourceAttr(dataSourceByTagsName, "ids.#", "1"), @@ -31,7 +31,7 @@ func TestAccNetworkManagerDevicesDataSource_basic(t *testing.T) { }) } -func testAccDevicesDataSourceConfig(rName string) string { +func testAccDevicesDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/global_network_data_source_test.go b/internal/service/networkmanager/global_network_data_source_test.go index 8ea36dc1b93..b023e813635 100644 --- a/internal/service/networkmanager/global_network_data_source_test.go +++ b/internal/service/networkmanager/global_network_data_source_test.go @@ -21,7 +21,7 @@ func TestAccNetworkManagerGlobalNetworkDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccGlobalNetworkDataSourceConfig(rName), + Config: testAccGlobalNetworkDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "description", resourceName, "description"), @@ -33,7 +33,7 @@ func TestAccNetworkManagerGlobalNetworkDataSource_basic(t *testing.T) { }) } -func testAccGlobalNetworkDataSourceConfig(rName string) string { +func testAccGlobalNetworkDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { description = "test" diff --git a/internal/service/networkmanager/global_network_test.go b/internal/service/networkmanager/global_network_test.go index ff9825e2249..d54160cd831 100644 --- a/internal/service/networkmanager/global_network_test.go +++ b/internal/service/networkmanager/global_network_test.go @@ -25,7 +25,7 @@ func TestAccNetworkManagerGlobalNetwork_basic(t *testing.T) { CheckDestroy: testAccCheckGlobalNetworkDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalNetworkConfig(), + Config: testAccGlobalNetworkConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalNetworkExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "networkmanager", regexp.MustCompile(`global-network/global-network-.+`)), @@ -52,7 +52,7 @@ func TestAccNetworkManagerGlobalNetwork_disappears(t *testing.T) { CheckDestroy: testAccCheckGlobalNetworkDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalNetworkConfig(), + Config: testAccGlobalNetworkConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalNetworkExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkmanager.ResourceGlobalNetwork(), resourceName), @@ -73,7 +73,7 @@ func TestAccNetworkManagerGlobalNetwork_tags(t *testing.T) { CheckDestroy: testAccCheckGlobalNetworkDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalNetworkConfigTags1("key1", "value1"), + Config: testAccGlobalNetworkConfig_tags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalNetworkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -86,7 +86,7 @@ func TestAccNetworkManagerGlobalNetwork_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccGlobalNetworkConfigTags2("key1", "value1updated", "key2", "value2"), + Config: testAccGlobalNetworkConfig_tags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalNetworkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -95,7 +95,7 @@ func TestAccNetworkManagerGlobalNetwork_tags(t *testing.T) { ), }, { - Config: testAccGlobalNetworkConfigTags1("key2", "value2"), + Config: testAccGlobalNetworkConfig_tags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalNetworkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -116,7 +116,7 @@ func TestAccNetworkManagerGlobalNetwork_description(t *testing.T) { CheckDestroy: testAccCheckGlobalNetworkDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalNetworkDescriptionConfig("description1"), + Config: testAccGlobalNetworkConfig_description("description1"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalNetworkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -128,7 +128,7 @@ func TestAccNetworkManagerGlobalNetwork_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccGlobalNetworkDescriptionConfig("description2"), + Config: testAccGlobalNetworkConfig_description("description2"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalNetworkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -185,13 +185,13 @@ func testAccCheckGlobalNetworkExists(n string) resource.TestCheckFunc { } } -func testAccGlobalNetworkConfig() string { +func testAccGlobalNetworkConfig_basic() string { return ` resource "aws_networkmanager_global_network" "test" {} ` } -func testAccGlobalNetworkConfigTags1(tagKey1, tagValue1 string) string { +func testAccGlobalNetworkConfig_tags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -201,7 +201,7 @@ resource "aws_networkmanager_global_network" "test" { `, tagKey1, tagValue1) } -func testAccGlobalNetworkConfigTags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccGlobalNetworkConfig_tags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -212,7 +212,7 @@ resource "aws_networkmanager_global_network" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccGlobalNetworkDescriptionConfig(description string) string { +func testAccGlobalNetworkConfig_description(description string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { description = %[1]q diff --git a/internal/service/networkmanager/global_networks_data_source_test.go b/internal/service/networkmanager/global_networks_data_source_test.go index 116a5dc8308..c41f2bc366d 100644 --- a/internal/service/networkmanager/global_networks_data_source_test.go +++ b/internal/service/networkmanager/global_networks_data_source_test.go @@ -21,7 +21,7 @@ func TestAccNetworkManagerGlobalNetworksDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccGlobalNetworksDataSourceConfig(rName), + Config: testAccGlobalNetworksDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceAllName, "ids.#", "1"), resource.TestCheckResourceAttr(dataSourceByTagsName, "ids.#", "1"), @@ -31,7 +31,7 @@ func TestAccNetworkManagerGlobalNetworksDataSource_basic(t *testing.T) { }) } -func testAccGlobalNetworksDataSourceConfig(rName string) string { +func testAccGlobalNetworksDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test1" { description = "test1" diff --git a/internal/service/networkmanager/link_association_test.go b/internal/service/networkmanager/link_association_test.go index 3a0bb5c99de..6f5d438b34a 100644 --- a/internal/service/networkmanager/link_association_test.go +++ b/internal/service/networkmanager/link_association_test.go @@ -26,7 +26,7 @@ func TestAccNetworkManagerLinkAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckLinkAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccLinkAssociationConfig(rName), + Config: testAccLinkAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLinkAssociationExists(resourceName), ), @@ -51,7 +51,7 @@ func TestAccNetworkManagerLinkAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckLinkAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccLinkAssociationConfig(rName), + Config: testAccLinkAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLinkAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkmanager.ResourceLinkAssociation(), resourceName), @@ -121,7 +121,7 @@ func testAccCheckLinkAssociationExists(n string) resource.TestCheckFunc { } } -func testAccLinkAssociationConfig(rName string) string { +func testAccLinkAssociationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/link_data_source_test.go b/internal/service/networkmanager/link_data_source_test.go index 2abc92a6272..1c34b95ff85 100644 --- a/internal/service/networkmanager/link_data_source_test.go +++ b/internal/service/networkmanager/link_data_source_test.go @@ -21,7 +21,7 @@ func TestAccNetworkManagerLinkDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLinkDataSourceConfig(rName), + Config: testAccLinkDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "bandwidth.#", resourceName, "bandwidth.#"), @@ -38,7 +38,7 @@ func TestAccNetworkManagerLinkDataSource_basic(t *testing.T) { }) } -func testAccLinkDataSourceConfig(rName string) string { +func testAccLinkDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/link_test.go b/internal/service/networkmanager/link_test.go index 6da8bb0bb2c..f82b81a3816 100644 --- a/internal/service/networkmanager/link_test.go +++ b/internal/service/networkmanager/link_test.go @@ -26,7 +26,7 @@ func TestAccNetworkManagerLink_basic(t *testing.T) { CheckDestroy: testAccCheckLinkDestroy, Steps: []resource.TestStep{ { - Config: testAccLinkConfig(rName), + Config: testAccLinkConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLinkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -60,7 +60,7 @@ func TestAccNetworkManagerLink_disappears(t *testing.T) { CheckDestroy: testAccCheckLinkDestroy, Steps: []resource.TestStep{ { - Config: testAccLinkConfig(rName), + Config: testAccLinkConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLinkExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkmanager.ResourceLink(), resourceName), @@ -82,7 +82,7 @@ func TestAccNetworkManagerLink_tags(t *testing.T) { CheckDestroy: testAccCheckLinkDestroy, Steps: []resource.TestStep{ { - Config: testAccLinkConfigTags1(rName, "key1", "value1"), + Config: testAccLinkConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLinkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -96,7 +96,7 @@ func TestAccNetworkManagerLink_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLinkConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccLinkConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLinkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -105,7 +105,7 @@ func TestAccNetworkManagerLink_tags(t *testing.T) { ), }, { - Config: testAccLinkConfigTags1(rName, "key2", "value2"), + Config: testAccLinkConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLinkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -127,7 +127,7 @@ func TestAccNetworkManagerLink_allAttributes(t *testing.T) { CheckDestroy: testAccCheckLinkDestroy, Steps: []resource.TestStep{ { - Config: testAccLinkAllAttributesConfig(rName), + Config: testAccLinkConfig_allAttributes(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLinkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bandwidth.#", "1"), @@ -145,7 +145,7 @@ func TestAccNetworkManagerLink_allAttributes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLinkAllAttributesUpdatedConfig(rName), + Config: testAccLinkConfig_allAttributesUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLinkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bandwidth.#", "1"), @@ -207,7 +207,7 @@ func testAccCheckLinkExists(n string) resource.TestCheckFunc { } } -func testAccLinkConfig(rName string) string { +func testAccLinkConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -235,7 +235,7 @@ resource "aws_networkmanager_link" "test" { `, rName) } -func testAccLinkConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccLinkConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -267,7 +267,7 @@ resource "aws_networkmanager_link" "test" { `, rName, tagKey1, tagValue1) } -func testAccLinkConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccLinkConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -300,7 +300,7 @@ resource "aws_networkmanager_link" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccLinkAllAttributesConfig(rName string) string { +func testAccLinkConfig_allAttributes(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -336,7 +336,7 @@ resource "aws_networkmanager_link" "test" { `, rName) } -func testAccLinkAllAttributesUpdatedConfig(rName string) string { +func testAccLinkConfig_allAttributesUpdated(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/links_data_source_test.go b/internal/service/networkmanager/links_data_source_test.go index 4d8e9ab094c..07cddea51dc 100644 --- a/internal/service/networkmanager/links_data_source_test.go +++ b/internal/service/networkmanager/links_data_source_test.go @@ -21,7 +21,7 @@ func TestAccNetworkManagerLinksDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLinksDataSourceConfig(rName), + Config: testAccLinksDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceAllName, "ids.#", "1"), resource.TestCheckResourceAttr(dataSourceByTagsName, "ids.#", "1"), @@ -31,7 +31,7 @@ func TestAccNetworkManagerLinksDataSource_basic(t *testing.T) { }) } -func testAccLinksDataSourceConfig(rName string) string { +func testAccLinksDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/site_data_source_test.go b/internal/service/networkmanager/site_data_source_test.go index 5f08c4ec034..cc772a9afb4 100644 --- a/internal/service/networkmanager/site_data_source_test.go +++ b/internal/service/networkmanager/site_data_source_test.go @@ -21,7 +21,7 @@ func TestAccNetworkManagerSiteDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSiteDataSourceConfig(rName), + Config: testAccSiteDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "description", resourceName, "description"), @@ -35,7 +35,7 @@ func TestAccNetworkManagerSiteDataSource_basic(t *testing.T) { }) } -func testAccSiteDataSourceConfig(rName string) string { +func testAccSiteDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/site_test.go b/internal/service/networkmanager/site_test.go index 13cff004a6d..ccc4a887794 100644 --- a/internal/service/networkmanager/site_test.go +++ b/internal/service/networkmanager/site_test.go @@ -26,7 +26,7 @@ func TestAccNetworkManagerSite_basic(t *testing.T) { CheckDestroy: testAccCheckSiteDestroy, Steps: []resource.TestStep{ { - Config: testAccSiteConfig(rName), + Config: testAccSiteConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSiteExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -56,7 +56,7 @@ func TestAccNetworkManagerSite_disappears(t *testing.T) { CheckDestroy: testAccCheckSiteDestroy, Steps: []resource.TestStep{ { - Config: testAccSiteConfig(rName), + Config: testAccSiteConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSiteExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkmanager.ResourceSite(), resourceName), @@ -78,7 +78,7 @@ func TestAccNetworkManagerSite_tags(t *testing.T) { CheckDestroy: testAccCheckSiteDestroy, Steps: []resource.TestStep{ { - Config: testAccSiteConfigTags1(rName, "key1", "value1"), + Config: testAccSiteConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSiteExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -92,7 +92,7 @@ func TestAccNetworkManagerSite_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSiteConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccSiteConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSiteExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -101,7 +101,7 @@ func TestAccNetworkManagerSite_tags(t *testing.T) { ), }, { - Config: testAccSiteConfigTags1(rName, "key2", "value2"), + Config: testAccSiteConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSiteExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -123,7 +123,7 @@ func TestAccNetworkManagerSite_description(t *testing.T) { CheckDestroy: testAccCheckSiteDestroy, Steps: []resource.TestStep{ { - Config: testAccSiteDescriptionConfig(rName, "description1"), + Config: testAccSiteConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckSiteExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -136,7 +136,7 @@ func TestAccNetworkManagerSite_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSiteDescriptionConfig(rName, "description2"), + Config: testAccSiteConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckSiteExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -157,7 +157,7 @@ func TestAccNetworkManagerSite_location(t *testing.T) { CheckDestroy: testAccCheckSiteDestroy, Steps: []resource.TestStep{ { - Config: testAccSiteLocationConfig(rName), + Config: testAccSiteConfig_location(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSiteExists(resourceName), resource.TestCheckResourceAttr(resourceName, "location.#", "1"), @@ -173,7 +173,7 @@ func TestAccNetworkManagerSite_location(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSiteLocationUpdatedConfig(rName), + Config: testAccSiteConfig_locationUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSiteExists(resourceName), resource.TestCheckResourceAttr(resourceName, "location.#", "1"), @@ -233,7 +233,7 @@ func testAccCheckSiteExists(n string) resource.TestCheckFunc { } } -func testAccSiteConfig(rName string) string { +func testAccSiteConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -247,7 +247,7 @@ resource "aws_networkmanager_site" "test" { `, rName) } -func testAccSiteConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccSiteConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -265,7 +265,7 @@ resource "aws_networkmanager_site" "test" { `, rName, tagKey1, tagValue1) } -func testAccSiteConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSiteConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -284,7 +284,7 @@ resource "aws_networkmanager_site" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccSiteDescriptionConfig(rName, description string) string { +func testAccSiteConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -303,7 +303,7 @@ resource "aws_networkmanager_site" "test" { `, rName, description) } -func testAccSiteLocationConfig(rName string) string { +func testAccSiteConfig_location(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -327,7 +327,7 @@ resource "aws_networkmanager_site" "test" { `, rName) } -func testAccSiteLocationUpdatedConfig(rName string) string { +func testAccSiteConfig_locationUpdated(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/sites_data_source_test.go b/internal/service/networkmanager/sites_data_source_test.go index e8560cb3356..698411537a7 100644 --- a/internal/service/networkmanager/sites_data_source_test.go +++ b/internal/service/networkmanager/sites_data_source_test.go @@ -21,7 +21,7 @@ func TestAccNetworkManagerSitesDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSitesDataSourceConfig(rName), + Config: testAccSitesDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceAllName, "ids.#", "1"), resource.TestCheckResourceAttr(dataSourceByTagsName, "ids.#", "1"), @@ -31,7 +31,7 @@ func TestAccNetworkManagerSitesDataSource_basic(t *testing.T) { }) } -func testAccSitesDataSourceConfig(rName string) string { +func testAccSitesDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/networkmanager/transit_gateway_connect_peer_association_test.go b/internal/service/networkmanager/transit_gateway_connect_peer_association_test.go index 52e8054e8af..3a9bf4de938 100644 --- a/internal/service/networkmanager/transit_gateway_connect_peer_association_test.go +++ b/internal/service/networkmanager/transit_gateway_connect_peer_association_test.go @@ -42,7 +42,7 @@ func testAccTransitGatewayConnectPeerAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayConnectPeerAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectPeerAssociationConfig(rName), + Config: testAccTransitGatewayConnectPeerAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectPeerAssociationExists(resourceName), ), @@ -67,7 +67,7 @@ func testAccTransitGatewayConnectPeerAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayConnectPeerAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectPeerAssociationConfig(rName), + Config: testAccTransitGatewayConnectPeerAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectPeerAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkmanager.ResourceTransitGatewayConnectPeerAssociation(), resourceName), @@ -90,7 +90,7 @@ func testAccTransitGatewayConnectPeerAssociation_Disappears_connectPeer(t *testi CheckDestroy: testAccCheckTransitGatewayConnectPeerAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayConnectPeerAssociationConfig(rName), + Config: testAccTransitGatewayConnectPeerAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayConnectPeerAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGatewayConnectPeer(), connetPeerResourceName), @@ -160,7 +160,7 @@ func testAccCheckTransitGatewayConnectPeerAssociationExists(n string) resource.T } } -func testAccTransitGatewayConnectPeerAssociationConfig(rName string) string { +func testAccTransitGatewayConnectPeerAssociationConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInDefaultExclude(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/networkmanager/transit_gateway_registration_test.go b/internal/service/networkmanager/transit_gateway_registration_test.go index e2d646f0bb3..2cdb2a1fd6d 100644 --- a/internal/service/networkmanager/transit_gateway_registration_test.go +++ b/internal/service/networkmanager/transit_gateway_registration_test.go @@ -44,7 +44,7 @@ func testAccTransitGatewayRegistration_basic(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRegistrationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRegistrationConfig(rName), + Config: testAccTransitGatewayRegistrationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRegistrationExists(resourceName), ), @@ -69,7 +69,7 @@ func testAccTransitGatewayRegistration_disappears(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRegistrationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRegistrationConfig(rName), + Config: testAccTransitGatewayRegistrationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRegistrationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfnetworkmanager.ResourceTransitGatewayRegistration(), resourceName), @@ -92,7 +92,7 @@ func testAccTransitGatewayRegistration_Disappears_transitGateway(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRegistrationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRegistrationConfig(rName), + Config: testAccTransitGatewayRegistrationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRegistrationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceTransitGateway(), transitGatewayResourceName), @@ -115,7 +115,7 @@ func testAccTransitGatewayRegistration_crossRegion(t *testing.T) { CheckDestroy: testAccCheckTransitGatewayRegistrationDestroy, Steps: []resource.TestStep{ { - Config: testAccTransitGatewayRegistrationCrossRegionConfig(rName), + Config: testAccTransitGatewayRegistrationConfig_crossRegion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTransitGatewayRegistrationExists(resourceName), ), @@ -187,7 +187,7 @@ func testAccCheckTransitGatewayRegistrationExists(n string) resource.TestCheckFu return nil } } -func testAccTransitGatewayRegistrationConfig(rName string) string { +func testAccTransitGatewayRegistrationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { @@ -208,7 +208,7 @@ resource "aws_networkmanager_transit_gateway_registration" "test" { `, rName) } -func testAccTransitGatewayRegistrationCrossRegionConfig(rName string) string { +func testAccTransitGatewayRegistrationConfig_crossRegion(rName string) string { return acctest.ConfigCompose(acctest.ConfigAlternateRegionProvider(), fmt.Sprintf(` resource "aws_networkmanager_global_network" "test" { tags = { diff --git a/internal/service/opensearch/domain.go b/internal/service/opensearch/domain.go index ffeae86e43e..caef55a60a4 100644 --- a/internal/service/opensearch/domain.go +++ b/internal/service/opensearch/domain.go @@ -413,7 +413,7 @@ func ResourceDomain() *schema.Resource { Optional: true, Computed: true, ForceNew: true, - DiffSuppressFunc: suppressEquivalentKmsKeyIds, + DiffSuppressFunc: suppressEquivalentKMSKeyIDs, }, }, }, @@ -1072,7 +1072,7 @@ func inPlaceEncryptionEnableVersion(version string) bool { return false } -func suppressEquivalentKmsKeyIds(k, old, new string, d *schema.ResourceData) bool { +func suppressEquivalentKMSKeyIDs(k, old, new string, d *schema.ResourceData) bool { // The OpenSearch API accepts a short KMS key id but always returns the ARN of the key. // The ARN is of the format 'arn:aws:kms:REGION:ACCOUNT_ID:key/KMS_KEY_ID'. // These should be treated as equivalent. diff --git a/internal/service/opensearch/domain_data_source_test.go b/internal/service/opensearch/domain_data_source_test.go index f889b0df8d4..876d33f5c78 100644 --- a/internal/service/opensearch/domain_data_source_test.go +++ b/internal/service/opensearch/domain_data_source_test.go @@ -26,7 +26,7 @@ func TestAccOpenSearchDomainDataSource_Data_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDomainWithDataSourceConfig(rName, autoTuneStartAtTime), + Config: testAccDomainDataSourceConfig_basic(rName, autoTuneStartAtTime), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "processing", "false"), resource.TestCheckResourceAttrPair(datasourceName, "engine_version", resourceName, "engine_version"), @@ -68,7 +68,7 @@ func TestAccOpenSearchDomainDataSource_Data_advanced(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDomainAdvancedWithDataSourceConfig(rName, autoTuneStartAtTime), + Config: testAccDomainDataSourceConfig_advanced(rName, autoTuneStartAtTime), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "engine_version", resourceName, "engine_version"), resource.TestCheckResourceAttrPair(datasourceName, "auto_tune_options.#", resourceName, "auto_tune_options.#"), @@ -96,7 +96,7 @@ func TestAccOpenSearchDomainDataSource_Data_advanced(t *testing.T) { }) } -func testAccDomainWithDataSourceConfig(rName, autoTuneStartAtTime string) string { +func testAccDomainDataSourceConfig_basic(rName, autoTuneStartAtTime string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -178,7 +178,7 @@ data "aws_opensearch_domain" "test" { `, rName, autoTuneStartAtTime) } -func testAccDomainAdvancedWithDataSourceConfig(rName, autoTuneStartAtTime string) string { +func testAccDomainDataSourceConfig_advanced(rName, autoTuneStartAtTime string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` diff --git a/internal/service/opensearch/domain_policy_test.go b/internal/service/opensearch/domain_policy_test.go index 02384373585..23a8471d771 100644 --- a/internal/service/opensearch/domain_policy_test.go +++ b/internal/service/opensearch/domain_policy_test.go @@ -53,7 +53,7 @@ func TestAccOpenSearchDomainPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainPolicyConfig(ri, policy), + Config: testAccDomainPolicyConfig_basic(ri, policy), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists("aws_opensearch_domain.test", &domain), resource.TestCheckResourceAttr("aws_opensearch_domain.test", "engine_version", "OpenSearch_1.1"), @@ -113,7 +113,7 @@ func buildDomainARN(name, partition, accId, region string) (string, error) { return fmt.Sprintf("arn:%s:es:%s:%s:domain/%s", partition, region, accId, name), nil } -func testAccDomainPolicyConfig(randInt int, policy string) string { +func testAccDomainPolicyConfig_basic(randInt int, policy string) string { return fmt.Sprintf(` resource "aws_opensearch_domain" "test" { domain_name = "tf-test-%d" diff --git a/internal/service/opensearch/domain_saml_options_test.go b/internal/service/opensearch/domain_saml_options_test.go index 713ddaef96d..f9d5ef68fbd 100644 --- a/internal/service/opensearch/domain_saml_options_test.go +++ b/internal/service/opensearch/domain_saml_options_test.go @@ -31,7 +31,7 @@ func TestAccOpenSearchDomainSAMLOptions_basic(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(esDomainResourceName, &domain), testAccCheckESDomainSAMLOptions(esDomainResourceName, resourceName), @@ -65,7 +65,7 @@ func TestAccOpenSearchDomainSAMLOptions_disappears(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( testAccCheckESDomainSAMLOptions(esDomainResourceName, resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfopensearch.ResourceDomainSAMLOptions(), resourceName), @@ -90,7 +90,7 @@ func TestAccOpenSearchDomainSAMLOptions_disappears_Domain(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( testAccCheckESDomainSAMLOptions(esDomainResourceName, resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfopensearch.ResourceDomain(), esDomainResourceName), @@ -116,7 +116,7 @@ func TestAccOpenSearchDomainSAMLOptions_Update(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "saml_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "60"), @@ -124,7 +124,7 @@ func TestAccOpenSearchDomainSAMLOptions_Update(t *testing.T) { ), }, { - Config: testAccDomainSAMLOptionsConfigUpdate(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_update(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "saml_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "180"), @@ -150,7 +150,7 @@ func TestAccOpenSearchDomainSAMLOptions_Disabled(t *testing.T) { CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSAMLOptionsConfig(rUserName, rName, idpEntityId), + Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "saml_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "60"), @@ -158,7 +158,7 @@ func TestAccOpenSearchDomainSAMLOptions_Disabled(t *testing.T) { ), }, { - Config: testAccDomainSAMLOptionsConfigDisabled(rUserName, rName), + Config: testAccDomainSAMLOptionsConfig_disabled(rUserName, rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "saml_options.#", "1"), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "0"), @@ -215,7 +215,7 @@ func testAccCheckESDomainSAMLOptions(esResource string, samlOptionsResource stri } } -func testAccDomainSAMLOptionsConfig(userName, domainName, idpEntityId string) string { +func testAccDomainSAMLOptionsConfig_basic(userName, domainName, idpEntityId string) string { return fmt.Sprintf(` resource "aws_iam_user" "test" { name = %[1]q @@ -272,7 +272,7 @@ resource "aws_opensearch_domain_saml_options" "test" { `, userName, domainName, idpEntityId) } -func testAccDomainSAMLOptionsConfigUpdate(userName, domainName, idpEntityId string) string { +func testAccDomainSAMLOptionsConfig_update(userName, domainName, idpEntityId string) string { return fmt.Sprintf(` resource "aws_iam_user" "test" { name = %[1]q @@ -330,7 +330,7 @@ resource "aws_opensearch_domain_saml_options" "test" { `, userName, domainName, idpEntityId) } -func testAccDomainSAMLOptionsConfigDisabled(userName string, domainName string) string { +func testAccDomainSAMLOptionsConfig_disabled(userName string, domainName string) string { return fmt.Sprintf(` resource "aws_iam_user" "test" { name = %[1]q diff --git a/internal/service/opensearch/domain_test.go b/internal/service/opensearch/domain_test.go index 928c8a76024..f5db024cb77 100644 --- a/internal/service/opensearch/domain_test.go +++ b/internal/service/opensearch/domain_test.go @@ -91,7 +91,7 @@ func TestAccOpenSearchDomain_basic(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "engine_version", "OpenSearch_1.1"), @@ -121,7 +121,7 @@ func TestAccOpenSearchDomain_requireHTTPS(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_domainEndpointOptions(rName, true, "Policy-Min-TLS-1-0-2019-07"), + Config: testAccDomainConfig_endpointOptions(rName, true, "Policy-Min-TLS-1-0-2019-07"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists("aws_opensearch_domain.test", &domain), testAccCheckDomainEndpointOptions(true, "Policy-Min-TLS-1-0-2019-07", &domain), @@ -134,7 +134,7 @@ func TestAccOpenSearchDomain_requireHTTPS(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_domainEndpointOptions(rName, true, "Policy-Min-TLS-1-2-2019-07"), + Config: testAccDomainConfig_endpointOptions(rName, true, "Policy-Min-TLS-1-2-2019-07"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists("aws_opensearch_domain.test", &domain), testAccCheckDomainEndpointOptions(true, "Policy-Min-TLS-1-2-2019-07", &domain), @@ -274,7 +274,7 @@ func TestAccOpenSearchDomain_Cluster_coldStorage(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_clusterWithColdStorageOptions(rName, true, false), + Config: testAccDomainConfig_clusterColdStorageOptions(rName, true, false), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "cluster_config.0.cold_storage_options.*", map[string]string{ @@ -288,7 +288,7 @@ func TestAccOpenSearchDomain_Cluster_coldStorage(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_clusterWithColdStorageOptions(rName, true, true), + Config: testAccDomainConfig_clusterColdStorageOptions(rName, true, true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "cluster_config.0.cold_storage_options.*", map[string]string{ @@ -476,7 +476,7 @@ func TestAccOpenSearchDomain_duplicate(t *testing.T) { t.Fatal(err) } }, - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "engine_version", "OpenSearch_1.1")), @@ -632,7 +632,7 @@ func TestAccOpenSearchDomain_VPC_internetToVPCEndpoint(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), ), @@ -644,7 +644,7 @@ func TestAccOpenSearchDomain_VPC_internetToVPCEndpoint(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainConfig_internetToVpcEndpoint(rName), + Config: testAccDomainConfig_internetToVPCEndpoint(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), ), @@ -1143,7 +1143,7 @@ func TestAccOpenSearchDomain_Encryption_atRestSpecifyKey(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_encryptAtRestWithKey(rName, "Elasticsearch_6.0", true), + Config: testAccDomainConfig_encryptAtRestKey(rName, "Elasticsearch_6.0", true), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), testAccCheckDomainEncrypted(true, &domain), @@ -1540,7 +1540,7 @@ func TestAccOpenSearchDomain_disappears(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceDisappears(acctest.Provider, tfopensearch.ResourceDomain(), resourceName), ), @@ -1869,7 +1869,7 @@ func testAccCheckELBDestroy(s *terraform.State) error { return nil } -func testAccDomainConfig(rName string) string { +func testAccDomainConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_opensearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -1932,7 +1932,7 @@ resource "aws_opensearch_domain" "test" { `, rName) } -func testAccDomainConfig_domainEndpointOptions(rName string, enforceHttps bool, tlsSecurityPolicy string) string { +func testAccDomainConfig_endpointOptions(rName string, enforceHttps bool, tlsSecurityPolicy string) string { return fmt.Sprintf(` resource "aws_opensearch_domain" "test" { domain_name = substr(%[1]q, 0, 28) @@ -2000,7 +2000,7 @@ resource "aws_opensearch_domain" "test" { `, rName, availabilityZoneCount) } -func testAccDomainConfig_clusterWithColdStorageOptions(rName string, warmEnabled bool, csEnabled bool) string { +func testAccDomainConfig_clusterColdStorageOptions(rName string, warmEnabled bool, csEnabled bool) string { warmConfig := "" if warmEnabled { warmConfig = ` @@ -2429,7 +2429,7 @@ resource "aws_opensearch_domain" "test" { `, rName, version, enabled) } -func testAccDomainConfig_encryptAtRestWithKey(rName, version string, enabled bool) string { +func testAccDomainConfig_encryptAtRestKey(rName, version string, enabled bool) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -2754,7 +2754,7 @@ resource "aws_opensearch_domain" "test" { `, rName)) } -func testAccDomainConfig_internetToVpcEndpoint(rName string) string { +func testAccDomainConfig_internetToVPCEndpoint(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` diff --git a/internal/service/opsworks/application_test.go b/internal/service/opsworks/application_test.go index d54f2c8e62e..9404bd45d2a 100644 --- a/internal/service/opsworks/application_test.go +++ b/internal/service/opsworks/application_test.go @@ -28,7 +28,7 @@ func TestAccOpsWorksApplication_basic(t *testing.T) { CheckDestroy: testAccCheckApplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccApplicationCreate(rName), + Config: testAccApplicationConfig_create(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &opsapp), testAccCheckCreateAppAttributes(&opsapp), @@ -55,7 +55,7 @@ func TestAccOpsWorksApplication_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"environment"}, }, { - Config: testAccApplicationUpdate(rName), + Config: testAccApplicationConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationExists(resourceName, &opsapp), testAccCheckUpdateAppAttributes(&opsapp), @@ -262,9 +262,9 @@ func testAccCheckApplicationDestroy(s *terraform.State) error { return nil } -func testAccApplicationCreate(rName string) string { +func testAccApplicationConfig_create(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), fmt.Sprintf(` resource "aws_opsworks_application" "test" { document_root = "foo" @@ -286,9 +286,9 @@ resource "aws_opsworks_application" "test" { `, rName)) } -func testAccApplicationUpdate(rName string) string { +func testAccApplicationConfig_update(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), fmt.Sprintf(` resource "aws_opsworks_application" "test" { auto_bundle_on_deploy = "true" diff --git a/internal/service/opsworks/custom_layer_test.go b/internal/service/opsworks/custom_layer_test.go index 5598a0884fe..0174f037915 100644 --- a/internal/service/opsworks/custom_layer_test.go +++ b/internal/service/opsworks/custom_layer_test.go @@ -30,7 +30,7 @@ func TestAccOpsWorksCustomLayer_basic(t *testing.T) { CheckDestroy: testAccCheckCustomLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomLayerVPCCreateConfig(rName), + Config: testAccCustomLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -73,7 +73,7 @@ func TestAccOpsWorksCustomLayer_tags(t *testing.T) { CheckDestroy: testAccCheckCustomLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomLayerTags1Config(rName, "key1", "value1"), + Config: testAccCustomLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -86,7 +86,7 @@ func TestAccOpsWorksCustomLayer_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCustomLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccCustomLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -95,7 +95,7 @@ func TestAccOpsWorksCustomLayer_tags(t *testing.T) { ), }, { - Config: testAccCustomLayerTags1Config(rName, "key2", "value2"), + Config: testAccCustomLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -118,7 +118,7 @@ func TestAccOpsWorksCustomLayer_noVPC(t *testing.T) { CheckDestroy: testAccCheckCustomLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomLayerNoVPCCreateConfig(rName), + Config: testAccCustomLayerConfig_noVPCCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -146,7 +146,7 @@ func TestAccOpsWorksCustomLayer_noVPC(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCustomLayerUpdateConfig(rName), + Config: testAccCustomLayerConfig_update(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "drain_elb_on_shutdown", "false"), @@ -256,7 +256,7 @@ func TestAccOpsWorksCustomLayer_disappears(t *testing.T) { CheckDestroy: testAccCheckCustomLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomLayerNoVPCCreateConfig(rName), + Config: testAccCustomLayerConfig_noVPCCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), acctest.CheckResourceDisappears(acctest.Provider, tfopsworks.ResourceCustomLayer(), resourceName), @@ -359,9 +359,9 @@ resource "aws_security_group" "tf-ops-acc-layer2" { `, name) } -func testAccCustomLayerNoVPCCreateConfig(name string) string { +func testAccCustomLayerConfig_noVPCCreate(name string) string { return acctest.ConfigCompose( - testAccStackNoVPCCreateConfig(name), + testAccStackConfig_noVPCCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_opsworks_custom_layer" "test" { @@ -392,9 +392,9 @@ resource "aws_opsworks_custom_layer" "test" { `, name)) } -func testAccCustomLayerVPCCreateConfig(name string) string { +func testAccCustomLayerConfig_vpcCreate(name string) string { return acctest.ConfigCompose( - testAccStackNoVPCCreateConfig(name), + testAccStackConfig_noVPCCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_opsworks_custom_layer" "test" { @@ -427,9 +427,9 @@ resource "aws_opsworks_custom_layer" "test" { `, name)) } -func testAccCustomLayerUpdateConfig(name string) string { +func testAccCustomLayerConfig_update(name string) string { return acctest.ConfigCompose( - testAccStackNoVPCCreateConfig(name), + testAccStackConfig_noVPCCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_security_group" "tf-ops-acc-layer3" { @@ -489,9 +489,9 @@ EOF `, name)) } -func testAccCustomLayerTags1Config(name, tagKey1, tagValue1 string) string { +func testAccCustomLayerConfig_tags1(name, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(name), + testAccStackConfig_vpcCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_opsworks_custom_layer" "test" { @@ -528,9 +528,9 @@ resource "aws_opsworks_custom_layer" "test" { `, name, tagKey1, tagValue1)) } -func testAccCustomLayerTags2Config(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccCustomLayerConfig_tags2(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(name), + testAccStackConfig_vpcCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_opsworks_custom_layer" "test" { @@ -570,7 +570,7 @@ resource "aws_opsworks_custom_layer" "test" { func testAccCustomLayerConfig_cloudWatch(name string, enabled bool) string { return acctest.ConfigCompose( - testAccStackNoVPCCreateConfig(name), + testAccStackConfig_noVPCCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { @@ -600,7 +600,7 @@ resource "aws_opsworks_custom_layer" "test" { func testAccCustomLayerConfig_cloudWatchFull(name string) string { return acctest.ConfigCompose( - testAccStackNoVPCCreateConfig(name), + testAccStackConfig_noVPCCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { diff --git a/internal/service/opsworks/ecs_cluster_layer_test.go b/internal/service/opsworks/ecs_cluster_layer_test.go index ce2d2c34407..ba5a6a381a2 100644 --- a/internal/service/opsworks/ecs_cluster_layer_test.go +++ b/internal/service/opsworks/ecs_cluster_layer_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksECSClusterLayer_basic(t *testing.T) { CheckDestroy: testAccCheckECSClusterLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccECSClusterLayerBasic(stackName), + Config: testAccECSClusterLayerConfig_basic(stackName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", stackName), @@ -47,7 +47,7 @@ func TestAccOpsWorksECSClusterLayer_tags(t *testing.T) { CheckDestroy: testAccCheckECSClusterLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccECSClusterLayerTags1Config(stackName, "key1", "value1"), + Config: testAccECSClusterLayerConfig_tags1(stackName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -55,7 +55,7 @@ func TestAccOpsWorksECSClusterLayer_tags(t *testing.T) { ), }, { - Config: testAccECSClusterLayerTags2Config(stackName, "key1", "value1updated", "key2", "value2"), + Config: testAccECSClusterLayerConfig_tags2(stackName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -64,7 +64,7 @@ func TestAccOpsWorksECSClusterLayer_tags(t *testing.T) { ), }, { - Config: testAccECSClusterLayerTags1Config(stackName, "key2", "value2"), + Config: testAccECSClusterLayerConfig_tags1(stackName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -79,9 +79,9 @@ func testAccCheckECSClusterLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_ecs_cluster_layer", s) } -func testAccECSClusterLayerBasic(name string) string { +func testAccECSClusterLayerConfig_basic(name string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(name), + testAccStackConfig_vpcCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_ecs_cluster" "test" { @@ -101,9 +101,9 @@ resource "aws_opsworks_ecs_cluster_layer" "test" { `, name)) } -func testAccECSClusterLayerTags1Config(name, tagKey1, tagValue1 string) string { +func testAccECSClusterLayerConfig_tags1(name, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(name), + testAccStackConfig_vpcCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_ecs_cluster" "test" { @@ -127,9 +127,9 @@ resource "aws_opsworks_ecs_cluster_layer" "test" { `, name, tagKey1, tagValue1)) } -func testAccECSClusterLayerTags2Config(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccECSClusterLayerConfig_tags2(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(name), + testAccStackConfig_vpcCreate(name), testAccCustomLayerSecurityGroups(name), fmt.Sprintf(` resource "aws_ecs_cluster" "test" { diff --git a/internal/service/opsworks/ganglia_layer_test.go b/internal/service/opsworks/ganglia_layer_test.go index ca065f4ae93..3fbd662ace6 100644 --- a/internal/service/opsworks/ganglia_layer_test.go +++ b/internal/service/opsworks/ganglia_layer_test.go @@ -22,7 +22,7 @@ func TestAccOpsWorksGangliaLayer_basic(t *testing.T) { CheckDestroy: testAccCheckGangliaLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccGangliaLayerVPCCreateConfig(rName), + Config: testAccGangliaLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -43,7 +43,7 @@ func TestAccOpsWorksGangliaLayer_tags(t *testing.T) { CheckDestroy: testAccCheckGangliaLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccGangliaLayerTags1Config(rName, "key1", "value1"), + Config: testAccGangliaLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -51,7 +51,7 @@ func TestAccOpsWorksGangliaLayer_tags(t *testing.T) { ), }, { - Config: testAccGangliaLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccGangliaLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -60,7 +60,7 @@ func TestAccOpsWorksGangliaLayer_tags(t *testing.T) { ), }, { - Config: testAccGangliaLayerTags1Config(rName, "key2", "value2"), + Config: testAccGangliaLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -75,9 +75,9 @@ func testAccCheckGangliaLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_ganglia_layer", s) } -func testAccGangliaLayerVPCCreateConfig(rName string) string { +func testAccGangliaLayerConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_ganglia_layer" "test" { @@ -93,9 +93,9 @@ resource "aws_opsworks_ganglia_layer" "test" { `, rName)) } -func testAccGangliaLayerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccGangliaLayerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_ganglia_layer" "test" { @@ -115,9 +115,9 @@ resource "aws_opsworks_ganglia_layer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccGangliaLayerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccGangliaLayerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_ganglia_layer" "test" { diff --git a/internal/service/opsworks/haproxy_layer_test.go b/internal/service/opsworks/haproxy_layer_test.go index 5e84fc10743..504758424b1 100644 --- a/internal/service/opsworks/haproxy_layer_test.go +++ b/internal/service/opsworks/haproxy_layer_test.go @@ -22,7 +22,7 @@ func TestAccOpsWorksHAProxyLayer_basic(t *testing.T) { CheckDestroy: testAccCheckHAProxyLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccHAProxyLayerVPCCreateConfig(rName), + Config: testAccHAProxyLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -43,7 +43,7 @@ func TestAccOpsWorksHAProxyLayer_tags(t *testing.T) { CheckDestroy: testAccCheckHAProxyLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccHAProxyLayerTags1Config(rName, "key1", "value1"), + Config: testAccHAProxyLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -51,7 +51,7 @@ func TestAccOpsWorksHAProxyLayer_tags(t *testing.T) { ), }, { - Config: testAccHAProxyLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccHAProxyLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -60,7 +60,7 @@ func TestAccOpsWorksHAProxyLayer_tags(t *testing.T) { ), }, { - Config: testAccHAProxyLayerTags1Config(rName, "key2", "value2"), + Config: testAccHAProxyLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -75,9 +75,9 @@ func testAccCheckHAProxyLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_haproxy_layer", s) } -func testAccHAProxyLayerVPCCreateConfig(rName string) string { +func testAccHAProxyLayerConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_haproxy_layer" "test" { @@ -93,9 +93,9 @@ resource "aws_opsworks_haproxy_layer" "test" { `, rName)) } -func testAccHAProxyLayerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccHAProxyLayerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_haproxy_layer" "test" { @@ -115,9 +115,9 @@ resource "aws_opsworks_haproxy_layer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccHAProxyLayerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccHAProxyLayerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_haproxy_layer" "test" { diff --git a/internal/service/opsworks/instance_test.go b/internal/service/opsworks/instance_test.go index bb36fd80425..5a3744c9e50 100644 --- a/internal/service/opsworks/instance_test.go +++ b/internal/service/opsworks/instance_test.go @@ -27,7 +27,7 @@ func TestAccOpsWorksInstance_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceCreateConfig(rName), + Config: testAccInstanceConfig_create(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &opsinst), testAccCheckInstanceAttributes(&opsinst), @@ -50,7 +50,7 @@ func TestAccOpsWorksInstance_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"state"}, //state is something we pass to the API and get back as status :( }, { - Config: testAccInstanceUpdateConfig(rName), + Config: testAccInstanceConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &opsinst), testAccCheckInstanceAttributes(&opsinst), @@ -77,7 +77,7 @@ func TestAccOpsWorksInstance_updateHostNameForceNew(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceCreateConfig(rName), + Config: testAccInstanceConfig_create(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "hostname", "tf-acc1"), @@ -90,7 +90,7 @@ func TestAccOpsWorksInstance_updateHostNameForceNew(t *testing.T) { ImportStateVerifyIgnore: []string{"state"}, }, { - Config: testAccInstanceUpdateHostNameConfig(rName), + Config: testAccInstanceConfig_updateHostName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "hostname", "tf-acc2"), @@ -203,9 +203,9 @@ func testAccCheckInstanceDestroy(s *terraform.State) error { return nil } -func testAccInstanceUpdateHostNameConfig(rName string) string { +func testAccInstanceConfig_updateHostName(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), fmt.Sprintf(` resource "aws_security_group" "tf-ops-acc-web" { name = "%[1]s-web" @@ -259,9 +259,9 @@ resource "aws_opsworks_instance" "test" { `, rName)) } -func testAccInstanceCreateConfig(rName string) string { +func testAccInstanceConfig_create(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), fmt.Sprintf(` resource "aws_security_group" "tf-ops-acc-web" { name = "%[1]s-web" @@ -315,9 +315,9 @@ resource "aws_opsworks_instance" "test" { `, rName)) } -func testAccInstanceUpdateConfig(rName string) string { +func testAccInstanceConfig_update(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), fmt.Sprintf(` resource "aws_security_group" "tf-ops-acc-web" { name = "%[1]s-web" diff --git a/internal/service/opsworks/java_app_layer_test.go b/internal/service/opsworks/java_app_layer_test.go index 0efbfd6e31f..9decddb647d 100644 --- a/internal/service/opsworks/java_app_layer_test.go +++ b/internal/service/opsworks/java_app_layer_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksJavaAppLayer_basic(t *testing.T) { CheckDestroy: testAccCheckJavaAppLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccJavaAppLayerVPCCreateConfig(rName), + Config: testAccJavaAppLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName)), @@ -45,7 +45,7 @@ func TestAccOpsWorksJavaAppLayer_tags(t *testing.T) { CheckDestroy: testAccCheckJavaAppLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccJavaAppLayerTags1Config(rName, "key1", "value1"), + Config: testAccJavaAppLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -53,7 +53,7 @@ func TestAccOpsWorksJavaAppLayer_tags(t *testing.T) { ), }, { - Config: testAccJavaAppLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccJavaAppLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -62,7 +62,7 @@ func TestAccOpsWorksJavaAppLayer_tags(t *testing.T) { ), }, { - Config: testAccJavaAppLayerTags1Config(rName, "key2", "value2"), + Config: testAccJavaAppLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -77,9 +77,9 @@ func testAccCheckJavaAppLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_java_app_layer", s) } -func testAccJavaAppLayerVPCCreateConfig(rName string) string { +func testAccJavaAppLayerConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_java_app_layer" "test" { @@ -94,9 +94,9 @@ resource "aws_opsworks_java_app_layer" "test" { `, rName)) } -func testAccJavaAppLayerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccJavaAppLayerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_java_app_layer" "test" { @@ -115,9 +115,9 @@ resource "aws_opsworks_java_app_layer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccJavaAppLayerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccJavaAppLayerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_java_app_layer" "test" { diff --git a/internal/service/opsworks/memcached_layer_test.go b/internal/service/opsworks/memcached_layer_test.go index f08f92030ad..f32144831df 100644 --- a/internal/service/opsworks/memcached_layer_test.go +++ b/internal/service/opsworks/memcached_layer_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksMemcachedLayer_basic(t *testing.T) { CheckDestroy: testAccCheckMemcachedLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccMemcachedLayerVPCCreateConfig(rName), + Config: testAccMemcachedLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName)), @@ -45,7 +45,7 @@ func TestAccOpsWorksMemcachedLayer_tags(t *testing.T) { CheckDestroy: testAccCheckMemcachedLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccMemcachedLayerTags1Config(rName, "key1", "value1"), + Config: testAccMemcachedLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -53,7 +53,7 @@ func TestAccOpsWorksMemcachedLayer_tags(t *testing.T) { ), }, { - Config: testAccMemcachedLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccMemcachedLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -62,7 +62,7 @@ func TestAccOpsWorksMemcachedLayer_tags(t *testing.T) { ), }, { - Config: testAccMemcachedLayerTags1Config(rName, "key2", "value2"), + Config: testAccMemcachedLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -77,9 +77,9 @@ func testAccCheckMemcachedLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_memcached_layer", s) } -func testAccMemcachedLayerVPCCreateConfig(rName string) string { +func testAccMemcachedLayerConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_memcached_layer" "test" { @@ -94,9 +94,9 @@ resource "aws_opsworks_memcached_layer" "test" { `, rName)) } -func testAccMemcachedLayerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccMemcachedLayerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_memcached_layer" "test" { @@ -115,9 +115,9 @@ resource "aws_opsworks_memcached_layer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccMemcachedLayerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccMemcachedLayerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_memcached_layer" "test" { diff --git a/internal/service/opsworks/mysql_layer_test.go b/internal/service/opsworks/mysql_layer_test.go index 14eff490f78..7037b11b67f 100644 --- a/internal/service/opsworks/mysql_layer_test.go +++ b/internal/service/opsworks/mysql_layer_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksMySQLLayer_basic(t *testing.T) { CheckDestroy: testAccCheckMySQLLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccMySQLLayerVPCCreateConfig(rName), + Config: testAccMySQLLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName)), @@ -45,7 +45,7 @@ func TestAccOpsWorksMySQLLayer_tags(t *testing.T) { CheckDestroy: testAccCheckMySQLLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccMySQLLayerTags1Config(rName, "key1", "value1"), + Config: testAccMySQLLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -53,7 +53,7 @@ func TestAccOpsWorksMySQLLayer_tags(t *testing.T) { ), }, { - Config: testAccMySQLLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccMySQLLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -62,7 +62,7 @@ func TestAccOpsWorksMySQLLayer_tags(t *testing.T) { ), }, { - Config: testAccMySQLLayerTags1Config(rName, "key2", "value2"), + Config: testAccMySQLLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -77,9 +77,9 @@ func testAccCheckMySQLLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_mysql_layer", s) } -func testAccMySQLLayerVPCCreateConfig(rName string) string { +func testAccMySQLLayerConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_mysql_layer" "test" { @@ -94,9 +94,9 @@ resource "aws_opsworks_mysql_layer" "test" { `, rName)) } -func testAccMySQLLayerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccMySQLLayerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_mysql_layer" "test" { @@ -115,9 +115,9 @@ resource "aws_opsworks_mysql_layer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccMySQLLayerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccMySQLLayerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_mysql_layer" "test" { diff --git a/internal/service/opsworks/nodejs_app_layer_test.go b/internal/service/opsworks/nodejs_app_layer_test.go index 3f9e72c02d9..6e3333769e4 100644 --- a/internal/service/opsworks/nodejs_app_layer_test.go +++ b/internal/service/opsworks/nodejs_app_layer_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksNodejsAppLayer_basic(t *testing.T) { CheckDestroy: testAccCheckNodejsAppLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccNodejsAppLayerVPCCreateConfig(rName), + Config: testAccNodejsAppLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName)), @@ -45,7 +45,7 @@ func TestAccOpsWorksNodejsAppLayer_tags(t *testing.T) { CheckDestroy: testAccCheckNodejsAppLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccNodejsAppLayerTags1Config(rName, "key1", "value1"), + Config: testAccNodejsAppLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -53,7 +53,7 @@ func TestAccOpsWorksNodejsAppLayer_tags(t *testing.T) { ), }, { - Config: testAccNodejsAppLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccNodejsAppLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -62,7 +62,7 @@ func TestAccOpsWorksNodejsAppLayer_tags(t *testing.T) { ), }, { - Config: testAccNodejsAppLayerTags1Config(rName, "key2", "value2"), + Config: testAccNodejsAppLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -77,9 +77,9 @@ func testAccCheckNodejsAppLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_nodejs_app_layer", s) } -func testAccNodejsAppLayerVPCCreateConfig(rName string) string { +func testAccNodejsAppLayerConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_nodejs_app_layer" "test" { @@ -94,9 +94,9 @@ resource "aws_opsworks_nodejs_app_layer" "test" { `, rName)) } -func testAccNodejsAppLayerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccNodejsAppLayerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_nodejs_app_layer" "test" { @@ -115,9 +115,9 @@ resource "aws_opsworks_nodejs_app_layer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccNodejsAppLayerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccNodejsAppLayerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_nodejs_app_layer" "test" { diff --git a/internal/service/opsworks/permission_test.go b/internal/service/opsworks/permission_test.go index 26e582af84a..c11b632b161 100644 --- a/internal/service/opsworks/permission_test.go +++ b/internal/service/opsworks/permission_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksPermission_basic(t *testing.T) { CheckDestroy: testAccCheckPermissionDestroy, Steps: []resource.TestStep{ { - Config: testAccPermissionCreate(rName, true, true, "iam_only"), + Config: testAccPermissionConfig_create(rName, true, true, "iam_only"), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName, &opsperm), testAccCheckCreatePermissionAttributes(&opsperm, true, true, "iam_only"), @@ -35,7 +35,7 @@ func TestAccOpsWorksPermission_basic(t *testing.T) { ), }, { - Config: testAccPermissionCreate(rName, true, false, "iam_only"), + Config: testAccPermissionConfig_create(rName, true, false, "iam_only"), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName, &opsperm), testAccCheckCreatePermissionAttributes(&opsperm, true, false, "iam_only"), @@ -45,7 +45,7 @@ func TestAccOpsWorksPermission_basic(t *testing.T) { ), }, { - Config: testAccPermissionCreate(rName, false, false, "deny"), + Config: testAccPermissionConfig_create(rName, false, false, "deny"), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName, &opsperm), testAccCheckCreatePermissionAttributes(&opsperm, false, false, "deny"), @@ -55,7 +55,7 @@ func TestAccOpsWorksPermission_basic(t *testing.T) { ), }, { - Config: testAccPermissionCreate(rName, false, false, "show"), + Config: testAccPermissionConfig_create(rName, false, false, "show"), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName, &opsperm), testAccCheckCreatePermissionAttributes(&opsperm, false, false, "show"), @@ -81,7 +81,7 @@ func TestAccOpsWorksPermission_self(t *testing.T) { CheckDestroy: nil, // Cannot delete own OpsWorks Permission Steps: []resource.TestStep{ { - Config: testAccPermissionSelf(rName, true, true), + Config: testAccPermissionConfig_self(rName, true, true), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName, &opsperm), resource.TestCheckResourceAttr(resourceName, "allow_ssh", "true"), @@ -89,7 +89,7 @@ func TestAccOpsWorksPermission_self(t *testing.T) { ), }, { - Config: testAccPermissionSelf(rName, true, false), + Config: testAccPermissionConfig_self(rName, true, false), Check: resource.ComposeTestCheckFunc( testAccCheckPermissionExists(resourceName, &opsperm), resource.TestCheckResourceAttr(resourceName, "allow_ssh", "true"), @@ -294,9 +294,9 @@ resource "aws_iam_instance_profile" "test" { `, rName) } -func testAccPermissionCreate(rName string, allowSSH, allowSudo bool, level string) string { +func testAccPermissionConfig_create(rName string, allowSSH, allowSudo bool, level string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), fmt.Sprintf(` resource "aws_opsworks_permission" "test" { stack_id = aws_opsworks_stack.test.id @@ -319,7 +319,7 @@ resource "aws_iam_user" "user" { `, allowSSH, allowSudo, level, rName)) } -func testAccPermissionSelf(rName string, allowSSH bool, allowSudo bool) string { +func testAccPermissionConfig_self(rName string, allowSSH bool, allowSudo bool) string { return acctest.ConfigCompose( testAccPermissionBase(rName), fmt.Sprintf(` diff --git a/internal/service/opsworks/php_app_layer_test.go b/internal/service/opsworks/php_app_layer_test.go index be53f294826..6a825b00791 100644 --- a/internal/service/opsworks/php_app_layer_test.go +++ b/internal/service/opsworks/php_app_layer_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksPHPAppLayer_basic(t *testing.T) { CheckDestroy: testAccCheckPHPAppLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccPHPAppLayerVPCCreateConfig(rName), + Config: testAccPHPAppLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName)), @@ -50,7 +50,7 @@ func TestAccOpsWorksPHPAppLayer_tags(t *testing.T) { CheckDestroy: testAccCheckPHPAppLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccPHPAppLayerTags1Config(rName, "key1", "value1"), + Config: testAccPHPAppLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -63,7 +63,7 @@ func TestAccOpsWorksPHPAppLayer_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPHPAppLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccPHPAppLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -72,7 +72,7 @@ func TestAccOpsWorksPHPAppLayer_tags(t *testing.T) { ), }, { - Config: testAccPHPAppLayerTags1Config(rName, "key2", "value2"), + Config: testAccPHPAppLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -87,9 +87,9 @@ func testAccCheckPHPAppLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_php_app_layer", s) } -func testAccPHPAppLayerVPCCreateConfig(rName string) string { +func testAccPHPAppLayerConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_php_app_layer" "test" { @@ -104,9 +104,9 @@ resource "aws_opsworks_php_app_layer" "test" { `, rName)) } -func testAccPHPAppLayerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccPHPAppLayerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_php_app_layer" "test" { @@ -125,9 +125,9 @@ resource "aws_opsworks_php_app_layer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccPHPAppLayerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccPHPAppLayerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_php_app_layer" "test" { diff --git a/internal/service/opsworks/rails_app_layer_test.go b/internal/service/opsworks/rails_app_layer_test.go index e279ab86ef1..18002e2dffb 100644 --- a/internal/service/opsworks/rails_app_layer_test.go +++ b/internal/service/opsworks/rails_app_layer_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksRailsAppLayer_basic(t *testing.T) { CheckDestroy: testAccCheckRailsAppLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccRailsAppLayerVPCCreateConfig(rName), + Config: testAccRailsAppLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -33,7 +33,7 @@ func TestAccOpsWorksRailsAppLayer_basic(t *testing.T) { ), }, { - Config: testAccRailsAppLayerNoManageBundlerVPCCreateConfig(rName), + Config: testAccRailsAppLayerConfig_noManageBundlerVPCCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -55,7 +55,7 @@ func TestAccOpsWorksRailsAppLayer_tags(t *testing.T) { CheckDestroy: testAccCheckRailsAppLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccRailsAppLayerTags1Config(rName, "key1", "value1"), + Config: testAccRailsAppLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -63,7 +63,7 @@ func TestAccOpsWorksRailsAppLayer_tags(t *testing.T) { ), }, { - Config: testAccRailsAppLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccRailsAppLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -72,7 +72,7 @@ func TestAccOpsWorksRailsAppLayer_tags(t *testing.T) { ), }, { - Config: testAccRailsAppLayerTags1Config(rName, "key2", "value2"), + Config: testAccRailsAppLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -87,9 +87,9 @@ func testAccCheckRailsAppLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_rails_app_layer", s) } -func testAccRailsAppLayerVPCCreateConfig(rName string) string { +func testAccRailsAppLayerConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_rails_app_layer" "test" { @@ -104,9 +104,9 @@ resource "aws_opsworks_rails_app_layer" "test" { `, rName)) } -func testAccRailsAppLayerNoManageBundlerVPCCreateConfig(rName string) string { +func testAccRailsAppLayerConfig_noManageBundlerVPCCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_rails_app_layer" "test" { @@ -123,9 +123,9 @@ resource "aws_opsworks_rails_app_layer" "test" { `, rName)) } -func testAccRailsAppLayerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccRailsAppLayerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_rails_app_layer" "test" { @@ -144,9 +144,9 @@ resource "aws_opsworks_rails_app_layer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccRailsAppLayerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccRailsAppLayerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_rails_app_layer" "test" { diff --git a/internal/service/opsworks/rds_db_instance_test.go b/internal/service/opsworks/rds_db_instance_test.go index a907fc31559..140b7bb37e6 100644 --- a/internal/service/opsworks/rds_db_instance_test.go +++ b/internal/service/opsworks/rds_db_instance_test.go @@ -30,7 +30,7 @@ func TestAccOpsWorksRDSDBInstance_basic(t *testing.T) { CheckDestroy: testAccCheckRDSDBDestroy, Steps: []resource.TestStep{ { - Config: testAccRDSDBInstance(rName, "foo", "barbarbarbar"), + Config: testAccRDSDBInstanceConfig_basic(rName, "foo", "barbarbarbar"), Check: resource.ComposeTestCheckFunc( testAccCheckRDSDBExists(resourceName, &opsdb), testAccCheckCreateRDSDBAttributes(&opsdb, "foo"), @@ -38,7 +38,7 @@ func TestAccOpsWorksRDSDBInstance_basic(t *testing.T) { ), }, { - Config: testAccRDSDBInstance(rName, "bar", "barbarbarbar"), + Config: testAccRDSDBInstanceConfig_basic(rName, "bar", "barbarbarbar"), Check: resource.ComposeTestCheckFunc( testAccCheckRDSDBExists(resourceName, &opsdb), testAccCheckCreateRDSDBAttributes(&opsdb, "bar"), @@ -46,7 +46,7 @@ func TestAccOpsWorksRDSDBInstance_basic(t *testing.T) { ), }, { - Config: testAccRDSDBInstance(rName, "bar", "foofoofoofoofoo"), + Config: testAccRDSDBInstanceConfig_basic(rName, "bar", "foofoofoofoofoo"), Check: resource.ComposeTestCheckFunc( testAccCheckRDSDBExists(resourceName, &opsdb), testAccCheckCreateRDSDBAttributes(&opsdb, "bar"), @@ -54,7 +54,7 @@ func TestAccOpsWorksRDSDBInstance_basic(t *testing.T) { ), }, { - Config: testAccRDSDBInstanceForceNew(rName), + Config: testAccRDSDBInstanceConfig_forceNew(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRDSDBExists(resourceName, &opsdb), testAccCheckCreateRDSDBAttributes(&opsdb, "foo"), @@ -141,9 +141,9 @@ func testAccCheckRDSDBDestroy(s *terraform.State) error { return nil } -func testAccRDSDBInstance(rName, userName, password string) string { +func testAccRDSDBInstanceConfig_basic(rName, userName, password string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccDBInstanceBasicConfig(), fmt.Sprintf(` resource "aws_opsworks_rds_db_instance" "test" { @@ -156,9 +156,9 @@ resource "aws_opsworks_rds_db_instance" "test" { `, userName, password)) } -func testAccRDSDBInstanceForceNew(rName string) string { +func testAccRDSDBInstanceConfig_forceNew(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccDBInstanceConfig_orderableClassMySQL(), ` resource "aws_opsworks_rds_db_instance" "test" { diff --git a/internal/service/opsworks/stack_test.go b/internal/service/opsworks/stack_test.go index 609d0a66215..0281a1bd186 100644 --- a/internal/service/opsworks/stack_test.go +++ b/internal/service/opsworks/stack_test.go @@ -35,7 +35,7 @@ func TestAccOpsWorksStack_noVPCBasic(t *testing.T) { CheckDestroy: testAccCheckStackDestroy, Steps: []resource.TestStep{ { - Config: testAccStackNoVPCCreateConfig(rName), + Config: testAccStackConfig_noVPCCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, false, &opsstack), testAccCheckCreateStackAttributes(rName), @@ -66,7 +66,7 @@ func TestAccOpsWorksStack_noVPCChangeServiceRoleForceNew(t *testing.T) { CheckDestroy: testAccCheckStackDestroy, Steps: []resource.TestStep{ { - Config: testAccStackNoVPCCreateConfig(rName), + Config: testAccStackConfig_noVPCCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, false, &before), ), @@ -77,7 +77,7 @@ func TestAccOpsWorksStack_noVPCChangeServiceRoleForceNew(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStackNoVPCCreateUpdateServiceRoleConfig(rName), + Config: testAccStackConfig_noVPCCreateUpdateServiceRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, false, &after), testAccCheckStackRecreated(t, &before, &after), @@ -103,7 +103,7 @@ func TestAccOpsWorksStack_vpc(t *testing.T) { CheckDestroy: testAccCheckStackDestroy, Steps: []resource.TestStep{ { - Config: testAccStackVPCCreateConfig(rName), + Config: testAccStackConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, true, &opsstack), testAccCheckCreateStackAttributes(rName), @@ -115,14 +115,14 @@ func TestAccOpsWorksStack_vpc(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStackVPCUpdateConfig(rName), + Config: testAccStackConfig_vpcUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, true, &opsstack), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrPair(resourceName, "default_availability_zone", "data.aws_availability_zones.available", "names.0"), resource.TestCheckResourceAttr(resourceName, "default_os", "Amazon Linux 2015.09"), resource.TestCheckResourceAttr(resourceName, "default_root_device_type", "ebs"), - resource.TestCheckResourceAttr(resourceName, "custom_json", customJson), + resource.TestCheckResourceAttr(resourceName, "custom_json", customJSON), resource.TestCheckResourceAttr(resourceName, "configuration_manager_version", "11.10"), resource.TestCheckResourceAttr(resourceName, "use_opsworks_security_groups", "false"), resource.TestCheckResourceAttr(resourceName, "use_custom_cookbooks", "true"), @@ -152,7 +152,7 @@ func TestAccOpsWorksStack_noVPCCreateTags(t *testing.T) { CheckDestroy: testAccCheckStackDestroy, Steps: []resource.TestStep{ { - Config: testAccStackNoVPCCreateTagsConfig(rName), + Config: testAccStackConfig_noVPCCreateTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, false, &opsstack), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -165,7 +165,7 @@ func TestAccOpsWorksStack_noVPCCreateTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStackNoVPCUpdateTagsConfig(rName), + Config: testAccStackConfig_noVPCUpdateTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, false, &opsstack), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -196,14 +196,14 @@ func TestAccOpsWorksStack_CustomCookbooks_setPrivateProperties(t *testing.T) { CheckDestroy: testAccCheckStackDestroy, Steps: []resource.TestStep{ { - Config: testAccStackConfig_CustomCookbooks_Set(rName), + Config: testAccStackConfig_customCookbooksSet(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, true, &opsstack), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrPair(resourceName, "default_availability_zone", "data.aws_availability_zones.available", "names.0"), resource.TestCheckResourceAttr(resourceName, "default_os", "Amazon Linux 2016.09"), resource.TestCheckResourceAttr(resourceName, "default_root_device_type", "ebs"), - resource.TestCheckResourceAttr(resourceName, "custom_json", customJson), + resource.TestCheckResourceAttr(resourceName, "custom_json", customJSON), resource.TestCheckResourceAttr(resourceName, "configuration_manager_version", "11.10"), resource.TestCheckResourceAttr(resourceName, "use_opsworks_security_groups", "false"), resource.TestCheckResourceAttr(resourceName, "use_custom_cookbooks", "true"), @@ -236,7 +236,7 @@ func TestAccOpsWorksStack_classicEndpoints(t *testing.T) { CheckDestroy: testAccCheckStackDestroy, Steps: []resource.TestStep{ { - Config: testAccStack_classicEndpoint(rName), + Config: testAccStackConfig_classicEndpoint(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStackExists(resourceName, false, &opsstack), ), @@ -248,7 +248,7 @@ func TestAccOpsWorksStack_classicEndpoints(t *testing.T) { }, // Ensure that changing region results in no plan { - Config: testAccStack_regionalEndpoint(rName), + Config: testAccStackConfig_regionalEndpoint(rName), PlanOnly: true, }, }, @@ -280,7 +280,7 @@ func testAccPreCheckStacks(t *testing.T) { } } -func testAccStack_classicEndpoint(rName string) string { +func testAccStackConfig_classicEndpoint(rName string) string { return fmt.Sprintf(` provider "aws" { region = "us-east-1" @@ -367,7 +367,7 @@ resource "aws_iam_instance_profile" "opsworks_instance" { `, rName) //lintignore:AWSAT003,AT004 } -func testAccStack_regionalEndpoint(rName string) string { +func testAccStackConfig_regionalEndpoint(rName string) string { return fmt.Sprintf(` provider "aws" { region = "us-west-2" @@ -465,7 +465,7 @@ func testAccCheckCreateStackAttributes(rName string) resource.TestCheckFunc { resource.TestCheckResourceAttrPair(resourceName, "default_availability_zone", "data.aws_availability_zones.available", "names.0"), resource.TestCheckResourceAttr(resourceName, "default_os", "Amazon Linux 2016.09"), resource.TestCheckResourceAttr(resourceName, "default_root_device_type", "ebs"), - resource.TestCheckResourceAttr(resourceName, "custom_json", customJson), + resource.TestCheckResourceAttr(resourceName, "custom_json", customJSON), resource.TestCheckResourceAttr(resourceName, "configuration_manager_version", "11.10"), resource.TestCheckResourceAttr(resourceName, "use_opsworks_security_groups", "false"), ) @@ -543,7 +543,7 @@ func testAccCheckStackDestroy(s *terraform.State) error { //// Helper configs for the necessary IAM objects ////////////////////////////////////////////////// -func testAccStackNoVPCCreateConfig(rName string) string { +func testAccStackConfig_noVPCCreate(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -642,7 +642,7 @@ resource "aws_iam_instance_profile" "opsworks_instance" { `, rName)) } -func testAccStackNoVPCCreateTagsConfig(rName string) string { +func testAccStackConfig_noVPCCreateTags(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -745,7 +745,7 @@ resource "aws_iam_instance_profile" "opsworks_instance" { `, rName)) } -func testAccStackNoVPCUpdateTagsConfig(rName string) string { +func testAccStackConfig_noVPCUpdateTags(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -848,7 +848,7 @@ resource "aws_iam_instance_profile" "opsworks_instance" { `, rName)) } -func testAccStackNoVPCCreateUpdateServiceRoleConfig(rName string) string { +func testAccStackConfig_noVPCCreateUpdateServiceRole(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -996,7 +996,7 @@ resource "aws_iam_instance_profile" "opsworks_instance" { //// Tests for the VPC case //////////////////////////// -func testAccStackVPCCreateConfig(rName string) string { +func testAccStackConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1115,7 +1115,7 @@ resource "aws_iam_instance_profile" "opsworks_instance" { `, rName)) } -func testAccStackVPCUpdateConfig(rName string) string { +func testAccStackConfig_vpcUpdate(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1245,7 +1245,7 @@ resource "aws_iam_instance_profile" "opsworks_instance" { // Helpers for Custom Cookbook properties ///////////////////////////////////////// -func testAccStackConfig_CustomCookbooks_Set(rName string) string { +func testAccStackConfig_customCookbooksSet(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` @@ -1403,6 +1403,6 @@ const sshKey = "-----BEGIN RSA PRIVATE KEY-----" + "tmm0+hpmkjX7jiPcljjs8S8gh+uCWieJoO4JNPk2SXRiePpYgKzdlg==" + "-----END RSA PRIVATE KEY-----" -const customJson = `{ +const customJSON = `{ "key": "value" }` diff --git a/internal/service/opsworks/static_web_layer_test.go b/internal/service/opsworks/static_web_layer_test.go index 57cd9774052..dc5eb61ab25 100644 --- a/internal/service/opsworks/static_web_layer_test.go +++ b/internal/service/opsworks/static_web_layer_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksStaticWebLayer_basic(t *testing.T) { CheckDestroy: testAccCheckStaticWebLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccStaticWebLayerVPCCreateConfig(rName), + Config: testAccStaticWebLayerConfig_vpcCreate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "name", rName)), @@ -50,7 +50,7 @@ func TestAccOpsWorksStaticWebLayer_tags(t *testing.T) { CheckDestroy: testAccCheckStaticWebLayerDestroy, Steps: []resource.TestStep{ { - Config: testAccStaticWebLayerTags1Config(rName, "key1", "value1"), + Config: testAccStaticWebLayerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -63,7 +63,7 @@ func TestAccOpsWorksStaticWebLayer_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStaticWebLayerTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccStaticWebLayerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -72,7 +72,7 @@ func TestAccOpsWorksStaticWebLayer_tags(t *testing.T) { ), }, { - Config: testAccStaticWebLayerTags1Config(rName, "key2", "value2"), + Config: testAccStaticWebLayerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLayerExists(resourceName, &opslayer), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -87,9 +87,9 @@ func testAccCheckStaticWebLayerDestroy(s *terraform.State) error { return testAccCheckLayerDestroy("aws_opsworks_static_web_layer", s) } -func testAccStaticWebLayerVPCCreateConfig(rName string) string { +func testAccStaticWebLayerConfig_vpcCreate(rName string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_static_web_layer" "test" { @@ -104,9 +104,9 @@ resource "aws_opsworks_static_web_layer" "test" { `, rName)) } -func testAccStaticWebLayerTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccStaticWebLayerConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_static_web_layer" "test" { @@ -125,9 +125,9 @@ resource "aws_opsworks_static_web_layer" "test" { `, rName, tagKey1, tagValue1)) } -func testAccStaticWebLayerTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccStaticWebLayerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( - testAccStackVPCCreateConfig(rName), + testAccStackConfig_vpcCreate(rName), testAccCustomLayerSecurityGroups(rName), fmt.Sprintf(` resource "aws_opsworks_static_web_layer" "test" { diff --git a/internal/service/opsworks/sweep.go b/internal/service/opsworks/sweep.go index d25ab971ed3..eb3fa4812bf 100644 --- a/internal/service/opsworks/sweep.go +++ b/internal/service/opsworks/sweep.go @@ -4,11 +4,13 @@ package opsworks import ( + "errors" "fmt" "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/opsworks" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -342,5 +344,20 @@ func sweepUserProfiles(region string) error { sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } - return sweep.SweepOrchestrator(sweepResources) + err = sweep.SweepOrchestrator(sweepResources) + + var errs *multierror.Error + if errors.As(err, &errs) { + var es *multierror.Error + for _, e := range errs.Errors { + if tfawserr.ErrMessageContains(err, opsworks.ErrCodeValidationException, "Cannot delete self") { + log.Printf("[WARN] Ignoring error: %s", e.Error()) + } else { + es = multierror.Append(es, e) + } + } + return es.ErrorOrNil() + } + + return err } diff --git a/internal/service/opsworks/user_profile.go b/internal/service/opsworks/user_profile.go index 4e0f28d1ce6..a6c2b3359e1 100644 --- a/internal/service/opsworks/user_profile.go +++ b/internal/service/opsworks/user_profile.go @@ -1,10 +1,10 @@ package opsworks import ( + "fmt" "log" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/opsworks" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -56,15 +56,13 @@ func resourceUserProfileRead(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Reading OpsWorks user profile: %s", d.Id()) resp, err := client.DescribeUserProfiles(req) + if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + log.Printf("[DEBUG] OpsWorks user profile (%s) not found", d.Id()) + d.SetId("") + return nil + } if err != nil { - if awserr, ok := err.(awserr.Error); ok { - if awserr.Code() == "ResourceNotFoundException" { - log.Printf("[DEBUG] OpsWorks user profile (%s) not found", d.Id()) - d.SetId("") - return nil - } - } - return err + return fmt.Errorf("error reading OpsWorks User Profile (%s): %w", d.Id(), err) } for _, profile := range resp.UserProfiles { @@ -90,7 +88,7 @@ func resourceUserProfileCreate(d *schema.ResourceData, meta interface{}) error { resp, err := client.CreateUserProfile(req) if err != nil { - return err + return fmt.Errorf("error creating OpsWorks User Profile (%s): %w", d.Id(), err) } d.SetId(aws.StringValue(resp.IamUserArn)) @@ -112,7 +110,7 @@ func resourceUserProfileUpdate(d *schema.ResourceData, meta interface{}) error { _, err := client.UpdateUserProfile(req) if err != nil { - return err + return fmt.Errorf("error updating OpsWorks User Profile (%s): %w", d.Id(), err) } return resourceUserProfileRead(d, meta) @@ -134,5 +132,9 @@ func resourceUserProfileDelete(d *schema.ResourceData, meta interface{}) error { return nil } - return err + if err != nil { + return fmt.Errorf("error deleting OpsWorks User Profile (%s): %w", d.Id(), err) + } + + return nil } diff --git a/internal/service/opsworks/user_profile_test.go b/internal/service/opsworks/user_profile_test.go index 37af96249d2..70c7c33f27a 100644 --- a/internal/service/opsworks/user_profile_test.go +++ b/internal/service/opsworks/user_profile_test.go @@ -25,7 +25,7 @@ func TestAccOpsWorksUserProfile_basic(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileCreate(rName), + Config: testAccUserProfileConfig_create(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, rName), resource.TestCheckResourceAttr(resourceName, "ssh_public_key", ""), @@ -34,7 +34,7 @@ func TestAccOpsWorksUserProfile_basic(t *testing.T) { ), }, { - Config: testAccUserProfileUpdate(rName, rName2), + Config: testAccUserProfileConfig_update(rName, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, rName2), resource.TestCheckResourceAttr(resourceName, "ssh_public_key", ""), @@ -120,7 +120,7 @@ func testAccCheckUserProfileDestroy(s *terraform.State) error { return nil } -func testAccUserProfileCreate(rName string) string { +func testAccUserProfileConfig_create(rName string) string { return fmt.Sprintf(` resource "aws_opsworks_user_profile" "test" { user_arn = aws_iam_user.test.arn @@ -134,7 +134,7 @@ resource "aws_iam_user" "test" { `, rName) } -func testAccUserProfileUpdate(rName, rName2 string) string { +func testAccUserProfileConfig_update(rName, rName2 string) string { return fmt.Sprintf(` resource "aws_opsworks_user_profile" "test" { user_arn = aws_iam_user.new-test.arn diff --git a/internal/service/organizations/account.go b/internal/service/organizations/account.go index 351fb4ed36f..bd4c67ff530 100644 --- a/internal/service/organizations/account.go +++ b/internal/service/organizations/account.go @@ -17,7 +17,6 @@ import ( tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" - "github.com/hashicorp/terraform-provider-aws/names" ) func ResourceAccount() *schema.Resource { @@ -140,6 +139,7 @@ func resourceAccountCreate(d *schema.ResourceData, meta interface{}) error { } d.SetId(aws.StringValue(output.AccountId)) + d.Set("govcloud_id", output.GovCloudAccountId) if v, ok := d.GetOk("parent_id"); ok { oldParentAccountID, err := findParentAccountID(conn, d.Id()) @@ -196,14 +196,6 @@ func resourceAccountRead(d *schema.ResourceData, meta interface{}) error { d.Set("parent_id", parentAccountID) d.Set("status", account.Status) - s, err := findCreateAccountStatusByID(conn, d.Id()) - - if err != nil { - return names.Error(names.Organizations, "finding", "Create Account Status", d.Id(), err) - } - - d.Set("govcloud_id", s.GovCloudAccountId) - tags, err := ListTags(conn, d.Id()) if err != nil { diff --git a/internal/service/organizations/account_test.go b/internal/service/organizations/account_test.go index 543a87b3b6e..fb1383007c8 100644 --- a/internal/service/organizations/account_test.go +++ b/internal/service/organizations/account_test.go @@ -15,6 +15,19 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) +func testAccAccountImportStep(n string) resource.TestStep { + return resource.TestStep{ + ResourceName: n, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "close_on_deletion", + "create_govcloud", + "govcloud_id", + }, + } +} + func testAccAccount_basic(t *testing.T) { key := "TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN" orgsEmailDomain := os.Getenv(key) @@ -35,7 +48,7 @@ func testAccAccount_basic(t *testing.T) { CheckDestroy: testAccCheckAccountDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountConfig(name, email), + Config: testAccAccountConfig_basic(name, email), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAccountExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), @@ -48,12 +61,7 @@ func testAccAccount_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"close_on_deletion"}, - }, + testAccAccountImportStep(resourceName), }, }) } @@ -78,11 +86,12 @@ func testAccAccount_CloseOnDeletion(t *testing.T) { CheckDestroy: testAccCheckAccountDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountCloseOnDeletionConfig(name, email), + Config: testAccAccountConfig_closeOnDeletion(name, email), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAccountExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "email", email), + resource.TestCheckResourceAttr(resourceName, "govcloud_id", ""), resource.TestCheckResourceAttrSet(resourceName, "joined_method"), acctest.CheckResourceAttrRFC3339(resourceName, "joined_timestamp"), resource.TestCheckResourceAttr(resourceName, "name", name), @@ -91,12 +100,7 @@ func testAccAccount_CloseOnDeletion(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"close_on_deletion"}, - }, + testAccAccountImportStep(resourceName), }, }) } @@ -123,20 +127,15 @@ func testAccAccount_ParentID(t *testing.T) { CheckDestroy: testAccCheckAccountDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountParentId1Config(name, email), + Config: testAccAccountConfig_parentId1(name, email), Check: resource.ComposeTestCheckFunc( testAccCheckAccountExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "parent_id", parentIdResourceName1, "id"), ), }, + testAccAccountImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"close_on_deletion"}, - }, - { - Config: testAccAccountParentId2Config(name, email), + Config: testAccAccountConfig_parentId2(name, email), Check: resource.ComposeTestCheckFunc( testAccCheckAccountExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "parent_id", parentIdResourceName2, "id"), @@ -166,21 +165,16 @@ func testAccAccount_Tags(t *testing.T) { CheckDestroy: testAccCheckAccountDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountTags1Config(name, email, "key1", "value1"), + Config: testAccAccountConfig_tags1(name, email, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAccountExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, + testAccAccountImportStep(resourceName), { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"close_on_deletion"}, - }, - { - Config: testAccAccountTags2Config(name, email, "key1", "value1updated", "key2", "value2"), + Config: testAccAccountConfig_tags2(name, email, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAccountExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -189,7 +183,7 @@ func testAccAccount_Tags(t *testing.T) { ), }, { - Config: testAccAccountTags1Config(name, email, "key2", "value2"), + Config: testAccAccountConfig_tags1(name, email, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAccountExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -214,18 +208,19 @@ func testAccAccount_govCloud(t *testing.T) { email := fmt.Sprintf("tf-acctest+%d@%s", rInt, orgsEmailDomain) resource.Test(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckOrganizationsEnabled(t) }, - ErrorCheck: acctest.ErrorCheck(t, organizations.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckAccountDestroy, + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckOrganizationsEnabled(t) }, + ErrorCheck: acctest.ErrorCheck(t, organizations.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAccountDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountGovCloudConfig(name, email), + Config: testAccAccountConfig_govCloud(name, email), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAccountExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "govcloud_id"), ), }, + testAccAccountImportStep(resourceName), }, }) } @@ -280,7 +275,7 @@ func testAccCheckAccountExists(n string, v *organizations.Account) resource.Test } } -func testAccAccountConfig(name, email string) string { +func testAccAccountConfig_basic(name, email string) string { return fmt.Sprintf(` resource "aws_organizations_account" "test" { name = %[1]q @@ -289,7 +284,7 @@ resource "aws_organizations_account" "test" { `, name, email) } -func testAccAccountCloseOnDeletionConfig(name, email string) string { +func testAccAccountConfig_closeOnDeletion(name, email string) string { return fmt.Sprintf(` resource "aws_organizations_account" "test" { name = %[1]q @@ -299,7 +294,7 @@ resource "aws_organizations_account" "test" { `, name, email) } -func testAccAccountParentId1Config(name, email string) string { +func testAccAccountConfig_parentId1(name, email string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -322,7 +317,7 @@ resource "aws_organizations_account" "test" { `, name, email) } -func testAccAccountParentId2Config(name, email string) string { +func testAccAccountConfig_parentId2(name, email string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -345,7 +340,7 @@ resource "aws_organizations_account" "test" { `, name, email) } -func testAccAccountTags1Config(name, email, tagKey1, tagValue1 string) string { +func testAccAccountConfig_tags1(name, email, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -361,7 +356,7 @@ resource "aws_organizations_account" "test" { `, name, email, tagKey1, tagValue1) } -func testAccAccountTags2Config(name, email, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAccountConfig_tags2(name, email, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -378,7 +373,7 @@ resource "aws_organizations_account" "test" { `, name, email, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccAccountGovCloudConfig(name, email string) string { +func testAccAccountConfig_govCloud(name, email string) string { return fmt.Sprintf(` resource "aws_organizations_account" "test" { name = %[1]q diff --git a/internal/service/organizations/delegated_administrator_test.go b/internal/service/organizations/delegated_administrator_test.go index a733c5bf006..a55a4779690 100644 --- a/internal/service/organizations/delegated_administrator_test.go +++ b/internal/service/organizations/delegated_administrator_test.go @@ -31,7 +31,7 @@ func testAccDelegatedAdministrator_basic(t *testing.T) { CheckDestroy: testAccCheckDelegatedAdministratorDestroy, Steps: []resource.TestStep{ { - Config: testAccDelegatedAdministratorConfig(servicePrincipal), + Config: testAccDelegatedAdministratorConfig_basic(servicePrincipal), Check: resource.ComposeTestCheckFunc( testAccCheckDelegatedAdministratorExists(resourceName, &organization), resource.TestCheckResourceAttrPair(resourceName, "account_id", dataSourceIdentity, "account_id"), @@ -65,7 +65,7 @@ func testAccDelegatedAdministrator_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, organizations.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccDelegatedAdministratorConfig(servicePrincipal), + Config: testAccDelegatedAdministratorConfig_basic(servicePrincipal), Check: resource.ComposeTestCheckFunc( testAccCheckDelegatedAdministratorExists(resourceName, &organization), acctest.CheckResourceDisappears(acctest.Provider, tforganizations.ResourceDelegatedAdministrator(), resourceName), @@ -162,7 +162,7 @@ func testAccCheckDelegatedAdministratorExists(n string, org *organizations.Deleg } } -func testAccDelegatedAdministratorConfig(servicePrincipal string) string { +func testAccDelegatedAdministratorConfig_basic(servicePrincipal string) string { return acctest.ConfigAlternateAccountProvider() + fmt.Sprintf(` data "aws_caller_identity" "delegated" { provider = "awsalternate" diff --git a/internal/service/organizations/delegated_administrators_data_source_test.go b/internal/service/organizations/delegated_administrators_data_source_test.go index e9440dd5066..9068afa3f02 100644 --- a/internal/service/organizations/delegated_administrators_data_source_test.go +++ b/internal/service/organizations/delegated_administrators_data_source_test.go @@ -25,7 +25,7 @@ func TestAccOrganizationsDelegatedAdministratorsDataSource_basic(t *testing.T) { ProviderFactories: acctest.FactoriesAlternate(&providers), Steps: []resource.TestStep{ { - Config: testAccDelegatedAdministratorsDataSourceConfig(servicePrincipal), + Config: testAccDelegatedAdministratorsDataSourceConfig_basic(servicePrincipal), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "delegated_administrators.#", "1"), resource.TestCheckResourceAttrPair(dataSourceName, "delegated_administrators.0.id", dataSourceIdentity, "account_id"), @@ -53,7 +53,7 @@ func TestAccOrganizationsDelegatedAdministratorsDataSource_multiple(t *testing.T ProviderFactories: acctest.FactoriesAlternate(&providers), Steps: []resource.TestStep{ { - Config: testAccDelegatedAdministratorsMultipleDataSourceConfig(servicePrincipal, servicePrincipal2), + Config: testAccDelegatedAdministratorsDataSourceConfig_multiple(servicePrincipal, servicePrincipal2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "delegated_administrators.#", "1"), resource.TestCheckResourceAttrPair(dataSourceName, "delegated_administrators.0.id", dataSourceIdentity, "account_id"), @@ -80,7 +80,7 @@ func TestAccOrganizationsDelegatedAdministratorsDataSource_servicePrincipal(t *t ProviderFactories: acctest.FactoriesAlternate(&providers), Steps: []resource.TestStep{ { - Config: testAccDelegatedAdministratorsServicePrincipalDataSourceConfig(servicePrincipal), + Config: testAccDelegatedAdministratorsDataSourceConfig_servicePrincipal(servicePrincipal), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "delegated_administrators.#", "1"), resource.TestCheckResourceAttrPair(dataSourceName, "delegated_administrators.0.id", dataSourceIdentity, "account_id"), @@ -102,7 +102,7 @@ func TestAccOrganizationsDelegatedAdministratorsDataSource_empty(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDelegatedAdministratorsEmptyDataSourceConfig(servicePrincipal), + Config: testAccDelegatedAdministratorsDataSourceConfig_empty(servicePrincipal), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "delegated_administrators.#", "0"), ), @@ -111,7 +111,7 @@ func TestAccOrganizationsDelegatedAdministratorsDataSource_empty(t *testing.T) { }) } -func testAccDelegatedAdministratorsEmptyDataSourceConfig(servicePrincipal string) string { +func testAccDelegatedAdministratorsDataSourceConfig_empty(servicePrincipal string) string { return acctest.ConfigAlternateAccountProvider() + fmt.Sprintf(` data "aws_organizations_delegated_administrators" "test" { service_principal = %[1]q @@ -119,7 +119,7 @@ data "aws_organizations_delegated_administrators" "test" { `, servicePrincipal) } -func testAccDelegatedAdministratorsDataSourceConfig(servicePrincipal string) string { +func testAccDelegatedAdministratorsDataSourceConfig_basic(servicePrincipal string) string { return acctest.ConfigAlternateAccountProvider() + fmt.Sprintf(` data "aws_caller_identity" "delegated" { provider = "awsalternate" @@ -134,7 +134,7 @@ data "aws_organizations_delegated_administrators" "test" {} `, servicePrincipal) } -func testAccDelegatedAdministratorsMultipleDataSourceConfig(servicePrincipal, servicePrincipal2 string) string { +func testAccDelegatedAdministratorsDataSourceConfig_multiple(servicePrincipal, servicePrincipal2 string) string { return acctest.ConfigAlternateAccountProvider() + fmt.Sprintf(` data "aws_caller_identity" "delegated" { provider = "awsalternate" @@ -154,7 +154,7 @@ data "aws_organizations_delegated_administrators" "test" {} `, servicePrincipal, servicePrincipal2) } -func testAccDelegatedAdministratorsServicePrincipalDataSourceConfig(servicePrincipal string) string { +func testAccDelegatedAdministratorsDataSourceConfig_servicePrincipal(servicePrincipal string) string { return acctest.ConfigAlternateAccountProvider() + fmt.Sprintf(` data "aws_caller_identity" "delegated" { provider = "awsalternate" diff --git a/internal/service/organizations/delegated_services_data_source_test.go b/internal/service/organizations/delegated_services_data_source_test.go index 310d70c2364..f3b50bba8d6 100644 --- a/internal/service/organizations/delegated_services_data_source_test.go +++ b/internal/service/organizations/delegated_services_data_source_test.go @@ -25,7 +25,7 @@ func TestAccOrganizationsDelegatedServicesDataSource_basic(t *testing.T) { ProviderFactories: acctest.FactoriesAlternate(&providers), Steps: []resource.TestStep{ { - Config: testAccDelegatedServicesDataSourceConfig(servicePrincipal), + Config: testAccDelegatedServicesDataSourceConfig_basic(servicePrincipal), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "delegated_services.#", "1"), resource.TestCheckResourceAttrPair(dataSourceName, "account_id", dataSourceIdentity, "account_id"), @@ -51,7 +51,7 @@ func TestAccOrganizationsDelegatedServicesDataSource_empty(t *testing.T) { ProviderFactories: acctest.FactoriesAlternate(&providers), Steps: []resource.TestStep{ { - Config: testAccDelegatedServicesEmptyDataSourceConfig(), + Config: testAccDelegatedServicesDataSourceConfig_empty(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "delegated_services.#", "0"), resource.TestCheckResourceAttrPair(dataSourceName, "account_id", dataSourceIdentity, "account_id"), @@ -77,7 +77,7 @@ func TestAccOrganizationsDelegatedServicesDataSource_multiple(t *testing.T) { ProviderFactories: acctest.FactoriesAlternate(&providers), Steps: []resource.TestStep{ { - Config: testAccDelegatedServicesMultipleDataSourceConfig(servicePrincipal, servicePrincipal2), + Config: testAccDelegatedServicesDataSourceConfig_multiple(servicePrincipal, servicePrincipal2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "delegated_services.#", "2"), resource.TestCheckResourceAttrPair(dataSourceName, "account_id", dataSourceIdentity, "account_id"), @@ -91,7 +91,7 @@ func TestAccOrganizationsDelegatedServicesDataSource_multiple(t *testing.T) { }) } -func testAccDelegatedServicesEmptyDataSourceConfig() string { +func testAccDelegatedServicesDataSourceConfig_empty() string { return acctest.ConfigAlternateAccountProvider() + ` data "aws_caller_identity" "delegated" { provider = "awsalternate" @@ -103,7 +103,7 @@ data "aws_organizations_delegated_services" "test" { ` } -func testAccDelegatedServicesDataSourceConfig(servicePrincipal string) string { +func testAccDelegatedServicesDataSourceConfig_basic(servicePrincipal string) string { return acctest.ConfigAlternateAccountProvider() + fmt.Sprintf(` data "aws_caller_identity" "delegated" { provider = "awsalternate" @@ -120,7 +120,7 @@ data "aws_organizations_delegated_services" "test" { `, servicePrincipal) } -func testAccDelegatedServicesMultipleDataSourceConfig(servicePrincipal, servicePrincipal2 string) string { +func testAccDelegatedServicesDataSourceConfig_multiple(servicePrincipal, servicePrincipal2 string) string { return acctest.ConfigAlternateAccountProvider() + fmt.Sprintf(` data "aws_caller_identity" "delegated" { provider = "awsalternate" diff --git a/internal/service/organizations/organization_data_source_test.go b/internal/service/organizations/organization_data_source_test.go index 00838a3769c..46adb6f4030 100644 --- a/internal/service/organizations/organization_data_source_test.go +++ b/internal/service/organizations/organization_data_source_test.go @@ -21,10 +21,10 @@ func testAccOrganizationDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccOrganizationConfig_resourceOnly, + Config: testAccOrganizationDataSourceConfig_resourceOnly, }, { - Config: testAccOrganizationConfig_basic, + Config: testAccOrganizationDataSourceConfig_basic, Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "accounts.#", dataSourceName, "accounts.#"), resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), @@ -43,17 +43,17 @@ func testAccOrganizationDataSource_basic(t *testing.T) { { // This is to make sure the data source isn't around trying to read the resource // when the resource is being destroyed - Config: testAccOrganizationConfig_resourceOnly, + Config: testAccOrganizationDataSourceConfig_resourceOnly, }, }, }) } -const testAccOrganizationConfig_resourceOnly = ` +const testAccOrganizationDataSourceConfig_resourceOnly = ` resource "aws_organizations_organization" "test" {} ` -const testAccOrganizationConfig_basic = ` +const testAccOrganizationDataSourceConfig_basic = ` resource "aws_organizations_organization" "test" {} data "aws_organizations_organization" "test" {} diff --git a/internal/service/organizations/organization_test.go b/internal/service/organizations/organization_test.go index d7346e90199..0792f6535c7 100644 --- a/internal/service/organizations/organization_test.go +++ b/internal/service/organizations/organization_test.go @@ -26,7 +26,7 @@ func testAccOrganization_basic(t *testing.T) { CheckDestroy: testAccCheckOrganizationDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationConfig, + Config: testAccOrganizationConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "accounts.#", "1"), @@ -67,7 +67,7 @@ func testAccOrganization_serviceAccessPrincipals(t *testing.T) { CheckDestroy: testAccCheckOrganizationDestroy, Steps: []resource.TestStep{ { - Config: testAccServiceAccessPrincipals1Config("config.amazonaws.com"), + Config: testAccOrganizationConfig_serviceAccessPrincipals1("config.amazonaws.com"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.#", "1"), @@ -80,7 +80,7 @@ func testAccOrganization_serviceAccessPrincipals(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccServiceAccessPrincipals2Config("config.amazonaws.com", "ds.amazonaws.com"), + Config: testAccOrganizationConfig_serviceAccessPrincipals2("config.amazonaws.com", "ds.amazonaws.com"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.#", "2"), @@ -89,7 +89,7 @@ func testAccOrganization_serviceAccessPrincipals(t *testing.T) { ), }, { - Config: testAccServiceAccessPrincipals1Config("fms.amazonaws.com"), + Config: testAccOrganizationConfig_serviceAccessPrincipals1("fms.amazonaws.com"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.#", "1"), @@ -111,7 +111,7 @@ func testAccOrganization_EnabledPolicyTypes(t *testing.T) { CheckDestroy: testAccCheckOrganizationDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationEnabledPolicyTypes1Config(organizations.PolicyTypeServiceControlPolicy), + Config: testAccOrganizationConfig_enabledPolicyTypes1(organizations.PolicyTypeServiceControlPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), @@ -124,14 +124,14 @@ func testAccOrganization_EnabledPolicyTypes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationConfig, + Config: testAccOrganizationConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "0"), ), }, { - Config: testAccOrganizationEnabledPolicyTypes1Config(organizations.PolicyTypeAiservicesOptOutPolicy), + Config: testAccOrganizationConfig_enabledPolicyTypes1(organizations.PolicyTypeAiservicesOptOutPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), @@ -139,7 +139,7 @@ func testAccOrganization_EnabledPolicyTypes(t *testing.T) { ), }, { - Config: testAccOrganizationEnabledPolicyTypes1Config(organizations.PolicyTypeServiceControlPolicy), + Config: testAccOrganizationConfig_enabledPolicyTypes1(organizations.PolicyTypeServiceControlPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), @@ -147,7 +147,7 @@ func testAccOrganization_EnabledPolicyTypes(t *testing.T) { ), }, { - Config: testAccOrganizationEnabledPolicyTypes1Config(organizations.PolicyTypeBackupPolicy), + Config: testAccOrganizationConfig_enabledPolicyTypes1(organizations.PolicyTypeBackupPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), @@ -155,7 +155,7 @@ func testAccOrganization_EnabledPolicyTypes(t *testing.T) { ), }, { - Config: testAccOrganizationEnabledPolicyTypes1Config(organizations.PolicyTypeTagPolicy), + Config: testAccOrganizationConfig_enabledPolicyTypes1(organizations.PolicyTypeTagPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), @@ -168,14 +168,14 @@ func testAccOrganization_EnabledPolicyTypes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationConfig, + Config: testAccOrganizationConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "0"), ), }, { - Config: testAccOrganizationEnabledPolicyTypes1Config(organizations.PolicyTypeTagPolicy), + Config: testAccOrganizationConfig_enabledPolicyTypes1(organizations.PolicyTypeTagPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), @@ -196,7 +196,7 @@ func testAccOrganization_FeatureSet(t *testing.T) { CheckDestroy: testAccCheckOrganizationDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationFeatureSetConfig(organizations.OrganizationFeatureSetConsolidatedBilling), + Config: testAccOrganizationConfig_featureSet(organizations.OrganizationFeatureSetConsolidatedBilling), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "feature_set", organizations.OrganizationFeatureSetConsolidatedBilling), @@ -222,7 +222,7 @@ func testAccOrganization_FeatureSetForcesNew(t *testing.T) { CheckDestroy: testAccCheckOrganizationDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationFeatureSetConfig(organizations.OrganizationFeatureSetAll), + Config: testAccOrganizationConfig_featureSet(organizations.OrganizationFeatureSetAll), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &beforeValue), resource.TestCheckResourceAttr(resourceName, "feature_set", organizations.OrganizationFeatureSetAll), @@ -234,7 +234,7 @@ func testAccOrganization_FeatureSetForcesNew(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationFeatureSetConfig(organizations.OrganizationFeatureSetConsolidatedBilling), + Config: testAccOrganizationConfig_featureSet(organizations.OrganizationFeatureSetConsolidatedBilling), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &afterValue), resource.TestCheckResourceAttr(resourceName, "feature_set", organizations.OrganizationFeatureSetConsolidatedBilling), @@ -256,7 +256,7 @@ func testAccOrganization_FeatureSetUpdate(t *testing.T) { CheckDestroy: testAccCheckOrganizationDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationFeatureSetConfig(organizations.OrganizationFeatureSetConsolidatedBilling), + Config: testAccOrganizationConfig_featureSet(organizations.OrganizationFeatureSetConsolidatedBilling), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &beforeValue), resource.TestCheckResourceAttr(resourceName, "feature_set", organizations.OrganizationFeatureSetConsolidatedBilling), @@ -268,7 +268,7 @@ func testAccOrganization_FeatureSetUpdate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationFeatureSetConfig(organizations.OrganizationFeatureSetAll), + Config: testAccOrganizationConfig_featureSet(organizations.OrganizationFeatureSetAll), ExpectNonEmptyPlan: true, // See note below on this perpetual difference Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationExists(resourceName, &afterValue), @@ -341,9 +341,9 @@ func testAccCheckOrganizationExists(n string, org *organizations.Organization) r } } -const testAccOrganizationConfig = "resource \"aws_organizations_organization\" \"test\" {}" +const testAccOrganizationConfig_basic = "resource \"aws_organizations_organization\" \"test\" {}" -func testAccServiceAccessPrincipals1Config(principal1 string) string { +func testAccOrganizationConfig_serviceAccessPrincipals1(principal1 string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" { aws_service_access_principals = [%q] @@ -351,7 +351,7 @@ resource "aws_organizations_organization" "test" { `, principal1) } -func testAccServiceAccessPrincipals2Config(principal1, principal2 string) string { +func testAccOrganizationConfig_serviceAccessPrincipals2(principal1, principal2 string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" { aws_service_access_principals = [%q, %q] @@ -359,7 +359,7 @@ resource "aws_organizations_organization" "test" { `, principal1, principal2) } -func testAccOrganizationEnabledPolicyTypes1Config(policyType1 string) string { +func testAccOrganizationConfig_enabledPolicyTypes1(policyType1 string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" { enabled_policy_types = [%[1]q] @@ -367,7 +367,7 @@ resource "aws_organizations_organization" "test" { `, policyType1) } -func testAccOrganizationFeatureSetConfig(featureSet string) string { +func testAccOrganizationConfig_featureSet(featureSet string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" { feature_set = %q diff --git a/internal/service/organizations/organizational_unit_test.go b/internal/service/organizations/organizational_unit_test.go index 3bfd736e0d9..a6cc73e23ec 100644 --- a/internal/service/organizations/organizational_unit_test.go +++ b/internal/service/organizations/organizational_unit_test.go @@ -29,7 +29,7 @@ func testAccOrganizationalUnit_basic(t *testing.T) { CheckDestroy: testAccCheckOrganizationalUnitDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationalUnitConfig(name), + Config: testAccOrganizationalUnitConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationalUnitExists(resourceName, &unit), resource.TestCheckResourceAttr(resourceName, "accounts.#", "0"), @@ -61,7 +61,7 @@ func testAccOrganizationalUnit_disappears(t *testing.T) { CheckDestroy: testAccCheckOrganizationalUnitDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationalUnitConfig(name), + Config: testAccOrganizationalUnitConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationalUnitExists(resourceName, &unit), acctest.CheckResourceDisappears(acctest.Provider, tforganizations.ResourceOrganizationalUnit(), resourceName), @@ -87,7 +87,7 @@ func testAccOrganizationalUnit_Name(t *testing.T) { CheckDestroy: testAccCheckOrganizationalUnitDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationalUnitConfig(name1), + Config: testAccOrganizationalUnitConfig_basic(name1), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationalUnitExists(resourceName, &unit), resource.TestCheckResourceAttr(resourceName, "name", name1), @@ -99,7 +99,7 @@ func testAccOrganizationalUnit_Name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationalUnitConfig(name2), + Config: testAccOrganizationalUnitConfig_basic(name2), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationalUnitExists(resourceName, &unit), resource.TestCheckResourceAttr(resourceName, "name", name2), @@ -123,7 +123,7 @@ func testAccOrganizationalUnit_Tags(t *testing.T) { CheckDestroy: testAccCheckOrganizationalUnitDestroy, Steps: []resource.TestStep{ { - Config: testAccOrganizationalUnitTags1Config(name, "key1", "value1"), + Config: testAccOrganizationalUnitConfig_tags1(name, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationalUnitExists(resourceName, &unit), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -136,7 +136,7 @@ func testAccOrganizationalUnit_Tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationalUnitTags2Config(name, "key1", "value1updated", "key2", "value2"), + Config: testAccOrganizationalUnitConfig_tags2(name, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationalUnitExists(resourceName, &unit), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -145,7 +145,7 @@ func testAccOrganizationalUnit_Tags(t *testing.T) { ), }, { - Config: testAccOrganizationalUnitConfig(name), + Config: testAccOrganizationalUnitConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckOrganizationalUnitExists(resourceName, &unit), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -219,7 +219,7 @@ func testAccCheckOrganizationalUnitExists(n string, ou *organizations.Organizati } } -func testAccOrganizationalUnitConfig(name string) string { +func testAccOrganizationalUnitConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -230,7 +230,7 @@ resource "aws_organizations_organizational_unit" "test" { `, name) } -func testAccOrganizationalUnitTags1Config(name, tagKey1, tagValue1 string) string { +func testAccOrganizationalUnitConfig_tags1(name, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -245,7 +245,7 @@ resource "aws_organizations_organizational_unit" "test" { `, name, tagKey1, tagValue1) } -func testAccOrganizationalUnitTags2Config(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccOrganizationalUnitConfig_tags2(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} diff --git a/internal/service/organizations/organizational_units_data_source_test.go b/internal/service/organizations/organizational_units_data_source_test.go index e1f353fd7b5..ed25ed9e445 100644 --- a/internal/service/organizations/organizational_units_data_source_test.go +++ b/internal/service/organizations/organizational_units_data_source_test.go @@ -20,7 +20,7 @@ func testAccOrganizationalUnitsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccOrganizationalUnitsDataSourceConfig, + Config: testAccOrganizationalUnitsDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "children.#", "1"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "children.0.name"), @@ -32,7 +32,7 @@ func testAccOrganizationalUnitsDataSource_basic(t *testing.T) { }) } -const testAccOrganizationalUnitsDataSourceConfig = ` +const testAccOrganizationalUnitsDataSourceConfig_basic = ` resource "aws_organizations_organization" "test" {} resource "aws_organizations_organizational_unit" "test" { diff --git a/internal/service/organizations/organizations_test.go b/internal/service/organizations/organizations_test.go index 866594142bf..f483c2ecbc3 100644 --- a/internal/service/organizations/organizations_test.go +++ b/internal/service/organizations/organizations_test.go @@ -2,8 +2,22 @@ package organizations_test import ( "testing" + + "github.com/aws/aws-sdk-go/service/organizations" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" ) +func init() { + acctest.RegisterServiceErrorCheckFunc(organizations.EndpointsID, testAccErrorCheckSkip) +} + +func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { + return acctest.ErrorCheckSkipMessagesContaining(t, + "MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED", + ) +} + func TestAccOrganizations_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Organization": { diff --git a/internal/service/organizations/policy_attachment_test.go b/internal/service/organizations/policy_attachment_test.go index d457d30a58c..ab5152d238f 100644 --- a/internal/service/organizations/policy_attachment_test.go +++ b/internal/service/organizations/policy_attachment_test.go @@ -33,7 +33,7 @@ func testAccPolicyAttachment_Account(t *testing.T) { CheckDestroy: testAccCheckPolicyAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyAttachmentConfig_Account(rName, organizations.PolicyTypeServiceControlPolicy, serviceControlPolicyContent), + Config: testAccPolicyAttachmentConfig_account(rName, organizations.PolicyTypeServiceControlPolicy, serviceControlPolicyContent), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "policy_id", policyIdResourceName, "id"), @@ -41,7 +41,7 @@ func testAccPolicyAttachment_Account(t *testing.T) { ), }, { - Config: testAccPolicyAttachmentConfig_Account(rName, organizations.PolicyTypeTagPolicy, tagPolicyContent), + Config: testAccPolicyAttachmentConfig_account(rName, organizations.PolicyTypeTagPolicy, tagPolicyContent), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "policy_id", policyIdResourceName, "id"), @@ -70,7 +70,7 @@ func testAccPolicyAttachment_OrganizationalUnit(t *testing.T) { CheckDestroy: testAccCheckPolicyAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyAttachmentConfig_OrganizationalUnit(rName), + Config: testAccPolicyAttachmentConfig_organizationalUnit(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "policy_id", policyIdResourceName, "id"), @@ -99,7 +99,7 @@ func testAccPolicyAttachment_Root(t *testing.T) { CheckDestroy: testAccCheckPolicyAttachmentDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyAttachmentConfig_Root(rName), + Config: testAccPolicyAttachmentConfig_root(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyAttachmentExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "policy_id", policyIdResourceName, "id"), @@ -210,7 +210,7 @@ func testAccCheckPolicyAttachmentExists(resourceName string) resource.TestCheckF } } -func testAccPolicyAttachmentConfig_Account(rName, policyType, policyContent string) string { +func testAccPolicyAttachmentConfig_account(rName, policyType, policyContent string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" { enabled_policy_types = ["SERVICE_CONTROL_POLICY", "TAG_POLICY"] @@ -231,7 +231,7 @@ resource "aws_organizations_policy_attachment" "test" { `, rName, policyType, strconv.Quote(policyContent)) } -func testAccPolicyAttachmentConfig_OrganizationalUnit(rName string) string { +func testAccPolicyAttachmentConfig_organizationalUnit(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" { enabled_policy_types = ["SERVICE_CONTROL_POLICY"] @@ -266,7 +266,7 @@ resource "aws_organizations_policy_attachment" "test" { `, rName) } -func testAccPolicyAttachmentConfig_Root(rName string) string { +func testAccPolicyAttachmentConfig_root(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" { enabled_policy_types = ["SERVICE_CONTROL_POLICY"] diff --git a/internal/service/organizations/policy_test.go b/internal/service/organizations/policy_test.go index 2fceb654943..b163afb7daa 100644 --- a/internal/service/organizations/policy_test.go +++ b/internal/service/organizations/policy_test.go @@ -30,7 +30,7 @@ func testAccPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_Required(rName, content1), + Config: testAccPolicyConfig_required(rName, content1), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "organizations", regexp.MustCompile("policy/o-.+/service_control_policy/p-.+$")), @@ -41,7 +41,7 @@ func testAccPolicy_basic(t *testing.T) { ), }, { - Config: testAccPolicyConfig_Required(rName, content2), + Config: testAccPolicyConfig_required(rName, content2), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "content", content2), @@ -73,7 +73,7 @@ func testAccPolicy_concurrent(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConcurrentConfig(rName), + Config: testAccPolicyConfig_concurrent(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName1, &policy1), testAccCheckPolicyExists(resourceName2, &policy2), @@ -98,14 +98,14 @@ func testAccPolicy_description(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_Description(rName, "description1"), + Config: testAccPolicyConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "description", "description1"), ), }, { - Config: testAccPolicyConfig_Description(rName, "description2"), + Config: testAccPolicyConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -132,7 +132,7 @@ func testAccPolicy_tags(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_TagA(rName), + Config: testAccPolicyConfig_tagA(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &p1), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -146,7 +146,7 @@ func testAccPolicy_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPolicyConfig_TagB(rName), + Config: testAccPolicyConfig_tagB(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &p2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -155,7 +155,7 @@ func testAccPolicy_tags(t *testing.T) { ), }, { - Config: testAccPolicyConfig_TagC(rName), + Config: testAccPolicyConfig_tagC(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &p3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -163,7 +163,7 @@ func testAccPolicy_tags(t *testing.T) { ), }, { - Config: testAccPolicyConfig_NoTag(rName), + Config: testAccPolicyConfig_noTag(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &p4), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -185,7 +185,7 @@ func testAccPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_Description(rName, ""), + Config: testAccPolicyConfig_description(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &p), acctest.CheckResourceDisappears(acctest.Provider, tforganizations.ResourcePolicy(), resourceName), @@ -210,7 +210,7 @@ func testAccPolicy_type_AI_OPT_OUT(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_Type(rName, AiOptOutPolicyContent, organizations.PolicyTypeAiservicesOptOutPolicy), + Config: testAccPolicyConfig_type(rName, AiOptOutPolicyContent, organizations.PolicyTypeAiservicesOptOutPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeAiservicesOptOutPolicy), @@ -307,7 +307,7 @@ func testAccPolicy_type_Backup(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_Type(rName, backupPolicyContent, organizations.PolicyTypeBackupPolicy), + Config: testAccPolicyConfig_type(rName, backupPolicyContent, organizations.PolicyTypeBackupPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeBackupPolicy), @@ -335,14 +335,14 @@ func testAccPolicy_type_SCP(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_Type(rName, serviceControlPolicyContent, organizations.PolicyTypeServiceControlPolicy), + Config: testAccPolicyConfig_type(rName, serviceControlPolicyContent, organizations.PolicyTypeServiceControlPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeServiceControlPolicy), ), }, { - Config: testAccPolicyConfig_Required(rName, serviceControlPolicyContent), + Config: testAccPolicyConfig_required(rName, serviceControlPolicyContent), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeServiceControlPolicy), @@ -370,7 +370,7 @@ func testAccPolicy_type_Tag(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_Type(rName, tagPolicyContent, organizations.PolicyTypeTagPolicy), + Config: testAccPolicyConfig_type(rName, tagPolicyContent, organizations.PolicyTypeTagPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeTagPolicy), @@ -397,10 +397,10 @@ func testAccPolicy_importManagedPolicy(t *testing.T) { CheckDestroy: testAccCheckPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig_managedPolicySetup, + Config: testAccPolicyConfig_managedSetup, }, { - Config: testAccPolicyConfig_managedPolicy, + Config: testAccPolicyConfig_managed, ResourceName: resourceName, ImportStateId: resourceID, ImportState: true, @@ -473,7 +473,7 @@ func testAccCheckPolicyExists(resourceName string, policy *organizations.Policy) } } -func testAccPolicyConfig_Description(rName, description string) string { +func testAccPolicyConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -497,7 +497,7 @@ EOF `, description, rName) } -func testAccPolicyConfig_TagA(rName string) string { +func testAccPolicyConfig_tagA(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -525,7 +525,7 @@ EOF `, rName) } -func testAccPolicyConfig_TagB(rName string) string { +func testAccPolicyConfig_tagB(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -553,7 +553,7 @@ EOF `, rName) } -func testAccPolicyConfig_TagC(rName string) string { +func testAccPolicyConfig_tagC(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -580,7 +580,7 @@ EOF `, rName) } -func testAccPolicyConfig_NoTag(rName string) string { +func testAccPolicyConfig_noTag(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -603,7 +603,7 @@ EOF `, rName) } -func testAccPolicyConfig_Required(rName, content string) string { +func testAccPolicyConfig_required(rName, content string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -616,7 +616,7 @@ resource "aws_organizations_policy" "test" { `, strconv.Quote(content), rName) } -func testAccPolicyConcurrentConfig(rName string) string { +func testAccPolicyConfig_concurrent(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -707,7 +707,7 @@ EOF `, rName) } -func testAccPolicyConfig_Type(rName, content, policyType string) string { +func testAccPolicyConfig_type(rName, content, policyType string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} @@ -721,13 +721,13 @@ resource "aws_organizations_policy" "test" { `, strconv.Quote(content), rName, policyType) } -const testAccPolicyConfig_managedPolicySetup = ` +const testAccPolicyConfig_managedSetup = ` resource "aws_organizations_organization" "test" { enabled_policy_types = ["SERVICE_CONTROL_POLICY"] } ` -const testAccPolicyConfig_managedPolicy = ` +const testAccPolicyConfig_managed = ` resource "aws_organizations_organization" "test" { enabled_policy_types = ["SERVICE_CONTROL_POLICY"] } diff --git a/internal/service/organizations/resource_tags_data_source_test.go b/internal/service/organizations/resource_tags_data_source_test.go index e1067603401..95b6c4d2dce 100644 --- a/internal/service/organizations/resource_tags_data_source_test.go +++ b/internal/service/organizations/resource_tags_data_source_test.go @@ -21,7 +21,7 @@ func testAccResourceTagsDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccResourceTagsDataSourceConfig(rName), + Config: testAccResourceTagsDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "tags.#", dataSourceName, "tags.#"), ), @@ -30,7 +30,7 @@ func testAccResourceTagsDataSource_basic(t *testing.T) { }) } -func testAccResourceTagsDataSourceConfig(rName string) string { +func testAccResourceTagsDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} diff --git a/internal/service/outposts/outpost_asset_data_source.go b/internal/service/outposts/outpost_asset_data_source.go new file mode 100644 index 00000000000..b35083639c6 --- /dev/null +++ b/internal/service/outposts/outpost_asset_data_source.go @@ -0,0 +1,83 @@ +package outposts + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func DataSourceOutpostAsset() *schema.Resource { + return &schema.Resource{ + Read: DataSourceOutpostAssetRead, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidARN, + }, + "asset_id": { + Type: schema.TypeString, + Required: true, + }, + "asset_type": { + Type: schema.TypeString, + Computed: true, + }, + "host_id": { + Type: schema.TypeString, + Computed: true, + }, + "rack_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func DataSourceOutpostAssetRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).OutpostsConn + outpost_id := aws.String(d.Get("arn").(string)) + + input := &outposts.ListAssetsInput{ + OutpostIdentifier: outpost_id, + } + + var results []*outposts.AssetInfo + err := conn.ListAssetsPages(input, func(page *outposts.ListAssetsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + for _, asset := range page.Assets { + if asset == nil { + continue + } + if v, ok := d.GetOk("asset_id"); ok && v.(string) != aws.StringValue(asset.AssetId) { + continue + } + results = append(results, asset) + } + return !lastPage + }) + + if err != nil { + return fmt.Errorf("error listing Outposts Asset: %w", err) + } + if len(results) == 0 { + return fmt.Errorf("no Outposts Asset found matching criteria; try different search") + } + + asset := results[0] + + d.SetId(aws.StringValue(outpost_id)) + d.Set("asset_id", asset.AssetId) + d.Set("asset_type", asset.AssetType) + d.Set("host_id", asset.ComputeAttributes.HostId) + d.Set("rack_id", asset.RackId) + return nil +} diff --git a/internal/service/outposts/outpost_asset_data_source_test.go b/internal/service/outposts/outpost_asset_data_source_test.go new file mode 100644 index 00000000000..c7a56f74cba --- /dev/null +++ b/internal/service/outposts/outpost_asset_data_source_test.go @@ -0,0 +1,46 @@ +package outposts_test + +import ( + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" +) + +func TestAccOutpostsAssetDataSource_id(t *testing.T) { + dataSourceName := "data.aws_outposts_asset.test" + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckOutpostsOutposts(t) }, + ErrorCheck: acctest.ErrorCheck(t, outposts.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccOutpostAssetDataSourceConfig_id(), + Check: resource.ComposeTestCheckFunc( + acctest.MatchResourceAttrRegionalARN(dataSourceName, "arn", "outposts", regexp.MustCompile(`outpost/.+`)), + resource.TestMatchResourceAttr(dataSourceName, "asset_id", regexp.MustCompile(`^(\w+)$`)), + resource.TestCheckResourceAttrSet(dataSourceName, "asset_type"), + resource.TestMatchResourceAttr(dataSourceName, "rack_id", regexp.MustCompile(`^[\S \n]+$`)), + ), + }, + }, + }) +} + +func testAccOutpostAssetDataSourceConfig_id() string { + return ` +data "aws_outposts_outposts" "test" {} + +data "aws_outposts_assets" "test" { + arn = tolist(data.aws_outposts_outposts.test.arns)[0] +} + +data "aws_outposts_asset" "test" { + arn = tolist(data.aws_outposts_outposts.test.arns)[0] + asset_id = data.aws_outposts_assets.test.asset_ids[0] +} + +` +} diff --git a/internal/service/outposts/outpost_assets_data_source.go b/internal/service/outposts/outpost_assets_data_source.go new file mode 100644 index 00000000000..ac412554c1f --- /dev/null +++ b/internal/service/outposts/outpost_assets_data_source.go @@ -0,0 +1,64 @@ +package outposts + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func DataSourceOutpostAssets() *schema.Resource { + return &schema.Resource{ + Read: DataSourceOutpostAssetsRead, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidARN, + }, + "asset_ids": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func DataSourceOutpostAssetsRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).OutpostsConn + outpost_id := aws.String(d.Get("arn").(string)) + + input := &outposts.ListAssetsInput{ + OutpostIdentifier: outpost_id, + } + var asset_ids []string + err := conn.ListAssetsPages(input, func(page *outposts.ListAssetsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + for _, asset := range page.Assets { + if asset == nil { + continue + } + asset_ids = append(asset_ids, aws.StringValue(asset.AssetId)) + } + return !lastPage + }) + + if err != nil { + return fmt.Errorf("error listing Outposts Assets: %w", err) + } + if len(asset_ids) == 0 { + return fmt.Errorf("no Outposts Assets found matching criteria; try different search") + } + + d.SetId(aws.StringValue(outpost_id)) + d.Set("asset_ids", asset_ids) + + return nil +} diff --git a/internal/service/outposts/outpost_assets_data_source_test.go b/internal/service/outposts/outpost_assets_data_source_test.go new file mode 100644 index 00000000000..0bab5c3eacf --- /dev/null +++ b/internal/service/outposts/outpost_assets_data_source_test.go @@ -0,0 +1,39 @@ +package outposts_test + +import ( + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" +) + +func TestAccOutpostsAssetsDataSource_id(t *testing.T) { + dataSourceName := "data.aws_outposts_assets.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckOutpostsOutposts(t) }, + ErrorCheck: acctest.ErrorCheck(t, outposts.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccOutpostAssetsDataSourceConfig_id(), + Check: resource.ComposeTestCheckFunc( + acctest.MatchResourceAttrRegionalARN(dataSourceName, "arn", "outposts", regexp.MustCompile(`outpost/.+`)), + ), + }, + }, + }) +} + +func testAccOutpostAssetsDataSourceConfig_id() string { + return ` +data "aws_outposts_outposts" "test" {} + +data "aws_outposts_assets" "test" { + arn = tolist(data.aws_outposts_outposts.test.arns)[0] +} + +` +} diff --git a/internal/service/outposts/outpost_data_source_test.go b/internal/service/outposts/outpost_data_source_test.go index 7caeb304da6..176c7da91e2 100644 --- a/internal/service/outposts/outpost_data_source_test.go +++ b/internal/service/outposts/outpost_data_source_test.go @@ -19,7 +19,7 @@ func TestAccOutpostsOutpostDataSource_id(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOutpostIDDataSourceConfig(), + Config: testAccOutpostDataSourceConfig_id(), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrRegionalARNIgnoreRegionAndAccount(dataSourceName, "arn", "outposts", regexp.MustCompile(`outpost/op-.+$`).String()), resource.TestMatchResourceAttr(dataSourceName, "availability_zone", regexp.MustCompile(`^.+$`)), @@ -45,7 +45,7 @@ func TestAccOutpostsOutpostDataSource_name(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOutpostNameDataSourceConfig(), + Config: testAccOutpostDataSourceConfig_name(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", sourceDataSourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone", sourceDataSourceName, "availability_zone"), @@ -71,7 +71,7 @@ func TestAccOutpostsOutpostDataSource_arn(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOutpostARNDataSourceConfig(), + Config: testAccOutpostDataSourceConfig_arn(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", sourceDataSourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone", sourceDataSourceName, "availability_zone"), @@ -97,7 +97,7 @@ func TestAccOutpostsOutpostDataSource_ownerID(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOutpostOwnerIDDataSourceConfig(), + Config: testAccOutpostDataSourceConfig_ownerID(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", sourceDataSourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone", sourceDataSourceName, "availability_zone"), @@ -112,7 +112,7 @@ func TestAccOutpostsOutpostDataSource_ownerID(t *testing.T) { }) } -func testAccOutpostIDDataSourceConfig() string { +func testAccOutpostDataSourceConfig_id() string { return ` data "aws_outposts_outposts" "test" {} @@ -122,7 +122,7 @@ data "aws_outposts_outpost" "test" { ` } -func testAccOutpostNameDataSourceConfig() string { +func testAccOutpostDataSourceConfig_name() string { return ` data "aws_outposts_outposts" "test" {} @@ -136,7 +136,7 @@ data "aws_outposts_outpost" "test" { ` } -func testAccOutpostARNDataSourceConfig() string { +func testAccOutpostDataSourceConfig_arn() string { return ` data "aws_outposts_outposts" "test" {} @@ -150,7 +150,7 @@ data "aws_outposts_outpost" "test" { ` } -func testAccOutpostOwnerIDDataSourceConfig() string { +func testAccOutpostDataSourceConfig_ownerID() string { return ` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/outposts/outpost_instance_type_data_source_test.go b/internal/service/outposts/outpost_instance_type_data_source_test.go index b1a43210f7f..cf44a638ff1 100644 --- a/internal/service/outposts/outpost_instance_type_data_source_test.go +++ b/internal/service/outposts/outpost_instance_type_data_source_test.go @@ -19,7 +19,7 @@ func TestAccOutpostsOutpostInstanceTypeDataSource_instanceType(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOutpostInstanceTypeInstanceTypeDataSourceConfig(), + Config: testAccOutpostInstanceTypeDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "instance_type", regexp.MustCompile(`^.+$`)), ), @@ -38,7 +38,7 @@ func TestAccOutpostsOutpostInstanceTypeDataSource_preferredInstanceTypes(t *test CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOutpostInstanceTypePreferredInstanceTypesDataSourceConfig(), + Config: testAccOutpostInstanceTypeDataSourceConfig_preferreds(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "instance_type", regexp.MustCompile(`^.+$`)), ), @@ -47,7 +47,7 @@ func TestAccOutpostsOutpostInstanceTypeDataSource_preferredInstanceTypes(t *test }) } -func testAccOutpostInstanceTypeInstanceTypeDataSourceConfig() string { +func testAccOutpostInstanceTypeDataSourceConfig_basic() string { return ` data "aws_outposts_outposts" "test" {} @@ -62,7 +62,7 @@ data "aws_outposts_outpost_instance_type" "test" { ` } -func testAccOutpostInstanceTypePreferredInstanceTypesDataSourceConfig() string { +func testAccOutpostInstanceTypeDataSourceConfig_preferreds() string { return ` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/outposts/outpost_instance_types_data_source_test.go b/internal/service/outposts/outpost_instance_types_data_source_test.go index d4a276cb69f..c4e654c1350 100644 --- a/internal/service/outposts/outpost_instance_types_data_source_test.go +++ b/internal/service/outposts/outpost_instance_types_data_source_test.go @@ -20,7 +20,7 @@ func TestAccOutpostsOutpostInstanceTypesDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOutpostInstanceTypesDataSourceConfig(), + Config: testAccOutpostInstanceTypesDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckOutpostInstanceTypesAttributes(dataSourceName), ), @@ -44,7 +44,7 @@ func testAccCheckOutpostInstanceTypesAttributes(dataSourceName string) resource. } } -func testAccOutpostInstanceTypesDataSourceConfig() string { +func testAccOutpostInstanceTypesDataSourceConfig_basic() string { return ` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/outposts/site_data_source_test.go b/internal/service/outposts/site_data_source_test.go index 357fe373663..5e8c48bd2c0 100644 --- a/internal/service/outposts/site_data_source_test.go +++ b/internal/service/outposts/site_data_source_test.go @@ -19,7 +19,7 @@ func TestAccOutpostsSiteDataSource_id(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccSiteIDDataSourceConfig(), + Config: testAccSiteDataSourceConfig_id(), Check: resource.ComposeTestCheckFunc( acctest.CheckResourceAttrAccountID(dataSourceName, "account_id"), resource.TestCheckResourceAttrSet(dataSourceName, "description"), @@ -42,7 +42,7 @@ func TestAccOutpostsSiteDataSource_name(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccSiteNameDataSourceConfig(), + Config: testAccSiteDataSourceConfig_name(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "account_id", sourceDataSourceName, "account_id"), resource.TestCheckResourceAttrPair(dataSourceName, "description", sourceDataSourceName, "description"), @@ -54,7 +54,7 @@ func TestAccOutpostsSiteDataSource_name(t *testing.T) { }) } -func testAccSiteIDDataSourceConfig() string { +func testAccSiteDataSourceConfig_id() string { return ` data "aws_outposts_sites" "test" {} @@ -64,7 +64,7 @@ data "aws_outposts_site" "test" { ` } -func testAccSiteNameDataSourceConfig() string { +func testAccSiteDataSourceConfig_name() string { return ` data "aws_outposts_sites" "test" {} diff --git a/internal/service/outposts/sites_data_source_test.go b/internal/service/outposts/sites_data_source_test.go index 6e344260790..ea98f8159b4 100644 --- a/internal/service/outposts/sites_data_source_test.go +++ b/internal/service/outposts/sites_data_source_test.go @@ -21,7 +21,7 @@ func TestAccOutpostsSitesDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccSitesDataSourceConfig(), + Config: testAccSitesDataSourceConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckSitesAttributes(dataSourceName), ), @@ -66,7 +66,7 @@ func testAccPreCheckSites(t *testing.T) { } } -func testAccSitesDataSourceConfig() string { +func testAccSitesDataSourceConfig_basic() string { return ` data "aws_outposts_sites" "test" {} ` diff --git a/internal/service/pinpoint/app_test.go b/internal/service/pinpoint/app_test.go index 02d8fdd7d0f..bf0dd612189 100644 --- a/internal/service/pinpoint/app_test.go +++ b/internal/service/pinpoint/app_test.go @@ -26,7 +26,7 @@ func TestAccPinpointApp_basic(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppConfig_withGeneratedName, + Config: testAccAppConfig_generatedName, Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), ), @@ -52,7 +52,7 @@ func TestAccPinpointApp_campaignHookLambda(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppConfig_CampaignHookLambda(rName), + Config: testAccAppConfig_campaignHookLambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), resource.TestCheckResourceAttr(resourceName, "campaign_hook.#", "1"), @@ -80,7 +80,7 @@ func TestAccPinpointApp_limits(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppConfig_Limits(rName), + Config: testAccAppConfig_limits(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), resource.TestCheckResourceAttr(resourceName, "limits.#", "1"), @@ -108,7 +108,7 @@ func TestAccPinpointApp_quietTime(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppConfig_QuietTime(rName), + Config: testAccAppConfig_quietTime(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), resource.TestCheckResourceAttr(resourceName, "quiet_time.#", "1"), @@ -136,7 +136,7 @@ func TestAccPinpointApp_tags(t *testing.T) { CheckDestroy: testAccCheckRAMResourceShareDestroy, Steps: []resource.TestStep{ { - Config: testAccAppConfig_Tag1(rName, "key1", "value1"), + Config: testAccAppConfig_tag1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -149,7 +149,7 @@ func TestAccPinpointApp_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAppConfig_Tag2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAppConfig_tag2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -158,7 +158,7 @@ func TestAccPinpointApp_tags(t *testing.T) { ), }, { - Config: testAccAppConfig_Tag1(rName, "key2", "value2"), + Config: testAccAppConfig_tag1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &application), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -214,11 +214,11 @@ func testAccCheckAppExists(n string, application *pinpoint.ApplicationResponse) } } -const testAccAppConfig_withGeneratedName = ` +const testAccAppConfig_generatedName = ` resource "aws_pinpoint_app" "test" {} ` -func testAccAppConfig_CampaignHookLambda(rName string) string { +func testAccAppConfig_campaignHookLambda(rName string) string { return fmt.Sprintf(` resource "aws_pinpoint_app" "test" { name = %[1]q @@ -276,7 +276,7 @@ resource "aws_lambda_permission" "test" { `, rName) } -func testAccAppConfig_Limits(rName string) string { +func testAccAppConfig_limits(rName string) string { return fmt.Sprintf(` resource "aws_pinpoint_app" "test" { name = %[1]q @@ -291,7 +291,7 @@ resource "aws_pinpoint_app" "test" { `, rName) } -func testAccAppConfig_QuietTime(rName string) string { +func testAccAppConfig_quietTime(rName string) string { return fmt.Sprintf(` resource "aws_pinpoint_app" "test" { name = %[1]q @@ -304,7 +304,7 @@ resource "aws_pinpoint_app" "test" { `, rName) } -func testAccAppConfig_Tag1(rName, tagKey1, tagValue1 string) string { +func testAccAppConfig_tag1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_pinpoint_app" "test" { name = %[1]q @@ -316,7 +316,7 @@ resource "aws_pinpoint_app" "test" { `, rName, tagKey1, tagValue1) } -func testAccAppConfig_Tag2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAppConfig_tag2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_pinpoint_app" "test" { name = %[1]q diff --git a/internal/service/pinpoint/email_channel_test.go b/internal/service/pinpoint/email_channel_test.go index 9355393986e..b581fa10db2 100644 --- a/internal/service/pinpoint/email_channel_test.go +++ b/internal/service/pinpoint/email_channel_test.go @@ -30,7 +30,7 @@ func TestAccPinpointEmailChannel_basic(t *testing.T) { CheckDestroy: testAccCheckEmailChannelDestroy, Steps: []resource.TestStep{ { - Config: testAccEmailChannelConfig_FromAddress(domain, address1), + Config: testAccEmailChannelConfig_fromAddress(domain, address1), Check: resource.ComposeTestCheckFunc( testAccCheckEmailChannelExists(resourceName, &channel), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -46,7 +46,7 @@ func TestAccPinpointEmailChannel_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEmailChannelConfig_FromAddress(domain, address2), + Config: testAccEmailChannelConfig_fromAddress(domain, address2), Check: resource.ComposeTestCheckFunc( testAccCheckEmailChannelExists(resourceName, &channel), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -73,7 +73,7 @@ func TestAccPinpointEmailChannel_set(t *testing.T) { CheckDestroy: testAccCheckEmailChannelDestroy, Steps: []resource.TestStep{ { - Config: testAccEmailChannelConfigurationSetConfig(domain, address, rName), + Config: testAccEmailChannelConfig_configurationSet(domain, address, rName), Check: resource.ComposeTestCheckFunc( testAccCheckEmailChannelExists(resourceName, &channel), resource.TestCheckResourceAttrPair(resourceName, "configuration_set", "aws_ses_configuration_set.test", "name"), @@ -103,7 +103,7 @@ func TestAccPinpointEmailChannel_noRole(t *testing.T) { CheckDestroy: testAccCheckEmailChannelDestroy, Steps: []resource.TestStep{ { - Config: testAccEmailChannelNoRoleConfig(domain, address, rName), + Config: testAccEmailChannelConfig_noRole(domain, address, rName), Check: resource.ComposeTestCheckFunc( testAccCheckEmailChannelExists(resourceName, &channel), resource.TestCheckResourceAttrPair(resourceName, "configuration_set", "aws_ses_configuration_set.test", "arn"), @@ -132,7 +132,7 @@ func TestAccPinpointEmailChannel_disappears(t *testing.T) { CheckDestroy: testAccCheckEmailChannelDestroy, Steps: []resource.TestStep{ { - Config: testAccEmailChannelConfig_FromAddress(domain, address), + Config: testAccEmailChannelConfig_fromAddress(domain, address), Check: resource.ComposeTestCheckFunc( testAccCheckEmailChannelExists(resourceName, &channel), acctest.CheckResourceDisappears(acctest.Provider, tfpinpoint.ResourceEmailChannel(), resourceName), @@ -172,7 +172,7 @@ func testAccCheckEmailChannelExists(n string, channel *pinpoint.EmailChannelResp } } -func testAccEmailChannelConfig_FromAddress(domain, fromAddress string) string { +func testAccEmailChannelConfig_fromAddress(domain, fromAddress string) string { return fmt.Sprintf(` resource "aws_pinpoint_app" "test" {} @@ -229,7 +229,7 @@ EOF `, domain, fromAddress) } -func testAccEmailChannelConfigurationSetConfig(domain, fromAddress, rName string) string { +func testAccEmailChannelConfig_configurationSet(domain, fromAddress, rName string) string { return fmt.Sprintf(` resource "aws_pinpoint_app" "test" {} @@ -291,7 +291,7 @@ EOF `, domain, fromAddress, rName) } -func testAccEmailChannelNoRoleConfig(domain, fromAddress, rName string) string { +func testAccEmailChannelConfig_noRole(domain, fromAddress, rName string) string { return fmt.Sprintf(` resource "aws_pinpoint_app" "test" {} diff --git a/internal/service/pricing/product_data_source_test.go b/internal/service/pricing/product_data_source_test.go index eb25c701530..1af4abc2fac 100644 --- a/internal/service/pricing/product_data_source_test.go +++ b/internal/service/pricing/product_data_source_test.go @@ -18,7 +18,7 @@ func TestAccPricingProductDataSource_ec2(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccProductEC2DataSourceConfig(), + Config: testAccProductDataSourceConfig_ec2(), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_pricing_product.test", "result"), testAccCheckValueIsJSON("data.aws_pricing_product.test"), @@ -35,7 +35,7 @@ func TestAccPricingProductDataSource_redshift(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccProductRedshiftDataSourceConfig(), + Config: testAccProductDataSourceConfig_redshift(), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_pricing_product.test", "result"), testAccCheckValueIsJSON("data.aws_pricing_product.test"), @@ -45,7 +45,7 @@ func TestAccPricingProductDataSource_redshift(t *testing.T) { }) } -func testAccProductEC2DataSourceConfig() string { +func testAccProductDataSourceConfig_ec2() string { return acctest.ConfigCompose( testAccRegionProviderConfig(), ` @@ -96,7 +96,7 @@ data "aws_pricing_product" "test" { `) } -func testAccProductRedshiftDataSourceConfig() string { +func testAccProductDataSourceConfig_redshift() string { return acctest.ConfigCompose( testAccRegionProviderConfig(), ` diff --git a/internal/service/qldb/ledger_data_source_test.go b/internal/service/qldb/ledger_data_source_test.go index e27f73c88c3..c5baa22f006 100644 --- a/internal/service/qldb/ledger_data_source_test.go +++ b/internal/service/qldb/ledger_data_source_test.go @@ -21,7 +21,7 @@ func TestAccQLDBLedgerDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccLedgerDataSourceConfig(rName), + Config: testAccLedgerDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(datasourceName, "deletion_protection", resourceName, "deletion_protection"), @@ -35,7 +35,7 @@ func TestAccQLDBLedgerDataSource_basic(t *testing.T) { }) } -func testAccLedgerDataSourceConfig(rName string) string { +func testAccLedgerDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_qldb_ledger" "test" { name = %[1]q diff --git a/internal/service/qldb/ledger_test.go b/internal/service/qldb/ledger_test.go index 2cc240a73ed..13d806d7676 100644 --- a/internal/service/qldb/ledger_test.go +++ b/internal/service/qldb/ledger_test.go @@ -28,7 +28,7 @@ func TestAccQLDBLedger_basic(t *testing.T) { CheckDestroy: testAccCheckLedgerDestroy, Steps: []resource.TestStep{ { - Config: testAccLedgerConfig(rName), + Config: testAccLedgerConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "qldb", regexp.MustCompile(`ledger/.+`)), @@ -60,7 +60,7 @@ func TestAccQLDBLedger_disappears(t *testing.T) { CheckDestroy: testAccCheckLedgerDestroy, Steps: []resource.TestStep{ { - Config: testAccLedgerConfig(rName), + Config: testAccLedgerConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfqldb.ResourceLedger(), resourceName), @@ -82,7 +82,7 @@ func TestAccQLDBLedger_nameGenerated(t *testing.T) { CheckDestroy: testAccCheckLedgerDestroy, Steps: []resource.TestStep{ { - Config: testAccLedgerNameGeneratedConfig(), + Config: testAccLedgerConfig_nameGenerated(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile(`tf\d+`)), @@ -109,7 +109,7 @@ func TestAccQLDBLedger_update(t *testing.T) { CheckDestroy: testAccCheckLedgerDestroy, Steps: []resource.TestStep{ { - Config: testAccLedgerConfig(rName), + Config: testAccLedgerConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "false"), @@ -122,7 +122,7 @@ func TestAccQLDBLedger_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLedgerUpdatedConfig(rName), + Config: testAccLedgerConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "true"), @@ -130,7 +130,7 @@ func TestAccQLDBLedger_update(t *testing.T) { ), }, { - Config: testAccLedgerConfig(rName), + Config: testAccLedgerConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "false"), @@ -154,7 +154,7 @@ func TestAccQLDBLedger_kmsKey(t *testing.T) { CheckDestroy: testAccCheckLedgerDestroy, Steps: []resource.TestStep{ { - Config: testAccLedgerKMSKeyConfig(rName), + Config: testAccLedgerConfig_kmsKey(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "kms_key", kmsKeyResourceName, "arn"), @@ -166,7 +166,7 @@ func TestAccQLDBLedger_kmsKey(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLedgerKMSKeyUpdatedConfig(rName), + Config: testAccLedgerConfig_kmsKeyUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "kms_key", "AWS_OWNED_KMS_KEY"), @@ -188,7 +188,7 @@ func TestAccQLDBLedger_tags(t *testing.T) { CheckDestroy: testAccCheckLedgerDestroy, Steps: []resource.TestStep{ { - Config: testAccLedgerConfigTags1(rName, "key1", "value1"), + Config: testAccLedgerConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -201,7 +201,7 @@ func TestAccQLDBLedger_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLedgerConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccLedgerConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -210,7 +210,7 @@ func TestAccQLDBLedger_tags(t *testing.T) { ), }, { - Config: testAccLedgerConfigTags1(rName, "key2", "value2"), + Config: testAccLedgerConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckLedgerExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -270,7 +270,7 @@ func testAccCheckLedgerExists(n string, v *qldb.DescribeLedgerOutput) resource.T } } -func testAccLedgerConfig(rName string) string { +func testAccLedgerConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_qldb_ledger" "test" { name = %[1]q @@ -280,7 +280,7 @@ resource "aws_qldb_ledger" "test" { `, rName) } -func testAccLedgerUpdatedConfig(rName string) string { +func testAccLedgerConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_qldb_ledger" "test" { name = %[1]q @@ -290,7 +290,7 @@ resource "aws_qldb_ledger" "test" { `, rName) } -func testAccLedgerNameGeneratedConfig() string { +func testAccLedgerConfig_nameGenerated() string { return ` resource "aws_qldb_ledger" "test" { permissions_mode = "ALLOW_ALL" @@ -299,7 +299,7 @@ resource "aws_qldb_ledger" "test" { ` } -func testAccLedgerKMSKeyConfig(rName string) string { +func testAccLedgerConfig_kmsKey(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -315,7 +315,7 @@ resource "aws_qldb_ledger" "test" { `, rName) } -func testAccLedgerKMSKeyUpdatedConfig(rName string) string { +func testAccLedgerConfig_kmsKeyUpdated(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -331,7 +331,7 @@ resource "aws_qldb_ledger" "test" { `, rName) } -func testAccLedgerConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccLedgerConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_qldb_ledger" "test" { name = %[1]q @@ -345,7 +345,7 @@ resource "aws_qldb_ledger" "test" { `, rName, tagKey1, tagValue1) } -func testAccLedgerConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccLedgerConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_qldb_ledger" "test" { name = %[1]q diff --git a/internal/service/qldb/stream_test.go b/internal/service/qldb/stream_test.go index 3e2b90ff6a1..facb4da1fba 100644 --- a/internal/service/qldb/stream_test.go +++ b/internal/service/qldb/stream_test.go @@ -28,7 +28,7 @@ func TestAccQLDBStream_basic(t *testing.T) { CheckDestroy: testAccCheckStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccStreamConfig(rName), + Config: testAccStreamConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckStreamExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "qldb", regexp.MustCompile(`stream/.+`)), @@ -59,7 +59,7 @@ func TestAccQLDBStream_disappears(t *testing.T) { CheckDestroy: testAccCheckStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccStreamConfig(rName), + Config: testAccStreamConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStreamExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfqldb.ResourceStream(), resourceName), @@ -82,7 +82,7 @@ func TestAccQLDBStream_tags(t *testing.T) { CheckDestroy: testAccCheckStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccStreamConfigTags1(rName, "key1", "value1"), + Config: testAccStreamConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckStreamExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -90,7 +90,7 @@ func TestAccQLDBStream_tags(t *testing.T) { ), }, { - Config: testAccStreamConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccStreamConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStreamExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -99,7 +99,7 @@ func TestAccQLDBStream_tags(t *testing.T) { ), }, { - Config: testAccStreamConfigTags1(rName, "key2", "value2"), + Config: testAccStreamConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStreamExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -122,7 +122,7 @@ func TestAccQLDBStream_withEndTime(t *testing.T) { CheckDestroy: testAccCheckStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccStreamEndTimeConfig(rName), + Config: testAccStreamConfig_endTime(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStreamExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "exclusive_end_time"), @@ -233,7 +233,7 @@ resource "aws_iam_role" "test" { `, rName) } -func testAccStreamConfig(rName string) string { +func testAccStreamConfig_basic(rName string) string { return acctest.ConfigCompose(testAccStreamBaseConfig(rName), fmt.Sprintf(` resource "aws_qldb_stream" "test" { stream_name = %[1]q @@ -248,7 +248,7 @@ resource "aws_qldb_stream" "test" { `, rName)) } -func testAccStreamEndTimeConfig(rName string) string { +func testAccStreamConfig_endTime(rName string) string { return acctest.ConfigCompose(testAccStreamBaseConfig(rName), fmt.Sprintf(` resource "aws_qldb_stream" "test" { stream_name = %[1]q @@ -265,7 +265,7 @@ resource "aws_qldb_stream" "test" { `, rName)) } -func testAccStreamConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccStreamConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccStreamBaseConfig(rName), fmt.Sprintf(` resource "aws_qldb_stream" "test" { stream_name = %[1]q @@ -284,7 +284,7 @@ resource "aws_qldb_stream" "test" { `, rName, tagKey1, tagValue1)) } -func testAccStreamConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccStreamConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccStreamBaseConfig(rName), fmt.Sprintf(` resource "aws_qldb_stream" "test" { stream_name = %[1]q diff --git a/internal/service/quicksight/data_source_test.go b/internal/service/quicksight/data_source_test.go index 43cdbf0428e..97a02d00218 100644 --- a/internal/service/quicksight/data_source_test.go +++ b/internal/service/quicksight/data_source_test.go @@ -237,7 +237,7 @@ func TestAccQuickSightDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckDataSourceDestroy, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig(rId, rName), + Config: testAccDataSourceConfig_basic(rId, rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataSourceExists(resourceName, &dataSource), resource.TestCheckResourceAttr(resourceName, "data_source_id", rId), @@ -274,7 +274,7 @@ func TestAccQuickSightDataSource_disappears(t *testing.T) { CheckDestroy: testAccCheckDataSourceDestroy, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig(rId, rName), + Config: testAccDataSourceConfig_basic(rId, rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataSourceExists(resourceName, &dataSource), acctest.CheckResourceDisappears(acctest.Provider, tfquicksight.ResourceDataSource(), resourceName), @@ -298,7 +298,7 @@ func TestAccQuickSightDataSource_tags(t *testing.T) { CheckDestroy: testAccCheckDataSourceDestroy, Steps: []resource.TestStep{ { - Config: testAccTags1DataSourceConfig(rId, rName, "key1", "value1"), + Config: testAccDataSourceConfig_tags1(rId, rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDataSourceExists(resourceName, &dataSource), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -311,7 +311,7 @@ func TestAccQuickSightDataSource_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTags2DataSourceConfig(rId, rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDataSourceConfig_tags2(rId, rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDataSourceExists(resourceName, &dataSource), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -320,7 +320,7 @@ func TestAccQuickSightDataSource_tags(t *testing.T) { ), }, { - Config: testAccTags1DataSourceConfig(rId, rName, "key1", "value1"), + Config: testAccDataSourceConfig_tags1(rId, rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDataSourceExists(resourceName, &dataSource), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -344,7 +344,7 @@ func TestAccQuickSightDataSource_permissions(t *testing.T) { CheckDestroy: testAccCheckDataSourceDestroy, Steps: []resource.TestStep{ { - Config: testAccDataSourceConfig_Permissions(rId, rName), + Config: testAccDataSourceConfig_permissions(rId, rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataSourceExists(resourceName, &dataSource), resource.TestCheckResourceAttr(resourceName, "permission.#", "1"), @@ -362,7 +362,7 @@ func TestAccQuickSightDataSource_permissions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDataSourceConfig_UpdatePermissions(rId, rName), + Config: testAccDataSourceConfig_updatePermissions(rId, rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataSourceExists(resourceName, &dataSource), resource.TestCheckResourceAttr(resourceName, "permission.#", "1"), @@ -383,7 +383,7 @@ func TestAccQuickSightDataSource_permissions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDataSourceConfig(rId, rName), + Config: testAccDataSourceConfig_basic(rId, rName), Check: resource.ComposeTestCheckFunc( testAccCheckDataSourceExists(resourceName, &dataSource), resource.TestCheckResourceAttr(resourceName, "permission.#", "0"), @@ -497,7 +497,7 @@ EOF `, rName) } -func testAccDataSourceConfig(rId, rName string) string { +func testAccDataSourceConfig_basic(rId, rName string) string { return acctest.ConfigCompose( testAccBaseDataSourceConfig(rName), fmt.Sprintf(` @@ -519,7 +519,7 @@ resource "aws_quicksight_data_source" "test" { `, rId, rName)) } -func testAccTags1DataSourceConfig(rId, rName, key, value string) string { +func testAccDataSourceConfig_tags1(rId, rName, key, value string) string { return acctest.ConfigCompose( testAccBaseDataSourceConfig(rName), fmt.Sprintf(` @@ -545,7 +545,7 @@ resource "aws_quicksight_data_source" "test" { `, rId, rName, key, value)) } -func testAccTags2DataSourceConfig(rId, rName, key1, value1, key2, value2 string) string { +func testAccDataSourceConfig_tags2(rId, rName, key1, value1, key2, value2 string) string { return acctest.ConfigCompose( testAccBaseDataSourceConfig(rName), fmt.Sprintf(` @@ -589,7 +589,7 @@ resource "aws_quicksight_user" "test" { `, rName, acctest.DefaultEmailAddress) } -func testAccDataSourceConfig_Permissions(rId, rName string) string { +func testAccDataSourceConfig_permissions(rId, rName string) string { return acctest.ConfigCompose( testAccBaseDataSourceConfig(rName), testAccDataSource_UserConfig(rName), @@ -622,7 +622,7 @@ resource "aws_quicksight_data_source" "test" { `, rId, rName)) } -func testAccDataSourceConfig_UpdatePermissions(rId, rName string) string { +func testAccDataSourceConfig_updatePermissions(rId, rName string) string { return acctest.ConfigCompose( testAccBaseDataSourceConfig(rName), testAccDataSource_UserConfig(rName), diff --git a/internal/service/quicksight/group.go b/internal/service/quicksight/group.go index 02e8c836ff5..b757e5d4b2d 100644 --- a/internal/service/quicksight/group.go +++ b/internal/service/quicksight/group.go @@ -106,8 +106,8 @@ func resourceGroupRead(d *schema.ResourceData, meta interface{}) error { } resp, err := conn.DescribeGroup(descOpts) - if tfawserr.ErrCodeEquals(err, quicksight.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] QuickSight Group %s is already gone", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, quicksight.ErrCodeResourceNotFoundException) { + log.Printf("[WARN] QuickSight Group (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -143,13 +143,8 @@ func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error { } _, err = conn.UpdateGroup(updateOpts) - if tfawserr.ErrCodeEquals(err, quicksight.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] QuickSight Group %s is already gone", d.Id()) - d.SetId("") - return nil - } if err != nil { - return fmt.Errorf("Error updating QuickSight Group %s: %s", d.Id(), err) + return fmt.Errorf("error updating QuickSight Group %s: %w", d.Id(), err) } return resourceGroupRead(d, meta) diff --git a/internal/service/quicksight/group_membership.go b/internal/service/quicksight/group_membership.go index 27beee17358..be715c215d7 100644 --- a/internal/service/quicksight/group_membership.go +++ b/internal/service/quicksight/group_membership.go @@ -111,8 +111,8 @@ func resourceGroupMembershipRead(ctx context.Context, d *schema.ResourceData, me return diag.Errorf("Error listing QuickSight Group Memberships (%s): %s", d.Id(), err) } - if !found { - log.Printf("[WARN] QuickSight User-group membership %s is not found, removing from state", d.Id()) + if !d.IsNewResource() && !found { + log.Printf("[WARN] QuickSight User-group membership (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/quicksight/group_membership_test.go b/internal/service/quicksight/group_membership_test.go index b8040154f60..5e9321d9f43 100644 --- a/internal/service/quicksight/group_membership_test.go +++ b/internal/service/quicksight/group_membership_test.go @@ -27,7 +27,7 @@ func TestAccQuickSightGroupMembership_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccGroupMembershipConfig(groupName, memberName), + Config: testAccGroupMembershipConfig_basic(groupName, memberName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupMembershipExists(resourceName), ), @@ -53,7 +53,7 @@ func TestAccQuickSightGroupMembership_disappears(t *testing.T) { CheckDestroy: testAccCheckGroupMembershipDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupMembershipConfig(groupName, memberName), + Config: testAccGroupMembershipConfig_basic(groupName, memberName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupMembershipExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfquicksight.ResourceGroupMembership(), resourceName), @@ -130,10 +130,10 @@ func testAccCheckGroupMembershipExists(resourceName string) resource.TestCheckFu } } -func testAccGroupMembershipConfig(groupName string, memberName string) string { +func testAccGroupMembershipConfig_basic(groupName string, memberName string) string { return acctest.ConfigCompose( - testAccGroupConfig(groupName), - testAccUserConfig(memberName), + testAccGroupConfig_basic(groupName), + testAccUserConfig_basic(memberName), fmt.Sprintf(` resource "aws_quicksight_group_membership" "default" { group_name = aws_quicksight_group.default.group_name diff --git a/internal/service/quicksight/group_test.go b/internal/service/quicksight/group_test.go index d9e71359e68..a0875ccd241 100644 --- a/internal/service/quicksight/group_test.go +++ b/internal/service/quicksight/group_test.go @@ -30,7 +30,7 @@ func TestAccQuickSightGroup_basic(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(rName1), + Config: testAccGroupConfig_basic(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "group_name", rName1), @@ -38,7 +38,7 @@ func TestAccQuickSightGroup_basic(t *testing.T) { ), }, { - Config: testAccGroupConfig(rName2), + Config: testAccGroupConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "group_name", rName2), @@ -66,14 +66,14 @@ func TestAccQuickSightGroup_withDescription(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupWithDescriptionConfig(rName, "Description 1"), + Config: testAccGroupConfig_description(rName, "Description 1"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "description", "Description 1"), ), }, { - Config: testAccGroupWithDescriptionConfig(rName, "Description 2"), + Config: testAccGroupConfig_description(rName, "Description 2"), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "description", "Description 2"), @@ -100,7 +100,7 @@ func TestAccQuickSightGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccGroupConfig(rName), + Config: testAccGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGroupExists(resourceName, &group), testAccCheckGroupDisappears(&group), @@ -203,7 +203,7 @@ func testAccCheckGroupDisappears(v *quicksight.Group) resource.TestCheckFunc { } } -func testAccGroupConfig(rName string) string { +func testAccGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_quicksight_group" "default" { group_name = %[1]q @@ -211,7 +211,7 @@ resource "aws_quicksight_group" "default" { `, rName) } -func testAccGroupWithDescriptionConfig(rName, description string) string { +func testAccGroupConfig_description(rName, description string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/quicksight/user.go b/internal/service/quicksight/user.go index 7fcd0d96467..217555cb9b3 100644 --- a/internal/service/quicksight/user.go +++ b/internal/service/quicksight/user.go @@ -149,7 +149,7 @@ func resourceUserRead(d *schema.ResourceData, meta interface{}) error { } resp, err := conn.DescribeUser(descOpts) - if tfawserr.ErrCodeEquals(err, quicksight.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, quicksight.ErrCodeResourceNotFoundException) { log.Printf("[WARN] QuickSight User %s is not found", d.Id()) d.SetId("") return nil @@ -185,11 +185,6 @@ func resourceUserUpdate(d *schema.ResourceData, meta interface{}) error { } _, err = conn.UpdateUser(updateOpts) - if tfawserr.ErrCodeEquals(err, quicksight.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] QuickSight User %s is not found", d.Id()) - d.SetId("") - return nil - } if err != nil { return fmt.Errorf("Error updating QuickSight User %s: %s", d.Id(), err) } diff --git a/internal/service/quicksight/user_test.go b/internal/service/quicksight/user_test.go index 50f83847dcb..3f3f610f61f 100644 --- a/internal/service/quicksight/user_test.go +++ b/internal/service/quicksight/user_test.go @@ -32,7 +32,7 @@ func TestAccQuickSightUser_basic(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfig(rName1), + Config: testAccUserConfig_basic(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName1, &user), resource.TestCheckResourceAttr(resourceName1, "user_name", rName1), @@ -40,7 +40,7 @@ func TestAccQuickSightUser_basic(t *testing.T) { ), }, { - Config: testAccUserConfig(rName2), + Config: testAccUserConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName2, &user), resource.TestCheckResourceAttr(resourceName2, "user_name", rName2), @@ -63,14 +63,14 @@ func TestAccQuickSightUser_withInvalidFormattedEmailStillWorks(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserWithEmailConfig(rName, "nottarealemailbutworks"), + Config: testAccUserConfig_email(rName, "nottarealemailbutworks"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), resource.TestCheckResourceAttr(resourceName, "email", "nottarealemailbutworks"), ), }, { - Config: testAccUserWithEmailConfig(rName, "nottarealemailbutworks2"), + Config: testAccUserConfig_email(rName, "nottarealemailbutworks2"), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), resource.TestCheckResourceAttr(resourceName, "email", "nottarealemailbutworks2"), @@ -98,7 +98,7 @@ func TestAccQuickSightUser_withNamespace(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserWithNamespaceConfig(rName, namespace), + Config: testAccUserConfig_namespace(rName, namespace), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), resource.TestCheckResourceAttr(resourceName, "namespace", namespace), @@ -120,7 +120,7 @@ func TestAccQuickSightUser_disappears(t *testing.T) { CheckDestroy: testAccCheckUserDestroy, Steps: []resource.TestStep{ { - Config: testAccUserConfig(rName), + Config: testAccUserConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserExists(resourceName, &user), testAccCheckUserDisappears(&user), @@ -223,7 +223,7 @@ func testAccCheckUserDisappears(v *quicksight.User) resource.TestCheckFunc { } } -func testAccUserWithEmailConfig(rName, email string) string { +func testAccUserConfig_email(rName, email string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -237,7 +237,7 @@ resource "aws_quicksight_user" %[1]q { `, rName, email) } -func testAccUserWithNamespaceConfig(rName, namespace string) string { +func testAccUserConfig_namespace(rName, namespace string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -252,6 +252,6 @@ resource "aws_quicksight_user" %[1]q { `, rName, acctest.DefaultEmailAddress, namespace) } -func testAccUserConfig(rName string) string { - return testAccUserWithEmailConfig(rName, acctest.DefaultEmailAddress) +func testAccUserConfig_basic(rName string) string { + return testAccUserConfig_email(rName, acctest.DefaultEmailAddress) } diff --git a/internal/service/ram/find.go b/internal/service/ram/find.go index b9859eaf8a2..dd388714b2a 100644 --- a/internal/service/ram/find.go +++ b/internal/service/ram/find.go @@ -44,7 +44,7 @@ func FindResourceShareInvitationByResourceShareARNAndStatus(conn *ram.RAM, resou // Retry for Ram resource share invitation eventual consistency err := resource.Retry(FindInvitationTimeout, func() *resource.RetryError { - i, err := resourceShareInvitationByResourceShareArnAndStatus(conn, resourceShareArn, status) + i, err := resourceShareInvitationByResourceShareARNAndStatus(conn, resourceShareArn, status) invitation = i if err != nil { @@ -59,7 +59,7 @@ func FindResourceShareInvitationByResourceShareARNAndStatus(conn *ram.RAM, resou }) if tfresource.TimedOut(err) { - invitation, err = resourceShareInvitationByResourceShareArnAndStatus(conn, resourceShareArn, status) + invitation, err = resourceShareInvitationByResourceShareARNAndStatus(conn, resourceShareArn, status) } if invitation == nil { @@ -80,7 +80,7 @@ func FindResourceShareInvitationByARN(conn *ram.RAM, arn string) (*ram.ResourceS // Retry for Ram resource share invitation eventual consistency err := resource.Retry(FindInvitationTimeout, func() *resource.RetryError { - i, err := resourceShareInvitationByArn(conn, arn) + i, err := resourceShareInvitationByARN(conn, arn) invitation = i if err != nil { @@ -95,7 +95,7 @@ func FindResourceShareInvitationByARN(conn *ram.RAM, arn string) (*ram.ResourceS }) if tfresource.TimedOut(err) { - invitation, err = resourceShareInvitationByArn(conn, arn) + invitation, err = resourceShareInvitationByARN(conn, arn) } if invitation == nil { @@ -147,7 +147,7 @@ func resourceShare(conn *ram.RAM, input *ram.GetResourceSharesInput) (*ram.Resou return shares.ResourceShares[0], nil } -func resourceShareInvitationByResourceShareArnAndStatus(conn *ram.RAM, resourceShareArn, status string) (*ram.ResourceShareInvitation, error) { +func resourceShareInvitationByResourceShareARNAndStatus(conn *ram.RAM, resourceShareArn, status string) (*ram.ResourceShareInvitation, error) { var invitation *ram.ResourceShareInvitation input := &ram.GetResourceShareInvitationsInput{ @@ -172,7 +172,7 @@ func resourceShareInvitationByResourceShareArnAndStatus(conn *ram.RAM, resourceS return invitation, nil } -func resourceShareInvitationByArn(conn *ram.RAM, arn string) (*ram.ResourceShareInvitation, error) { +func resourceShareInvitationByARN(conn *ram.RAM, arn string) (*ram.ResourceShareInvitation, error) { input := &ram.GetResourceShareInvitationsInput{ ResourceShareInvitationArns: []*string{aws.String(arn)}, } diff --git a/internal/service/ram/principal_association.go b/internal/service/ram/principal_association.go index 9203c15aae8..b11c6b9b954 100644 --- a/internal/service/ram/principal_association.go +++ b/internal/service/ram/principal_association.go @@ -106,7 +106,7 @@ func resourcePrincipalAssociationRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("error reading RAM Resource Share (%s) Principal Association (%s): %s", resourceShareArn, principal, err) } - if association == nil || aws.StringValue(association.Status) == ram.ResourceShareAssociationStatusDisassociated { + if !d.IsNewResource() && (association == nil || aws.StringValue(association.Status) == ram.ResourceShareAssociationStatusDisassociated) { log.Printf("[WARN] RAM resource share principal association with ARN (%s) found, but empty or disassociated - removing from state", d.Id()) d.SetId("") return nil diff --git a/internal/service/ram/principal_association_test.go b/internal/service/ram/principal_association_test.go index 8ddbc8aed78..bf4c85f65b4 100644 --- a/internal/service/ram/principal_association_test.go +++ b/internal/service/ram/principal_association_test.go @@ -27,7 +27,7 @@ func TestAccRAMPrincipalAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckPrincipalAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccPrincipalAssociationConfig(rName), + Config: testAccPrincipalAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPrincipalAssociationExists(resourceName, &association), ), @@ -53,7 +53,7 @@ func TestAccRAMPrincipalAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckPrincipalAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccPrincipalAssociationConfig(rName), + Config: testAccPrincipalAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPrincipalAssociationExists(resourceName, &association), acctest.CheckResourceDisappears(acctest.Provider, tfram.ResourcePrincipalAssociation(), resourceName), @@ -138,7 +138,7 @@ func testAccCheckPrincipalAssociationDestroy(s *terraform.State) error { return nil } -func testAccPrincipalAssociationConfig(rName string) string { +func testAccPrincipalAssociationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ram_resource_share" "test" { allow_external_principals = true diff --git a/internal/service/ram/resource_association.go b/internal/service/ram/resource_association.go index ee7eca6e81e..ad0eb8b0c0d 100644 --- a/internal/service/ram/resource_association.go +++ b/internal/service/ram/resource_association.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func ResourceResourceAssociation() *schema.Resource { @@ -75,18 +76,16 @@ func resourceResourceAssociationRead(d *schema.ResourceData, meta interface{}) e } resourceShareAssociation, err := GetResourceShareAssociation(conn, resourceShareARN, resourceARN) - - if err != nil { - return fmt.Errorf("error reading RAM Resource Share (%s) Resource Association (%s): %s", resourceShareARN, resourceARN, err) - } - - if resourceShareAssociation == nil { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] RAM Resource Share (%s) Resource Association (%s) not found, removing from state", resourceShareARN, resourceARN) d.SetId("") return nil } + if err != nil { + return fmt.Errorf("error reading RAM Resource Share (%s) Resource Association (%s): %w", resourceShareARN, resourceARN, err) + } - if aws.StringValue(resourceShareAssociation.Status) != ram.ResourceShareAssociationStatusAssociated { + if !d.IsNewResource() && aws.StringValue(resourceShareAssociation.Status) != ram.ResourceShareAssociationStatusAssociated { log.Printf("[WARN] RAM Resource Share (%s) Resource Association (%s) not associated, removing from state", resourceShareARN, resourceARN) d.SetId("") return nil @@ -150,31 +149,35 @@ func GetResourceShareAssociation(conn *ram.RAM, resourceShareARN, resourceARN st output, err := conn.GetResourceShareAssociations(input) if tfawserr.ErrCodeEquals(err, ram.ErrCodeUnknownResourceException) { - return nil, nil + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } } if err != nil { return nil, err } - if output == nil || len(output.ResourceShareAssociations) == 0 || output.ResourceShareAssociations[0] == nil { - return nil, nil + switch count := len(output.ResourceShareAssociations); count { + case 0: + return nil, tfresource.NewEmptyResultError(input) + case 1: + return output.ResourceShareAssociations[0], nil + default: + return nil, tfresource.NewTooManyResultsError(count, input) } - - return output.ResourceShareAssociations[0], nil } func resourceAssociationStateRefreshFunc(conn *ram.RAM, resourceShareARN, resourceARN string) resource.StateRefreshFunc { return func() (interface{}, string, error) { resourceShareAssociation, err := GetResourceShareAssociation(conn, resourceShareARN, resourceARN) - - if err != nil { - return nil, ram.ResourceShareAssociationStatusFailed, err - } - - if resourceShareAssociation == nil { + if tfresource.NotFound(err) { return nil, ram.ResourceShareAssociationStatusDisassociated, nil } + if err != nil { + return nil, "", err + } if aws.StringValue(resourceShareAssociation.Status) == ram.ResourceShareAssociationStatusFailed { extendedErr := fmt.Errorf("association status message: %s", aws.StringValue(resourceShareAssociation.StatusMessage)) diff --git a/internal/service/ram/resource_association_test.go b/internal/service/ram/resource_association_test.go index a50069ceaee..0132fcbf2c2 100644 --- a/internal/service/ram/resource_association_test.go +++ b/internal/service/ram/resource_association_test.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfram "github.com/hashicorp/terraform-provider-aws/internal/service/ram" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func TestAccRAMResourceAssociation_basic(t *testing.T) { @@ -26,7 +27,7 @@ func TestAccRAMResourceAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckResourceAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceAssociationConfig(rName), + Config: testAccResourceAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceAssociationExists(resourceName, &resourceShareAssociation1), ), @@ -52,7 +53,7 @@ func TestAccRAMResourceAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckResourceAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceAssociationConfig(rName), + Config: testAccResourceAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceAssociationExists(resourceName, &resourceShareAssociation1), testAccCheckResourceAssociationDisappears(&resourceShareAssociation1), @@ -98,15 +99,13 @@ func testAccCheckResourceAssociationExists(resourceName string, association *ram } resourceShareAssociation, err := tfram.GetResourceShareAssociation(conn, resourceShareARN, resourceARN) - + if tfresource.NotFound(err) { + return fmt.Errorf("RAM Resource Share (%s) Resource Association (%s) not found", resourceShareARN, resourceARN) + } if err != nil { return fmt.Errorf("error reading RAM Resource Share (%s) Resource Association (%s): %s", resourceShareARN, resourceARN, err) } - if resourceShareAssociation == nil { - return fmt.Errorf("RAM Resource Share (%s) Resource Association (%s) not found", resourceShareARN, resourceARN) - } - if aws.StringValue(resourceShareAssociation.Status) != ram.ResourceShareAssociationStatusAssociated { return fmt.Errorf("RAM Resource Share (%s) Resource Association (%s) not associated: %s", resourceShareARN, resourceARN, aws.StringValue(resourceShareAssociation.Status)) } @@ -132,7 +131,9 @@ func testAccCheckResourceAssociationDestroy(s *terraform.State) error { } resourceShareAssociation, err := tfram.GetResourceShareAssociation(conn, resourceShareARN, resourceARN) - + if tfresource.NotFound(err) { + return nil + } if err != nil { return err } @@ -145,7 +146,7 @@ func testAccCheckResourceAssociationDestroy(s *terraform.State) error { return nil } -func testAccResourceAssociationConfig(rName string) string { +func testAccResourceAssociationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/ram/resource_share.go b/internal/service/ram/resource_share.go index fa536b42778..ce22d6e2a33 100644 --- a/internal/service/ram/resource_share.go +++ b/internal/service/ram/resource_share.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -31,22 +32,29 @@ func ResourceResourceShare() *schema.Resource { }, Schema: map[string]*schema.Schema{ + "allow_external_principals": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, "arn": { Type: schema.TypeString, Computed: true, }, - "name": { Type: schema.TypeString, Required: true, }, - - "allow_external_principals": { - Type: schema.TypeBool, + "permission_arns": { + Type: schema.TypeSet, Optional: true, - Default: false, + Computed: true, + ForceNew: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidARN, + }, }, - "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), }, @@ -60,26 +68,31 @@ func resourceResourceShareCreate(d *schema.ResourceData, meta interface{}) error defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) - request := &ram.CreateResourceShareInput{ - Name: aws.String(d.Get("name").(string)), + name := d.Get("name").(string) + input := &ram.CreateResourceShareInput{ AllowExternalPrincipals: aws.Bool(d.Get("allow_external_principals").(bool)), + Name: aws.String(name), + } + + if v, ok := d.GetOk("permission_arns"); ok && v.(*schema.Set).Len() > 0 { + input.PermissionArns = flex.ExpandStringSet(v.(*schema.Set)) } if len(tags) > 0 { - request.Tags = Tags(tags.IgnoreAWS()) + input.Tags = Tags(tags.IgnoreAWS()) } - log.Println("[DEBUG] Create RAM resource share request:", request) - createResp, err := conn.CreateResourceShare(request) + log.Printf("[DEBUG] Creating RAM Resource Share: %s", input) + output, err := conn.CreateResourceShare(input) + if err != nil { - return fmt.Errorf("Error creating RAM resource share: %s", err) + return fmt.Errorf("creating RAM Resource Share (%s): %w", name, err) } - d.SetId(aws.StringValue(createResp.ResourceShare.ResourceShareArn)) + d.SetId(aws.StringValue(output.ResourceShare.ResourceShareArn)) - _, err = WaitResourceShareOwnedBySelfActive(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) - if err != nil { - return fmt.Errorf("Error waiting for RAM resource share (%s) to become ready: %s", d.Id(), err) + if _, err = WaitResourceShareOwnedBySelfActive(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return fmt.Errorf("waiting for RAM Resource Share (%s) to become ready: %w", d.Id(), err) } return resourceResourceShareRead(d, meta) @@ -90,50 +103,55 @@ func resourceResourceShareRead(d *schema.ResourceData, meta interface{}) error { defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - request := &ram.GetResourceSharesInput{ - ResourceShareArns: []*string{aws.String(d.Id())}, - ResourceOwner: aws.String(ram.ResourceOwnerSelf), - } + resourceShare, err := FindResourceShareOwnerSelfByARN(conn, d.Id()) - output, err := conn.GetResourceShares(request) - if err != nil { - if tfawserr.ErrCodeEquals(err, ram.ErrCodeUnknownResourceException) { - log.Printf("[WARN] No RAM resource share by ARN (%s) found, removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error reading RAM resource share %s: %s", d.Id(), err) - } - - if len(output.ResourceShares) == 0 { - log.Printf("[WARN] No RAM resource share by ARN (%s) found, removing from state", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, ram.ErrCodeUnknownResourceException) { + log.Printf("[WARN] RAM Resource Share (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - resourceShare := output.ResourceShares[0] + if err != nil { + return fmt.Errorf("reading RAM Resource Share (%s): %w", d.Id(), err) + } - if aws.StringValue(resourceShare.Status) != ram.ResourceShareStatusActive { - log.Printf("[WARN] RAM resource share (%s) delet(ing|ed), removing from state", d.Id()) + if !d.IsNewResource() && aws.StringValue(resourceShare.Status) != ram.ResourceShareStatusActive { + log.Printf("[WARN] RAM Resource Share (%s) not active, removing from state", d.Id()) d.SetId("") return nil } + d.Set("allow_external_principals", resourceShare.AllowExternalPrincipals) d.Set("arn", resourceShare.ResourceShareArn) d.Set("name", resourceShare.Name) - d.Set("allow_external_principals", resourceShare.AllowExternalPrincipals) tags := KeyValueTags(resourceShare.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) + } + + perms, err := conn.ListResourceSharePermissions(&ram.ListResourceSharePermissionsInput{ + ResourceShareArn: aws.String(d.Id()), + }) + + if err != nil { + return fmt.Errorf("listing RAM Resource Share (%s) permissions: %w", d.Id(), err) + } + + permissionARNs := make([]*string, 0, len(perms.Permissions)) + + for _, v := range perms.Permissions { + permissionARNs = append(permissionARNs, v.Arn) } + d.Set("permission_arns", aws.StringValueSlice(permissionARNs)) + return nil } @@ -141,21 +159,17 @@ func resourceResourceShareUpdate(d *schema.ResourceData, meta interface{}) error conn := meta.(*conns.AWSClient).RAMConn if d.HasChanges("name", "allow_external_principals") { - request := &ram.UpdateResourceShareInput{ - ResourceShareArn: aws.String(d.Id()), - Name: aws.String(d.Get("name").(string)), + input := &ram.UpdateResourceShareInput{ AllowExternalPrincipals: aws.Bool(d.Get("allow_external_principals").(bool)), + Name: aws.String(d.Get("name").(string)), + ResourceShareArn: aws.String(d.Id()), } - log.Println("[DEBUG] Update RAM resource share request:", request) - _, err := conn.UpdateResourceShare(request) + log.Printf("[DEBUG] Updating RAM Resource Share: %s", input) + _, err := conn.UpdateResourceShare(input) + if err != nil { - if tfawserr.ErrCodeEquals(err, ram.ErrCodeUnknownResourceException) { - log.Printf("[WARN] No RAM resource share by ARN (%s) found", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error updating RAM resource share %s: %s", d.Id(), err) + return fmt.Errorf("updating RAM Resource Share (%s): %w", d.Id(), err) } } @@ -163,7 +177,7 @@ func resourceResourceShareUpdate(d *schema.ResourceData, meta interface{}) error o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating RAM resource share (%s) tags: %s", d.Id(), err) + return fmt.Errorf("updating RAM Resource Share (%s) tags: %w", d.Id(), err) } } @@ -173,23 +187,21 @@ func resourceResourceShareUpdate(d *schema.ResourceData, meta interface{}) error func resourceResourceShareDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).RAMConn - deleteResourceShareInput := &ram.DeleteResourceShareInput{ + log.Printf("[DEBUG] Delete RAM Resource Share: %s", d.Id()) + _, err := conn.DeleteResourceShare(&ram.DeleteResourceShareInput{ ResourceShareArn: aws.String(d.Id()), + }) + + if tfawserr.ErrCodeEquals(err, ram.ErrCodeUnknownResourceException) { + return nil } - log.Println("[DEBUG] Delete RAM resource share request:", deleteResourceShareInput) - _, err := conn.DeleteResourceShare(deleteResourceShareInput) if err != nil { - if tfawserr.ErrCodeEquals(err, ram.ErrCodeUnknownResourceException) { - return nil - } - return fmt.Errorf("Error deleting RAM resource share %s: %s", d.Id(), err) + return fmt.Errorf("deleting RAM Resource Share (%s): %w", d.Id(), err) } - _, err = WaitResourceShareOwnedBySelfDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)) - - if err != nil { - return fmt.Errorf("Error waiting for RAM resource share (%s) to become ready: %s", d.Id(), err) + if _, err = WaitResourceShareOwnedBySelfDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + return fmt.Errorf("waiting for RAM Resource Share (%s) delete: %w", d.Id(), err) } return nil diff --git a/internal/service/ram/resource_share_accepter_test.go b/internal/service/ram/resource_share_accepter_test.go index 120555a12a3..96f5b251002 100644 --- a/internal/service/ram/resource_share_accepter_test.go +++ b/internal/service/ram/resource_share_accepter_test.go @@ -34,7 +34,7 @@ func TestAccRAMResourceShareAccepter_basic(t *testing.T) { CheckDestroy: testAccCheckResourceShareAccepterDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceShareAccepterBasic(rName), + Config: testAccResourceShareAccepterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareAccepterExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "share_arn", principalAssociationResourceName, "resource_share_arn"), @@ -48,7 +48,7 @@ func TestAccRAMResourceShareAccepter_basic(t *testing.T) { ), }, { - Config: testAccResourceShareAccepterBasic(rName), + Config: testAccResourceShareAccepterConfig_basic(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -72,7 +72,7 @@ func TestAccRAMResourceShareAccepter_disappears(t *testing.T) { CheckDestroy: testAccCheckResourceShareAccepterDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceShareAccepterBasic(rName), + Config: testAccResourceShareAccepterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareAccepterExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfram.ResourceResourceShareAccepter(), resourceName), @@ -99,7 +99,7 @@ func TestAccRAMResourceShareAccepter_resourceAssociation(t *testing.T) { CheckDestroy: testAccCheckResourceShareAccepterDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceShareAccepterResourceAssociation(rName), + Config: testAccResourceShareAccepterConfig_association(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareAccepterExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "share_arn", principalAssociationResourceName, "resource_share_arn"), @@ -113,7 +113,7 @@ func TestAccRAMResourceShareAccepter_resourceAssociation(t *testing.T) { ), }, { - Config: testAccResourceShareAccepterResourceAssociation(rName), + Config: testAccResourceShareAccepterConfig_association(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -175,7 +175,7 @@ func testAccCheckResourceShareAccepterExists(name string) resource.TestCheckFunc } } -func testAccResourceShareAccepterBasic(rName string) string { +func testAccResourceShareAccepterConfig_basic(rName string) string { return acctest.ConfigAlternateAccountProvider() + fmt.Sprintf(` resource "aws_ram_resource_share_accepter" "test" { share_arn = aws_ram_principal_association.test.resource_share_arn @@ -203,8 +203,8 @@ data "aws_caller_identity" "receiver" {} `, rName) } -func testAccResourceShareAccepterResourceAssociation(rName string) string { - return acctest.ConfigCompose(testAccResourceShareAccepterBasic(rName), fmt.Sprintf(` +func testAccResourceShareAccepterConfig_association(rName string) string { + return acctest.ConfigCompose(testAccResourceShareAccepterConfig_basic(rName), fmt.Sprintf(` resource "aws_ram_resource_association" "test" { provider = "awsalternate" diff --git a/internal/service/ram/resource_share_data_source.go b/internal/service/ram/resource_share_data_source.go index 33552e57836..9638f433320 100644 --- a/internal/service/ram/resource_share_data_source.go +++ b/internal/service/ram/resource_share_data_source.go @@ -35,12 +35,15 @@ func DataSourceResourceShare() *schema.Resource { }, "resource_owner": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - ram.ResourceOwnerOtherAccounts, - ram.ResourceOwnerSelf, - }, false), + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(ram.ResourceOwner_Values(), false), + }, + + "resource_share_status": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice(ram.ResourceShareStatus_Values(), false), }, "name": { @@ -82,6 +85,10 @@ func dataSourceResourceShareRead(d *schema.ResourceData, meta interface{}) error ResourceOwner: aws.String(owner), } + if v, ok := d.GetOk("resource_share_status"); ok { + params.ResourceShareStatus = aws.String(v.(string)) + } + if filtersOk { params.TagFilters = buildTagFilters(filters.(*schema.Set)) } diff --git a/internal/service/ram/resource_share_data_source_test.go b/internal/service/ram/resource_share_data_source_test.go index 7abe8cb462c..4e9352f80df 100644 --- a/internal/service/ram/resource_share_data_source_test.go +++ b/internal/service/ram/resource_share_data_source_test.go @@ -22,11 +22,11 @@ func TestAccRAMResourceShareDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccResourceShareDataSourceConfig_NonExistent, + Config: testAccResourceShareDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`No matching resource found`), }, { - Config: testAccResourceShareDataSourceConfig_Name(rName), + Config: testAccResourceShareDataSourceConfig_name(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), @@ -48,7 +48,7 @@ func TestAccRAMResourceShareDataSource_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccResourceShareDataSourceConfig_Tags(rName), + Config: testAccResourceShareDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), @@ -59,30 +59,52 @@ func TestAccRAMResourceShareDataSource_tags(t *testing.T) { }) } -func testAccResourceShareDataSourceConfig_Name(rName string) string { +func TestAccRAMResourceShareDataSource_status(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_ram_resource_share.test" + datasourceName := "data.aws_ram_resource_share.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ram.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccResourceShareDataSourceConfig_status(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrSet(datasourceName, "owning_account_id"), + ), + }, + }, + }) +} + +func testAccResourceShareDataSourceConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_ram_resource_share" "wrong" { - name = "%s-wrong" + name = "%[1]s-wrong" } resource "aws_ram_resource_share" "test" { - name = "%s" + name = %[1]q } data "aws_ram_resource_share" "test" { name = aws_ram_resource_share.test.name resource_owner = "SELF" } -`, rName, rName) +`, rName) } -func testAccResourceShareDataSourceConfig_Tags(rName string) string { +func testAccResourceShareDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` resource "aws_ram_resource_share" "test" { - name = "%s" + name = %[1]q tags = { - Name = "%s-Tags" + Name = "%[1]s-Tags" } } @@ -92,15 +114,29 @@ data "aws_ram_resource_share" "test" { filter { name = "Name" - values = ["%s-Tags"] + values = ["%[1]s-Tags"] } } -`, rName, rName, rName) +`, rName) } -const testAccResourceShareDataSourceConfig_NonExistent = ` +const testAccResourceShareDataSourceConfig_nonExistent = ` data "aws_ram_resource_share" "test" { name = "tf-acc-test-does-not-exist" resource_owner = "SELF" } ` + +func testAccResourceShareDataSourceConfig_status(rName string) string { + return fmt.Sprintf(` +resource "aws_ram_resource_share" "test" { + name = "%s" +} + +data "aws_ram_resource_share" "test" { + name = aws_ram_resource_share.test.name + resource_owner = "SELF" + resource_share_status = "ACTIVE" +} +`, rName) +} diff --git a/internal/service/ram/resource_share_test.go b/internal/service/ram/resource_share_test.go index 8adf4c92e27..d7e050b29bb 100644 --- a/internal/service/ram/resource_share_test.go +++ b/internal/service/ram/resource_share_test.go @@ -12,6 +12,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" + tfram "github.com/hashicorp/terraform-provider-aws/internal/service/ram" ) func TestAccRAMResourceShare_basic(t *testing.T) { @@ -26,12 +27,44 @@ func TestAccRAMResourceShare_basic(t *testing.T) { CheckDestroy: testAccCheckResourceShareDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceShareNameConfig(rName), + Config: testAccResourceShareConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareExists(resourceName, &resourceShare), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ram", regexp.MustCompile(`resource-share/.+`)), resource.TestCheckResourceAttr(resourceName, "allow_external_principals", "false"), resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "permission_arns.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccRAMResourceShare_permission(t *testing.T) { + var resourceShare ram.ResourceShare + resourceName := "aws_ram_resource_share.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ram.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckResourceShareDestroy, + Steps: []resource.TestStep{ + { + Config: testAccResourceShareConfig_namePermission(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckResourceShareExists(resourceName, &resourceShare), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ram", regexp.MustCompile(`resource-share/.+`)), + resource.TestCheckResourceAttr(resourceName, "allow_external_principals", "false"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "permission_arns.#", "1"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, @@ -56,7 +89,7 @@ func TestAccRAMResourceShare_allowExternalPrincipals(t *testing.T) { CheckDestroy: testAccCheckResourceShareDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceShareAllowExternalPrincipalsConfig(rName, false), + Config: testAccResourceShareConfig_allowExternalPrincipals(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareExists(resourceName, &resourceShare1), resource.TestCheckResourceAttr(resourceName, "allow_external_principals", "false"), @@ -68,7 +101,7 @@ func TestAccRAMResourceShare_allowExternalPrincipals(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccResourceShareAllowExternalPrincipalsConfig(rName, true), + Config: testAccResourceShareConfig_allowExternalPrincipals(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareExists(resourceName, &resourceShare2), resource.TestCheckResourceAttr(resourceName, "allow_external_principals", "true"), @@ -91,7 +124,7 @@ func TestAccRAMResourceShare_name(t *testing.T) { CheckDestroy: testAccCheckResourceShareDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceShareNameConfig(rName), + Config: testAccResourceShareConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareExists(resourceName, &resourceShare1), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -103,7 +136,7 @@ func TestAccRAMResourceShare_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccResourceShareNameConfig(rName2), + Config: testAccResourceShareConfig_name(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareExists(resourceName, &resourceShare2), resource.TestCheckResourceAttr(resourceName, "name", rName2), @@ -125,7 +158,7 @@ func TestAccRAMResourceShare_tags(t *testing.T) { CheckDestroy: testAccCheckResourceShareDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceShareTags1Config(rName, "key1", "value1"), + Config: testAccResourceShareConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareExists(resourceName, &resourceShare1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -138,7 +171,7 @@ func TestAccRAMResourceShare_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccResourceShareTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccResourceShareConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareExists(resourceName, &resourceShare2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -147,7 +180,7 @@ func TestAccRAMResourceShare_tags(t *testing.T) { ), }, { - Config: testAccResourceShareTags1Config(rName, "key2", "value2"), + Config: testAccResourceShareConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceShareExists(resourceName, &resourceShare3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -158,7 +191,30 @@ func TestAccRAMResourceShare_tags(t *testing.T) { }) } -func testAccCheckResourceShareExists(resourceName string, resourceShare *ram.ResourceShare) resource.TestCheckFunc { +func TestAccRAMResourceShare_disappears(t *testing.T) { + var resourceShare ram.ResourceShare + resourceName := "aws_ram_resource_share.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ram.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckResourceShareDestroy, + Steps: []resource.TestStep{ + { + Config: testAccResourceShareConfig_name(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckResourceShareExists(resourceName, &resourceShare), + acctest.CheckResourceDisappears(acctest.Provider, tfram.ResourceResourceShare(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckResourceShareExists(resourceName string, v *ram.ResourceShare) resource.TestCheckFunc { return func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).RAMConn @@ -171,26 +227,18 @@ func testAccCheckResourceShareExists(resourceName string, resourceShare *ram.Res return fmt.Errorf("No ID is set") } - request := &ram.GetResourceSharesInput{ - ResourceShareArns: []*string{aws.String(rs.Primary.ID)}, - ResourceOwner: aws.String(ram.ResourceOwnerSelf), - } + output, err := tfram.FindResourceShareOwnerSelfByARN(conn, rs.Primary.ID) - output, err := conn.GetResourceShares(request) if err != nil { return err } - if len(output.ResourceShares) == 0 { - return fmt.Errorf("No RAM resource share found") - } - - resourceShare = output.ResourceShares[0] - - if aws.StringValue(resourceShare.Status) != ram.ResourceShareStatusActive { + if aws.StringValue(output.Status) != ram.ResourceShareStatusActive { return fmt.Errorf("RAM resource share (%s) delet(ing|ed)", rs.Primary.ID) } + *v = *output + return nil } } @@ -203,28 +251,21 @@ func testAccCheckResourceShareDestroy(s *terraform.State) error { continue } - request := &ram.GetResourceSharesInput{ - ResourceShareArns: []*string{aws.String(rs.Primary.ID)}, - ResourceOwner: aws.String(ram.ResourceOwnerSelf), - } + resourceShare, err := tfram.FindResourceShareOwnerSelfByARN(conn, rs.Primary.ID) - output, err := conn.GetResourceShares(request) if err != nil { return err } - if len(output.ResourceShares) > 0 { - resourceShare := output.ResourceShares[0] - if aws.StringValue(resourceShare.Status) != ram.ResourceShareStatusDeleted { - return fmt.Errorf("RAM resource share (%s) still exists", rs.Primary.ID) - } + if aws.StringValue(resourceShare.Status) != ram.ResourceShareStatusDeleted { + return fmt.Errorf("RAM resource share (%s) still exists", rs.Primary.ID) } } return nil } -func testAccResourceShareAllowExternalPrincipalsConfig(rName string, allowExternalPrincipals bool) string { +func testAccResourceShareConfig_allowExternalPrincipals(rName string, allowExternalPrincipals bool) string { return fmt.Sprintf(` resource "aws_ram_resource_share" "test" { allow_external_principals = %[1]t @@ -233,7 +274,7 @@ resource "aws_ram_resource_share" "test" { `, allowExternalPrincipals, rName) } -func testAccResourceShareNameConfig(rName string) string { +func testAccResourceShareConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_ram_resource_share" "test" { name = %[1]q @@ -241,7 +282,7 @@ resource "aws_ram_resource_share" "test" { `, rName) } -func testAccResourceShareTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccResourceShareConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ram_resource_share" "test" { name = %[1]q @@ -253,7 +294,7 @@ resource "aws_ram_resource_share" "test" { `, rName, tagKey1, tagValue1) } -func testAccResourceShareTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccResourceShareConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_ram_resource_share" "test" { name = %[1]q @@ -265,3 +306,14 @@ resource "aws_ram_resource_share" "test" { } `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } + +func testAccResourceShareConfig_namePermission(rName string) string { + return fmt.Sprintf(` +data "aws_partition" "current" {} + +resource "aws_ram_resource_share" "test" { + name = %[1]q + permission_arns = ["arn:${data.aws_partition.current.partition}:ram::aws:permission/AWSRAMBlankEndEntityCertificateAPICSRPassthroughIssuanceCertificateAuthority"] +} +`, rName) +} diff --git a/internal/service/rds/certificate_data_source_test.go b/internal/service/rds/certificate_data_source_test.go index 592f93c6083..b64eebe5d79 100644 --- a/internal/service/rds/certificate_data_source_test.go +++ b/internal/service/rds/certificate_data_source_test.go @@ -20,7 +20,7 @@ func TestAccRDSCertificateDataSource_id(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccCertificateIDDataSourceConfig(), + Config: testAccCertificateDataSourceConfig_id(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "id", "data.aws_rds_certificate.latest", "id"), ), @@ -39,7 +39,7 @@ func TestAccRDSCertificateDataSource_latestValidTill(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccCertificateLatestValidTillDataSourceConfig(), + Config: testAccCertificateDataSourceConfig_latestValidTill(), Check: resource.ComposeTestCheckFunc( acctest.MatchResourceAttrRegionalARNNoAccount(dataSourceName, "arn", "rds", regexp.MustCompile(`cert:rds-ca-[0-9]{4}`)), resource.TestCheckResourceAttr(dataSourceName, "certificate_type", "CA"), @@ -71,7 +71,7 @@ func testAccCertificatePreCheck(t *testing.T) { } } -func testAccCertificateIDDataSourceConfig() string { +func testAccCertificateDataSourceConfig_id() string { return ` data "aws_rds_certificate" "latest" { latest_valid_till = true @@ -83,7 +83,7 @@ data "aws_rds_certificate" "test" { ` } -func testAccCertificateLatestValidTillDataSourceConfig() string { +func testAccCertificateDataSourceConfig_latestValidTill() string { return ` data "aws_rds_certificate" "test" { latest_valid_till = true diff --git a/internal/service/rds/cluster_activity_stream_test.go b/internal/service/rds/cluster_activity_stream_test.go index 38ba352ce6b..95f58bb1e3f 100644 --- a/internal/service/rds/cluster_activity_stream_test.go +++ b/internal/service/rds/cluster_activity_stream_test.go @@ -36,7 +36,7 @@ func TestAccRDSClusterActivityStream_basic(t *testing.T) { CheckDestroy: testAccCheckClusterActivityStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterActivityStreamConfig(clusterName, instanceName), + Config: testAccClusterActivityStreamConfig_basic(clusterName, instanceName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterActivityStreamExists(resourceName, &dbCluster), testAccCheckClusterActivityStreamAttributes(&dbCluster), @@ -73,7 +73,7 @@ func TestAccRDSClusterActivityStream_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterActivityStreamDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterActivityStreamConfig(clusterName, instanceName), + Config: testAccClusterActivityStreamConfig_basic(clusterName, instanceName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterActivityStreamExists(resourceName, &dbCluster), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceClusterActivityStream(), resourceName), @@ -195,7 +195,7 @@ resource "aws_rds_cluster_instance" "test" { `, clusterName, instanceName)) } -func testAccClusterActivityStreamConfig(clusterName, instanceName string) string { +func testAccClusterActivityStreamConfig_basic(clusterName, instanceName string) string { return acctest.ConfigCompose(testAccClusterActivityStreamConfigBase(clusterName, instanceName), ` resource "aws_rds_cluster_activity_stream" "test" { resource_arn = aws_rds_cluster.test.arn diff --git a/internal/service/rds/cluster_data_source_test.go b/internal/service/rds/cluster_data_source_test.go index 5ff6bc61479..03df6aa6410 100644 --- a/internal/service/rds/cluster_data_source_test.go +++ b/internal/service/rds/cluster_data_source_test.go @@ -21,7 +21,7 @@ func TestAccRDSClusterDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccClusterBasicDataSourceConfig(rName), + Config: testAccClusterDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "backtrack_window", resourceName, "backtrack_window"), @@ -39,7 +39,7 @@ func TestAccRDSClusterDataSource_basic(t *testing.T) { }) } -func testAccClusterBasicDataSourceConfig(rName string) string { +func testAccClusterDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %[1]q diff --git a/internal/service/rds/cluster_endpoint_test.go b/internal/service/rds/cluster_endpoint_test.go index e8f224455c9..d811fa73d44 100644 --- a/internal/service/rds/cluster_endpoint_test.go +++ b/internal/service/rds/cluster_endpoint_test.go @@ -35,7 +35,7 @@ func TestAccRDSClusterEndpoint_basic(t *testing.T) { CheckDestroy: testAccCheckClusterEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEndpointConfig(rInt), + Config: testAccClusterEndpointConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(readerResourceName, &customReaderEndpoint), testAccCheckClusterEndpointAttributes(&customReaderEndpoint), @@ -80,7 +80,7 @@ func TestAccRDSClusterEndpoint_tags(t *testing.T) { CheckDestroy: testAccCheckClusterEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEndpointTags1Config(rInt, "key1", "value1"), + Config: testAccClusterEndpointConfig_tags1(rInt, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(resourceName, &customReaderEndpoint), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -93,7 +93,7 @@ func TestAccRDSClusterEndpoint_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterEndpointTags2Config(rInt, "key1", "value1updated", "key2", "value2"), + Config: testAccClusterEndpointConfig_tags2(rInt, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(resourceName, &customReaderEndpoint), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -102,7 +102,7 @@ func TestAccRDSClusterEndpoint_tags(t *testing.T) { ), }, { - Config: testAccClusterEndpointTags1Config(rInt, "key2", "value2"), + Config: testAccClusterEndpointConfig_tags1(rInt, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterEndpointExists(resourceName, &customReaderEndpoint), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -255,7 +255,7 @@ resource "aws_rds_cluster_instance" "test2" { `, n)) } -func testAccClusterEndpointConfig(n int) string { +func testAccClusterEndpointConfig_basic(n int) string { return acctest.ConfigCompose( testAccClusterEndpointBaseConfig(n), fmt.Sprintf(` @@ -277,7 +277,7 @@ resource "aws_rds_cluster_endpoint" "default" { `, n)) } -func testAccClusterEndpointTags1Config(n int, tagKey1, tagValue1 string) string { +func testAccClusterEndpointConfig_tags1(n int, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( testAccClusterEndpointBaseConfig(n), fmt.Sprintf(` @@ -295,7 +295,7 @@ resource "aws_rds_cluster_endpoint" "reader" { `, n, tagKey1, tagValue1)) } -func testAccClusterEndpointTags2Config(n int, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccClusterEndpointConfig_tags2(n int, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( testAccClusterEndpointBaseConfig(n), fmt.Sprintf(` diff --git a/internal/service/rds/cluster_instance.go b/internal/service/rds/cluster_instance.go index 51aed6cdee7..d0b03a42ba5 100644 --- a/internal/service/rds/cluster_instance.go +++ b/internal/service/rds/cluster_instance.go @@ -331,7 +331,7 @@ func resourceClusterInstanceCreate(d *schema.ResourceData, meta interface{}) err stateConf := &resource.StateChangeConf{ Pending: resourceClusterInstanceCreateUpdatePendingStates, Target: []string{"available"}, - Refresh: resourceInstanceStateRefreshFunc(d.Id(), conn), + Refresh: resourceDBInstanceStateRefreshFunc(d.Id(), conn), Timeout: d.Timeout(schema.TimeoutCreate), MinTimeout: 10 * time.Second, Delay: 30 * time.Second, @@ -604,7 +604,7 @@ func resourceClusterInstanceUpdate(d *schema.ResourceData, meta interface{}) err stateConf := &resource.StateChangeConf{ Pending: resourceClusterInstanceCreateUpdatePendingStates, Target: []string{"available"}, - Refresh: resourceInstanceStateRefreshFunc(d.Id(), conn), + Refresh: resourceDBInstanceStateRefreshFunc(d.Id(), conn), Timeout: d.Timeout(schema.TimeoutUpdate), MinTimeout: 10 * time.Second, Delay: 30 * time.Second, // Wait 30 secs before starting diff --git a/internal/service/rds/cluster_instance_test.go b/internal/service/rds/cluster_instance_test.go index c9d533d69d4..976de55c7ea 100644 --- a/internal/service/rds/cluster_instance_test.go +++ b/internal/service/rds/cluster_instance_test.go @@ -33,7 +33,7 @@ func TestAccRDSClusterInstance_basic(t *testing.T) { CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceConfig(sdkacctest.RandInt()), + Config: testAccClusterInstanceConfig_basic(sdkacctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &v), testAccCheckClusterInstanceAttributes(&v), @@ -58,7 +58,7 @@ func TestAccRDSClusterInstance_basic(t *testing.T) { }, }, { - Config: testAccClusterInstanceModifiedConfig(sdkacctest.RandInt()), + Config: testAccClusterInstanceConfig_modified(sdkacctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &v), testAccCheckClusterInstanceAttributes(&v), @@ -85,7 +85,7 @@ func TestAccRDSClusterInstance_isAlreadyBeingDeleted(t *testing.T) { CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceConfig(rInt), + Config: testAccClusterInstanceConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &v), ), @@ -103,7 +103,7 @@ func TestAccRDSClusterInstance_isAlreadyBeingDeleted(t *testing.T) { t.Fatalf("error deleting Database Instance: %s", err) } }, - Config: testAccClusterInstanceConfig(rInt), + Config: testAccClusterInstanceConfig_basic(rInt), Destroy: true, }, }, @@ -234,7 +234,7 @@ func TestAccRDSClusterInstance_kmsKey(t *testing.T) { CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceKMSKeyConfig(sdkacctest.RandInt()), + Config: testAccClusterInstanceConfig_kmsKey(sdkacctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &v), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsKeyResourceName, "arn"), @@ -269,7 +269,7 @@ func TestAccRDSClusterInstance_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceConfig(sdkacctest.RandInt()), + Config: testAccClusterInstanceConfig_basic(sdkacctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceClusterInstance(), resourceName), @@ -296,7 +296,7 @@ func TestAccRDSClusterInstance_publiclyAccessible(t *testing.T) { CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceConfig_PubliclyAccessible(rName, true), + Config: testAccClusterInstanceConfig_publiclyAccessible(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "publicly_accessible", "true"), @@ -312,7 +312,7 @@ func TestAccRDSClusterInstance_publiclyAccessible(t *testing.T) { }, }, { - Config: testAccClusterInstanceConfig_PubliclyAccessible(rName, false), + Config: testAccClusterInstanceConfig_publiclyAccessible(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "publicly_accessible", "false"), @@ -338,7 +338,7 @@ func TestAccRDSClusterInstance_copyTagsToSnapshot(t *testing.T) { CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceConfig_CopyTagsToSnapshot(rNameSuffix, true), + Config: testAccClusterInstanceConfig_copyTagsToSnapshot(rNameSuffix, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_snapshot", "true"), @@ -354,7 +354,7 @@ func TestAccRDSClusterInstance_copyTagsToSnapshot(t *testing.T) { }, }, { - Config: testAccClusterInstanceConfig_CopyTagsToSnapshot(rNameSuffix, false), + Config: testAccClusterInstanceConfig_copyTagsToSnapshot(rNameSuffix, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_snapshot", "false"), @@ -380,7 +380,7 @@ func TestAccRDSClusterInstance_monitoringInterval(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceMonitoringIntervalConfig(rName, 30), + Config: testAccClusterInstanceConfig_monitoringInterval(rName, 30), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "30"), @@ -396,21 +396,21 @@ func TestAccRDSClusterInstance_monitoringInterval(t *testing.T) { }, }, { - Config: testAccClusterInstanceMonitoringIntervalConfig(rName, 60), + Config: testAccClusterInstanceConfig_monitoringInterval(rName, 60), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "60"), ), }, { - Config: testAccClusterInstanceMonitoringIntervalConfig(rName, 0), + Config: testAccClusterInstanceConfig_monitoringInterval(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "0"), ), }, { - Config: testAccClusterInstanceMonitoringIntervalConfig(rName, 30), + Config: testAccClusterInstanceConfig_monitoringInterval(rName, 30), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "30"), @@ -437,7 +437,7 @@ func TestAccRDSClusterInstance_MonitoringRoleARN_enabledToDisabled(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceMonitoringRoleARNConfig(rName), + Config: testAccClusterInstanceConfig_monitoringRoleARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttrPair(resourceName, "monitoring_role_arn", iamRoleResourceName, "arn"), @@ -453,7 +453,7 @@ func TestAccRDSClusterInstance_MonitoringRoleARN_enabledToDisabled(t *testing.T) }, }, { - Config: testAccClusterInstanceMonitoringIntervalConfig(rName, 0), + Config: testAccClusterInstanceConfig_monitoringInterval(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "0"), @@ -480,7 +480,7 @@ func TestAccRDSClusterInstance_MonitoringRoleARN_enabledToRemoved(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceMonitoringRoleARNConfig(rName), + Config: testAccClusterInstanceConfig_monitoringRoleARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttrPair(resourceName, "monitoring_role_arn", iamRoleResourceName, "arn"), @@ -496,7 +496,7 @@ func TestAccRDSClusterInstance_MonitoringRoleARN_enabledToRemoved(t *testing.T) }, }, { - Config: testAccClusterInstanceMonitoringRoleARNRemovedConfig(rName), + Config: testAccClusterInstanceConfig_monitoringRoleARNRemoved(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), ), @@ -522,7 +522,7 @@ func TestAccRDSClusterInstance_MonitoringRoleARN_removedToEnabled(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceMonitoringRoleARNRemovedConfig(rName), + Config: testAccClusterInstanceConfig_monitoringRoleARNRemoved(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), ), @@ -537,7 +537,7 @@ func TestAccRDSClusterInstance_MonitoringRoleARN_removedToEnabled(t *testing.T) }, }, { - Config: testAccClusterInstanceMonitoringRoleARNConfig(rName), + Config: testAccClusterInstanceConfig_monitoringRoleARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttrPair(resourceName, "monitoring_role_arn", iamRoleResourceName, "arn"), @@ -564,7 +564,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsEnabled_auroraMySQL1(t *testin CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsEnabledAuroraMySQL1Config(rName, engine), + Config: testAccClusterInstanceConfig_performanceInsightsEnabledAuroraMySQL1(rName, engine), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -601,7 +601,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsEnabled_auroraMySQL2(t *testin CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsEnabledAuroraMySQL2Config(rName, engine, engineVersion), + Config: testAccClusterInstanceConfig_performanceInsightsEnabledAuroraMySQL2(rName, engine, engineVersion), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -637,7 +637,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsEnabled_auroraPostgresql(t *te CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsEnabledAuroraPostgresqlConfig(rName, engine), + Config: testAccClusterInstanceConfig_performanceInsightsEnabledAuroraPostgresql(rName, engine), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -674,7 +674,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsKMSKeyID_auroraMySQL1(t *testi CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsKMSKeyIdAuroraMySQL1Config(rName, engine), + Config: testAccClusterInstanceConfig_performanceInsightsKMSKeyIDAuroraMySQL1(rName, engine), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -711,7 +711,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsKMSKeyIDAuroraMySQL1_defaultKe CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsEnabledAuroraMySQL1Config(rName, engine), + Config: testAccClusterInstanceConfig_performanceInsightsEnabledAuroraMySQL1(rName, engine), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -727,7 +727,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsKMSKeyIDAuroraMySQL1_defaultKe }, }, { - Config: testAccClusterInstancePerformanceInsightsKMSKeyIdAuroraMySQL1Config(rName, engine), + Config: testAccClusterInstanceConfig_performanceInsightsKMSKeyIDAuroraMySQL1(rName, engine), ExpectError: regexp.MustCompile(`InvalidParameterCombination: You .* change your Performance Insights KMS key`), }, }, @@ -753,7 +753,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsKMSKeyID_auroraMySQL2(t *testi CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsKMSKeyIdAuroraMySQL2Config(rName, engine, engineVersion), + Config: testAccClusterInstanceConfig_performanceInsightsKMSKeyIDAuroraMySQL2(rName, engine, engineVersion), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -791,7 +791,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsKMSKeyIDAuroraMySQL2_defaultKe CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsEnabledAuroraMySQL2Config(rName, engine, engineVersion), + Config: testAccClusterInstanceConfig_performanceInsightsEnabledAuroraMySQL2(rName, engine, engineVersion), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -807,7 +807,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsKMSKeyIDAuroraMySQL2_defaultKe }, }, { - Config: testAccClusterInstancePerformanceInsightsKMSKeyIdAuroraMySQL2Config(rName, engine, engineVersion), + Config: testAccClusterInstanceConfig_performanceInsightsKMSKeyIDAuroraMySQL2(rName, engine, engineVersion), ExpectError: regexp.MustCompile(`InvalidParameterCombination: You .* change your Performance Insights KMS key`), }, }, @@ -830,7 +830,7 @@ func TestAccRDSClusterInstance_performanceInsightsRetentionPeriod(t *testing.T) CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsRetentionPeriodConfig(rName, 731), + Config: testAccClusterInstanceConfig_performanceInsightsRetentionPeriod(rName, 731), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -847,7 +847,7 @@ func TestAccRDSClusterInstance_performanceInsightsRetentionPeriod(t *testing.T) }, }, { - Config: testAccClusterInstancePerformanceInsightsRetentionPeriodConfig(rName, 7), + Config: testAccClusterInstanceConfig_performanceInsightsRetentionPeriod(rName, 7), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -876,7 +876,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsKMSKeyID_auroraPostgresql(t *t CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsKMSKeyIdAuroraPostgresqlConfig(rName, engine), + Config: testAccClusterInstanceConfig_performanceInsightsKMSKeyIDAuroraPostgresql(rName, engine), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -913,7 +913,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsKMSKeyIDAuroraPostgresql_defau CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstancePerformanceInsightsEnabledAuroraPostgresqlConfig(rName, engine), + Config: testAccClusterInstanceConfig_performanceInsightsEnabledAuroraPostgresql(rName, engine), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -929,7 +929,7 @@ func TestAccRDSClusterInstance_PerformanceInsightsKMSKeyIDAuroraPostgresql_defau }, }, { - Config: testAccClusterInstancePerformanceInsightsKMSKeyIdAuroraPostgresqlConfig(rName, engine), + Config: testAccClusterInstanceConfig_performanceInsightsKMSKeyIDAuroraPostgresql(rName, engine), ExpectError: regexp.MustCompile(`InvalidParameterCombination: You .* change your Performance Insights KMS key`), }, }, @@ -953,7 +953,7 @@ func TestAccRDSClusterInstance_caCertificateIdentifier(t *testing.T) { CheckDestroy: testAccCheckClusterInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterInstanceConfig_CACertificateIdentifier(rName), + Config: testAccClusterInstanceConfig_caCertificateID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttrPair(resourceName, "ca_cert_identifier", dataSourceName, "id"), @@ -1092,7 +1092,7 @@ func testAccCheckClusterInstanceDestroy(s *terraform.State) error { } // Add some random to the name, to avoid collision -func testAccClusterInstanceConfig(n int) string { +func testAccClusterInstanceConfig_basic(n int) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` data "aws_rds_orderable_db_instance" "test" { engine = aws_rds_cluster.default.engine @@ -1138,7 +1138,7 @@ resource "aws_db_parameter_group" "bar" { `, n)) } -func testAccClusterInstanceModifiedConfig(n int) string { +func testAccClusterInstanceConfig_modified(n int) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_rds_cluster" "default" { cluster_identifier = "tf-aurora-cluster-test-%[1]d" @@ -1345,7 +1345,7 @@ resource "aws_db_subnet_group" "test" { `, n)) } -func testAccClusterInstanceKMSKeyConfig(n int) string { +func testAccClusterInstanceConfig_kmsKey(n int) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_kms_key" "foo" { description = "Terraform acc test %[1]d" @@ -1414,7 +1414,7 @@ resource "aws_db_parameter_group" "bar" { `, n)) } -func testAccClusterInstanceMonitoringIntervalConfig(rName string, monitoringInterval int) string { +func testAccClusterInstanceConfig_monitoringInterval(rName string, monitoringInterval int) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -1469,7 +1469,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName, monitoringInterval) } -func testAccClusterInstanceMonitoringRoleARNRemovedConfig(rName string) string { +func testAccClusterInstanceConfig_monitoringRoleARNRemoved(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %[1]q @@ -1493,7 +1493,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName) } -func testAccClusterInstanceMonitoringRoleARNConfig(rName string) string { +func testAccClusterInstanceConfig_monitoringRoleARN(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -1548,7 +1548,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName) } -func testAccClusterInstancePerformanceInsightsEnabledAuroraMySQL1Config(rName, engine string) string { +func testAccClusterInstanceConfig_performanceInsightsEnabledAuroraMySQL1(rName, engine string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %[1]q @@ -1576,7 +1576,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName, engine) } -func testAccClusterInstancePerformanceInsightsEnabledAuroraMySQL2Config(rName, engine, engineVersion string) string { +func testAccClusterInstanceConfig_performanceInsightsEnabledAuroraMySQL2(rName, engine, engineVersion string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %[1]q @@ -1606,7 +1606,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName, engine, engineVersion) } -func testAccClusterInstancePerformanceInsightsEnabledAuroraPostgresqlConfig(rName, engine string) string { +func testAccClusterInstanceConfig_performanceInsightsEnabledAuroraPostgresql(rName, engine string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %[1]q @@ -1634,7 +1634,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName, engine) } -func testAccClusterInstancePerformanceInsightsKMSKeyIdAuroraMySQL1Config(rName, engine string) string { +func testAccClusterInstanceConfig_performanceInsightsKMSKeyIDAuroraMySQL1(rName, engine string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -1667,7 +1667,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName, engine) } -func testAccClusterInstancePerformanceInsightsKMSKeyIdAuroraMySQL2Config(rName, engine, engineVersion string) string { +func testAccClusterInstanceConfig_performanceInsightsKMSKeyIDAuroraMySQL2(rName, engine, engineVersion string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -1702,7 +1702,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName, engine, engineVersion) } -func testAccClusterInstancePerformanceInsightsKMSKeyIdAuroraPostgresqlConfig(rName, engine string) string { +func testAccClusterInstanceConfig_performanceInsightsKMSKeyIDAuroraPostgresql(rName, engine string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -1735,7 +1735,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName, engine) } -func testAccClusterInstancePerformanceInsightsRetentionPeriodConfig(rName string, performanceInsightsRetentionPeriod int) string { +func testAccClusterInstanceConfig_performanceInsightsRetentionPeriod(rName string, performanceInsightsRetentionPeriod int) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %[1]q @@ -1764,7 +1764,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName, performanceInsightsRetentionPeriod) } -func testAccClusterInstanceConfig_PubliclyAccessible(rName string, publiclyAccessible bool) string { +func testAccClusterInstanceConfig_publiclyAccessible(rName string, publiclyAccessible bool) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %[1]q @@ -1789,7 +1789,7 @@ resource "aws_rds_cluster_instance" "test" { `, rName, publiclyAccessible) } -func testAccClusterInstanceConfig_CopyTagsToSnapshot(n int, f bool) string { +func testAccClusterInstanceConfig_copyTagsToSnapshot(n int, f bool) string { return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` resource "aws_rds_cluster" "default" { cluster_identifier = "tf-aurora-cluster-test-%[1]d" @@ -1820,7 +1820,7 @@ resource "aws_rds_cluster_instance" "cluster_instances" { `, n, f)) } -func testAccClusterInstanceConfig_CACertificateIdentifier(rName string) string { +func testAccClusterInstanceConfig_caCertificateID(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %[1]q diff --git a/internal/service/rds/cluster_parameter_group_test.go b/internal/service/rds/cluster_parameter_group_test.go index 7aa16f9715e..ba5f6006756 100644 --- a/internal/service/rds/cluster_parameter_group_test.go +++ b/internal/service/rds/cluster_parameter_group_test.go @@ -29,7 +29,7 @@ func TestAccRDSClusterParameterGroup_basic(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupConfig(parameterGroupName), + Config: testAccClusterParameterGroupConfig_basic(parameterGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -58,7 +58,7 @@ func TestAccRDSClusterParameterGroup_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterParameterGroupAddParametersConfig(parameterGroupName), + Config: testAccClusterParameterGroupConfig_addParameters(parameterGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -89,7 +89,7 @@ func TestAccRDSClusterParameterGroup_basic(t *testing.T) { ), }, { - Config: testAccClusterParameterGroupConfig(parameterGroupName), + Config: testAccClusterParameterGroupConfig_basic(parameterGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -126,7 +126,7 @@ func TestAccRDSClusterParameterGroup_withApplyMethod(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupWithApplyMethodConfig(parameterGroupName), + Config: testAccClusterParameterGroupConfig_applyMethod(parameterGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -166,7 +166,7 @@ func TestAccRDSClusterParameterGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupNamePrefixConfig("tf-acc-test-prefix-"), + Config: testAccClusterParameterGroupConfig_namePrefix("tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), @@ -193,7 +193,7 @@ func TestAccRDSClusterParameterGroup_NamePrefix_parameter(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupNamePrefixParameterConfig("tf-acc-test-prefix-"), + Config: testAccClusterParameterGroupConfig_namePrefixParameter("tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), @@ -275,7 +275,7 @@ func TestAccRDSClusterParameterGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupConfig(parameterGroupName), + Config: testAccClusterParameterGroupConfig_basic(parameterGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccClusterParameterGroupDisappears(&v), @@ -298,7 +298,7 @@ func TestAccRDSClusterParameterGroup_only(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupOnlyConfig(parameterGroupName), + Config: testAccClusterParameterGroupConfig_only(parameterGroupName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, parameterGroupName), @@ -331,7 +331,7 @@ func TestAccRDSClusterParameterGroup_updateParameters(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupUpdateParametersInitialConfig(groupName), + Config: testAccClusterParameterGroupConfig_updateParametersInitial(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, groupName), @@ -357,7 +357,7 @@ func TestAccRDSClusterParameterGroup_updateParameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterParameterGroupUpdateParametersUpdatedConfig(groupName), + Config: testAccClusterParameterGroupConfig_updateParametersUpdated(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, groupName), @@ -391,7 +391,7 @@ func TestAccRDSClusterParameterGroup_caseParameters(t *testing.T) { CheckDestroy: testAccCheckClusterParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterParameterGroupUpperCaseConfig(rName), + Config: testAccClusterParameterGroupConfig_upperCase(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterParameterGroupExists(resourceName, &v), testAccCheckClusterParameterGroupAttributes(&v, rName), @@ -409,7 +409,7 @@ func TestAccRDSClusterParameterGroup_caseParameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccClusterParameterGroupUpperCaseConfig(rName), + Config: testAccClusterParameterGroupConfig_upperCase(rName), }, }, }) @@ -558,7 +558,7 @@ func testAccCheckClusterParameterGroupExists(n string, v *rds.DBClusterParameter } } -func testAccClusterParameterGroupConfig(name string) string { +func testAccClusterParameterGroupConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_rds_cluster_parameter_group" "test" { name = "%s" @@ -587,7 +587,7 @@ resource "aws_rds_cluster_parameter_group" "test" { `, name) } -func testAccClusterParameterGroupWithApplyMethodConfig(name string) string { +func testAccClusterParameterGroupConfig_applyMethod(name string) string { return fmt.Sprintf(` resource "aws_rds_cluster_parameter_group" "test" { name = "%s" @@ -612,7 +612,7 @@ resource "aws_rds_cluster_parameter_group" "test" { `, name) } -func testAccClusterParameterGroupAddParametersConfig(name string) string { +func testAccClusterParameterGroupConfig_addParameters(name string) string { return fmt.Sprintf(` resource "aws_rds_cluster_parameter_group" "test" { name = "%s" @@ -652,7 +652,7 @@ resource "aws_rds_cluster_parameter_group" "test" { `, name) } -func testAccClusterParameterGroupOnlyConfig(name string) string { +func testAccClusterParameterGroupConfig_only(name string) string { return fmt.Sprintf(` resource "aws_rds_cluster_parameter_group" "test" { name = "%s" @@ -661,7 +661,7 @@ resource "aws_rds_cluster_parameter_group" "test" { `, name) } -func testAccClusterParameterGroupUpdateParametersInitialConfig(name string) string { +func testAccClusterParameterGroupConfig_updateParametersInitial(name string) string { return fmt.Sprintf(` resource "aws_rds_cluster_parameter_group" "test" { name = "%s" @@ -685,7 +685,7 @@ resource "aws_rds_cluster_parameter_group" "test" { `, name) } -func testAccClusterParameterGroupUpdateParametersUpdatedConfig(name string) string { +func testAccClusterParameterGroupConfig_updateParametersUpdated(name string) string { return fmt.Sprintf(` resource "aws_rds_cluster_parameter_group" "test" { name = "%s" @@ -709,7 +709,7 @@ resource "aws_rds_cluster_parameter_group" "test" { `, name) } -func testAccClusterParameterGroupUpperCaseConfig(rName string) string { +func testAccClusterParameterGroupConfig_upperCase(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster_parameter_group" "test" { name = "%s" @@ -723,7 +723,7 @@ resource "aws_rds_cluster_parameter_group" "test" { `, rName) } -func testAccClusterParameterGroupNamePrefixConfig(namePrefix string) string { +func testAccClusterParameterGroupConfig_namePrefix(namePrefix string) string { return fmt.Sprintf(` resource "aws_rds_cluster_parameter_group" "test" { name_prefix = %[1]q @@ -732,7 +732,7 @@ resource "aws_rds_cluster_parameter_group" "test" { `, namePrefix) } -func testAccClusterParameterGroupNamePrefixParameterConfig(namePrefix string) string { +func testAccClusterParameterGroupConfig_namePrefixParameter(namePrefix string) string { return fmt.Sprintf(` resource "aws_rds_cluster_parameter_group" "test" { name_prefix = %[1]q diff --git a/internal/service/rds/cluster_role_association.go b/internal/service/rds/cluster_role_association.go index c98e3b1de48..fc1202a680f 100644 --- a/internal/service/rds/cluster_role_association.go +++ b/internal/service/rds/cluster_role_association.go @@ -7,6 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -55,9 +56,20 @@ func resourceClusterRoleAssociationCreate(d *schema.ResourceData, meta interface RoleArn: aws.String(roleARN), } - log.Printf("[DEBUG] Creating RDS DB Cluster IAM Role Association: %s", input) - _, err := conn.AddRoleToDBCluster(input) - + err := resource.Retry(propagationTimeout, func() *resource.RetryError { + var err error + _, err = conn.AddRoleToDBCluster(input) + if err != nil { + if tfawserr.ErrMessageContains(err, "InvalidParameterValue", "IAM role ARN value is invalid or does not include the required permissions") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if tfresource.TimedOut(err) { + _, err = conn.AddRoleToDBCluster(input) + } if err != nil { return fmt.Errorf("error creating RDS DB Cluster (%s) IAM Role (%s) Association: %w", dbClusterID, roleARN, err) } diff --git a/internal/service/rds/cluster_role_association_test.go b/internal/service/rds/cluster_role_association_test.go index 7dbacd674d9..25a7ef2aeb0 100644 --- a/internal/service/rds/cluster_role_association_test.go +++ b/internal/service/rds/cluster_role_association_test.go @@ -29,7 +29,7 @@ func TestAccRDSClusterRoleAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckClusterRoleAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterRoleAssociationConfig(rName), + Config: testAccClusterRoleAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterRoleAssociationExists(resourceName, &dbClusterRole), resource.TestCheckResourceAttrPair(resourceName, "db_cluster_identifier", dbClusterResourceName, "id"), @@ -58,7 +58,7 @@ func TestAccRDSClusterRoleAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterRoleAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterRoleAssociationConfig(rName), + Config: testAccClusterRoleAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterRoleAssociationExists(resourceName, &dbClusterRole), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceClusterRoleAssociation(), resourceName), @@ -82,7 +82,7 @@ func TestAccRDSClusterRoleAssociation_Disappears_cluster(t *testing.T) { CheckDestroy: testAccCheckClusterRoleAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterRoleAssociationConfig(rName), + Config: testAccClusterRoleAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterRoleAssociationExists(resourceName, &dbClusterRole), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceCluster(), clusterResourceName), @@ -106,7 +106,7 @@ func TestAccRDSClusterRoleAssociation_Disappears_role(t *testing.T) { CheckDestroy: testAccCheckClusterRoleAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterRoleAssociationConfig(rName), + Config: testAccClusterRoleAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterRoleAssociationExists(resourceName, &dbClusterRole), acctest.CheckResourceDisappears(acctest.Provider, iam.ResourceRole(), roleResourceName), @@ -175,23 +175,14 @@ func testAccCheckClusterRoleAssociationDestroy(s *terraform.State) error { return nil } -func testAccClusterRoleAssociationConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` -data "aws_iam_policy_document" "rds_assume_role_policy" { - statement { - actions = ["sts:AssumeRole"] - effect = "Allow" - - principals { - identifiers = ["rds.amazonaws.com"] - type = "Service" - } - } -} - -resource "aws_iam_role" "test" { - assume_role_policy = data.aws_iam_policy_document.rds_assume_role_policy.json - name = %[1]q +func testAccClusterRoleAssociationConfig_basic(rName string) string { + return acctest.ConfigCompose( + acctest.ConfigAvailableAZsNoOptIn(), + fmt.Sprintf(` +resource "aws_rds_cluster_role_association" "test" { + db_cluster_identifier = aws_rds_cluster.test.id + feature_name = "s3Import" + role_arn = aws_iam_role.test.arn } resource "aws_rds_cluster" "test" { @@ -206,10 +197,24 @@ resource "aws_rds_cluster" "test" { skip_final_snapshot = true } -resource "aws_rds_cluster_role_association" "test" { - db_cluster_identifier = aws_rds_cluster.test.id - feature_name = "s3Import" - role_arn = aws_iam_role.test.arn +resource "aws_iam_role" "test" { + assume_role_policy = data.aws_iam_policy_document.rds_assume_role_policy.json + name = %[1]q + + # ensure IAM role is created just before association to exercise IAM eventual consistency + depends_on = [aws_rds_cluster.test] +} + +data "aws_iam_policy_document" "rds_assume_role_policy" { + statement { + actions = ["sts:AssumeRole"] + effect = "Allow" + + principals { + identifiers = ["rds.amazonaws.com"] + type = "Service" + } + } } `, rName)) } diff --git a/internal/service/rds/cluster_snapshot_data_source.go b/internal/service/rds/cluster_snapshot_data_source.go index 3b7b0a580dd..7d187aa885f 100644 --- a/internal/service/rds/cluster_snapshot_data_source.go +++ b/internal/service/rds/cluster_snapshot_data_source.go @@ -152,7 +152,7 @@ func dataSourceClusterSnapshotRead(d *schema.ResourceData, meta interface{}) err recent := d.Get("most_recent").(bool) log.Printf("[DEBUG] aws_db_cluster_snapshot - multiple results found and `most_recent` is set to: %t", recent) if recent { - snapshot = mostRecentDbClusterSnapshot(resp.DBClusterSnapshots) + snapshot = mostRecentClusterSnapshot(resp.DBClusterSnapshots) } else { return errors.New("Your query returned more than one result. Please try a more specific search criteria.") } @@ -211,7 +211,7 @@ func (a rdsClusterSnapshotSort) Less(i, j int) bool { return (*a[i].SnapshotCreateTime).Before(*a[j].SnapshotCreateTime) } -func mostRecentDbClusterSnapshot(snapshots []*rds.DBClusterSnapshot) *rds.DBClusterSnapshot { +func mostRecentClusterSnapshot(snapshots []*rds.DBClusterSnapshot) *rds.DBClusterSnapshot { sortedSnapshots := snapshots sort.Sort(rdsClusterSnapshotSort(sortedSnapshots)) return sortedSnapshots[len(sortedSnapshots)-1] diff --git a/internal/service/rds/cluster_snapshot_data_source_test.go b/internal/service/rds/cluster_snapshot_data_source_test.go index 61286069a1f..505d0e50d8c 100644 --- a/internal/service/rds/cluster_snapshot_data_source_test.go +++ b/internal/service/rds/cluster_snapshot_data_source_test.go @@ -22,7 +22,7 @@ func TestAccRDSClusterSnapshotDataSource_dbClusterSnapshotIdentifier(t *testing. ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckClusterSnapshotDataSourceConfig_DbClusterSnapshotIdentifier(rName), + Config: testAccClusterSnapshotDataSourceConfig_clusterSnapshotIdentifier(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterSnapshotExistsDataSource(dataSourceName), resource.TestCheckResourceAttrPair(dataSourceName, "allocated_storage", resourceName, "allocated_storage"), @@ -59,7 +59,7 @@ func TestAccRDSClusterSnapshotDataSource_dbClusterIdentifier(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckClusterSnapshotDataSourceConfig_DbClusterIdentifier(rName), + Config: testAccClusterSnapshotDataSourceConfig_clusterIdentifier(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterSnapshotExistsDataSource(dataSourceName), resource.TestCheckResourceAttrPair(dataSourceName, "allocated_storage", resourceName, "allocated_storage"), @@ -96,7 +96,7 @@ func TestAccRDSClusterSnapshotDataSource_mostRecent(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckClusterSnapshotDataSourceConfig_MostRecent(rName), + Config: testAccClusterSnapshotDataSourceConfig_mostRecent(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterSnapshotExistsDataSource(dataSourceName), resource.TestCheckResourceAttrPair(dataSourceName, "db_cluster_snapshot_arn", resourceName, "db_cluster_snapshot_arn"), @@ -121,7 +121,7 @@ func testAccCheckClusterSnapshotExistsDataSource(dataSourceName string) resource } } -func testAccCheckClusterSnapshotDataSourceConfig_DbClusterSnapshotIdentifier(rName string) string { +func testAccClusterSnapshotDataSourceConfig_clusterSnapshotIdentifier(rName string) string { return acctest.ConfigAvailableAZsNoOptIn() + fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "192.168.0.0/16" @@ -171,7 +171,7 @@ data "aws_db_cluster_snapshot" "test" { `, rName) } -func testAccCheckClusterSnapshotDataSourceConfig_DbClusterIdentifier(rName string) string { +func testAccClusterSnapshotDataSourceConfig_clusterIdentifier(rName string) string { return acctest.ConfigAvailableAZsNoOptIn() + fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "192.168.0.0/16" @@ -221,7 +221,7 @@ data "aws_db_cluster_snapshot" "test" { `, rName) } -func testAccCheckClusterSnapshotDataSourceConfig_MostRecent(rName string) string { +func testAccClusterSnapshotDataSourceConfig_mostRecent(rName string) string { return acctest.ConfigAvailableAZsNoOptIn() + fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "192.168.0.0/16" diff --git a/internal/service/rds/cluster_snapshot_test.go b/internal/service/rds/cluster_snapshot_test.go index c0ef4483d9b..41262d08540 100644 --- a/internal/service/rds/cluster_snapshot_test.go +++ b/internal/service/rds/cluster_snapshot_test.go @@ -24,12 +24,12 @@ func TestAccRDSClusterSnapshot_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, rds.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDbClusterSnapshotDestroy, + CheckDestroy: testAccCheckClusterSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterSnapshotConfig(rName), + Config: testAccClusterSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDbClusterSnapshotExists(resourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(resourceName, &dbClusterSnapshot), resource.TestCheckResourceAttrSet(resourceName, "allocated_storage"), resource.TestCheckResourceAttrSet(resourceName, "availability_zones.#"), acctest.MatchResourceAttrRegionalARN(resourceName, "db_cluster_snapshot_arn", "rds", regexp.MustCompile(fmt.Sprintf("cluster-snapshot:%s$", rName))), @@ -64,12 +64,12 @@ func TestAccRDSClusterSnapshot_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, rds.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDbClusterSnapshotDestroy, + CheckDestroy: testAccCheckClusterSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterSnapshotTags1Config(rName, "key1", "value1"), + Config: testAccClusterSnapshotConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckDbClusterSnapshotExists(resourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(resourceName, &dbClusterSnapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), @@ -87,18 +87,18 @@ func TestAccRDSClusterSnapshot_tags(t *testing.T) { }, }, { - Config: testAccClusterSnapshotTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccClusterSnapshotConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckDbClusterSnapshotExists(resourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(resourceName, &dbClusterSnapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { - Config: testAccClusterSnapshotTags1Config(rName, "key2", "value2"), + Config: testAccClusterSnapshotConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckDbClusterSnapshotExists(resourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(resourceName, &dbClusterSnapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), @@ -107,7 +107,7 @@ func TestAccRDSClusterSnapshot_tags(t *testing.T) { }) } -func testAccCheckDbClusterSnapshotDestroy(s *terraform.State) error { +func testAccCheckClusterSnapshotDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).RDSConn for _, rs := range s.RootModule().Resources { @@ -135,7 +135,7 @@ func testAccCheckDbClusterSnapshotDestroy(s *terraform.State) error { return nil } -func testAccCheckDbClusterSnapshotExists(resourceName string, dbClusterSnapshot *rds.DBClusterSnapshot) resource.TestCheckFunc { +func testAccCheckClusterSnapshotExists(resourceName string, dbClusterSnapshot *rds.DBClusterSnapshot) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { @@ -167,7 +167,7 @@ func testAccCheckDbClusterSnapshotExists(resourceName string, dbClusterSnapshot } } -func testAccClusterSnapshotConfig(rName string) string { +func testAccClusterSnapshotConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -218,7 +218,7 @@ resource "aws_db_cluster_snapshot" "test" { `, rName) } -func testAccClusterSnapshotTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccClusterSnapshotConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -272,7 +272,7 @@ resource "aws_db_cluster_snapshot" "test" { `, rName, tagKey1, tagValue1) } -func testAccClusterSnapshotTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccClusterSnapshotConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" diff --git a/internal/service/rds/cluster_test.go b/internal/service/rds/cluster_test.go index 80178cc596a..bba9366255a 100644 --- a/internal/service/rds/cluster_test.go +++ b/internal/service/rds/cluster_test.go @@ -21,7 +21,6 @@ import ( func init() { acctest.RegisterServiceErrorCheckFunc(rds.EndpointsID, testAccErrorCheckSkip) - } func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { @@ -46,7 +45,7 @@ func TestAccRDSCluster_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(clusterName), + Config: testAccClusterConfig_basic(clusterName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("cluster:%s", clusterName)), @@ -105,7 +104,7 @@ func TestAccRDSCluster_allowMajorVersionUpgrade(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_AllowMajorVersionUpgrade(rName, true, engine, engineVersion1), + Config: testAccClusterConfig_allowMajorVersionUpgrade(rName, true, engine, engineVersion1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "allow_major_version_upgrade", "true"), @@ -128,7 +127,7 @@ func TestAccRDSCluster_allowMajorVersionUpgrade(t *testing.T) { }, }, { - Config: testAccClusterConfig_AllowMajorVersionUpgrade(rName, true, engine, engineVersion2), + Config: testAccClusterConfig_allowMajorVersionUpgrade(rName, true, engine, engineVersion2), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster2), resource.TestCheckResourceAttr(resourceName, "allow_major_version_upgrade", "true"), @@ -162,7 +161,7 @@ func TestAccRDSCluster_allowMajorVersionUpgradeWithCustomParametersApplyImm(t *t CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_AllowMajorVersionUpgradeWithCustomParameters(rName, true, engine, engineVersion1, true), + Config: testAccClusterConfig_allowMajorVersionUpgradeCustomParameters(rName, true, engine, engineVersion1, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "allow_major_version_upgrade", "true"), @@ -171,7 +170,7 @@ func TestAccRDSCluster_allowMajorVersionUpgradeWithCustomParametersApplyImm(t *t ), }, { - Config: testAccClusterConfig_AllowMajorVersionUpgradeWithCustomParameters(rName, true, engine, engineVersion2, true), + Config: testAccClusterConfig_allowMajorVersionUpgradeCustomParameters(rName, true, engine, engineVersion2, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster2), resource.TestCheckResourceAttr(resourceName, "allow_major_version_upgrade", "true"), @@ -205,7 +204,7 @@ func TestAccRDSCluster_allowMajorVersionUpgradeWithCustomParameters(t *testing.T CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_AllowMajorVersionUpgradeWithCustomParameters(rName, true, engine, engineVersion1, false), + Config: testAccClusterConfig_allowMajorVersionUpgradeCustomParameters(rName, true, engine, engineVersion1, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "allow_major_version_upgrade", "true"), @@ -228,7 +227,7 @@ func TestAccRDSCluster_allowMajorVersionUpgradeWithCustomParameters(t *testing.T }, }, { - Config: testAccClusterConfig_AllowMajorVersionUpgradeWithCustomParameters(rName, true, engine, engineVersion2, false), + Config: testAccClusterConfig_allowMajorVersionUpgradeCustomParameters(rName, true, engine, engineVersion2, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster2), resource.TestCheckResourceAttr(resourceName, "allow_major_version_upgrade", "true"), @@ -261,7 +260,7 @@ func TestAccRDSCluster_onlyMajorVersion(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_MajorVersionOnly(rName, false, engine, engineVersion1), + Config: testAccClusterConfig_majorVersionOnly(rName, false, engine, engineVersion1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "engine", engine), @@ -299,7 +298,7 @@ func TestAccRDSCluster_availabilityZones(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_AvailabilityZones(rName), + Config: testAccClusterConfig_availabilityZones(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), ), @@ -320,7 +319,7 @@ func TestAccRDSCluster_storageType(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_StorageType(rName), + Config: testAccClusterConfig_storageType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "storage_type", "io1"), @@ -342,7 +341,7 @@ func TestAccRDSCluster_allocatedStorage(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_AllocatedStorage(rName), + Config: testAccClusterConfig_allocatedStorage(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "allocated_storage", "100"), @@ -364,7 +363,7 @@ func TestAccRDSCluster_iops(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Iops(rName), + Config: testAccClusterConfig_iops(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "iops", "1000"), @@ -386,7 +385,7 @@ func TestAccRDSCluster_dbClusterInstanceClass(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_DbClusterInstanceClass(rName), + Config: testAccClusterConfig_dbClusterInstanceClass(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "db_cluster_instance_class", "db.r6gd.xlarge"), @@ -407,14 +406,14 @@ func TestAccRDSCluster_backtrackWindow(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_BacktrackWindow(43200), + Config: testAccClusterConfig_backtrackWindow(43200), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "backtrack_window", "43200"), ), }, { - Config: testAccClusterConfig_BacktrackWindow(86400), + Config: testAccClusterConfig_backtrackWindow(86400), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "backtrack_window", "86400"), @@ -435,7 +434,7 @@ func TestAccRDSCluster_clusterIdentifierPrefix(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_ClusterIdentifierPrefix("tf-test-"), + Config: testAccClusterConfig_clusterIDPrefix("tf-test-"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestMatchResourceAttr( @@ -458,7 +457,7 @@ func TestAccRDSCluster_dbSubnetGroupName(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SubnetGroupName(rName), + Config: testAccClusterConfig_subnetGroupName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), ), @@ -591,7 +590,7 @@ func TestAccRDSCluster_takeFinalSnapshot(t *testing.T) { CheckDestroy: testAccCheckClusterSnapshot(rInt), Steps: []resource.TestStep{ { - Config: testAccClusterWithFinalSnapshotConfig(rInt), + Config: testAccClusterConfig_finalSnapshot(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), ), @@ -611,7 +610,7 @@ func TestAccRDSCluster_missingUserNameCausesError(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterWithoutUserNameAndPasswordConfig(sdkacctest.RandInt()), + Config: testAccClusterConfig_withoutUserNameAndPassword(sdkacctest.RandInt()), ExpectError: regexp.MustCompile(`InvalidParameterValue: The parameter MasterUsername must be provided`), }, }, @@ -630,7 +629,7 @@ func TestAccRDSCluster_tags(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterTags1Config(rName, "key1", "value1"), + Config: testAccClusterConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -638,7 +637,7 @@ func TestAccRDSCluster_tags(t *testing.T) { ), }, { - Config: testAccClusterTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccClusterConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -647,7 +646,7 @@ func TestAccRDSCluster_tags(t *testing.T) { ), }, { - Config: testAccClusterTags1Config(rName, "key2", "value2"), + Config: testAccClusterConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -670,7 +669,7 @@ func TestAccRDSCluster_EnabledCloudWatchLogsExports_mySQL(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEnabledCloudWatchLogsExports1Config(rName, "audit"), + Config: testAccClusterConfig_enabledCloudWatchLogsExports1(rName, "audit"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "1"), @@ -678,7 +677,7 @@ func TestAccRDSCluster_EnabledCloudWatchLogsExports_mySQL(t *testing.T) { ), }, { - Config: testAccClusterEnabledCloudWatchLogsExports2Config(rName, "slowquery", "error"), + Config: testAccClusterConfig_enabledCloudWatchLogsExports2(rName, "slowquery", "error"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster2), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "2"), @@ -687,7 +686,7 @@ func TestAccRDSCluster_EnabledCloudWatchLogsExports_mySQL(t *testing.T) { ), }, { - Config: testAccClusterEnabledCloudWatchLogsExports1Config(rName, "error"), + Config: testAccClusterConfig_enabledCloudWatchLogsExports1(rName, "error"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster3), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "1"), @@ -710,7 +709,7 @@ func TestAccRDSCluster_EnabledCloudWatchLogsExports_postgresql(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterEnabledCloudWatchLogsExportsPostgres1Config(rName, "postgresql"), + Config: testAccClusterConfig_enabledCloudWatchLogsExportsPostgreSQL1(rName, "postgresql"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "1"), @@ -733,13 +732,13 @@ func TestAccRDSCluster_updateIAMRoles(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterIncludingIAMRolesConfig(ri), + Config: testAccClusterConfig_includingIAMRoles(ri), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), ), }, { - Config: testAccClusterAddIAMRolesConfig(ri), + Config: testAccClusterConfig_addIAMRoles(ri), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -747,7 +746,7 @@ func TestAccRDSCluster_updateIAMRoles(t *testing.T) { ), }, { - Config: testAccClusterRemoveIAMRolesConfig(ri), + Config: testAccClusterConfig_removeIAMRoles(ri), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -816,21 +815,21 @@ func TestAccRDSCluster_copyTagsToSnapshot(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterWithCopyTagsToSnapshotConfig(rInt, true), + Config: testAccClusterConfig_copyTagsToSnapshot(rInt, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_snapshot", "true"), ), }, { - Config: testAccClusterWithCopyTagsToSnapshotConfig(rInt, false), + Config: testAccClusterConfig_copyTagsToSnapshot(rInt, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_snapshot", "false"), ), }, { - Config: testAccClusterWithCopyTagsToSnapshotConfig(rInt, true), + Config: testAccClusterConfig_copyTagsToSnapshot(rInt, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "copy_tags_to_snapshot", "true"), @@ -865,7 +864,7 @@ func TestAccRDSCluster_ReplicationSourceIdentifier_kmsKeyID(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckClusterDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccClusterReplicationSourceIdentifierKMSKeyIDConfig(rName), + Config: testAccClusterConfig_replicationSourceIDKMSKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExistsWithProvider(resourceName, &primaryCluster, acctest.RegionProviderFunc(acctest.Region(), &providers)), testAccCheckClusterExistsWithProvider(resourceName2, &replicaCluster, acctest.RegionProviderFunc(acctest.AlternateRegion(), &providers)), @@ -948,14 +947,14 @@ func TestAccRDSCluster_deletionProtection(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_DeletionProtection(rName, true), + Config: testAccClusterConfig_deletionProtection(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "true"), ), }, { - Config: testAccClusterConfig_DeletionProtection(rName, false), + Config: testAccClusterConfig_deletionProtection(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "false"), @@ -982,7 +981,7 @@ func TestAccRDSCluster_engineMode(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EngineMode(rName, "serverless"), + Config: testAccClusterConfig_engineMode(rName, "serverless"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "engine_mode", "serverless"), @@ -991,7 +990,7 @@ func TestAccRDSCluster_engineMode(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineMode(rName, "provisioned"), + Config: testAccClusterConfig_engineMode(rName, "provisioned"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster2), testAccCheckClusterRecreated(&dbCluster1, &dbCluster2), @@ -1017,7 +1016,7 @@ func TestAccRDSCluster_EngineMode_global(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EngineMode_Global(rName), + Config: testAccClusterConfig_EngineMode_global(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "engine_mode", "global"), @@ -1040,7 +1039,7 @@ func TestAccRDSCluster_EngineMode_multiMaster(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EngineMode_Multimaster(rName), + Config: testAccClusterConfig_EngineMode_multimaster(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "engine_mode", "multimaster"), @@ -1063,7 +1062,7 @@ func TestAccRDSCluster_EngineMode_parallelQuery(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EngineMode(rName, "parallelquery"), + Config: testAccClusterConfig_engineMode(rName, "parallelquery"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "engine_mode", "parallelquery"), @@ -1090,7 +1089,7 @@ func TestAccRDSCluster_engineVersion(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EngineVersion(false, rInt), + Config: testAccClusterConfig_engineVersion(false, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "engine", "aurora-postgresql"), @@ -1098,7 +1097,7 @@ func TestAccRDSCluster_engineVersion(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersion(true, rInt), + Config: testAccClusterConfig_engineVersion(true, rInt), ExpectError: regexp.MustCompile(`Cannot modify engine version without a healthy primary instance in DB cluster`), }, }, @@ -1123,7 +1122,7 @@ func TestAccRDSCluster_engineVersionWithPrimaryInstance(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EngineVersionWithPrimaryInstance(false, rInt), + Config: testAccClusterConfig_engineVersionPrimaryInstance(false, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttrPair(resourceName, "engine", dataSourceName, "engine"), @@ -1131,7 +1130,7 @@ func TestAccRDSCluster_engineVersionWithPrimaryInstance(t *testing.T) { ), }, { - Config: testAccClusterConfig_EngineVersionWithPrimaryInstance(true, rInt), + Config: testAccClusterConfig_engineVersionPrimaryInstance(true, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttrPair(resourceName, "engine", dataSourceNameUpgrade, "engine"), @@ -1156,7 +1155,7 @@ func TestAccRDSCluster_GlobalClusterIdentifierEngineMode_global(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_GlobalClusterIdentifier_EngineMode_Global(rName), + Config: testAccClusterConfig_GlobalClusterID_EngineMode_global(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttrPair(resourceName, "global_cluster_identifier", globalClusterResourceName, "id"), @@ -1179,14 +1178,14 @@ func TestAccRDSCluster_GlobalClusterIdentifierEngineModeGlobal_add(t *testing.T) CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EngineMode_Global(rName), + Config: testAccClusterConfig_EngineMode_global(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "global_cluster_identifier", ""), ), }, { - Config: testAccClusterConfig_GlobalClusterIdentifier_EngineMode_Global(rName), + Config: testAccClusterConfig_GlobalClusterID_EngineMode_global(rName), ExpectError: regexp.MustCompile(`Existing RDS Clusters cannot be added to an existing RDS Global Cluster`), }, }, @@ -1207,14 +1206,14 @@ func TestAccRDSCluster_GlobalClusterIdentifierEngineModeGlobal_remove(t *testing CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_GlobalClusterIdentifier_EngineMode_Global(rName), + Config: testAccClusterConfig_GlobalClusterID_EngineMode_global(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttrPair(resourceName, "global_cluster_identifier", globalClusterResourceName, "id"), ), }, { - Config: testAccClusterConfig_EngineMode_Global(rName), + Config: testAccClusterConfig_EngineMode_global(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "global_cluster_identifier", ""), @@ -1239,14 +1238,14 @@ func TestAccRDSCluster_GlobalClusterIdentifierEngineModeGlobal_update(t *testing CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_GlobalClusterIdentifier_EngineMode_Global_Update(rName, globalClusterResourceName1), + Config: testAccClusterConfig_GlobalClusterID_EngineMode_globalUpdate(rName, globalClusterResourceName1), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttrPair(resourceName, "global_cluster_identifier", globalClusterResourceName1, "id"), ), }, { - Config: testAccClusterConfig_GlobalClusterIdentifier_EngineMode_Global_Update(rName, globalClusterResourceName2), + Config: testAccClusterConfig_GlobalClusterID_EngineMode_globalUpdate(rName, globalClusterResourceName2), ExpectError: regexp.MustCompile(`Existing RDS Clusters cannot be migrated between existing RDS Global Clusters`), }, }, @@ -1267,7 +1266,7 @@ func TestAccRDSCluster_GlobalClusterIdentifierEngineMode_provisioned(t *testing. CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_GlobalClusterIdentifier_EngineMode_Provisioned(rName), + Config: testAccClusterConfig_GlobalClusterID_EngineMode_provisioned(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttrPair(resourceName, "global_cluster_identifier", globalClusterResourceName, "id"), @@ -1304,7 +1303,7 @@ func TestAccRDSCluster_GlobalClusterIdentifier_primarySecondaryClusters(t *testi CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_GlobalClusterIdentifier_PrimarySecondaryClusters(rNameGlobal, rNamePrimary, rNameSecondary), + Config: testAccClusterConfig_GlobalClusterID_primarySecondaryClusters(rNameGlobal, rNamePrimary, rNameSecondary), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExistsWithProvider(resourceNamePrimary, &primaryDbCluster, acctest.RegionProviderFunc(acctest.Region(), &providers)), testAccCheckClusterExistsWithProvider(resourceNameSecondary, &secondaryDbCluster, acctest.RegionProviderFunc(acctest.AlternateRegion(), &providers)), @@ -1338,7 +1337,7 @@ func TestAccRDSCluster_GlobalClusterIdentifier_replicationSourceIdentifier(t *te CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_GlobalClusterIdentifier_ReplicationSourceIdentifier(rName), + Config: testAccClusterConfig_GlobalClusterID_replicationSourceID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExistsWithProvider(resourceNamePrimary, &primaryDbCluster, acctest.RegionProviderFunc(acctest.Region(), &providers)), testAccCheckClusterExistsWithProvider(resourceNameSecondary, &secondaryDbCluster, acctest.RegionProviderFunc(acctest.AlternateRegion(), &providers)), @@ -1375,7 +1374,7 @@ func TestAccRDSCluster_GlobalClusterIdentifier_secondaryClustersWriteForwarding( CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_GlobalClusterIdentifier_SecondaryClustersWriteForwarding(rNameGlobal, rNamePrimary, rNameSecondary), + Config: testAccClusterConfig_GlobalClusterID_secondaryClustersWriteForwarding(rNameGlobal, rNamePrimary, rNameSecondary), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExistsWithProvider(resourceNamePrimary, &primaryDbCluster, acctest.RegionProviderFunc(acctest.Region(), &providers)), testAccCheckClusterExistsWithProvider(resourceNameSecondary, &secondaryDbCluster, acctest.RegionProviderFunc(acctest.AlternateRegion(), &providers)), @@ -1398,14 +1397,14 @@ func TestAccRDSCluster_port(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_Port(rName, 5432), + Config: testAccClusterConfig_port(rName, 5432), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster1), resource.TestCheckResourceAttr(resourceName, "port", "5432"), ), }, { - Config: testAccClusterConfig_Port(rName, 2345), + Config: testAccClusterConfig_port(rName, 2345), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster2), resource.TestCheckResourceAttr(resourceName, "port", "2345"), @@ -1432,7 +1431,7 @@ func TestAccRDSCluster_scaling(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_ScalingConfiguration(rName, false, 128, 4, 301, "RollbackCapacityChange"), + Config: testAccClusterConfig_scalingConfiguration(rName, false, 128, 4, 301, "RollbackCapacityChange"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "scaling_configuration.#", "1"), @@ -1444,7 +1443,7 @@ func TestAccRDSCluster_scaling(t *testing.T) { ), }, { - Config: testAccClusterConfig_ScalingConfiguration(rName, true, 256, 8, 86400, "ForceApplyCapacityChange"), + Config: testAccClusterConfig_scalingConfiguration(rName, true, 256, 8, 86400, "ForceApplyCapacityChange"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "scaling_configuration.#", "1"), @@ -1476,7 +1475,7 @@ func TestAccRDSCluster_serverlessV2ScalingConfiguration(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterServerlessV2ScalingConfigurationConfig(rName, 64.0, 0.5), + Config: testAccClusterConfig_serverlessV2ScalingConfiguration(rName, 64.0, 0.5), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "serverlessv2_scaling_configuration.#", "1"), @@ -1485,7 +1484,7 @@ func TestAccRDSCluster_serverlessV2ScalingConfiguration(t *testing.T) { ), }, { - Config: testAccClusterServerlessV2ScalingConfigurationConfig(rName, 128.0, 8.5), + Config: testAccClusterConfig_serverlessV2ScalingConfiguration(rName, 128.0, 8.5), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "serverlessv2_scaling_configuration.#", "1"), @@ -1511,7 +1510,7 @@ func TestAccRDSCluster_Scaling_defaultMinCapacity(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_ScalingConfiguration_DefaultMinCapacity(rName, false, 128, 301, "RollbackCapacityChange"), + Config: testAccClusterConfig_ScalingConfiguration_defaultMinCapacity(rName, false, 128, 301, "RollbackCapacityChange"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "scaling_configuration.#", "1"), @@ -1546,10 +1545,10 @@ func TestAccRDSCluster_snapshotIdentifier(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier(rName), + Config: testAccClusterConfig_snapshotID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), ), }, @@ -1577,20 +1576,20 @@ func TestAccRDSCluster_SnapshotIdentifier_deletionProtection(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_DeletionProtection(rName, true), + Config: testAccClusterConfig_SnapshotID_deletionProtection(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "true"), ), }, // Ensure we disable deletion protection before attempting to delete :) { - Config: testAccClusterConfig_SnapshotIdentifier_DeletionProtection(rName, false), + Config: testAccClusterConfig_SnapshotID_deletionProtection(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "false"), ), @@ -1619,10 +1618,10 @@ func TestAccRDSCluster_SnapshotIdentifierEngineMode_parallelQuery(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_EngineMode(rName, "parallelquery"), + Config: testAccClusterConfig_SnapshotID_engineMode(rName, "parallelquery"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "engine_mode", "parallelquery"), ), @@ -1651,10 +1650,10 @@ func TestAccRDSCluster_SnapshotIdentifierEngineMode_provisioned(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_EngineMode(rName, "provisioned"), + Config: testAccClusterConfig_SnapshotID_engineMode(rName, "provisioned"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "engine_mode", "provisioned"), ), @@ -1683,10 +1682,10 @@ func TestAccRDSCluster_SnapshotIdentifierEngineMode_serverless(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_EngineMode(rName, "serverless"), + Config: testAccClusterConfig_SnapshotID_engineMode(rName, "serverless"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "engine_mode", "serverless"), ), @@ -1717,10 +1716,10 @@ func TestAccRDSCluster_SnapshotIdentifierEngineVersion_different(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_EngineVersion(rName, false), + Config: testAccClusterConfig_SnapshotID_engineVersion(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttrPair(resourceName, "engine_version", dataSourceName, "version"), ), @@ -1751,10 +1750,10 @@ func TestAccRDSCluster_SnapshotIdentifierEngineVersion_equal(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_EngineVersion(rName, true), + Config: testAccClusterConfig_SnapshotID_engineVersion(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttrPair(resourceName, "engine_version", dataSourceName, "version"), ), @@ -1784,10 +1783,10 @@ func TestAccRDSCluster_SnapshotIdentifier_kmsKeyID(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_KMSKeyID(rName), + Config: testAccClusterConfig_SnapshotID_kmsKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsKeyResourceName, "arn"), ), @@ -1816,10 +1815,10 @@ func TestAccRDSCluster_SnapshotIdentifier_masterPassword(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_MasterPassword(rName, "password1"), + Config: testAccClusterConfig_SnapshotID_masterPassword(rName, "password1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "master_password", "password1"), ), @@ -1848,10 +1847,10 @@ func TestAccRDSCluster_SnapshotIdentifier_masterUsername(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_MasterUsername(rName, "username1"), + Config: testAccClusterConfig_SnapshotID_masterUsername(rName, "username1"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "master_username", "foo"), ), @@ -1882,10 +1881,10 @@ func TestAccRDSCluster_SnapshotIdentifier_preferredBackupWindow(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_PreferredBackupWindow(rName, "00:00-08:00"), + Config: testAccClusterConfig_SnapshotID_preferredBackupWindow(rName, "00:00-08:00"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "preferred_backup_window", "00:00-08:00"), ), @@ -1914,10 +1913,10 @@ func TestAccRDSCluster_SnapshotIdentifier_preferredMaintenanceWindow(t *testing. CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_PreferredMaintenanceWindow(rName, "sun:01:00-sun:01:30"), + Config: testAccClusterConfig_SnapshotID_preferredMaintenanceWindow(rName, "sun:01:00-sun:01:30"), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "preferred_maintenance_window", "sun:01:00-sun:01:30"), ), @@ -1946,10 +1945,10 @@ func TestAccRDSCluster_SnapshotIdentifier_tags(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_Tags(rName), + Config: testAccClusterConfig_SnapshotID_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), @@ -1979,10 +1978,10 @@ func TestAccRDSCluster_SnapshotIdentifier_vpcSecurityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_VPCSecurityGroupIDs(rName), + Config: testAccClusterConfig_SnapshotID_vpcSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), ), }, @@ -2014,10 +2013,10 @@ func TestAccRDSCluster_SnapshotIdentifierVPCSecurityGroupIDs_tags(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_VPCSecurityGroupIds_Tags(rName), + Config: testAccClusterConfig_SnapshotID_VPCSecurityGroupIds_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), @@ -2048,10 +2047,10 @@ func TestAccRDSCluster_SnapshotIdentifier_encryptedRestore(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_SnapshotIdentifier_EncryptedRestore(rName), + Config: testAccClusterConfig_SnapshotID_encryptedRestore(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(sourceDbResourceName, &sourceDbCluster), - testAccCheckDbClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), + testAccCheckClusterSnapshotExists(snapshotResourceName, &dbClusterSnapshot), testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsKeyResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "storage_encrypted", "true"), @@ -2078,14 +2077,14 @@ func TestAccRDSCluster_enableHTTPEndpoint(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig_EnableHTTPEndpoint(rName, true), + Config: testAccClusterConfig_enableHTTPEndpoint(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "enable_http_endpoint", "true"), ), }, { - Config: testAccClusterConfig_EnableHTTPEndpoint(rName, false), + Config: testAccClusterConfig_enableHTTPEndpoint(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "enable_http_endpoint", "false"), @@ -2224,7 +2223,7 @@ func testAccCheckClusterRecreated(i, j *rds.DBCluster) resource.TestCheckFunc { } } -func testAccClusterConfig(rName string) string { +func testAccClusterConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -2237,7 +2236,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_AllowMajorVersionUpgrade(rName string, allowMajorVersionUpgrade bool, engine string, engineVersion string) string { +func testAccClusterConfig_allowMajorVersionUpgrade(rName string, allowMajorVersionUpgrade bool, engine string, engineVersion string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { allow_major_version_upgrade = %[1]t @@ -2271,7 +2270,7 @@ resource "aws_rds_cluster_instance" "test" { `, allowMajorVersionUpgrade, rName, engine, engineVersion) } -func testAccClusterConfig_AllowMajorVersionUpgradeWithCustomParameters(rName string, allowMajorVersionUpgrade bool, engine string, engineVersion string, applyImmediate bool) string { +func testAccClusterConfig_allowMajorVersionUpgradeCustomParameters(rName string, allowMajorVersionUpgrade bool, engine string, engineVersion string, applyImmediate bool) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { allow_major_version_upgrade = %[1]t @@ -2327,7 +2326,7 @@ resource "aws_db_parameter_group" "test" { `, allowMajorVersionUpgrade, rName, engine, engineVersion, applyImmediate, engine+strings.Split(engineVersion, ".")[0]) } -func testAccClusterConfig_MajorVersionOnly(rName string, allowMajorVersionUpgrade bool, engine string, engineVersion string) string { +func testAccClusterConfig_majorVersionOnly(rName string, allowMajorVersionUpgrade bool, engine string, engineVersion string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { allow_major_version_upgrade = %[1]t @@ -2351,7 +2350,7 @@ resource "aws_rds_cluster_instance" "test" { `, allowMajorVersionUpgrade, rName, engine, engineVersion) } -func testAccClusterConfig_AvailabilityZones(rName string) string { +func testAccClusterConfig_availabilityZones(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -2373,7 +2372,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_StorageType(rName string) string { +func testAccClusterConfig_storageType(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { apply_immediately = true @@ -2390,7 +2389,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_AllocatedStorage(rName string) string { +func testAccClusterConfig_allocatedStorage(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { apply_immediately = true @@ -2407,7 +2406,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_Iops(rName string) string { +func testAccClusterConfig_iops(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { apply_immediately = true @@ -2424,7 +2423,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_DbClusterInstanceClass(rName string) string { +func testAccClusterConfig_dbClusterInstanceClass(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { apply_immediately = true @@ -2441,7 +2440,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_BacktrackWindow(backtrackWindow int) string { +func testAccClusterConfig_backtrackWindow(backtrackWindow int) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { apply_immediately = true @@ -2454,7 +2453,7 @@ resource "aws_rds_cluster" "test" { `, backtrackWindow) } -func testAccClusterConfig_ClusterIdentifierPrefix(clusterIdentifierPrefix string) string { +func testAccClusterConfig_clusterIDPrefix(clusterIdentifierPrefix string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier_prefix = %q @@ -2465,7 +2464,7 @@ resource "aws_rds_cluster" "test" { `, clusterIdentifierPrefix) } -func testAccClusterConfig_SubnetGroupName(rName string) string { +func testAccClusterConfig_subnetGroupName(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -2621,7 +2620,7 @@ resource "aws_rds_cluster" "test" { ` } -func testAccClusterWithFinalSnapshotConfig(n int) string { +func testAccClusterConfig_finalSnapshot(n int) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = "tf-aurora-cluster-%[1]d" @@ -2638,7 +2637,7 @@ resource "aws_rds_cluster" "test" { `, n) } -func testAccClusterWithoutUserNameAndPasswordConfig(n int) string { +func testAccClusterConfig_withoutUserNameAndPassword(n int) string { return fmt.Sprintf(` resource "aws_rds_cluster" "default" { cluster_identifier = "tf-aurora-cluster-%d" @@ -2741,7 +2740,7 @@ resource "aws_rds_cluster" "restored_pit" { `, parentId, childId, enabledCloudwatchLogExports)) } -func testAccClusterTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccClusterConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -2756,7 +2755,7 @@ resource "aws_rds_cluster" "test" { `, rName, tagKey1, tagValue1) } -func testAccClusterTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccClusterConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -2772,7 +2771,7 @@ resource "aws_rds_cluster" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccClusterEnabledCloudWatchLogsExports1Config(rName, enabledCloudwatchLogExports1 string) string { +func testAccClusterConfig_enabledCloudWatchLogsExports1(rName, enabledCloudwatchLogExports1 string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -2784,7 +2783,7 @@ resource "aws_rds_cluster" "test" { `, rName, enabledCloudwatchLogExports1) } -func testAccClusterEnabledCloudWatchLogsExports2Config(rName, enabledCloudwatchLogExports1, enabledCloudwatchLogExports2 string) string { +func testAccClusterConfig_enabledCloudWatchLogsExports2(rName, enabledCloudwatchLogExports1, enabledCloudwatchLogExports2 string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -2796,7 +2795,7 @@ resource "aws_rds_cluster" "test" { `, rName, enabledCloudwatchLogExports1, enabledCloudwatchLogExports2) } -func testAccClusterEnabledCloudWatchLogsExportsPostgres1Config(rName, enabledCloudwatchLogExports1 string) string { +func testAccClusterConfig_enabledCloudWatchLogsExportsPostgreSQL1(rName, enabledCloudwatchLogExports1 string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -2905,7 +2904,7 @@ resource "aws_rds_cluster" "test" { `, n) } -func testAccClusterConfig_EngineVersion(upgrade bool, rInt int) string { +func testAccClusterConfig_engineVersion(upgrade bool, rInt int) string { return fmt.Sprintf(` data "aws_rds_engine_version" "test" { engine = "aurora-postgresql" @@ -2936,7 +2935,7 @@ resource "aws_rds_cluster" "test" { `, upgrade, rInt) } -func testAccClusterConfig_EngineVersionWithPrimaryInstance(upgrade bool, rInt int) string { +func testAccClusterConfig_engineVersionPrimaryInstance(upgrade bool, rInt int) string { return fmt.Sprintf(` data "aws_rds_engine_version" "test" { engine = "aurora-postgresql" @@ -2980,7 +2979,7 @@ resource "aws_rds_cluster_instance" "test" { `, upgrade, rInt) } -func testAccClusterConfig_Port(rName string, port int) string { +func testAccClusterConfig_port(rName string, port int) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %[1]q @@ -2995,7 +2994,7 @@ resource "aws_rds_cluster" "test" { `, rName, port) } -func testAccClusterIncludingIAMRolesConfig(n int) string { +func testAccClusterConfig_includingIAMRoles(n int) string { return fmt.Sprintf(` resource "aws_iam_role" "rds_sample_role" { name = "rds_sample_role_%[1]d" @@ -3088,7 +3087,7 @@ resource "aws_rds_cluster" "test" { `, n) } -func testAccClusterAddIAMRolesConfig(n int) string { +func testAccClusterConfig_addIAMRoles(n int) string { return fmt.Sprintf(` resource "aws_iam_role" "rds_sample_role" { name = "rds_sample_role_%[1]d" @@ -3182,7 +3181,7 @@ resource "aws_rds_cluster" "test" { `, n) } -func testAccClusterRemoveIAMRolesConfig(n int) string { +func testAccClusterConfig_removeIAMRoles(n int) string { return fmt.Sprintf(` resource "aws_iam_role" "another_rds_sample_role" { name = "another_rds_sample_role_%[1]d" @@ -3239,7 +3238,7 @@ resource "aws_rds_cluster" "test" { `, n) } -func testAccClusterReplicationSourceIdentifierKMSKeyIDConfig(rName string) string { +func testAccClusterConfig_replicationSourceIDKMSKeyID(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), fmt.Sprintf(` @@ -3354,7 +3353,7 @@ resource "aws_rds_cluster" "alternate" { `, rName)) } -func testAccClusterConfig_DeletionProtection(rName string, deletionProtection bool) string { +func testAccClusterConfig_deletionProtection(rName string, deletionProtection bool) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -3366,7 +3365,7 @@ resource "aws_rds_cluster" "test" { `, rName, deletionProtection) } -func testAccClusterConfig_EngineMode(rName, engineMode string) string { +func testAccClusterConfig_engineMode(rName, engineMode string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -3382,7 +3381,7 @@ resource "aws_rds_cluster" "test" { `, rName, engineMode) } -func testAccClusterConfig_EngineMode_Global(rName string) string { +func testAccClusterConfig_EngineMode_global(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -3395,7 +3394,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_EngineMode_Multimaster(rName string) string { +func testAccClusterConfig_EngineMode_multimaster(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -3451,7 +3450,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_GlobalClusterIdentifier_EngineMode_Global(rName string) string { +func testAccClusterConfig_GlobalClusterID_EngineMode_global(rName string) string { return fmt.Sprintf(` resource "aws_rds_global_cluster" "test" { engine_version = "5.6.10a" # version compatible with engine_mode = "global" @@ -3471,7 +3470,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_GlobalClusterIdentifier_EngineMode_Global_Update(rName, globalClusterIdentifierResourceName string) string { +func testAccClusterConfig_GlobalClusterID_EngineMode_globalUpdate(rName, globalClusterIdentifierResourceName string) string { return fmt.Sprintf(` resource "aws_rds_global_cluster" "test" { count = 2 @@ -3492,7 +3491,7 @@ resource "aws_rds_cluster" "test" { `, rName, globalClusterIdentifierResourceName) } -func testAccClusterConfig_GlobalClusterIdentifier_EngineMode_Provisioned(rName string) string { +func testAccClusterConfig_GlobalClusterID_EngineMode_provisioned(rName string) string { return fmt.Sprintf(` resource "aws_rds_global_cluster" "test" { engine = "aurora-postgresql" @@ -3512,7 +3511,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_GlobalClusterIdentifier_PrimarySecondaryClusters(rNameGlobal, rNamePrimary, rNameSecondary string) string { +func testAccClusterConfig_GlobalClusterID_primarySecondaryClusters(rNameGlobal, rNamePrimary, rNameSecondary string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), fmt.Sprintf(` @@ -3609,7 +3608,7 @@ resource "aws_rds_cluster_instance" "secondary" { `, rNameGlobal, rNamePrimary, rNameSecondary)) } -func testAccClusterConfig_GlobalClusterIdentifier_SecondaryClustersWriteForwarding(rNameGlobal, rNamePrimary, rNameSecondary string) string { +func testAccClusterConfig_GlobalClusterID_secondaryClustersWriteForwarding(rNameGlobal, rNamePrimary, rNameSecondary string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), fmt.Sprintf(` @@ -3707,7 +3706,7 @@ resource "aws_rds_cluster_instance" "secondary" { `, rNameGlobal, rNamePrimary, rNameSecondary)) } -func testAccClusterConfig_GlobalClusterIdentifier_ReplicationSourceIdentifier(rName string) string { +func testAccClusterConfig_GlobalClusterID_replicationSourceID(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), fmt.Sprintf(` @@ -3811,7 +3810,7 @@ resource "aws_rds_cluster_instance" "secondary" { `, rName)) } -func testAccClusterConfig_ScalingConfiguration(rName string, autoPause bool, maxCapacity, minCapacity, secondsUntilAutoPause int, timeoutAction string) string { +func testAccClusterConfig_scalingConfiguration(rName string, autoPause bool, maxCapacity, minCapacity, secondsUntilAutoPause int, timeoutAction string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -3831,7 +3830,7 @@ resource "aws_rds_cluster" "test" { `, rName, autoPause, maxCapacity, minCapacity, secondsUntilAutoPause, timeoutAction) } -func testAccClusterServerlessV2ScalingConfigurationConfig(rName string, maxCapacity, minCapacity float64) string { +func testAccClusterConfig_serverlessV2ScalingConfiguration(rName string, maxCapacity, minCapacity float64) string { return fmt.Sprintf(` data "aws_rds_engine_version" "test" { engine = "aurora-postgresql" @@ -3854,7 +3853,7 @@ resource "aws_rds_cluster" "test" { `, rName, maxCapacity, minCapacity) } -func testAccClusterConfig_ScalingConfiguration_DefaultMinCapacity(rName string, autoPause bool, maxCapacity, secondsUntilAutoPause int, timeoutAction string) string { +func testAccClusterConfig_ScalingConfiguration_defaultMinCapacity(rName string, autoPause bool, maxCapacity, secondsUntilAutoPause int, timeoutAction string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q @@ -3873,7 +3872,7 @@ resource "aws_rds_cluster" "test" { `, rName, autoPause, maxCapacity, secondsUntilAutoPause, timeoutAction) } -func testAccClusterConfig_SnapshotIdentifier(rName string) string { +func testAccClusterConfig_snapshotID(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "source" { cluster_identifier = "%[1]s-source" @@ -3895,7 +3894,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_SnapshotIdentifier_DeletionProtection(rName string, deletionProtection bool) string { +func testAccClusterConfig_SnapshotID_deletionProtection(rName string, deletionProtection bool) string { return fmt.Sprintf(` resource "aws_rds_cluster" "source" { cluster_identifier = "%[1]s-source" @@ -3918,7 +3917,7 @@ resource "aws_rds_cluster" "test" { `, rName, deletionProtection) } -func testAccClusterConfig_SnapshotIdentifier_EngineMode(rName, engineMode string) string { +func testAccClusterConfig_SnapshotID_engineMode(rName, engineMode string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "source" { cluster_identifier = "%[1]s-source" @@ -3942,7 +3941,7 @@ resource "aws_rds_cluster" "test" { `, rName, engineMode) } -func testAccClusterConfig_SnapshotIdentifier_EngineVersion(rName string, same bool) string { +func testAccClusterConfig_SnapshotID_engineVersion(rName string, same bool) string { return fmt.Sprintf(` data "aws_rds_engine_version" "test" { engine = "aurora-postgresql" @@ -3978,7 +3977,7 @@ resource "aws_rds_cluster" "test" { `, rName, same) } -func testAccClusterConfig_SnapshotIdentifier_KMSKeyID(rName string) string { +func testAccClusterConfig_SnapshotID_kmsKeyID(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -4005,7 +4004,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_SnapshotIdentifier_MasterPassword(rName, masterPassword string) string { +func testAccClusterConfig_SnapshotID_masterPassword(rName, masterPassword string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "source" { cluster_identifier = "%[1]s-source" @@ -4028,7 +4027,7 @@ resource "aws_rds_cluster" "test" { `, rName, masterPassword) } -func testAccClusterConfig_SnapshotIdentifier_MasterUsername(rName, masterUsername string) string { +func testAccClusterConfig_SnapshotID_masterUsername(rName, masterUsername string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "source" { cluster_identifier = "%[1]s-source" @@ -4051,7 +4050,7 @@ resource "aws_rds_cluster" "test" { `, rName, masterUsername) } -func testAccClusterConfig_SnapshotIdentifier_PreferredBackupWindow(rName, preferredBackupWindow string) string { +func testAccClusterConfig_SnapshotID_preferredBackupWindow(rName, preferredBackupWindow string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "source" { cluster_identifier = "%[1]s-source" @@ -4075,7 +4074,7 @@ resource "aws_rds_cluster" "test" { `, rName, preferredBackupWindow) } -func testAccClusterConfig_SnapshotIdentifier_PreferredMaintenanceWindow(rName, preferredMaintenanceWindow string) string { +func testAccClusterConfig_SnapshotID_preferredMaintenanceWindow(rName, preferredMaintenanceWindow string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "source" { cluster_identifier = "%[1]s-source" @@ -4098,7 +4097,7 @@ resource "aws_rds_cluster" "test" { `, rName, preferredMaintenanceWindow) } -func testAccClusterConfig_SnapshotIdentifier_Tags(rName string) string { +func testAccClusterConfig_SnapshotID_tags(rName string) string { return fmt.Sprintf(` resource "aws_rds_cluster" "source" { cluster_identifier = "%[1]s-source" @@ -4124,7 +4123,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_SnapshotIdentifier_VPCSecurityGroupIDs(rName string) string { +func testAccClusterConfig_SnapshotID_vpcSecurityGroupIDs(rName string) string { return fmt.Sprintf(` data "aws_vpc" "default" { default = true @@ -4156,7 +4155,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_SnapshotIdentifier_VPCSecurityGroupIds_Tags(rName string) string { +func testAccClusterConfig_SnapshotID_VPCSecurityGroupIds_tags(rName string) string { return fmt.Sprintf(` data "aws_vpc" "default" { default = true @@ -4192,7 +4191,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterConfig_SnapshotIdentifier_EncryptedRestore(rName string) string { +func testAccClusterConfig_SnapshotID_encryptedRestore(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" {} @@ -4219,7 +4218,7 @@ resource "aws_rds_cluster" "test" { `, rName) } -func testAccClusterWithCopyTagsToSnapshotConfig(n int, f bool) string { +func testAccClusterConfig_copyTagsToSnapshot(n int, f bool) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = "tf-aurora-cluster-%d" @@ -4233,7 +4232,7 @@ resource "aws_rds_cluster" "test" { `, n, f) } -func testAccClusterConfig_EnableHTTPEndpoint(rName string, enableHttpEndpoint bool) string { +func testAccClusterConfig_enableHTTPEndpoint(rName string, enableHttpEndpoint bool) string { return fmt.Sprintf(` resource "aws_rds_cluster" "test" { cluster_identifier = %q diff --git a/internal/service/rds/consts.go b/internal/service/rds/consts.go index 5dfa2cfcd23..2cfc5ce5be8 100644 --- a/internal/service/rds/consts.go +++ b/internal/service/rds/consts.go @@ -9,16 +9,16 @@ const ( ) const ( - StorageTypeStandard = "standard" - StorageTypeGp2 = "gp2" - StorageTypeIo1 = "io1" + storageTypeStandard = "standard" + storageTypeGP2 = "gp2" + storageTypeIO1 = "io1" ) func StorageType_Values() []string { return []string{ - StorageTypeStandard, - StorageTypeGp2, - StorageTypeIo1, + storageTypeStandard, + storageTypeGP2, + storageTypeIO1, } } diff --git a/internal/service/rds/engine_version_data_source_test.go b/internal/service/rds/engine_version_data_source_test.go index 0dd18325a72..3b5b3d62665 100644 --- a/internal/service/rds/engine_version_data_source_test.go +++ b/internal/service/rds/engine_version_data_source_test.go @@ -25,7 +25,7 @@ func TestAccRDSEngineVersionDataSource_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccEngineVersionBasicDataSourceConfig(engine, version, paramGroup), + Config: testAccEngineVersionDataSourceConfig_basic(engine, version, paramGroup), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "engine", engine), resource.TestCheckResourceAttr(dataSourceName, "version", version), @@ -60,7 +60,7 @@ func TestAccRDSEngineVersionDataSource_upgradeTargets(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccEngineVersionUpgradeTargetsDataSourceConfig(), + Config: testAccEngineVersionDataSourceConfig_upgradeTargets(), Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr(dataSourceName, "valid_upgrade_targets.#", regexp.MustCompile(`^[1-9][0-9]*`)), ), @@ -79,7 +79,7 @@ func TestAccRDSEngineVersionDataSource_preferred(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccEngineVersionPreferredDataSourceConfig(), + Config: testAccEngineVersionDataSourceConfig_preferred(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "version", "8.0.27"), ), @@ -98,7 +98,7 @@ func TestAccRDSEngineVersionDataSource_defaultOnly(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccEngineVersionDefaultOnlyDataSourceConfig(), + Config: testAccEngineVersionDataSourceConfig_defaultOnly(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "version"), ), @@ -126,7 +126,7 @@ func testAccEngineVersionPreCheck(t *testing.T) { } } -func testAccEngineVersionBasicDataSourceConfig(engine, version, paramGroup string) string { +func testAccEngineVersionDataSourceConfig_basic(engine, version, paramGroup string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "test" { engine = %[1]q @@ -136,7 +136,7 @@ data "aws_rds_engine_version" "test" { `, engine, version, paramGroup) } -func testAccEngineVersionUpgradeTargetsDataSourceConfig() string { +func testAccEngineVersionDataSourceConfig_upgradeTargets() string { return ` data "aws_rds_engine_version" "test" { engine = "mysql" @@ -145,7 +145,7 @@ data "aws_rds_engine_version" "test" { ` } -func testAccEngineVersionPreferredDataSourceConfig() string { +func testAccEngineVersionDataSourceConfig_preferred() string { return ` data "aws_rds_engine_version" "test" { engine = "mysql" @@ -154,7 +154,7 @@ data "aws_rds_engine_version" "test" { ` } -func testAccEngineVersionDefaultOnlyDataSourceConfig() string { +func testAccEngineVersionDataSourceConfig_defaultOnly() string { return ` data "aws_rds_engine_version" "test" { engine = "mysql" diff --git a/internal/service/rds/event_categories_data_source_test.go b/internal/service/rds/event_categories_data_source_test.go index 8ab0e3f1a89..396aa4894cd 100644 --- a/internal/service/rds/event_categories_data_source_test.go +++ b/internal/service/rds/event_categories_data_source_test.go @@ -18,7 +18,7 @@ func TestAccRDSEventCategoriesDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckEventCategoriesConfig(), + Config: testAccEventCategoriesDataSourceConfig_basic(), Check: resource.ComposeAggregateTestCheckFunc( // These checks are not meant to be exhaustive, as regions have different support. // Instead these are generally to indicate that filtering works as expected. @@ -49,7 +49,7 @@ func TestAccRDSEventCategoriesDataSource_sourceType(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckEventCategoriesSourceTypeConfig("db-snapshot"), + Config: testAccEventCategoriesDataSourceConfig_sourceType("db-snapshot"), Check: resource.ComposeAggregateTestCheckFunc( // These checks are not meant to be exhaustive, as regions have different support. // Instead these are generally to indicate that filtering works as expected. @@ -63,13 +63,13 @@ func TestAccRDSEventCategoriesDataSource_sourceType(t *testing.T) { }) } -func testAccCheckEventCategoriesConfig() string { +func testAccEventCategoriesDataSourceConfig_basic() string { return ` data "aws_db_event_categories" "test" {} ` } -func testAccCheckEventCategoriesSourceTypeConfig(sourceType string) string { +func testAccEventCategoriesDataSourceConfig_sourceType(sourceType string) string { return fmt.Sprintf(` data "aws_db_event_categories" "test" { source_type = %[1]q diff --git a/internal/service/rds/event_subscription_test.go b/internal/service/rds/event_subscription_test.go index ac3a1d342fa..8299b39a06e 100644 --- a/internal/service/rds/event_subscription_test.go +++ b/internal/service/rds/event_subscription_test.go @@ -27,7 +27,7 @@ func TestAccRDSEventSubscription_basic(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionBasicConfig(rName), + Config: testAccEventSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("es:%s", rName)), @@ -62,7 +62,7 @@ func TestAccRDSEventSubscription_disappears(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionBasicConfig(rName), + Config: testAccEventSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &eventSubscription), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceEventSubscription(), resourceName), @@ -85,7 +85,7 @@ func TestAccRDSEventSubscription_Name_generated(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionNameGeneratedConfig(rName), + Config: testAccEventSubscriptionConfig_nameGenerated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -113,7 +113,7 @@ func TestAccRDSEventSubscription_namePrefix(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionNamePrefixConfig(rName, "tf-acc-test-prefix-"), + Config: testAccEventSubscriptionConfig_namePrefix(rName, "tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), @@ -141,7 +141,7 @@ func TestAccRDSEventSubscription_tags(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionTags1Config(rName, "key1", "value1"), + Config: testAccEventSubscriptionConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &eventSubscription), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -154,7 +154,7 @@ func TestAccRDSEventSubscription_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEventSubscriptionTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccEventSubscriptionConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &eventSubscription), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -163,7 +163,7 @@ func TestAccRDSEventSubscription_tags(t *testing.T) { ), }, { - Config: testAccEventSubscriptionTags1Config(rName, "key2", "value2"), + Config: testAccEventSubscriptionConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &eventSubscription), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -187,7 +187,7 @@ func TestAccRDSEventSubscription_categories(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionCategoriesConfig(rName), + Config: testAccEventSubscriptionConfig_categories(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("es:%s", rName)), @@ -213,7 +213,7 @@ func TestAccRDSEventSubscription_categories(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEventSubscriptionCategoriesUpdatedConfig(rName), + Config: testAccEventSubscriptionConfig_categoriesUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("es:%s", rName)), @@ -230,7 +230,7 @@ func TestAccRDSEventSubscription_categories(t *testing.T) { ), }, { - Config: testAccEventSubscriptionCategoriesAndSourceTypeUpdatedConfig(rName), + Config: testAccEventSubscriptionConfig_categoriesAndSourceTypeUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("es:%s", rName)), @@ -266,7 +266,7 @@ func TestAccRDSEventSubscription_sourceIDs(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionSourceIDsConfig(rName), + Config: testAccEventSubscriptionConfig_sourceIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "source_ids.#", "2"), @@ -280,7 +280,7 @@ func TestAccRDSEventSubscription_sourceIDs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEventSubscriptionSourceIDsUpdatedConfig(rName), + Config: testAccEventSubscriptionConfig_sourceIDsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "source_ids.#", "1"), @@ -340,7 +340,7 @@ func testAccCheckEventSubscriptionDestroy(s *terraform.State) error { return nil } -func testAccEventSubscriptionBasicConfig(rName string) string { +func testAccEventSubscriptionConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -353,7 +353,7 @@ resource "aws_db_event_subscription" "test" { `, rName) } -func testAccEventSubscriptionNameGeneratedConfig(rName string) string { +func testAccEventSubscriptionConfig_nameGenerated(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -365,7 +365,7 @@ resource "aws_db_event_subscription" "test" { `, rName) } -func testAccEventSubscriptionNamePrefixConfig(rName, namePrefix string) string { +func testAccEventSubscriptionConfig_namePrefix(rName, namePrefix string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -378,7 +378,7 @@ resource "aws_db_event_subscription" "test" { `, rName, namePrefix) } -func testAccEventSubscriptionTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccEventSubscriptionConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -395,7 +395,7 @@ resource "aws_db_event_subscription" "test" { `, rName, tagKey1, tagValue1) } -func testAccEventSubscriptionTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccEventSubscriptionConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -413,7 +413,7 @@ resource "aws_db_event_subscription" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccEventSubscriptionCategoriesConfig(rName string) string { +func testAccEventSubscriptionConfig_categories(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -436,7 +436,7 @@ resource "aws_db_event_subscription" "test" { `, rName) } -func testAccEventSubscriptionCategoriesUpdatedConfig(rName string) string { +func testAccEventSubscriptionConfig_categoriesUpdated(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -455,7 +455,7 @@ resource "aws_db_event_subscription" "test" { `, rName) } -func testAccEventSubscriptionCategoriesAndSourceTypeUpdatedConfig(rName string) string { +func testAccEventSubscriptionConfig_categoriesAndSourceTypeUpdated(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -498,7 +498,7 @@ resource "aws_db_parameter_group" "test3" { `, rName) } -func testAccEventSubscriptionSourceIDsConfig(rName string) string { +func testAccEventSubscriptionConfig_sourceIDs(rName string) string { return acctest.ConfigCompose(testAccEventSubscriptionSourceIDsBaseConfig(rName), fmt.Sprintf(` resource "aws_db_event_subscription" "test" { name = %[1]q @@ -517,7 +517,7 @@ resource "aws_db_event_subscription" "test" { `, rName)) } -func testAccEventSubscriptionSourceIDsUpdatedConfig(rName string) string { +func testAccEventSubscriptionConfig_sourceIDsUpdated(rName string) string { return acctest.ConfigCompose(testAccEventSubscriptionSourceIDsBaseConfig(rName), fmt.Sprintf(` resource "aws_db_event_subscription" "test" { name = %[1]q diff --git a/internal/service/rds/global_cluster_test.go b/internal/service/rds/global_cluster_test.go index 23523002b15..15fcfb568e5 100644 --- a/internal/service/rds/global_cluster_test.go +++ b/internal/service/rds/global_cluster_test.go @@ -101,7 +101,7 @@ func TestAccRDSGlobalCluster_basic(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterConfig(rName), + Config: testAccGlobalClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), acctest.CheckResourceAttrGlobalARN(resourceName, "arn", "rds", fmt.Sprintf("global-cluster:%s", rName)), @@ -135,7 +135,7 @@ func TestAccRDSGlobalCluster_disappears(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterConfig(rName), + Config: testAccGlobalClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), testAccCheckGlobalClusterDisappears(&globalCluster1), @@ -158,7 +158,7 @@ func TestAccRDSGlobalCluster_databaseName(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterDatabaseNameConfig(rName, "database1"), + Config: testAccGlobalClusterConfig_databaseName(rName, "database1"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), resource.TestCheckResourceAttr(resourceName, "database_name", "database1"), @@ -170,7 +170,7 @@ func TestAccRDSGlobalCluster_databaseName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccGlobalClusterDatabaseNameConfig(rName, "database2"), + Config: testAccGlobalClusterConfig_databaseName(rName, "database2"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster2), testAccCheckGlobalClusterRecreated(&globalCluster1, &globalCluster2), @@ -193,7 +193,7 @@ func TestAccRDSGlobalCluster_deletionProtection(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterDeletionProtectionConfig(rName, true), + Config: testAccGlobalClusterConfig_deletionProtection(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "true"), @@ -205,7 +205,7 @@ func TestAccRDSGlobalCluster_deletionProtection(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccGlobalClusterDeletionProtectionConfig(rName, false), + Config: testAccGlobalClusterConfig_deletionProtection(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster2), testAccCheckGlobalClusterNotRecreated(&globalCluster1, &globalCluster2), @@ -228,7 +228,7 @@ func TestAccRDSGlobalCluster_Engine_aurora(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterEngineConfig(rName, "aurora"), + Config: testAccGlobalClusterConfig_engine(rName, "aurora"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), resource.TestCheckResourceAttr(resourceName, "engine", "aurora"), @@ -255,7 +255,7 @@ func TestAccRDSGlobalCluster_EngineVersion_aurora(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterEngineVersionConfig(rName, "aurora"), + Config: testAccGlobalClusterConfig_engineVersion(rName, "aurora"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), resource.TestCheckResourceAttrPair(resourceName, "engine_version", "data.aws_rds_engine_version.default", "version"), @@ -286,15 +286,15 @@ func TestAccRDSGlobalCluster_EngineVersion_updateMinor(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - //Config: testAccGlobalClusterWithPrimaryEngineVersionConfig(rName, "aurora", "5.6.mysql_aurora.1.22.2"), - Config: testAccGlobalClusterWithPrimaryEngineVersionConfig(rName, "aurora-postgresql", "13.4"), + //Config: testAccGlobalClusterConfig_primaryEngineVersion(rName, "aurora", "5.6.mysql_aurora.1.22.2"), + Config: testAccGlobalClusterConfig_primaryEngineVersion(rName, "aurora-postgresql", "13.4"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), ), }, { - //Config: testAccGlobalClusterWithPrimaryEngineVersionConfig(rName, "aurora", "5.6.mysql_aurora.1.23.2"), - Config: testAccGlobalClusterWithPrimaryEngineVersionConfig(rName, "aurora-postgresql", "13.5"), + //Config: testAccGlobalClusterConfig_primaryEngineVersion(rName, "aurora", "5.6.mysql_aurora.1.23.2"), + Config: testAccGlobalClusterConfig_primaryEngineVersion(rName, "aurora-postgresql", "13.5"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster2), testAccCheckGlobalClusterNotRecreated(&globalCluster1, &globalCluster2), @@ -326,13 +326,13 @@ func TestAccRDSGlobalCluster_EngineVersion_updateMajor(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterWithPrimaryEngineVersionConfig(rName, "aurora", "5.6.mysql_aurora.1.23.4"), + Config: testAccGlobalClusterConfig_primaryEngineVersion(rName, "aurora", "5.6.mysql_aurora.1.23.4"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), ), }, { - Config: testAccGlobalClusterWithPrimaryEngineVersionConfig(rName, "aurora-mysql", "5.7.mysql_aurora.2.10.2"), + Config: testAccGlobalClusterConfig_primaryEngineVersion(rName, "aurora-mysql", "5.7.mysql_aurora.2.10.2"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster2), testAccCheckGlobalClusterNotRecreated(&globalCluster1, &globalCluster2), @@ -367,13 +367,13 @@ func TestAccRDSGlobalCluster_EngineVersion_updateMinorMultiRegion(t *testing.T) CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterEngineVersionUpgradeMultiRegionConfig(rNameGlobal, rNamePrimary, rNameSecondary, "aurora-mysql", "5.7.mysql_aurora.2.07.5"), + Config: testAccGlobalClusterConfig_engineVersionUpgradeMultiRegion(rNameGlobal, rNamePrimary, rNameSecondary, "aurora-mysql", "5.7.mysql_aurora.2.07.5"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), ), }, { - Config: testAccGlobalClusterEngineVersionUpgradeMultiRegionConfig(rNameGlobal, rNamePrimary, rNameSecondary, "aurora-mysql", "5.7.mysql_aurora.2.07.7"), + Config: testAccGlobalClusterConfig_engineVersionUpgradeMultiRegion(rNameGlobal, rNamePrimary, rNameSecondary, "aurora-mysql", "5.7.mysql_aurora.2.07.7"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster2), testAccCheckGlobalClusterNotRecreated(&globalCluster1, &globalCluster2), @@ -403,13 +403,13 @@ func TestAccRDSGlobalCluster_EngineVersion_updateMajorMultiRegion(t *testing.T) CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterEngineVersionUpgradeMultiRegionConfig(rNameGlobal, rNamePrimary, rNameSecondary, "aurora", "5.6.mysql_aurora.1.23.4"), + Config: testAccGlobalClusterConfig_engineVersionUpgradeMultiRegion(rNameGlobal, rNamePrimary, rNameSecondary, "aurora", "5.6.mysql_aurora.1.23.4"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), ), }, { - Config: testAccGlobalClusterEngineVersionUpgradeMultiRegionConfig(rNameGlobal, rNamePrimary, rNameSecondary, "aurora-mysql", "5.7.mysql_aurora.2.10.2"), + Config: testAccGlobalClusterConfig_engineVersionUpgradeMultiRegion(rNameGlobal, rNamePrimary, rNameSecondary, "aurora-mysql", "5.7.mysql_aurora.2.10.2"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster2), testAccCheckGlobalClusterNotRecreated(&globalCluster1, &globalCluster2), @@ -432,7 +432,7 @@ func TestAccRDSGlobalCluster_EngineVersion_auroraMySQL(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterEngineVersionConfig(rName, "aurora-mysql"), + Config: testAccGlobalClusterConfig_engineVersion(rName, "aurora-mysql"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), resource.TestCheckResourceAttrPair(resourceName, "engine_version", "data.aws_rds_engine_version.default", "version"), @@ -459,7 +459,7 @@ func TestAccRDSGlobalCluster_EngineVersion_auroraPostgreSQL(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterEngineVersionConfig(rName, "aurora-postgresql"), + Config: testAccGlobalClusterConfig_engineVersion(rName, "aurora-postgresql"), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), resource.TestCheckResourceAttrPair(resourceName, "engine_version", "data.aws_rds_engine_version.default", "version"), @@ -487,7 +487,7 @@ func TestAccRDSGlobalCluster_sourceDBClusterIdentifier(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterSourceClusterIdentifierConfig(rName), + Config: testAccGlobalClusterConfig_sourceClusterID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), resource.TestCheckResourceAttrPair(resourceName, "source_db_cluster_identifier", clusterResourceName, "arn"), @@ -516,7 +516,7 @@ func TestAccRDSGlobalCluster_SourceDBClusterIdentifier_storageEncrypted(t *testi CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterSourceClusterIdentifierStorageEncryptedConfig(rName), + Config: testAccGlobalClusterConfig_sourceClusterIDStorageEncrypted(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), resource.TestCheckResourceAttrPair(resourceName, "source_db_cluster_identifier", clusterResourceName, "arn"), @@ -544,7 +544,7 @@ func TestAccRDSGlobalCluster_storageEncrypted(t *testing.T) { CheckDestroy: testAccCheckGlobalClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccGlobalClusterStorageEncryptedConfig(rName, true), + Config: testAccGlobalClusterConfig_storageEncrypted(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster1), resource.TestCheckResourceAttr(resourceName, "storage_encrypted", "true"), @@ -556,7 +556,7 @@ func TestAccRDSGlobalCluster_storageEncrypted(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccGlobalClusterStorageEncryptedConfig(rName, false), + Config: testAccGlobalClusterConfig_storageEncrypted(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckGlobalClusterExists(resourceName, &globalCluster2), testAccCheckGlobalClusterRecreated(&globalCluster1, &globalCluster2), @@ -682,7 +682,7 @@ func testAccPreCheckGlobalCluster(t *testing.T) { } } -func testAccGlobalClusterConfig(rName string) string { +func testAccGlobalClusterConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_rds_global_cluster" "test" { global_cluster_identifier = %[1]q @@ -690,7 +690,7 @@ resource "aws_rds_global_cluster" "test" { `, rName) } -func testAccGlobalClusterDatabaseNameConfig(rName, databaseName string) string { +func testAccGlobalClusterConfig_databaseName(rName, databaseName string) string { return fmt.Sprintf(` resource "aws_rds_global_cluster" "test" { database_name = %[1]q @@ -699,7 +699,7 @@ resource "aws_rds_global_cluster" "test" { `, databaseName, rName) } -func testAccGlobalClusterDeletionProtectionConfig(rName string, deletionProtection bool) string { +func testAccGlobalClusterConfig_deletionProtection(rName string, deletionProtection bool) string { return fmt.Sprintf(` resource "aws_rds_global_cluster" "test" { deletion_protection = %[1]t @@ -708,7 +708,7 @@ resource "aws_rds_global_cluster" "test" { `, deletionProtection, rName) } -func testAccGlobalClusterEngineConfig(rName, engine string) string { +func testAccGlobalClusterConfig_engine(rName, engine string) string { return fmt.Sprintf(` resource "aws_rds_global_cluster" "test" { engine = %[1]q @@ -717,7 +717,7 @@ resource "aws_rds_global_cluster" "test" { `, engine, rName) } -func testAccGlobalClusterEngineVersionConfig(rName, engine string) string { +func testAccGlobalClusterConfig_engineVersion(rName, engine string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = %[1]q @@ -731,7 +731,7 @@ resource "aws_rds_global_cluster" "test" { `, engine, rName) } -func testAccGlobalClusterWithPrimaryEngineVersionConfig(rName, engine, engineVersion string) string { +func testAccGlobalClusterConfig_primaryEngineVersion(rName, engine, engineVersion string) string { return fmt.Sprintf(` data "aws_rds_orderable_db_instance" "test" { engine = %[1]q @@ -777,7 +777,7 @@ resource "aws_rds_cluster_instance" "test" { `, engine, engineVersion, rName) } -func testAccGlobalClusterEngineVersionUpgradeMultiRegionConfig(rNameGlobal, rNamePrimary, rNameSecondary, engine, engineVersion string) string { +func testAccGlobalClusterConfig_engineVersionUpgradeMultiRegion(rNameGlobal, rNamePrimary, rNameSecondary, engine, engineVersion string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), fmt.Sprintf(` @@ -884,7 +884,7 @@ resource "aws_rds_cluster_instance" "secondary" { `, rNameGlobal, engine, engineVersion, rNamePrimary, rNameSecondary)) } -func testAccGlobalClusterSourceClusterIdentifierConfig(rName string) string { +func testAccGlobalClusterConfig_sourceClusterID(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "aurora-postgresql" @@ -913,7 +913,7 @@ resource "aws_rds_global_cluster" "test" { `, rName) } -func testAccGlobalClusterSourceClusterIdentifierStorageEncryptedConfig(rName string) string { +func testAccGlobalClusterConfig_sourceClusterIDStorageEncrypted(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "aurora-postgresql" @@ -943,7 +943,7 @@ resource "aws_rds_global_cluster" "test" { `, rName) } -func testAccGlobalClusterStorageEncryptedConfig(rName string, storageEncrypted bool) string { +func testAccGlobalClusterConfig_storageEncrypted(rName string, storageEncrypted bool) string { return fmt.Sprintf(` resource "aws_rds_global_cluster" "test" { global_cluster_identifier = %[1]q diff --git a/internal/service/rds/instance.go b/internal/service/rds/instance.go index 6a90cfea739..775a25ea0f0 100644 --- a/internal/service/rds/instance.go +++ b/internal/service/rds/instance.go @@ -880,7 +880,7 @@ func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { stateConf := &resource.StateChangeConf{ Pending: resourceInstanceCreatePendingStates, Target: []string{"available", "storage-optimization"}, - Refresh: resourceInstanceStateRefreshFunc(d.Id(), conn), + Refresh: resourceDBInstanceStateRefreshFunc(d.Id(), conn), Timeout: d.Timeout(schema.TimeoutCreate), MinTimeout: 10 * time.Second, Delay: 30 * time.Second, // Wait 30 secs before starting @@ -1379,7 +1379,7 @@ func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { stateConf := &resource.StateChangeConf{ Pending: resourceInstanceCreatePendingStates, Target: []string{"available", "storage-optimization"}, - Refresh: resourceInstanceStateRefreshFunc(d.Id(), conn), + Refresh: resourceDBInstanceStateRefreshFunc(d.Id(), conn), Timeout: d.Timeout(schema.TimeoutCreate), MinTimeout: 10 * time.Second, Delay: 30 * time.Second, // Wait 30 secs before starting @@ -1609,7 +1609,7 @@ func waitUntilDBInstanceAvailableAfterUpdate(id string, conn *rds.RDS, timeout t stateConf := &resource.StateChangeConf{ Pending: resourceInstanceUpdatePendingStates, Target: []string{"available", "storage-optimization"}, - Refresh: resourceInstanceStateRefreshFunc(id, conn), + Refresh: resourceDBInstanceStateRefreshFunc(id, conn), Timeout: timeout, MinTimeout: 10 * time.Second, Delay: 30 * time.Second, // Wait 30 secs before starting @@ -1711,7 +1711,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { req.StorageType = aws.String(d.Get("storage_type").(string)) requestUpdate = true - if aws.StringValue(req.StorageType) == StorageTypeIo1 { + if aws.StringValue(req.StorageType) == storageTypeIO1 { req.Iops = aws.Int64(int64(d.Get("iops").(int))) } } @@ -1881,11 +1881,11 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { return resourceInstanceRead(d, meta) } -// resourceInstanceRetrieve fetches DBInstance information from the AWS +// resourceDBInstanceRetrieve fetches DBInstance information from the AWS // API. It returns an error if there is a communication problem or unexpected // error with AWS. When the DBInstance is not found, it returns no error and a // nil pointer. -func resourceInstanceRetrieve(id string, conn *rds.RDS) (*rds.DBInstance, error) { +func resourceDBInstanceRetrieve(id string, conn *rds.RDS) (*rds.DBInstance, error) { opts := rds.DescribeDBInstancesInput{ DBInstanceIdentifier: aws.String(id), } @@ -1917,12 +1917,11 @@ func resourceInstanceImport( return []*schema.ResourceData{d}, nil } -func resourceInstanceStateRefreshFunc(id string, conn *rds.RDS) resource.StateRefreshFunc { +func resourceDBInstanceStateRefreshFunc(id string, conn *rds.RDS) resource.StateRefreshFunc { return func() (interface{}, string, error) { - v, err := resourceInstanceRetrieve(id, conn) + v, err := resourceDBInstanceRetrieve(id, conn) if err != nil { - log.Printf("Error on retrieving DB Instance when waiting: %s", err) return nil, "", err } @@ -1930,11 +1929,7 @@ func resourceInstanceStateRefreshFunc(id string, conn *rds.RDS) resource.StateRe return nil, "", nil } - if v.DBInstanceStatus != nil { - log.Printf("[DEBUG] DB Instance status for instance %s: %s", id, *v.DBInstanceStatus) - } - - return v, *v.DBInstanceStatus, nil + return v, aws.StringValue(v.DBInstanceStatus), nil } } diff --git a/internal/service/rds/instance_automated_backups_replication_test.go b/internal/service/rds/instance_automated_backups_replication_test.go index 8672e12e2e3..73e11092d98 100644 --- a/internal/service/rds/instance_automated_backups_replication_test.go +++ b/internal/service/rds/instance_automated_backups_replication_test.go @@ -35,7 +35,7 @@ func TestAccRDSInstanceAutomatedBackupsReplication_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceAutomatedBackupsReplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceAutomatedBackupsReplicationConfig(rName), + Config: testAccInstanceAutomatedBackupsReplicationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceAutomatedBackupsReplicationExist(resourceName), resource.TestCheckResourceAttr(resourceName, "retention_period", "7"), @@ -70,7 +70,7 @@ func TestAccRDSInstanceAutomatedBackupsReplication_retentionPeriod(t *testing.T) CheckDestroy: testAccCheckInstanceAutomatedBackupsReplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceAutomatedBackupReplicationsRetentionPeriodConfig(rName), + Config: testAccInstanceAutomatedBackupsReplicationConfig_retentionPeriod(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceAutomatedBackupsReplicationExist(resourceName), resource.TestCheckResourceAttr(resourceName, "retention_period", "14"), @@ -105,7 +105,7 @@ func TestAccRDSInstanceAutomatedBackupsReplication_kmsEncrypted(t *testing.T) { CheckDestroy: testAccCheckInstanceAutomatedBackupsReplicationDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceAutomatedBackupsReplicationKMSEncryptedConfig(rName), + Config: testAccInstanceAutomatedBackupsReplicationConfig_kmsEncrypted(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceAutomatedBackupsReplicationExist(resourceName), resource.TestCheckResourceAttr(resourceName, "retention_period", "7"), @@ -120,7 +120,7 @@ func TestAccRDSInstanceAutomatedBackupsReplication_kmsEncrypted(t *testing.T) { }) } -func testAccInstanceAutomatedBackupsReplicationConfig(rName string) string { +func testAccInstanceAutomatedBackupsReplicationConfig_basic(rName string) string { return acctest.ConfigCompose(acctest.ConfigMultipleRegionProvider(2), fmt.Sprintf(` resource "aws_db_instance" "test" { allocated_storage = 10 @@ -143,7 +143,7 @@ resource "aws_db_instance_automated_backups_replication" "test" { `, rName)) } -func testAccInstanceAutomatedBackupReplicationsRetentionPeriodConfig(rName string) string { +func testAccInstanceAutomatedBackupsReplicationConfig_retentionPeriod(rName string) string { return acctest.ConfigCompose(acctest.ConfigMultipleRegionProvider(2), fmt.Sprintf(` resource "aws_db_instance" "test" { allocated_storage = 10 @@ -167,7 +167,7 @@ resource "aws_db_instance_automated_backups_replication" "test" { `, rName)) } -func testAccInstanceAutomatedBackupsReplicationKMSEncryptedConfig(rName string) string { +func testAccInstanceAutomatedBackupsReplicationConfig_kmsEncrypted(rName string) string { return acctest.ConfigCompose(acctest.ConfigMultipleRegionProvider(2), fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q diff --git a/internal/service/rds/instance_data_source_test.go b/internal/service/rds/instance_data_source_test.go index e8aa25f5c8f..c3869f86b6d 100644 --- a/internal/service/rds/instance_data_source_test.go +++ b/internal/service/rds/instance_data_source_test.go @@ -24,7 +24,7 @@ func TestAccRDSInstanceDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstanceDataSourceConfig(rName), + Config: testAccInstanceDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "address"), resource.TestCheckResourceAttrSet(dataSourceName, "allocated_storage"), @@ -72,7 +72,7 @@ func TestAccRDSInstanceDataSource_ec2Classic(t *testing.T) { }) } -func testAccInstanceDataSourceConfig(rName string) string { +func testAccInstanceDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), acctest.ConfigAvailableAZsNoOptIn(), diff --git a/internal/service/rds/instance_role_association.go b/internal/service/rds/instance_role_association.go index 20ab8fcaf80..3de114bf370 100644 --- a/internal/service/rds/instance_role_association.go +++ b/internal/service/rds/instance_role_association.go @@ -12,14 +12,19 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) // Constants not currently provided by the AWS Go SDK const ( - instanceRoleStatusActive = "ACTIVE" - instanceRoleStatusDeleted = "DELETED" - instanceRoleStatusPending = "PENDING" + dbInstanceRoleStatusActive = "ACTIVE" + dbInstanceRoleStatusPending = "PENDING" +) + +const ( + dbInstanceRoleAssociationCreatedTimeout = 10 * time.Minute + dbInstanceRoleAssociationDeletedTimeout = 10 * time.Minute ) func ResourceInstanceRoleAssociation() *schema.Resource { @@ -65,17 +70,28 @@ func resourceInstanceRoleAssociationCreate(d *schema.ResourceData, meta interfac RoleArn: aws.String(roleArn), } - log.Printf("[DEBUG] RDS DB Instance (%s) IAM Role associating: %s", dbInstanceIdentifier, roleArn) - _, err := conn.AddRoleToDBInstance(input) - + err := resource.Retry(propagationTimeout, func() *resource.RetryError { + var err error + _, err = conn.AddRoleToDBInstance(input) + if err != nil { + if tfawserr.ErrMessageContains(err, "InvalidParameterValue", "IAM role ARN value is invalid or does not include the required permissions") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if tfresource.TimedOut(err) { + _, err = conn.AddRoleToDBInstance(input) + } if err != nil { - return fmt.Errorf("error associating RDS DB Instance (%s) IAM Role (%s): %s", dbInstanceIdentifier, roleArn, err) + return fmt.Errorf("error associating RDS DB Instance (%s) IAM Role (%s): %w", dbInstanceIdentifier, roleArn, err) } d.SetId(fmt.Sprintf("%s,%s", dbInstanceIdentifier, roleArn)) if err := waitForDBInstanceRoleAssociation(conn, dbInstanceIdentifier, roleArn); err != nil { - return fmt.Errorf("error waiting for RDS DB Instance (%s) IAM Role (%s) association: %s", dbInstanceIdentifier, roleArn, err) + return fmt.Errorf("error waiting for RDS DB Instance (%s) IAM Role (%s) association: %w", dbInstanceIdentifier, roleArn, err) } return resourceInstanceRoleAssociationRead(d, meta) @@ -87,25 +103,19 @@ func resourceInstanceRoleAssociationRead(d *schema.ResourceData, meta interface{ dbInstanceIdentifier, roleArn, err := InstanceRoleAssociationDecodeID(d.Id()) if err != nil { - return fmt.Errorf("error reading resource ID: %s", err) + return fmt.Errorf("error reading resource ID: %w", err) } - dbInstanceRole, err := DescribeInstanceRole(conn, dbInstanceIdentifier, roleArn) + dbInstanceRole, err := DescribeDBInstanceRole(conn, dbInstanceIdentifier, roleArn) - if tfawserr.ErrCodeEquals(err, rds.ErrCodeDBInstanceNotFoundFault) { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] RDS DB Instance (%s) not found, removing from state", dbInstanceIdentifier) d.SetId("") return nil } if err != nil { - return fmt.Errorf("error reading RDS DB Instance (%s) IAM Role (%s) association: %s", dbInstanceIdentifier, roleArn, err) - } - - if dbInstanceRole == nil { - log.Printf("[WARN] RDS DB Instance (%s) IAM Role (%s) association not found, removing from state", dbInstanceIdentifier, roleArn) - d.SetId("") - return nil + return fmt.Errorf("error reading RDS DB Instance (%s) IAM Role (%s) association: %w", dbInstanceIdentifier, roleArn, err) } d.Set("db_instance_identifier", dbInstanceIdentifier) @@ -121,7 +131,7 @@ func resourceInstanceRoleAssociationDelete(d *schema.ResourceData, meta interfac dbInstanceIdentifier, roleArn, err := InstanceRoleAssociationDecodeID(d.Id()) if err != nil { - return fmt.Errorf("error reading resource ID: %s", err) + return fmt.Errorf("error reading resource ID: %w", err) } input := &rds.RemoveRoleFromDBInstanceInput{ @@ -142,11 +152,11 @@ func resourceInstanceRoleAssociationDelete(d *schema.ResourceData, meta interfac } if err != nil { - return fmt.Errorf("error disassociating RDS DB Instance (%s) IAM Role (%s): %s", dbInstanceIdentifier, roleArn, err) + return fmt.Errorf("error disassociating RDS DB Instance (%s) IAM Role (%s): %w", dbInstanceIdentifier, roleArn, err) } - if err := WaitForInstanceRoleDisassociation(conn, dbInstanceIdentifier, roleArn); err != nil { - return fmt.Errorf("error waiting for RDS DB Instance (%s) IAM Role (%s) disassociation: %s", dbInstanceIdentifier, roleArn, err) + if err := WaitForDBInstanceRoleDisassociation(conn, dbInstanceIdentifier, roleArn); err != nil { + return fmt.Errorf("error waiting for RDS DB Instance (%s) IAM Role (%s) disassociation: %w", dbInstanceIdentifier, roleArn, err) } return nil @@ -162,62 +172,27 @@ func InstanceRoleAssociationDecodeID(id string) (string, string, error) { return parts[0], parts[1], nil } -func DescribeInstanceRole(conn *rds.RDS, dbInstanceIdentifier, roleArn string) (*rds.DBInstanceRole, error) { - input := &rds.DescribeDBInstancesInput{ - DBInstanceIdentifier: aws.String(dbInstanceIdentifier), - } - - log.Printf("[DEBUG] Describing RDS DB Instance: %s", input) - output, err := conn.DescribeDBInstances(input) - +func DescribeDBInstanceRole(conn *rds.RDS, dbInstanceIdentifier, roleArn string) (*rds.DBInstanceRole, error) { + dbInstance, err := FindDBInstanceByID(conn, dbInstanceIdentifier) if err != nil { return nil, err } - var dbInstance *rds.DBInstance - - for _, outputDbInstance := range output.DBInstances { - if aws.StringValue(outputDbInstance.DBInstanceIdentifier) == dbInstanceIdentifier { - dbInstance = outputDbInstance - break - } - } - - if dbInstance == nil { - return nil, nil - } - - var dbInstanceRole *rds.DBInstanceRole - for _, associatedRole := range dbInstance.AssociatedRoles { if aws.StringValue(associatedRole.RoleArn) == roleArn { - dbInstanceRole = associatedRole - break + return associatedRole, nil } } - return dbInstanceRole, nil + return nil, &tfresource.EmptyResultError{} } func waitForDBInstanceRoleAssociation(conn *rds.RDS, dbInstanceIdentifier, roleArn string) error { stateConf := &resource.StateChangeConf{ - Pending: []string{instanceRoleStatusPending}, - Target: []string{instanceRoleStatusActive}, - Refresh: func() (interface{}, string, error) { - dbInstanceRole, err := DescribeInstanceRole(conn, dbInstanceIdentifier, roleArn) - - if err != nil { - return nil, "", err - } - - if dbInstanceRole == nil { - return nil, instanceRoleStatusPending, nil - } - - return dbInstanceRole, aws.StringValue(dbInstanceRole.Status), nil - }, - Timeout: 5 * time.Minute, - Delay: 5 * time.Second, + Pending: []string{dbInstanceRoleStatusPending}, + Target: []string{dbInstanceRoleStatusActive}, + Refresh: statusDBInstanceRoleAssociation(conn, dbInstanceIdentifier, roleArn), + Timeout: dbInstanceRoleAssociationCreatedTimeout, } log.Printf("[DEBUG] Waiting for RDS DB Instance (%s) IAM Role association: %s", dbInstanceIdentifier, roleArn) @@ -226,32 +201,15 @@ func waitForDBInstanceRoleAssociation(conn *rds.RDS, dbInstanceIdentifier, roleA return err } -func WaitForInstanceRoleDisassociation(conn *rds.RDS, dbInstanceIdentifier, roleArn string) error { +func WaitForDBInstanceRoleDisassociation(conn *rds.RDS, dbInstanceIdentifier, roleArn string) error { stateConf := &resource.StateChangeConf{ Pending: []string{ - instanceRoleStatusActive, - instanceRoleStatusPending, + dbInstanceRoleStatusActive, + dbInstanceRoleStatusPending, }, - Target: []string{instanceRoleStatusDeleted}, - Refresh: func() (interface{}, string, error) { - dbInstanceRole, err := DescribeInstanceRole(conn, dbInstanceIdentifier, roleArn) - - if tfawserr.ErrCodeEquals(err, rds.ErrCodeDBInstanceNotFoundFault) { - return &rds.DBInstanceRole{}, instanceRoleStatusDeleted, nil - } - - if err != nil { - return nil, "", err - } - - if dbInstanceRole != nil { - return dbInstanceRole, aws.StringValue(dbInstanceRole.Status), nil - } - - return &rds.DBInstanceRole{}, instanceRoleStatusDeleted, nil - }, - Timeout: 5 * time.Minute, - Delay: 5 * time.Second, + Target: []string{}, + Refresh: statusDBInstanceRoleAssociation(conn, dbInstanceIdentifier, roleArn), + Timeout: dbInstanceRoleAssociationDeletedTimeout, } log.Printf("[DEBUG] Waiting for RDS DB Instance (%s) IAM Role disassociation: %s", dbInstanceIdentifier, roleArn) @@ -259,3 +217,19 @@ func WaitForInstanceRoleDisassociation(conn *rds.RDS, dbInstanceIdentifier, role return err } + +func statusDBInstanceRoleAssociation(conn *rds.RDS, dbInstanceIdentifier, roleArn string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + dbInstanceRole, err := DescribeDBInstanceRole(conn, dbInstanceIdentifier, roleArn) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return dbInstanceRole, aws.StringValue(dbInstanceRole.Status), nil + } +} diff --git a/internal/service/rds/instance_role_association_test.go b/internal/service/rds/instance_role_association_test.go index 59525ded17c..e0e8d02f972 100644 --- a/internal/service/rds/instance_role_association_test.go +++ b/internal/service/rds/instance_role_association_test.go @@ -6,13 +6,13 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfrds "github.com/hashicorp/terraform-provider-aws/internal/service/rds" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func TestAccRDSInstanceRoleAssociation_basic(t *testing.T) { @@ -33,7 +33,7 @@ func TestAccRDSInstanceRoleAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceRoleAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceRoleAssociationConfig(rName), + Config: testAccInstanceRoleAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceRoleAssociationExists(resourceName, &dbInstanceRole1), resource.TestCheckResourceAttrPair(resourceName, "db_instance_identifier", dbInstanceResourceName, "id"), @@ -68,7 +68,7 @@ func TestAccRDSInstanceRoleAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckInstanceRoleAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceRoleAssociationConfig(rName), + Config: testAccInstanceRoleAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(dbInstanceResourceName, &dbInstance1), testAccCheckInstanceRoleAssociationExists(resourceName, &dbInstanceRole1), @@ -96,16 +96,14 @@ func testAccCheckInstanceRoleAssociationExists(resourceName string, dbInstanceRo conn := acctest.Provider.Meta().(*conns.AWSClient).RDSConn - role, err := tfrds.DescribeInstanceRole(conn, dbInstanceIdentifier, roleArn) - + role, err := tfrds.DescribeDBInstanceRole(conn, dbInstanceIdentifier, roleArn) + if tfresource.NotFound(err) { + return fmt.Errorf("RDS DB Instance IAM Role Association not found") + } if err != nil { return err } - if role == nil { - return fmt.Errorf("RDS DB Instance IAM Role Association not found") - } - if aws.StringValue(role.Status) != "ACTIVE" { return fmt.Errorf("RDS DB Instance (%s) IAM Role (%s) association exists in non-ACTIVE (%s) state", dbInstanceIdentifier, roleArn, aws.StringValue(role.Status)) } @@ -130,20 +128,14 @@ func testAccCheckInstanceRoleAssociationDestroy(s *terraform.State) error { return fmt.Errorf("error reading resource ID: %s", err) } - dbInstanceRole, err := tfrds.DescribeInstanceRole(conn, dbInstanceIdentifier, roleArn) - - if tfawserr.ErrCodeEquals(err, rds.ErrCodeDBInstanceNotFoundFault) { + dbInstanceRole, err := tfrds.DescribeDBInstanceRole(conn, dbInstanceIdentifier, roleArn) + if tfresource.NotFound(err) { continue } - if err != nil { return err } - if dbInstanceRole == nil { - continue - } - return fmt.Errorf("RDS DB Instance (%s) IAM Role (%s) association still exists in non-deleted (%s) state", dbInstanceIdentifier, roleArn, aws.StringValue(dbInstanceRole.Status)) } @@ -166,13 +158,28 @@ func testAccCheckInstanceRoleAssociationDisappears(dbInstance *rds.DBInstance, d return err } - return tfrds.WaitForInstanceRoleDisassociation(conn, aws.StringValue(dbInstance.DBInstanceIdentifier), aws.StringValue(dbInstanceRole.RoleArn)) + return tfrds.WaitForDBInstanceRoleDisassociation(conn, aws.StringValue(dbInstance.DBInstanceIdentifier), aws.StringValue(dbInstanceRole.RoleArn)) } } -func testAccInstanceRoleAssociationConfig(rName string) string { +func testAccInstanceRoleAssociationConfig_basic(rName string) string { return fmt.Sprintf(` -data "aws_partition" "current" {} +resource "aws_db_instance_role_association" "test" { + db_instance_identifier = aws_db_instance.test.id + feature_name = "S3_INTEGRATION" + role_arn = aws_iam_role.test.arn +} + +resource "aws_db_instance" "test" { + allocated_storage = 10 + engine = data.aws_rds_orderable_db_instance.test.engine + identifier = %[1]q + instance_class = data.aws_rds_orderable_db_instance.test.instance_class + license_model = data.aws_rds_orderable_db_instance.test.license_model + password = "avoid-plaintext-passwords" + username = "tfacctest" + skip_final_snapshot = true +} data "aws_rds_orderable_db_instance" "test" { engine = "oracle-se2" @@ -182,6 +189,14 @@ data "aws_rds_orderable_db_instance" "test" { preferred_instance_classes = ["db.m5.large", "db.m4.large", "db.r4.large"] } +resource "aws_iam_role" "test" { + assume_role_policy = data.aws_iam_policy_document.rds_assume_role_policy.json + name = %[1]q + + # ensure IAM role is created just before association to exercise IAM eventual consistency + depends_on = [aws_db_instance.test] +} + data "aws_iam_policy_document" "rds_assume_role_policy" { statement { actions = ["sts:AssumeRole"] @@ -194,26 +209,6 @@ data "aws_iam_policy_document" "rds_assume_role_policy" { } } -resource "aws_iam_role" "test" { - assume_role_policy = data.aws_iam_policy_document.rds_assume_role_policy.json - name = %[1]q -} - -resource "aws_db_instance" "test" { - allocated_storage = 10 - engine = data.aws_rds_orderable_db_instance.test.engine - identifier = %[1]q - instance_class = data.aws_rds_orderable_db_instance.test.instance_class - license_model = data.aws_rds_orderable_db_instance.test.license_model - password = "avoid-plaintext-passwords" - username = "tfacctest" - skip_final_snapshot = true -} - -resource "aws_db_instance_role_association" "test" { - db_instance_identifier = aws_db_instance.test.id - feature_name = "S3_INTEGRATION" - role_arn = aws_iam_role.test.arn -} +data "aws_partition" "current" {} `, rName) } diff --git a/internal/service/rds/instance_test.go b/internal/service/rds/instance_test.go index 2c97c3dc2ea..b0cb15f320a 100644 --- a/internal/service/rds/instance_test.go +++ b/internal/service/rds/instance_test.go @@ -39,7 +39,7 @@ func TestAccRDSInstance_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceBasicConfig(rName), + Config: testAccInstanceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance1), testAccCheckInstanceAttributes(&dbInstance1), @@ -112,7 +112,7 @@ func TestAccRDSInstance_NameDeprecated_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceNameDeprecatedBasicConfig(rName), + Config: testAccInstanceConfig_nameDeprecated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance1), testAccCheckInstanceAttributes(&dbInstance1), @@ -186,7 +186,7 @@ func TestAccRDSInstance_onlyMajorVersion(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MajorVersionOnly(), + Config: testAccInstanceConfig_majorVersionOnly(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance1), resource.TestCheckResourceAttr(resourceName, "engine", engine), @@ -294,7 +294,7 @@ func TestAccRDSInstance_kmsKey(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_KMSKeyID(rName), + Config: testAccInstanceConfig_kmsKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testAccCheckInstanceAttributes(&v), @@ -333,14 +333,14 @@ func TestAccRDSInstance_subnetGroup(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_WithSubnetGroup(rName), + Config: testAccInstanceConfig_subnetGroup(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "db_subnet_group_name", rName), ), }, { - Config: testAccInstanceConfig_WithSubnetGroupUpdated(rName), + Config: testAccInstanceConfig_subnetGroupUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "db_subnet_group_name", fmt.Sprintf("%s-2", rName)), @@ -367,7 +367,7 @@ func TestAccRDSInstance_optionGroup(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_WithOptionGroup(rName), + Config: testAccInstanceConfig_optionGroup(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testAccCheckInstanceAttributes(&v), @@ -393,7 +393,7 @@ func TestAccRDSInstance_iamAuth(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_IAMAuth(rName), + Config: testAccInstanceConfig_iamAuth(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists("aws_db_instance.bar", &v), testAccCheckInstanceAttributes(&v), @@ -422,7 +422,7 @@ func TestAccRDSInstance_allowMajorVersionUpgrade(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_AllowMajorVersionUpgrade(rName, true), + Config: testAccInstanceConfig_allowMajorVersionUpgrade(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance1), resource.TestCheckResourceAttr(resourceName, "allow_major_version_upgrade", "true"), @@ -441,7 +441,7 @@ func TestAccRDSInstance_allowMajorVersionUpgrade(t *testing.T) { }, }, { - Config: testAccInstanceConfig_AllowMajorVersionUpgrade(rName, false), + Config: testAccInstanceConfig_allowMajorVersionUpgrade(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance1), resource.TestCheckResourceAttr(resourceName, "allow_major_version_upgrade", "false"), @@ -470,7 +470,7 @@ func TestAccRDSInstance_dbSubnetGroupName(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_DBSubnetGroupName(rName), + Config: testAccInstanceConfig_dbSubnetGroupName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), testAccCheckDBSubnetGroupExists(resourceName, &dbSubnetGroup), @@ -501,7 +501,7 @@ func TestAccRDSInstance_DBSubnetGroupName_ramShared(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_DBSubnetGroupName_RAMShared(rName), + Config: testAccInstanceConfig_DBSubnetGroupName_ramShared(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), testAccCheckDBSubnetGroupExists(dbSubnetGroupResourceName, &dbSubnetGroup), @@ -531,7 +531,7 @@ func TestAccRDSInstance_DBSubnetGroupName_vpcSecurityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_DBSubnetGroupName_VPCSecurityGroupIDs(rName), + Config: testAccInstanceConfig_DBSubnetGroupName_vpcSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), testAccCheckDBSubnetGroupExists(resourceName, &dbSubnetGroup), @@ -559,7 +559,7 @@ func TestAccRDSInstance_deletionProtection(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_DeletionProtection(rName, true), + Config: testAccInstanceConfig_deletionProtection(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "true"), @@ -578,7 +578,7 @@ func TestAccRDSInstance_deletionProtection(t *testing.T) { }, }, { - Config: testAccInstanceConfig_DeletionProtection(rName, false), + Config: testAccInstanceConfig_deletionProtection(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "false"), @@ -605,7 +605,7 @@ func TestAccRDSInstance_finalSnapshotIdentifier(t *testing.T) { CheckDestroy: testAccCheckInstanceSnapshot, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_FinalSnapshotIdentifier(rName), + Config: testAccInstanceConfig_finalSnapshotID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists("aws_db_instance.snapshot", &snap), ), @@ -629,7 +629,7 @@ func TestAccRDSInstance_FinalSnapshotIdentifier_skipFinalSnapshot(t *testing.T) CheckDestroy: testAccCheckInstanceNoSnapshot, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_FinalSnapshotIdentifier_SkipFinalSnapshot(rName), + Config: testAccInstanceConfig_FinalSnapshotID_skipFinalSnapshot(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists("aws_db_instance.snapshot", &snap), ), @@ -655,7 +655,7 @@ func TestAccRDSInstance_isAlreadyBeingDeleted(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MariaDB(rName), + Config: testAccInstanceConfig_mariaDB(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), ), @@ -673,7 +673,7 @@ func TestAccRDSInstance_isAlreadyBeingDeleted(t *testing.T) { t.Fatalf("error deleting Database Instance: %s", err) } }, - Config: testAccInstanceConfig_MariaDB(rName), + Config: testAccInstanceConfig_mariaDB(rName), Destroy: true, }, }, @@ -697,28 +697,28 @@ func TestAccRDSInstance_maxAllocatedStorage(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MaxAllocatedStorage(rName, 10), + Config: testAccInstanceConfig_maxAllocatedStorage(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "max_allocated_storage", "10"), ), }, { - Config: testAccInstanceConfig_MaxAllocatedStorage(rName, 5), + Config: testAccInstanceConfig_maxAllocatedStorage(rName, 5), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "max_allocated_storage", "0"), ), }, { - Config: testAccInstanceConfig_MaxAllocatedStorage(rName, 15), + Config: testAccInstanceConfig_maxAllocatedStorage(rName, 15), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "max_allocated_storage", "15"), ), }, { - Config: testAccInstanceConfig_MaxAllocatedStorage(rName, 0), + Config: testAccInstanceConfig_maxAllocatedStorage(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "max_allocated_storage", "0"), @@ -746,11 +746,11 @@ func TestAccRDSInstance_password(t *testing.T) { Steps: []resource.TestStep{ // Password should not be shown in error message { - Config: testAccInstanceConfig_Password(rName, "invalid"), + Config: testAccInstanceConfig_password(rName, "invalid"), ExpectError: regexp.MustCompile(`MasterUserPassword: "\*{8}",`), }, { - Config: testAccInstanceConfig_Password(rName, "valid-password"), + Config: testAccInstanceConfig_password(rName, "valid-password"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "password", "valid-password"), @@ -938,7 +938,7 @@ func TestAccRDSInstance_ReplicateSourceDB_allocatedStorage(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_AllocatedStorage(rName, 10), + Config: testAccInstanceConfig_ReplicateSourceDB_allocatedStorage(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -968,7 +968,7 @@ func TestAccRDSInstance_ReplicateSourceDB_iops(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_Iops(rName, 1000), + Config: testAccInstanceConfig_ReplicateSourceDB_iops(rName, 1000), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -998,7 +998,7 @@ func TestAccRDSInstance_ReplicateSourceDB_allocatedStorageAndIops(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_AllocatedStorageAndIops(rName, 220, 2200), + Config: testAccInstanceConfig_ReplicateSourceDB_allocatedStorageAndIOPS(rName, 220, 2200), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1029,7 +1029,7 @@ func TestAccRDSInstance_ReplicateSourceDB_allowMajorVersionUpgrade(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_AllowMajorVersionUpgrade(rName, true), + Config: testAccInstanceConfig_ReplicateSourceDB_allowMajorVersionUpgrade(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1059,7 +1059,7 @@ func TestAccRDSInstance_ReplicateSourceDB_autoMinorVersionUpgrade(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_AutoMinorVersionUpgrade(rName, false), + Config: testAccInstanceConfig_ReplicateSourceDB_autoMinorVersionUpgrade(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1089,7 +1089,7 @@ func TestAccRDSInstance_ReplicateSourceDB_availabilityZone(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_AvailabilityZone(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_availabilityZone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1118,7 +1118,7 @@ func TestAccRDSInstance_ReplicateSourceDB_backupRetentionPeriod(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_BackupRetentionPeriod(rName, 1), + Config: testAccInstanceConfig_ReplicateSourceDB_backupRetentionPeriod(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1148,7 +1148,7 @@ func TestAccRDSInstance_ReplicateSourceDB_backupWindow(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_BackupWindow(rName, "00:00-08:00", "sun:23:00-sun:23:30"), + Config: testAccInstanceConfig_ReplicateSourceDB_backupWindow(rName, "00:00-08:00", "sun:23:00-sun:23:30"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1183,7 +1183,7 @@ func TestAccRDSInstance_ReplicateSourceDB_dbSubnetGroupName(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_DbSubnetGroupName(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_dbSubnetGroupName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), testAccCheckDBSubnetGroupExists(resourceName, &dbSubnetGroup), @@ -1219,7 +1219,7 @@ func TestAccRDSInstance_ReplicateSourceDBDBSubnetGroupName_ramShared(t *testing. CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_DbSubnetGroupName_RAMShared(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_DBSubnetGroupName_ramShared(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), testAccCheckDBSubnetGroupExists(dbSubnetGroupResourceName, &dbSubnetGroup), @@ -1253,7 +1253,7 @@ func TestAccRDSInstance_ReplicateSourceDBDBSubnetGroupName_vpcSecurityGroupIDs(t CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_DbSubnetGroupName_VPCSecurityGroupIDs(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_DBSubnetGroupName_vpcSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), testAccCheckDBSubnetGroupExists(resourceName, &dbSubnetGroup), @@ -1290,7 +1290,7 @@ func TestAccRDSInstance_ReplicateSourceDB_deletionProtection(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_DeletionProtection(rName, true), + Config: testAccInstanceConfig_ReplicateSourceDB_deletionProtection(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1300,7 +1300,7 @@ func TestAccRDSInstance_ReplicateSourceDB_deletionProtection(t *testing.T) { }, // Ensure we disable deletion protection before attempting to delete :) { - Config: testAccInstanceConfig_ReplicateSourceDB_DeletionProtection(rName, false), + Config: testAccInstanceConfig_ReplicateSourceDB_deletionProtection(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1330,7 +1330,7 @@ func TestAccRDSInstance_ReplicateSourceDB_iamDatabaseAuthenticationEnabled(t *te CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_IAMDatabaseAuthenticationEnabled(rName, true), + Config: testAccInstanceConfig_ReplicateSourceDB_iamDatabaseAuthenticationEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1360,7 +1360,7 @@ func TestAccRDSInstance_ReplicateSourceDB_maintenanceWindow(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_MaintenanceWindow(rName, "00:00-08:00", "sun:23:00-sun:23:30"), + Config: testAccInstanceConfig_ReplicateSourceDB_maintenanceWindow(rName, "00:00-08:00", "sun:23:00-sun:23:30"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1390,7 +1390,7 @@ func TestAccRDSInstance_ReplicateSourceDB_maxAllocatedStorage(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_MaxAllocatedStorage(rName, 10), + Config: testAccInstanceConfig_ReplicateSourceDB_maxAllocatedStorage(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1420,7 +1420,7 @@ func TestAccRDSInstance_ReplicateSourceDB_monitoring(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_Monitoring(rName, 5), + Config: testAccInstanceConfig_ReplicateSourceDB_monitoring(rName, 5), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1450,7 +1450,7 @@ func TestAccRDSInstance_ReplicateSourceDB_multiAZ(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_MultiAZ(rName, true), + Config: testAccInstanceConfig_ReplicateSourceDB_multiAZ(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1609,7 +1609,7 @@ func TestAccRDSInstance_ReplicateSourceDB_port(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_Port(rName, 9999), + Config: testAccInstanceConfig_ReplicateSourceDB_port(rName, 9999), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1639,7 +1639,7 @@ func TestAccRDSInstance_ReplicateSourceDB_vpcSecurityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_VPCSecurityGroupIDs(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_vpcSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1670,7 +1670,7 @@ func TestAccRDSInstance_ReplicateSourceDB_caCertificateIdentifier(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_CACertificateIdentifier(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_caCertificateID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1701,7 +1701,7 @@ func TestAccRDSInstance_ReplicateSourceDB_replicaMode(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_ReplicaMode(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_replicaMode(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -1737,7 +1737,7 @@ func TestAccRDSInstance_ReplicateSourceDB_parameterGroupTwoStep(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_ParameterGroupTwoStep_Setup(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_ParameterGroupTwoStep_setup(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), resource.TestCheckResourceAttr(sourceResourceName, "parameter_group_name", "default.oracle-ee-19"), @@ -1745,7 +1745,7 @@ func TestAccRDSInstance_ReplicateSourceDB_parameterGroupTwoStep(t *testing.T) { ), }, { - Config: testAccInstanceConfig_ReplicateSourceDB_ParameterGroupTwoStep(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_parameterGroupTwoStep(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), resource.TestCheckResourceAttr(sourceResourceName, "parameter_group_name", "default.oracle-ee-19"), @@ -1913,10 +1913,10 @@ func TestAccRDSInstance_SnapshotIdentifier_basic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier(rName), + Config: testAccInstanceConfig_snapshotID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "identifier", rName), resource.TestCheckResourceAttr(resourceName, "identifier_prefix", ""), @@ -2029,13 +2029,13 @@ func TestAccRDSInstance_SnapshotIdentifier_AssociationRemoved(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier(rName), + Config: testAccInstanceConfig_snapshotID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance1), ), }, { - Config: testAccInstanceConfig_SnapshotIdentifier_AssociationRemoved(rName), + Config: testAccInstanceConfig_SnapshotID_associationRemoved(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance2), testAccCheckInstanceNotRecreated(&dbInstance1, &dbInstance2), @@ -2068,10 +2068,10 @@ func TestAccRDSInstance_SnapshotIdentifier_allocatedStorage(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_AllocatedStorage(rName, 10), + Config: testAccInstanceConfig_SnapshotID_allocatedStorage(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "allocated_storage", "10"), ), @@ -2100,10 +2100,10 @@ func TestAccRDSInstance_SnapshotIdentifier_io1Storage(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_Io1Storage(rName, 1000), + Config: testAccInstanceConfig_SnapshotID_io1Storage(rName, 1000), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "iops", "1000"), ), @@ -2132,10 +2132,10 @@ func TestAccRDSInstance_SnapshotIdentifier_allowMajorVersionUpgrade(t *testing.T CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_AllowMajorVersionUpgrade(rName, true), + Config: testAccInstanceConfig_SnapshotID_allowMajorVersionUpgrade(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "allow_major_version_upgrade", "true"), ), @@ -2164,10 +2164,10 @@ func TestAccRDSInstance_SnapshotIdentifier_autoMinorVersionUpgrade(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_AutoMinorVersionUpgrade(rName, false), + Config: testAccInstanceConfig_SnapshotID_autoMinorVersionUpgrade(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), ), @@ -2196,10 +2196,10 @@ func TestAccRDSInstance_SnapshotIdentifier_availabilityZone(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_AvailabilityZone(rName), + Config: testAccInstanceConfig_SnapshotID_availabilityZone(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), ), }, @@ -2227,10 +2227,10 @@ func TestAccRDSInstance_SnapshotIdentifier_backupRetentionPeriodOverride(t *test CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_BackupRetentionPeriod(rName, 1), + Config: testAccInstanceConfig_SnapshotID_backupRetentionPeriod(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "backup_retention_period", "1"), ), @@ -2259,10 +2259,10 @@ func TestAccRDSInstance_SnapshotIdentifier_backupRetentionPeriodUnset(t *testing CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_BackupRetentionPeriod_Unset(rName), + Config: testAccInstanceConfig_SnapshotID_BackupRetentionPeriod_unset(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "backup_retention_period", "0"), ), @@ -2291,10 +2291,10 @@ func TestAccRDSInstance_SnapshotIdentifier_backupWindow(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_BackupWindow(rName, "00:00-08:00", "sun:23:00-sun:23:30"), + Config: testAccInstanceConfig_SnapshotID_backupWindow(rName, "00:00-08:00", "sun:23:00-sun:23:30"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "backup_window", "00:00-08:00"), ), @@ -2325,10 +2325,10 @@ func TestAccRDSInstance_SnapshotIdentifier_dbSubnetGroupName(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_DBSubnetGroupName(rName), + Config: testAccInstanceConfig_SnapshotID_dbSubnetGroupName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), testAccCheckDBSubnetGroupExists(resourceName, &dbSubnetGroup), resource.TestCheckResourceAttrPair(resourceName, "db_subnet_group_name", dbSubnetGroupResourceName, "name"), @@ -2365,10 +2365,10 @@ func TestAccRDSInstance_SnapshotIdentifier_dbSubnetGroupNameRAMShared(t *testing CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_DBSubnetGroupName_RAMShared(rName), + Config: testAccInstanceConfig_SnapshotID_DBSubnetGroupName_ramShared(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), testAccCheckDBSubnetGroupExists(dbSubnetGroupResourceName, &dbSubnetGroup), resource.TestCheckResourceAttrPair(resourceName, "db_subnet_group_name", dbSubnetGroupResourceName, "name"), @@ -2400,10 +2400,10 @@ func TestAccRDSInstance_SnapshotIdentifier_dbSubnetGroupNameVPCSecurityGroupIDs( CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_DBSubnetGroupName_VPCSecurityGroupIDs(rName), + Config: testAccInstanceConfig_SnapshotID_DBSubnetGroupName_vpcSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), testAccCheckDBSubnetGroupExists(resourceName, &dbSubnetGroup), resource.TestCheckResourceAttrPair(resourceName, "db_subnet_group_name", dbSubnetGroupResourceName, "name"), @@ -2433,20 +2433,20 @@ func TestAccRDSInstance_SnapshotIdentifier_deletionProtection(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_DeletionProtection(rName, true), + Config: testAccInstanceConfig_SnapshotID_deletionProtection(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "true"), ), }, // Ensure we disable deletion protection before attempting to delete :) { - Config: testAccInstanceConfig_SnapshotIdentifier_DeletionProtection(rName, false), + Config: testAccInstanceConfig_SnapshotID_deletionProtection(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "deletion_protection", "false"), ), @@ -2475,10 +2475,10 @@ func TestAccRDSInstance_SnapshotIdentifier_iamDatabaseAuthenticationEnabled(t *t CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_IAMDatabaseAuthenticationEnabled(rName, true), + Config: testAccInstanceConfig_SnapshotID_iamDatabaseAuthenticationEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "iam_database_authentication_enabled", "true"), ), @@ -2507,10 +2507,10 @@ func TestAccRDSInstance_SnapshotIdentifier_maintenanceWindow(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_MaintenanceWindow(rName, "00:00-08:00", "sun:23:00-sun:23:30"), + Config: testAccInstanceConfig_SnapshotID_maintenanceWindow(rName, "00:00-08:00", "sun:23:00-sun:23:30"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "maintenance_window", "sun:23:00-sun:23:30"), ), @@ -2539,10 +2539,10 @@ func TestAccRDSInstance_SnapshotIdentifier_maxAllocatedStorage(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_MaxAllocatedStorage(rName, 10), + Config: testAccInstanceConfig_SnapshotID_maxAllocatedStorage(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "max_allocated_storage", "10"), ), @@ -2571,10 +2571,10 @@ func TestAccRDSInstance_SnapshotIdentifier_monitoring(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_Monitoring(rName, 5), + Config: testAccInstanceConfig_SnapshotID_monitoring(rName, 5), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "5"), ), @@ -2603,10 +2603,10 @@ func TestAccRDSInstance_SnapshotIdentifier_multiAZ(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_MultiAZ(rName, true), + Config: testAccInstanceConfig_SnapshotID_multiAZ(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "multi_az", "true"), ), @@ -2635,10 +2635,10 @@ func TestAccRDSInstance_SnapshotIdentifier_multiAZSQLServer(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_MultiAZ_SQLServer(rName, true), + Config: testAccInstanceConfig_SnapshotID_MultiAZ_sqlServer(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "multi_az", "true"), ), @@ -2667,10 +2667,10 @@ func TestAccRDSInstance_SnapshotIdentifier_parameterGroupName(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_ParameterGroupName(rName), + Config: testAccInstanceConfig_SnapshotID_parameterGroupName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "parameter_group_name", rName), testAccCheckInstanceParameterApplyStatusInSync(&dbInstance), @@ -2700,10 +2700,10 @@ func TestAccRDSInstance_SnapshotIdentifier_port(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_Port(rName, 9999), + Config: testAccInstanceConfig_SnapshotID_port(rName, 9999), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "port", "9999"), ), @@ -2732,10 +2732,10 @@ func TestAccRDSInstance_SnapshotIdentifier_tags(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_Tags(rName), + Config: testAccInstanceConfig_SnapshotID_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), @@ -2765,10 +2765,10 @@ func TestAccRDSInstance_SnapshotIdentifier_tagsRemove(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_Tags_Clear(rName), + Config: testAccInstanceConfig_SnapshotID_Tags_clear(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), @@ -2797,10 +2797,10 @@ func TestAccRDSInstance_SnapshotIdentifier_vpcSecurityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_VPCSecurityGroupIDs(rName), + Config: testAccInstanceConfig_SnapshotID_vpcSecurityGroupIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), ), }, @@ -2832,10 +2832,10 @@ func TestAccRDSInstance_SnapshotIdentifier_vpcSecurityGroupIDsTags(t *testing.T) CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_VPCSecurityGroupIds_Tags(rName), + Config: testAccInstanceConfig_SnapshotID_VPCSecurityGroupIDs_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), @@ -2861,7 +2861,7 @@ func TestAccRDSInstance_monitoringInterval(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MonitoringInterval(rName, 30), + Config: testAccInstanceConfig_monitoringInterval(rName, 30), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "30"), @@ -2879,21 +2879,21 @@ func TestAccRDSInstance_monitoringInterval(t *testing.T) { }, }, { - Config: testAccInstanceConfig_MonitoringInterval(rName, 60), + Config: testAccInstanceConfig_monitoringInterval(rName, 60), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "60"), ), }, { - Config: testAccInstanceConfig_MonitoringInterval(rName, 0), + Config: testAccInstanceConfig_monitoringInterval(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "0"), ), }, { - Config: testAccInstanceConfig_MonitoringInterval(rName, 30), + Config: testAccInstanceConfig_monitoringInterval(rName, 30), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "30"), @@ -2920,7 +2920,7 @@ func TestAccRDSInstance_MonitoringRoleARN_enabledToDisabled(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MonitoringRoleARN(rName), + Config: testAccInstanceConfig_monitoringRoleARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttrPair(resourceName, "monitoring_role_arn", iamRoleResourceName, "arn"), @@ -2938,7 +2938,7 @@ func TestAccRDSInstance_MonitoringRoleARN_enabledToDisabled(t *testing.T) { }, }, { - Config: testAccInstanceConfig_MonitoringInterval(rName, 0), + Config: testAccInstanceConfig_monitoringInterval(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "monitoring_interval", "0"), @@ -2965,7 +2965,7 @@ func TestAccRDSInstance_MonitoringRoleARN_enabledToRemoved(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MonitoringRoleARN(rName), + Config: testAccInstanceConfig_monitoringRoleARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttrPair(resourceName, "monitoring_role_arn", iamRoleResourceName, "arn"), @@ -2983,7 +2983,7 @@ func TestAccRDSInstance_MonitoringRoleARN_enabledToRemoved(t *testing.T) { }, }, { - Config: testAccInstanceConfig_MonitoringRoleARNRemoved(rName), + Config: testAccInstanceConfig_monitoringRoleARNRemoved(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), ), @@ -3009,7 +3009,7 @@ func TestAccRDSInstance_MonitoringRoleARN_removedToEnabled(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MonitoringRoleARNRemoved(rName), + Config: testAccInstanceConfig_monitoringRoleARNRemoved(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), ), @@ -3026,7 +3026,7 @@ func TestAccRDSInstance_MonitoringRoleARN_removedToEnabled(t *testing.T) { }, }, { - Config: testAccInstanceConfig_MonitoringRoleARN(rName), + Config: testAccInstanceConfig_monitoringRoleARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttrPair(resourceName, "monitoring_role_arn", iamRoleResourceName, "arn"), @@ -3166,7 +3166,7 @@ func TestAccRDSInstance_MSSQL_domain(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MSSQLDomain(rName, directory1, directory2), + Config: testAccInstanceConfig_mssqlDomain(rName, directory1, directory2), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &vBefore), testAccCheckInstanceDomainAttributes(directory1, &vBefore), @@ -3175,7 +3175,7 @@ func TestAccRDSInstance_MSSQL_domain(t *testing.T) { ), }, { - Config: testAccInstanceConfig_MSSQLUpdateDomain(rName, directory1, directory2), + Config: testAccInstanceConfig_mssqlUpdateDomain(rName, directory1, directory2), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &vAfter), testAccCheckInstanceDomainAttributes(directory2, &vAfter), @@ -3210,7 +3210,7 @@ func TestAccRDSInstance_MSSQL_domainSnapshotRestore(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MSSQLDomainSnapshotRestore(rName, domain), + Config: testAccInstanceConfig_mssqlDomainSnapshotRestore(rName, domain), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &vRestoredInstance), testAccCheckInstanceExists(originResourceName, &v), @@ -3240,7 +3240,7 @@ func TestAccRDSInstance_MySQL_snapshotRestoreWithEngineVersion(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_MySQLSnapshotRestoreWithEngineVersion(rName), + Config: testAccInstanceConfig_mySQLSnapshotRestoreEngineVersion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(restoreResourceName, &vRestoredInstance), testAccCheckInstanceExists(resourceName, &v), @@ -3268,7 +3268,7 @@ func TestAccRDSInstance_minorVersion(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_AutoMinorVersion(rName), + Config: testAccInstanceConfig_autoMinorVersion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists("aws_db_instance.bar", &v), ), @@ -3289,7 +3289,7 @@ func TestAccRDSInstance_ec2Classic(t *testing.T) { CheckDestroy: testAccCheckInstanceEC2ClassicDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_EC2Classic(rName), + Config: testAccInstanceConfig_ec2Classic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceEC2ClassicExists(resourceName, &v), ), @@ -3314,7 +3314,7 @@ func TestAccRDSInstance_cloudWatchLogsExport(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CloudWatchLogsExportConfiguration(rName), + Config: testAccInstanceConfig_cloudWatchLogsExportConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists("aws_db_instance.bar", &v), ), @@ -3351,7 +3351,7 @@ func TestAccRDSInstance_EnabledCloudWatchLogsExports_mySQL(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CloudWatchLogsExportConfiguration(rName), + Config: testAccInstanceConfig_cloudWatchLogsExportConfiguration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "2"), @@ -3360,7 +3360,7 @@ func TestAccRDSInstance_EnabledCloudWatchLogsExports_mySQL(t *testing.T) { ), }, { - Config: testAccInstanceConfig_CloudWatchLogsExportConfigurationAdd(rName), + Config: testAccInstanceConfig_cloudWatchLogsExportConfigurationAdd(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "3"), @@ -3370,7 +3370,7 @@ func TestAccRDSInstance_EnabledCloudWatchLogsExports_mySQL(t *testing.T) { ), }, { - Config: testAccInstanceConfig_CloudWatchLogsExportConfigurationModify(rName), + Config: testAccInstanceConfig_cloudWatchLogsExportConfigurationModify(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "3"), @@ -3380,7 +3380,7 @@ func TestAccRDSInstance_EnabledCloudWatchLogsExports_mySQL(t *testing.T) { ), }, { - Config: testAccInstanceConfig_CloudWatchLogsExportConfigurationDelete(rName), + Config: testAccInstanceConfig_cloudWatchLogsExportConfigurationDelete(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "0"), @@ -3407,7 +3407,7 @@ func TestAccRDSInstance_EnabledCloudWatchLogsExports_msSQL(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_EnabledCloudWatchLogsExports_MSSQL(rName), + Config: testAccInstanceConfig_EnabledCloudWatchLogsExports_mssql(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "2"), @@ -3445,7 +3445,7 @@ func TestAccRDSInstance_EnabledCloudWatchLogsExports_oracle(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_EnabledCloudWatchLogsExports_Oracle(rName), + Config: testAccInstanceConfig_EnabledCloudWatchLogsExports_oracle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "3"), @@ -3484,7 +3484,7 @@ func TestAccRDSInstance_EnabledCloudWatchLogsExports_postgresql(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_EnabledCloudWatchLogsExports_Postgresql(rName), + Config: testAccInstanceConfig_EnabledCloudWatchLogsExports_postgreSQL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "enabled_cloudwatch_logs_exports.#", "2"), @@ -3523,7 +3523,7 @@ func TestAccRDSInstance_noDeleteAutomatedBackups(t *testing.T) { CheckDestroy: testAccCheckInstanceAutomatedBackups, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_NoDeleteAutomatedBackups(rName), + Config: testAccInstanceConfig_noDeleteAutomatedBackups(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), ), @@ -3878,7 +3878,7 @@ func TestAccRDSInstance_PerformanceInsightsEnabled_disabledToEnabled(t *testing. CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_PerformanceInsightsDisabled(rName), + Config: testAccInstanceConfig_performanceInsightsDisabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "false"), @@ -3895,7 +3895,7 @@ func TestAccRDSInstance_PerformanceInsightsEnabled_disabledToEnabled(t *testing. }, }, { - Config: testAccInstanceConfig_PerformanceInsightsEnabled(rName), + Config: testAccInstanceConfig_performanceInsightsEnabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -3921,7 +3921,7 @@ func TestAccRDSInstance_PerformanceInsightsEnabled_enabledToDisabled(t *testing. CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_PerformanceInsightsEnabled(rName), + Config: testAccInstanceConfig_performanceInsightsEnabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -3938,7 +3938,7 @@ func TestAccRDSInstance_PerformanceInsightsEnabled_enabledToDisabled(t *testing. }, }, { - Config: testAccInstanceConfig_PerformanceInsightsDisabled(rName), + Config: testAccInstanceConfig_performanceInsightsDisabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "false"), @@ -3965,7 +3965,7 @@ func TestAccRDSInstance_performanceInsightsKMSKeyID(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_PerformanceInsightsKMSKeyID(rName), + Config: testAccInstanceConfig_performanceInsightsKMSKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -3983,7 +3983,7 @@ func TestAccRDSInstance_performanceInsightsKMSKeyID(t *testing.T) { }, }, { - Config: testAccInstanceConfig_PerformanceInsightsKMSKeyIdDisabled(rName), + Config: testAccInstanceConfig_performanceInsightsKMSKeyIdDisabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "false"), @@ -3991,7 +3991,7 @@ func TestAccRDSInstance_performanceInsightsKMSKeyID(t *testing.T) { ), }, { - Config: testAccInstanceConfig_PerformanceInsightsKMSKeyID(rName), + Config: testAccInstanceConfig_performanceInsightsKMSKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -4018,7 +4018,7 @@ func TestAccRDSInstance_performanceInsightsRetentionPeriod(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_PerformanceInsightsRetentionPeriod(rName, 731), + Config: testAccInstanceConfig_performanceInsightsRetentionPeriod(rName, 731), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -4036,7 +4036,7 @@ func TestAccRDSInstance_performanceInsightsRetentionPeriod(t *testing.T) { }, }, { - Config: testAccInstanceConfig_PerformanceInsightsRetentionPeriod(rName, 7), + Config: testAccInstanceConfig_performanceInsightsRetentionPeriod(rName, 7), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), @@ -4066,7 +4066,7 @@ func TestAccRDSInstance_ReplicateSourceDB_performanceInsightsEnabled(t *testing. CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_ReplicateSourceDB_PerformanceInsightsEnabled(rName), + Config: testAccInstanceConfig_ReplicateSourceDB_performanceInsightsEnabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceResourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -4101,10 +4101,10 @@ func TestAccRDSInstance_SnapshotIdentifier_performanceInsightsEnabled(t *testing CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_SnapshotIdentifier_PerformanceInsightsEnabled(rName), + Config: testAccInstanceConfig_SnapshotID_performanceInsightsEnabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "performance_insights_enabled", "true"), resource.TestCheckResourceAttrPair(resourceName, "performance_insights_kms_key_id", kmsKeyResourceName, "arn"), @@ -4132,7 +4132,7 @@ func TestAccRDSInstance_caCertificateIdentifier(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_WithCACertificateIdentifier(), + Config: testAccInstanceConfig_caCertificateID(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttrPair(resourceName, "ca_cert_identifier", dataSourceName, "id"), @@ -4159,7 +4159,7 @@ func TestAccRDSInstance_RestoreToPointInTime_sourceIdentifier(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_RestoreToPointInTime_SourceIdentifier(rName), + Config: testAccInstanceConfig_RestoreToPointInTime_sourceID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -4200,7 +4200,7 @@ func TestAccRDSInstance_RestoreToPointInTime_sourceResourceID(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_RestoreToPointInTime_SourceResourceID(rName), + Config: testAccInstanceConfig_RestoreToPointInTime_sourceResourceID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -4241,7 +4241,7 @@ func TestAccRDSInstance_NationalCharacterSet_oracle(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_NationalCharacterSet_Oracle(rName), + Config: testAccInstanceConfig_NationalCharacterSet_oracle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "nchar_character_set_name", "UTF8"), @@ -4280,7 +4280,7 @@ func TestAccRDSInstance_NoNationalCharacterSet_oracle(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_NoNationalCharacterSet_Oracle(rName), + Config: testAccInstanceConfig_NoNationalCharacterSet_oracle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "nchar_character_set_name", "AL16UTF16"), @@ -4314,7 +4314,7 @@ func TestAccRDSInstance_coIPEnabled(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_Outpost_CoIPEnabled(rName, true, 0), + Config: testAccInstanceConfig_Outpost_coIPEnabled(rName, true, 0), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), testAccCheckInstanceAttributes(&v), @@ -4338,7 +4338,7 @@ func TestAccRDSInstance_CoIPEnabled_disabledToEnabled(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_Outpost_CoIPEnabled(rName, false, 0), + Config: testAccInstanceConfig_Outpost_coIPEnabled(rName, false, 0), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "customer_owned_ip_enabled", "false"), @@ -4355,7 +4355,7 @@ func TestAccRDSInstance_CoIPEnabled_disabledToEnabled(t *testing.T) { }, }, { - Config: testAccInstanceConfig_Outpost_CoIPEnabled(rName, true, 0), + Config: testAccInstanceConfig_Outpost_coIPEnabled(rName, true, 0), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "customer_owned_ip_enabled", "true"), @@ -4377,7 +4377,7 @@ func TestAccRDSInstance_CoIPEnabled_enabledToDisabled(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_Outpost_CoIPEnabled(rName, true, 0), + Config: testAccInstanceConfig_Outpost_coIPEnabled(rName, true, 0), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "customer_owned_ip_enabled", "true"), @@ -4394,7 +4394,7 @@ func TestAccRDSInstance_CoIPEnabled_enabledToDisabled(t *testing.T) { }, }, { - Config: testAccInstanceConfig_Outpost_CoIPEnabled(rName, false, 0), + Config: testAccInstanceConfig_Outpost_coIPEnabled(rName, false, 0), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "customer_owned_ip_enabled", "false"), @@ -4417,7 +4417,7 @@ func TestAccRDSInstance_CoIPEnabled_restoreToPointInTime(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CoIPEnabled_RestorePointInTime(rName, false, true), + Config: testAccInstanceConfig_CoIPEnabled_restorePointInTime(rName, false, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceName, &sourceDbInstance), testAccCheckInstanceExists(resourceName, &dbInstance), @@ -4458,10 +4458,10 @@ func TestAccRDSInstance_CoIPEnabled_snapshotIdentifier(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_CoIPEnabled_SnapshotIdentifier(rName, false, true), + Config: testAccInstanceConfig_CoIPEnabled_snapshotID(rName, false, true), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(sourceDbResourceName, &sourceDbInstance), - testAccCheckDbSnapshotExists(snapshotResourceName, &dbSnapshot), + testAccCheckDBSnapshotExists(snapshotResourceName, &dbSnapshot), testAccCheckInstanceExists(resourceName, &dbInstance), resource.TestCheckResourceAttr(resourceName, "customer_owned_ip_enabled", "true"), ), @@ -4548,7 +4548,7 @@ func testAccInstanceConfig_orderableClassSQLServerSe() string { return testAccInstanceConfig_orderableClass("sqlserver-se", "license-included", "standard", sqlServerSEPreferredInstanceClasses) } -func testAccInstanceBasicConfig(rName string) string { +func testAccInstanceConfig_basic(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` @@ -4573,7 +4573,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceNameDeprecatedBasicConfig(rName string) string { +func testAccInstanceConfig_nameDeprecated(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` @@ -4598,7 +4598,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_MajorVersionOnly() string { +func testAccInstanceConfig_majorVersionOnly() string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), ` @@ -4654,7 +4654,7 @@ resource "aws_db_instance" "test" { `) } -func testAccInstanceConfig_KMSKeyID(rName string) string { +func testAccInstanceConfig_kmsKeyID(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "foo" { description = %[1]q @@ -4714,7 +4714,7 @@ resource "aws_db_instance" "bar" { `, rName, mySQLPreferredInstanceClasses) } -func testAccInstanceConfig_WithCACertificateIdentifier() string { +func testAccInstanceConfig_caCertificateID() string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), ` data "aws_rds_certificate" "latest" { latest_valid_till = true @@ -4734,7 +4734,7 @@ resource "aws_db_instance" "bar" { `) } -func testAccInstanceConfig_WithOptionGroup(rName string) string { +func testAccInstanceConfig_optionGroup(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` @@ -4760,7 +4760,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_IAMAuth(rName string) string { +func testAccInstanceConfig_iamAuth(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -4793,7 +4793,7 @@ resource "aws_db_instance" "bar" { `, mySQLPreferredInstanceClasses, rName) } -func testAccInstanceConfig_FinalSnapshotIdentifier_SkipFinalSnapshot(rName string) string { +func testAccInstanceConfig_FinalSnapshotID_skipFinalSnapshot(rName string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "snapshot" { identifier = %[1]q @@ -4819,7 +4819,7 @@ resource "aws_db_instance" "snapshot" { func testAccInstanceConfig_S3Import_Base(rName, bucketPrefix string) string { return acctest.ConfigCompose( - acctest.ConfigVpcWithSubnets(rName, 2), + acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_s3_bucket" "xtrabackup" { bucket = %[1]q @@ -5049,7 +5049,7 @@ resource "aws_db_instance" "test" { `, bucketPrefix)) } -func testAccInstanceConfig_FinalSnapshotIdentifier(rName string) string { +func testAccInstanceConfig_finalSnapshotID(rName string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "snapshot" { identifier = %[1]q @@ -5076,7 +5076,7 @@ resource "aws_db_instance" "snapshot" { `, rName)) } -func testAccInstanceConfig_MonitoringInterval(rName string, monitoringInterval int) string { +func testAccInstanceConfig_monitoringInterval(rName string, monitoringInterval int) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -5137,7 +5137,7 @@ resource "aws_db_instance" "test" { `, rName, monitoringInterval) } -func testAccInstanceConfig_MonitoringRoleARNRemoved(rName string) string { +func testAccInstanceConfig_monitoringRoleARNRemoved(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -5167,7 +5167,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_MonitoringRoleARN(rName string) string { +func testAccInstanceConfig_monitoringRoleARN(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -5253,7 +5253,7 @@ resource "aws_db_instance" "test" { } ` -func testAccInstanceConfig_RestoreToPointInTime_SourceIdentifier(rName string) string { +func testAccInstanceConfig_RestoreToPointInTime_sourceID(rName string) string { return acctest.ConfigCompose( testAccInstanceBaseConfig, fmt.Sprintf(` @@ -5269,7 +5269,7 @@ resource "aws_db_instance" "restore" { `, rName)) } -func testAccInstanceConfig_RestoreToPointInTime_SourceResourceID(rName string) string { +func testAccInstanceConfig_RestoreToPointInTime_sourceResourceID(rName string) string { return acctest.ConfigCompose( testAccInstanceBaseConfig, fmt.Sprintf(` @@ -5365,7 +5365,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_WithSubnetGroup(rName string) string { +func testAccInstanceConfig_subnetGroup(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -5427,7 +5427,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_WithSubnetGroupUpdated(rName string) string { +func testAccInstanceConfig_subnetGroupUpdated(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -5766,7 +5766,7 @@ data "aws_partition" "current" {} `, rName, domain)) } -func testAccInstanceConfig_MSSQLDomain(rName, directory1, directory2 string) string { +func testAccInstanceConfig_mssqlDomain(rName, directory1, directory2 string) string { return acctest.ConfigCompose( testAccInstanceConfig_MSSQLDomain_SharedConfig(rName, directory1), fmt.Sprintf(` @@ -5801,7 +5801,7 @@ resource "aws_directory_service_directory" "directory-2" { `, rName, directory2)) } -func testAccInstanceConfig_MSSQLUpdateDomain(rName, directory1, directory2 string) string { +func testAccInstanceConfig_mssqlUpdateDomain(rName, directory1, directory2 string) string { return acctest.ConfigCompose( testAccInstanceConfig_MSSQLDomain_SharedConfig(rName, directory1), fmt.Sprintf(` @@ -5837,7 +5837,7 @@ resource "aws_directory_service_directory" "directory-2" { `, rName, directory2)) } -func testAccInstanceConfig_MSSQLDomainSnapshotRestore(rName, directory string) string { +func testAccInstanceConfig_mssqlDomainSnapshotRestore(rName, directory string) string { return acctest.ConfigCompose( testAccInstanceConfig_MSSQLDomain_SharedConfig(rName, directory), fmt.Sprintf(` @@ -5879,7 +5879,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_MySQLSnapshotRestoreWithEngineVersion(rName string) string { +func testAccInstanceConfig_mySQLSnapshotRestoreEngineVersion(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -5970,7 +5970,7 @@ resource "aws_security_group_rule" "test" { `, rName)) } -func testAccInstanceConfig_AllowMajorVersionUpgrade(rName string, allowMajorVersionUpgrade bool) string { +func testAccInstanceConfig_allowMajorVersionUpgrade(rName string, allowMajorVersionUpgrade bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "test" { allocated_storage = 10 @@ -5987,7 +5987,7 @@ resource "aws_db_instance" "test" { `, allowMajorVersionUpgrade, rName)) } -func testAccInstanceConfig_AutoMinorVersion(rName string) string { +func testAccInstanceConfig_autoMinorVersion(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` @@ -6005,7 +6005,7 @@ resource "aws_db_instance" "bar" { `, rName)) } -func testAccInstanceConfig_CloudWatchLogsExportConfiguration(rName string) string { +func testAccInstanceConfig_cloudWatchLogsExportConfiguration(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -6066,7 +6066,7 @@ resource "aws_db_instance" "bar" { `, rName)) } -func testAccInstanceConfig_CloudWatchLogsExportConfigurationAdd(rName string) string { +func testAccInstanceConfig_cloudWatchLogsExportConfigurationAdd(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -6130,7 +6130,7 @@ resource "aws_db_instance" "bar" { `, rName)) } -func testAccInstanceConfig_CloudWatchLogsExportConfigurationModify(rName string) string { +func testAccInstanceConfig_cloudWatchLogsExportConfigurationModify(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -6194,7 +6194,7 @@ resource "aws_db_instance" "bar" { `, rName)) } -func testAccInstanceConfig_CloudWatchLogsExportConfigurationDelete(rName string) string { +func testAccInstanceConfig_cloudWatchLogsExportConfigurationDelete(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -6252,7 +6252,7 @@ resource "aws_db_instance" "bar" { `, rName)) } -func testAccInstanceConfig_EC2Classic(rName string) string { +func testAccInstanceConfig_ec2Classic(rName string) string { return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` @@ -6285,7 +6285,7 @@ resource "aws_db_instance" "bar" { `, rName)) } -func testAccInstanceConfig_MariaDB(rName string) string { +func testAccInstanceConfig_mariaDB(rName string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "test" { allocated_storage = 5 @@ -6299,7 +6299,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_DBSubnetGroupName(rName string) string { +func testAccInstanceConfig_dbSubnetGroupName(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -6342,7 +6342,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_DBSubnetGroupName_RAMShared(rName string) string { +func testAccInstanceConfig_DBSubnetGroupName_ramShared(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAlternateAccountProvider(), @@ -6432,7 +6432,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_DBSubnetGroupName_VPCSecurityGroupIDs(rName string) string { +func testAccInstanceConfig_DBSubnetGroupName_vpcSecurityGroupIDs(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -6481,7 +6481,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_DeletionProtection(rName string, deletionProtection bool) string { +func testAccInstanceConfig_deletionProtection(rName string, deletionProtection bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "test" { allocated_storage = 5 @@ -6496,7 +6496,7 @@ resource "aws_db_instance" "test" { `, deletionProtection, rName)) } -func testAccInstanceConfig_EnabledCloudWatchLogsExports_Oracle(rName string) string { +func testAccInstanceConfig_EnabledCloudWatchLogsExports_oracle(rName string) string { return fmt.Sprintf(` data "aws_rds_orderable_db_instance" "test" { engine = "oracle-se2" @@ -6520,7 +6520,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_NationalCharacterSet_Oracle(rName string) string { +func testAccInstanceConfig_NationalCharacterSet_oracle(rName string) string { return fmt.Sprintf(` data "aws_rds_orderable_db_instance" "test" { engine = "oracle-se2" @@ -6544,7 +6544,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_NoNationalCharacterSet_Oracle(rName string) string { +func testAccInstanceConfig_NoNationalCharacterSet_oracle(rName string) string { return fmt.Sprintf(` data "aws_rds_orderable_db_instance" "test" { engine = "oracle-se2" @@ -6567,7 +6567,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_EnabledCloudWatchLogsExports_MSSQL(rName string) string { +func testAccInstanceConfig_EnabledCloudWatchLogsExports_mssql(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassSQLServerSe(), fmt.Sprintf(` @@ -6585,7 +6585,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_EnabledCloudWatchLogsExports_Postgresql(rName string) string { +func testAccInstanceConfig_EnabledCloudWatchLogsExports_postgreSQL(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "postgres" @@ -6610,7 +6610,7 @@ resource "aws_db_instance" "test" { `, postgresPreferredInstanceClasses, rName) } -func testAccInstanceConfig_MaxAllocatedStorage(rName string, maxAllocatedStorage int) string { +func testAccInstanceConfig_maxAllocatedStorage(rName string, maxAllocatedStorage int) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "test" { allocated_storage = 5 @@ -6625,7 +6625,7 @@ resource "aws_db_instance" "test" { `, rName, maxAllocatedStorage)) } -func testAccInstanceConfig_Password(rName, password string) string { +func testAccInstanceConfig_password(rName, password string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "test" { allocated_storage = 5 @@ -6738,7 +6738,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_ReplicateSourceDB_AllocatedStorage(rName string, allocatedStorage int) string { +func testAccInstanceConfig_ReplicateSourceDB_allocatedStorage(rName string, allocatedStorage int) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` @@ -6763,7 +6763,7 @@ resource "aws_db_instance" "test" { `, rName, allocatedStorage)) } -func testAccInstanceConfig_ReplicateSourceDB_Iops(rName string, iops int) string { +func testAccInstanceConfig_ReplicateSourceDB_iops(rName string, iops int) string { return fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 200 @@ -6789,7 +6789,7 @@ resource "aws_db_instance" "test" { `, rName, iops) } -func testAccInstanceConfig_ReplicateSourceDB_AllocatedStorageAndIops(rName string, allocatedStorage, iops int) string { +func testAccInstanceConfig_ReplicateSourceDB_allocatedStorageAndIOPS(rName string, allocatedStorage, iops int) string { return fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = %[2]d @@ -6816,7 +6816,7 @@ resource "aws_db_instance" "test" { `, rName, allocatedStorage, iops) } -func testAccInstanceConfig_ReplicateSourceDB_AllowMajorVersionUpgrade(rName string, allowMajorVersionUpgrade bool) string { +func testAccInstanceConfig_ReplicateSourceDB_allowMajorVersionUpgrade(rName string, allowMajorVersionUpgrade bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -6839,7 +6839,7 @@ resource "aws_db_instance" "test" { `, rName, allowMajorVersionUpgrade)) } -func testAccInstanceConfig_ReplicateSourceDB_AutoMinorVersionUpgrade(rName string, autoMinorVersionUpgrade bool) string { +func testAccInstanceConfig_ReplicateSourceDB_autoMinorVersionUpgrade(rName string, autoMinorVersionUpgrade bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -6862,7 +6862,7 @@ resource "aws_db_instance" "test" { `, rName, autoMinorVersionUpgrade)) } -func testAccInstanceConfig_ReplicateSourceDB_AvailabilityZone(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_availabilityZone(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), acctest.ConfigAvailableAZsNoOptIn(), @@ -6888,7 +6888,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_ReplicateSourceDB_BackupRetentionPeriod(rName string, backupRetentionPeriod int) string { +func testAccInstanceConfig_ReplicateSourceDB_backupRetentionPeriod(rName string, backupRetentionPeriod int) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -6913,7 +6913,7 @@ resource "aws_db_instance" "test" { // We provide maintenance_window to prevent the following error from a randomly selected window: // InvalidParameterValue: The backup window and maintenance window must not overlap. -func testAccInstanceConfig_ReplicateSourceDB_BackupWindow(rName, backupWindow, maintenanceWindow string) string { +func testAccInstanceConfig_ReplicateSourceDB_backupWindow(rName, backupWindow, maintenanceWindow string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -6937,7 +6937,7 @@ resource "aws_db_instance" "test" { `, rName, backupWindow, maintenanceWindow)) } -func testAccInstanceConfig_ReplicateSourceDB_DbSubnetGroupName(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_dbSubnetGroupName(rName string) string { return acctest.ConfigCompose( acctest.ConfigAlternateRegionProvider(), acctest.ConfigAvailableAZsNoOptIn(), @@ -7072,7 +7072,7 @@ provider "awssameaccountalternateregion" { `, os.Getenv(conns.EnvVarAlternateAccessKeyId), os.Getenv(conns.EnvVarAlternateProfile), acctest.AlternateRegion(), os.Getenv(conns.EnvVarAlternateSecretAccessKey)) } -func testAccInstanceConfig_ReplicateSourceDB_DbSubnetGroupName_RAMShared(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_DBSubnetGroupName_ramShared(rName string) string { return acctest.ConfigCompose(testAccAlternateAccountAndAlternateRegionProviderConfig(), fmt.Sprintf(` data "aws_availability_zones" "alternateaccountsameregion" { provider = "awsalternateaccountsameregion" @@ -7228,7 +7228,7 @@ resource "aws_db_instance" "test" { `, rName, mySQLPreferredInstanceClasses)) } -func testAccInstanceConfig_ReplicateSourceDB_DbSubnetGroupName_VPCSecurityGroupIDs(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_DBSubnetGroupName_vpcSecurityGroupIDs(rName string) string { return acctest.ConfigCompose( acctest.ConfigAlternateRegionProvider(), acctest.ConfigAvailableAZsNoOptIn(), @@ -7345,7 +7345,7 @@ resource "aws_db_instance" "test" { `, rName, mySQLPreferredInstanceClasses)) } -func testAccInstanceConfig_ReplicateSourceDB_DeletionProtection(rName string, deletionProtection bool) string { +func testAccInstanceConfig_ReplicateSourceDB_deletionProtection(rName string, deletionProtection bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -7368,7 +7368,7 @@ resource "aws_db_instance" "test" { `, rName, deletionProtection)) } -func testAccInstanceConfig_ReplicateSourceDB_IAMDatabaseAuthenticationEnabled(rName string, iamDatabaseAuthenticationEnabled bool) string { +func testAccInstanceConfig_ReplicateSourceDB_iamDatabaseAuthenticationEnabled(rName string, iamDatabaseAuthenticationEnabled bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -7393,7 +7393,7 @@ resource "aws_db_instance" "test" { // We provide backup_window to prevent the following error from a randomly selected window: // InvalidParameterValue: The backup window and maintenance window must not overlap. -func testAccInstanceConfig_ReplicateSourceDB_MaintenanceWindow(rName, backupWindow, maintenanceWindow string) string { +func testAccInstanceConfig_ReplicateSourceDB_maintenanceWindow(rName, backupWindow, maintenanceWindow string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -7417,7 +7417,7 @@ resource "aws_db_instance" "test" { `, rName, backupWindow, maintenanceWindow)) } -func testAccInstanceConfig_ReplicateSourceDB_MaxAllocatedStorage(rName string, maxAllocatedStorage int) string { +func testAccInstanceConfig_ReplicateSourceDB_maxAllocatedStorage(rName string, maxAllocatedStorage int) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -7441,7 +7441,7 @@ resource "aws_db_instance" "test" { `, rName, maxAllocatedStorage)) } -func testAccInstanceConfig_ReplicateSourceDB_Monitoring(rName string, monitoringInterval int) string { +func testAccInstanceConfig_ReplicateSourceDB_monitoring(rName string, monitoringInterval int) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), testAccInstanceConfig_MonitoringRole(rName), @@ -7468,7 +7468,7 @@ resource "aws_db_instance" "test" { `, rName, monitoringInterval)) } -func testAccInstanceConfig_ReplicateSourceDB_MultiAZ(rName string, multiAz bool) string { +func testAccInstanceConfig_ReplicateSourceDB_multiAZ(rName string, multiAz bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -7647,7 +7647,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_ReplicateSourceDB_Port(rName string, port int) string { +func testAccInstanceConfig_ReplicateSourceDB_port(rName string, port int) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -7670,7 +7670,7 @@ resource "aws_db_instance" "test" { `, rName, port)) } -func testAccInstanceConfig_ReplicateSourceDB_VPCSecurityGroupIDs(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_vpcSecurityGroupIDs(rName string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` data "aws_vpc" "default" { default = true @@ -7702,7 +7702,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_ReplicateSourceDB_CACertificateIdentifier(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_caCertificateID(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` @@ -7732,7 +7732,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_ReplicateSourceDB_ReplicaMode(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_replicaMode(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "oracle-ee" @@ -7770,7 +7770,7 @@ resource "aws_db_instance" "test" { `, oraclePreferredInstanceClasses, rName) } -func testAccInstanceConfig_ReplicateSourceDB_ParameterGroupTwoStep_Setup(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_ParameterGroupTwoStep_setup(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "oracle-ee" @@ -7809,9 +7809,9 @@ resource "aws_db_instance" "source" { `, rName, oraclePreferredInstanceClasses) } -func testAccInstanceConfig_ReplicateSourceDB_ParameterGroupTwoStep(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_parameterGroupTwoStep(rName string) string { return acctest.ConfigCompose( - testAccInstanceConfig_ReplicateSourceDB_ParameterGroupTwoStep_Setup(rName), + testAccInstanceConfig_ReplicateSourceDB_ParameterGroupTwoStep_setup(rName), fmt.Sprintf(` resource "aws_db_instance" "test" { identifier = %[1]q @@ -7867,7 +7867,7 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName) } -func testAccInstanceConfig_SnapshotIdentifier(rName string) string { +func testAccInstanceConfig_snapshotID(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` @@ -7950,7 +7950,7 @@ resource "aws_db_instance" "test" { `, sourceName)) } -func testAccInstanceConfig_SnapshotIdentifier_AssociationRemoved(rName string) string { +func testAccInstanceConfig_SnapshotID_associationRemoved(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` @@ -7977,7 +7977,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_SnapshotIdentifier_AllocatedStorage(rName string, allocatedStorage int) string { +func testAccInstanceConfig_SnapshotID_allocatedStorage(rName string, allocatedStorage int) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8004,7 +8004,7 @@ resource "aws_db_instance" "test" { `, rName, allocatedStorage)) } -func testAccInstanceConfig_SnapshotIdentifier_Io1Storage(rName string, iops int) string { +func testAccInstanceConfig_SnapshotID_io1Storage(rName string, iops int) string { return fmt.Sprintf(` data "aws_rds_orderable_db_instance" "test" { engine = "mariadb" @@ -8042,7 +8042,7 @@ resource "aws_db_instance" "test" { `, rName, iops) } -func testAccInstanceConfig_SnapshotIdentifier_AllowMajorVersionUpgrade(rName string, allowMajorVersionUpgrade bool) string { +func testAccInstanceConfig_SnapshotID_allowMajorVersionUpgrade(rName string, allowMajorVersionUpgrade bool) string { return fmt.Sprintf(` data "aws_rds_orderable_db_instance" "postgres13" { engine = "postgres" @@ -8090,7 +8090,7 @@ resource "aws_db_instance" "test" { `, rName, allowMajorVersionUpgrade) } -func testAccInstanceConfig_SnapshotIdentifier_AutoMinorVersionUpgrade(rName string, autoMinorVersionUpgrade bool) string { +func testAccInstanceConfig_SnapshotID_autoMinorVersionUpgrade(rName string, autoMinorVersionUpgrade bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8117,7 +8117,7 @@ resource "aws_db_instance" "test" { `, rName, autoMinorVersionUpgrade)) } -func testAccInstanceConfig_SnapshotIdentifier_AvailabilityZone(rName string) string { +func testAccInstanceConfig_SnapshotID_availabilityZone(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), acctest.ConfigAvailableAZsNoOptIn(), @@ -8147,7 +8147,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_SnapshotIdentifier_BackupRetentionPeriod(rName string, backupRetentionPeriod int) string { +func testAccInstanceConfig_SnapshotID_backupRetentionPeriod(rName string, backupRetentionPeriod int) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8174,7 +8174,7 @@ resource "aws_db_instance" "test" { `, rName, backupRetentionPeriod)) } -func testAccInstanceConfig_SnapshotIdentifier_BackupRetentionPeriod_Unset(rName string) string { +func testAccInstanceConfig_SnapshotID_BackupRetentionPeriod_unset(rName string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8204,7 +8204,7 @@ resource "aws_db_instance" "test" { // We provide maintenance_window to prevent the following error from a randomly selected window: // InvalidParameterValue: The backup window and maintenance window must not overlap. -func testAccInstanceConfig_SnapshotIdentifier_BackupWindow(rName, backupWindow, maintenanceWindow string) string { +func testAccInstanceConfig_SnapshotID_backupWindow(rName, backupWindow, maintenanceWindow string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8232,7 +8232,7 @@ resource "aws_db_instance" "test" { `, rName, backupWindow, maintenanceWindow)) } -func testAccInstanceConfig_SnapshotIdentifier_DBSubnetGroupName(rName string) string { +func testAccInstanceConfig_SnapshotID_dbSubnetGroupName(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), acctest.ConfigAvailableAZsNoOptIn(), @@ -8287,7 +8287,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_SnapshotIdentifier_DBSubnetGroupName_RAMShared(rName string) string { +func testAccInstanceConfig_SnapshotID_DBSubnetGroupName_ramShared(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), acctest.ConfigAlternateAccountProvider(), @@ -8389,7 +8389,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_SnapshotIdentifier_DBSubnetGroupName_VPCSecurityGroupIDs(rName string) string { +func testAccInstanceConfig_SnapshotID_DBSubnetGroupName_vpcSecurityGroupIDs(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), acctest.ConfigAvailableAZsNoOptIn(), @@ -8450,7 +8450,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_SnapshotIdentifier_DeletionProtection(rName string, deletionProtection bool) string { +func testAccInstanceConfig_SnapshotID_deletionProtection(rName string, deletionProtection bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8477,7 +8477,7 @@ resource "aws_db_instance" "test" { `, rName, deletionProtection)) } -func testAccInstanceConfig_SnapshotIdentifier_IAMDatabaseAuthenticationEnabled(rName string, iamDatabaseAuthenticationEnabled bool) string { +func testAccInstanceConfig_SnapshotID_iamDatabaseAuthenticationEnabled(rName string, iamDatabaseAuthenticationEnabled bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8506,7 +8506,7 @@ resource "aws_db_instance" "test" { // We provide backup_window to prevent the following error from a randomly selected window: // InvalidParameterValue: The backup window and maintenance window must not overlap. -func testAccInstanceConfig_SnapshotIdentifier_MaintenanceWindow(rName, backupWindow, maintenanceWindow string) string { +func testAccInstanceConfig_SnapshotID_maintenanceWindow(rName, backupWindow, maintenanceWindow string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8534,7 +8534,7 @@ resource "aws_db_instance" "test" { `, rName, backupWindow, maintenanceWindow)) } -func testAccInstanceConfig_SnapshotIdentifier_MaxAllocatedStorage(rName string, maxAllocatedStorage int) string { +func testAccInstanceConfig_SnapshotID_maxAllocatedStorage(rName string, maxAllocatedStorage int) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8562,7 +8562,7 @@ resource "aws_db_instance" "test" { `, rName, maxAllocatedStorage)) } -func testAccInstanceConfig_SnapshotIdentifier_Monitoring(rName string, monitoringInterval int) string { +func testAccInstanceConfig_SnapshotID_monitoring(rName string, monitoringInterval int) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` data "aws_partition" "current" {} @@ -8617,7 +8617,7 @@ resource "aws_db_instance" "test" { `, rName, monitoringInterval)) } -func testAccInstanceConfig_SnapshotIdentifier_MultiAZ(rName string, multiAz bool) string { +func testAccInstanceConfig_SnapshotID_multiAZ(rName string, multiAz bool) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "source" { allocated_storage = 5 @@ -8644,7 +8644,7 @@ resource "aws_db_instance" "test" { `, rName, multiAz)) } -func testAccInstanceConfig_SnapshotIdentifier_MultiAZ_SQLServer(rName string, multiAz bool) string { +func testAccInstanceConfig_SnapshotID_MultiAZ_sqlServer(rName string, multiAz bool) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassSQLServerSe(), fmt.Sprintf(` @@ -8676,7 +8676,7 @@ resource "aws_db_instance" "test" { `, rName, multiAz)) } -func testAccInstanceConfig_SnapshotIdentifier_ParameterGroupName(rName string) string { +func testAccInstanceConfig_SnapshotID_parameterGroupName(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` @@ -8716,7 +8716,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_SnapshotIdentifier_Port(rName string, port int) string { +func testAccInstanceConfig_SnapshotID_port(rName string, port int) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` @@ -8745,7 +8745,7 @@ resource "aws_db_instance" "test" { `, rName, port)) } -func testAccInstanceConfig_SnapshotIdentifier_Tags(rName string) string { +func testAccInstanceConfig_SnapshotID_tags(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` @@ -8781,7 +8781,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_SnapshotIdentifier_Tags_Clear(rName string) string { +func testAccInstanceConfig_SnapshotID_Tags_clear(rName string) string { return acctest.ConfigCompose( testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` @@ -8815,7 +8815,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_SnapshotIdentifier_VPCSecurityGroupIDs(rName string) string { +func testAccInstanceConfig_SnapshotID_vpcSecurityGroupIDs(rName string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` data "aws_vpc" "default" { default = true @@ -8851,7 +8851,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_SnapshotIdentifier_VPCSecurityGroupIds_Tags(rName string) string { +func testAccInstanceConfig_SnapshotID_VPCSecurityGroupIDs_tags(rName string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` data "aws_vpc" "default" { default = true @@ -8891,7 +8891,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_PerformanceInsightsDisabled(rName string) string { +func testAccInstanceConfig_performanceInsightsDisabled(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -8921,7 +8921,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_PerformanceInsightsEnabled(rName string) string { +func testAccInstanceConfig_performanceInsightsEnabled(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -8953,7 +8953,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_PerformanceInsightsKMSKeyIdDisabled(rName string) string { +func testAccInstanceConfig_performanceInsightsKMSKeyIdDisabled(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -8986,7 +8986,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_PerformanceInsightsKMSKeyID(rName string) string { +func testAccInstanceConfig_performanceInsightsKMSKeyID(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 @@ -9023,7 +9023,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_PerformanceInsightsRetentionPeriod(rName string, performanceInsightsRetentionPeriod int) string { +func testAccInstanceConfig_performanceInsightsRetentionPeriod(rName string, performanceInsightsRetentionPeriod int) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -9055,7 +9055,7 @@ resource "aws_db_instance" "test" { `, rName, performanceInsightsRetentionPeriod) } -func testAccInstanceConfig_ReplicateSourceDB_PerformanceInsightsEnabled(rName string) string { +func testAccInstanceConfig_ReplicateSourceDB_performanceInsightsEnabled(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Terraform acc test" @@ -9116,7 +9116,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_SnapshotIdentifier_PerformanceInsightsEnabled(rName string) string { +func testAccInstanceConfig_SnapshotID_performanceInsightsEnabled(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Terraform acc test" @@ -9181,7 +9181,7 @@ resource "aws_db_instance" "test" { `, rName) } -func testAccInstanceConfig_NoDeleteAutomatedBackups(rName string) string { +func testAccInstanceConfig_noDeleteAutomatedBackups(rName string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMariadb(), fmt.Sprintf(` resource "aws_db_instance" "test" { allocated_storage = 10 @@ -9198,7 +9198,7 @@ resource "aws_db_instance" "test" { `, rName)) } -func testAccInstanceConfig_Outpost_CoIPEnabled(rName string, coipEnabled bool, backupRetentionPeriod int) string { +func testAccInstanceConfig_Outpost_coIPEnabled(rName string, coipEnabled bool, backupRetentionPeriod int) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -9272,9 +9272,9 @@ resource "aws_db_instance" "test" { `, rName, coipEnabled, backupRetentionPeriod) } -func testAccInstanceConfig_CoIPEnabled_RestorePointInTime(rName string, sourceCoipEnabled bool, targetCoipEnabled bool) string { +func testAccInstanceConfig_CoIPEnabled_restorePointInTime(rName string, sourceCoipEnabled bool, targetCoipEnabled bool) string { return acctest.ConfigCompose( - testAccInstanceConfig_Outpost_CoIPEnabled(rName, sourceCoipEnabled, 1), + testAccInstanceConfig_Outpost_coIPEnabled(rName, sourceCoipEnabled, 1), fmt.Sprintf(` resource "aws_db_instance" "restore" { identifier = "%[1]s-restore" @@ -9291,8 +9291,8 @@ resource "aws_db_instance" "restore" { `, rName, targetCoipEnabled)) } -func testAccInstanceConfig_CoIPEnabled_SnapshotIdentifier(rName string, sourceCoipEnabled bool, targetCoipEnabled bool) string { - return acctest.ConfigCompose(testAccInstanceConfig_Outpost_CoIPEnabled(rName, sourceCoipEnabled, 1), fmt.Sprintf(` +func testAccInstanceConfig_CoIPEnabled_snapshotID(rName string, sourceCoipEnabled bool, targetCoipEnabled bool) string { + return acctest.ConfigCompose(testAccInstanceConfig_Outpost_coIPEnabled(rName, sourceCoipEnabled, 1), fmt.Sprintf(` resource "aws_db_snapshot" "test" { db_instance_identifier = aws_db_instance.test.id db_snapshot_identifier = %[1]q diff --git a/internal/service/rds/option_group_test.go b/internal/service/rds/option_group_test.go index 5dbc346756c..b7db69a38a5 100644 --- a/internal/service/rds/option_group_test.go +++ b/internal/service/rds/option_group_test.go @@ -28,7 +28,7 @@ func TestAccRDSOptionGroup_basic(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupBasicConfig(rName), + Config: testAccOptionGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "rds", regexp.MustCompile(`og:.+`)), @@ -62,7 +62,7 @@ func TestAccRDSOptionGroup_timeoutBlock(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupBasicTimeoutBlockConfig(rName), + Config: testAccOptionGroupConfig_timeoutBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -88,7 +88,7 @@ func TestAccRDSOptionGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroup_namePrefix, + Config: testAccOptionGroupConfig_namePrefix, Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists("aws_db_option_group.test", &v), resource.TestMatchResourceAttr("aws_db_option_group.test", "name", regexp.MustCompile("^tf-test-")), @@ -114,7 +114,7 @@ func TestAccRDSOptionGroup_generatedName(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroup_generatedName, + Config: testAccOptionGroupConfig_generatedName, Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists("aws_db_option_group.test", &v), ), @@ -141,7 +141,7 @@ func TestAccRDSOptionGroup_optionGroupDescription(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupOptionGroupDescriptionConfig(rName, "description1"), + Config: testAccOptionGroupConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &optionGroup1), resource.TestCheckResourceAttr(resourceName, "option_group_description", "description1"), @@ -172,7 +172,7 @@ func TestAccRDSOptionGroup_basicDestroyWithInstance(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupBasicDestroyConfig(rName), + Config: testAccOptionGroupConfig_destroy(rName), }, { ResourceName: resourceName, @@ -196,7 +196,7 @@ func TestAccRDSOptionGroup_Option_optionSettings(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupOptionSettings(rName), + Config: testAccOptionGroupConfig_optionSettings(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -215,7 +215,7 @@ func TestAccRDSOptionGroup_Option_optionSettings(t *testing.T) { ImportStateVerifyIgnore: []string{"name_prefix", "option"}, }, { - Config: testAccOptionGroupOptionSettings_update(rName), + Config: testAccOptionGroupConfig_optionSettingsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -248,7 +248,7 @@ func TestAccRDSOptionGroup_OptionOptionSettings_iamRole(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupOptionSettingsIAMRole(rName), + Config: testAccOptionGroupConfig_optionSettingsIAMRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -278,7 +278,7 @@ func TestAccRDSOptionGroup_sqlServerOptionsUpdate(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupSQLServerEEOptions(rName), + Config: testAccOptionGroupConfig_sqlServerEEOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -291,7 +291,7 @@ func TestAccRDSOptionGroup_sqlServerOptionsUpdate(t *testing.T) { ImportStateVerifyIgnore: []string{"name_prefix"}, }, { - Config: testAccOptionGroupSQLServerEEOptions_update(rName), + Config: testAccOptionGroupConfig_sqlServerEEOptionsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -314,7 +314,7 @@ func TestAccRDSOptionGroup_oracleOptionsUpdate(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupOracleEEOptionSettings(rName, "13.2.0.0.v2"), + Config: testAccOptionGroupConfig_oracleEEOptionSettings(rName, "13.2.0.0.v2"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -330,7 +330,7 @@ func TestAccRDSOptionGroup_oracleOptionsUpdate(t *testing.T) { ImportStateVerifyIgnore: []string{"name_prefix", "option"}, }, { - Config: testAccOptionGroupOracleEEOptionSettings(rName, "13.3.0.0.v2"), + Config: testAccOptionGroupConfig_oracleEEOptionSettings(rName, "13.3.0.0.v2"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -355,7 +355,7 @@ func TestAccRDSOptionGroup_OptionOptionSettings_multipleNonDefault(t *testing.T) CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupOptionOptionSettingsMultipleConfig(rName, "example1"), + Config: testAccOptionGroupConfig_settingsMultiple(rName, "example1"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &optionGroup1), resource.TestCheckResourceAttr(resourceName, "option.#", "1"), @@ -368,7 +368,7 @@ func TestAccRDSOptionGroup_OptionOptionSettings_multipleNonDefault(t *testing.T) ImportStateVerifyIgnore: []string{"name_prefix"}, }, { - Config: testAccOptionGroupOptionOptionSettingsMultipleConfig(rName, "example1,example2"), + Config: testAccOptionGroupConfig_settingsMultiple(rName, "example1,example2"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &optionGroup2), resource.TestCheckResourceAttr(resourceName, "option.#", "1"), @@ -390,7 +390,7 @@ func TestAccRDSOptionGroup_multipleOptions(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupMultipleOptions(rName), + Config: testAccOptionGroupConfig_multipleOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -419,7 +419,7 @@ func TestAccRDSOptionGroup_tags(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupTags1Config(rName, "key1", "value1"), + Config: testAccOptionGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &optionGroup1), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -433,7 +433,7 @@ func TestAccRDSOptionGroup_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"name_prefix"}, }, { - Config: testAccOptionGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccOptionGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &optionGroup2), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -442,7 +442,7 @@ func TestAccRDSOptionGroup_tags(t *testing.T) { ), }, { - Config: testAccOptionGroupTags1Config(rName, "key2", "value2"), + Config: testAccOptionGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &optionGroup3), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -466,7 +466,7 @@ func TestAccRDSOptionGroup_Tags_withOptions(t *testing.T) { CheckDestroy: testAccCheckOptionGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccOptionGroupTagsWithOption1Config(rName, "key1", "value1"), + Config: testAccOptionGroupConfig_tagsOption1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &optionGroup1), resource.TestCheckResourceAttr(resourceName, "option.#", "1"), @@ -481,7 +481,7 @@ func TestAccRDSOptionGroup_Tags_withOptions(t *testing.T) { ImportStateVerifyIgnore: []string{"name_prefix"}, }, { - Config: testAccOptionGroupTagsWithOption2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccOptionGroupConfig_tagsOption2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &optionGroup2), resource.TestCheckResourceAttr(resourceName, "option.#", "1"), @@ -491,7 +491,7 @@ func TestAccRDSOptionGroup_Tags_withOptions(t *testing.T) { ), }, { - Config: testAccOptionGroupTagsWithOption1Config(rName, "key2", "value2"), + Config: testAccOptionGroupConfig_tagsOption1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckOptionGroupExists(resourceName, &optionGroup3), resource.TestCheckResourceAttr(resourceName, "option.#", "1"), @@ -608,7 +608,7 @@ func testAccCheckOptionGroupDestroy(s *terraform.State) error { return nil } -func testAccOptionGroupBasicTimeoutBlockConfig(rName string) string { +func testAccOptionGroupConfig_timeoutBlock(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -627,7 +627,7 @@ resource "aws_db_option_group" "test" { `, rName) } -func testAccOptionGroupBasicConfig(rName string) string { +func testAccOptionGroupConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -641,7 +641,7 @@ resource "aws_db_option_group" "test" { `, rName) } -func testAccOptionGroupBasicDestroyConfig(rName string) string { +func testAccOptionGroupConfig_destroy(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -682,7 +682,7 @@ resource "aws_db_option_group" "test" { `, mySQLPreferredInstanceClasses, rName) } -func testAccOptionGroupOptionSettings(rName string) string { +func testAccOptionGroupConfig_optionSettings(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "oracle-ee" @@ -706,7 +706,7 @@ resource "aws_db_option_group" "test" { `, rName) } -func testAccOptionGroupOptionSettingsIAMRole(rName string) string { +func testAccOptionGroupConfig_optionSettingsIAMRole(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -748,7 +748,7 @@ resource "aws_db_option_group" "test" { `, rName) } -func testAccOptionGroupOptionSettings_update(rName string) string { +func testAccOptionGroupConfig_optionSettingsUpdate(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "oracle-ee" @@ -772,7 +772,7 @@ resource "aws_db_option_group" "test" { `, rName) } -func testAccOptionGroupSQLServerEEOptions(rName string) string { +func testAccOptionGroupConfig_sqlServerEEOptions(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "sqlserver-ee" @@ -787,7 +787,7 @@ resource "aws_db_option_group" "test" { `, rName) } -func testAccOptionGroupSQLServerEEOptions_update(rName string) string { +func testAccOptionGroupConfig_sqlServerEEOptionsUpdate(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "sqlserver-ee" @@ -806,7 +806,7 @@ resource "aws_db_option_group" "test" { `, rName) } -func testAccOptionGroupOracleEEOptionSettings(rName, optionVersion string) string { +func testAccOptionGroupConfig_oracleEEOptionSettings(rName, optionVersion string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "oracle-ee" @@ -848,7 +848,7 @@ resource "aws_db_option_group" "test" { `, rName, optionVersion) } -func testAccOptionGroupMultipleOptions(rName string) string { +func testAccOptionGroupConfig_multipleOptions(rName string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "oracle-ee" @@ -871,7 +871,7 @@ resource "aws_db_option_group" "test" { `, rName) } -const testAccOptionGroup_namePrefix = ` +const testAccOptionGroupConfig_namePrefix = ` data "aws_rds_engine_version" "default" { engine = "mysql" } @@ -884,7 +884,7 @@ resource "aws_db_option_group" "test" { } ` -const testAccOptionGroup_generatedName = ` +const testAccOptionGroupConfig_generatedName = ` data "aws_rds_engine_version" "default" { engine = "mysql" } @@ -896,7 +896,7 @@ resource "aws_db_option_group" "test" { } ` -func testAccOptionGroupOptionGroupDescriptionConfig(rName, optionGroupDescription string) string { +func testAccOptionGroupConfig_description(rName, optionGroupDescription string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -911,7 +911,7 @@ resource "aws_db_option_group" "test" { `, rName, optionGroupDescription) } -func testAccOptionGroupOptionOptionSettingsMultipleConfig(rName, value string) string { +func testAccOptionGroupConfig_settingsMultiple(rName, value string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -944,7 +944,7 @@ resource "aws_db_option_group" "test" { `, rName, value) } -func testAccOptionGroupTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccOptionGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -962,7 +962,7 @@ resource "aws_db_option_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccOptionGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccOptionGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -981,7 +981,7 @@ resource "aws_db_option_group" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccOptionGroupTagsWithOption1Config(rName, tagKey1, tagValue1 string) string { +func testAccOptionGroupConfig_tagsOption1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" @@ -1008,7 +1008,7 @@ resource "aws_db_option_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccOptionGroupTagsWithOption2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccOptionGroupConfig_tagsOption2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" diff --git a/internal/service/rds/parameter_group_test.go b/internal/service/rds/parameter_group_test.go index d50218b5d74..a0f3b2c5bd4 100644 --- a/internal/service/rds/parameter_group_test.go +++ b/internal/service/rds/parameter_group_test.go @@ -29,7 +29,7 @@ func TestAccRDSParameterGroup_basic(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig(groupName), + Config: testAccParameterGroupConfig_basic(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, groupName), @@ -56,7 +56,7 @@ func TestAccRDSParameterGroup_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupAddParametersConfig(groupName), + Config: testAccParameterGroupConfig_addParameters(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, groupName), @@ -86,7 +86,7 @@ func TestAccRDSParameterGroup_basic(t *testing.T) { ), }, { - Config: testAccParameterGroupConfig(groupName), + Config: testAccParameterGroupConfig_basic(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, groupName), @@ -121,7 +121,7 @@ func TestAccRDSParameterGroup_caseWithMixedParameters(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupCaseWithMixedParametersConfig(groupName), + Config: testAccParameterGroupConfig_caseWithMixedParameters(groupName), Check: resource.ComposeTestCheckFunc(), }, }, @@ -140,7 +140,7 @@ func TestAccRDSParameterGroup_limit(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: createParameterGroupsExceedDefaultLimit(groupName), + Config: testAccParameterGroupConfig_exceedDefaultLimit(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, groupName), @@ -319,7 +319,7 @@ func TestAccRDSParameterGroup_limit(t *testing.T) { ImportStateVerify: true, }, { - Config: updateParameterGroupsExceedDefaultLimit(groupName), + Config: testAccParameterGroupConfig_updateExceedDefaultLimit(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, groupName), @@ -508,7 +508,7 @@ func TestAccRDSParameterGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig(groupName), + Config: testAccParameterGroupConfig_basic(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParamaterGroupDisappears(&v), @@ -570,7 +570,7 @@ func TestAccRDSParameterGroup_withApplyMethod(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupWithApplyMethodConfig(groupName), + Config: testAccParameterGroupConfig_applyMethod(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, groupName), @@ -610,7 +610,7 @@ func TestAccRDSParameterGroup_only(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupOnlyConfig(groupName), + Config: testAccParameterGroupConfig_only(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, groupName), @@ -639,7 +639,7 @@ func TestAccRDSParameterGroup_matchDefault(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupIncludeDefaultConfig(groupName), + Config: testAccParameterGroupConfig_includeDefault(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", groupName), @@ -668,7 +668,7 @@ func TestAccRDSParameterGroup_updateParameters(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupUpdateParametersInitialConfig(groupName), + Config: testAccParameterGroupConfig_updateParametersInitial(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, groupName), @@ -694,7 +694,7 @@ func TestAccRDSParameterGroup_updateParameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupUpdateParametersUpdatedConfig(groupName), + Config: testAccParameterGroupConfig_updateParametersUpdated(groupName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, groupName), @@ -728,7 +728,7 @@ func TestAccRDSParameterGroup_caseParameters(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupUpperCaseConfig(rName, "Max_connections"), + Config: testAccParameterGroupConfig_upperCase(rName, "Max_connections"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), testAccCheckParameterGroupAttributes(&v, rName), @@ -746,7 +746,7 @@ func TestAccRDSParameterGroup_caseParameters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupUpperCaseConfig(rName, "max_connections"), + Config: testAccParameterGroupConfig_upperCase(rName, "max_connections"), }, }, }) @@ -1116,7 +1116,7 @@ func testAccCheckParameterNotUserDefined(rName, paramName string) resource.TestC } } -func testAccParameterGroupConfig(rName string) string { +func testAccParameterGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1140,7 +1140,7 @@ resource "aws_db_parameter_group" "test" { `, rName) } -func testAccParameterGroupCaseWithMixedParametersConfig(rName string) string { +func testAccParameterGroupConfig_caseWithMixedParameters(rName string) string { return acctest.ConfigCompose(testAccInstanceConfig_orderableClassMySQL(), fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1185,7 +1185,7 @@ resource "aws_db_parameter_group" "test" { `, rName)) } -func testAccParameterGroupWithApplyMethodConfig(rName string) string { +func testAccParameterGroupConfig_applyMethod(rName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1209,7 +1209,7 @@ resource "aws_db_parameter_group" "test" { `, rName) } -func testAccParameterGroupAddParametersConfig(rName string) string { +func testAccParameterGroupConfig_addParameters(rName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1243,7 +1243,7 @@ resource "aws_db_parameter_group" "test" { `, rName) } -func testAccParameterGroupOnlyConfig(rName string) string { +func testAccParameterGroupConfig_only(rName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1253,7 +1253,7 @@ resource "aws_db_parameter_group" "test" { `, rName) } -func createParameterGroupsExceedDefaultLimit(rName string) string { +func testAccParameterGroupConfig_exceedDefaultLimit(rName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1473,7 +1473,7 @@ resource "aws_db_parameter_group" "test" { `, rName) } -func updateParameterGroupsExceedDefaultLimit(rName string) string { +func testAccParameterGroupConfig_updateExceedDefaultLimit(rName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1693,7 +1693,7 @@ resource "aws_db_parameter_group" "test" { `, rName) } -func testAccParameterGroupIncludeDefaultConfig(rName string) string { +func testAccParameterGroupConfig_includeDefault(rName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1708,7 +1708,7 @@ resource "aws_db_parameter_group" "test" { `, rName) } -func testAccParameterGroupUpdateParametersInitialConfig(rName string) string { +func testAccParameterGroupConfig_updateParametersInitial(rName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1732,7 +1732,7 @@ resource "aws_db_parameter_group" "test" { `, rName) } -func testAccParameterGroupUpdateParametersUpdatedConfig(rName string) string { +func testAccParameterGroupConfig_updateParametersUpdated(rName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q @@ -1756,7 +1756,7 @@ resource "aws_db_parameter_group" "test" { `, rName) } -func testAccParameterGroupUpperCaseConfig(rName, paramName string) string { +func testAccParameterGroupConfig_upperCase(rName, paramName string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { name = %[1]q diff --git a/internal/service/rds/proxy.go b/internal/service/rds/proxy.go index 634b0fabffe..12bd34a6ff0 100644 --- a/internal/service/rds/proxy.go +++ b/internal/service/rds/proxy.go @@ -130,7 +130,7 @@ func resourceProxyCreate(d *schema.ResourceData, meta interface{}) error { tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) input := rds.CreateDBProxyInput{ - Auth: expandDbProxyAuth(d.Get("auth").(*schema.Set).List()), + Auth: expandProxyAuth(d.Get("auth").(*schema.Set).List()), DBProxyName: aws.String(d.Get("name").(string)), EngineFamily: aws.String(d.Get("engine_family").(string)), RoleArn: aws.String(d.Get("role_arn").(string)), @@ -188,7 +188,7 @@ func resourceProxyRead(d *schema.ResourceData, meta interface{}) error { } d.Set("arn", dbProxy.DBProxyArn) - d.Set("auth", flattenDbProxyAuths(dbProxy.Auth)) + d.Set("auth", flattenProxyAuths(dbProxy.Auth)) d.Set("name", dbProxy.DBProxyName) d.Set("debug_logging", dbProxy.DebugLogging) d.Set("engine_family", dbProxy.EngineFamily) @@ -225,7 +225,7 @@ func resourceProxyUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChangesExcept("tags", "tags_all") { oName, nName := d.GetChange("name") input := &rds.ModifyDBProxyInput{ - Auth: expandDbProxyAuth(d.Get("auth").(*schema.Set).List()), + Auth: expandProxyAuth(d.Get("auth").(*schema.Set).List()), DBProxyName: aws.String(oName.(string)), DebugLogging: aws.Bool(d.Get("debug_logging").(bool)), NewDBProxyName: aws.String(nName.(string)), @@ -291,7 +291,7 @@ func resourceProxyDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func expandDbProxyAuth(l []interface{}) []*rds.UserAuthConfig { +func expandProxyAuth(l []interface{}) []*rds.UserAuthConfig { if len(l) == 0 { return nil } @@ -333,7 +333,7 @@ func expandDbProxyAuth(l []interface{}) []*rds.UserAuthConfig { return userAuthConfigs } -func flattenDbProxyAuth(userAuthConfig *rds.UserAuthConfigInfo) map[string]interface{} { +func flattenProxyAuth(userAuthConfig *rds.UserAuthConfigInfo) map[string]interface{} { m := make(map[string]interface{}) m["auth_scheme"] = aws.StringValue(userAuthConfig.AuthScheme) @@ -345,10 +345,10 @@ func flattenDbProxyAuth(userAuthConfig *rds.UserAuthConfigInfo) map[string]inter return m } -func flattenDbProxyAuths(userAuthConfigs []*rds.UserAuthConfigInfo) []interface{} { +func flattenProxyAuths(userAuthConfigs []*rds.UserAuthConfigInfo) []interface{} { s := []interface{}{} for _, v := range userAuthConfigs { - s = append(s, flattenDbProxyAuth(v)) + s = append(s, flattenProxyAuth(v)) } return s } diff --git a/internal/service/rds/proxy_data_source.go b/internal/service/rds/proxy_data_source.go index 61e7728d919..5c64aadfc81 100644 --- a/internal/service/rds/proxy_data_source.go +++ b/internal/service/rds/proxy_data_source.go @@ -102,7 +102,7 @@ func dataSourceProxyRead(d *schema.ResourceData, meta interface{}) error { d.SetId(name) d.Set("arn", dbProxy.DBProxyArn) - d.Set("auth", flattenDbProxyAuths(dbProxy.Auth)) + d.Set("auth", flattenProxyAuths(dbProxy.Auth)) d.Set("debug_logging", dbProxy.DebugLogging) d.Set("endpoint", dbProxy.Endpoint) d.Set("engine_family", dbProxy.EngineFamily) diff --git a/internal/service/rds/proxy_data_source_test.go b/internal/service/rds/proxy_data_source_test.go index e12cb7bf575..64e6cc82f7a 100644 --- a/internal/service/rds/proxy_data_source_test.go +++ b/internal/service/rds/proxy_data_source_test.go @@ -25,7 +25,7 @@ func TestAccRDSProxyDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccProxyDataSourceConfig(rName), + Config: testAccProxyDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "auth", resourceName, "auth"), @@ -44,7 +44,7 @@ func TestAccRDSProxyDataSource_basic(t *testing.T) { }) } -func testAccProxyDataSourceConfig(rName string) string { +func testAccProxyDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` # Secrets Manager setup diff --git a/internal/service/rds/proxy_default_target_group.go b/internal/service/rds/proxy_default_target_group.go index f82c86eca55..5da95a3a3ac 100644 --- a/internal/service/rds/proxy_default_target_group.go +++ b/internal/service/rds/proxy_default_target_group.go @@ -118,7 +118,7 @@ func resourceProxyDefaultTargetGroupRead(d *schema.ResourceData, meta interface{ d.Set("name", tg.TargetGroupName) cpc := tg.ConnectionPoolConfig - d.Set("connection_pool_config", flattenDbProxyTargetGroupConnectionPoolConfig(cpc)) + d.Set("connection_pool_config", flattenProxyTargetGroupConnectionPoolConfig(cpc)) return nil } @@ -141,7 +141,7 @@ func resourceProxyDefaultTargetGroupCreateUpdate(d *schema.ResourceData, meta in } if v, ok := d.GetOk("connection_pool_config"); ok { - params.ConnectionPoolConfig = expandDbProxyConnectionPoolConfig(v.([]interface{})) + params.ConnectionPoolConfig = expandProxyConnectionPoolConfig(v.([]interface{})) } log.Printf("[DEBUG] Update DB Proxy default target group: %#v", params) @@ -165,7 +165,7 @@ func resourceProxyDefaultTargetGroupCreateUpdate(d *schema.ResourceData, meta in return resourceProxyDefaultTargetGroupRead(d, meta) } -func expandDbProxyConnectionPoolConfig(configs []interface{}) *rds.ConnectionPoolConfiguration { +func expandProxyConnectionPoolConfig(configs []interface{}) *rds.ConnectionPoolConfiguration { if len(configs) < 1 { return nil } @@ -183,7 +183,7 @@ func expandDbProxyConnectionPoolConfig(configs []interface{}) *rds.ConnectionPoo return result } -func flattenDbProxyTargetGroupConnectionPoolConfig(cpc *rds.ConnectionPoolConfigurationInfo) []interface{} { +func flattenProxyTargetGroupConnectionPoolConfig(cpc *rds.ConnectionPoolConfigurationInfo) []interface{} { if cpc == nil { return []interface{}{} } diff --git a/internal/service/rds/proxy_default_target_group_test.go b/internal/service/rds/proxy_default_target_group_test.go index 0641ffa6a40..6b8a697efdb 100644 --- a/internal/service/rds/proxy_default_target_group_test.go +++ b/internal/service/rds/proxy_default_target_group_test.go @@ -32,7 +32,7 @@ func TestAccRDSProxyDefaultTargetGroup_basic(t *testing.T) { CheckDestroy: testAccCheckProxyTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyDefaultTargetGroupConfig_Basic(rName), + Config: testAccProxyDefaultTargetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "rds", regexp.MustCompile(`target-group:.+`)), @@ -71,7 +71,7 @@ func TestAccRDSProxyDefaultTargetGroup_emptyConnectionPool(t *testing.T) { CheckDestroy: testAccCheckProxyTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyDefaultTargetGroupConfig_EmptyConnectionPoolConfig(rName), + Config: testAccProxyDefaultTargetGroupConfig_emptyConnectionPoolConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "rds", regexp.MustCompile(`target-group:.+`)), @@ -110,7 +110,7 @@ func TestAccRDSProxyDefaultTargetGroup_connectionBorrowTimeout(t *testing.T) { CheckDestroy: testAccCheckProxyTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyDefaultTargetGroupConfig_ConnectionBorrowTimeout(rName, 120), + Config: testAccProxyDefaultTargetGroupConfig_connectionBorrowTimeout(rName, 120), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.connection_borrow_timeout", "120"), @@ -122,7 +122,7 @@ func TestAccRDSProxyDefaultTargetGroup_connectionBorrowTimeout(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyDefaultTargetGroupConfig_ConnectionBorrowTimeout(rName, 90), + Config: testAccProxyDefaultTargetGroupConfig_connectionBorrowTimeout(rName, 90), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.connection_borrow_timeout", "90"), @@ -148,7 +148,7 @@ func TestAccRDSProxyDefaultTargetGroup_initQuery(t *testing.T) { CheckDestroy: testAccCheckProxyTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyDefaultTargetGroupConfig_InitQuery(rName, "SET x=1, y=2"), + Config: testAccProxyDefaultTargetGroupConfig_initQuery(rName, "SET x=1, y=2"), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.init_query", "SET x=1, y=2"), @@ -160,7 +160,7 @@ func TestAccRDSProxyDefaultTargetGroup_initQuery(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyDefaultTargetGroupConfig_InitQuery(rName, "SET a=2, b=1"), + Config: testAccProxyDefaultTargetGroupConfig_initQuery(rName, "SET a=2, b=1"), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.init_query", "SET a=2, b=1"), @@ -186,7 +186,7 @@ func TestAccRDSProxyDefaultTargetGroup_maxConnectionsPercent(t *testing.T) { CheckDestroy: testAccCheckProxyTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyDefaultTargetGroupConfig_MaxConnectionsPercent(rName, 100), + Config: testAccProxyDefaultTargetGroupConfig_maxConnectionsPercent(rName, 100), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.max_connections_percent", "100"), @@ -198,7 +198,7 @@ func TestAccRDSProxyDefaultTargetGroup_maxConnectionsPercent(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyDefaultTargetGroupConfig_MaxConnectionsPercent(rName, 75), + Config: testAccProxyDefaultTargetGroupConfig_maxConnectionsPercent(rName, 75), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.max_connections_percent", "75"), @@ -224,7 +224,7 @@ func TestAccRDSProxyDefaultTargetGroup_maxIdleConnectionsPercent(t *testing.T) { CheckDestroy: testAccCheckProxyTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyDefaultTargetGroupConfig_MaxIdleConnectionsPercent(rName, 50), + Config: testAccProxyDefaultTargetGroupConfig_maxIdleConnectionsPercent(rName, 50), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.max_idle_connections_percent", "50"), @@ -236,7 +236,7 @@ func TestAccRDSProxyDefaultTargetGroup_maxIdleConnectionsPercent(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyDefaultTargetGroupConfig_MaxIdleConnectionsPercent(rName, 33), + Config: testAccProxyDefaultTargetGroupConfig_maxIdleConnectionsPercent(rName, 33), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.max_idle_connections_percent", "33"), @@ -263,7 +263,7 @@ func TestAccRDSProxyDefaultTargetGroup_sessionPinningFilters(t *testing.T) { CheckDestroy: testAccCheckProxyTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyDefaultTargetGroupConfig_Basic(rName), + Config: testAccProxyDefaultTargetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.session_pinning_filters.#", "0"), @@ -275,7 +275,7 @@ func TestAccRDSProxyDefaultTargetGroup_sessionPinningFilters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyDefaultTargetGroupConfig_SessionPinningFilters(rName, sessionPinningFilters), + Config: testAccProxyDefaultTargetGroupConfig_sessionPinningFilters(rName, sessionPinningFilters), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetGroupExists(resourceName, &dbProxyTargetGroup), resource.TestCheckResourceAttr(resourceName, "connection_pool_config.0.session_pinning_filters.#", "1"), @@ -302,7 +302,7 @@ func TestAccRDSProxyDefaultTargetGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckProxyTargetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyDefaultTargetGroupConfig_Basic(rName), + Config: testAccProxyDefaultTargetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &v), // DB Proxy default Target Group implicitly exists so it cannot be removed. @@ -496,7 +496,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccProxyDefaultTargetGroupConfig_Basic(rName string) string { +func testAccProxyDefaultTargetGroupConfig_basic(rName string) string { return testAccProxyDefaultTargetGroupBaseConfig(rName) + ` resource "aws_db_proxy_default_target_group" "test" { db_proxy_name = aws_db_proxy.test.name @@ -504,7 +504,7 @@ resource "aws_db_proxy_default_target_group" "test" { ` } -func testAccProxyDefaultTargetGroupConfig_EmptyConnectionPoolConfig(rName string) string { +func testAccProxyDefaultTargetGroupConfig_emptyConnectionPoolConfig(rName string) string { return testAccProxyDefaultTargetGroupBaseConfig(rName) + ` resource "aws_db_proxy_default_target_group" "test" { db_proxy_name = aws_db_proxy.test.name @@ -515,7 +515,7 @@ resource "aws_db_proxy_default_target_group" "test" { ` } -func testAccProxyDefaultTargetGroupConfig_ConnectionBorrowTimeout(rName string, connectionBorrowTimeout int) string { +func testAccProxyDefaultTargetGroupConfig_connectionBorrowTimeout(rName string, connectionBorrowTimeout int) string { return testAccProxyDefaultTargetGroupBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_default_target_group" "test" { db_proxy_name = aws_db_proxy.test.name @@ -527,7 +527,7 @@ resource "aws_db_proxy_default_target_group" "test" { `, rName, connectionBorrowTimeout) } -func testAccProxyDefaultTargetGroupConfig_InitQuery(rName, initQuery string) string { +func testAccProxyDefaultTargetGroupConfig_initQuery(rName, initQuery string) string { return testAccProxyDefaultTargetGroupBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_default_target_group" "test" { db_proxy_name = aws_db_proxy.test.name @@ -539,7 +539,7 @@ resource "aws_db_proxy_default_target_group" "test" { `, rName, initQuery) } -func testAccProxyDefaultTargetGroupConfig_MaxConnectionsPercent(rName string, maxConnectionsPercent int) string { +func testAccProxyDefaultTargetGroupConfig_maxConnectionsPercent(rName string, maxConnectionsPercent int) string { return testAccProxyDefaultTargetGroupBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_default_target_group" "test" { db_proxy_name = aws_db_proxy.test.name @@ -551,7 +551,7 @@ resource "aws_db_proxy_default_target_group" "test" { `, rName, maxConnectionsPercent) } -func testAccProxyDefaultTargetGroupConfig_MaxIdleConnectionsPercent(rName string, maxIdleConnectionsPercent int) string { +func testAccProxyDefaultTargetGroupConfig_maxIdleConnectionsPercent(rName string, maxIdleConnectionsPercent int) string { return testAccProxyDefaultTargetGroupBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_default_target_group" "test" { db_proxy_name = aws_db_proxy.test.name @@ -563,7 +563,7 @@ resource "aws_db_proxy_default_target_group" "test" { `, rName, maxIdleConnectionsPercent) } -func testAccProxyDefaultTargetGroupConfig_SessionPinningFilters(rName, sessionPinningFilters string) string { +func testAccProxyDefaultTargetGroupConfig_sessionPinningFilters(rName, sessionPinningFilters string) string { return testAccProxyDefaultTargetGroupBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_default_target_group" "test" { db_proxy_name = aws_db_proxy.test.name diff --git a/internal/service/rds/proxy_endpoint_test.go b/internal/service/rds/proxy_endpoint_test.go index 09758c00af1..f2184664bcd 100644 --- a/internal/service/rds/proxy_endpoint_test.go +++ b/internal/service/rds/proxy_endpoint_test.go @@ -31,7 +31,7 @@ func TestAccRDSProxyEndpoint_basic(t *testing.T) { CheckDestroy: testAccCheckProxyEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyEndpointConfig(rName), + Config: testAccProxyEndpointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyEndpointExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "db_proxy_endpoint_name", rName), @@ -73,7 +73,7 @@ func TestAccRDSProxyEndpoint_targetRole(t *testing.T) { CheckDestroy: testAccCheckProxyEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyEndpointTargetRoleConfig(rName), + Config: testAccProxyEndpointConfig_targetRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyEndpointExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "target_role", "READ_ONLY"), @@ -104,7 +104,7 @@ func TestAccRDSProxyEndpoint_vpcSecurityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckProxyEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyEndpointVPCSecurityGroupIds1Config(rName), + Config: testAccProxyEndpointConfig_vpcSecurityGroupIDs1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyEndpointExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "1"), @@ -117,7 +117,7 @@ func TestAccRDSProxyEndpoint_vpcSecurityGroupIDs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyEndpointVPCSecurityGroupIds2Config(rName), + Config: testAccProxyEndpointConfig_vpcSecurityGroupIDs2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyEndpointExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "2"), @@ -145,7 +145,7 @@ func TestAccRDSProxyEndpoint_tags(t *testing.T) { CheckDestroy: testAccCheckProxyEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyEndpointTags1Config(rName, "key1", "value1"), + Config: testAccProxyEndpointConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckProxyEndpointExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -158,7 +158,7 @@ func TestAccRDSProxyEndpoint_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyEndpointTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccProxyEndpointConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckProxyEndpointExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -167,7 +167,7 @@ func TestAccRDSProxyEndpoint_tags(t *testing.T) { ), }, { - Config: testAccProxyEndpointTags1Config(rName, "key2", "value2"), + Config: testAccProxyEndpointConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckProxyEndpointExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -193,7 +193,7 @@ func TestAccRDSProxyEndpoint_disappears(t *testing.T) { CheckDestroy: testAccCheckProxyEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyEndpointConfig(rName), + Config: testAccProxyEndpointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyEndpointExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceProxyEndpoint(), resourceName), @@ -219,7 +219,7 @@ func TestAccRDSProxyEndpoint_Disappears_proxy(t *testing.T) { CheckDestroy: testAccCheckProxyEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyEndpointConfig(rName), + Config: testAccProxyEndpointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyEndpointExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceProxy(), "aws_db_proxy.test"), @@ -412,7 +412,7 @@ resource "aws_db_proxy" "test" { `, rName) } -func testAccProxyEndpointConfig(rName string) string { +func testAccProxyEndpointConfig_basic(rName string) string { return testAccProxyEndpointBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_endpoint" "test" { db_proxy_name = aws_db_proxy.test.name @@ -422,7 +422,7 @@ resource "aws_db_proxy_endpoint" "test" { `, rName) } -func testAccProxyEndpointTargetRoleConfig(rName string) string { +func testAccProxyEndpointConfig_targetRole(rName string) string { return testAccProxyEndpointBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_endpoint" "test" { db_proxy_name = aws_db_proxy.test.name @@ -433,7 +433,7 @@ resource "aws_db_proxy_endpoint" "test" { `, rName) } -func testAccProxyEndpointVPCSecurityGroupIds1Config(rName string) string { +func testAccProxyEndpointConfig_vpcSecurityGroupIDs1(rName string) string { return testAccProxyEndpointBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_endpoint" "test" { db_proxy_name = aws_db_proxy.test.name @@ -444,7 +444,7 @@ resource "aws_db_proxy_endpoint" "test" { `, rName) } -func testAccProxyEndpointVPCSecurityGroupIds2Config(rName string) string { +func testAccProxyEndpointConfig_vpcSecurityGroupIDs2(rName string) string { return testAccProxyEndpointBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_endpoint" "test" { db_proxy_name = aws_db_proxy.test.name @@ -460,7 +460,7 @@ resource "aws_security_group" "test2" { `, rName) } -func testAccProxyEndpointTags1Config(rName, key1, value1 string) string { +func testAccProxyEndpointConfig_tags1(rName, key1, value1 string) string { return testAccProxyEndpointBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_endpoint" "test" { db_proxy_name = aws_db_proxy.test.name @@ -474,7 +474,7 @@ resource "aws_db_proxy_endpoint" "test" { `, rName, key1, value1) } -func testAccProxyEndpointTags2Config(rName, key1, value1, key2, value2 string) string { +func testAccProxyEndpointConfig_tags2(rName, key1, value1, key2, value2 string) string { return testAccProxyEndpointBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy_endpoint" "test" { db_proxy_name = aws_db_proxy.test.name diff --git a/internal/service/rds/proxy_target.go b/internal/service/rds/proxy_target.go index 909b300acc0..be969bd2aaa 100644 --- a/internal/service/rds/proxy_target.go +++ b/internal/service/rds/proxy_target.go @@ -4,12 +4,14 @@ import ( "fmt" "log" "strings" + "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func ResourceProxyTarget() *schema.Resource { @@ -17,41 +19,36 @@ func ResourceProxyTarget() *schema.Resource { Create: resourceProxyTargetCreate, Read: resourceProxyTargetRead, Delete: resourceProxyTargetDelete, + Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ - "db_proxy_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validIdentifier, - }, - "target_group_name": { + "db_cluster_identifier": { Type: schema.TypeString, - Required: true, + Optional: true, ForceNew: true, ValidateFunc: validIdentifier, - }, - "db_instance_identifier": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, ExactlyOneOf: []string{ "db_instance_identifier", "db_cluster_identifier", }, - ValidateFunc: validIdentifier, }, - "db_cluster_identifier": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, + "db_instance_identifier": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validIdentifier, ExactlyOneOf: []string{ "db_instance_identifier", "db_cluster_identifier", }, + }, + "db_proxy_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, ValidateFunc: validIdentifier, }, "endpoint": { @@ -70,6 +67,12 @@ func ResourceProxyTarget() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "target_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validIdentifier, + }, "tracked_cluster_id": { Type: schema.TypeString, Computed: true, @@ -87,27 +90,30 @@ func resourceProxyTargetCreate(d *schema.ResourceData, meta interface{}) error { dbProxyName := d.Get("db_proxy_name").(string) targetGroupName := d.Get("target_group_name").(string) - - params := rds.RegisterDBProxyTargetsInput{ + input := &rds.RegisterDBProxyTargetsInput{ DBProxyName: aws.String(dbProxyName), TargetGroupName: aws.String(targetGroupName), } - if v, ok := d.GetOk("db_instance_identifier"); ok { - params.DBInstanceIdentifiers = []*string{aws.String(v.(string))} + if v, ok := d.GetOk("db_cluster_identifier"); ok { + input.DBClusterIdentifiers = aws.StringSlice([]string{v.(string)}) } - if v, ok := d.GetOk("db_cluster_identifier"); ok { - params.DBClusterIdentifiers = []*string{aws.String(v.(string))} + if v, ok := d.GetOk("db_instance_identifier"); ok { + input.DBInstanceIdentifiers = aws.StringSlice([]string{v.(string)}) } - resp, err := conn.RegisterDBProxyTargets(¶ms) + outputRaw, err := tfresource.RetryWhenAWSErrMessageContains(5*time.Minute, + func() (interface{}, error) { + return conn.RegisterDBProxyTargets(input) + }, + rds.ErrCodeInvalidDBInstanceStateFault, "CREATING") if err != nil { return fmt.Errorf("error registering RDS DB Proxy (%s/%s) Target: %w", dbProxyName, targetGroupName, err) } - dbProxyTarget := resp.DBProxyTargets[0] + dbProxyTarget := outputRaw.(*rds.RegisterDBProxyTargetsOutput).DBProxyTargets[0] d.SetId(strings.Join([]string{dbProxyName, targetGroupName, aws.StringValue(dbProxyTarget.Type), aws.StringValue(dbProxyTarget.RdsResourceId)}, "/")) diff --git a/internal/service/rds/proxy_target_test.go b/internal/service/rds/proxy_target_test.go index 23a26fca9b1..fcb87f353be 100644 --- a/internal/service/rds/proxy_target_test.go +++ b/internal/service/rds/proxy_target_test.go @@ -30,7 +30,7 @@ func TestAccRDSProxyTarget_instance(t *testing.T) { CheckDestroy: testAccCheckProxyTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyTargetConfig_Instance(rName), + Config: testAccProxyTargetConfig_instance(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetExists(resourceName, &dbProxyTarget), resource.TestCheckResourceAttrPair(resourceName, "endpoint", "aws_db_instance.test", "address"), @@ -66,7 +66,7 @@ func TestAccRDSProxyTarget_cluster(t *testing.T) { CheckDestroy: testAccCheckProxyTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyTargetConfig_Cluster(rName), + Config: testAccProxyTargetConfig_cluster(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetExists(resourceName, &dbProxyTarget), resource.TestCheckResourceAttr(resourceName, "endpoint", ""), @@ -102,7 +102,7 @@ func TestAccRDSProxyTarget_disappears(t *testing.T) { CheckDestroy: testAccCheckProxyTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyTargetConfig_Instance(rName), + Config: testAccProxyTargetConfig_instance(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyTargetExists(resourceName, &dbProxyTarget), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceProxyTarget(), resourceName), @@ -189,14 +189,14 @@ func testAccCheckProxyTargetExists(n string, v *rds.DBProxyTarget) resource.Test } func testAccProxyTargetBaseConfig(rName string) string { - return fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ aws_secretsmanager_secret_version.test, aws_iam_role_policy.test ] - name = "%[1]s" + name = %[1]q debug_logging = false engine_family = "MYSQL" idle_client_timeout = 1800 @@ -213,22 +213,23 @@ resource "aws_db_proxy" "test" { } tags = { - Name = "%[1]s" + Name = %[1]q } } resource "aws_db_subnet_group" "test" { - name = "%[1]s" + name = %[1]q subnet_ids = aws_subnet.test.*.id + tags = { - Name = "%[1]s" + Name = %[1]q } } # Secrets Manager setup resource "aws_secretsmanager_secret" "test" { - name = "%[1]s" + name = %[1]q recovery_window_in_days = 0 } @@ -240,7 +241,7 @@ resource "aws_secretsmanager_secret_version" "test" { # IAM setup resource "aws_iam_role" "test" { - name = "%[1]s" + name = %[1]q assume_role_policy = data.aws_iam_policy_document.assume.json } @@ -277,25 +278,8 @@ data "aws_iam_policy_document" "test" { # VPC setup -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - -resource "aws_vpc" "test" { - cidr_block = "10.0.0.0/16" - - tags = { - Name = "%[1]s" - } -} - resource "aws_security_group" "test" { - name = "%[1]s" + name = %[1]q vpc_id = aws_vpc.test.id ingress { @@ -304,23 +288,16 @@ resource "aws_security_group" "test" { protocol = "tcp" self = true } -} - -resource "aws_subnet" "test" { - count = 2 - cidr_block = cidrsubnet(aws_vpc.test.cidr_block, 8, count.index) - availability_zone = data.aws_availability_zones.available.names[count.index] - vpc_id = aws_vpc.test.id tags = { - Name = "%[1]s-${count.index}" + Name = %[1]q } } -`, rName) +`, rName)) } -func testAccProxyTargetConfig_Instance(rName string) string { - return testAccProxyTargetBaseConfig(rName) + fmt.Sprintf(` +func testAccProxyTargetConfig_instance(rName string) string { + return acctest.ConfigCompose(testAccProxyTargetBaseConfig(rName), fmt.Sprintf(` data "aws_rds_engine_version" "test" { engine = "mysql" preferred_versions = ["5.7.31", "5.7.30"] @@ -337,7 +314,7 @@ resource "aws_db_instance" "test" { db_subnet_group_name = aws_db_subnet_group.test.id engine = data.aws_rds_orderable_db_instance.test.engine engine_version = data.aws_rds_orderable_db_instance.test.engine_version - identifier = "%[1]s" + identifier = %[1]q instance_class = data.aws_rds_orderable_db_instance.test.instance_class password = "testtest" skip_final_snapshot = true @@ -345,7 +322,7 @@ resource "aws_db_instance" "test" { vpc_security_group_ids = [aws_security_group.test.id] tags = { - Name = "%[1]s" + Name = %[1]q } } @@ -354,17 +331,17 @@ resource "aws_db_proxy_target" "test" { db_proxy_name = aws_db_proxy.test.name target_group_name = "default" } -`, rName) +`, rName)) } -func testAccProxyTargetConfig_Cluster(rName string) string { - return testAccProxyTargetBaseConfig(rName) + fmt.Sprintf(` +func testAccProxyTargetConfig_cluster(rName string) string { + return acctest.ConfigCompose(testAccProxyTargetBaseConfig(rName), fmt.Sprintf(` data "aws_rds_engine_version" "test" { engine = "aurora-mysql" } resource "aws_rds_cluster" "test" { - cluster_identifier = "%[1]s" + cluster_identifier = %[1]q db_subnet_group_name = aws_db_subnet_group.test.id engine = data.aws_rds_engine_version.test.engine engine_version = data.aws_rds_engine_version.test.version @@ -374,7 +351,7 @@ resource "aws_rds_cluster" "test" { vpc_security_group_ids = [aws_security_group.test.id] tags = { - Name = "%[1]s" + Name = %[1]q } } @@ -383,5 +360,5 @@ resource "aws_db_proxy_target" "test" { db_proxy_name = aws_db_proxy.test.name target_group_name = "default" } -`, rName) +`, rName)) } diff --git a/internal/service/rds/proxy_test.go b/internal/service/rds/proxy_test.go index d43d50463b1..7fce6f8c17f 100644 --- a/internal/service/rds/proxy_test.go +++ b/internal/service/rds/proxy_test.go @@ -32,7 +32,7 @@ func TestAccRDSProxy_basic(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyConfig(rName), + Config: testAccProxyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -79,7 +79,7 @@ func TestAccRDSProxy_name(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyNameConfig(rName, rName), + Config: testAccProxyConfig_name(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -91,7 +91,7 @@ func TestAccRDSProxy_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyNameConfig(rName, nName), + Config: testAccProxyConfig_name(rName, nName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "name", nName), @@ -117,7 +117,7 @@ func TestAccRDSProxy_debugLogging(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyDebugLoggingConfig(rName, true), + Config: testAccProxyConfig_debugLogging(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "debug_logging", "true"), @@ -129,7 +129,7 @@ func TestAccRDSProxy_debugLogging(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyDebugLoggingConfig(rName, false), + Config: testAccProxyConfig_debugLogging(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "debug_logging", "false"), @@ -155,7 +155,7 @@ func TestAccRDSProxy_idleClientTimeout(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyIdleClientTimeoutConfig(rName, 900), + Config: testAccProxyConfig_idleClientTimeout(rName, 900), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "idle_client_timeout", "900"), @@ -167,7 +167,7 @@ func TestAccRDSProxy_idleClientTimeout(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyIdleClientTimeoutConfig(rName, 3600), + Config: testAccProxyConfig_idleClientTimeout(rName, 3600), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "idle_client_timeout", "3600"), @@ -193,7 +193,7 @@ func TestAccRDSProxy_requireTLS(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyRequireTLSConfig(rName, true), + Config: testAccProxyConfig_requireTLS(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "require_tls", "true"), @@ -205,7 +205,7 @@ func TestAccRDSProxy_requireTLS(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyRequireTLSConfig(rName, false), + Config: testAccProxyConfig_requireTLS(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "require_tls", "false"), @@ -232,7 +232,7 @@ func TestAccRDSProxy_roleARN(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyNameConfig(rName, rName), + Config: testAccProxyConfig_name(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test", "arn"), @@ -244,7 +244,7 @@ func TestAccRDSProxy_roleARN(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyRoleARNConfig(rName, nName), + Config: testAccProxyConfig_roleARN(rName, nName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttrPair(resourceName, "role_arn", "aws_iam_role.test2", "arn"), @@ -271,7 +271,7 @@ func TestAccRDSProxy_vpcSecurityGroupIDs(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyNameConfig(rName, rName), + Config: testAccProxyConfig_name(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "1"), @@ -284,7 +284,7 @@ func TestAccRDSProxy_vpcSecurityGroupIDs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyVPCSecurityGroupIDsConfig(rName, nName), + Config: testAccProxyConfig_vpcSecurityGroupIDs(rName, nName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "1"), @@ -312,7 +312,7 @@ func TestAccRDSProxy_authDescription(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyNameConfig(rName, rName), + Config: testAccProxyConfig_name(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "auth.0.description", "test"), @@ -324,7 +324,7 @@ func TestAccRDSProxy_authDescription(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyAuthDescriptionConfig(rName, description), + Config: testAccProxyConfig_authDescription(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "auth.0.description", description), @@ -351,7 +351,7 @@ func TestAccRDSProxy_authIAMAuth(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyNameConfig(rName, rName), + Config: testAccProxyConfig_name(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "auth.0.iam_auth", "DISABLED"), @@ -363,7 +363,7 @@ func TestAccRDSProxy_authIAMAuth(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyAuthIAMAuthConfig(rName, iamAuth), + Config: testAccProxyConfig_authIAMAuth(rName, iamAuth), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "auth.0.iam_auth", iamAuth), @@ -390,7 +390,7 @@ func TestAccRDSProxy_authSecretARN(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyNameConfig(rName, rName), + Config: testAccProxyConfig_name(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttrPair(resourceName, "auth.0.secret_arn", "aws_secretsmanager_secret.test", "arn"), @@ -402,7 +402,7 @@ func TestAccRDSProxy_authSecretARN(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyAuthSecretARNConfig(rName, nName), + Config: testAccProxyConfig_authSecretARN(rName, nName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttrPair(resourceName, "auth.0.secret_arn", "aws_secretsmanager_secret.test2", "arn"), @@ -428,7 +428,7 @@ func TestAccRDSProxy_authUsername(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyNameConfig(rName, rName), + Config: testAccProxyConfig_name(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "auth.0.username", ""), @@ -456,7 +456,7 @@ func TestAccRDSProxy_tags(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyNameConfig(rName, rName), + Config: testAccProxyConfig_name(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), @@ -468,7 +468,7 @@ func TestAccRDSProxy_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProxyTagsConfig(rName, key, value), + Config: testAccProxyConfig_tags(rName, key, value), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &dbProxy), resource.TestCheckResourceAttr(resourceName, "tags.foo", value), @@ -493,7 +493,7 @@ func TestAccRDSProxy_disappears(t *testing.T) { CheckDestroy: testAccCheckProxyDestroy, Steps: []resource.TestStep{ { - Config: testAccProxyConfig(rName), + Config: testAccProxyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProxyExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceProxy(), resourceName), @@ -658,7 +658,7 @@ resource "aws_subnet" "test" { `, rName) } -func testAccProxyConfig(rName string) string { +func testAccProxyConfig_basic(rName string) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -689,7 +689,7 @@ resource "aws_db_proxy" "test" { `, rName) } -func testAccProxyNameConfig(rName, nName string) string { +func testAccProxyConfig_name(rName, nName string) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -713,7 +713,7 @@ resource "aws_db_proxy" "test" { `, rName, nName) } -func testAccProxyDebugLoggingConfig(rName string, debugLogging bool) string { +func testAccProxyConfig_debugLogging(rName string, debugLogging bool) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -737,7 +737,7 @@ resource "aws_db_proxy" "test" { `, rName, debugLogging) } -func testAccProxyIdleClientTimeoutConfig(rName string, idleClientTimeout int) string { +func testAccProxyConfig_idleClientTimeout(rName string, idleClientTimeout int) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -761,7 +761,7 @@ resource "aws_db_proxy" "test" { `, rName, idleClientTimeout) } -func testAccProxyRequireTLSConfig(rName string, requireTls bool) string { +func testAccProxyConfig_requireTLS(rName string, requireTls bool) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -785,7 +785,7 @@ resource "aws_db_proxy" "test" { `, rName, requireTls) } -func testAccProxyRoleARNConfig(rName, nName string) string { +func testAccProxyConfig_roleARN(rName, nName string) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -820,7 +820,7 @@ resource "aws_iam_role_policy" "test2" { `, rName, nName) } -func testAccProxyVPCSecurityGroupIDsConfig(rName, nName string) string { +func testAccProxyConfig_vpcSecurityGroupIDs(rName, nName string) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -849,7 +849,7 @@ resource "aws_security_group" "test2" { `, rName, nName) } -func testAccProxyAuthDescriptionConfig(rName, description string) string { +func testAccProxyConfig_authDescription(rName, description string) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -873,7 +873,7 @@ resource "aws_db_proxy" "test" { `, rName, description) } -func testAccProxyAuthIAMAuthConfig(rName, iamAuth string) string { +func testAccProxyConfig_authIAMAuth(rName, iamAuth string) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -898,7 +898,7 @@ resource "aws_db_proxy" "test" { `, rName, iamAuth) } -func testAccProxyAuthSecretARNConfig(rName, nName string) string { +func testAccProxyConfig_authSecretARN(rName, nName string) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ @@ -932,7 +932,7 @@ resource "aws_secretsmanager_secret_version" "test2" { `, rName, nName) } -func testAccProxyTagsConfig(rName, key, value string) string { +func testAccProxyConfig_tags(rName, key, value string) string { return testAccProxyBaseConfig(rName) + fmt.Sprintf(` resource "aws_db_proxy" "test" { depends_on = [ diff --git a/internal/service/rds/security_group_test.go b/internal/service/rds/security_group_test.go index d586d3efc67..24c1b985bf9 100644 --- a/internal/service/rds/security_group_test.go +++ b/internal/service/rds/security_group_test.go @@ -26,7 +26,7 @@ func TestAccRDSSecurityGroup_basic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig(rName), + Config: testAccSecurityGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &v), testAccCheckSecurityGroupAttributes(&v), @@ -140,7 +140,7 @@ func testAccCheckSecurityGroupExists(n string, v *rds.DBSecurityGroup) resource. } } -func testAccSecurityGroupConfig(name string) string { +func testAccSecurityGroupConfig_basic(name string) string { return acctest.ConfigCompose( acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` diff --git a/internal/service/rds/snapshot_copy_test.go b/internal/service/rds/snapshot_copy_test.go index da910f98d24..fd1d44d6ad4 100644 --- a/internal/service/rds/snapshot_copy_test.go +++ b/internal/service/rds/snapshot_copy_test.go @@ -32,7 +32,7 @@ func TestAccRDSSnapshotCopy_basic(t *testing.T) { CheckDestroy: testAccCheckSnapshotCopyDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotCopyConfig(rName), + Config: testAccSnapshotCopyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotCopyExists(resourceName, &v), ), @@ -62,9 +62,9 @@ func TestAccRDSSnapshotCopy_tags(t *testing.T) { CheckDestroy: testAccCheckSnapshotCopyDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotCopyTagsConfig1(rName, "key1", "value1"), + Config: testAccSnapshotCopyConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckDbSnapshotExists(resourceName, &v), + testAccCheckDBSnapshotExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), @@ -75,18 +75,18 @@ func TestAccRDSSnapshotCopy_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSnapshotCopyTagsConfig2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccSnapshotCopyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckDbSnapshotExists(resourceName, &v), + testAccCheckDBSnapshotExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { - Config: testAccSnapshotCopyTagsConfig1(rName, "key2", "value2"), + Config: testAccSnapshotCopyConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckDbSnapshotExists(resourceName, &v), + testAccCheckDBSnapshotExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), @@ -111,7 +111,7 @@ func TestAccRDSSnapshotCopy_disappears(t *testing.T) { CheckDestroy: testAccCheckSnapshotCopyDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotCopyConfig(rName), + Config: testAccSnapshotCopyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotCopyExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfrds.ResourceSnapshotCopy(), resourceName), @@ -202,7 +202,7 @@ resource "aws_db_snapshot" "test" { }`, rName) } -func testAccSnapshotCopyConfig(rName string) string { +func testAccSnapshotCopyConfig_basic(rName string) string { return acctest.ConfigCompose( testAccSnapshotCopyBaseConfig(rName), fmt.Sprintf(` @@ -212,7 +212,7 @@ resource "aws_db_snapshot_copy" "test" { }`, rName)) } -func testAccSnapshotCopyTagsConfig1(rName, tagKey, tagValue string) string { +func testAccSnapshotCopyConfig_tags1(rName, tagKey, tagValue string) string { return acctest.ConfigCompose( testAccSnapshotCopyBaseConfig(rName), fmt.Sprintf(` @@ -226,7 +226,7 @@ resource "aws_db_snapshot_copy" "test" { }`, rName, tagKey, tagValue)) } -func testAccSnapshotCopyTagsConfig2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSnapshotCopyConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( testAccSnapshotCopyBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/rds/snapshot_data_source.go b/internal/service/rds/snapshot_data_source.go index 7d4e7878343..046335ee84f 100644 --- a/internal/service/rds/snapshot_data_source.go +++ b/internal/service/rds/snapshot_data_source.go @@ -162,7 +162,7 @@ func dataSourceSnapshotRead(d *schema.ResourceData, meta interface{}) error { recent := d.Get("most_recent").(bool) log.Printf("[DEBUG] aws_db_snapshot - multiple results found and `most_recent` is set to: %t", recent) if recent { - snapshot = mostRecentDbSnapshot(resp.DBSnapshots) + snapshot = mostRecentDBSnapshot(resp.DBSnapshots) } else { return fmt.Errorf("Your query returned more than one result. Please try a more specific search criteria.") } @@ -189,7 +189,7 @@ func (a rdsSnapshotSort) Less(i, j int) bool { return (*a[i].SnapshotCreateTime).Before(*a[j].SnapshotCreateTime) } -func mostRecentDbSnapshot(snapshots []*rds.DBSnapshot) *rds.DBSnapshot { +func mostRecentDBSnapshot(snapshots []*rds.DBSnapshot) *rds.DBSnapshot { sortedSnapshots := snapshots sort.Sort(rdsSnapshotSort(sortedSnapshots)) return sortedSnapshots[len(sortedSnapshots)-1] diff --git a/internal/service/rds/snapshot_data_source_test.go b/internal/service/rds/snapshot_data_source_test.go index 80286547008..8f4b03f531b 100644 --- a/internal/service/rds/snapshot_data_source_test.go +++ b/internal/service/rds/snapshot_data_source_test.go @@ -23,7 +23,7 @@ func TestAccRDSSnapshotDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckSnapshotDataSourceConfig(rInt), + Config: testAccSnapshotDataSourceConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotIDDataSource("data.aws_db_snapshot.snapshot"), ), @@ -46,7 +46,7 @@ func testAccCheckSnapshotIDDataSource(n string) resource.TestCheckFunc { } } -func testAccCheckSnapshotDataSourceConfig(rInt int) string { +func testAccSnapshotDataSourceConfig_basic(rInt int) string { return fmt.Sprintf(` data "aws_rds_engine_version" "default" { engine = "mysql" diff --git a/internal/service/rds/snapshot_test.go b/internal/service/rds/snapshot_test.go index a379390e999..ac89cec7ff4 100644 --- a/internal/service/rds/snapshot_test.go +++ b/internal/service/rds/snapshot_test.go @@ -28,12 +28,12 @@ func TestAccRDSSnapshot_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, rds.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDbSnapshotDestroy, + CheckDestroy: testAccCheckDBSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotConfig(rName), + Config: testAccSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDbSnapshotExists(resourceName, &v), + testAccCheckDBSnapshotExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), acctest.MatchResourceAttrRegionalARN(resourceName, "db_snapshot_arn", "rds", regexp.MustCompile(`snapshot:.+`)), ), @@ -60,12 +60,12 @@ func TestAccRDSSnapshot_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, rds.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDbSnapshotDestroy, + CheckDestroy: testAccCheckDBSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotTags1Config(rName, "key1", "value1"), + Config: testAccSnapshotConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckDbSnapshotExists(resourceName, &v), + testAccCheckDBSnapshotExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), @@ -76,18 +76,18 @@ func TestAccRDSSnapshot_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSnapshotTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccSnapshotConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckDbSnapshotExists(resourceName, &v), + testAccCheckDBSnapshotExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { - Config: testAccSnapshotTags1Config(rName, "key2", "value2"), + Config: testAccSnapshotConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckDbSnapshotExists(resourceName, &v), + testAccCheckDBSnapshotExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), @@ -109,13 +109,13 @@ func TestAccRDSSnapshot_disappears(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, rds.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDbSnapshotDestroy, + CheckDestroy: testAccCheckDBSnapshotDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotConfig(rName), + Config: testAccSnapshotConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDbSnapshotExists(resourceName, &v), - testAccCheckDbSnapshotDisappears(&v), + testAccCheckDBSnapshotExists(resourceName, &v), + testAccCheckDBSnapshotDisappears(&v), ), ExpectNonEmptyPlan: true, }, @@ -123,7 +123,7 @@ func TestAccRDSSnapshot_disappears(t *testing.T) { }) } -func testAccCheckDbSnapshotDestroy(s *terraform.State) error { +func testAccCheckDBSnapshotDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).RDSConn for _, rs := range s.RootModule().Resources { @@ -155,7 +155,7 @@ func testAccCheckDbSnapshotDestroy(s *terraform.State) error { return nil } -func testAccCheckDbSnapshotExists(n string, v *rds.DBSnapshot) resource.TestCheckFunc { +func testAccCheckDBSnapshotExists(n string, v *rds.DBSnapshot) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -183,7 +183,7 @@ func testAccCheckDbSnapshotExists(n string, v *rds.DBSnapshot) resource.TestChec } } -func testAccCheckDbSnapshotDisappears(snapshot *rds.DBSnapshot) resource.TestCheckFunc { +func testAccCheckDBSnapshotDisappears(snapshot *rds.DBSnapshot) resource.TestCheckFunc { return func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).RDSConn @@ -225,7 +225,7 @@ resource "aws_db_instance" "test" { }`, rName) } -func testAccSnapshotConfig(rName string) string { +func testAccSnapshotConfig_basic(rName string) string { return acctest.ConfigCompose( testAccSnapshotBaseConfig(rName), fmt.Sprintf(` @@ -236,7 +236,7 @@ resource "aws_db_snapshot" "test" { `, rName)) } -func testAccSnapshotTags1Config(rName, tag1Key, tag1Value string) string { +func testAccSnapshotConfig_tags1(rName, tag1Key, tag1Value string) string { return acctest.ConfigCompose( testAccSnapshotBaseConfig(rName), fmt.Sprintf(` @@ -251,7 +251,7 @@ resource "aws_db_snapshot" "test" { `, rName, tag1Key, tag1Value)) } -func testAccSnapshotTags2Config(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccSnapshotConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return acctest.ConfigCompose( testAccSnapshotBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/rds/subnet_group_data_source_test.go b/internal/service/rds/subnet_group_data_source_test.go index e5c9d0cb212..00ca385bbc9 100644 --- a/internal/service/rds/subnet_group_data_source_test.go +++ b/internal/service/rds/subnet_group_data_source_test.go @@ -22,7 +22,7 @@ func TestAccRDSSubnetGroupDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupDataSourceConfig(rName), + Config: testAccSubnetGroupDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "description", dataSourceName, "description"), @@ -43,20 +43,20 @@ func TestAccRDSSubnetGroupDataSource_nonexistent(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupDataSourceConfig_NonExistent, + Config: testAccSubnetGroupDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`error reading DB SubnetGroup \(tf-acc-test-does-not-exist\)`), }, }, }) } -const testAccSubnetGroupDataSourceConfig_NonExistent = ` +const testAccSubnetGroupDataSourceConfig_nonExistent = ` data "aws_db_subnet_group" "test" { name = "tf-acc-test-does-not-exist" } ` -func testAccSubnetGroupDataSourceConfig(rName string) string { +func testAccSubnetGroupDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` diff --git a/internal/service/rds/subnet_group_test.go b/internal/service/rds/subnet_group_test.go index 7f00051c2a9..63c40d67819 100644 --- a/internal/service/rds/subnet_group_test.go +++ b/internal/service/rds/subnet_group_test.go @@ -28,7 +28,7 @@ func TestAccRDSSubnetGroup_basic(t *testing.T) { CheckDestroy: testAccCheckDBSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDBSubnetGroupConfig(rName), + Config: testAccSubnetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDBSubnetGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -134,7 +134,7 @@ func TestAccRDSSubnetGroup_updateDescription(t *testing.T) { CheckDestroy: testAccCheckDBSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccDBSubnetGroupConfig(rName), + Config: testAccSubnetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDBSubnetGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), @@ -217,7 +217,7 @@ func testAccCheckDBSubnetGroupExists(n string, v *rds.DBSubnetGroup) resource.Te } } -func testAccDBSubnetGroupConfig(rName string) string { +func testAccSubnetGroupConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" diff --git a/internal/service/rds/wait.go b/internal/service/rds/wait.go index 92245ef39ff..da786359479 100644 --- a/internal/service/rds/wait.go +++ b/internal/service/rds/wait.go @@ -12,8 +12,8 @@ import ( ) const ( - dbClusterRoleAssociationCreatedTimeout = 5 * time.Minute - dbClusterRoleAssociationDeletedTimeout = 5 * time.Minute + dbClusterRoleAssociationCreatedTimeout = 10 * time.Minute + dbClusterRoleAssociationDeletedTimeout = 10 * time.Minute dbClusterActivityStreamStartedTimeout = 30 * time.Minute dbClusterActivityStreamStoppedTimeout = 30 * time.Minute diff --git a/internal/service/redshift/authentication_profile.go b/internal/service/redshift/authentication_profile.go new file mode 100644 index 00000000000..c8ec6fc6861 --- /dev/null +++ b/internal/service/redshift/authentication_profile.go @@ -0,0 +1,125 @@ +package redshift + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceAuthenticationProfile() *schema.Resource { + return &schema.Resource{ + Create: resourceAuthenticationProfileCreate, + Read: resourceAuthenticationProfileRead, + Update: resourceAuthenticationProfileUpdate, + Delete: resourceAuthenticationProfileDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "authentication_profile_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "authentication_profile_content": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsJSON, + DiffSuppressFunc: verify.SuppressEquivalentJSONDiffs, + StateFunc: func(v interface{}) string { + json, _ := structure.NormalizeJsonString(v) + return json + }, + }, + }, + } +} + +func resourceAuthenticationProfileCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + authProfileName := d.Get("authentication_profile_name").(string) + + input := redshift.CreateAuthenticationProfileInput{ + AuthenticationProfileName: aws.String(authProfileName), + AuthenticationProfileContent: aws.String(d.Get("authentication_profile_content").(string)), + } + + out, err := conn.CreateAuthenticationProfile(&input) + + if err != nil { + return fmt.Errorf("error creating Redshift Authentication Profile (%s): %s", authProfileName, err) + } + + d.SetId(aws.StringValue(out.AuthenticationProfileName)) + + return resourceAuthenticationProfileRead(d, meta) +} + +func resourceAuthenticationProfileRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + out, err := FindAuthenticationProfileByID(conn, d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift Authentication Profile (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error reading Redshift Authentication Profile (%s): %w", d.Id(), err) + } + + d.Set("authentication_profile_content", out.AuthenticationProfileContent) + d.Set("authentication_profile_name", out.AuthenticationProfileName) + + return nil +} + +func resourceAuthenticationProfileUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + input := &redshift.ModifyAuthenticationProfileInput{ + AuthenticationProfileName: aws.String(d.Id()), + AuthenticationProfileContent: aws.String(d.Get("authentication_profile_content").(string)), + } + + _, err := conn.ModifyAuthenticationProfile(input) + + if err != nil { + return fmt.Errorf("error modifying Redshift Authentication Profile (%s): %w", d.Id(), err) + } + + return resourceAuthenticationProfileRead(d, meta) +} + +func resourceAuthenticationProfileDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + deleteInput := redshift.DeleteAuthenticationProfileInput{ + AuthenticationProfileName: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Deleting Redshift Authentication Profile: %s", d.Id()) + _, err := conn.DeleteAuthenticationProfile(&deleteInput) + + if err != nil { + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeAuthenticationProfileNotFoundFault) { + return nil + } + return err + } + + return err +} diff --git a/internal/service/redshift/authentication_profile_test.go b/internal/service/redshift/authentication_profile_test.go new file mode 100644 index 00000000000..fc11ac081d9 --- /dev/null +++ b/internal/service/redshift/authentication_profile_test.go @@ -0,0 +1,133 @@ +package redshift_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/redshift" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccRedshiftAuthenticationProfile_basic(t *testing.T) { + resourceName := "aws_redshift_authentication_profile.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + rNameUpdated := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAuthenticationProfileDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAuthenticationProfileConfig_basic(rName, rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAuthenticationProfileExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "authentication_profile_name", rName), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAuthenticationProfileConfig_basic(rName, rNameUpdated), + Check: resource.ComposeTestCheckFunc( + testAccCheckAuthenticationProfileExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "authentication_profile_name", rName), + ), + }, + }, + }) +} + +func TestAccRedshiftAuthenticationProfile_disappears(t *testing.T) { + resourceName := "aws_redshift_authentication_profile.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAuthenticationProfileDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAuthenticationProfileConfig_basic(rName, rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAuthenticationProfileExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceAuthenticationProfile(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckAuthenticationProfileDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_redshift_authentication_profile" { + continue + } + + _, err := tfredshift.FindAuthenticationProfileByID(conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("Redshift Authentication Profile %s still exists", rs.Primary.ID) + } + + return nil +} + +func testAccCheckAuthenticationProfileExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("Authentication Profile ID is not set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + _, err := tfredshift.FindAuthenticationProfileByID(conn, rs.Primary.ID) + + if err != nil { + return err + } + + return nil + } +} + +func testAccAuthenticationProfileConfig_basic(rName, id string) string { + return fmt.Sprintf(` +resource "aws_redshift_authentication_profile" "test" { + authentication_profile_name = %[1]q + authentication_profile_content = jsonencode( + { + AllowDBUserOverride = "1" + Client_ID = "ExampleClientID" + App_ID = %[2]q + } + ) +} +`, rName, id) +} diff --git a/internal/service/redshift/cluster.go b/internal/service/redshift/cluster.go index 1c910d705e2..b4600d7a9c0 100644 --- a/internal/service/redshift/cluster.go +++ b/internal/service/redshift/cluster.go @@ -45,6 +45,17 @@ func ResourceCluster() *schema.Resource { Optional: true, Default: true, }, + "apply_immediately": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "aqua_configuration_status": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice(redshift.AquaConfigurationStatus_Values(), false), + }, "arn": { Type: schema.TypeString, Computed: true, @@ -115,7 +126,6 @@ func ResourceCluster() *schema.Resource { Optional: true, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "cluster_subnet_group_name": { Type: schema.TypeString, @@ -143,6 +153,12 @@ func ResourceCluster() *schema.Resource { validation.StringMatch(regexp.MustCompile(`(?i)^[a-z_]`), "first character must be a letter or underscore"), ), }, + "default_iam_role_arn": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: verify.ValidARN, + }, "dns_name": { Type: schema.TypeString, Computed: true, @@ -180,8 +196,10 @@ func ResourceCluster() *schema.Resource { Type: schema.TypeSet, Optional: true, Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidARN, + }, }, "kms_key_id": { Type: schema.TypeString, @@ -205,6 +223,16 @@ func ResourceCluster() *schema.Resource { Type: schema.TypeBool, Required: true, }, + "log_destination_type": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice(redshift.LogDestinationType_Values(), false), + }, + "log_exports": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, "s3_key_prefix": { Type: schema.TypeString, Optional: true, @@ -213,6 +241,17 @@ func ResourceCluster() *schema.Resource { }, }, }, + "maintenance_track_name": { + Type: schema.TypeString, + Optional: true, + Default: "current", + }, + "manual_snapshot_retention_period": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + ValidateFunc: validation.IntBetween(-1, 3653), + }, "master_password": { Type: schema.TypeString, Optional: true, @@ -245,13 +284,15 @@ func ResourceCluster() *schema.Resource { Default: 1, }, "owner_account": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: verify.ValidAccountID, }, "port": { - Type: schema.TypeInt, - Optional: true, - Default: 5439, + Type: schema.TypeInt, + Optional: true, + Default: 5439, + ValidateFunc: validation.IntBetween(1115, 65535), }, "preferred_maintenance_window": { Type: schema.TypeString, @@ -314,7 +355,6 @@ func ResourceCluster() *schema.Resource { Optional: true, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, }, @@ -348,76 +388,123 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) - if v, ok := d.GetOk("snapshot_identifier"); ok { - clusterID := d.Get("cluster_identifier").(string) - input := &redshift.RestoreFromClusterSnapshotInput{ - AllowVersionUpgrade: aws.Bool(d.Get("allow_version_upgrade").(bool)), - AutomatedSnapshotRetentionPeriod: aws.Int64(int64(d.Get("automated_snapshot_retention_period").(int))), - ClusterIdentifier: aws.String(clusterID), - Port: aws.Int64(int64(d.Get("port").(int))), - NodeType: aws.String(d.Get("node_type").(string)), - PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)), - SnapshotIdentifier: aws.String(v.(string)), - } + clusterID := d.Get("cluster_identifier").(string) + backupInput := &redshift.RestoreFromClusterSnapshotInput{ + AllowVersionUpgrade: aws.Bool(d.Get("allow_version_upgrade").(bool)), + AutomatedSnapshotRetentionPeriod: aws.Int64(int64(d.Get("automated_snapshot_retention_period").(int))), + ClusterIdentifier: aws.String(clusterID), + Port: aws.Int64(int64(d.Get("port").(int))), + NodeType: aws.String(d.Get("node_type").(string)), + PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)), + } - if v, ok := d.GetOk("availability_zone"); ok { - input.AvailabilityZone = aws.String(v.(string)) - } + input := &redshift.CreateClusterInput{ + AllowVersionUpgrade: aws.Bool(d.Get("allow_version_upgrade").(bool)), + AutomatedSnapshotRetentionPeriod: aws.Int64(int64(d.Get("automated_snapshot_retention_period").(int))), + ClusterIdentifier: aws.String(clusterID), + ClusterVersion: aws.String(d.Get("cluster_version").(string)), + DBName: aws.String(d.Get("database_name").(string)), + MasterUsername: aws.String(d.Get("master_username").(string)), + MasterUserPassword: aws.String(d.Get("master_password").(string)), + NodeType: aws.String(d.Get("node_type").(string)), + Port: aws.Int64(int64(d.Get("port").(int))), + PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)), + Tags: Tags(tags.IgnoreAWS()), + } - if v, ok := d.GetOk("availability_zone_relocation_enabled"); ok { - input.AvailabilityZoneRelocation = aws.Bool(v.(bool)) - } + if v, ok := d.GetOk("aqua_configuration_status"); ok { + backupInput.AquaConfigurationStatus = aws.String(v.(string)) + input.AquaConfigurationStatus = aws.String(v.(string)) + } - if v, ok := d.GetOk("cluster_subnet_group_name"); ok { - input.ClusterSubnetGroupName = aws.String(v.(string)) - } + if v, ok := d.GetOk("availability_zone"); ok { + backupInput.AvailabilityZone = aws.String(v.(string)) + input.AvailabilityZone = aws.String(v.(string)) + } - if v, ok := d.GetOk("cluster_parameter_group_name"); ok { - input.ClusterParameterGroupName = aws.String(v.(string)) - } + if v, ok := d.GetOk("availability_zone_relocation_enabled"); ok { + backupInput.AvailabilityZoneRelocation = aws.Bool(v.(bool)) + input.AvailabilityZoneRelocation = aws.Bool(v.(bool)) + } - if v := d.Get("cluster_security_groups").(*schema.Set); v.Len() > 0 { - input.ClusterSecurityGroups = flex.ExpandStringSet(v) - } + if v, ok := d.GetOk("cluster_parameter_group_name"); ok { + backupInput.ClusterParameterGroupName = aws.String(v.(string)) + input.ClusterParameterGroupName = aws.String(v.(string)) + } - if v, ok := d.GetOk("elastic_ip"); ok { - input.ElasticIp = aws.String(v.(string)) - } + if v := d.Get("cluster_security_groups").(*schema.Set); v.Len() > 0 { + backupInput.ClusterSecurityGroups = flex.ExpandStringSet(v) + input.ClusterSecurityGroups = flex.ExpandStringSet(v) + } - if v, ok := d.GetOk("enhanced_vpc_routing"); ok { - input.EnhancedVpcRouting = aws.Bool(v.(bool)) - } + if v, ok := d.GetOk("cluster_subnet_group_name"); ok { + backupInput.ClusterSubnetGroupName = aws.String(v.(string)) + input.ClusterSubnetGroupName = aws.String(v.(string)) + } - if v, ok := d.GetOk("iam_roles"); ok { - input.IamRoles = flex.ExpandStringSet(v.(*schema.Set)) - } + if v, ok := d.GetOk("default_iam_role_arn"); ok { + backupInput.DefaultIamRoleArn = aws.String(v.(string)) + input.DefaultIamRoleArn = aws.String(v.(string)) + } - if v, ok := d.GetOk("kms_key_id"); ok { - input.KmsKeyId = aws.String(v.(string)) - } + if v, ok := d.GetOk("elastic_ip"); ok { + backupInput.ElasticIp = aws.String(v.(string)) + input.ElasticIp = aws.String(v.(string)) + } - if v, ok := d.GetOk("number_of_nodes"); ok { - input.NumberOfNodes = aws.Int64(int64(v.(int))) - } + if v, ok := d.GetOk("enhanced_vpc_routing"); ok { + backupInput.EnhancedVpcRouting = aws.Bool(v.(bool)) + input.EnhancedVpcRouting = aws.Bool(v.(bool)) + } - if v, ok := d.GetOk("owner_account"); ok { - input.OwnerAccount = aws.String(v.(string)) - } + if v, ok := d.GetOk("iam_roles"); ok { + backupInput.IamRoles = flex.ExpandStringSet(v.(*schema.Set)) + input.IamRoles = flex.ExpandStringSet(v.(*schema.Set)) + } - if v, ok := d.GetOk("preferred_maintenance_window"); ok { - input.PreferredMaintenanceWindow = aws.String(v.(string)) - } + if v, ok := d.GetOk("kms_key_id"); ok { + backupInput.KmsKeyId = aws.String(v.(string)) + input.KmsKeyId = aws.String(v.(string)) + } - if v, ok := d.GetOk("snapshot_cluster_identifier"); ok { - input.SnapshotClusterIdentifier = aws.String(v.(string)) + if v, ok := d.GetOk("maintenance_track_name"); ok { + backupInput.MaintenanceTrackName = aws.String(v.(string)) + input.MaintenanceTrackName = aws.String(v.(string)) + } + + if v, ok := d.GetOk("manual_snapshot_retention_period"); ok { + backupInput.ManualSnapshotRetentionPeriod = aws.Int64(int64(v.(int))) + input.ManualSnapshotRetentionPeriod = aws.Int64(int64(v.(int))) + } + + if v, ok := d.GetOk("number_of_nodes"); ok { + backupInput.NumberOfNodes = aws.Int64(int64(v.(int))) + // NumberOfNodes set below for CreateCluster. + } + + if v, ok := d.GetOk("preferred_maintenance_window"); ok { + backupInput.PreferredMaintenanceWindow = aws.String(v.(string)) + input.PreferredMaintenanceWindow = aws.String(v.(string)) + } + + if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 { + backupInput.VpcSecurityGroupIds = flex.ExpandStringSet(v) + input.VpcSecurityGroupIds = flex.ExpandStringSet(v) + } + + if v, ok := d.GetOk("snapshot_identifier"); ok { + backupInput.SnapshotIdentifier = aws.String(v.(string)) + + if v, ok := d.GetOk("owner_account"); ok { + backupInput.OwnerAccount = aws.String(v.(string)) } - if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 { - input.VpcSecurityGroupIds = flex.ExpandStringSet(v) + if v, ok := d.GetOk("snapshot_cluster_identifier"); ok { + backupInput.SnapshotClusterIdentifier = aws.String(v.(string)) } - log.Printf("[DEBUG] Restoring Redshift Cluster: %s", input) - output, err := conn.RestoreFromClusterSnapshot(input) + log.Printf("[DEBUG] Restoring Redshift Cluster: %s", backupInput) + output, err := conn.RestoreFromClusterSnapshot(backupInput) if err != nil { return fmt.Errorf("error restoring Redshift Cluster (%s) from snapshot: %w", clusterID, err) @@ -433,61 +520,10 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf(`provider.aws: aws_redshift_cluster: %s: "master_username": required field is not set`, d.Get("cluster_identifier").(string)) } - clusterID := d.Get("cluster_identifier").(string) - input := &redshift.CreateClusterInput{ - AllowVersionUpgrade: aws.Bool(d.Get("allow_version_upgrade").(bool)), - AutomatedSnapshotRetentionPeriod: aws.Int64(int64(d.Get("automated_snapshot_retention_period").(int))), - ClusterIdentifier: aws.String(clusterID), - ClusterVersion: aws.String(d.Get("cluster_version").(string)), - DBName: aws.String(d.Get("database_name").(string)), - MasterUsername: aws.String(d.Get("master_username").(string)), - MasterUserPassword: aws.String(d.Get("master_password").(string)), - NodeType: aws.String(d.Get("node_type").(string)), - Port: aws.Int64(int64(d.Get("port").(int))), - PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)), - Tags: Tags(tags.IgnoreAWS()), - } - - if v, ok := d.GetOk("availability_zone"); ok { - input.AvailabilityZone = aws.String(v.(string)) - } - - if v, ok := d.GetOk("availability_zone_relocation_enabled"); ok { - input.AvailabilityZoneRelocation = aws.Bool(v.(bool)) - } - - if v, ok := d.GetOk("cluster_parameter_group_name"); ok { - input.ClusterParameterGroupName = aws.String(v.(string)) - } - - if v := d.Get("cluster_security_groups").(*schema.Set); v.Len() > 0 { - input.ClusterSecurityGroups = flex.ExpandStringSet(v) - } - - if v, ok := d.GetOk("cluster_subnet_group_name"); ok { - input.ClusterSubnetGroupName = aws.String(v.(string)) - } - - if v, ok := d.GetOk("elastic_ip"); ok { - input.ElasticIp = aws.String(v.(string)) - } - if v, ok := d.GetOk("encrypted"); ok { input.Encrypted = aws.Bool(v.(bool)) } - if v, ok := d.GetOk("enhanced_vpc_routing"); ok { - input.EnhancedVpcRouting = aws.Bool(v.(bool)) - } - - if v, ok := d.GetOk("iam_roles"); ok { - input.IamRoles = flex.ExpandStringSet(v.(*schema.Set)) - } - - if v, ok := d.GetOk("kms_key_id"); ok { - input.KmsKeyId = aws.String(v.(string)) - } - if v := d.Get("number_of_nodes").(int); v > 1 { input.ClusterType = aws.String(clusterTypeMultiNode) input.NumberOfNodes = aws.Int64(int64(d.Get("number_of_nodes").(int))) @@ -495,14 +531,6 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { input.ClusterType = aws.String(clusterTypeSingleNode) } - if v, ok := d.GetOk("preferred_maintenance_window"); ok { - input.PreferredMaintenanceWindow = aws.String(v.(string)) - } - - if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 { - input.VpcSecurityGroupIds = flex.ExpandStringSet(v) - } - log.Printf("[DEBUG] Creating Redshift Cluster: %s", input) output, err := conn.CreateCluster(input) @@ -570,17 +598,20 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { d.Set("allow_version_upgrade", rsc.AllowVersionUpgrade) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: "redshift", + Service: redshift.ServiceName, Region: meta.(*conns.AWSClient).Region, AccountID: meta.(*conns.AWSClient).AccountID, Resource: fmt.Sprintf("cluster:%s", d.Id()), }.String() d.Set("arn", arn) + if rsc.AquaConfiguration != nil { + d.Set("aqua_configuration_status", rsc.AquaConfiguration.AquaConfigurationStatus) + } d.Set("automated_snapshot_retention_period", rsc.AutomatedSnapshotRetentionPeriod) d.Set("availability_zone", rsc.AvailabilityZone) azr, err := clusterAvailabilityZoneRelocationStatus(rsc) if err != nil { - return fmt.Errorf("error reading Redshift Cluster (%s): %w", d.Id(), err) + return err } d.Set("availability_zone_relocation_enabled", azr) d.Set("cluster_identifier", rsc.ClusterIdentifier) @@ -598,12 +629,15 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { } d.Set("cluster_version", rsc.ClusterVersion) d.Set("database_name", rsc.DBName) + d.Set("default_iam_role_arn", rsc.DefaultIamRoleArn) d.Set("encrypted", rsc.Encrypted) d.Set("enhanced_vpc_routing", rsc.EnhancedVpcRouting) d.Set("kms_key_id", rsc.KmsKeyId) if err := d.Set("logging", flattenLogging(loggingStatus)); err != nil { return fmt.Errorf("error setting logging: %w", err) } + d.Set("maintenance_track_name", rsc.MaintenanceTrackName) + d.Set("manual_snapshot_retention_period", rsc.ManualSnapshotRetentionPeriod) d.Set("master_username", rsc.MasterUsername) d.Set("node_type", rsc.NodeType) d.Set("number_of_nodes", rsc.NumberOfNodes) @@ -666,7 +700,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).RedshiftConn - if d.HasChangesExcept("availability_zone", "iam_roles", "logging", "snapshot_copy", "tags", "tags_all") { + if d.HasChangesExcept("aqua_configuration_status", "availability_zone", "iam_roles", "logging", "snapshot_copy", "tags", "tags_all") { input := &redshift.ModifyClusterInput{ ClusterIdentifier: aws.String(d.Id()), } @@ -691,6 +725,14 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { input.ClusterSecurityGroups = flex.ExpandStringSet(d.Get("cluster_security_groups").(*schema.Set)) } + if d.HasChange("maintenance_track_name") { + input.MaintenanceTrackName = aws.String(d.Get("maintenance_track_name").(string)) + } + + if d.HasChange("manual_snapshot_retention_period") { + input.ManualSnapshotRetentionPeriod = aws.Int64(int64(d.Get("manual_snapshot_retention_period").(int))) + } + // If the cluster type, node type, or number of nodes changed, then the AWS API expects all three // items to be sent over. if d.HasChanges("cluster_type", "node_type", "number_of_nodes") { @@ -752,7 +794,7 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { } } - if d.HasChange("iam_roles") { + if d.HasChanges("iam_roles", "default_iam_role_arn") { o, n := d.GetChange("iam_roles") if o == nil { o = new(schema.Set) @@ -770,6 +812,7 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { AddIamRoles: flex.ExpandStringSet(add), ClusterIdentifier: aws.String(d.Id()), RemoveIamRoles: flex.ExpandStringSet(del), + DefaultIamRoleArn: aws.String(d.Get("default_iam_role_arn").(string)), } log.Printf("[DEBUG] Modifying Redshift Cluster IAM Roles: %s", input) @@ -784,6 +827,46 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { } } + if d.HasChange("aqua_configuration_status") { + input := &redshift.ModifyAquaConfigurationInput{ + AquaConfigurationStatus: aws.String(d.Get("aqua_configuration_status").(string)), + ClusterIdentifier: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Modifying Redshift Cluster Aqua Configuration: %s", input) + _, err := conn.ModifyAquaConfiguration(input) + + if err != nil { + return fmt.Errorf("error modifying Redshift Cluster (%s) Aqua Configuration: %w", d.Id(), err) + } + + if d.Get("apply_immediately").(bool) { + rebootInput := &redshift.RebootClusterInput{ + ClusterIdentifier: aws.String(d.Id()), + } + + _, err := tfresource.RetryWhenAWSErrCodeEquals( + clusterInvalidClusterStateFaultTimeout, + func() (interface{}, error) { + return conn.RebootCluster(rebootInput) + }, + redshift.ErrCodeInvalidClusterStateFault, + ) + + if err != nil { + return fmt.Errorf("error rebooting Redshift Cluster (%s): %w", d.Id(), err) + } + + if _, err := waitClusterRebooted(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("error waiting for Redshift Cluster (%s) Rebooted: %w", d.Id(), err) + } + + if _, err := waitClusterAquaApplied(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("error waiting for Redshift Cluster (%s) Aqua Configuration update: %w", d.Id(), err) + } + } + } + // Availability Zone cannot be changed at the same time as other settings if d.HasChange("availability_zone") { input := &redshift.ModifyClusterInput{ @@ -911,15 +994,20 @@ func resourceClusterImport(d *schema.ResourceData, meta interface{}) ([]*schema. } func enableLogging(conn *redshift.Redshift, clusterID string, tfMap map[string]interface{}) error { - bucketName, ok := tfMap["bucket_name"].(string) + input := &redshift.EnableLoggingInput{ + ClusterIdentifier: aws.String(clusterID), + } - if !ok || bucketName == "" { - return fmt.Errorf("`bucket_name` must be set when enabling logging for Redshift Clusters") + if v, ok := tfMap["bucket_name"].(string); ok && v != "" { + input.BucketName = aws.String(v) } - input := &redshift.EnableLoggingInput{ - BucketName: aws.String(bucketName), - ClusterIdentifier: aws.String(clusterID), + if v, ok := tfMap["log_destination_type"].(string); ok && v != "" { + input.LogDestinationType = aws.String(v) + } + + if v, ok := tfMap["log_exports"].(*schema.Set); ok && v.Len() > 0 { + input.LogExports = flex.ExpandStringSet(v) } if v, ok := tfMap["s3_key_prefix"].(string); ok && v != "" { diff --git a/internal/service/redshift/cluster_credentials_data_source.go b/internal/service/redshift/cluster_credentials_data_source.go new file mode 100644 index 00000000000..71dc519a397 --- /dev/null +++ b/internal/service/redshift/cluster_credentials_data_source.go @@ -0,0 +1,92 @@ +package redshift + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" +) + +func DataSourceClusterCredentials() *schema.Resource { + return &schema.Resource{ + Read: dataSourceClusterCredentialsRead, + + Schema: map[string]*schema.Schema{ + "auto_create": { + Type: schema.TypeBool, + Optional: true, + }, + "cluster_identifier": { + Type: schema.TypeString, + Required: true, + }, + "db_groups": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "db_name": { + Type: schema.TypeString, + Optional: true, + }, + "db_password": { + Type: schema.TypeString, + Computed: true, + Sensitive: true, + }, + "db_user": { + Type: schema.TypeString, + Required: true, + }, + "duration_seconds": { + Type: schema.TypeInt, + Optional: true, + Default: 900, + ValidateFunc: validation.IntBetween(900, 3600), + }, + "expiration": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceClusterCredentialsRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + clusterID := d.Get("cluster_identifier").(string) + input := &redshift.GetClusterCredentialsInput{ + AutoCreate: aws.Bool(d.Get("auto_create").(bool)), + ClusterIdentifier: aws.String(clusterID), + DbUser: aws.String(d.Get("db_user").(string)), + DurationSeconds: aws.Int64(int64(d.Get("duration_seconds").(int))), + } + + if v, ok := d.GetOk("db_groups"); ok && v.(*schema.Set).Len() > 0 { + input.DbGroups = flex.ExpandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("db_name"); ok { + input.DbName = aws.String(v.(string)) + } + + creds, err := conn.GetClusterCredentials(input) + + if err != nil { + return fmt.Errorf("reading Redshift Cluster Credentials for Cluster (%s): %w", clusterID, err) + } + + d.SetId(clusterID) + + d.Set("db_password", creds.DbPassword) + d.Set("db_user", creds.DbUser) + d.Set("expiration", aws.TimeValue(creds.Expiration).Format(time.RFC3339)) + + return nil +} diff --git a/internal/service/redshift/cluster_credentials_data_source_test.go b/internal/service/redshift/cluster_credentials_data_source_test.go new file mode 100644 index 00000000000..b23bde7decb --- /dev/null +++ b/internal/service/redshift/cluster_credentials_data_source_test.go @@ -0,0 +1,52 @@ +package redshift_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/redshift" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" +) + +func TestAccRedshiftClusterCredentialsDataSource_basic(t *testing.T) { + dataSourceName := "data.aws_redshift_cluster_credentials.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccClusterCredentialsDataSourceConfig_basic(rName), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "cluster_identifier", "aws_redshift_cluster.test", "cluster_identifier"), + resource.TestCheckResourceAttrSet(dataSourceName, "db_password"), + resource.TestCheckResourceAttrSet(dataSourceName, "expiration"), + ), + }, + }, + }) +} + +func testAccClusterCredentialsDataSourceConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_redshift_cluster" "test" { + cluster_identifier = %[1]q + + database_name = "testdb" + master_username = "foo" + master_password = "Password1" + node_type = "dc2.large" + cluster_type = "single-node" + skip_final_snapshot = true +} + +data "aws_redshift_cluster_credentials" "test" { + cluster_identifier = aws_redshift_cluster.test.cluster_identifier + db_user = aws_redshift_cluster.test.master_username +} +`, rName) +} diff --git a/internal/service/redshift/cluster_data_source.go b/internal/service/redshift/cluster_data_source.go index 15db32922bf..57a9c9c0a97 100644 --- a/internal/service/redshift/cluster_data_source.go +++ b/internal/service/redshift/cluster_data_source.go @@ -2,12 +2,13 @@ package redshift import ( "fmt" - "log" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/redshift" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" ) @@ -16,156 +17,174 @@ func DataSourceCluster() *schema.Resource { Read: dataSourceClusterRead, Schema: map[string]*schema.Schema{ - - "cluster_identifier": { - Type: schema.TypeString, - Required: true, - }, - "allow_version_upgrade": { Type: schema.TypeBool, Computed: true, }, - + "aqua_configuration_status": { + Type: schema.TypeString, + Computed: true, + }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, "automated_snapshot_retention_period": { Type: schema.TypeInt, Computed: true, }, - "availability_zone": { Type: schema.TypeString, Computed: true, }, - "availability_zone_relocation_enabled": { Type: schema.TypeBool, Computed: true, }, - "bucket_name": { Type: schema.TypeString, Computed: true, }, - + "cluster_identifier": { + Type: schema.TypeString, + Required: true, + }, + "cluster_nodes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_role": { + Type: schema.TypeString, + Computed: true, + }, + "private_ip_address": { + Type: schema.TypeString, + Computed: true, + }, + "public_ip_address": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, "cluster_parameter_group_name": { Type: schema.TypeString, Computed: true, }, - "cluster_public_key": { Type: schema.TypeString, Computed: true, }, - "cluster_revision_number": { Type: schema.TypeString, Computed: true, }, - "cluster_security_groups": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "cluster_subnet_group_name": { Type: schema.TypeString, Computed: true, }, - "cluster_type": { Type: schema.TypeString, Computed: true, }, - "cluster_version": { Type: schema.TypeString, Computed: true, }, - "database_name": { Type: schema.TypeString, Computed: true, }, - + "default_iam_role_arn": { + Type: schema.TypeString, + Computed: true, + }, "elastic_ip": { Type: schema.TypeString, Computed: true, }, - "enable_logging": { Type: schema.TypeBool, Computed: true, }, - "encrypted": { Type: schema.TypeBool, Computed: true, }, - "endpoint": { Type: schema.TypeString, Computed: true, }, - "enhanced_vpc_routing": { Type: schema.TypeBool, Computed: true, }, - "iam_roles": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "kms_key_id": { Type: schema.TypeString, Computed: true, }, - "master_username": { Type: schema.TypeString, Computed: true, }, - + "maintenance_track_name": { + Type: schema.TypeString, + Computed: true, + }, + "manual_snapshot_retention_period": { + Type: schema.TypeInt, + Computed: true, + }, "node_type": { Type: schema.TypeString, Computed: true, }, - "number_of_nodes": { Type: schema.TypeInt, Computed: true, }, - "port": { Type: schema.TypeInt, Computed: true, }, - "preferred_maintenance_window": { Type: schema.TypeString, Computed: true, }, - "publicly_accessible": { Type: schema.TypeBool, Computed: true, }, - "s3_key_prefix": { Type: schema.TypeString, Computed: true, }, - + "log_destination_type": { + Type: schema.TypeString, + Computed: true, + }, + "log_exports": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, "tags": tftags.TagsSchema(), - "vpc_id": { Type: schema.TypeString, Computed: true, }, - "vpc_security_group_ids": { Type: schema.TypeList, Computed: true, @@ -179,34 +198,37 @@ func dataSourceClusterRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).RedshiftConn ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - cluster := d.Get("cluster_identifier").(string) - - log.Printf("[INFO] Reading Redshift Cluster Information: %s", cluster) - - resp, err := conn.DescribeClusters(&redshift.DescribeClustersInput{ - ClusterIdentifier: aws.String(cluster), - }) + clusterID := d.Get("cluster_identifier").(string) + rsc, err := FindClusterByID(conn, clusterID) if err != nil { - return fmt.Errorf("Error describing Redshift Cluster: %s, error: %w", cluster, err) + return fmt.Errorf("reading Redshift Cluster (%s): %w", clusterID, err) } - if resp.Clusters == nil || len(resp.Clusters) == 0 || resp.Clusters[0] == nil { - return fmt.Errorf("Error describing Redshift Cluster: %s, cluster information not found", cluster) - } - - rsc := resp.Clusters[0] - - d.SetId(cluster) + d.SetId(clusterID) d.Set("allow_version_upgrade", rsc.AllowVersionUpgrade) + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: redshift.ServiceName, + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("cluster:%s", d.Id()), + }.String() + d.Set("arn", arn) d.Set("automated_snapshot_retention_period", rsc.AutomatedSnapshotRetentionPeriod) + if rsc.AquaConfiguration != nil { + d.Set("aqua_configuration_status", rsc.AquaConfiguration.AquaConfigurationStatus) + } d.Set("availability_zone", rsc.AvailabilityZone) azr, err := clusterAvailabilityZoneRelocationStatus(rsc) if err != nil { - return fmt.Errorf("error reading Redshift Cluster (%s): %w", d.Id(), err) + return err } d.Set("availability_zone_relocation_enabled", azr) d.Set("cluster_identifier", rsc.ClusterIdentifier) + if err := d.Set("cluster_nodes", flattenClusterNodes(rsc.ClusterNodes)); err != nil { + return fmt.Errorf("setting cluster_nodes: %w", err) + } if len(rsc.ClusterParameterGroups) > 0 { d.Set("cluster_parameter_group_name", rsc.ClusterParameterGroups[0].ParameterGroupName) @@ -217,18 +239,16 @@ func dataSourceClusterRead(d *schema.ResourceData, meta interface{}) error { var csg []string for _, g := range rsc.ClusterSecurityGroups { - csg = append(csg, *g.ClusterSecurityGroupName) - } - if err := d.Set("cluster_security_groups", csg); err != nil { - return fmt.Errorf("Error saving Cluster Security Group Names to state for Redshift Cluster (%s): %w", cluster, err) + csg = append(csg, aws.StringValue(g.ClusterSecurityGroupName)) } + d.Set("cluster_security_groups", csg) d.Set("cluster_subnet_group_name", rsc.ClusterSubnetGroupName) if len(rsc.ClusterNodes) > 1 { - d.Set("cluster_type", "multi-node") + d.Set("cluster_type", clusterTypeMultiNode) } else { - d.Set("cluster_type", "single-node") + d.Set("cluster_type", clusterTypeSingleNode) } d.Set("cluster_version", rsc.ClusterVersion) @@ -248,11 +268,9 @@ func dataSourceClusterRead(d *schema.ResourceData, meta interface{}) error { var iamRoles []string for _, i := range rsc.IamRoles { - iamRoles = append(iamRoles, *i.IamRoleArn) - } - if err := d.Set("iam_roles", iamRoles); err != nil { - return fmt.Errorf("Error saving IAM Roles to state for Redshift Cluster (%s): %w", cluster, err) + iamRoles = append(iamRoles, aws.StringValue(i.IamRoleArn)) } + d.Set("iam_roles", iamRoles) d.Set("kms_key_id", rsc.KmsKeyId) d.Set("master_username", rsc.MasterUsername) @@ -261,34 +279,36 @@ func dataSourceClusterRead(d *schema.ResourceData, meta interface{}) error { d.Set("port", rsc.Endpoint.Port) d.Set("preferred_maintenance_window", rsc.PreferredMaintenanceWindow) d.Set("publicly_accessible", rsc.PubliclyAccessible) + d.Set("default_iam_role_arn", rsc.DefaultIamRoleArn) + d.Set("maintenance_track_name", rsc.MaintenanceTrackName) + d.Set("manual_snapshot_retention_period", rsc.ManualSnapshotRetentionPeriod) if err := d.Set("tags", KeyValueTags(rsc.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } d.Set("vpc_id", rsc.VpcId) var vpcg []string for _, g := range rsc.VpcSecurityGroups { - vpcg = append(vpcg, *g.VpcSecurityGroupId) - } - if err := d.Set("vpc_security_group_ids", vpcg); err != nil { - return fmt.Errorf("Error saving VPC Security Group IDs to state for Redshift Cluster (%s): %w", cluster, err) + vpcg = append(vpcg, aws.StringValue(g.VpcSecurityGroupId)) } + d.Set("vpc_security_group_ids", vpcg) - log.Printf("[INFO] Reading Redshift Cluster Logging Status: %s", cluster) - loggingStatus, loggingErr := conn.DescribeLoggingStatus(&redshift.DescribeLoggingStatusInput{ - ClusterIdentifier: aws.String(cluster), + loggingStatus, err := conn.DescribeLoggingStatus(&redshift.DescribeLoggingStatusInput{ + ClusterIdentifier: aws.String(clusterID), }) - if loggingErr != nil { - return loggingErr + if err != nil { + return fmt.Errorf("reading Redshift Cluster (%s) logging status: %w", d.Id(), err) } if loggingStatus != nil && aws.BoolValue(loggingStatus.LoggingEnabled) { d.Set("enable_logging", loggingStatus.LoggingEnabled) d.Set("bucket_name", loggingStatus.BucketName) d.Set("s3_key_prefix", loggingStatus.S3KeyPrefix) + d.Set("log_exports", flex.FlattenStringSet(loggingStatus.LogExports)) + d.Set("log_destination_type", loggingStatus.LogDestinationType) } return nil diff --git a/internal/service/redshift/cluster_data_source_test.go b/internal/service/redshift/cluster_data_source_test.go index 6e0be44fe4e..6d512ecc52b 100644 --- a/internal/service/redshift/cluster_data_source_test.go +++ b/internal/service/redshift/cluster_data_source_test.go @@ -21,8 +21,10 @@ func TestAccRedshiftClusterDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccClusterDataSourceConfig(rName), + Config: testAccClusterDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "cluster_nodes.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "cluster_nodes.0.public_ip_address"), resource.TestCheckResourceAttrSet(dataSourceName, "allow_version_upgrade"), resource.TestCheckResourceAttrSet(dataSourceName, "automated_snapshot_retention_period"), resource.TestCheckResourceAttrSet(dataSourceName, "availability_zone"), @@ -40,6 +42,9 @@ func TestAccRedshiftClusterDataSource_basic(t *testing.T) { resource.TestCheckResourceAttrSet(dataSourceName, "number_of_nodes"), resource.TestCheckResourceAttrSet(dataSourceName, "port"), resource.TestCheckResourceAttrSet(dataSourceName, "preferred_maintenance_window"), + resource.TestCheckResourceAttrSet(dataSourceName, "manual_snapshot_retention_period"), + resource.TestCheckResourceAttrSet(dataSourceName, "maintenance_track_name"), + resource.TestCheckResourceAttrSet(dataSourceName, "arn"), resource.TestCheckResourceAttrSet(dataSourceName, "publicly_accessible"), resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone_relocation_enabled", resourceName, "availability_zone_relocation_enabled"), ), @@ -59,7 +64,7 @@ func TestAccRedshiftClusterDataSource_vpc(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccClusterWithVPCDataSourceConfig(rName), + Config: testAccClusterDataSourceConfig_vpc(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet(dataSourceName, "vpc_id"), resource.TestCheckResourceAttr(dataSourceName, "vpc_security_group_ids.#", "1"), @@ -82,7 +87,7 @@ func TestAccRedshiftClusterDataSource_logging(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccClusterWithLoggingDataSourceConfig(rName), + Config: testAccClusterDataSourceConfig_logging(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "enable_logging", "true"), resource.TestCheckResourceAttrPair(dataSourceName, "bucket_name", bucketResourceName, "bucket"), @@ -113,7 +118,7 @@ func TestAccRedshiftClusterDataSource_availabilityZoneRelocationEnabled(t *testi }) } -func testAccClusterDataSourceConfig(rName string) string { +func testAccClusterDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_redshift_cluster" "test" { cluster_identifier = %[1]q @@ -132,39 +137,11 @@ data "aws_redshift_cluster" "test" { `, rName) } -func testAccClusterWithVPCDataSourceConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = %[1]q - } -} - -resource "aws_subnet" "test1" { - cidr_block = "10.1.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] - vpc_id = aws_vpc.test.id - - tags = { - Name = %[1]q - } -} - -resource "aws_subnet" "test2" { - cidr_block = "10.1.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] - vpc_id = aws_vpc.test.id - - tags = { - Name = %[1]q - } -} - +func testAccClusterDataSourceConfig_vpc(rName string) string { + return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_redshift_subnet_group" "test" { name = %[1]q - subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] + subnet_ids = aws_subnet.test[*].id } resource "aws_security_group" "test" { @@ -197,7 +174,7 @@ data "aws_redshift_cluster" "test" { `, rName)) } -func testAccClusterWithLoggingDataSourceConfig(rName string) string { +func testAccClusterDataSourceConfig_logging(rName string) string { return fmt.Sprintf(` data "aws_redshift_service_account" "test" {} diff --git a/internal/service/redshift/cluster_iam_roles.go b/internal/service/redshift/cluster_iam_roles.go new file mode 100644 index 00000000000..7c76f59ffc5 --- /dev/null +++ b/internal/service/redshift/cluster_iam_roles.go @@ -0,0 +1,176 @@ +package redshift + +import ( + "fmt" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceClusterIAMRoles() *schema.Resource { + return &schema.Resource{ + Create: resourceClusterIAMRolesCreate, + Read: resourceClusterIAMRolesRead, + Update: resourceClusterIAMRolesUpdate, + Delete: resourceClusterIAMRolesDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(75 * time.Minute), + Update: schema.DefaultTimeout(75 * time.Minute), + Delete: schema.DefaultTimeout(40 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "cluster_identifier": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "default_iam_role_arn": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: verify.ValidARN, + }, + "iam_role_arns": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidARN, + }, + }, + }, + } +} + +func resourceClusterIAMRolesCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + clusterID := d.Get("cluster_identifier").(string) + input := &redshift.ModifyClusterIamRolesInput{ + ClusterIdentifier: aws.String(clusterID), + } + + if v, ok := d.GetOk("default_iam_role_arn"); ok { + input.DefaultIamRoleArn = aws.String(v.(string)) + } + + if v, ok := d.GetOk("iam_role_arns"); ok && v.(*schema.Set).Len() > 0 { + input.AddIamRoles = flex.ExpandStringSet(v.(*schema.Set)) + } + + log.Printf("[DEBUG] Adding Redshift Cluster IAM Roles: %s", input) + output, err := conn.ModifyClusterIamRoles(input) + + if err != nil { + return fmt.Errorf("creating Redshift Cluster IAM Roles (%s): %w", clusterID, err) + } + + d.SetId(aws.StringValue(output.Cluster.ClusterIdentifier)) + + if _, err := waitClusterUpdated(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for Redshift Cluster IAM Roles (%s) update: %w", d.Id(), err) + } + + return resourceClusterIAMRolesRead(d, meta) +} + +func resourceClusterIAMRolesRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + rsc, err := FindClusterByID(conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift Cluster IAM Roles (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("reading Redshift Cluster IAM Roles (%s): %w", d.Id(), err) + } + + var roleARNs []*string + + for _, iamRole := range rsc.IamRoles { + roleARNs = append(roleARNs, iamRole.IamRoleArn) + } + + d.Set("cluster_identifier", rsc.ClusterIdentifier) + d.Set("default_iam_role_arn", rsc.DefaultIamRoleArn) + d.Set("iam_role_arns", aws.StringValueSlice(roleARNs)) + + return nil +} + +func resourceClusterIAMRolesUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + o, n := d.GetChange("iam_role_arns") + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } + os := o.(*schema.Set) + ns := n.(*schema.Set) + add := ns.Difference(os) + del := os.Difference(ns) + + input := &redshift.ModifyClusterIamRolesInput{ + AddIamRoles: flex.ExpandStringSet(add), + ClusterIdentifier: aws.String(d.Id()), + RemoveIamRoles: flex.ExpandStringSet(del), + DefaultIamRoleArn: aws.String(d.Get("default_iam_role_arn").(string)), + } + + log.Printf("[DEBUG] Modifying Redshift Cluster IAM Roles: %s", input) + _, err := conn.ModifyClusterIamRoles(input) + + if err != nil { + return fmt.Errorf("updating Redshift Cluster IAM Roles (%s): %w", d.Id(), err) + } + + if _, err := waitClusterUpdated(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for Redshift Cluster IAM Roles (%s) update: %w", d.Id(), err) + } + + return resourceClusterIAMRolesRead(d, meta) +} + +func resourceClusterIAMRolesDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + input := &redshift.ModifyClusterIamRolesInput{ + ClusterIdentifier: aws.String(d.Id()), + RemoveIamRoles: flex.ExpandStringSet(d.Get("iam_role_arns").(*schema.Set)), + DefaultIamRoleArn: aws.String(d.Get("default_iam_role_arn").(string)), + } + + log.Printf("[DEBUG] Removing Redshift Cluster IAM Roles: %s", input) + _, err := conn.ModifyClusterIamRoles(input) + + if err != nil { + return fmt.Errorf("deleting Redshift Cluster IAM Roles (%s): %w", d.Id(), err) + } + + if _, err := waitClusterUpdated(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for Redshift Cluster IAM Roles (%s) update: %w", d.Id(), err) + } + + return nil +} diff --git a/internal/service/redshift/cluster_iam_roles_test.go b/internal/service/redshift/cluster_iam_roles_test.go new file mode 100644 index 00000000000..f3bcb099b56 --- /dev/null +++ b/internal/service/redshift/cluster_iam_roles_test.go @@ -0,0 +1,158 @@ +package redshift_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/redshift" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" +) + +func TestAccRedshiftClusterIAMRoles_basic(t *testing.T) { + var v redshift.Cluster + resourceName := "aws_redshift_cluster_iam_roles.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccClusterIAMRolesConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckClusterExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "iam_role_arns.#", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccClusterIAMRolesConfig_updated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckClusterExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "iam_role_arns.#", "2"), + ), + }, + { + Config: testAccClusterIAMRolesConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckClusterExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "iam_role_arns.#", "1"), + ), + }, + }, + }) +} + +func TestAccRedshiftClusterIAMRoles_disappears(t *testing.T) { + var v redshift.Cluster + resourceName := "aws_redshift_cluster.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccClusterIAMRolesConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckClusterExists(resourceName, &v), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceCluster(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccClusterIAMRolesConfigBase(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInExclude("usw2-az2"), fmt.Sprintf(` +resource "aws_iam_role" "ec2" { + name = "%[1]s-ec2" + path = "/" + + assume_role_policy = < 0 { + createOpts.VpcSecurityGroupIds = flex.ExpandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("cluster_identifier"); ok { + createOpts.ClusterIdentifier = aws.String(v.(string)) + } + + if v, ok := d.GetOk("resource_owner"); ok { + createOpts.ResourceOwner = aws.String(v.(string)) + } + + _, err := conn.CreateEndpointAccess(&createOpts) + if err != nil { + return fmt.Errorf("error creating Redshift endpoint access: %w", err) + } + + d.SetId(aws.StringValue(createOpts.EndpointName)) + log.Printf("[INFO] Redshift endpoint access ID: %s", d.Id()) + + if _, err := waitEndpointAccessActive(conn, d.Id()); err != nil { + return fmt.Errorf("error waiting for Redshift Endpoint Access (%s) to be active: %w", d.Id(), err) + } + + return resourceEndpointAccessRead(d, meta) +} + +func resourceEndpointAccessRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + endpoint, err := FindEndpointAccessByName(conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift endpoint access (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error reading Redshift endpoint access (%s): %w", d.Id(), err) + } + + d.Set("endpoint_name", endpoint.EndpointName) + d.Set("subnet_group_name", endpoint.SubnetGroupName) + d.Set("vpc_security_group_ids", vpcSgsIdsToSlice(endpoint.VpcSecurityGroups)) + d.Set("resource_owner", endpoint.ResourceOwner) + d.Set("cluster_identifier", endpoint.ClusterIdentifier) + d.Set("port", endpoint.Port) + d.Set("address", endpoint.Address) + + if err := d.Set("vpc_endpoint", flattenVPCEndpoint(endpoint.VpcEndpoint)); err != nil { + return fmt.Errorf("setting vpc_endpoint: %w", err) + } + + return nil +} + +func resourceEndpointAccessUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + if d.HasChanges("vpc_security_group_ids") { + _, n := d.GetChange("vpc_security_group_ids") + if n == nil { + n = new(schema.Set) + } + ns := n.(*schema.Set) + + var sIds []*string + for _, s := range ns.List() { + sIds = append(sIds, aws.String(s.(string))) + } + + _, err := conn.ModifyEndpointAccess(&redshift.ModifyEndpointAccessInput{ + EndpointName: aws.String(d.Id()), + VpcSecurityGroupIds: sIds, + }) + + if err != nil { + return fmt.Errorf("error updating Redshift endpoint access (%s): %w", d.Id(), err) + } + + if _, err := waitEndpointAccessActive(conn, d.Id()); err != nil { + return fmt.Errorf("error waiting for Redshift Endpoint Access (%s) to be active: %w", d.Id(), err) + } + } + + return resourceEndpointAccessRead(d, meta) +} + +func resourceEndpointAccessDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + _, err := conn.DeleteEndpointAccess(&redshift.DeleteEndpointAccessInput{ + EndpointName: aws.String(d.Id()), + }) + + if err != nil { + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeEndpointNotFoundFault) { + return nil + } + return err + } + + if _, err := waitEndpointAccessDeleted(conn, d.Id()); err != nil { + return fmt.Errorf("error waiting for Redshift Endpoint Access (%s) to be deleted: %w", d.Id(), err) + } + + return nil +} + +func vpcSgsIdsToSlice(vpsSgsIds []*redshift.VpcSecurityGroupMembership) []string { + VpcSgsSlice := make([]string, 0, len(vpsSgsIds)) + for _, s := range vpsSgsIds { + VpcSgsSlice = append(VpcSgsSlice, *s.VpcSecurityGroupId) + } + return VpcSgsSlice +} + +func flattenVPCEndpoint(apiObject *redshift.VpcEndpoint) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.NetworkInterfaces; v != nil { + tfMap["network_interface"] = flattenNetworkInterfaces(v) + } + + if v := apiObject.VpcEndpointId; v != nil { + tfMap["vpc_endpoint_id"] = aws.StringValue(v) + } + + if v := apiObject.VpcId; v != nil { + tfMap["vpc_id"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +func flattenNetworkInterface(apiObject *redshift.NetworkInterface) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.AvailabilityZone; v != nil { + tfMap["availability_zone"] = aws.StringValue(v) + } + + if v := apiObject.NetworkInterfaceId; v != nil { + tfMap["network_interface_id"] = aws.StringValue(v) + } + + if v := apiObject.PrivateIpAddress; v != nil { + tfMap["private_ip_address"] = aws.StringValue(v) + } + + if v := apiObject.SubnetId; v != nil { + tfMap["subnet_id"] = aws.StringValue(v) + } + + return tfMap +} + +func flattenNetworkInterfaces(apiObjects []*redshift.NetworkInterface) []interface{} { + if len(apiObjects) == 0 { + return nil + } + + var tfList []interface{} + + for _, apiObject := range apiObjects { + if apiObject == nil { + continue + } + + tfList = append(tfList, flattenNetworkInterface(apiObject)) + } + + return tfList +} diff --git a/internal/service/redshift/endpoint_access_test.go b/internal/service/redshift/endpoint_access_test.go new file mode 100644 index 00000000000..1852537d56b --- /dev/null +++ b/internal/service/redshift/endpoint_access_test.go @@ -0,0 +1,248 @@ +package redshift_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/redshift" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccRedshiftEndpointAccess_basic(t *testing.T) { + var v redshift.EndpointAccess + rName := fmt.Sprintf("tf-acc-test-%s", sdkacctest.RandString(18)) + resourceName := "aws_redshift_endpoint_access.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointAccessDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointAccessConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointAccessExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "endpoint_name", rName), + resource.TestCheckResourceAttr(resourceName, "port", "5439"), + resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "1"), + resource.TestCheckResourceAttr(resourceName, "vpc_endpoint.#", "1"), + acctest.CheckResourceAttrAccountID(resourceName, "resource_owner"), + resource.TestCheckResourceAttrPair(resourceName, "subnet_group_name", "aws_redshift_subnet_group.test", "id"), + resource.TestCheckResourceAttrPair(resourceName, "cluster_identifier", "aws_redshift_cluster.test", "cluster_identifier"), + resource.TestCheckResourceAttrSet(resourceName, "address"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccRedshiftEndpointAccess_sgs(t *testing.T) { + var v redshift.EndpointAccess + rName := fmt.Sprintf("tf-acc-test-%s", sdkacctest.RandString(18)) + resourceName := "aws_redshift_endpoint_access.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointAccessDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointAccessConfig_sgs(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointAccessExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccEndpointAccessConfig_sgsUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointAccessExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "2"), + ), + }, + }, + }) +} + +func TestAccRedshiftEndpointAccess_disappears(t *testing.T) { + var v redshift.EndpointAccess + rName := fmt.Sprintf("tf-acc-test-%s", sdkacctest.RandString(18)) + resourceName := "aws_redshift_endpoint_access.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointAccessDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointAccessConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointAccessExists(resourceName, &v), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceEndpointAccess(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccRedshiftEndpointAccess_disappears_cluster(t *testing.T) { + var v redshift.EndpointAccess + rName := fmt.Sprintf("tf-acc-test-%s", sdkacctest.RandString(18)) + resourceName := "aws_redshift_endpoint_access.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointAccessDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointAccessConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointAccessExists(resourceName, &v), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceCluster(), "aws_redshift_cluster.test"), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckEndpointAccessDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_redshift_endpoint_access" { + continue + } + + _, err := tfredshift.FindEndpointAccessByName(conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("Redshift Endpoint Access %s still exists", rs.Primary.ID) + } + + return nil +} + +func testAccCheckEndpointAccessExists(n string, v *redshift.EndpointAccess) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Redshift Endpoint Access ID is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + output, err := tfredshift.FindEndpointAccessByName(conn, rs.Primary.ID) + + if err != nil { + return err + } + + *v = *output + + return nil + } +} + +func testAccEndpointAccessConfigBase(rName string) string { + return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` +resource "aws_redshift_subnet_group" "test" { + name = %[1]q + subnet_ids = aws_subnet.test[*].id +} + +resource "aws_redshift_cluster" "test" { + cluster_identifier = %[1]q + availability_zone = data.aws_availability_zones.available.names[0] + database_name = "mydb" + master_username = "foo_test" + master_password = "Mustbe8characters" + node_type = "ra3.xlplus" + automated_snapshot_retention_period = 1 + allow_version_upgrade = false + skip_final_snapshot = true + availability_zone_relocation_enabled = true + publicly_accessible = false +} +`, rName)) +} + +func testAccEndpointAccessConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccEndpointAccessConfigBase(rName), fmt.Sprintf(` +resource "aws_redshift_endpoint_access" "test" { + endpoint_name = %[1]q + subnet_group_name = aws_redshift_subnet_group.test.id + cluster_identifier = aws_redshift_cluster.test.cluster_identifier +} +`, rName)) +} + +func testAccEndpointAccessConfig_sgs(rName string) string { + return acctest.ConfigCompose(testAccEndpointAccessConfigBase(rName), fmt.Sprintf(` +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id +} + +resource "aws_redshift_endpoint_access" "test" { + endpoint_name = %[1]q + subnet_group_name = aws_redshift_subnet_group.test.id + cluster_identifier = aws_redshift_cluster.test.cluster_identifier + vpc_security_group_ids = [aws_security_group.test.id] +} +`, rName)) +} + +func testAccEndpointAccessConfig_sgsUpdated(rName string) string { + return acctest.ConfigCompose(testAccEndpointAccessConfigBase(rName), fmt.Sprintf(` +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id +} + +resource "aws_security_group" "test2" { + name = "%[1]s-2" + vpc_id = aws_vpc.test.id +} + +resource "aws_redshift_endpoint_access" "test" { + endpoint_name = %[1]q + subnet_group_name = aws_redshift_subnet_group.test.id + cluster_identifier = aws_redshift_cluster.test.cluster_identifier + vpc_security_group_ids = [aws_security_group.test.id, aws_security_group.test2.id] +} +`, rName)) +} diff --git a/internal/service/redshift/event_subscription.go b/internal/service/redshift/event_subscription.go index 3b4ffb5a6bc..eae1f8eb908 100644 --- a/internal/service/redshift/event_subscription.go +++ b/internal/service/redshift/event_subscription.go @@ -10,9 +10,11 @@ import ( "github.com/aws/aws-sdk-go/service/redshift" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -22,60 +24,81 @@ func ResourceEventSubscription() *schema.Resource { Read: resourceEventSubscriptionRead, Update: resourceEventSubscriptionUpdate, Delete: resourceEventSubscriptionDelete, + Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, + Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(40 * time.Minute), Delete: schema.DefaultTimeout(40 * time.Minute), Update: schema.DefaultTimeout(40 * time.Minute), }, + Schema: map[string]*schema.Schema{ "arn": { Type: schema.TypeString, Computed: true, }, - + "customer_aws_id": { + Type: schema.TypeString, + Computed: true, + }, + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "event_categories": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + "configuration", + "management", + "monitoring", + "security", + "pending", + }, false), + }, + }, "name": { Type: schema.TypeString, Required: true, ForceNew: true, }, + "severity": { + Type: schema.TypeString, + Optional: true, + Default: "INFO", + ValidateFunc: validation.StringInSlice([]string{ + "ERROR", + "INFO", + }, false), + }, "sns_topic_arn": { Type: schema.TypeString, Required: true, ValidateFunc: verify.ValidARN, }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "event_categories": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, "source_ids": { Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "source_type": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + "cluster", + "cluster-parameter-group", + "cluster-security-group", + "cluster-snapshot", + "scheduled-action", + }, false), }, - "enabled": { - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - "severity": { - Type: schema.TypeString, - Optional: true, - }, - "customer_aws_id": { + "status": { Type: schema.TypeString, Computed: true, }, @@ -96,13 +119,25 @@ func resourceEventSubscriptionCreate(d *schema.ResourceData, meta interface{}) e SubscriptionName: aws.String(d.Get("name").(string)), SnsTopicArn: aws.String(d.Get("sns_topic_arn").(string)), Enabled: aws.Bool(d.Get("enabled").(bool)), - SourceIds: flex.ExpandStringSet(d.Get("source_ids").(*schema.Set)), - SourceType: aws.String(d.Get("source_type").(string)), - Severity: aws.String(d.Get("severity").(string)), - EventCategories: flex.ExpandStringSet(d.Get("event_categories").(*schema.Set)), Tags: Tags(tags.IgnoreAWS()), } + if v, ok := d.GetOk("event_categories"); ok && v.(*schema.Set).Len() > 0 { + request.EventCategories = flex.ExpandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("source_ids"); ok && v.(*schema.Set).Len() > 0 { + request.SourceIds = flex.ExpandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("severity"); ok { + request.Severity = aws.String(v.(string)) + } + + if v, ok := d.GetOk("source_type"); ok { + request.SourceType = aws.String(v.(string)) + } + log.Println("[DEBUG] Create Redshift Event Subscription:", request) output, err := conn.CreateEventSubscription(request) @@ -120,6 +155,21 @@ func resourceEventSubscriptionRead(d *schema.ResourceData, meta interface{}) err defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + sub, err := FindEventSubscriptionByName(conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift Event Subscription (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("error retrieving Redshift Event Subscription %s: %w", d.Id(), err) + } + + if err != nil { + return fmt.Errorf("error reading Redshift Event Subscription (%s): %w", d.Id(), err) + } + arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, Service: "redshift", @@ -127,46 +177,17 @@ func resourceEventSubscriptionRead(d *schema.ResourceData, meta interface{}) err AccountID: meta.(*conns.AWSClient).AccountID, Resource: fmt.Sprintf("eventsubscription:%s", d.Id()), }.String() - d.Set("arn", arn) + d.Set("customer_aws_id", sub.CustomerAwsId) + d.Set("enabled", sub.Enabled) + d.Set("event_categories", aws.StringValueSlice(sub.EventCategoriesList)) + d.Set("name", sub.CustSubscriptionId) + d.Set("severity", sub.Severity) + d.Set("sns_topic_arn", sub.SnsTopicArn) + d.Set("source_ids", aws.StringValueSlice(sub.SourceIdsList)) + d.Set("source_type", sub.SourceType) + d.Set("status", sub.Status) - sub, err := resourceEventSubscriptionRetrieve(d.Id(), conn) - if err != nil { - return fmt.Errorf("Error retrieving Redshift Event Subscription %s: %s", d.Id(), err) - } - if sub == nil { - log.Printf("[WARN] Redshift Event Subscription (%s) not found - removing from state", d.Id()) - d.SetId("") - return nil - } - - if err := d.Set("name", sub.CustSubscriptionId); err != nil { - return err - } - if err := d.Set("sns_topic_arn", sub.SnsTopicArn); err != nil { - return err - } - if err := d.Set("status", sub.Status); err != nil { - return err - } - if err := d.Set("source_type", sub.SourceType); err != nil { - return err - } - if err := d.Set("severity", sub.Severity); err != nil { - return err - } - if err := d.Set("enabled", sub.Enabled); err != nil { - return err - } - if err := d.Set("source_ids", flex.FlattenStringList(sub.SourceIdsList)); err != nil { - return err - } - if err := d.Set("event_categories", flex.FlattenStringList(sub.EventCategoriesList)); err != nil { - return err - } - if err := d.Set("customer_aws_id", sub.CustomerAwsId); err != nil { - return err - } tags := KeyValueTags(sub.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 @@ -181,45 +202,25 @@ func resourceEventSubscriptionRead(d *schema.ResourceData, meta interface{}) err return nil } -func resourceEventSubscriptionRetrieve(name string, conn *redshift.Redshift) (*redshift.EventSubscription, error) { - - request := &redshift.DescribeEventSubscriptionsInput{ - SubscriptionName: aws.String(name), - } - - describeResp, err := conn.DescribeEventSubscriptions(request) - if err != nil { - if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSubscriptionNotFoundFault) { - log.Printf("[WARN] No Redshift Event Subscription by name (%s) found", name) - return nil, nil - } - return nil, fmt.Errorf("Error reading Redshift Event Subscription %s: %s", name, err) - } - - if len(describeResp.EventSubscriptionsList) != 1 { - return nil, fmt.Errorf("Unable to find Redshift Event Subscription: %#v", describeResp.EventSubscriptionsList) - } - - return describeResp.EventSubscriptionsList[0], nil -} - func resourceEventSubscriptionUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).RedshiftConn - req := &redshift.ModifyEventSubscriptionInput{ - SubscriptionName: aws.String(d.Id()), - SnsTopicArn: aws.String(d.Get("sns_topic_arn").(string)), - Enabled: aws.Bool(d.Get("enabled").(bool)), - SourceIds: flex.ExpandStringSet(d.Get("source_ids").(*schema.Set)), - SourceType: aws.String(d.Get("source_type").(string)), - Severity: aws.String(d.Get("severity").(string)), - EventCategories: flex.ExpandStringSet(d.Get("event_categories").(*schema.Set)), - } + if d.HasChangesExcept("tags", "tags_all") { + req := &redshift.ModifyEventSubscriptionInput{ + SubscriptionName: aws.String(d.Id()), + SnsTopicArn: aws.String(d.Get("sns_topic_arn").(string)), + Enabled: aws.Bool(d.Get("enabled").(bool)), + SourceIds: flex.ExpandStringSet(d.Get("source_ids").(*schema.Set)), + SourceType: aws.String(d.Get("source_type").(string)), + Severity: aws.String(d.Get("severity").(string)), + EventCategories: flex.ExpandStringSet(d.Get("event_categories").(*schema.Set)), + } - log.Printf("[DEBUG] Redshift Event Subscription modification request: %#v", req) - _, err := conn.ModifyEventSubscription(req) - if err != nil { - return fmt.Errorf("Modifying Redshift Event Subscription %s failed: %s", d.Id(), err) + log.Printf("[DEBUG] Redshift Event Subscription modification request: %#v", req) + _, err := conn.ModifyEventSubscription(req) + if err != nil { + return fmt.Errorf("Modifying Redshift Event Subscription %s failed: %s", d.Id(), err) + } } if d.HasChange("tags_all") { diff --git a/internal/service/redshift/event_subscription_test.go b/internal/service/redshift/event_subscription_test.go index 8a2c2551b9c..ee1a8e20cf5 100644 --- a/internal/service/redshift/event_subscription_test.go +++ b/internal/service/redshift/event_subscription_test.go @@ -2,22 +2,23 @@ package redshift_test import ( "fmt" + "regexp" "testing" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func TestAccRedshiftEventSubscription_basicUpdate(t *testing.T) { +func TestAccRedshiftEventSubscription_basic(t *testing.T) { var v redshift.EventSubscription - rInt := sdkacctest.RandInt() - rName := fmt.Sprintf("tf-acc-test-redshift-event-subs-%d", rInt) + resourceName := "aws_redshift_event_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -26,73 +27,47 @@ func TestAccRedshiftEventSubscription_basicUpdate(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionConfig(rInt), + Config: testAccEventSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEventSubscriptionExists("aws_redshift_event_subscription.bar", &v), - resource.TestCheckResourceAttr("aws_redshift_event_subscription.bar", "enabled", "true"), - resource.TestCheckResourceAttr("aws_redshift_event_subscription.bar", "source_type", "cluster"), - resource.TestCheckResourceAttr("aws_redshift_event_subscription.bar", "name", rName), - resource.TestCheckResourceAttr("aws_redshift_event_subscription.bar", "tags.%", "1"), - resource.TestCheckResourceAttr("aws_redshift_event_subscription.bar", "tags.Name", "name"), - ), - }, - { - Config: testAccEventSubscriptionUpdateConfig(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckEventSubscriptionExists("aws_redshift_event_subscription.bar", &v), - resource.TestCheckResourceAttr("aws_redshift_event_subscription.bar", "enabled", "false"), - resource.TestCheckResourceAttr("aws_redshift_event_subscription.bar", "source_type", "cluster-snapshot"), - resource.TestCheckResourceAttr("aws_redshift_event_subscription.bar", "tags.%", "1"), - resource.TestCheckResourceAttr("aws_redshift_event_subscription.bar", "tags.Name", "new-name"), + testAccCheckEventSubscriptionExists(resourceName, &v), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "redshift", regexp.MustCompile(`eventsubscription:.+`)), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "severity", "INFO"), + resource.TestCheckResourceAttr(resourceName, "status", "active"), + acctest.CheckResourceAttrAccountID(resourceName, "customer_aws_id"), + resource.TestCheckResourceAttr(resourceName, "event_categories.#", "0"), + resource.TestCheckResourceAttr(resourceName, "source_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "sns_topic_arn", "aws_sns_topic.test", "arn"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { - ResourceName: "aws_redshift_event_subscription.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, - }, - }) -} - -func TestAccRedshiftEventSubscription_withPrefix(t *testing.T) { - var v redshift.EventSubscription - rInt := sdkacctest.RandInt() - rName := fmt.Sprintf("tf-acc-test-redshift-event-subs-%d", rInt) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), - ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckEventSubscriptionDestroy, - Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionConfig(rInt), + Config: testAccEventSubscriptionConfig_update(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEventSubscriptionExists("aws_redshift_event_subscription.bar", &v), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "enabled", "true"), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "source_type", "cluster"), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "name", rName), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "tags.Name", "name"), + testAccCheckEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "severity", "INFO"), + resource.TestCheckResourceAttr(resourceName, "source_type", "cluster-snapshot"), + resource.TestCheckTypeSetElemAttr(resourceName, "event_categories.*", "monitoring"), + resource.TestCheckResourceAttrPair(resourceName, "sns_topic_arn", "aws_sns_topic.test", "arn"), + acctest.CheckResourceAttrAccountID(resourceName, "customer_aws_id"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, - { - ResourceName: "aws_redshift_event_subscription.bar", - ImportState: true, - ImportStateVerify: true, - }, }, }) } func TestAccRedshiftEventSubscription_withSourceIDs(t *testing.T) { var v redshift.EventSubscription - rInt := sdkacctest.RandInt() - rName := fmt.Sprintf("tf-acc-test-redshift-event-subs-with-ids-%d", rInt) + resourceName := "aws_redshift_event_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -101,35 +76,27 @@ func TestAccRedshiftEventSubscription_withSourceIDs(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionWithSourceIDsConfig(rInt), + Config: testAccEventSubscriptionConfig_sourceIDs(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEventSubscriptionExists("aws_redshift_event_subscription.bar", &v), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "enabled", "true"), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "source_type", "cluster-parameter-group"), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "name", rName), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "source_ids.#", "1"), + testAccCheckEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "source_type", "cluster-parameter-group"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "source_ids.#", "1"), ), }, { - Config: testAccEventSubscriptionUpdateSourceIDsConfig(rInt), + Config: testAccEventSubscriptionConfig_updateSourceIDs(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEventSubscriptionExists("aws_redshift_event_subscription.bar", &v), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "enabled", "true"), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "source_type", "cluster-parameter-group"), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "name", rName), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "source_ids.#", "2"), + testAccCheckEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "source_type", "cluster-parameter-group"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "source_ids.#", "2"), ), }, { - ResourceName: "aws_redshift_event_subscription.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -139,8 +106,8 @@ func TestAccRedshiftEventSubscription_withSourceIDs(t *testing.T) { func TestAccRedshiftEventSubscription_categoryUpdate(t *testing.T) { var v redshift.EventSubscription - rInt := sdkacctest.RandInt() - rName := fmt.Sprintf("tf-acc-test-redshift-event-subs-%d", rInt) + resourceName := "aws_redshift_event_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -149,29 +116,23 @@ func TestAccRedshiftEventSubscription_categoryUpdate(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionConfig(rInt), + Config: testAccEventSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEventSubscriptionExists("aws_redshift_event_subscription.bar", &v), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "enabled", "true"), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "source_type", "cluster"), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "name", rName), + testAccCheckEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "name", rName), ), }, { - Config: testAccEventSubscriptionUpdateCategoriesConfig(rInt), + Config: testAccEventSubscriptionConfig_updateCategories(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckEventSubscriptionExists("aws_redshift_event_subscription.bar", &v), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "enabled", "true"), - resource.TestCheckResourceAttr( - "aws_redshift_event_subscription.bar", "source_type", "cluster"), + testAccCheckEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "source_type", "cluster"), ), }, { - ResourceName: "aws_redshift_event_subscription.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -179,10 +140,10 @@ func TestAccRedshiftEventSubscription_categoryUpdate(t *testing.T) { }) } -func TestAccRedshiftEventSubscription_tagsUpdate(t *testing.T) { +func TestAccRedshiftEventSubscription_tags(t *testing.T) { var v redshift.EventSubscription - rInt := sdkacctest.RandInt() - resourceName := "aws_redshift_event_subscription.bar" + resourceName := "aws_redshift_event_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -191,38 +152,57 @@ func TestAccRedshiftEventSubscription_tagsUpdate(t *testing.T) { CheckDestroy: testAccCheckEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionConfig(rInt), + Config: testAccEventSubscriptionConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", "name"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { - Config: testAccEventSubscriptionUpdateTagsConfig(rInt, "aaaaa"), + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccEventSubscriptionConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", "name"), - resource.TestCheckResourceAttr(resourceName, "tags.Test", "aaaaa"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { - Config: testAccEventSubscriptionUpdateTagsConfig(rInt, "bbbbb"), + Config: testAccEventSubscriptionConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", "name"), - resource.TestCheckResourceAttr(resourceName, "tags.Test", "bbbbb"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, + }, + }) +} + +func TestAccRedshiftEventSubscription_disappears(t *testing.T) { + var v redshift.EventSubscription + resourceName := "aws_redshift_event_subscription.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEventSubscriptionDestroy, + Steps: []resource.TestStep{ { - Config: testAccEventSubscriptionConfig(rInt), + Config: testAccEventSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEventSubscriptionExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", "name"), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceEventSubscription(), resourceName), ), + ExpectNonEmptyPlan: true, }, }, }) @@ -241,22 +221,14 @@ func testAccCheckEventSubscriptionExists(n string, v *redshift.EventSubscription conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn - opts := redshift.DescribeEventSubscriptionsInput{ - SubscriptionName: aws.String(rs.Primary.ID), - } - - resp, err := conn.DescribeEventSubscriptions(&opts) + out, err := tfredshift.FindEventSubscriptionByName(conn, rs.Primary.ID) if err != nil { return err } - if len(resp.EventSubscriptionsList) != 1 || - *resp.EventSubscriptionsList[0].CustSubscriptionId != rs.Primary.ID { - return fmt.Errorf("Redshift Event Subscription not found") - } + *v = *out - *v = *resp.EventSubscriptionsList[0] return nil } } @@ -269,13 +241,9 @@ func testAccCheckEventSubscriptionDestroy(s *terraform.State) error { continue } - var err error - resp, err := conn.DescribeEventSubscriptions( - &redshift.DescribeEventSubscriptionsInput{ - SubscriptionName: aws.String(rs.Primary.ID), - }) + _, err := tfredshift.FindEventSubscriptionByName(conn, rs.Primary.ID) - if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSubscriptionNotFoundFault) { + if tfresource.NotFound(err) { continue } @@ -283,50 +251,34 @@ func testAccCheckEventSubscriptionDestroy(s *terraform.State) error { return err } - if len(resp.EventSubscriptionsList) != 0 && - *resp.EventSubscriptionsList[0].CustSubscriptionId == rs.Primary.ID { - return fmt.Errorf("Event Subscription still exists") - } + return fmt.Errorf("Redshift Event Subscription %s still exists", rs.Primary.ID) } return nil } -func testAccEventSubscriptionConfig(rInt int) string { +func testAccEventSubscriptionConfig_basic(rName string) string { return fmt.Sprintf(` -resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-redshift-event-subs-sns-topic-%d" +resource "aws_sns_topic" "test" { + name = %[1]q } -resource "aws_redshift_event_subscription" "bar" { - name = "tf-acc-test-redshift-event-subs-%d" - sns_topic_arn = aws_sns_topic.aws_sns_topic.arn - source_type = "cluster" - severity = "INFO" - - event_categories = [ - "configuration", - "management", - "monitoring", - "security", - ] - - tags = { - Name = "name" - } +resource "aws_redshift_event_subscription" "test" { + name = %[1]q + sns_topic_arn = aws_sns_topic.test.arn } -`, rInt, rInt) +`, rName) } -func testAccEventSubscriptionUpdateConfig(rInt int) string { +func testAccEventSubscriptionConfig_update(rName string) string { return fmt.Sprintf(` -resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-redshift-event-subs-sns-topic-%d" +resource "aws_sns_topic" "test" { + name = %[1]q } -resource "aws_redshift_event_subscription" "bar" { - name = "tf-acc-test-redshift-event-subs-%d" - sns_topic_arn = aws_sns_topic.aws_sns_topic.arn +resource "aws_redshift_event_subscription" "test" { + name = %[1]q + sns_topic_arn = aws_sns_topic.test.arn enabled = false source_type = "cluster-snapshot" severity = "INFO" @@ -334,112 +286,122 @@ resource "aws_redshift_event_subscription" "bar" { event_categories = [ "monitoring", ] - - tags = { - Name = "new-name" - } } -`, rInt, rInt) +`, rName) } -func testAccEventSubscriptionWithSourceIDsConfig(rInt int) string { +func testAccEventSubscriptionConfig_sourceIDs(rName string) string { return fmt.Sprintf(` -resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-redshift-event-subs-sns-topic-%d" +resource "aws_sns_topic" "test" { + name = %[1]q } -resource "aws_redshift_parameter_group" "bar" { - name = "redshift-parameter-group-event-%d" +resource "aws_redshift_parameter_group" "test" { + name = %[1]q family = "redshift-1.0" description = "Test parameter group for terraform" } -resource "aws_redshift_event_subscription" "bar" { - name = "tf-acc-test-redshift-event-subs-with-ids-%d" - sns_topic_arn = aws_sns_topic.aws_sns_topic.arn +resource "aws_redshift_event_subscription" "test" { + name = %[1]q + sns_topic_arn = aws_sns_topic.test.arn source_type = "cluster-parameter-group" severity = "INFO" - source_ids = [aws_redshift_parameter_group.bar.id] + source_ids = [aws_redshift_parameter_group.test.id] event_categories = [ "configuration", ] - - tags = { - Name = "name" - } } -`, rInt, rInt, rInt) +`, rName) } -func testAccEventSubscriptionUpdateSourceIDsConfig(rInt int) string { +func testAccEventSubscriptionConfig_updateSourceIDs(rName string) string { return fmt.Sprintf(` -resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-redshift-event-subs-sns-topic-%d" +resource "aws_sns_topic" "test" { + name = %[1]q } -resource "aws_redshift_parameter_group" "bar" { - name = "tf-acc-redshift-parameter-group-event-%d" +resource "aws_redshift_parameter_group" "test" { + name = %[1]q family = "redshift-1.0" description = "Test parameter group for terraform" } resource "aws_redshift_parameter_group" "foo" { - name = "tf-acc-redshift-parameter-group-event-2-%d" + name = "%[1]s-2" family = "redshift-1.0" description = "Test parameter group for terraform" } -resource "aws_redshift_event_subscription" "bar" { - name = "tf-acc-test-redshift-event-subs-with-ids-%d" - sns_topic_arn = aws_sns_topic.aws_sns_topic.arn +resource "aws_redshift_event_subscription" "test" { + name = %[1]q + sns_topic_arn = aws_sns_topic.test.arn source_type = "cluster-parameter-group" severity = "INFO" - source_ids = [aws_redshift_parameter_group.bar.id, aws_redshift_parameter_group.foo.id] + source_ids = [aws_redshift_parameter_group.test.id, aws_redshift_parameter_group.foo.id] event_categories = [ "configuration", ] +} +`, rName) +} - tags = { - Name = "name" - } +func testAccEventSubscriptionConfig_updateCategories(rName string) string { + return fmt.Sprintf(` +resource "aws_sns_topic" "test" { + name = %[1]q +} + +resource "aws_redshift_event_subscription" "test" { + name = %[1]q + sns_topic_arn = aws_sns_topic.test.arn + source_type = "cluster" + severity = "INFO" + + event_categories = [ + "monitoring", + ] } -`, rInt, rInt, rInt, rInt) +`, rName) } -func testAccEventSubscriptionUpdateCategoriesConfig(rInt int) string { +func testAccEventSubscriptionConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` -resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-redshift-event-subs-sns-topic-%d" +resource "aws_sns_topic" "test" { + name = %[1]q } -resource "aws_redshift_event_subscription" "bar" { - name = "tf-acc-test-redshift-event-subs-%d" - sns_topic_arn = aws_sns_topic.aws_sns_topic.arn +resource "aws_redshift_event_subscription" "test" { + name = %[1]q + sns_topic_arn = aws_sns_topic.test.arn source_type = "cluster" severity = "INFO" event_categories = [ + "configuration", + "management", "monitoring", + "security", ] tags = { - Name = "name" + %[2]q = %[3]q } } -`, rInt, rInt) +`, rName, tagKey1, tagValue1) } -func testAccEventSubscriptionUpdateTagsConfig(rInt int, rString string) string { +func testAccEventSubscriptionConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` -resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-redshift-event-subs-sns-topic-%d" +resource "aws_sns_topic" "test" { + name = %[1]q } -resource "aws_redshift_event_subscription" "bar" { - name = "tf-acc-test-redshift-event-subs-%d" - sns_topic_arn = aws_sns_topic.aws_sns_topic.arn +resource "aws_redshift_event_subscription" "test" { + name = %[1]q + sns_topic_arn = aws_sns_topic.test.arn source_type = "cluster" severity = "INFO" @@ -451,9 +413,9 @@ resource "aws_redshift_event_subscription" "bar" { ] tags = { - Name = "name" - Test = "%s" + %[2]q = %[3]q + %[4]q = %[5]q } } -`, rInt, rInt, rString) +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) } diff --git a/internal/service/redshift/find.go b/internal/service/redshift/find.go index 18d6defb0a9..93dce64cad7 100644 --- a/internal/service/redshift/find.go +++ b/internal/service/redshift/find.go @@ -1,6 +1,8 @@ package redshift import ( + "fmt" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" @@ -8,12 +10,22 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func FindClusterByID(conn *redshift.Redshift, id string) (*redshift.Cluster, error) { - input := &redshift.DescribeClustersInput{ - ClusterIdentifier: aws.String(id), - } +func findClusters(conn *redshift.Redshift, input *redshift.DescribeClustersInput) ([]*redshift.Cluster, error) { + var output []*redshift.Cluster - output, err := conn.DescribeClusters(input) + err := conn.DescribeClustersPages(input, func(page *redshift.DescribeClustersOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, v := range page.Clusters { + if v != nil { + output = append(output, v) + } + } + + return !lastPage + }) if tfawserr.ErrCodeEquals(err, redshift.ErrCodeClusterNotFoundFault) { return nil, &resource.NotFoundError{ @@ -26,15 +38,46 @@ func FindClusterByID(conn *redshift.Redshift, id string) (*redshift.Cluster, err return nil, err } - if output == nil || len(output.Clusters) == 0 || output.Clusters[0] == nil { + return output, nil +} + +func findCluster(conn *redshift.Redshift, input *redshift.DescribeClustersInput) (*redshift.Cluster, error) { + output, err := findClusters(conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 || output[0] == nil { return nil, tfresource.NewEmptyResultError(input) } - if count := len(output.Clusters); count > 1 { + if count := len(output); count > 1 { return nil, tfresource.NewTooManyResultsError(count, input) } - return output.Clusters[0], nil + return output[0], nil +} + +func FindClusterByID(conn *redshift.Redshift, id string) (*redshift.Cluster, error) { + input := &redshift.DescribeClustersInput{ + ClusterIdentifier: aws.String(id), + } + + output, err := findCluster(conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.StringValue(output.ClusterIdentifier) != id { + return nil, &resource.NotFoundError{ + LastRequest: input, + } + } + + return output, nil } func FindScheduledActionByName(conn *redshift.Redshift, name string) (*redshift.ScheduledAction, error) { @@ -65,3 +108,251 @@ func FindScheduledActionByName(conn *redshift.Redshift, name string) (*redshift. return output.ScheduledActions[0], nil } + +func FindScheduleAssociationById(conn *redshift.Redshift, id string) (string, *redshift.ClusterAssociatedToSchedule, error) { + clusterIdentifier, scheduleIdentifier, err := SnapshotScheduleAssociationParseID(id) + if err != nil { + return "", nil, fmt.Errorf("error parsing Redshift Cluster Snapshot Schedule Association ID %s: %s", id, err) + } + + input := &redshift.DescribeSnapshotSchedulesInput{ + ClusterIdentifier: aws.String(clusterIdentifier), + ScheduleIdentifier: aws.String(scheduleIdentifier), + } + resp, err := conn.DescribeSnapshotSchedules(input) + + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotScheduleNotFoundFault) { + return "", nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return "", nil, err + } + + if resp.SnapshotSchedules == nil || len(resp.SnapshotSchedules) == 0 { + return "", nil, tfresource.NewEmptyResultError(input) + } + + snapshotSchedule := resp.SnapshotSchedules[0] + + if snapshotSchedule == nil { + return "", nil, tfresource.NewEmptyResultError(input) + } + + var associatedCluster *redshift.ClusterAssociatedToSchedule + for _, cluster := range snapshotSchedule.AssociatedClusters { + if aws.StringValue(cluster.ClusterIdentifier) == clusterIdentifier { + associatedCluster = cluster + break + } + } + + if associatedCluster == nil { + return "", nil, tfresource.NewEmptyResultError(input) + } + + return aws.StringValue(snapshotSchedule.ScheduleIdentifier), associatedCluster, nil +} + +func FindHSMClientCertificateByID(conn *redshift.Redshift, id string) (*redshift.HsmClientCertificate, error) { + input := redshift.DescribeHsmClientCertificatesInput{ + HsmClientCertificateIdentifier: aws.String(id), + } + + out, err := conn.DescribeHsmClientCertificates(&input) + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeHsmClientCertificateNotFoundFault) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if out == nil || len(out.HsmClientCertificates) == 0 { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(out.HsmClientCertificates); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return out.HsmClientCertificates[0], nil +} + +func FindHSMConfigurationByID(conn *redshift.Redshift, id string) (*redshift.HsmConfiguration, error) { + input := redshift.DescribeHsmConfigurationsInput{ + HsmConfigurationIdentifier: aws.String(id), + } + + out, err := conn.DescribeHsmConfigurations(&input) + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeHsmConfigurationNotFoundFault) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if out == nil || len(out.HsmConfigurations) == 0 { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(out.HsmConfigurations); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return out.HsmConfigurations[0], nil +} + +func FindUsageLimitByID(conn *redshift.Redshift, id string) (*redshift.UsageLimit, error) { + input := &redshift.DescribeUsageLimitsInput{ + UsageLimitId: aws.String(id), + } + + output, err := conn.DescribeUsageLimits(input) + + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeUsageLimitNotFoundFault) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || len(output.UsageLimits) == 0 || output.UsageLimits[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output.UsageLimits); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output.UsageLimits[0], nil +} + +func FindAuthenticationProfileByID(conn *redshift.Redshift, id string) (*redshift.AuthenticationProfile, error) { + input := redshift.DescribeAuthenticationProfilesInput{ + AuthenticationProfileName: aws.String(id), + } + + out, err := conn.DescribeAuthenticationProfiles(&input) + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeAuthenticationProfileNotFoundFault) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if out == nil || len(out.AuthenticationProfiles) == 0 { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(out.AuthenticationProfiles); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return out.AuthenticationProfiles[0], nil +} + +func FindEventSubscriptionByName(conn *redshift.Redshift, name string) (*redshift.EventSubscription, error) { + input := &redshift.DescribeEventSubscriptionsInput{ + SubscriptionName: aws.String(name), + } + + output, err := conn.DescribeEventSubscriptions(input) + + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSubscriptionNotFoundFault) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || len(output.EventSubscriptionsList) == 0 || output.EventSubscriptionsList[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output.EventSubscriptionsList); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output.EventSubscriptionsList[0], nil +} + +func FindSubnetGroupByName(conn *redshift.Redshift, name string) (*redshift.ClusterSubnetGroup, error) { + input := &redshift.DescribeClusterSubnetGroupsInput{ + ClusterSubnetGroupName: aws.String(name), + } + + output, err := conn.DescribeClusterSubnetGroups(input) + + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeClusterSubnetGroupNotFoundFault) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || len(output.ClusterSubnetGroups) == 0 || output.ClusterSubnetGroups[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output.ClusterSubnetGroups); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output.ClusterSubnetGroups[0], nil +} + +func FindEndpointAccessByName(conn *redshift.Redshift, name string) (*redshift.EndpointAccess, error) { + input := &redshift.DescribeEndpointAccessInput{ + EndpointName: aws.String(name), + } + + output, err := conn.DescribeEndpointAccess(input) + + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeEndpointNotFoundFault) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || len(output.EndpointAccessList) == 0 || output.EndpointAccessList[0] == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if count := len(output.EndpointAccessList); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, input) + } + + return output.EndpointAccessList[0], nil +} diff --git a/internal/service/redshift/flex.go b/internal/service/redshift/flex.go index 952b0f53eac..4fb913452ac 100644 --- a/internal/service/redshift/flex.go +++ b/internal/service/redshift/flex.go @@ -3,6 +3,7 @@ package redshift import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/flex" ) func ExpandParameters(configured []interface{}) []*redshift.Parameter { @@ -38,6 +39,12 @@ func flattenLogging(ls *redshift.LoggingStatus) []interface{} { if ls.BucketName != nil { cfg["bucket_name"] = aws.StringValue(ls.BucketName) } + if ls.LogDestinationType != nil { + cfg["log_destination_type"] = aws.StringValue(ls.LogDestinationType) + } + if ls.LogExports != nil { + cfg["log_exports"] = flex.FlattenStringSet(ls.LogExports) + } if ls.S3KeyPrefix != nil { cfg["s3_key_prefix"] = aws.StringValue(ls.S3KeyPrefix) } diff --git a/internal/service/redshift/hsm_client_certificate.go b/internal/service/redshift/hsm_client_certificate.go new file mode 100644 index 00000000000..83ac9939e27 --- /dev/null +++ b/internal/service/redshift/hsm_client_certificate.go @@ -0,0 +1,149 @@ +package redshift + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" + "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceHSMClientCertificate() *schema.Resource { + return &schema.Resource{ + Create: resourceHSMClientCertificateCreate, + Read: resourceHSMClientCertificateRead, + Update: resourceHSMClientCertificateUpdate, + Delete: resourceHSMClientCertificateDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "hsm_client_certificate_identifier": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "hsm_client_certificate_public_key": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourceHSMClientCertificateCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + certIdentifier := d.Get("hsm_client_certificate_identifier").(string) + + input := redshift.CreateHsmClientCertificateInput{ + HsmClientCertificateIdentifier: aws.String(certIdentifier), + } + + input.Tags = Tags(tags.IgnoreAWS()) + + out, err := conn.CreateHsmClientCertificate(&input) + if err != nil { + return fmt.Errorf("error creating Redshift Hsm Client Certificate (%s): %s", certIdentifier, err) + } + + d.SetId(aws.StringValue(out.HsmClientCertificate.HsmClientCertificateIdentifier)) + + return resourceHSMClientCertificateRead(d, meta) +} + +func resourceHSMClientCertificateRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + out, err := FindHSMClientCertificateByID(conn, d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift Hsm Client Certificate (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error reading Redshift Hsm Client Certificate (%s): %w", d.Id(), err) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: "redshift", + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("hsmclientcertificate:%s", d.Id()), + }.String() + + d.Set("arn", arn) + + d.Set("hsm_client_certificate_identifier", out.HsmClientCertificateIdentifier) + d.Set("hsm_client_certificate_public_key", out.HsmClientCertificatePublicKey) + + tags := KeyValueTags(out.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %w", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return fmt.Errorf("error setting tags_all: %w", err) + } + + return nil +} + +func resourceHSMClientCertificateUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating Redshift Hsm Client Certificate (%s) tags: %s", d.Get("arn").(string), err) + } + } + + return resourceHSMClientCertificateRead(d, meta) +} + +func resourceHSMClientCertificateDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + deleteInput := redshift.DeleteHsmClientCertificateInput{ + HsmClientCertificateIdentifier: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Deleting Redshift Hsm Client Certificate: %s", d.Id()) + _, err := conn.DeleteHsmClientCertificate(&deleteInput) + + if err != nil { + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeHsmClientCertificateNotFoundFault) { + return nil + } + return err + } + + return err +} diff --git a/internal/service/redshift/hsm_client_certificate_test.go b/internal/service/redshift/hsm_client_certificate_test.go new file mode 100644 index 00000000000..f51e860b248 --- /dev/null +++ b/internal/service/redshift/hsm_client_certificate_test.go @@ -0,0 +1,190 @@ +package redshift_test + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/redshift" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccRedshiftHSMClientCertificate_basic(t *testing.T) { + resourceName := "aws_redshift_hsm_client_certificate.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckHSMClientCertificateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccHSMClientCertificateConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMClientCertificateExists(resourceName), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "redshift", regexp.MustCompile(`hsmclientcertificate:.+`)), + resource.TestCheckResourceAttr(resourceName, "hsm_client_certificate_identifier", rName), + resource.TestCheckResourceAttrSet(resourceName, "hsm_client_certificate_public_key"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccRedshiftHSMClientCertificate_tags(t *testing.T) { + resourceName := "aws_redshift_hsm_client_certificate.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckHSMClientCertificateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccHSMClientCertificateConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMClientCertificateExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccHSMClientCertificateConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMClientCertificateExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, { + Config: testAccHSMClientCertificateConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMClientCertificateExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func TestAccRedshiftHSMClientCertificate_disappears(t *testing.T) { + resourceName := "aws_redshift_hsm_client_certificate.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckHSMClientCertificateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccHSMClientCertificateConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMClientCertificateExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceHSMClientCertificate(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckHSMClientCertificateDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_redshift_hsm_client_certificate" { + continue + } + + _, err := tfredshift.FindHSMClientCertificateByID(conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("Redshift Hsm Client Certificate %s still exists", rs.Primary.ID) + } + + return nil +} + +func testAccCheckHSMClientCertificateExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("Snapshot Copy Grant ID (HsmClientCertificateName) is not set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + _, err := tfredshift.FindHSMClientCertificateByID(conn, rs.Primary.ID) + + if err != nil { + return err + } + + return nil + } +} + +func testAccHSMClientCertificateConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_redshift_hsm_client_certificate" "test" { + hsm_client_certificate_identifier = %[1]q +} +`, rName) +} + +func testAccHSMClientCertificateConfig_tags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_redshift_hsm_client_certificate" "test" { + hsm_client_certificate_identifier = %[1]q + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccHSMClientCertificateConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_redshift_hsm_client_certificate" "test" { + hsm_client_certificate_identifier = %[1]q + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/internal/service/redshift/hsm_configuration.go b/internal/service/redshift/hsm_configuration.go new file mode 100644 index 00000000000..b9f680162ce --- /dev/null +++ b/internal/service/redshift/hsm_configuration.go @@ -0,0 +1,178 @@ +package redshift + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" + "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceHSMConfiguration() *schema.Resource { + return &schema.Resource{ + Create: resourceHSMConfigurationCreate, + Read: resourceHSMConfigurationRead, + Update: resourceHSMConfigurationUpdate, + Delete: resourceHSMConfigurationDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "hsm_configuration_identifier": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "hsm_ip_address": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "hsm_partition_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "hsm_partition_password": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Sensitive: true, + }, + "hsm_server_public_certificate": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourceHSMConfigurationCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + hsmConfigurationID := d.Get("hsm_configuration_identifier").(string) + input := &redshift.CreateHsmConfigurationInput{ + Description: aws.String(d.Get("description").(string)), + HsmConfigurationIdentifier: aws.String(hsmConfigurationID), + HsmIpAddress: aws.String(d.Get("hsm_ip_address").(string)), + HsmPartitionName: aws.String(d.Get("hsm_partition_name").(string)), + HsmPartitionPassword: aws.String(d.Get("hsm_partition_password").(string)), + HsmServerPublicCertificate: aws.String(d.Get("hsm_server_public_certificate").(string)), + } + + input.Tags = Tags(tags.IgnoreAWS()) + + output, err := conn.CreateHsmConfiguration(input) + + if err != nil { + return fmt.Errorf("creating Redshift HSM Configuration (%s): %s", hsmConfigurationID, err) + } + + d.SetId(aws.StringValue(output.HsmConfiguration.HsmConfigurationIdentifier)) + + return resourceHSMConfigurationRead(d, meta) +} + +func resourceHSMConfigurationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + hsmConfiguration, err := FindHSMConfigurationByID(conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift HSM Configuration (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("reading Redshift HSM Configuration (%s): %w", d.Id(), err) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: redshift.ServiceName, + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("hsmconfiguration:%s", d.Id()), + }.String() + d.Set("arn", arn) + d.Set("hsm_configuration_identifier", hsmConfiguration.HsmConfigurationIdentifier) + d.Set("hsm_ip_address", hsmConfiguration.HsmIpAddress) + d.Set("hsm_partition_name", hsmConfiguration.HsmPartitionName) + d.Set("description", hsmConfiguration.Description) + d.Set("hsm_partition_password", d.Get("hsm_partition_password").(string)) + d.Set("hsm_server_public_certificate", d.Get("hsm_server_public_certificate").(string)) + + tags := KeyValueTags(hsmConfiguration.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return fmt.Errorf("setting tags: %w", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return fmt.Errorf("setting tags_all: %w", err) + } + + return nil +} + +func resourceHSMConfigurationUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("updating Redshift HSM Configuration (%s) tags: %w", d.Get("arn").(string), err) + } + } + + return resourceHSMConfigurationRead(d, meta) +} + +func resourceHSMConfigurationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + log.Printf("[DEBUG] Deleting Redshift HSM Configuration: %s", d.Id()) + _, err := conn.DeleteHsmConfiguration(&redshift.DeleteHsmConfigurationInput{ + HsmConfigurationIdentifier: aws.String(d.Id()), + }) + + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeHsmConfigurationNotFoundFault) { + return nil + } + + if err != nil { + return fmt.Errorf("deleting Redshift HSM Configuration (%s): %w", d.Id(), err) + } + + return nil +} diff --git a/internal/service/redshift/hsm_configuration_test.go b/internal/service/redshift/hsm_configuration_test.go new file mode 100644 index 00000000000..67e758d8d0c --- /dev/null +++ b/internal/service/redshift/hsm_configuration_test.go @@ -0,0 +1,206 @@ +package redshift_test + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/service/redshift" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccRedshiftHSMConfiguration_basic(t *testing.T) { + resourceName := "aws_redshift_hsm_configuration.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckHSMConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccHSMConfigurationConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMConfigurationExists(resourceName), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "redshift", regexp.MustCompile(`hsmconfiguration:.+`)), + resource.TestCheckResourceAttr(resourceName, "hsm_configuration_identifier", rName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"hsm_partition_password", "hsm_server_public_certificate"}, + }, + }, + }) +} + +func TestAccRedshiftHSMConfiguration_tags(t *testing.T) { + resourceName := "aws_redshift_hsm_configuration.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckHSMConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccHSMConfigurationConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMConfigurationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"hsm_partition_password", "hsm_server_public_certificate"}, + }, + { + Config: testAccHSMConfigurationConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMConfigurationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, { + Config: testAccHSMConfigurationConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMConfigurationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func TestAccRedshiftHSMConfiguration_disappears(t *testing.T) { + resourceName := "aws_redshift_hsm_configuration.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckHSMConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccHSMConfigurationConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHSMConfigurationExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceHSMConfiguration(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckHSMConfigurationDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_redshift_hsm_configuration" { + continue + } + + _, err := tfredshift.FindHSMConfigurationByID(conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("Redshift Hsm Configuration %s still exists", rs.Primary.ID) + } + + return nil +} + +func testAccCheckHSMConfigurationExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("Redshift Hsm Configuration is not set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + _, err := tfredshift.FindHSMConfigurationByID(conn, rs.Primary.ID) + + if err != nil { + return err + } + + return nil + } +} + +func testAccHSMConfigurationConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_redshift_hsm_configuration" "test" { + description = %[1]q + hsm_configuration_identifier = %[1]q + hsm_ip_address = "10.0.0.1" + hsm_partition_name = "aws" + hsm_partition_password = %[1]q + hsm_server_public_certificate = %[1]q +} +`, rName) +} + +func testAccHSMConfigurationConfig_tags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_redshift_hsm_configuration" "test" { + description = %[1]q + hsm_configuration_identifier = %[1]q + hsm_ip_address = "10.0.0.1" + hsm_partition_name = "aws" + hsm_partition_password = %[1]q + hsm_server_public_certificate = %[1]q + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccHSMConfigurationConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_redshift_hsm_configuration" "test" { + description = %[1]q + hsm_configuration_identifier = %[1]q + hsm_ip_address = "10.0.0.1" + hsm_partition_name = "aws" + hsm_partition_password = %[1]q + hsm_server_public_certificate = %[1]q + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/internal/service/redshift/orderable_cluster_data_source_test.go b/internal/service/redshift/orderable_cluster_data_source_test.go index 3ad50c77608..ab820ca7f74 100644 --- a/internal/service/redshift/orderable_cluster_data_source_test.go +++ b/internal/service/redshift/orderable_cluster_data_source_test.go @@ -21,7 +21,7 @@ func TestAccRedshiftOrderableClusterDataSource_clusterType(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOrderableClusterDataSourceConfig_ClusterType("multi-node"), + Config: testAccOrderableClusterDataSourceConfig_type("multi-node"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "cluster_type", "multi-node"), ), @@ -40,7 +40,7 @@ func TestAccRedshiftOrderableClusterDataSource_clusterVersion(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOrderableClusterDataSourceConfig_ClusterVersion("1.0"), + Config: testAccOrderableClusterDataSourceConfig_version("1.0"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "cluster_version", "1.0"), ), @@ -60,7 +60,7 @@ func TestAccRedshiftOrderableClusterDataSource_nodeType(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOrderableClusterDataSourceConfig_NodeType(nodeType), + Config: testAccOrderableClusterDataSourceConfig_nodeType(nodeType), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "node_type", nodeType), ), @@ -80,7 +80,7 @@ func TestAccRedshiftOrderableClusterDataSource_preferredNodeTypes(t *testing.T) CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccOrderableClusterDataSourceConfig_PreferredNodeTypes(preferredNodeType), + Config: testAccOrderableClusterDataSourceConfig_preferredNodeTypes(preferredNodeType), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "node_type", preferredNodeType), ), @@ -107,7 +107,7 @@ func testAccOrderableClusterPreCheck(t *testing.T) { } } -func testAccOrderableClusterDataSourceConfig_ClusterType(clusterType string) string { +func testAccOrderableClusterDataSourceConfig_type(clusterType string) string { return fmt.Sprintf(` data "aws_redshift_orderable_cluster" "test" { cluster_type = %[1]q @@ -116,7 +116,7 @@ data "aws_redshift_orderable_cluster" "test" { `, clusterType) } -func testAccOrderableClusterDataSourceConfig_ClusterVersion(clusterVersion string) string { +func testAccOrderableClusterDataSourceConfig_version(clusterVersion string) string { return fmt.Sprintf(` data "aws_redshift_orderable_cluster" "test" { cluster_version = %[1]q @@ -125,7 +125,7 @@ data "aws_redshift_orderable_cluster" "test" { `, clusterVersion) } -func testAccOrderableClusterDataSourceConfig_NodeType(nodeType string) string { +func testAccOrderableClusterDataSourceConfig_nodeType(nodeType string) string { return fmt.Sprintf(` data "aws_redshift_orderable_cluster" "test" { node_type = %[1]q @@ -134,7 +134,7 @@ data "aws_redshift_orderable_cluster" "test" { `, nodeType) } -func testAccOrderableClusterDataSourceConfig_PreferredNodeTypes(preferredNodeType string) string { +func testAccOrderableClusterDataSourceConfig_preferredNodeTypes(preferredNodeType string) string { return fmt.Sprintf(` data "aws_redshift_orderable_cluster" "test" { preferred_node_types = [ diff --git a/internal/service/redshift/parameter_group_test.go b/internal/service/redshift/parameter_group_test.go index 7570fa8e037..89fca6e5e68 100644 --- a/internal/service/redshift/parameter_group_test.go +++ b/internal/service/redshift/parameter_group_test.go @@ -26,7 +26,7 @@ func TestAccRedshiftParameterGroup_basic(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig(rInt), + Config: testAccParameterGroupConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), ), @@ -52,7 +52,7 @@ func TestAccRedshiftParameterGroup_withParameters(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupConfig(rInt), + Config: testAccParameterGroupConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -96,7 +96,7 @@ func TestAccRedshiftParameterGroup_withoutParameters(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupOnlyConfig(rInt), + Config: testAccParameterGroupConfig_only(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -128,7 +128,7 @@ func TestAccRedshiftParameterGroup_withTags(t *testing.T) { CheckDestroy: testAccCheckParameterGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterGroupWithTagsConfig(rInt, "aaa"), + Config: testAccParameterGroupConfig_tags(rInt, "aaa"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -144,7 +144,7 @@ func TestAccRedshiftParameterGroup_withTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterGroupWithTagsConfig(rInt, "bbb"), + Config: testAccParameterGroupConfig_tags(rInt, "bbb"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -153,7 +153,7 @@ func TestAccRedshiftParameterGroup_withTags(t *testing.T) { ), }, { - Config: testAccParameterGroupWithTagsUpdateConfig(rInt), + Config: testAccParameterGroupConfig_tagsUpdate(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckParameterGroupExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -233,7 +233,7 @@ func testAccCheckParameterGroupExists(n string, v *redshift.ClusterParameterGrou } } -func testAccParameterGroupOnlyConfig(rInt int) string { +func testAccParameterGroupConfig_only(rInt int) string { return fmt.Sprintf(` resource "aws_redshift_parameter_group" "test" { name = "test-terraform-%d" @@ -243,7 +243,7 @@ resource "aws_redshift_parameter_group" "test" { `, rInt) } -func testAccParameterGroupConfig(rInt int) string { +func testAccParameterGroupConfig_basic(rInt int) string { return fmt.Sprintf(` resource "aws_redshift_parameter_group" "test" { name = "test-terraform-%d" @@ -267,7 +267,7 @@ resource "aws_redshift_parameter_group" "test" { `, rInt) } -func testAccParameterGroupWithTagsConfig(rInt int, rString string) string { +func testAccParameterGroupConfig_tags(rInt int, rString string) string { return fmt.Sprintf(` resource "aws_redshift_parameter_group" "test" { name = "test-terraform-%[1]d" @@ -283,7 +283,7 @@ resource "aws_redshift_parameter_group" "test" { `, rInt, rString) } -func testAccParameterGroupWithTagsUpdateConfig(rInt int) string { +func testAccParameterGroupConfig_tagsUpdate(rInt int) string { return fmt.Sprintf(` resource "aws_redshift_parameter_group" "test" { name = "test-terraform-%[1]d" diff --git a/internal/service/redshift/scheduled_action_test.go b/internal/service/redshift/scheduled_action_test.go index cdc73ec6a35..c6a852c55e4 100644 --- a/internal/service/redshift/scheduled_action_test.go +++ b/internal/service/redshift/scheduled_action_test.go @@ -27,7 +27,7 @@ func TestAccRedshiftScheduledAction_basicPauseCluster(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccScheduledActionPauseClusterConfig(rName, "cron(00 23 * * ? *)"), + Config: testAccScheduledActionConfig_pauseCluster(rName, "cron(00 23 * * ? *)"), Check: resource.ComposeTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -49,7 +49,7 @@ func TestAccRedshiftScheduledAction_basicPauseCluster(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccScheduledActionPauseClusterConfig(rName, "at(2060-03-04T17:27:00)"), + Config: testAccScheduledActionConfig_pauseCluster(rName, "at(2060-03-04T17:27:00)"), Check: resource.ComposeTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -83,7 +83,7 @@ func TestAccRedshiftScheduledAction_pauseClusterWithOptions(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccScheduledActionPauseClusterWithFullOptionsConfig(rName, "cron(00 * * * ? *)", "This is test action", true, startTime, endTime), + Config: testAccScheduledActionConfig_pauseClusterFullOptions(rName, "cron(00 * * * ? *)", "This is test action", true, startTime, endTime), Check: resource.ComposeTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", "This is test action"), @@ -120,7 +120,7 @@ func TestAccRedshiftScheduledAction_basicResumeCluster(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccScheduledActionResumeClusterConfig(rName, "cron(00 23 * * ? *)"), + Config: testAccScheduledActionConfig_resumeCluster(rName, "cron(00 23 * * ? *)"), Check: resource.ComposeTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -142,7 +142,7 @@ func TestAccRedshiftScheduledAction_basicResumeCluster(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccScheduledActionResumeClusterConfig(rName, "at(2060-03-04T17:27:00)"), + Config: testAccScheduledActionConfig_resumeCluster(rName, "at(2060-03-04T17:27:00)"), Check: resource.ComposeTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -174,7 +174,7 @@ func TestAccRedshiftScheduledAction_basicResizeCluster(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccScheduledActionResizeClusterBasicConfig(rName, "cron(00 23 * * ? *)"), + Config: testAccScheduledActionConfig_resizeClusterBasic(rName, "cron(00 23 * * ? *)"), Check: resource.ComposeTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -196,7 +196,7 @@ func TestAccRedshiftScheduledAction_basicResizeCluster(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccScheduledActionResizeClusterBasicConfig(rName, "at(2060-03-04T17:27:00)"), + Config: testAccScheduledActionConfig_resizeClusterBasic(rName, "at(2060-03-04T17:27:00)"), Check: resource.ComposeTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -228,7 +228,7 @@ func TestAccRedshiftScheduledAction_resizeClusterWithOptions(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccScheduledActionResizeClusterWithFullOptionsConfig(rName, "cron(00 23 * * ? *)", true, "multi-node", "dc2.large", 2), + Config: testAccScheduledActionConfig_resizeClusterFullOptions(rName, "cron(00 23 * * ? *)", true, "multi-node", "dc2.large", 2), Check: resource.ComposeTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -269,7 +269,7 @@ func TestAccRedshiftScheduledAction_disappears(t *testing.T) { CheckDestroy: testAccCheckScheduledActionDestroy, Steps: []resource.TestStep{ { - Config: testAccScheduledActionPauseClusterConfig(rName, "cron(00 23 * * ? *)"), + Config: testAccScheduledActionConfig_pauseCluster(rName, "cron(00 23 * * ? *)"), Check: resource.ComposeTestCheckFunc( testAccCheckScheduledActionExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceScheduledAction(), resourceName), @@ -383,7 +383,7 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName, rName) } -func testAccScheduledActionPauseClusterConfig(rName, schedule string) string { +func testAccScheduledActionConfig_pauseCluster(rName, schedule string) string { return acctest.ConfigCompose(testAccScheduledActionBaseConfig(rName), fmt.Sprintf(` resource "aws_redshift_scheduled_action" "test" { name = %[1]q @@ -399,7 +399,7 @@ resource "aws_redshift_scheduled_action" "test" { `, rName, schedule)) } -func testAccScheduledActionPauseClusterWithFullOptionsConfig(rName, schedule, description string, enable bool, startTime, endTime string) string { +func testAccScheduledActionConfig_pauseClusterFullOptions(rName, schedule, description string, enable bool, startTime, endTime string) string { return acctest.ConfigCompose(testAccScheduledActionBaseConfig(rName), fmt.Sprintf(` resource "aws_redshift_scheduled_action" "test" { name = %[1]q @@ -419,7 +419,7 @@ resource "aws_redshift_scheduled_action" "test" { `, rName, description, enable, startTime, endTime, schedule)) } -func testAccScheduledActionResumeClusterConfig(rName, schedule string) string { +func testAccScheduledActionConfig_resumeCluster(rName, schedule string) string { return acctest.ConfigCompose(testAccScheduledActionBaseConfig(rName), fmt.Sprintf(` resource "aws_redshift_scheduled_action" "test" { name = %[1]q @@ -435,7 +435,7 @@ resource "aws_redshift_scheduled_action" "test" { `, rName, schedule)) } -func testAccScheduledActionResizeClusterBasicConfig(rName, schedule string) string { +func testAccScheduledActionConfig_resizeClusterBasic(rName, schedule string) string { return acctest.ConfigCompose(testAccScheduledActionBaseConfig(rName), fmt.Sprintf(` resource "aws_redshift_scheduled_action" "test" { name = %[1]q @@ -451,7 +451,7 @@ resource "aws_redshift_scheduled_action" "test" { `, rName, schedule)) } -func testAccScheduledActionResizeClusterWithFullOptionsConfig(rName, schedule string, classic bool, clusterType, nodeType string, numberOfNodes int) string { +func testAccScheduledActionConfig_resizeClusterFullOptions(rName, schedule string, classic bool, clusterType, nodeType string, numberOfNodes int) string { return acctest.ConfigCompose(testAccScheduledActionBaseConfig(rName), fmt.Sprintf(` resource "aws_redshift_scheduled_action" "test" { name = %[1]q diff --git a/internal/service/redshift/service_account_data_source_test.go b/internal/service/redshift/service_account_data_source_test.go index b789f814262..44afcb459e2 100644 --- a/internal/service/redshift/service_account_data_source_test.go +++ b/internal/service/redshift/service_account_data_source_test.go @@ -20,7 +20,7 @@ func TestAccRedshiftServiceAccountDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccServiceAccountConfig_basic, + Config: testAccServiceAccountDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", expectedAccountID), acctest.CheckResourceAttrGlobalARNAccountID(dataSourceName, "arn", expectedAccountID, "iam", "user/logs"), @@ -41,7 +41,7 @@ func TestAccRedshiftServiceAccountDataSource_region(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccServiceAccountConfig_explicitRegion, + Config: testAccServiceAccountDataSourceConfig_explicitRegion, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", expectedAccountID), acctest.CheckResourceAttrGlobalARNAccountID(dataSourceName, "arn", expectedAccountID, "iam", "user/logs"), @@ -51,11 +51,11 @@ func TestAccRedshiftServiceAccountDataSource_region(t *testing.T) { }) } -const testAccServiceAccountConfig_basic = ` +const testAccServiceAccountDataSourceConfig_basic = ` data "aws_redshift_service_account" "main" {} ` -const testAccServiceAccountConfig_explicitRegion = ` +const testAccServiceAccountDataSourceConfig_explicitRegion = ` data "aws_region" "current" {} data "aws_redshift_service_account" "regional" { diff --git a/internal/service/redshift/snapshot_copy_grant.go b/internal/service/redshift/snapshot_copy_grant.go index 496f7812af8..68f7a0c888c 100644 --- a/internal/service/redshift/snapshot_copy_grant.go +++ b/internal/service/redshift/snapshot_copy_grant.go @@ -112,11 +112,10 @@ func resourceSnapshotCopyGrantRead(d *schema.ResourceData, meta interface{}) err ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig grantName := d.Id() - log.Printf("[DEBUG] Looking for grant: %s", grantName) grant, err := findSnapshotCopyGrant(conn, grantName) - if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotCopyGrantNotFoundFault) || grant == nil { - log.Printf("[WARN] snapshot copy grant (%s) not found, removing from state", grantName) + if !d.IsNewResource() && (tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotCopyGrantNotFoundFault) || grant == nil) { + log.Printf("[WARN] Redshift Snapshot Copy Grant (%s) not found, removing from state", grantName) d.SetId("") return nil } diff --git a/internal/service/redshift/snapshot_copy_grant_test.go b/internal/service/redshift/snapshot_copy_grant_test.go index 938001dd7cd..35ca09afa33 100644 --- a/internal/service/redshift/snapshot_copy_grant_test.go +++ b/internal/service/redshift/snapshot_copy_grant_test.go @@ -25,7 +25,7 @@ func TestAccRedshiftSnapshotCopyGrant_basic(t *testing.T) { CheckDestroy: testAccCheckSnapshotCopyGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotCopyGrant_Basic(rName), + Config: testAccSnapshotCopyGrantConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotCopyGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "snapshot_copy_grant_name", rName), @@ -53,7 +53,7 @@ func TestAccRedshiftSnapshotCopyGrant_update(t *testing.T) { CheckDestroy: testAccCheckSnapshotCopyGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotCopyGrantWithTags(rName), + Config: testAccSnapshotCopyGrantConfig_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotCopyGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -62,14 +62,14 @@ func TestAccRedshiftSnapshotCopyGrant_update(t *testing.T) { ), }, { - Config: testAccSnapshotCopyGrant_Basic(rName), + Config: testAccSnapshotCopyGrantConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotCopyGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { - Config: testAccSnapshotCopyGrantWithTags(rName), + Config: testAccSnapshotCopyGrantConfig_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotCopyGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -97,7 +97,7 @@ func TestAccRedshiftSnapshotCopyGrant_disappears(t *testing.T) { CheckDestroy: testAccCheckSnapshotCopyGrantDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotCopyGrant_Basic(rName), + Config: testAccSnapshotCopyGrantConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotCopyGrantExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceSnapshotCopyGrant(), resourceName), @@ -159,7 +159,7 @@ func testAccCheckSnapshotCopyGrantExists(name string) resource.TestCheckFunc { } } -func testAccSnapshotCopyGrant_Basic(rName string) string { +func testAccSnapshotCopyGrantConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_redshift_snapshot_copy_grant" "test" { snapshot_copy_grant_name = %[1]q @@ -167,7 +167,7 @@ resource "aws_redshift_snapshot_copy_grant" "test" { `, rName) } -func testAccSnapshotCopyGrantWithTags(rName string) string { +func testAccSnapshotCopyGrantConfig_tags(rName string) string { return fmt.Sprintf(` resource "aws_redshift_snapshot_copy_grant" "test" { snapshot_copy_grant_name = %[1]q diff --git a/internal/service/redshift/snapshot_schedule.go b/internal/service/redshift/snapshot_schedule.go index 3a8104cd69f..a47b3fd0049 100644 --- a/internal/service/redshift/snapshot_schedule.go +++ b/internal/service/redshift/snapshot_schedule.go @@ -114,11 +114,11 @@ func resourceSnapshotScheduleRead(d *schema.ResourceData, meta interface{}) erro resp, err := conn.DescribeSnapshotSchedules(descOpts) if err != nil { - return fmt.Errorf("Error describing Redshift Cluster Snapshot Schedule %s: %s", d.Id(), err) + return fmt.Errorf("error describing Redshift Cluster Snapshot Schedule %s: %w", d.Id(), err) } - if resp.SnapshotSchedules == nil || len(resp.SnapshotSchedules) != 1 { - log.Printf("[WARN] Unable to find Redshift Cluster Snapshot Schedule (%s)", d.Id()) + if !d.IsNewResource() && (resp.SnapshotSchedules == nil || len(resp.SnapshotSchedules) != 1) { + log.Printf("[WARN] Redshift Cluster Snapshot Schedule (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -127,7 +127,7 @@ func resourceSnapshotScheduleRead(d *schema.ResourceData, meta interface{}) erro d.Set("identifier", snapshotSchedule.ScheduleIdentifier) d.Set("description", snapshotSchedule.ScheduleDescription) if err := d.Set("definitions", flex.FlattenStringList(snapshotSchedule.ScheduleDefinitions)); err != nil { - return fmt.Errorf("Error setting definitions: %s", err) + return fmt.Errorf("error setting definitions: %w", err) } tags := KeyValueTags(snapshotSchedule.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -161,7 +161,7 @@ func resourceSnapshotScheduleUpdate(d *schema.ResourceData, meta interface{}) er o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating Redshift Snapshot Schedule (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("error updating Redshift Snapshot Schedule (%s) tags: %w", d.Get("arn").(string), err) } } @@ -171,13 +171,8 @@ func resourceSnapshotScheduleUpdate(d *schema.ResourceData, meta interface{}) er ScheduleDefinitions: flex.ExpandStringSet(d.Get("definitions").(*schema.Set)), } _, err := conn.ModifySnapshotSchedule(modifyOpts) - if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotScheduleNotFoundFault) { - log.Printf("[WARN] Redshift Snapshot Schedule (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } if err != nil { - return fmt.Errorf("Error modifying Redshift Snapshot Schedule %s: %s", d.Id(), err) + return fmt.Errorf("error modifying Redshift Snapshot Schedule %s: %w", d.Id(), err) } } @@ -231,8 +226,10 @@ func resourceSnapshotScheduleDeleteAllAssociatedClusters(conn *redshift.Redshift DisassociateSchedule: aws.Bool(true), }) + clusterId := aws.StringValue(associatedCluster.ClusterIdentifier) + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeClusterNotFoundFault) { - log.Printf("[WARN] Redshift Snapshot Cluster (%s) not found, removing from state", aws.StringValue(associatedCluster.ClusterIdentifier)) + log.Printf("[WARN] Redshift Snapshot Cluster (%s) not found, removing from state", clusterId) continue } if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotScheduleNotFoundFault) { @@ -240,12 +237,13 @@ func resourceSnapshotScheduleDeleteAllAssociatedClusters(conn *redshift.Redshift continue } if err != nil { - return fmt.Errorf("Error disassociate Redshift Cluster (%s) and Snapshot Schedule (%s) Association: %s", aws.StringValue(associatedCluster.ClusterIdentifier), scheduleIdentifier, err) + return fmt.Errorf("Error disassociate Redshift Cluster (%s) and Snapshot Schedule (%s) Association: %s", clusterId, scheduleIdentifier, err) } } for _, associatedCluster := range snapshotSchedule.AssociatedClusters { - if err := waitForSnapshotScheduleAssociationDestroy(conn, snapshotScheduleAssociationDestroyedTimeout, aws.StringValue(associatedCluster.ClusterIdentifier), scheduleIdentifier); err != nil { + id := fmt.Sprintf("%s/%s", aws.StringValue(associatedCluster.ClusterIdentifier), scheduleIdentifier) + if _, err := waitScheduleAssociationDeleted(conn, id); err != nil { return err } } diff --git a/internal/service/redshift/snapshot_schedule_association.go b/internal/service/redshift/snapshot_schedule_association.go index 753872b5dab..fb24beab426 100644 --- a/internal/service/redshift/snapshot_schedule_association.go +++ b/internal/service/redshift/snapshot_schedule_association.go @@ -4,19 +4,13 @@ import ( "fmt" "log" "strings" - "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" -) - -const ( - snapshotScheduleAssociationActivatedTimeout = 75 * time.Minute - snapshotScheduleAssociationDestroyedTimeout = 75 * time.Minute + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func ResourceSnapshotScheduleAssociation() *schema.Resource { @@ -26,17 +20,7 @@ func ResourceSnapshotScheduleAssociation() *schema.Resource { Read: resourceSnapshotScheduleAssociationRead, Delete: resourceSnapshotScheduleAssociationDelete, Importer: &schema.ResourceImporter{ - State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - clusterIdentifier, scheduleIdentifier, err := SnapshotScheduleAssociationParseID(d.Id()) - if err != nil { - return nil, fmt.Errorf("Error parse Redshift Cluster Snapshot Schedule Association ID %s: %s", d.Id(), err) - } - - d.Set("cluster_identifier", clusterIdentifier) - d.Set("schedule_identifier", scheduleIdentifier) - d.SetId(fmt.Sprintf("%s/%s", clusterIdentifier, scheduleIdentifier)) - return []*schema.ResourceData{d}, nil - }, + State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ @@ -69,54 +53,31 @@ func resourceSnapshotScheduleAssociationCreate(d *schema.ResourceData, meta inte return fmt.Errorf("Error associating Redshift Cluster (%s) and Snapshot Schedule (%s): %s", clusterIdentifier, scheduleIdentifier, err) } - if err := WaitForSnapshotScheduleAssociationActive(conn, snapshotScheduleAssociationActivatedTimeout, clusterIdentifier, scheduleIdentifier); err != nil { + d.SetId(fmt.Sprintf("%s/%s", clusterIdentifier, scheduleIdentifier)) + + if _, err := WaitScheduleAssociationActive(conn, d.Id()); err != nil { return err } - d.SetId(fmt.Sprintf("%s/%s", clusterIdentifier, scheduleIdentifier)) - return resourceSnapshotScheduleAssociationRead(d, meta) } func resourceSnapshotScheduleAssociationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).RedshiftConn - clusterIdentifier, scheduleIdentifier, err := SnapshotScheduleAssociationParseID(d.Id()) - if err != nil { - return fmt.Errorf("Error parse Redshift Cluster Snapshot Schedule Association ID %s: %s", d.Id(), err) - } - - descOpts := &redshift.DescribeSnapshotSchedulesInput{ - ClusterIdentifier: aws.String(clusterIdentifier), - ScheduleIdentifier: aws.String(scheduleIdentifier), - } - - resp, err := conn.DescribeSnapshotSchedules(descOpts) - if err != nil { - return fmt.Errorf("Error describing Redshift Cluster %s Snapshot Schedule %s: %s", clusterIdentifier, clusterIdentifier, err) - } - if resp.SnapshotSchedules == nil || len(resp.SnapshotSchedules) == 0 { - return fmt.Errorf("Unable to find Redshift Cluster (%s) Snapshot Schedule (%s) Association", clusterIdentifier, scheduleIdentifier) - } - snapshotSchedule := resp.SnapshotSchedules[0] - if snapshotSchedule.AssociatedClusters == nil || aws.Int64Value(snapshotSchedule.AssociatedClusterCount) == 0 { - return fmt.Errorf("Unable to find Redshift Cluster (%s)", clusterIdentifier) - } + scheduleIdentifier, assoicatedCluster, err := FindScheduleAssociationById(conn, d.Id()) - var associatedCluster *redshift.ClusterAssociatedToSchedule - for _, cluster := range snapshotSchedule.AssociatedClusters { - if aws.StringValue(cluster.ClusterIdentifier) == clusterIdentifier { - associatedCluster = cluster - break - } + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift Schedule Association (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } - if associatedCluster == nil { - return fmt.Errorf("Unable to find Redshift Cluster (%s)", clusterIdentifier) + if err != nil { + return fmt.Errorf("error reading Redshift Schedule Association (%s): %w", d.Id(), err) } - - d.Set("cluster_identifier", associatedCluster.ClusterIdentifier) - d.Set("schedule_identifier", snapshotSchedule.ScheduleIdentifier) + d.Set("cluster_identifier", assoicatedCluster.ClusterIdentifier) + d.Set("schedule_identifier", scheduleIdentifier) return nil } @@ -143,7 +104,7 @@ func resourceSnapshotScheduleAssociationDelete(d *schema.ResourceData, meta inte return fmt.Errorf("Error disassociate Redshift Cluster (%s) and Snapshot Schedule (%s) Association: %s", clusterIdentifier, scheduleIdentifier, err) } - if err := waitForSnapshotScheduleAssociationDestroy(conn, snapshotScheduleAssociationDestroyedTimeout, clusterIdentifier, scheduleIdentifier); err != nil { + if _, err := waitScheduleAssociationDeleted(conn, d.Id()); err != nil { return err } @@ -161,79 +122,3 @@ func SnapshotScheduleAssociationParseID(id string) (clusterIdentifier, scheduleI scheduleIdentifier = parts[1] return } - -func resourceSnapshotScheduleAssociationStateRefreshFunc(clusterIdentifier, scheduleIdentifier string, conn *redshift.Redshift) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - log.Printf("[INFO] Reading Redshift Cluster (%s) Snapshot Schedule (%s) Association Information", clusterIdentifier, scheduleIdentifier) - resp, err := conn.DescribeSnapshotSchedules(&redshift.DescribeSnapshotSchedulesInput{ - ClusterIdentifier: aws.String(clusterIdentifier), - ScheduleIdentifier: aws.String(scheduleIdentifier), - }) - if tfawserr.ErrCodeEquals(err, redshift.ErrCodeClusterNotFoundFault) { - return 42, "destroyed", nil - } - if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotScheduleNotFoundFault) { - return 42, "destroyed", nil - } - if err != nil { - log.Printf("[WARN] Error on retrieving Redshift Cluster (%s) Snapshot Schedule (%s) Association when waiting: %s", clusterIdentifier, scheduleIdentifier, err) - return nil, "", err - } - - var rcas *redshift.ClusterAssociatedToSchedule - - for _, s := range resp.SnapshotSchedules { - if aws.StringValue(s.ScheduleIdentifier) == scheduleIdentifier { - for _, c := range s.AssociatedClusters { - if aws.StringValue(c.ClusterIdentifier) == clusterIdentifier { - rcas = c - } - } - } - } - - if rcas == nil { - return 42, "destroyed", nil - } - - if rcas.ScheduleAssociationState != nil { - log.Printf("[DEBUG] Redshift Cluster (%s) Snapshot Schedule (%s) Association status: %s", clusterIdentifier, scheduleIdentifier, aws.StringValue(rcas.ScheduleAssociationState)) - } - - return rcas, aws.StringValue(rcas.ScheduleAssociationState), nil - } -} - -func WaitForSnapshotScheduleAssociationActive(conn *redshift.Redshift, timeout time.Duration, clusterIdentifier, scheduleIdentifier string) error { - stateConf := &resource.StateChangeConf{ - Pending: []string{redshift.ScheduleStateModifying}, - Target: []string{redshift.ScheduleStateActive}, - Refresh: resourceSnapshotScheduleAssociationStateRefreshFunc(clusterIdentifier, scheduleIdentifier, conn), - Timeout: timeout, - MinTimeout: 10 * time.Second, - Delay: 30 * time.Second, - } - - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Redshift Cluster (%s) and Snapshot Schedule (%s) Association state to be \"ACTIVE\": %s", clusterIdentifier, scheduleIdentifier, err) - } - - return nil -} - -func waitForSnapshotScheduleAssociationDestroy(conn *redshift.Redshift, timeout time.Duration, clusterIdentifier, scheduleIdentifier string) error { - - stateConf := &resource.StateChangeConf{ - Pending: []string{redshift.ScheduleStateModifying, redshift.ScheduleStateActive}, - Target: []string{"destroyed"}, - Refresh: resourceSnapshotScheduleAssociationStateRefreshFunc(clusterIdentifier, scheduleIdentifier, conn), - Timeout: timeout, - MinTimeout: 10 * time.Second, - } - - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Redshift Cluster (%s) and Snapshot Schedule (%s) Association state to be \"destroyed\": %s", clusterIdentifier, scheduleIdentifier, err) - } - - return nil -} diff --git a/internal/service/redshift/snapshot_schedule_association_test.go b/internal/service/redshift/snapshot_schedule_association_test.go index c6a295a60e9..73592692d5e 100644 --- a/internal/service/redshift/snapshot_schedule_association_test.go +++ b/internal/service/redshift/snapshot_schedule_association_test.go @@ -4,7 +4,6 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -12,11 +11,12 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func TestAccRedshiftSnapshotScheduleAssociation_basic(t *testing.T) { - rName := sdkacctest.RandString(8) - resourceName := "aws_redshift_snapshot_schedule_association.default" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_redshift_snapshot_schedule_association.test" snapshotScheduleResourceName := "aws_redshift_snapshot_schedule.default" clusterResourceName := "aws_redshift_cluster.test" @@ -27,7 +27,7 @@ func TestAccRedshiftSnapshotScheduleAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckSnapshotScheduleAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotScheduleAssociationConfig(rName, "rate(12 hours)"), + Config: testAccSnapshotScheduleAssociationConfig_basic(rName, "rate(12 hours)"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleAssociationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "schedule_identifier", snapshotScheduleResourceName, "id"), @@ -43,6 +43,51 @@ func TestAccRedshiftSnapshotScheduleAssociation_basic(t *testing.T) { }) } +func TestAccRedshiftSnapshotScheduleAssociation_disappears(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_redshift_snapshot_schedule_association.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSnapshotScheduleAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSnapshotScheduleAssociationConfig_basic(rName, "rate(12 hours)"), + Check: resource.ComposeTestCheckFunc( + testAccCheckSnapshotScheduleAssociationExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceSnapshotScheduleAssociation(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccRedshiftSnapshotScheduleAssociation_disappears_cluster(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_redshift_snapshot_schedule_association.test" + clusterResourceName := "aws_redshift_cluster.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSnapshotScheduleAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSnapshotScheduleAssociationConfig_basic(rName, "rate(12 hours)"), + Check: resource.ComposeTestCheckFunc( + testAccCheckSnapshotScheduleAssociationExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceCluster(), clusterResourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckSnapshotScheduleAssociationDestroy(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "aws_redshift_snapshot_schedule_association" { @@ -50,25 +95,18 @@ func testAccCheckSnapshotScheduleAssociationDestroy(s *terraform.State) error { } conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn - clusterIdentifier, scheduleIdentifier, err := tfredshift.SnapshotScheduleAssociationParseID(rs.Primary.ID) - if err != nil { - return err - } - resp, err := conn.DescribeSnapshotSchedules(&redshift.DescribeSnapshotSchedulesInput{ - ScheduleIdentifier: aws.String(scheduleIdentifier), - ClusterIdentifier: aws.String(clusterIdentifier), - }) + _, _, err := tfredshift.FindScheduleAssociationById(conn, rs.Primary.ID) - if err != nil { - return err + if tfresource.NotFound(err) { + continue } - if resp != nil && len(resp.SnapshotSchedules) > 0 { - return fmt.Errorf("Redshift Cluster (%s) Snapshot Schedule (%s) Association still exist", clusterIdentifier, scheduleIdentifier) + if err != nil { + return err } - return err + return fmt.Errorf("Redshift Schedule Association %s still exists", rs.Primary.ID) } return nil @@ -85,32 +123,21 @@ func testAccCheckSnapshotScheduleAssociationExists(n string) resource.TestCheckF return fmt.Errorf("No Redshift Cluster Snapshot Schedule Association ID is set") } - clusterIdentifier, scheduleIdentifier, err := tfredshift.SnapshotScheduleAssociationParseID(rs.Primary.ID) - if err != nil { - return err - } - conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn - resp, err := conn.DescribeSnapshotSchedules(&redshift.DescribeSnapshotSchedulesInput{ - ScheduleIdentifier: aws.String(scheduleIdentifier), - ClusterIdentifier: aws.String(clusterIdentifier), - }) + + _, _, err := tfredshift.FindScheduleAssociationById(conn, rs.Primary.ID) if err != nil { return err } - if len(resp.SnapshotSchedules) != 0 { - return nil - } - - return fmt.Errorf("Redshift Cluster (%s) Snapshot Schedule (%s) Association not found", clusterIdentifier, scheduleIdentifier) + return nil } } -func testAccSnapshotScheduleAssociationConfig(rName, definition string) string { - return acctest.ConfigCompose(testAccClusterConfig_basic(rName), testAccSnapshotScheduleConfig(rName, definition), ` -resource "aws_redshift_snapshot_schedule_association" "default" { +func testAccSnapshotScheduleAssociationConfig_basic(rName, definition string) string { + return acctest.ConfigCompose(testAccClusterConfig_basic(rName), testAccSnapshotScheduleConfig_basic(rName, definition), ` +resource "aws_redshift_snapshot_schedule_association" "test" { schedule_identifier = aws_redshift_snapshot_schedule.default.id cluster_identifier = aws_redshift_cluster.test.id } diff --git a/internal/service/redshift/snapshot_schedule_test.go b/internal/service/redshift/snapshot_schedule_test.go index 157d7b12ab3..795d2c87142 100644 --- a/internal/service/redshift/snapshot_schedule_test.go +++ b/internal/service/redshift/snapshot_schedule_test.go @@ -3,7 +3,6 @@ package redshift_test import ( "fmt" "testing" - "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" @@ -27,14 +26,14 @@ func TestAccRedshiftSnapshotSchedule_basic(t *testing.T) { CheckDestroy: testAccCheckSnapshotScheduleDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotScheduleConfig(rName, "rate(12 hours)"), + Config: testAccSnapshotScheduleConfig_basic(rName, "rate(12 hours)"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "definitions.#", "1"), ), }, { - Config: testAccSnapshotScheduleConfig(rName, "cron(30 12 *)"), + Config: testAccSnapshotScheduleConfig_basic(rName, "cron(30 12 *)"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "definitions.#", "1"), @@ -64,14 +63,14 @@ func TestAccRedshiftSnapshotSchedule_withMultipleDefinition(t *testing.T) { CheckDestroy: testAccCheckSnapshotScheduleDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotScheduleWithMultipleDefinitionConfig(rName, "cron(30 12 *)", "cron(15 6 *)"), + Config: testAccSnapshotScheduleConfig_multipleDefinition(rName, "cron(30 12 *)", "cron(15 6 *)"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "definitions.#", "2"), ), }, { - Config: testAccSnapshotScheduleWithMultipleDefinitionConfig(rName, "cron(30 8 *)", "cron(15 10 *)"), + Config: testAccSnapshotScheduleConfig_multipleDefinition(rName, "cron(30 8 *)", "cron(15 10 *)"), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "definitions.#", "2"), @@ -101,7 +100,7 @@ func TestAccRedshiftSnapshotSchedule_withIdentifierPrefix(t *testing.T) { CheckDestroy: testAccCheckSnapshotScheduleDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotScheduleWithIdentifierPrefixConfig, + Config: testAccSnapshotScheduleConfig_identifierPrefix, Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleExists(resourceName, &v), ), @@ -131,7 +130,7 @@ func TestAccRedshiftSnapshotSchedule_withDescription(t *testing.T) { CheckDestroy: testAccCheckSnapshotScheduleDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotScheduleWithDescriptionConfig(rName), + Config: testAccSnapshotScheduleConfig_description(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleExists(resourceName, &v), resource.TestCheckResourceAttr( @@ -162,7 +161,7 @@ func TestAccRedshiftSnapshotSchedule_withTags(t *testing.T) { CheckDestroy: testAccCheckSnapshotScheduleDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotScheduleWithTagsConfig(rName), + Config: testAccSnapshotScheduleConfig_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -171,7 +170,7 @@ func TestAccRedshiftSnapshotSchedule_withTags(t *testing.T) { ), }, { - Config: testAccSnapshotScheduleWithTagsUpdateConfig(rName), + Config: testAccSnapshotScheduleConfig_tagsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -205,7 +204,7 @@ func TestAccRedshiftSnapshotSchedule_withForceDestroy(t *testing.T) { CheckDestroy: testAccCheckSnapshotScheduleDestroy, Steps: []resource.TestStep{ { - Config: testAccSnapshotScheduleWithForceDestroyConfig(rName), + Config: testAccSnapshotScheduleConfig_forceDestroy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSnapshotScheduleExists(resourceName, &snapshotSchedule), testAccCheckClusterExists(clusterResourceName, &cluster), @@ -294,7 +293,8 @@ func testAccCheckSnapshotScheduleCreateSnapshotScheduleAssociation(cluster *reds return fmt.Errorf("Error associate Redshift Cluster and Snapshot Schedule: %s", err) } - if err := tfredshift.WaitForSnapshotScheduleAssociationActive(conn, 75*time.Minute, aws.StringValue(cluster.ClusterIdentifier), aws.StringValue(snapshotSchedule.ScheduleIdentifier)); err != nil { + id := fmt.Sprintf("%s/%s", aws.StringValue(cluster.ClusterIdentifier), aws.StringValue(snapshotSchedule.ScheduleIdentifier)) + if _, err := tfredshift.WaitScheduleAssociationActive(conn, id); err != nil { return err } @@ -302,7 +302,7 @@ func testAccCheckSnapshotScheduleCreateSnapshotScheduleAssociation(cluster *reds } } -const testAccSnapshotScheduleWithIdentifierPrefixConfig = ` +const testAccSnapshotScheduleConfig_identifierPrefix = ` resource "aws_redshift_snapshot_schedule" "default" { identifier_prefix = "tf-acc-test" definitions = [ @@ -311,7 +311,7 @@ resource "aws_redshift_snapshot_schedule" "default" { } ` -func testAccSnapshotScheduleConfig(rName, definition string) string { +func testAccSnapshotScheduleConfig_basic(rName, definition string) string { return fmt.Sprintf(` resource "aws_redshift_snapshot_schedule" "default" { identifier = %[1]q @@ -322,7 +322,7 @@ resource "aws_redshift_snapshot_schedule" "default" { `, rName, definition) } -func testAccSnapshotScheduleWithMultipleDefinitionConfig(rName, definition1, definition2 string) string { +func testAccSnapshotScheduleConfig_multipleDefinition(rName, definition1, definition2 string) string { return fmt.Sprintf(` resource "aws_redshift_snapshot_schedule" "default" { identifier = %[1]q @@ -334,7 +334,7 @@ resource "aws_redshift_snapshot_schedule" "default" { `, rName, definition1, definition2) } -func testAccSnapshotScheduleWithDescriptionConfig(rName string) string { +func testAccSnapshotScheduleConfig_description(rName string) string { return fmt.Sprintf(` resource "aws_redshift_snapshot_schedule" "default" { identifier = %[1]q @@ -346,7 +346,7 @@ resource "aws_redshift_snapshot_schedule" "default" { `, rName) } -func testAccSnapshotScheduleWithTagsConfig(rName string) string { +func testAccSnapshotScheduleConfig_tags(rName string) string { return fmt.Sprintf(` resource "aws_redshift_snapshot_schedule" "default" { identifier = %[1]q @@ -362,7 +362,7 @@ resource "aws_redshift_snapshot_schedule" "default" { `, rName) } -func testAccSnapshotScheduleWithTagsUpdateConfig(rName string) string { +func testAccSnapshotScheduleConfig_tagsUpdate(rName string) string { return fmt.Sprintf(` resource "aws_redshift_snapshot_schedule" "default" { identifier = %[1]q @@ -378,7 +378,7 @@ resource "aws_redshift_snapshot_schedule" "default" { `, rName) } -func testAccSnapshotScheduleWithForceDestroyConfig(rName string) string { +func testAccSnapshotScheduleConfig_forceDestroy(rName string) string { return acctest.ConfigCompose(testAccClusterConfig_basic(rName), fmt.Sprintf(` resource "aws_redshift_snapshot_schedule" "default" { identifier = %[1]q diff --git a/internal/service/redshift/status.go b/internal/service/redshift/status.go index 0d58add3948..55ed97f38c1 100644 --- a/internal/service/redshift/status.go +++ b/internal/service/redshift/status.go @@ -38,3 +38,67 @@ func statusClusterAvailabilityZoneRelocation(conn *redshift.Redshift, id string) return output, aws.StringValue(output.AvailabilityZoneRelocationStatus), nil } } + +func statusCluster(conn *redshift.Redshift, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindClusterByID(conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.StringValue(output.ClusterStatus), nil + } +} + +func statusClusterAqua(conn *redshift.Redshift, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindClusterByID(conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.StringValue(output.AquaConfiguration.AquaStatus), nil + } +} + +func statusScheduleAssociation(conn *redshift.Redshift, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + _, output, err := FindScheduleAssociationById(conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.StringValue(output.ScheduleAssociationState), nil + } +} + +func statusEndpointAccess(conn *redshift.Redshift, name string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindEndpointAccessByName(conn, name) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.StringValue(output.EndpointStatus), nil + } +} diff --git a/internal/service/redshift/subnet_group.go b/internal/service/redshift/subnet_group.go index 332da536a47..1960e9941a0 100644 --- a/internal/service/redshift/subnet_group.go +++ b/internal/service/redshift/subnet_group.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -22,6 +23,7 @@ func ResourceSubnetGroup() *schema.Resource { Read: resourceSubnetGroupRead, Update: resourceSubnetGroupUpdate, Delete: resourceSubnetGroupDelete, + Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, @@ -31,7 +33,11 @@ func ResourceSubnetGroup() *schema.Resource { Type: schema.TypeString, Computed: true, }, - + "description": { + Type: schema.TypeString, + Optional: true, + Default: "Managed by Terraform", + }, "name": { Type: schema.TypeString, ForceNew: true, @@ -42,20 +48,11 @@ func ResourceSubnetGroup() *schema.Resource { validation.StringNotInSlice([]string{"default"}, false), ), }, - - "description": { - Type: schema.TypeString, - Optional: true, - Default: "Managed by Terraform", - }, - "subnet_ids": { Type: schema.TypeSet, Required: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, - "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), }, @@ -75,21 +72,23 @@ func resourceSubnetGroupCreate(d *schema.ResourceData, meta interface{}) error { subnetIds[i] = aws.String(subnetId.(string)) } - createOpts := redshift.CreateClusterSubnetGroupInput{ - ClusterSubnetGroupName: aws.String(d.Get("name").(string)), + name := d.Get("name").(string) + input := redshift.CreateClusterSubnetGroupInput{ + ClusterSubnetGroupName: aws.String(name), Description: aws.String(d.Get("description").(string)), SubnetIds: subnetIds, Tags: Tags(tags.IgnoreAWS()), } - log.Printf("[DEBUG] Create Redshift Subnet Group: %#v", createOpts) - _, err := conn.CreateClusterSubnetGroup(&createOpts) + log.Printf("[DEBUG] Creating Redshift Subnet Group: %s", input) + _, err := conn.CreateClusterSubnetGroup(&input) + if err != nil { - return fmt.Errorf("Error creating Redshift Subnet Group: %s", err) + return fmt.Errorf("creating Redshift Subnet Group (%s): %w", name, err) } - d.SetId(aws.StringValue(createOpts.ClusterSubnetGroupName)) - log.Printf("[INFO] Redshift Subnet Group ID: %s", d.Id()) + d.SetId(aws.StringValue(input.ClusterSubnetGroupName)) + return resourceSubnetGroupRead(d, meta) } @@ -98,48 +97,40 @@ func resourceSubnetGroupRead(d *schema.ResourceData, meta interface{}) error { defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - describeOpts := redshift.DescribeClusterSubnetGroupsInput{ - ClusterSubnetGroupName: aws.String(d.Id()), - } + subnetgroup, err := FindSubnetGroupByName(conn, d.Id()) - describeResp, err := conn.DescribeClusterSubnetGroups(&describeOpts) - if err != nil { - if tfawserr.ErrCodeEquals(err, "ClusterSubnetGroupNotFoundFault") { - log.Printf("[INFO] Redshift Subnet Group: %s was not found", d.Id()) - d.SetId("") - return nil - } - return err + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift Subnet Group (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } - if len(describeResp.ClusterSubnetGroups) == 0 { - return fmt.Errorf("Unable to find Redshift Subnet Group: %#v", describeResp.ClusterSubnetGroups) + if err != nil { + return fmt.Errorf("reading Redshift Subnet Group (%s): %w", d.Id(), err) } + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: redshift.ServiceName, + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("subnetgroup:%s", d.Id()), + }.String() + d.Set("arn", arn) + d.Set("description", subnetgroup.Description) d.Set("name", d.Id()) - d.Set("description", describeResp.ClusterSubnetGroups[0].Description) - d.Set("subnet_ids", subnetIdsToSlice(describeResp.ClusterSubnetGroups[0].Subnets)) - tags := KeyValueTags(describeResp.ClusterSubnetGroups[0].Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + d.Set("subnet_ids", subnetIdsToSlice(subnetgroup.Subnets)) + tags := KeyValueTags(subnetgroup.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } - arn := arn.ARN{ - Partition: meta.(*conns.AWSClient).Partition, - Service: "redshift", - Region: meta.(*conns.AWSClient).Region, - AccountID: meta.(*conns.AWSClient).AccountID, - Resource: fmt.Sprintf("subnetgroup:%s", d.Id()), - }.String() - - d.Set("arn", arn) - return nil } @@ -150,7 +141,7 @@ func resourceSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating Redshift Subnet Group (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("updating Redshift Subnet Group (%s) tags: %s", d.Get("arn").(string), err) } } @@ -166,14 +157,17 @@ func resourceSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { sIds = append(sIds, aws.String(s.(string))) } - _, err := conn.ModifyClusterSubnetGroup(&redshift.ModifyClusterSubnetGroupInput{ + input := &redshift.ModifyClusterSubnetGroupInput{ ClusterSubnetGroupName: aws.String(d.Id()), Description: aws.String(d.Get("description").(string)), SubnetIds: sIds, - }) + } + + log.Printf("[DEBUG] Updating Redshift Subnet Group: %s", input) + _, err := conn.ModifyClusterSubnetGroup(input) if err != nil { - return err + return fmt.Errorf("modifying Redshift Subnet Group (%s): %w", d.Id(), err) } } @@ -183,14 +177,20 @@ func resourceSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { func resourceSubnetGroupDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).RedshiftConn + log.Printf("[DEBUG] Deleting Redshift Subnet Group: %s", d.Id()) _, err := conn.DeleteClusterSubnetGroup(&redshift.DeleteClusterSubnetGroupInput{ ClusterSubnetGroupName: aws.String(d.Id()), }) - if err != nil && tfawserr.ErrCodeEquals(err, "ClusterSubnetGroupNotFoundFault") { + + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeClusterSubnetGroupNotFoundFault) { return nil } - return err + if err != nil { + return fmt.Errorf("deleting Redshift Subnet Group (%s): %w", d.Id(), err) + } + + return nil } func subnetIdsToSlice(subnetIds []*redshift.Subnet) []string { diff --git a/internal/service/redshift/subnet_group_data_source.go b/internal/service/redshift/subnet_group_data_source.go new file mode 100644 index 00000000000..ca753fd582f --- /dev/null +++ b/internal/service/redshift/subnet_group_data_source.go @@ -0,0 +1,70 @@ +package redshift + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" + "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" +) + +func DataSourceSubnetGroup() *schema.Resource { + return &schema.Resource{ + Read: dataSourceSubnetGroupRead, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + }, + "subnet_ids": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "tags": tftags.TagsSchemaComputed(), + }, + } +} + +func dataSourceSubnetGroupRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + subnetgroup, err := FindSubnetGroupByName(conn, d.Get("name").(string)) + + if err != nil { + return fmt.Errorf("reading Redshift Subnet Group (%s): %w", d.Id(), err) + } + + d.SetId(aws.StringValue(subnetgroup.ClusterSubnetGroupName)) + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: redshift.ServiceName, + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("subnetgroup:%s", d.Id()), + }.String() + d.Set("arn", arn) + d.Set("description", subnetgroup.Description) + d.Set("name", subnetgroup.ClusterSubnetGroupName) + d.Set("subnet_ids", subnetIdsToSlice(subnetgroup.Subnets)) + + //lintignore:AWSR002 + if err := d.Set("tags", KeyValueTags(subnetgroup.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("setting tags: %w", err) + } + + return nil +} diff --git a/internal/service/redshift/subnet_group_data_source_test.go b/internal/service/redshift/subnet_group_data_source_test.go new file mode 100644 index 00000000000..d198c845d5a --- /dev/null +++ b/internal/service/redshift/subnet_group_data_source_test.go @@ -0,0 +1,42 @@ +package redshift_test + +import ( + "testing" + + "github.com/aws/aws-sdk-go/service/redshift" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" +) + +func TestAccRedshiftSubnetGroupDataSource_basic(t *testing.T) { + dataSourceName := "data.aws_redshift_subnet_group.test" + resourceName := "aws_redshift_subnet_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccSubnetGroupDataSourceConfig_basic(rName), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName, "description", resourceName, "description"), + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(dataSourceName, "subnet_ids.#", resourceName, "subnet_ids.#"), + resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"), + ), + }, + }, + }) +} + +func testAccSubnetGroupDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccSubnetGroupConfig_basic(rName), ` +data "aws_redshift_subnet_group" "test" { + name = aws_redshift_subnet_group.test.name +} +`) +} diff --git a/internal/service/redshift/subnet_group_test.go b/internal/service/redshift/subnet_group_test.go index 3d74a16262d..5d09242bcdb 100644 --- a/internal/service/redshift/subnet_group_test.go +++ b/internal/service/redshift/subnet_group_test.go @@ -4,8 +4,6 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/redshift" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -13,11 +11,12 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func TestAccRedshiftSubnetGroup_basic(t *testing.T) { var v redshift.ClusterSubnetGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_redshift_subnet_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -27,29 +26,25 @@ func TestAccRedshiftSubnetGroup_basic(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig_basic(rInt), + Config: testAccSubnetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &v), - resource.TestCheckResourceAttr( - resourceName, "subnet_ids.#", "2"), - resource.TestCheckResourceAttr( - resourceName, "description", "test description"), + resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), + resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "description"}, }, }, }) } func TestAccRedshiftSubnetGroup_disappears(t *testing.T) { - var clusterSubnetGroup redshift.ClusterSubnetGroup - rInt := sdkacctest.RandInt() + var v redshift.ClusterSubnetGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_redshift_subnet_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -59,9 +54,9 @@ func TestAccRedshiftSubnetGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig_basic(rInt), + Config: testAccSubnetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckSubnetGroupExists(resourceName, &clusterSubnetGroup), + testAccCheckSubnetGroupExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceSubnetGroup(), resourceName), ), ExpectNonEmptyPlan: true, @@ -72,7 +67,7 @@ func TestAccRedshiftSubnetGroup_disappears(t *testing.T) { func TestAccRedshiftSubnetGroup_updateDescription(t *testing.T) { var v redshift.ClusterSubnetGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_redshift_subnet_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -82,26 +77,22 @@ func TestAccRedshiftSubnetGroup_updateDescription(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig_basic(rInt), + Config: testAccSubnetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &v), - resource.TestCheckResourceAttr( - resourceName, "description", "test description"), + resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "description"}, }, { - Config: testAccSubnetGroupConfig_updateDescription(rInt), + Config: testAccSubnetGroupConfig_updateDescription(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &v), - resource.TestCheckResourceAttr( - resourceName, "description", "test description updated"), + resource.TestCheckResourceAttr(resourceName, "description", "test description updated"), ), }, }, @@ -110,7 +101,7 @@ func TestAccRedshiftSubnetGroup_updateDescription(t *testing.T) { func TestAccRedshiftSubnetGroup_updateSubnetIDs(t *testing.T) { var v redshift.ClusterSubnetGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_redshift_subnet_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -120,26 +111,22 @@ func TestAccRedshiftSubnetGroup_updateSubnetIDs(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig_basic(rInt), + Config: testAccSubnetGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &v), - resource.TestCheckResourceAttr( - resourceName, "subnet_ids.#", "2"), + resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "description"}, }, { - Config: testAccSubnetGroupConfig_updateSubnetIDs(rInt), + Config: testAccSubnetGroupConfig_updateIDs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &v), - resource.TestCheckResourceAttr( - resourceName, "subnet_ids.#", "3"), + resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "3"), ), }, }, @@ -148,7 +135,7 @@ func TestAccRedshiftSubnetGroup_updateSubnetIDs(t *testing.T) { func TestAccRedshiftSubnetGroup_tags(t *testing.T) { var v redshift.ClusterSubnetGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_redshift_subnet_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -158,30 +145,33 @@ func TestAccRedshiftSubnetGroup_tags(t *testing.T) { CheckDestroy: testAccCheckSubnetGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSubnetGroupConfig_tags(rInt), + Config: testAccSubnetGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &v), - resource.TestCheckResourceAttr( - resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", "tf-redshift-subnetgroup"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "description"}, }, { - Config: testAccSubnetGroupConfig_tagsUpdated(rInt), + Config: testAccSubnetGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckSubnetGroupExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccSubnetGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSubnetGroupExists(resourceName, &v), - resource.TestCheckResourceAttr( - resourceName, "tags.%", "3"), - resource.TestCheckResourceAttr(resourceName, "tags.environment", "production"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", "tf-redshift-subnetgroup"), - resource.TestCheckResourceAttr(resourceName, "tags.test", "test2"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, }, @@ -196,24 +186,17 @@ func testAccCheckSubnetGroupDestroy(s *terraform.State) error { continue } - resp, err := conn.DescribeClusterSubnetGroups( - &redshift.DescribeClusterSubnetGroupsInput{ - ClusterSubnetGroupName: aws.String(rs.Primary.ID)}) - if err == nil { - if len(resp.ClusterSubnetGroups) > 0 { - return fmt.Errorf("still exist.") - } + _, err := tfredshift.FindSubnetGroupByName(conn, rs.Primary.ID) - return nil + if tfresource.NotFound(err) { + continue } - redshiftErr, ok := err.(awserr.Error) - if !ok { - return err - } - if redshiftErr.Code() != "ClusterSubnetGroupNotFoundFault" { + if err != nil { return err } + + return fmt.Errorf("Redshift Subent Group %s still exists", rs.Primary.ID) } return nil @@ -227,228 +210,74 @@ func testAccCheckSubnetGroupExists(n string, v *redshift.ClusterSubnetGroup) res } if rs.Primary.ID == "" { - return fmt.Errorf("No ID is set") + return fmt.Errorf("No Redshift Subnet Group ID is set") } conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn - resp, err := conn.DescribeClusterSubnetGroups( - &redshift.DescribeClusterSubnetGroupsInput{ClusterSubnetGroupName: aws.String(rs.Primary.ID)}) + + output, err := tfredshift.FindSubnetGroupByName(conn, rs.Primary.ID) + if err != nil { return err } - if len(resp.ClusterSubnetGroups) == 0 { - return fmt.Errorf("ClusterSubnetGroup not found") - } - *v = *resp.ClusterSubnetGroups[0] + *v = *output return nil } } -func testAccSubnetGroupConfig_basic(rInt int) string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = "terraform-testacc-redshift-subnet-group" - } -} - -resource "aws_subnet" "test" { - cidr_block = "10.1.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] - vpc_id = aws_vpc.test.id - - tags = { - Name = "tf-acc-redshift-subnet-group-test" - } -} - -resource "aws_subnet" "test2" { - cidr_block = "10.1.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] - vpc_id = aws_vpc.test.id - - tags = { - Name = "tf-acc-redshift-subnet-group-test2" - } -} - +func testAccSubnetGroupConfig_basic(rName string) string { + return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_redshift_subnet_group" "test" { - name = "test-%d" - description = "test description" - subnet_ids = [aws_subnet.test.id, aws_subnet.test2.id] -} -`, rInt)) -} - -func testAccSubnetGroupConfig_updateDescription(rInt int) string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = "terraform-testacc-redshift-subnet-group-upd-description" - } -} - -resource "aws_subnet" "test" { - cidr_block = "10.1.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] - vpc_id = aws_vpc.test.id - - tags = { - Name = "tf-acc-redshift-subnet-group-upd-description-test" - } + name = %[1]q + subnet_ids = aws_subnet.test[*].id } - -resource "aws_subnet" "test2" { - cidr_block = "10.1.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] - vpc_id = aws_vpc.test.id - - tags = { - Name = "tf-acc-redshift-subnet-group-upd-description-test2" - } +`, rName)) } +func testAccSubnetGroupConfig_updateDescription(rName string) string { + return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_redshift_subnet_group" "test" { - name = "test-%d" + name = %[1]q description = "test description updated" - subnet_ids = [aws_subnet.test.id, aws_subnet.test2.id] -} -`, rInt)) -} - -func testAccSubnetGroupConfig_tags(rInt int) string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = "terraform-testacc-redshift-subnet-group-with-tags" - } -} - -resource "aws_subnet" "test" { - cidr_block = "10.1.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] - vpc_id = aws_vpc.test.id - - tags = { - Name = "tf-acc-redshift-subnet-group-with-tags-test" - } + subnet_ids = aws_subnet.test[*].id } - -resource "aws_subnet" "test2" { - cidr_block = "10.1.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] - vpc_id = aws_vpc.test.id - - tags = { - Name = "tf-acc-redshift-subnet-group-with-tags-test2" - } +`, rName)) } +func testAccSubnetGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { + return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_redshift_subnet_group" "test" { - name = "test-%d" - subnet_ids = [aws_subnet.test.id, aws_subnet.test2.id] - - tags = { - Name = "tf-redshift-subnetgroup" - } -} -`, rInt)) -} - -func testAccSubnetGroupConfig_tagsUpdated(rInt int) string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = "terraform-testacc-redshift-subnet-group-with-tags" - } -} - -resource "aws_subnet" "test" { - cidr_block = "10.1.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] - vpc_id = aws_vpc.test.id + name = %[1]q + subnet_ids = aws_subnet.test[*].id tags = { - Name = "tf-acc-redshift-subnet-group-with-tags-test" + %[2]q = %[3]q } } - -resource "aws_subnet" "test2" { - cidr_block = "10.1.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] - vpc_id = aws_vpc.test.id - - tags = { - Name = "tf-acc-redshift-subnet-group-with-tags-test2" - } +`, rName, tagKey1, tagValue1)) } +func testAccSubnetGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` resource "aws_redshift_subnet_group" "test" { - name = "test-%d" - subnet_ids = [aws_subnet.test.id, aws_subnet.test2.id] - - tags = { - Name = "tf-redshift-subnetgroup" - environment = "production" - test = "test2" - } -} -`, rInt)) -} - -func testAccSubnetGroupConfig_updateSubnetIDs(rInt int) string { - return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptIn(), fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = "terraform-testacc-redshift-subnet-group-upd-subnet-ids" - } -} - -resource "aws_subnet" "test" { - cidr_block = "10.1.1.0/24" - availability_zone = data.aws_availability_zones.available.names[0] - vpc_id = aws_vpc.test.id - - tags = { - Name = "tf-acc-redshift-subnet-group-upd-subnet-ids-test" - } -} - -resource "aws_subnet" "test2" { - cidr_block = "10.1.2.0/24" - availability_zone = data.aws_availability_zones.available.names[1] - vpc_id = aws_vpc.test.id + name = %[1]q + subnet_ids = aws_subnet.test[*].id tags = { - Name = "tf-acc-redshift-subnet-group-upd-subnet-ids-test2" + %[2]q = %[3]q + %[4]q = %[5]q } } - -resource "aws_subnet" "testtest2" { - cidr_block = "10.1.3.0/24" - availability_zone = data.aws_availability_zones.available.names[2] - vpc_id = aws_vpc.test.id - - tags = { - Name = "tf-acc-redshift-subnet-group-upd-subnet-ids-testtest2" - } +`, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } +func testAccSubnetGroupConfig_updateIDs(rName string) string { + return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 3), fmt.Sprintf(` resource "aws_redshift_subnet_group" "test" { - name = "test-%d" - subnet_ids = [aws_subnet.test.id, aws_subnet.test2.id, aws_subnet.testtest2.id] + name = %[1]q + subnet_ids = aws_subnet.test[*].id } -`, rInt)) +`, rName)) } diff --git a/internal/service/redshift/sweep.go b/internal/service/redshift/sweep.go index f3eaba19dc0..9c421cfe693 100644 --- a/internal/service/redshift/sweep.go +++ b/internal/service/redshift/sweep.go @@ -30,6 +30,21 @@ func init() { F: sweepClusters, }) + resource.AddTestSweepers("aws_redshift_hsm_client_certificate", &resource.Sweeper{ + Name: "aws_redshift_hsm_client_certificate", + F: sweepHSMClientCertificates, + }) + + resource.AddTestSweepers("aws_redshift_hsm_configuration", &resource.Sweeper{ + Name: "aws_redshift_hsm_configuration", + F: sweepHSMConfigurations, + }) + + resource.AddTestSweepers("aws_redshift_authentication_profile", &resource.Sweeper{ + Name: "aws_redshift_authentication_profile", + F: sweepAuthenticationProfiles, + }) + resource.AddTestSweepers("aws_redshift_event_subscription", &resource.Sweeper{ Name: "aws_redshift_event_subscription", F: sweepEventSubscriptions, @@ -335,3 +350,136 @@ func sweepSubnetGroups(region string) error { return errs.ErrorOrNil() } + +func sweepHSMClientCertificates(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + + conn := client.(*conns.AWSClient).RedshiftConn + sweepResources := make([]*sweep.SweepResource, 0) + var errs *multierror.Error + + err = conn.DescribeHsmClientCertificatesPages(&redshift.DescribeHsmClientCertificatesInput{}, func(resp *redshift.DescribeHsmClientCertificatesOutput, lastPage bool) bool { + if len(resp.HsmClientCertificates) == 0 { + log.Print("[DEBUG] No Redshift Hsm Client Certificates to sweep") + return !lastPage + } + + for _, c := range resp.HsmClientCertificates { + r := ResourceHSMClientCertificate() + d := r.Data(nil) + d.SetId(aws.StringValue(c.HsmClientCertificateIdentifier)) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + return !lastPage + }) + + if err != nil { + errs = multierror.Append(errs, fmt.Errorf("error describing Redshift Hsm Client Certificates: %w", err)) + // in case work can be done, don't jump out yet + } + + if err = sweep.SweepOrchestrator(sweepResources); err != nil { + errs = multierror.Append(errs, fmt.Errorf("error sweeping Redshift Hsm Client Certificates for %s: %w", region, err)) + } + + if sweep.SkipSweepError(errs.ErrorOrNil()) { + log.Printf("[WARN] Skipping Redshift Hsm Client Certificate sweep for %s: %s", region, err) + return nil + } + + return errs.ErrorOrNil() +} + +func sweepHSMConfigurations(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + + conn := client.(*conns.AWSClient).RedshiftConn + sweepResources := make([]*sweep.SweepResource, 0) + var errs *multierror.Error + + err = conn.DescribeHsmConfigurationsPages(&redshift.DescribeHsmConfigurationsInput{}, func(resp *redshift.DescribeHsmConfigurationsOutput, lastPage bool) bool { + if len(resp.HsmConfigurations) == 0 { + log.Print("[DEBUG] No Redshift Hsm Configurations to sweep") + return !lastPage + } + + for _, c := range resp.HsmConfigurations { + r := ResourceHSMConfiguration() + d := r.Data(nil) + d.SetId(aws.StringValue(c.HsmConfigurationIdentifier)) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + return !lastPage + }) + + if err != nil { + errs = multierror.Append(errs, fmt.Errorf("error describing Redshift Hsm Configurations: %w", err)) + // in case work can be done, don't jump out yet + } + + if err = sweep.SweepOrchestrator(sweepResources); err != nil { + errs = multierror.Append(errs, fmt.Errorf("error sweeping Redshift Hsm Configurations for %s: %w", region, err)) + } + + if sweep.SkipSweepError(errs.ErrorOrNil()) { + log.Printf("[WARN] Skipping Redshift Hsm Configuration sweep for %s: %s", region, err) + return nil + } + + return errs.ErrorOrNil() +} + +func sweepAuthenticationProfiles(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + + conn := client.(*conns.AWSClient).RedshiftConn + sweepResources := make([]*sweep.SweepResource, 0) + var errs *multierror.Error + + input := &redshift.DescribeAuthenticationProfilesInput{} + output, err := conn.DescribeAuthenticationProfiles(input) + + if len(output.AuthenticationProfiles) == 0 { + log.Print("[DEBUG] No Redshift Authentication Profiles to sweep") + } + + if err != nil { + errs = multierror.Append(errs, fmt.Errorf("error describing Redshift Authentication Profiles: %w", err)) + // in case work can be done, don't jump out yet + } + + for _, c := range output.AuthenticationProfiles { + r := ResourceAuthenticationProfile() + d := r.Data(nil) + d.SetId(aws.StringValue(c.AuthenticationProfileName)) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + if err = sweep.SweepOrchestrator(sweepResources); err != nil { + errs = multierror.Append(errs, fmt.Errorf("error sweeping Redshift Authentication Profiles for %s: %w", region, err)) + } + + if sweep.SkipSweepError(errs.ErrorOrNil()) { + log.Printf("[WARN] Skipping Redshift Authentication Profile sweep for %s: %s", region, err) + return nil + } + + return errs.ErrorOrNil() +} diff --git a/internal/service/redshift/usage_limit.go b/internal/service/redshift/usage_limit.go new file mode 100644 index 00000000000..3bc16bf5e7a --- /dev/null +++ b/internal/service/redshift/usage_limit.go @@ -0,0 +1,209 @@ +package redshift + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" + "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "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" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceUsageLimit() *schema.Resource { + return &schema.Resource{ + Create: resourceUsageLimitCreate, + Read: resourceUsageLimitRead, + Update: resourceUsageLimitUpdate, + Delete: resourceUsageLimitDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "amount": { + Type: schema.TypeInt, + Required: true, + }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "breach_action": { + Type: schema.TypeString, + Optional: true, + Default: redshift.UsageLimitBreachActionLog, + ValidateFunc: validation.StringInSlice(redshift.UsageLimitBreachAction_Values(), false), + }, + "cluster_identifier": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "feature_type": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(redshift.UsageLimitFeatureType_Values(), false), + }, + "limit_type": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(redshift.UsageLimitLimitType_Values(), false), + }, + "period": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: redshift.UsageLimitPeriodMonthly, + ValidateFunc: validation.StringInSlice(redshift.UsageLimitPeriod_Values(), false), + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourceUsageLimitCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + clusterId := d.Get("cluster_identifier").(string) + + input := redshift.CreateUsageLimitInput{ + Amount: aws.Int64(int64(d.Get("amount").(int))), + ClusterIdentifier: aws.String(clusterId), + FeatureType: aws.String(d.Get("feature_type").(string)), + LimitType: aws.String(d.Get("limit_type").(string)), + } + + if v, ok := d.GetOk("breach_action"); ok { + input.BreachAction = aws.String(v.(string)) + } + + if v, ok := d.GetOk("period"); ok { + input.Period = aws.String(v.(string)) + } + + input.Tags = Tags(tags.IgnoreAWS()) + + out, err := conn.CreateUsageLimit(&input) + + if err != nil { + return fmt.Errorf("error creating Redshift Usage Limit (%s): %s", clusterId, err) + } + + d.SetId(aws.StringValue(out.UsageLimitId)) + + return resourceUsageLimitRead(d, meta) +} + +func resourceUsageLimitRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + out, err := FindUsageLimitByID(conn, d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift Usage Limit (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error reading Redshift Usage Limit (%s): %w", d.Id(), err) + } + + arn := arn.ARN{ + Partition: meta.(*conns.AWSClient).Partition, + Service: "redshift", + Region: meta.(*conns.AWSClient).Region, + AccountID: meta.(*conns.AWSClient).AccountID, + Resource: fmt.Sprintf("usagelimit:%s", d.Id()), + }.String() + + d.Set("arn", arn) + d.Set("amount", out.Amount) + d.Set("period", out.Period) + d.Set("limit_type", out.LimitType) + d.Set("feature_type", out.FeatureType) + d.Set("breach_action", out.BreachAction) + d.Set("cluster_identifier", out.ClusterIdentifier) + + tags := KeyValueTags(out.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %w", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return fmt.Errorf("error setting tags_all: %w", err) + } + + return nil +} + +func resourceUsageLimitUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + if d.HasChangesExcept("tags", "tags_all") { + input := &redshift.ModifyUsageLimitInput{ + UsageLimitId: aws.String(d.Id()), + } + + if d.HasChange("amount") { + input.Amount = aws.Int64(int64(d.Get("amount").(int))) + } + + if d.HasChange("breach_action") { + input.BreachAction = aws.String(d.Get("breach_action").(string)) + } + + _, err := conn.ModifyUsageLimit(input) + if err != nil { + return fmt.Errorf("error updating Redshift Usage Limit (%s): %w", d.Id(), err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating Redshift Usage Limit (%s) tags: %s", d.Get("arn").(string), err) + } + } + + return resourceUsageLimitRead(d, meta) +} + +func resourceUsageLimitDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftConn + + deleteInput := redshift.DeleteUsageLimitInput{ + UsageLimitId: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Deleting snapshot copy grant: %s", d.Id()) + _, err := conn.DeleteUsageLimit(&deleteInput) + + if err != nil { + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeUsageLimitNotFoundFault) { + return nil + } + return err + } + + return err +} diff --git a/internal/service/redshift/usage_limit_test.go b/internal/service/redshift/usage_limit_test.go new file mode 100644 index 00000000000..cbf6151962b --- /dev/null +++ b/internal/service/redshift/usage_limit_test.go @@ -0,0 +1,213 @@ +package redshift_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/redshift" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfredshift "github.com/hashicorp/terraform-provider-aws/internal/service/redshift" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccRedshiftUsageLimit_basic(t *testing.T) { + resourceName := "aws_redshift_usage_limit.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckUsageLimitDestroy, + Steps: []resource.TestStep{ + { + Config: testAccUsageLimitConfig_basic(rName, 60), + Check: resource.ComposeTestCheckFunc( + testAccCheckUsageLimitExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "feature_type", "concurrency-scaling"), + resource.TestCheckResourceAttr(resourceName, "limit_type", "time"), + resource.TestCheckResourceAttr(resourceName, "amount", "60"), + resource.TestCheckResourceAttr(resourceName, "breach_action", "log"), + resource.TestCheckResourceAttr(resourceName, "period", "monthly"), + resource.TestCheckResourceAttrPair(resourceName, "cluster_identifier", "aws_redshift_cluster.test", "id"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccUsageLimitConfig_basic(rName, 120), + Check: resource.ComposeTestCheckFunc( + testAccCheckUsageLimitExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "feature_type", "concurrency-scaling"), + resource.TestCheckResourceAttr(resourceName, "limit_type", "time"), + resource.TestCheckResourceAttr(resourceName, "amount", "120"), + resource.TestCheckResourceAttr(resourceName, "breach_action", "log"), + resource.TestCheckResourceAttr(resourceName, "period", "monthly"), + resource.TestCheckResourceAttrPair(resourceName, "cluster_identifier", "aws_redshift_cluster.test", "id"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + }, + }) +} + +func TestAccRedshiftUsageLimit_tags(t *testing.T) { + resourceName := "aws_redshift_usage_limit.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckUsageLimitDestroy, + Steps: []resource.TestStep{ + { + Config: testAccUsageLimitConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckUsageLimitExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccUsageLimitConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccUsageLimitConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckUsageLimitExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func TestAccRedshiftUsageLimit_disappears(t *testing.T) { + resourceName := "aws_redshift_usage_limit.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshift.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckUsageLimitDestroy, + Steps: []resource.TestStep{ + { + Config: testAccUsageLimitConfig_basic(rName, 60), + Check: resource.ComposeTestCheckFunc( + testAccCheckUsageLimitExists(resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfredshift.ResourceUsageLimit(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckUsageLimitDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_redshift_usage_limit" { + continue + } + _, err := tfredshift.FindUsageLimitByID(conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("Redshift Usage Limit %s still exists", rs.Primary.ID) + } + + return nil +} + +func testAccCheckUsageLimitExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("Snapshot Copy Grant ID (UsageLimitName) is not set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn + + _, err := tfredshift.FindUsageLimitByID(conn, rs.Primary.ID) + + if err != nil { + return err + } + + return nil + } +} + +func testAccUsageLimitConfig_basic(rName string, amount int) string { + return acctest.ConfigCompose(testAccClusterConfig_basic(rName), fmt.Sprintf(` +resource "aws_redshift_usage_limit" "test" { + cluster_identifier = aws_redshift_cluster.test.id + feature_type = "concurrency-scaling" + limit_type = "time" + amount = %[1]d +} +`, amount)) +} + +func testAccUsageLimitConfig_tags1(rName, tagKey1, tagValue1 string) string { + return acctest.ConfigCompose(testAccClusterConfig_basic(rName), fmt.Sprintf(` +resource "aws_redshift_usage_limit" "test" { + cluster_identifier = aws_redshift_cluster.test.id + feature_type = "concurrency-scaling" + limit_type = "time" + amount = 60 + + tags = { + %[1]q = %[2]q + } +} +`, tagKey1, tagValue1)) +} + +func testAccUsageLimitConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return acctest.ConfigCompose(testAccClusterConfig_basic(rName), fmt.Sprintf(` +resource "aws_redshift_usage_limit" "test" { + cluster_identifier = aws_redshift_cluster.test.id + feature_type = "concurrency-scaling" + limit_type = "time" + amount = 60 + + tags = { + %[1]q = %[2]q + %[3]q = %[4]q + } +} +`, tagKey1, tagValue1, tagKey2, tagValue2)) +} diff --git a/internal/service/redshift/wait.go b/internal/service/redshift/wait.go index 698b7ee34d0..b1e7e0cd003 100644 --- a/internal/service/redshift/wait.go +++ b/internal/service/redshift/wait.go @@ -14,6 +14,9 @@ const ( clusterInvalidClusterStateFaultTimeout = 15 * time.Minute clusterRelocationStatusResolvedTimeout = 1 * time.Minute + + snapshotScheduleAssociationActivatedTimeout = 75 * time.Minute + snapshotScheduleAssociationDestroyedTimeout = 75 * time.Minute ) func waitClusterCreated(conn *redshift.Redshift, id string, timeout time.Duration) (*redshift.Cluster, error) { @@ -90,3 +93,125 @@ func waitClusterRelocationStatusResolved(conn *redshift.Redshift, id string) (*r return nil, err } + +func waitClusterRebooted(conn *redshift.Redshift, id string, timeout time.Duration) (*redshift.Cluster, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{clusterStatusRebooting, clusterStatusModifying}, + Target: []string{clusterStatusAvailable}, + Refresh: statusCluster(conn, id), + Timeout: timeout, + MinTimeout: 10 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*redshift.Cluster); ok { + tfresource.SetLastError(err, errors.New(aws.StringValue(output.ClusterStatus))) + + return output, err + } + + return nil, err +} + +func waitClusterAquaApplied(conn *redshift.Redshift, id string, timeout time.Duration) (*redshift.Cluster, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{redshift.AquaStatusApplying}, + Target: []string{redshift.AquaStatusDisabled, redshift.AquaStatusEnabled}, + Refresh: statusClusterAqua(conn, id), + Timeout: timeout, + MinTimeout: 10 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*redshift.Cluster); ok { + tfresource.SetLastError(err, errors.New(aws.StringValue(output.ClusterStatus))) + + return output, err + } + + return nil, err +} + +func WaitScheduleAssociationActive(conn *redshift.Redshift, id string) (*redshift.ClusterAssociatedToSchedule, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{redshift.ScheduleStateModifying}, + Target: []string{redshift.ScheduleStateActive}, + Refresh: statusScheduleAssociation(conn, id), + Timeout: snapshotScheduleAssociationActivatedTimeout, + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*redshift.ClusterAssociatedToSchedule); ok { + tfresource.SetLastError(err, errors.New(aws.StringValue(output.ScheduleAssociationState))) + + return output, err + } + + return nil, err +} + +func waitScheduleAssociationDeleted(conn *redshift.Redshift, id string) (*redshift.ClusterAssociatedToSchedule, error) { //nolint:unparam + stateConf := &resource.StateChangeConf{ + Pending: []string{redshift.ScheduleStateModifying, redshift.ScheduleStateActive}, + Target: []string{}, + Refresh: statusScheduleAssociation(conn, id), + Timeout: snapshotScheduleAssociationDestroyedTimeout, + MinTimeout: 10 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*redshift.ClusterAssociatedToSchedule); ok { + tfresource.SetLastError(err, errors.New(aws.StringValue(output.ScheduleAssociationState))) + return output, err + } + + return nil, err +} + +func waitEndpointAccessActive(conn *redshift.Redshift, id string) (*redshift.EndpointAccess, error) { //nolint:unparam + stateConf := &resource.StateChangeConf{ + Pending: []string{endpointAccessStatusCreating, endpointAccessStatusModifying}, + Target: []string{endpointAccessStatusActive}, + Refresh: statusEndpointAccess(conn, id), + Timeout: 10 * time.Minute, + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*redshift.EndpointAccess); ok { + tfresource.SetLastError(err, errors.New(aws.StringValue(output.EndpointStatus))) + + return output, err + } + + return nil, err +} + +func waitEndpointAccessDeleted(conn *redshift.Redshift, id string) (*redshift.EndpointAccess, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{endpointAccessStatusDeleting}, + Target: []string{}, + Refresh: statusEndpointAccess(conn, id), + Timeout: 10 * time.Minute, + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*redshift.EndpointAccess); ok { + tfresource.SetLastError(err, errors.New(aws.StringValue(output.EndpointStatus))) + + return output, err + } + + return nil, err +} diff --git a/internal/service/redshiftdata/find.go b/internal/service/redshiftdata/find.go new file mode 100644 index 00000000000..859d114a952 --- /dev/null +++ b/internal/service/redshiftdata/find.go @@ -0,0 +1,34 @@ +package redshiftdata + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/redshiftdataapiservice" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func FindStatementByID(conn *redshiftdataapiservice.RedshiftDataAPIService, id string) (*redshiftdataapiservice.DescribeStatementOutput, error) { + input := &redshiftdataapiservice.DescribeStatementInput{ + Id: aws.String(id), + } + + output, err := conn.DescribeStatement(input) + + if tfawserr.ErrCodeEquals(err, redshiftdataapiservice.ErrCodeResourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} diff --git a/internal/service/redshiftdata/statement.go b/internal/service/redshiftdata/statement.go new file mode 100644 index 00000000000..4f93959571c --- /dev/null +++ b/internal/service/redshiftdata/statement.go @@ -0,0 +1,237 @@ +package redshiftdata + +import ( + "fmt" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/redshiftdataapiservice" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceStatement() *schema.Resource { + return &schema.Resource{ + Create: resourceStatementCreate, + Read: resourceStatementRead, + Delete: schema.Noop, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(10 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "cluster_identifier": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "database": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "db_user": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "parameters": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + MinItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "value": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + }, + }, + "secret_arn": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: verify.ValidARN, + }, + "sql": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "statement_name": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "with_event": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + }, + }, + } +} + +func resourceStatementCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftDataConn + + input := &redshiftdataapiservice.ExecuteStatementInput{ + ClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)), + Database: aws.String(d.Get("database").(string)), + Sql: aws.String(d.Get("sql").(string)), + WithEvent: aws.Bool(d.Get("with_event").(bool)), + } + + if v, ok := d.GetOk("db_user"); ok { + input.DbUser = aws.String(v.(string)) + } + + if v, ok := d.GetOk("parameters"); ok && len(v.([]interface{})) > 0 { + input.Parameters = expandParameters(v.([]interface{})) + } + + if v, ok := d.GetOk("secret_arn"); ok { + input.SecretArn = aws.String(v.(string)) + } + + if v, ok := d.GetOk("statement_name"); ok { + input.StatementName = aws.String(v.(string)) + } + + output, err := conn.ExecuteStatement(input) + + if err != nil { + return fmt.Errorf("executing Redshift Data Statement: %w", err) + } + + d.SetId(aws.StringValue(output.Id)) + + if _, err := waitStatementFinished(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return fmt.Errorf("waiting for Redshift Data Statement (%s) to finish: %w", d.Id(), err) + } + + return resourceStatementRead(d, meta) +} + +func resourceStatementRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RedshiftDataConn + + sub, err := FindStatementByID(conn, d.Id()) + + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Redshift Data Statement (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("reading Redshift Data Statement (%s): %w", d.Id(), err) + } + + d.Set("cluster_identifier", sub.ClusterIdentifier) + d.Set("secret_arn", sub.SecretArn) + d.Set("database", d.Get("database").(string)) + d.Set("db_user", d.Get("db_user").(string)) + d.Set("sql", sub.QueryString) + + if err := d.Set("parameters", flattenParameters(sub.QueryParameters)); err != nil { + return fmt.Errorf("setting parameters: %w", err) + } + + return nil +} + +func expandParameter(tfMap map[string]interface{}) *redshiftdataapiservice.SqlParameter { + if tfMap == nil { + return nil + } + + apiObject := &redshiftdataapiservice.SqlParameter{} + + if v, ok := tfMap["name"].(string); ok { + apiObject.Name = aws.String(v) + } + + if v, ok := tfMap["value"].(string); ok { + apiObject.Value = aws.String(v) + } + + return apiObject +} + +func expandParameters(tfList []interface{}) []*redshiftdataapiservice.SqlParameter { + if len(tfList) == 0 { + return nil + } + + var apiObjects []*redshiftdataapiservice.SqlParameter + + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]interface{}) + + if !ok { + continue + } + + apiObject := expandParameter(tfMap) + + if apiObject == nil { + continue + } + + apiObjects = append(apiObjects, apiObject) + } + + return apiObjects +} + +func flattenParameter(apiObject *redshiftdataapiservice.SqlParameter) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.Name; v != nil { + tfMap["name"] = aws.StringValue(v) + } + + if v := apiObject.Value; v != nil { + tfMap["value"] = aws.StringValue(v) + } + return tfMap +} + +func flattenParameters(apiObjects []*redshiftdataapiservice.SqlParameter) []interface{} { + if len(apiObjects) == 0 { + return nil + } + + var tfList []interface{} + + for _, apiObject := range apiObjects { + if apiObject == nil { + continue + } + + tfList = append(tfList, flattenParameter(apiObject)) + } + + return tfList +} diff --git a/internal/service/redshiftdata/statement_test.go b/internal/service/redshiftdata/statement_test.go new file mode 100644 index 00000000000..3a9d013aea3 --- /dev/null +++ b/internal/service/redshiftdata/statement_test.go @@ -0,0 +1,92 @@ +package redshiftdata_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/redshiftdataapiservice" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfredshiftdata "github.com/hashicorp/terraform-provider-aws/internal/service/redshiftdata" +) + +func TestAccRedshiftDataStatement_basic(t *testing.T) { + var v redshiftdataapiservice.DescribeStatementOutput + resourceName := "aws_redshiftdata_statement.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, redshiftdataapiservice.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccStatementConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckStatementExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "cluster_identifier", "aws_redshift_cluster.test", "cluster_identifier"), + resource.TestCheckResourceAttr(resourceName, "sql", "CREATE GROUP group_name;"), + resource.TestCheckResourceAttr(resourceName, "parameters.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"database", "db_user"}, + }, + }, + }) +} + +func testAccCheckStatementExists(n string, v *redshiftdataapiservice.DescribeStatementOutput) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Redshift Data Statement ID is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftDataConn + + output, err := tfredshiftdata.FindStatementByID(conn, rs.Primary.ID) + + if err != nil { + return err + } + + *v = *output + + return nil + } +} + +func testAccStatementConfig_basic(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInExclude("usw2-az2"), fmt.Sprintf(` +resource "aws_redshift_cluster" "test" { + cluster_identifier = %[1]q + availability_zone = data.aws_availability_zones.available.names[0] + database_name = "mydb" + master_username = "foo_test" + master_password = "Mustbe8characters" + node_type = "dc2.large" + automated_snapshot_retention_period = 0 + allow_version_upgrade = false + skip_final_snapshot = true +} + +resource "aws_redshiftdata_statement" "test" { + cluster_identifier = aws_redshift_cluster.test.cluster_identifier + database = aws_redshift_cluster.test.database_name + db_user = aws_redshift_cluster.test.master_username + sql = "CREATE GROUP group_name;" +} +`, rName)) +} diff --git a/internal/service/redshiftdata/status.go b/internal/service/redshiftdata/status.go new file mode 100644 index 00000000000..ae19f4f650b --- /dev/null +++ b/internal/service/redshiftdata/status.go @@ -0,0 +1,24 @@ +package redshiftdata + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/redshiftdataapiservice" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func statusStatement(conn *redshiftdataapiservice.RedshiftDataAPIService, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindStatementByID(conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.StringValue(output.Status), nil + } +} diff --git a/internal/service/redshiftdata/wait.go b/internal/service/redshiftdata/wait.go new file mode 100644 index 00000000000..03f15d2df96 --- /dev/null +++ b/internal/service/redshiftdata/wait.go @@ -0,0 +1,38 @@ +package redshiftdata + +import ( + "errors" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/redshiftdataapiservice" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func waitStatementFinished(conn *redshiftdataapiservice.RedshiftDataAPIService, id string, timeout time.Duration) (*redshiftdataapiservice.DescribeStatementOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ + redshiftdataapiservice.StatusStringPicked, + redshiftdataapiservice.StatusStringStarted, + redshiftdataapiservice.StatusStringSubmitted, + }, + Target: []string{redshiftdataapiservice.StatusStringFinished}, + Refresh: statusStatement(conn, id), + Timeout: timeout, + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*redshiftdataapiservice.DescribeStatementOutput); ok { + if status := aws.StringValue(output.Status); status == redshiftdataapiservice.StatusStringFailed { + tfresource.SetLastError(err, errors.New(aws.StringValue(output.Error))) + } + + return output, err + } + + return nil, err +} diff --git a/internal/service/resourcegroups/group_test.go b/internal/service/resourcegroups/group_test.go index 7689c441bd6..1a9980c1a98 100644 --- a/internal/service/resourcegroups/group_test.go +++ b/internal/service/resourcegroups/group_test.go @@ -43,7 +43,7 @@ func TestAccResourceGroupsGroup_Resource_basic(t *testing.T) { CheckDestroy: testAccCheckResourceGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceGroupConfig_basic(n, desc1, testAccResourceGroupQueryConfig), + Config: testAccGroupConfig_basic(n, desc1, testAccResourceGroupQueryConfig), Check: resource.ComposeTestCheckFunc( testAccCheckResourceGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", n), @@ -58,7 +58,7 @@ func TestAccResourceGroupsGroup_Resource_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccResourceGroupConfig_basic(n, desc2, query2), + Config: testAccGroupConfig_basic(n, desc2, query2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "description", desc2), resource.TestCheckResourceAttr(resourceName, "resource_query.0.query", query2+"\n"), @@ -81,7 +81,7 @@ func TestAccResourceGroupsGroup_Resource_tags(t *testing.T) { CheckDestroy: testAccCheckResourceGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceGroupTags1Config(n, desc1, testAccResourceGroupQueryConfig, "key1", "value1"), + Config: testAccGroupConfig_tags1(n, desc1, testAccResourceGroupQueryConfig, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -94,7 +94,7 @@ func TestAccResourceGroupsGroup_Resource_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccResourceGroupTags2Config(n, desc1, testAccResourceGroupQueryConfig, "key1", "value1updated", "key2", "value2"), + Config: testAccGroupConfig_tags2(n, desc1, testAccResourceGroupQueryConfig, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -103,7 +103,7 @@ func TestAccResourceGroupsGroup_Resource_tags(t *testing.T) { ), }, { - Config: testAccResourceGroupTags1Config(n, desc1, testAccResourceGroupQueryConfig, "key2", "value2"), + Config: testAccGroupConfig_tags1(n, desc1, testAccResourceGroupQueryConfig, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceGroupExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -185,7 +185,7 @@ const testAccResourceGroupQueryConfig = `{ ] }` -func testAccResourceGroupConfig_basic(rName, desc, query string) string { +func testAccGroupConfig_basic(rName, desc, query string) string { return fmt.Sprintf(` resource "aws_resourcegroups_group" "test" { name = "%s" @@ -201,7 +201,7 @@ JSON `, rName, desc, query) } -func testAccResourceGroupTags1Config(rName, desc, query, tag1Key, tag1Value string) string { +func testAccGroupConfig_tags1(rName, desc, query, tag1Key, tag1Value string) string { return fmt.Sprintf(` resource "aws_resourcegroups_group" "test" { name = "%s" @@ -221,7 +221,7 @@ JSON `, rName, desc, query, tag1Key, tag1Value) } -func testAccResourceGroupTags2Config(rName, desc, query, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccGroupConfig_tags2(rName, desc, query, tag1Key, tag1Value, tag2Key, tag2Value string) string { return fmt.Sprintf(` resource "aws_resourcegroups_group" "test" { name = "%s" diff --git a/internal/service/resourcegroupstaggingapi/resources_data_source_test.go b/internal/service/resourcegroupstaggingapi/resources_data_source_test.go index af779e37160..860f04bbe3c 100644 --- a/internal/service/resourcegroupstaggingapi/resources_data_source_test.go +++ b/internal/service/resourcegroupstaggingapi/resources_data_source_test.go @@ -21,7 +21,7 @@ func TestAccResourceGroupsTaggingAPIResourcesDataSource_tagFilter(t *testing.T) ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccResourcesTagFilterDataSourceConfig(rName), + Config: testAccResourcesDataSourceConfig_tagFilter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckTypeSetElemNestedAttrs(dataSourceName, "resource_tag_mapping_list.*", map[string]string{ "tags.Key": rName, @@ -43,7 +43,7 @@ func TestAccResourceGroupsTaggingAPIResourcesDataSource_includeComplianceDetails ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccResourcesIncludeComplianceDetailsDataSourceConfig(rName), + Config: testAccResourcesDataSourceConfig_includeComplianceDetails(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "resource_tag_mapping_list.0.compliance_details.#", "1"), resource.TestCheckResourceAttr(dataSourceName, "resource_tag_mapping_list.0.compliance_details.0.compliance_status", "true"), @@ -64,7 +64,7 @@ func TestAccResourceGroupsTaggingAPIResourcesDataSource_resourceTypeFilters(t *t ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccResourcesResourceTypeFiltersDataSourceConfig(rName), + Config: testAccResourcesDataSourceConfig_resourceTypeFilters(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckTypeSetElemNestedAttrs(dataSourceName, "resource_tag_mapping_list.*", map[string]string{ "tags.Key": rName, @@ -87,7 +87,7 @@ func TestAccResourceGroupsTaggingAPIResourcesDataSource_resourceARNList(t *testi ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccResourcesResourceARNListDataSourceConfig(rName), + Config: testAccResourcesDataSourceConfig_resourceARNList(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckTypeSetElemNestedAttrs(dataSourceName, "resource_tag_mapping_list.*", map[string]string{ "tags.Key": rName, @@ -99,7 +99,7 @@ func TestAccResourceGroupsTaggingAPIResourcesDataSource_resourceARNList(t *testi }) } -func testAccResourcesTagFilterDataSourceConfig(rName string) string { +func testAccResourcesDataSourceConfig_tagFilter(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -118,7 +118,7 @@ data "aws_resourcegroupstaggingapi_resources" "test" { `, rName) } -func testAccResourcesResourceTypeFiltersDataSourceConfig(rName string) string { +func testAccResourcesDataSourceConfig_resourceTypeFilters(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -136,7 +136,7 @@ data "aws_resourcegroupstaggingapi_resources" "test" { `, rName) } -func testAccResourcesResourceARNListDataSourceConfig(rName string) string { +func testAccResourcesDataSourceConfig_resourceARNList(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -152,7 +152,7 @@ data "aws_resourcegroupstaggingapi_resources" "test" { `, rName) } -func testAccResourcesIncludeComplianceDetailsDataSourceConfig(rName string) string { +func testAccResourcesDataSourceConfig_includeComplianceDetails(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/route53/health_check_test.go b/internal/service/route53/health_check_test.go index 8847e849a74..6dadff46c62 100644 --- a/internal/service/route53/health_check_test.go +++ b/internal/service/route53/health_check_test.go @@ -143,7 +143,7 @@ func TestAccRoute53HealthCheck_withChildHealthChecks(t *testing.T) { CheckDestroy: testAccCheckHealthCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccHealthCheckConfig_childHealthChecks, + Config: testAccHealthCheckConfig_childs, Check: resource.ComposeTestCheckFunc( testAccCheckHealthCheckExists(resourceName, &check), ), @@ -514,7 +514,7 @@ resource "aws_route53_health_check" "test" { `, ip) } -const testAccHealthCheckConfig_childHealthChecks = ` +const testAccHealthCheckConfig_childs = ` resource "aws_route53_health_check" "child1" { fqdn = "child1.example.com" port = 80 diff --git a/internal/service/route53/hosted_zone_dnssec_test.go b/internal/service/route53/hosted_zone_dnssec_test.go index e5ffa640b00..204bb947411 100644 --- a/internal/service/route53/hosted_zone_dnssec_test.go +++ b/internal/service/route53/hosted_zone_dnssec_test.go @@ -29,7 +29,7 @@ func TestAccRoute53HostedZoneDNSSEC_basic(t *testing.T) { CheckDestroy: testAccCheckHostedZoneDNSSECDestroy, Steps: []resource.TestStep{ { - Config: testAccHostedZoneDNSSECConfig(rName, domainName), + Config: testAccHostedZoneDNSSECConfig_basic(rName, domainName), Check: resource.ComposeAggregateTestCheckFunc( testAccHostedZoneDNSSECExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "hosted_zone_id", route53ZoneResourceName, "id"), @@ -58,7 +58,7 @@ func TestAccRoute53HostedZoneDNSSEC_disappears(t *testing.T) { CheckDestroy: testAccCheckHostedZoneDNSSECDestroy, Steps: []resource.TestStep{ { - Config: testAccHostedZoneDNSSECConfig(rName, domainName), + Config: testAccHostedZoneDNSSECConfig_basic(rName, domainName), Check: resource.ComposeAggregateTestCheckFunc( testAccHostedZoneDNSSECExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53.ResourceHostedZoneDNSSEC(), resourceName), @@ -82,7 +82,7 @@ func TestAccRoute53HostedZoneDNSSEC_signingStatus(t *testing.T) { CheckDestroy: testAccCheckHostedZoneDNSSECDestroy, Steps: []resource.TestStep{ { - Config: testAccHostedZoneDNSSECConfig_SigningStatus(rName, domainName, tfroute53.ServeSignatureNotSigning), + Config: testAccHostedZoneDNSSECConfig_signingStatus(rName, domainName, tfroute53.ServeSignatureNotSigning), Check: resource.ComposeAggregateTestCheckFunc( testAccHostedZoneDNSSECExists(resourceName), resource.TestCheckResourceAttr(resourceName, "signing_status", tfroute53.ServeSignatureNotSigning), @@ -94,14 +94,14 @@ func TestAccRoute53HostedZoneDNSSEC_signingStatus(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccHostedZoneDNSSECConfig_SigningStatus(rName, domainName, tfroute53.ServeSignatureSigning), + Config: testAccHostedZoneDNSSECConfig_signingStatus(rName, domainName, tfroute53.ServeSignatureSigning), Check: resource.ComposeAggregateTestCheckFunc( testAccHostedZoneDNSSECExists(resourceName), resource.TestCheckResourceAttr(resourceName, "signing_status", tfroute53.ServeSignatureSigning), ), }, { - Config: testAccHostedZoneDNSSECConfig_SigningStatus(rName, domainName, tfroute53.ServeSignatureNotSigning), + Config: testAccHostedZoneDNSSECConfig_signingStatus(rName, domainName, tfroute53.ServeSignatureNotSigning), Check: resource.ComposeAggregateTestCheckFunc( testAccHostedZoneDNSSECExists(resourceName), resource.TestCheckResourceAttr(resourceName, "signing_status", tfroute53.ServeSignatureNotSigning), @@ -217,7 +217,7 @@ resource "aws_route53_key_signing_key" "test" { `, rName, domainName)) } -func testAccHostedZoneDNSSECConfig(rName, domainName string) string { +func testAccHostedZoneDNSSECConfig_basic(rName, domainName string) string { return acctest.ConfigCompose( testAccHostedZoneDNSSECConfig_Base(rName, domainName), ` resource "aws_route53_hosted_zone_dnssec" "test" { @@ -226,7 +226,7 @@ resource "aws_route53_hosted_zone_dnssec" "test" { `) } -func testAccHostedZoneDNSSECConfig_SigningStatus(rName, domainName, signingStatus string) string { +func testAccHostedZoneDNSSECConfig_signingStatus(rName, domainName, signingStatus string) string { return acctest.ConfigCompose( testAccHostedZoneDNSSECConfig_Base(rName, domainName), fmt.Sprintf(` diff --git a/internal/service/route53/key_signing_key_test.go b/internal/service/route53/key_signing_key_test.go index 907512d68db..d2ad78eb87b 100644 --- a/internal/service/route53/key_signing_key_test.go +++ b/internal/service/route53/key_signing_key_test.go @@ -38,7 +38,7 @@ func TestAccRoute53KeySigningKey_basic(t *testing.T) { CheckDestroy: testAccCheckKeySigningKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeySigningKeyConfig_Name(rName, domainName), + Config: testAccKeySigningKeyConfig_name(rName, domainName), Check: resource.ComposeAggregateTestCheckFunc( testAccKeySigningKeyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "digest_algorithm_mnemonic", "SHA-256"), @@ -79,7 +79,7 @@ func TestAccRoute53KeySigningKey_disappears(t *testing.T) { CheckDestroy: testAccCheckKeySigningKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeySigningKeyConfig_Name(rName, domainName), + Config: testAccKeySigningKeyConfig_name(rName, domainName), Check: resource.ComposeAggregateTestCheckFunc( testAccKeySigningKeyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53.ResourceKeySigningKey(), resourceName), @@ -103,7 +103,7 @@ func TestAccRoute53KeySigningKey_status(t *testing.T) { CheckDestroy: testAccCheckKeySigningKeyDestroy, Steps: []resource.TestStep{ { - Config: testAccKeySigningKeyConfig_Status(rName, domainName, tfroute53.KeySigningKeyStatusInactive), + Config: testAccKeySigningKeyConfig_status(rName, domainName, tfroute53.KeySigningKeyStatusInactive), Check: resource.ComposeAggregateTestCheckFunc( testAccKeySigningKeyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "status", tfroute53.KeySigningKeyStatusInactive), @@ -115,14 +115,14 @@ func TestAccRoute53KeySigningKey_status(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccKeySigningKeyConfig_Status(rName, domainName, tfroute53.KeySigningKeyStatusActive), + Config: testAccKeySigningKeyConfig_status(rName, domainName, tfroute53.KeySigningKeyStatusActive), Check: resource.ComposeAggregateTestCheckFunc( testAccKeySigningKeyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "status", tfroute53.KeySigningKeyStatusActive), ), }, { - Config: testAccKeySigningKeyConfig_Status(rName, domainName, tfroute53.KeySigningKeyStatusInactive), + Config: testAccKeySigningKeyConfig_status(rName, domainName, tfroute53.KeySigningKeyStatusInactive), Check: resource.ComposeAggregateTestCheckFunc( testAccKeySigningKeyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "status", tfroute53.KeySigningKeyStatusInactive), @@ -232,7 +232,7 @@ resource "aws_route53_zone" "test" { `, rName, domainName)) } -func testAccKeySigningKeyConfig_Name(rName, domainName string) string { +func testAccKeySigningKeyConfig_name(rName, domainName string) string { return acctest.ConfigCompose( testAccKeySigningKeyConfig_Base(rName, domainName), fmt.Sprintf(` @@ -244,7 +244,7 @@ resource "aws_route53_key_signing_key" "test" { `, rName)) } -func testAccKeySigningKeyConfig_Status(rName, domainName, status string) string { +func testAccKeySigningKeyConfig_status(rName, domainName, status string) string { return acctest.ConfigCompose( testAccKeySigningKeyConfig_Base(rName, domainName), fmt.Sprintf(` @@ -290,11 +290,11 @@ func testAccPreCheckKeySigningKey(t *testing.T) { testAccProviderRoute53KeySigningKeyConfigure.Do(func() { testAccProviderRoute53KeySigningKey = provider.Provider() - config := map[string]interface{}{ + testAccRecordConfig_config := map[string]interface{}{ "region": region, } - diags := testAccProviderRoute53KeySigningKey.Configure(context.Background(), terraform.NewResourceConfigRaw(config)) + diags := testAccProviderRoute53KeySigningKey.Configure(context.Background(), terraform.NewResourceConfigRaw(testAccRecordConfig_config)) if diags != nil && diags.HasError() { for _, d := range diags { diff --git a/internal/service/route53/query_log_test.go b/internal/service/route53/query_log_test.go index 447c6b628ff..86f25891b21 100644 --- a/internal/service/route53/query_log_test.go +++ b/internal/service/route53/query_log_test.go @@ -38,7 +38,7 @@ func TestAccRoute53QueryLog_basic(t *testing.T) { CheckDestroy: testAccCheckQueryLogDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckQueryLogResourceBasic1Config(rName, domainName), + Config: testAccQueryLogConfig_resourceBasic1(rName, domainName), Check: resource.ComposeTestCheckFunc( testAccCheckQueryLogExists(resourceName, &queryLoggingConfig), acctest.MatchResourceAttrGlobalARNNoAccount(resourceName, "arn", "route53", regexp.MustCompile("queryloggingconfig/.+")), @@ -69,7 +69,7 @@ func TestAccRoute53QueryLog_disappears(t *testing.T) { CheckDestroy: testAccCheckQueryLogDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckQueryLogResourceBasic1Config(rName, domainName), + Config: testAccQueryLogConfig_resourceBasic1(rName, domainName), Check: resource.ComposeTestCheckFunc( testAccCheckQueryLogExists(resourceName, &queryLoggingConfig), acctest.CheckResourceDisappears(acctest.Provider, tfroute53.ResourceQueryLog(), resourceName), @@ -95,7 +95,7 @@ func TestAccRoute53QueryLog_Disappears_hostedZone(t *testing.T) { CheckDestroy: testAccCheckQueryLogDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckQueryLogResourceBasic1Config(rName, domainName), + Config: testAccQueryLogConfig_resourceBasic1(rName, domainName), Check: resource.ComposeTestCheckFunc( testAccCheckQueryLogExists(resourceName, &queryLoggingConfig), acctest.CheckResourceDisappears(acctest.Provider, tfroute53.ResourceZone(), route53ZoneResourceName), @@ -162,7 +162,7 @@ func testAccCheckQueryLogDestroy(s *terraform.State) error { return nil } -func testAccCheckQueryLogResourceBasic1Config(rName, domainName string) string { +func testAccQueryLogConfig_resourceBasic1(rName, domainName string) string { return acctest.ConfigCompose( testAccQueryLogRegionProviderConfig(), fmt.Sprintf(` @@ -240,11 +240,11 @@ func testAccPreCheckQueryLog(t *testing.T) { testAccProviderRoute53QueryLogConfigure.Do(func() { testAccProviderRoute53QueryLog = provider.Provider() - config := map[string]interface{}{ + testAccRecordConfig_config := map[string]interface{}{ "region": region, } - diags := testAccProviderRoute53QueryLog.Configure(context.Background(), terraform.NewResourceConfigRaw(config)) + diags := testAccProviderRoute53QueryLog.Configure(context.Background(), terraform.NewResourceConfigRaw(testAccRecordConfig_config)) if diags != nil && diags.HasError() { for _, d := range diags { diff --git a/internal/service/route53/record_test.go b/internal/service/route53/record_test.go index 33de7f474e5..6126ceb4abc 100644 --- a/internal/service/route53/record_test.go +++ b/internal/service/route53/record_test.go @@ -466,7 +466,7 @@ func TestAccRoute53Record_failover(t *testing.T) { CheckDestroy: testAccCheckRecordDestroy, Steps: []resource.TestStep{ { - Config: testAccRecordConfig_failoverCNAMERecord, + Config: testAccRecordConfig_failoverCNAME, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists(resourceName, &record1), testAccCheckRecordExists("aws_route53_record.www-secondary", &record2), @@ -493,7 +493,7 @@ func TestAccRoute53Record_Weighted_basic(t *testing.T) { CheckDestroy: testAccCheckRecordDestroy, Steps: []resource.TestStep{ { - Config: testAccRecordConfig_weightedCNAMERecord, + Config: testAccRecordConfig_weightedCNAME, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists("aws_route53_record.www-dev", &record1), testAccCheckRecordExists(resourceName, &record2), @@ -521,7 +521,7 @@ func TestAccRoute53Record_WeightedToSimple_basic(t *testing.T) { CheckDestroy: testAccCheckRecordDestroy, Steps: []resource.TestStep{ { - Config: testaccRecordConfig_weightedRoutingPolicy, + Config: testAccRecordConfig_weightedRoutingPolicy, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists(resourceName, &record1), ), @@ -533,7 +533,7 @@ func TestAccRoute53Record_WeightedToSimple_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"allow_overwrite", "weight"}, }, { - Config: testaccRecordConfig_simpleRoutingPolicy, + Config: testAccRecordConfig_simpleRoutingPolicy, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists(resourceName, &record1), ), @@ -547,7 +547,7 @@ func TestAccRoute53Record_Alias_elb(t *testing.T) { resourceName := "aws_route53_record.alias" rs := sdkacctest.RandString(10) - config := fmt.Sprintf(testAccRecordConfig_aliasELB, rs) + testAccRecordConfig_config := fmt.Sprintf(testAccRecordConfig_aliasELB, rs) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), @@ -555,7 +555,7 @@ func TestAccRoute53Record_Alias_elb(t *testing.T) { CheckDestroy: testAccCheckRecordDestroy, Steps: []resource.TestStep{ { - Config: config, + Config: testAccRecordConfig_config, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists(resourceName, &record1), ), @@ -633,7 +633,7 @@ func TestAccRoute53Record_Alias_uppercase(t *testing.T) { resourceName := "aws_route53_record.alias" rs := sdkacctest.RandString(10) - config := fmt.Sprintf(testAccRecordConfig_aliasELBUppercase, rs) + testAccRecordConfig_config := fmt.Sprintf(testAccRecordConfig_aliasELBUppercase, rs) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), @@ -641,7 +641,7 @@ func TestAccRoute53Record_Alias_uppercase(t *testing.T) { CheckDestroy: testAccCheckRecordDestroy, Steps: []resource.TestStep{ { - Config: config, + Config: testAccRecordConfig_config, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists(resourceName, &record1), ), @@ -667,7 +667,7 @@ func TestAccRoute53Record_Weighted_alias(t *testing.T) { CheckDestroy: testAccCheckRecordDestroy, Steps: []resource.TestStep{ { - Config: testAccRecordConfig_weightedELBAliasRecord, + Config: testAccRecordConfig_weightedELBAlias, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists(resourceName, &record1), testAccCheckRecordExists("aws_route53_record.elb_weighted_alias_dev", &record2), @@ -681,7 +681,7 @@ func TestAccRoute53Record_Weighted_alias(t *testing.T) { }, { - Config: testAccRecordConfig_weightedAliasRecord, + Config: testAccRecordConfig_weightedAlias, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists("aws_route53_record.green_origin", &record3), testAccCheckRecordExists("aws_route53_record.r53_weighted_alias_live", &record4), @@ -704,7 +704,7 @@ func TestAccRoute53Record_Geolocation_basic(t *testing.T) { CheckDestroy: testAccCheckRecordDestroy, Steps: []resource.TestStep{ { - Config: testAccRecordConfig_geolocationCNAMERecord, + Config: testAccRecordConfig_geolocationCNAME, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists("aws_route53_record.default", &record1), testAccCheckRecordExists("aws_route53_record.california", &record2), @@ -983,7 +983,7 @@ func TestAccRoute53Record_longTXTrecord(t *testing.T) { CheckDestroy: testAccCheckRecordDestroy, Steps: []resource.TestStep{ { - Config: testAccRecordConfig_longTxtRecord, + Config: testAccRecordConfig_longTxt, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists(resourceName, &record1), ), @@ -1009,7 +1009,7 @@ func TestAccRoute53Record_MultiValueAnswer_basic(t *testing.T) { CheckDestroy: testAccCheckRecordDestroy, Steps: []resource.TestStep{ { - Config: testAccRecordConfig_multiValueAnswerARecord, + Config: testAccRecordConfig_multiValueAnswerA, Check: resource.ComposeTestCheckFunc( testAccCheckRecordExists("aws_route53_record.www-server1", &record1), testAccCheckRecordExists("aws_route53_record.www-server2", &record2), @@ -1472,7 +1472,7 @@ resource "aws_route53_record" "default" { } ` -const testAccRecordConfig_failoverCNAMERecord = ` +const testAccRecordConfig_failoverCNAME = ` resource "aws_route53_zone" "main" { name = "domain.test" } @@ -1520,7 +1520,7 @@ resource "aws_route53_record" "www-secondary" { } ` -const testAccRecordConfig_weightedCNAMERecord = ` +const testAccRecordConfig_weightedCNAME = ` resource "aws_route53_zone" "main" { name = "domain.test" } @@ -1568,7 +1568,7 @@ resource "aws_route53_record" "www-off" { } ` -const testAccRecordConfig_geolocationCNAMERecord = ` +const testAccRecordConfig_geolocationCNAME = ` resource "aws_route53_zone" "main" { name = "domain.test" } @@ -1982,7 +1982,7 @@ resource "aws_route53_record" "test" { ` } -const testAccRecordConfig_weightedELBAliasRecord = ` +const testAccRecordConfig_weightedELBAlias = ` data "aws_availability_zones" "available" { state = "available" @@ -2057,7 +2057,7 @@ resource "aws_route53_record" "elb_weighted_alias_dev" { } ` -const testAccRecordConfig_weightedAliasRecord = ` +const testAccRecordConfig_weightedAlias = ` resource "aws_route53_zone" "main" { name = "domain.test" } @@ -2271,7 +2271,7 @@ resource "aws_route53_record" "empty" { } ` -const testAccRecordConfig_longTxtRecord = ` +const testAccRecordConfig_longTxt = ` resource "aws_route53_zone" "main" { name = "domain.test" } @@ -2301,7 +2301,7 @@ resource "aws_route53_record" "underscore" { } ` -const testAccRecordConfig_multiValueAnswerARecord = ` +const testAccRecordConfig_multiValueAnswerA = ` resource "aws_route53_zone" "main" { name = "domain.test" } @@ -2327,7 +2327,7 @@ resource "aws_route53_record" "www-server2" { } ` -const testaccRecordConfig_weightedRoutingPolicy = ` +const testAccRecordConfig_weightedRoutingPolicy = ` resource "aws_route53_zone" "main" { name = "domain.test" } @@ -2347,7 +2347,7 @@ resource "aws_route53_record" "www-server1" { } ` -const testaccRecordConfig_simpleRoutingPolicy = ` +const testAccRecordConfig_simpleRoutingPolicy = ` resource "aws_route53_zone" "main" { name = "domain.test" } diff --git a/internal/service/route53/traffic_policy_document_data_source_test.go b/internal/service/route53/traffic_policy_document_data_source_test.go index c8b24681462..ea49d3921c2 100644 --- a/internal/service/route53/traffic_policy_document_data_source_test.go +++ b/internal/service/route53/traffic_policy_document_data_source_test.go @@ -20,7 +20,7 @@ func TestAccRoute53TrafficPolicyDocumentDataSource_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccTrafficPolicyDocumentDataSourceConfig, + Config: testAccTrafficPolicyDocumentDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckTrafficPolicySameJSON("data.aws_route53_traffic_policy_document.test", testAccTrafficPolicyDocumentConfigExpectedJSON()), @@ -37,7 +37,7 @@ func TestAccRoute53TrafficPolicyDocumentDataSource_complete(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccTrafficPolicyDocumentDataSourceConfigComplete, + Config: testAccTrafficPolicyDocumentDataSourceConfig_complete, Check: resource.ComposeTestCheckFunc( testAccCheckTrafficPolicySameJSON("data.aws_route53_traffic_policy_document.test", testAccTrafficPolicyDocumentConfigCompleteExpectedJSON()), @@ -162,7 +162,7 @@ func testAccTrafficPolicyDocumentConfigCompleteExpectedJSON() string { }`, acctest.Region(), acctest.AlternateRegion()) } -const testAccTrafficPolicyDocumentDataSourceConfig = ` +const testAccTrafficPolicyDocumentDataSourceConfig_basic = ` data "aws_region" "current" {} data "aws_route53_traffic_policy_document" "test" { @@ -195,7 +195,7 @@ data "aws_route53_traffic_policy_document" "test" { } ` -const testAccTrafficPolicyDocumentDataSourceConfigComplete = ` +const testAccTrafficPolicyDocumentDataSourceConfig_complete = ` data "aws_availability_zones" "available" { state = "available" } diff --git a/internal/service/route53/traffic_policy_document_model.go b/internal/service/route53/traffic_policy_document_model.go index 061628e763d..ac3d3c3250c 100644 --- a/internal/service/route53/traffic_policy_document_model.go +++ b/internal/service/route53/traffic_policy_document_model.go @@ -2,7 +2,7 @@ package route53 const ( trafficPolicyDocEndpointValue = "value" - trafficPolicyDocEndpointCloudfront = "cloudfront" + trafficPolicyDocEndpointCloudFront = "cloudfront" trafficPolicyDocEndpointElastic = "elastic-load-balancer" trafficPolicyDocEndpointS3 = "s3-website" ) @@ -11,7 +11,7 @@ const ( func TrafficPolicyDocEndpointType_values() []string { return []string{ trafficPolicyDocEndpointValue, - trafficPolicyDocEndpointCloudfront, + trafficPolicyDocEndpointCloudFront, trafficPolicyDocEndpointElastic, trafficPolicyDocEndpointS3, } diff --git a/internal/service/route53/traffic_policy_instance_test.go b/internal/service/route53/traffic_policy_instance_test.go index d563390625d..abebecbfe9f 100644 --- a/internal/service/route53/traffic_policy_instance_test.go +++ b/internal/service/route53/traffic_policy_instance_test.go @@ -37,7 +37,7 @@ func TestAccRoute53TrafficPolicyInstance_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccTrafficPolicyInstanceConfig(rName, zoneName, 3600), + Config: testAccTrafficPolicyInstanceConfig_basic(rName, zoneName, 3600), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficPolicyInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("%s.%s", rName, zoneName)), @@ -66,7 +66,7 @@ func TestAccRoute53TrafficPolicyInstance_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccTrafficPolicyInstanceConfig(rName, zoneName, 360), + Config: testAccTrafficPolicyInstanceConfig_basic(rName, zoneName, 360), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficPolicyInstanceExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfroute53.ResourceTrafficPolicyInstance(), resourceName), @@ -90,14 +90,14 @@ func TestAccRoute53TrafficPolicyInstance_update(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccTrafficPolicyInstanceConfig(rName, zoneName, 3600), + Config: testAccTrafficPolicyInstanceConfig_basic(rName, zoneName, 3600), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficPolicyInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ttl", "3600"), ), }, { - Config: testAccTrafficPolicyInstanceConfig(rName, zoneName, 7200), + Config: testAccTrafficPolicyInstanceConfig_basic(rName, zoneName, 7200), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficPolicyInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "ttl", "7200"), @@ -160,7 +160,7 @@ func testAccCheckTrafficPolicyInstanceDestroy(s *terraform.State) error { return nil } -func testAccTrafficPolicyInstanceConfig(rName, zoneName string, ttl int) string { +func testAccTrafficPolicyInstanceConfig_basic(rName, zoneName string, ttl int) string { return fmt.Sprintf(` resource "aws_route53_zone" "test" { name = %[2]q diff --git a/internal/service/route53/traffic_policy_test.go b/internal/service/route53/traffic_policy_test.go index 5b318a95fcf..ac7a1902402 100644 --- a/internal/service/route53/traffic_policy_test.go +++ b/internal/service/route53/traffic_policy_test.go @@ -27,7 +27,7 @@ func TestAccRoute53TrafficPolicy_basic(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccTrafficPolicyConfig(rName), + Config: testAccTrafficPolicyConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckTrafficPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "comment", ""), @@ -58,7 +58,7 @@ func TestAccRoute53TrafficPolicy_disappears(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccTrafficPolicyConfig(rName), + Config: testAccTrafficPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficPolicyExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfroute53.ResourceTrafficPolicy(), resourceName), @@ -83,14 +83,14 @@ func TestAccRoute53TrafficPolicy_update(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, route53.EndpointsID), Steps: []resource.TestStep{ { - Config: testAccTrafficPolicyConfigComplete(rName, comment), + Config: testAccTrafficPolicyConfig_complete(rName, comment), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "comment", comment), ), }, { - Config: testAccTrafficPolicyConfigComplete(rName, commentUpdated), + Config: testAccTrafficPolicyConfig_complete(rName, commentUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckTrafficPolicyExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "comment", commentUpdated), @@ -165,7 +165,7 @@ func testAccTrafficPolicyImportStateIdFunc(resourceName string) resource.ImportS } } -func testAccTrafficPolicyConfig(rName string) string { +func testAccTrafficPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_route53_traffic_policy" "test" { name = %[1]q @@ -186,7 +186,7 @@ EOT `, rName) } -func testAccTrafficPolicyConfigComplete(rName, comment string) string { +func testAccTrafficPolicyConfig_complete(rName, comment string) string { return fmt.Sprintf(` resource "aws_route53_traffic_policy" "test" { name = %[1]q diff --git a/internal/service/route53/zone_data_source_test.go b/internal/service/route53/zone_data_source_test.go index 4caa55745c8..fcae9e1e53d 100644 --- a/internal/service/route53/zone_data_source_test.go +++ b/internal/service/route53/zone_data_source_test.go @@ -23,7 +23,7 @@ func TestAccRoute53ZoneDataSource_id(t *testing.T) { CheckDestroy: testAccCheckZoneDestroy, Steps: []resource.TestStep{ { - Config: testAccZoneIDDataSourceConfig(fqdn), + Config: testAccZoneDataSourceConfig_id(fqdn), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "id"), @@ -49,7 +49,7 @@ func TestAccRoute53ZoneDataSource_name(t *testing.T) { CheckDestroy: testAccCheckZoneDestroy, Steps: []resource.TestStep{ { - Config: testAccZoneNameDataSourceConfig(fqdn), + Config: testAccZoneDataSourceConfig_name(fqdn), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "id"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "name"), @@ -75,7 +75,7 @@ func TestAccRoute53ZoneDataSource_tags(t *testing.T) { CheckDestroy: testAccCheckZoneDestroy, Steps: []resource.TestStep{ { - Config: testAccZoneTagsPrivateDataSourceConfig(fqdn, rInt), + Config: testAccZoneDataSourceConfig_tagsPrivate(fqdn, rInt), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "id"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "name"), @@ -99,7 +99,7 @@ func TestAccRoute53ZoneDataSource_vpc(t *testing.T) { CheckDestroy: testAccCheckZoneDestroy, Steps: []resource.TestStep{ { - Config: testAccZoneVPCDataSourceConfig(rInt), + Config: testAccZoneDataSourceConfig_vpc(rInt), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "id"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "name"), @@ -123,7 +123,7 @@ func TestAccRoute53ZoneDataSource_serviceDiscovery(t *testing.T) { CheckDestroy: testAccCheckZoneDestroy, Steps: []resource.TestStep{ { - Config: testAccZoneServiceDiscoveryDataSourceConfig(rInt), + Config: testAccZoneDataSourceConfig_serviceDiscovery(rInt), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), resource.TestCheckResourceAttr(dataSourceName, "linked_service_principal", "servicediscovery.amazonaws.com"), @@ -134,7 +134,7 @@ func TestAccRoute53ZoneDataSource_serviceDiscovery(t *testing.T) { }) } -func testAccZoneIDDataSourceConfig(fqdn string) string { +func testAccZoneDataSourceConfig_id(fqdn string) string { return fmt.Sprintf(` resource "aws_route53_zone" "test" { name = %[1]q @@ -146,7 +146,7 @@ data "aws_route53_zone" "test" { `, fqdn) } -func testAccZoneNameDataSourceConfig(fqdn string) string { +func testAccZoneDataSourceConfig_name(fqdn string) string { return fmt.Sprintf(` resource "aws_route53_zone" "test" { name = %[1]q @@ -158,7 +158,7 @@ data "aws_route53_zone" "test" { `, fqdn) } -func testAccZoneTagsPrivateDataSourceConfig(fqdn string, rInt int) string { +func testAccZoneDataSourceConfig_tagsPrivate(fqdn string, rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -189,7 +189,7 @@ data "aws_route53_zone" "test" { `, fqdn, rInt) } -func testAccZoneVPCDataSourceConfig(rInt int) string { +func testAccZoneDataSourceConfig_vpc(rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -219,7 +219,7 @@ data "aws_route53_zone" "test" { `, rInt) } -func testAccZoneServiceDiscoveryDataSourceConfig(rInt int) string { +func testAccZoneDataSourceConfig_serviceDiscovery(rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" diff --git a/internal/service/route53domains/registered_domain_test.go b/internal/service/route53domains/registered_domain_test.go index cd8bd387ab9..3f24bbc58cf 100644 --- a/internal/service/route53domains/registered_domain_test.go +++ b/internal/service/route53domains/registered_domain_test.go @@ -73,14 +73,14 @@ func testAccRegisteredDomain_tags(t *testing.T) { CheckDestroy: testAccCheckRegisteredDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccRegisteredDomainConfigTags1(domainName, "key1", "value1"), + Config: testAccRegisteredDomainConfig_tags1(domainName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { - Config: testAccRegisteredDomainConfigTags2(domainName, "key1", "value1updated", "key2", "value2"), + Config: testAccRegisteredDomainConfig_tags2(domainName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), @@ -88,7 +88,7 @@ func testAccRegisteredDomain_tags(t *testing.T) { ), }, { - Config: testAccRegisteredDomainConfigTags1(domainName, "key2", "value2"), + Config: testAccRegisteredDomainConfig_tags1(domainName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), @@ -114,13 +114,13 @@ func testAccRegisteredDomain_autoRenew(t *testing.T) { CheckDestroy: testAccCheckRegisteredDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccRegisteredDomainAutoRenewConfig(domainName, false), + Config: testAccRegisteredDomainConfig_autoRenew(domainName, false), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "auto_renew", "false"), ), }, { - Config: testAccRegisteredDomainAutoRenewConfig(domainName, true), + Config: testAccRegisteredDomainConfig_autoRenew(domainName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "auto_renew", "true"), ), @@ -145,7 +145,7 @@ func testAccRegisteredDomain_contacts(t *testing.T) { CheckDestroy: testAccCheckRegisteredDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccRegisteredDomainContactsConfig(domainName), + Config: testAccRegisteredDomainConfig_contacts(domainName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "admin_contact.#", "1"), resource.TestCheckResourceAttr(resourceName, "admin_contact.0.address_line_1", "99 High Street"), @@ -185,7 +185,7 @@ func testAccRegisteredDomain_contacts(t *testing.T) { ), }, { - Config: testAccRegisteredDomainContactsUpdatedConfig(domainName), + Config: testAccRegisteredDomainConfig_contactsUpdated(domainName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "admin_contact.#", "1"), resource.TestCheckResourceAttr(resourceName, "admin_contact.0.address_line_1", "101 2nd St #700"), @@ -248,7 +248,7 @@ func testAccRegisteredDomain_contactPrivacy(t *testing.T) { CheckDestroy: testAccCheckRegisteredDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccRegisteredDomainContactPrivacyConfig(domainName, true, true, true), + Config: testAccRegisteredDomainConfig_contactPrivacy(domainName, true, true, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "admin_privacy", "true"), resource.TestCheckResourceAttr(resourceName, "registrant_privacy", "true"), @@ -256,7 +256,7 @@ func testAccRegisteredDomain_contactPrivacy(t *testing.T) { ), }, { - Config: testAccRegisteredDomainContactPrivacyConfig(domainName, false, false, false), + Config: testAccRegisteredDomainConfig_contactPrivacy(domainName, false, false, false), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "admin_privacy", "false"), resource.TestCheckResourceAttr(resourceName, "registrant_privacy", "false"), @@ -283,7 +283,7 @@ func testAccRegisteredDomain_nameservers(t *testing.T) { CheckDestroy: testAccCheckRegisteredDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccRegisteredDomainNameserversConfig(domainName), + Config: testAccRegisteredDomainConfig_nameservers(domainName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name_server.#", "2"), resource.TestCheckResourceAttr(resourceName, "name_server.0.name", fmt.Sprintf("ns1.%s", domainName)), @@ -294,7 +294,7 @@ func testAccRegisteredDomain_nameservers(t *testing.T) { ), }, { - Config: testAccRegisteredDomainNameserversUpdatedConfig(domainName), + Config: testAccRegisteredDomainConfig_nameserversUpdated(domainName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "name_server.#", "4"), resource.TestCheckResourceAttr(resourceName, "name_server.0.name", "ns-195.awsdns-24.com"), @@ -327,13 +327,13 @@ func testAccRegisteredDomain_transferLock(t *testing.T) { CheckDestroy: testAccCheckRegisteredDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccRegisteredDomainTransferLockConfig(domainName, false), + Config: testAccRegisteredDomainConfig_transferLock(domainName, false), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "transfer_lock", "false"), ), }, { - Config: testAccRegisteredDomainTransferLockConfig(domainName, true), + Config: testAccRegisteredDomainConfig_transferLock(domainName, true), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "transfer_lock", "true"), ), @@ -346,7 +346,7 @@ func testAccCheckRegisteredDomainDestroy(s *terraform.State) error { return nil } -func testAccRegisteredDomainConfigTags1(domainName, tagKey1, tagValue1 string) string { +func testAccRegisteredDomainConfig_tags1(domainName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_route53domains_registered_domain" "test" { domain_name = %[1]q @@ -358,7 +358,7 @@ resource "aws_route53domains_registered_domain" "test" { `, domainName, tagKey1, tagValue1) } -func testAccRegisteredDomainConfigTags2(domainName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccRegisteredDomainConfig_tags2(domainName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_route53domains_registered_domain" "test" { domain_name = %[1]q @@ -371,7 +371,7 @@ resource "aws_route53domains_registered_domain" "test" { `, domainName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccRegisteredDomainAutoRenewConfig(domainName string, autoRenew bool) string { +func testAccRegisteredDomainConfig_autoRenew(domainName string, autoRenew bool) string { return fmt.Sprintf(` resource "aws_route53domains_registered_domain" "test" { domain_name = %[1]q @@ -380,7 +380,7 @@ resource "aws_route53domains_registered_domain" "test" { `, domainName, autoRenew) } -func testAccRegisteredDomainContactsConfig(domainName string) string { +func testAccRegisteredDomainConfig_contacts(domainName string) string { return fmt.Sprintf(` resource "aws_route53domains_registered_domain" "test" { domain_name = %[1]q @@ -429,7 +429,7 @@ resource "aws_route53domains_registered_domain" "test" { `, domainName) } -func testAccRegisteredDomainContactsUpdatedConfig(domainName string) string { +func testAccRegisteredDomainConfig_contactsUpdated(domainName string) string { return fmt.Sprintf(` resource "aws_route53domains_registered_domain" "test" { domain_name = %[1]q @@ -482,7 +482,7 @@ resource "aws_route53domains_registered_domain" "test" { `, domainName) } -func testAccRegisteredDomainContactPrivacyConfig(domainName string, adminPrivacy, registrantPrivacy, techPrivacy bool) string { +func testAccRegisteredDomainConfig_contactPrivacy(domainName string, adminPrivacy, registrantPrivacy, techPrivacy bool) string { return fmt.Sprintf(` resource "aws_route53domains_registered_domain" "test" { domain_name = %[1]q @@ -494,7 +494,7 @@ resource "aws_route53domains_registered_domain" "test" { `, domainName, adminPrivacy, registrantPrivacy, techPrivacy) } -func testAccRegisteredDomainNameserversConfig(domainName string) string { +func testAccRegisteredDomainConfig_nameservers(domainName string) string { return fmt.Sprintf(` resource "aws_route53domains_registered_domain" "test" { domain_name = %[1]q @@ -513,7 +513,7 @@ resource "aws_route53domains_registered_domain" "test" { `, domainName) } -func testAccRegisteredDomainNameserversUpdatedConfig(domainName string) string { +func testAccRegisteredDomainConfig_nameserversUpdated(domainName string) string { return fmt.Sprintf(` resource "aws_route53domains_registered_domain" "test" { domain_name = %[1]q @@ -537,7 +537,7 @@ resource "aws_route53domains_registered_domain" "test" { `, domainName) } -func testAccRegisteredDomainTransferLockConfig(domainName string, transferLock bool) string { +func testAccRegisteredDomainConfig_transferLock(domainName string, transferLock bool) string { return fmt.Sprintf(` resource "aws_route53domains_registered_domain" "test" { domain_name = %[1]q diff --git a/internal/service/route53recoverycontrolconfig/cluster_test.go b/internal/service/route53recoverycontrolconfig/cluster_test.go index 97f3e08fb8e..20caae00a5e 100644 --- a/internal/service/route53recoverycontrolconfig/cluster_test.go +++ b/internal/service/route53recoverycontrolconfig/cluster_test.go @@ -25,7 +25,7 @@ func testAccCluster_basic(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -54,7 +54,7 @@ func testAccCluster_disappears(t *testing.T) { CheckDestroy: testAccCheckClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccClusterConfig(rName), + Config: testAccClusterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckClusterExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53recoverycontrolconfig.ResourceCluster(), resourceName), @@ -87,7 +87,7 @@ func testAccCheckClusterDestroy(s *terraform.State) error { return nil } -func testAccClusterConfig(rName string) string { +func testAccClusterConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_route53recoverycontrolconfig_cluster" "test" { name = %[1]q diff --git a/internal/service/route53recoverycontrolconfig/control_panel_test.go b/internal/service/route53recoverycontrolconfig/control_panel_test.go index c7d146459a6..875327cfd65 100644 --- a/internal/service/route53recoverycontrolconfig/control_panel_test.go +++ b/internal/service/route53recoverycontrolconfig/control_panel_test.go @@ -25,7 +25,7 @@ func testAccControlPanel_basic(t *testing.T) { CheckDestroy: testAccCheckControlPanelDestroy, Steps: []resource.TestStep{ { - Config: testAccControlPanelConfig(rName), + Config: testAccControlPanelConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckControlPanelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -54,7 +54,7 @@ func testAccControlPanel_disappears(t *testing.T) { CheckDestroy: testAccCheckControlPanelDestroy, Steps: []resource.TestStep{ { - Config: testAccControlPanelConfig(rName), + Config: testAccControlPanelConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckControlPanelExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53recoverycontrolconfig.ResourceControlPanel(), resourceName), @@ -95,7 +95,7 @@ resource "aws_route53recoverycontrolconfig_cluster" "test" { `, rName) } -func testAccControlPanelConfig(rName string) string { +func testAccControlPanelConfig_basic(rName string) string { return acctest.ConfigCompose(testAccClusterSetUp(rName), fmt.Sprintf(` resource "aws_route53recoverycontrolconfig_control_panel" "test" { name = %[1]q diff --git a/internal/service/route53recoverycontrolconfig/routing_control_test.go b/internal/service/route53recoverycontrolconfig/routing_control_test.go index 8e4039ab9c5..58c1ea96dd6 100644 --- a/internal/service/route53recoverycontrolconfig/routing_control_test.go +++ b/internal/service/route53recoverycontrolconfig/routing_control_test.go @@ -25,7 +25,7 @@ func testAccRoutingControl_basic(t *testing.T) { CheckDestroy: testAccCheckRoutingControlDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingControlConfig_InDefaultControlPanel(rName), + Config: testAccRoutingControlConfig_inDefaultPanel(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRoutingControlExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -55,7 +55,7 @@ func testAccRoutingControl_disappears(t *testing.T) { CheckDestroy: testAccCheckRoutingControlDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingControlConfig_InDefaultControlPanel(rName), + Config: testAccRoutingControlConfig_inDefaultPanel(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRoutingControlExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53recoverycontrolconfig.ResourceRoutingControl(), resourceName), @@ -77,7 +77,7 @@ func testAccRoutingControl_nonDefaultControlPanel(t *testing.T) { CheckDestroy: testAccCheckRoutingControlDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingControlConfig_InNonDefaultControlPanel(rName), + Config: testAccRoutingControlConfig_inNonDefaultPanel(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRoutingControlExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -137,7 +137,7 @@ resource "aws_route53recoverycontrolconfig_cluster" "test" { `, rName) } -func testAccRoutingControlConfig_InDefaultControlPanel(rName string) string { +func testAccRoutingControlConfig_inDefaultPanel(rName string) string { return acctest.ConfigCompose( testAccClusterBase(rName), fmt.Sprintf(` resource "aws_route53recoverycontrolconfig_routing_control" "test" { @@ -156,7 +156,7 @@ resource "aws_route53recoverycontrolconfig_control_panel" "test" { `, rName) } -func testAccRoutingControlConfig_InNonDefaultControlPanel(rName string) string { +func testAccRoutingControlConfig_inNonDefaultPanel(rName string) string { return acctest.ConfigCompose( testAccClusterBase(rName), testAccControlPanelBase(rName), diff --git a/internal/service/route53recoverycontrolconfig/safety_rule_test.go b/internal/service/route53recoverycontrolconfig/safety_rule_test.go index c91d2e69995..5162586a17f 100644 --- a/internal/service/route53recoverycontrolconfig/safety_rule_test.go +++ b/internal/service/route53recoverycontrolconfig/safety_rule_test.go @@ -25,7 +25,7 @@ func testAccSafetyRule_assertionRule(t *testing.T) { CheckDestroy: testAccCheckSafetyRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingControlSafetyRuleAssertionConfig(rName), + Config: testAccSafetyRuleConfig_routingControlAssertion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSafetyRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -55,7 +55,7 @@ func testAccSafetyRule_disappears(t *testing.T) { CheckDestroy: testAccCheckSafetyRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingControlSafetyRuleAssertionConfig(rName), + Config: testAccSafetyRuleConfig_routingControlAssertion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSafetyRuleExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53recoverycontrolconfig.ResourceSafetyRule(), resourceName), @@ -77,7 +77,7 @@ func testAccSafetyRule_gatingRule(t *testing.T) { CheckDestroy: testAccCheckSafetyRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccRoutingControlSafetyRuleGatingConfig(rName), + Config: testAccSafetyRuleConfig_routingControlGating(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSafetyRuleExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -138,7 +138,7 @@ func testAccCheckSafetyRuleExists(name string) resource.TestCheckFunc { } } -func testAccRoutingControlSafetyRuleAssertionConfig(rName string) string { +func testAccSafetyRuleConfig_routingControlAssertion(rName string) string { return fmt.Sprintf(` resource "aws_route53recoverycontrolconfig_cluster" "test" { name = %[1]q @@ -170,7 +170,7 @@ resource "aws_route53recoverycontrolconfig_safety_rule" "test" { `, rName) } -func testAccRoutingControlSafetyRuleGatingConfig(rName string) string { +func testAccSafetyRuleConfig_routingControlGating(rName string) string { return fmt.Sprintf(` resource "aws_route53recoverycontrolconfig_cluster" "test" { name = %[1]q diff --git a/internal/service/route53recoveryreadiness/cell_test.go b/internal/service/route53recoveryreadiness/cell_test.go index 4fa296db491..789b8410b60 100644 --- a/internal/service/route53recoveryreadiness/cell_test.go +++ b/internal/service/route53recoveryreadiness/cell_test.go @@ -26,7 +26,7 @@ func TestAccRoute53RecoveryReadinessCell_basic(t *testing.T) { CheckDestroy: testAccCheckCellDestroy, Steps: []resource.TestStep{ { - Config: testAccCellConfig(rName), + Config: testAccCellConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCellExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`cell/.+`)), @@ -55,7 +55,7 @@ func TestAccRoute53RecoveryReadinessCell_disappears(t *testing.T) { CheckDestroy: testAccCheckCellDestroy, Steps: []resource.TestStep{ { - Config: testAccCellConfig(rName), + Config: testAccCellConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCellExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53recoveryreadiness.ResourceCell(), resourceName), @@ -79,14 +79,14 @@ func TestAccRoute53RecoveryReadinessCell_nestedCell(t *testing.T) { CheckDestroy: testAccCheckCellDestroy, Steps: []resource.TestStep{ { - Config: testAccCellChildConfig(rNameChild), + Config: testAccCellConfig_child(rNameChild), Check: resource.ComposeTestCheckFunc( testAccCheckCellExists(resourceNameChild), acctest.MatchResourceAttrGlobalARN(resourceNameChild, "arn", "route53-recovery-readiness", regexp.MustCompile(`cell/.+`)), ), }, { - Config: testAccCellParentConfig(rNameChild, rNameParent), + Config: testAccCellConfig_parent(rNameChild, rNameParent), Check: resource.ComposeTestCheckFunc( testAccCheckCellExists(resourceNameParent), acctest.MatchResourceAttrGlobalARN(resourceNameParent, "arn", "route53-recovery-readiness", regexp.MustCompile(`cell/.+`)), @@ -98,7 +98,7 @@ func TestAccRoute53RecoveryReadinessCell_nestedCell(t *testing.T) { ), }, { - Config: testAccCellParentConfig(rNameChild, rNameParent), + Config: testAccCellConfig_parent(rNameChild, rNameParent), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceNameChild, "parent_readiness_scopes.#", "1"), ), @@ -128,7 +128,7 @@ func TestAccRoute53RecoveryReadinessCell_tags(t *testing.T) { CheckDestroy: testAccCheckCellDestroy, Steps: []resource.TestStep{ { - Config: testAccCellConfig_Tags1(rName, "key1", "value1"), + Config: testAccCellConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckCellExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -141,7 +141,7 @@ func TestAccRoute53RecoveryReadinessCell_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCellConfig_Tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccCellConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCellExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -150,7 +150,7 @@ func TestAccRoute53RecoveryReadinessCell_tags(t *testing.T) { ), }, { - Config: testAccCellConfig_Tags1(rName, "key2", "value2"), + Config: testAccCellConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCellExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -172,7 +172,7 @@ func TestAccRoute53RecoveryReadinessCell_timeout(t *testing.T) { CheckDestroy: testAccCheckCellDestroy, Steps: []resource.TestStep{ { - Config: testAccCellConfig_Timeout(rName), + Config: testAccCellConfig_timeout(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCellExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`cell/.+`)), @@ -247,7 +247,7 @@ func testAccPreCheck(t *testing.T) { } } -func testAccCellConfig(rName string) string { +func testAccCellConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_cell" "test" { cell_name = %q @@ -255,7 +255,7 @@ resource "aws_route53recoveryreadiness_cell" "test" { `, rName) } -func testAccCellChildConfig(rName string) string { +func testAccCellConfig_child(rName string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_cell" "test_child" { cell_name = %q @@ -263,8 +263,8 @@ resource "aws_route53recoveryreadiness_cell" "test_child" { `, rName) } -func testAccCellParentConfig(rName, rName2 string) string { - return acctest.ConfigCompose(testAccCellChildConfig(rName), fmt.Sprintf(` +func testAccCellConfig_parent(rName, rName2 string) string { + return acctest.ConfigCompose(testAccCellConfig_child(rName), fmt.Sprintf(` resource "aws_route53recoveryreadiness_cell" "test_parent" { cell_name = %q cells = [aws_route53recoveryreadiness_cell.test_child.arn] @@ -272,7 +272,7 @@ resource "aws_route53recoveryreadiness_cell" "test_parent" { `, rName2)) } -func testAccCellConfig_Tags1(rName, tagKey1, tagValue1 string) string { +func testAccCellConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_cell" "test" { cell_name = %[1]q @@ -284,7 +284,7 @@ resource "aws_route53recoveryreadiness_cell" "test" { `, rName, tagKey1, tagValue1) } -func testAccCellConfig_Tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccCellConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_cell" "test" { cell_name = %[1]q @@ -297,7 +297,7 @@ resource "aws_route53recoveryreadiness_cell" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccCellConfig_Timeout(rName string) string { +func testAccCellConfig_timeout(rName string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_cell" "test" { cell_name = %q diff --git a/internal/service/route53recoveryreadiness/readiness_check_test.go b/internal/service/route53recoveryreadiness/readiness_check_test.go index 2342e6d3bad..a6923885a02 100644 --- a/internal/service/route53recoveryreadiness/readiness_check_test.go +++ b/internal/service/route53recoveryreadiness/readiness_check_test.go @@ -36,7 +36,7 @@ func TestAccRoute53RecoveryReadinessReadinessCheck_basic(t *testing.T) { CheckDestroy: testAccCheckReadinessCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccReadinessCheckConfig(rName, rSetName, cwArn), + Config: testAccReadinessCheckConfig_basic(rName, rSetName, cwArn), Check: resource.ComposeTestCheckFunc( testAccCheckReadinessCheckExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`readiness-check/.+`)), @@ -71,7 +71,7 @@ func TestAccRoute53RecoveryReadinessReadinessCheck_disappears(t *testing.T) { CheckDestroy: testAccCheckReadinessCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccReadinessCheckConfig(rName, rSetName, cwArn), + Config: testAccReadinessCheckConfig_basic(rName, rSetName, cwArn), Check: resource.ComposeTestCheckFunc( testAccCheckReadinessCheckExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53recoveryreadiness.ResourceReadinessCheck(), resourceName), @@ -100,7 +100,7 @@ func TestAccRoute53RecoveryReadinessReadinessCheck_tags(t *testing.T) { CheckDestroy: testAccCheckReadinessCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccReadinessCheckConfig_Tags1(rName, cwArn, "key1", "value1"), + Config: testAccReadinessCheckConfig_tags1(rName, cwArn, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckReadinessCheckExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -113,7 +113,7 @@ func TestAccRoute53RecoveryReadinessReadinessCheck_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccReadinessCheckConfig_Tags2(rName, cwArn, "key1", "value1updated", "key2", "value2"), + Config: testAccReadinessCheckConfig_tags2(rName, cwArn, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckReadinessCheckExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -122,7 +122,7 @@ func TestAccRoute53RecoveryReadinessReadinessCheck_tags(t *testing.T) { ), }, { - Config: testAccReadinessCheckConfig_Tags1(rName, cwArn, "key2", "value2"), + Config: testAccReadinessCheckConfig_tags1(rName, cwArn, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckReadinessCheckExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -152,7 +152,7 @@ func TestAccRoute53RecoveryReadinessReadinessCheck_timeout(t *testing.T) { CheckDestroy: testAccCheckReadinessCheckDestroy, Steps: []resource.TestStep{ { - Config: testAccReadinessCheckConfig_Timeout(rName, rSetName, cwArn), + Config: testAccReadinessCheckConfig_timeout(rName, rSetName, cwArn), Check: resource.ComposeTestCheckFunc( testAccCheckReadinessCheckExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`readiness-check/.+`)), @@ -221,7 +221,7 @@ resource "aws_route53recoveryreadiness_resource_set" "test" { `, rSetName, cwArn) } -func testAccReadinessCheckConfig(rName, rSetName, cwArn string) string { +func testAccReadinessCheckConfig_basic(rName, rSetName, cwArn string) string { return acctest.ConfigCompose(testAccReadinessCheckConfig_ResourceSet(rSetName, cwArn), fmt.Sprintf(` resource "aws_route53recoveryreadiness_readiness_check" "test" { readiness_check_name = %q @@ -230,7 +230,7 @@ resource "aws_route53recoveryreadiness_readiness_check" "test" { `, rName)) } -func testAccReadinessCheckConfig_Tags1(rName, cwArn, tagKey1, tagValue1 string) string { +func testAccReadinessCheckConfig_tags1(rName, cwArn, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccReadinessCheckConfig_ResourceSet("resource-set-for-testing", cwArn), fmt.Sprintf(` resource "aws_route53recoveryreadiness_readiness_check" "test" { readiness_check_name = %[1]q @@ -243,7 +243,7 @@ resource "aws_route53recoveryreadiness_readiness_check" "test" { `, rName, tagKey1, tagValue1)) } -func testAccReadinessCheckConfig_Tags2(rName, cwArn, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccReadinessCheckConfig_tags2(rName, cwArn, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccReadinessCheckConfig_ResourceSet("resource-set-for-testing", cwArn), fmt.Sprintf(` resource "aws_route53recoveryreadiness_readiness_check" "test" { readiness_check_name = %[1]q @@ -257,7 +257,7 @@ resource "aws_route53recoveryreadiness_readiness_check" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccReadinessCheckConfig_Timeout(rName, rSetName, cwArn string) string { +func testAccReadinessCheckConfig_timeout(rName, rSetName, cwArn string) string { return acctest.ConfigCompose(testAccReadinessCheckConfig_ResourceSet(rSetName, cwArn), fmt.Sprintf(` resource "aws_route53recoveryreadiness_readiness_check" "test" { readiness_check_name = %q diff --git a/internal/service/route53recoveryreadiness/recovery_group_test.go b/internal/service/route53recoveryreadiness/recovery_group_test.go index 3d3f2d4524a..3aa85338005 100644 --- a/internal/service/route53recoveryreadiness/recovery_group_test.go +++ b/internal/service/route53recoveryreadiness/recovery_group_test.go @@ -26,7 +26,7 @@ func TestAccRoute53RecoveryReadinessRecoveryGroup_basic(t *testing.T) { CheckDestroy: testAccCheckRecoveryGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRecoveryGroupConfig(rName), + Config: testAccRecoveryGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRecoveryGroupExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`recovery-group/.+`)), @@ -54,7 +54,7 @@ func TestAccRoute53RecoveryReadinessRecoveryGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckRecoveryGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRecoveryGroupConfig(rName), + Config: testAccRecoveryGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRecoveryGroupExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53recoveryreadiness.ResourceRecoveryGroup(), resourceName), @@ -76,7 +76,7 @@ func TestAccRoute53RecoveryReadinessRecoveryGroup_nestedCell(t *testing.T) { CheckDestroy: testAccCheckRecoveryGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRecoveryGroupAndCellConfig(rName, rNameCell), + Config: testAccRecoveryGroupConfig_andCell(rName, rNameCell), Check: resource.ComposeTestCheckFunc( testAccCheckRecoveryGroupExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`recovery-group/.+`)), @@ -102,7 +102,7 @@ func TestAccRoute53RecoveryReadinessRecoveryGroup_tags(t *testing.T) { CheckDestroy: testAccCheckRecoveryGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRecoveryGroupConfig_Tags1(rName, "key1", "value1"), + Config: testAccRecoveryGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckRecoveryGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -115,7 +115,7 @@ func TestAccRoute53RecoveryReadinessRecoveryGroup_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRecoveryGroupConfig_Tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccRecoveryGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRecoveryGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -124,7 +124,7 @@ func TestAccRoute53RecoveryReadinessRecoveryGroup_tags(t *testing.T) { ), }, { - Config: testAccRecoveryGroupConfig_Tags1(rName, "key2", "value2"), + Config: testAccRecoveryGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRecoveryGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -145,7 +145,7 @@ func TestAccRoute53RecoveryReadinessRecoveryGroup_timeout(t *testing.T) { CheckDestroy: testAccCheckRecoveryGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccRecoveryGroupConfig_Timeout(rName), + Config: testAccRecoveryGroupConfig_timeout(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRecoveryGroupExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`recovery-group/.+`)), @@ -202,7 +202,7 @@ func testAccCheckRecoveryGroupExists(name string) resource.TestCheckFunc { } } -func testAccRecoveryGroupConfig(rName string) string { +func testAccRecoveryGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_recovery_group" "test" { recovery_group_name = %q @@ -210,7 +210,7 @@ resource "aws_route53recoveryreadiness_recovery_group" "test" { `, rName) } -func testAccRecoveryGroupAndCellConfig(rName, rNameCell string) string { +func testAccRecoveryGroupConfig_andCell(rName, rNameCell string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_cell" "test" { cell_name = %[2]q @@ -223,7 +223,7 @@ resource "aws_route53recoveryreadiness_recovery_group" "test" { `, rName, rNameCell) } -func testAccRecoveryGroupConfig_Tags1(rName, tagKey1, tagValue1 string) string { +func testAccRecoveryGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_recovery_group" "test" { recovery_group_name = %[1]q @@ -234,7 +234,7 @@ resource "aws_route53recoveryreadiness_recovery_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccRecoveryGroupConfig_Tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccRecoveryGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_recovery_group" "test" { recovery_group_name = %[1]q @@ -246,7 +246,7 @@ resource "aws_route53recoveryreadiness_recovery_group" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccRecoveryGroupConfig_Timeout(rName string) string { +func testAccRecoveryGroupConfig_timeout(rName string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_recovery_group" "test" { recovery_group_name = %q diff --git a/internal/service/route53recoveryreadiness/resource_set_test.go b/internal/service/route53recoveryreadiness/resource_set_test.go index 56cab2088c4..aa5bf592e31 100644 --- a/internal/service/route53recoveryreadiness/resource_set_test.go +++ b/internal/service/route53recoveryreadiness/resource_set_test.go @@ -35,7 +35,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_basic(t *testing.T) { CheckDestroy: testAccCheckResourceSetDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceSetConfig(rName, cwArn), + Config: testAccResourceSetConfig_basic(rName, cwArn), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`resource-set.+`)), @@ -70,7 +70,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_disappears(t *testing.T) { CheckDestroy: testAccCheckResourceSetDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceSetConfig(rName, cwArn), + Config: testAccResourceSetConfig_basic(rName, cwArn), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfroute53recoveryreadiness.ResourceResourceSet(), resourceName), @@ -99,7 +99,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_tags(t *testing.T) { CheckDestroy: testAccCheckResourceSetDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceSetConfig_Tags1(rName, cwArn, "key1", "value1"), + Config: testAccResourceSetConfig_tags1(rName, cwArn, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -112,7 +112,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccResourceSetConfig_Tags2(rName, cwArn, "key1", "value1updated", "key2", "value2"), + Config: testAccResourceSetConfig_tags2(rName, cwArn, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -121,7 +121,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_tags(t *testing.T) { ), }, { - Config: testAccResourceSetConfig_Tags1(rName, cwArn, "key2", "value2"), + Config: testAccResourceSetConfig_tags1(rName, cwArn, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -150,7 +150,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_readinessScope(t *testing.T) { CheckDestroy: testAccCheckResourceSetDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceSetConfig_ReadinessScopes(rName, cwArn), + Config: testAccResourceSetConfig_readinessScopes(rName, cwArn), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`resource-set.+`)), @@ -190,7 +190,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_basicDNSTargetResource(t *testin CheckDestroy: testAccCheckResourceSetDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceSetBasicDNSTargetResourceConfig(rName, domainName, hzArn, recordType, recordSetId), + Config: testAccResourceSetConfig_basicDNSTarget(rName, domainName, hzArn, recordType, recordSetId), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`resource-set.+`)), @@ -230,7 +230,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_dnsTargetResourceNLBTarget(t *te CheckDestroy: testAccCheckResourceSetDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceSetDNSTargetResourceNlbTargetConfig(rName, hzArn), + Config: testAccResourceSetConfig_dnsTargetNlbTarget(rName, hzArn), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`resource-set.+`)), @@ -269,7 +269,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_dnsTargetResourceR53Target(t *te CheckDestroy: testAccCheckResourceSetDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceSetDNSTargetResourceR53TargetConfig(rName, hzArn, domainName, recordSetId), + Config: testAccResourceSetConfig_dnsTargetR53Target(rName, hzArn, domainName, recordSetId), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`resource-set.+`)), @@ -304,7 +304,7 @@ func TestAccRoute53RecoveryReadinessResourceSet_timeout(t *testing.T) { CheckDestroy: testAccCheckResourceSetDestroy, Steps: []resource.TestStep{ { - Config: testAccResourceSetConfig_Timeout(rName, cwArn), + Config: testAccResourceSetConfig_timeout(rName, cwArn), Check: resource.ComposeTestCheckFunc( testAccCheckResourceSetExists(resourceName), acctest.MatchResourceAttrGlobalARN(resourceName, "arn", "route53-recovery-readiness", regexp.MustCompile(`resource-set.+`)), @@ -422,7 +422,7 @@ data "aws_caller_identity" "current" {} `, rName) } -func testAccResourceSetConfig(rName, cwArn string) string { +func testAccResourceSetConfig_basic(rName, cwArn string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_resource_set" "test" { resource_set_name = %[1]q @@ -435,7 +435,7 @@ resource "aws_route53recoveryreadiness_resource_set" "test" { `, rName, cwArn) } -func testAccResourceSetConfig_Tags1(rName, cwArn, tagKey1, tagValue1 string) string { +func testAccResourceSetConfig_tags1(rName, cwArn, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_resource_set" "test" { resource_set_name = %[1]q @@ -452,7 +452,7 @@ resource "aws_route53recoveryreadiness_resource_set" "test" { `, rName, cwArn, tagKey1, tagValue1) } -func testAccResourceSetConfig_Tags2(rName, cwArn, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccResourceSetConfig_tags2(rName, cwArn, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_resource_set" "test" { resource_set_name = %[1]q @@ -470,7 +470,7 @@ resource "aws_route53recoveryreadiness_resource_set" "test" { `, rName, cwArn, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccResourceSetConfig_ReadinessScopes(rName, cwArn string) string { +func testAccResourceSetConfig_readinessScopes(rName, cwArn string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_cell" "test" { cell_name = "resource_set_test_cell" @@ -488,7 +488,7 @@ resource "aws_route53recoveryreadiness_resource_set" "test" { `, rName, cwArn) } -func testAccResourceSetBasicDNSTargetResourceConfig(rName, domainName, hzArn, recordType, recordSetId string) string { +func testAccResourceSetConfig_basicDNSTarget(rName, domainName, hzArn, recordType, recordSetId string) string { return acctest.ConfigCompose(fmt.Sprintf(` resource "aws_route53recoveryreadiness_resource_set" "test" { resource_set_name = %[1]q @@ -506,7 +506,7 @@ resource "aws_route53recoveryreadiness_resource_set" "test" { `, rName, domainName, hzArn, recordType, recordSetId)) } -func testAccResourceSetDNSTargetResourceNlbTargetConfig(rName, hzArn string) string { +func testAccResourceSetConfig_dnsTargetNlbTarget(rName, hzArn string) string { return acctest.ConfigCompose(testAccResourceSetConfig_NLB(rName), fmt.Sprintf(` resource "aws_route53recoveryreadiness_resource_set" "test" { resource_set_name = %[1]q @@ -530,7 +530,7 @@ resource "aws_route53recoveryreadiness_resource_set" "test" { `, rName, hzArn)) } -func testAccResourceSetDNSTargetResourceR53TargetConfig(rName, hzArn, domainName, recordSetId string) string { +func testAccResourceSetConfig_dnsTargetR53Target(rName, hzArn, domainName, recordSetId string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_resource_set" "test" { resource_set_name = %[1]q @@ -555,7 +555,7 @@ resource "aws_route53recoveryreadiness_resource_set" "test" { `, rName, hzArn, domainName, recordSetId) } -func testAccResourceSetConfig_Timeout(rName, cwArn string) string { +func testAccResourceSetConfig_timeout(rName, cwArn string) string { return fmt.Sprintf(` resource "aws_route53recoveryreadiness_resource_set" "test" { resource_set_name = %[1]q diff --git a/internal/service/route53resolver/dnssec_config.go b/internal/service/route53resolver/dnssec_config.go index 18cc8c9fa05..952f1a0230d 100644 --- a/internal/service/route53resolver/dnssec_config.go +++ b/internal/service/route53resolver/dnssec_config.go @@ -127,7 +127,7 @@ func resourceDNSSECConfigDelete(d *schema.ResourceData, meta interface{}) error // (1) Update Route 53 ResolverDnssecConfig to "DISABLED" state, if necessary if aws.StringValue(config.ValidationStatus) == route53resolver.ResolverDNSSECValidationStatusEnabled { - config, err = updateResolverDnsSecConfigValidation(conn, aws.StringValue(config.ResourceId), route53resolver.ValidationDisable) + config, err = updateResolverDNSSECConfigValidation(conn, aws.StringValue(config.ResourceId), route53resolver.ValidationDisable) if err != nil { return fmt.Errorf("error deleting Route 53 Resolver DNSSEC config (%s): %w", d.Id(), err) } @@ -148,7 +148,7 @@ func resourceDNSSECConfigDelete(d *schema.ResourceData, meta interface{}) error } // (2) Update Route 53 ResolverDnssecConfig again, effectively deleting the resource - _, err = updateResolverDnsSecConfigValidation(conn, aws.StringValue(config.ResourceId), route53resolver.ValidationDisable) + _, err = updateResolverDNSSECConfigValidation(conn, aws.StringValue(config.ResourceId), route53resolver.ValidationDisable) if tfawserr.ErrCodeEquals(err, route53resolver.ErrCodeResourceNotFoundException) { return nil @@ -161,7 +161,7 @@ func resourceDNSSECConfigDelete(d *schema.ResourceData, meta interface{}) error return nil } -func updateResolverDnsSecConfigValidation(conn *route53resolver.Route53Resolver, resourceId, validation string) (*route53resolver.ResolverDnssecConfig, error) { +func updateResolverDNSSECConfigValidation(conn *route53resolver.Route53Resolver, resourceId, validation string) (*route53resolver.ResolverDnssecConfig, error) { output, err := conn.UpdateResolverDnssecConfig(&route53resolver.UpdateResolverDnssecConfigInput{ ResourceId: aws.String(resourceId), Validation: aws.String(validation), diff --git a/internal/service/route53resolver/endpoint_data_source_test.go b/internal/service/route53resolver/endpoint_data_source_test.go index 8305b3597bb..c004b02abd7 100644 --- a/internal/service/route53resolver/endpoint_data_source_test.go +++ b/internal/service/route53resolver/endpoint_data_source_test.go @@ -24,7 +24,7 @@ func TestAccRoute53ResolverEndpointDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEndpointDataSourceConfig_NonExistent, + Config: testAccEndpointDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile("The ID provided could not be found"), }, { @@ -53,7 +53,7 @@ func TestAccRoute53ResolverEndpointDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccEndpointDataSourceConfig_NonExistentFilter, + Config: testAccEndpointDataSourceConfig_nonExistentFilter, ExpectError: regexp.MustCompile("Your query returned no results. Please change your search criteria and try again"), }, { @@ -203,13 +203,13 @@ data "aws_route53_resolver_endpoint" "foo" { `, direction, name)) } -const testAccEndpointDataSourceConfig_NonExistent = ` +const testAccEndpointDataSourceConfig_nonExistent = ` data "aws_route53_resolver_endpoint" "foo" { resolver_endpoint_id = "rslvr-in-8g85830108dd4c82b" } ` -const testAccEndpointDataSourceConfig_NonExistentFilter = ` +const testAccEndpointDataSourceConfig_nonExistentFilter = ` data "aws_route53_resolver_endpoint" "foo" { filter { name = "Name" diff --git a/internal/service/route53resolver/rule_data_source_test.go b/internal/service/route53resolver/rule_data_source_test.go index 2c05a438565..ac9c280a64d 100644 --- a/internal/service/route53resolver/rule_data_source_test.go +++ b/internal/service/route53resolver/rule_data_source_test.go @@ -28,7 +28,7 @@ func TestAccRoute53ResolverRuleDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRuleDataSource_basic(rName), + Config: testAccRuleDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(ds1ResourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "arn", resourceName, "arn"), @@ -79,7 +79,7 @@ func TestAccRoute53ResolverRuleDataSource_resolverEndpointIdWithTags(t *testing. ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRuleDataSource_resolverEndpointIdWithTags(rName), + Config: testAccRuleDataSourceConfig_resolverEndpointIDTags(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(ds1ResourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "arn", resourceName, "arn"), @@ -116,7 +116,7 @@ func TestAccRoute53ResolverRuleDataSource_sharedByMe(t *testing.T) { ProviderFactories: acctest.FactoriesAlternate(&providers), Steps: []resource.TestStep{ { - Config: testAccRuleDataSource_sharedByMe(rName), + Config: testAccRuleDataSourceConfig_sharedByMe(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(ds1ResourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "arn", resourceName, "arn"), @@ -154,7 +154,7 @@ func TestAccRoute53ResolverRuleDataSource_sharedWithMe(t *testing.T) { ProviderFactories: acctest.FactoriesAlternate(&providers), Steps: []resource.TestStep{ { - Config: testAccRuleDataSource_sharedWithMe(rName), + Config: testAccRuleDataSourceConfig_sharedWithMe(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(ds1ResourceName, "id", resourceName, "id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "arn", resourceName, "arn"), @@ -174,7 +174,7 @@ func TestAccRoute53ResolverRuleDataSource_sharedWithMe(t *testing.T) { }) } -func testAccRuleDataSource_basic(rName string) string { +func testAccRuleDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_route53_resolver_rule" "example" { domain_name = "%[1]s.example.com" @@ -197,7 +197,7 @@ data "aws_route53_resolver_rule" "by_name_and_rule_type" { `, rName) } -func testAccRuleDataSource_resolverEndpointIdWithTags(rName string) string { +func testAccRuleDataSourceConfig_resolverEndpointIDTags(rName string) string { return testAccRuleConfig_resolverEndpoint(rName) + fmt.Sprintf(` resource "aws_route53_resolver_rule" "example" { domain_name = "%[1]s.example.com" @@ -222,7 +222,7 @@ data "aws_route53_resolver_rule" "by_resolver_endpoint_id" { `, rName) } -func testAccRuleDataSource_sharedByMe(rName string) string { +func testAccRuleDataSourceConfig_sharedByMe(rName string) string { return acctest.ConfigAlternateAccountProvider() + testAccRuleConfig_resolverEndpoint(rName) + fmt.Sprintf(` resource "aws_route53_resolver_rule" "example" { domain_name = "%[1]s.example.com" @@ -266,7 +266,7 @@ data "aws_route53_resolver_rule" "by_resolver_endpoint_id" { `, rName) } -func testAccRuleDataSource_sharedWithMe(rName string) string { +func testAccRuleDataSourceConfig_sharedWithMe(rName string) string { return acctest.ConfigAlternateAccountProvider() + testAccRuleConfig_resolverEndpoint(rName) + fmt.Sprintf(` resource "aws_route53_resolver_rule" "example" { domain_name = "%[1]s.example.com" diff --git a/internal/service/route53resolver/rules_data_source_test.go b/internal/service/route53resolver/rules_data_source_test.go index de37addc462..14d557cf355 100644 --- a/internal/service/route53resolver/rules_data_source_test.go +++ b/internal/service/route53resolver/rules_data_source_test.go @@ -20,7 +20,7 @@ func TestAccRoute53ResolverRulesDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRulesDataSource_basic, + Config: testAccRulesDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dsResourceName, "resolver_rule_ids.#", "1"), resource.TestCheckTypeSetElemAttr(dsResourceName, "resolver_rule_ids.*", "rslvr-autodefined-rr-internet-resolver"), @@ -43,7 +43,7 @@ func TestAccRoute53ResolverRulesDataSource_resolverEndpointID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRulesDataSource_resolverEndpointID(rName1, rName2), + Config: testAccRulesDataSourceConfig_resolverEndpointID(rName1, rName2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(ds1ResourceName, "resolver_rule_ids.#", "1"), resource.TestCheckResourceAttr(ds2ResourceName, "resolver_rule_ids.#", "1"), @@ -60,12 +60,12 @@ func TestAccRoute53ResolverRulesDataSource_nameRegex(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, route53resolver.EndpointsID), - Providers: acctest.Providers, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, route53resolver.EndpointsID), + ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRulesDataSource_nameRegex(rCount, rName), + Config: testAccRulesDataSourceConfig_nameRegex(rCount, rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dsResourceName, "resolver_rule_ids.#", strconv.Itoa(rCount)), ), @@ -78,12 +78,12 @@ func TestAccRoute53ResolverRulesDataSource_nonExistentNameRegex(t *testing.T) { dsResourceName := "data.aws_route53_resolver_rules.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, route53resolver.EndpointsID), - Providers: acctest.Providers, + PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, route53resolver.EndpointsID), + ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccRulesDataSource_nonExistentNameRegex, + Config: testAccRulesDataSourceConfig_nonExistentNameRegex, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dsResourceName, "resolver_rule_ids.#", "0"), ), @@ -92,7 +92,7 @@ func TestAccRoute53ResolverRulesDataSource_nonExistentNameRegex(t *testing.T) { }) } -const testAccRulesDataSource_basic = ` +const testAccRulesDataSourceConfig_basic = ` # The default Internet Resolver rule. data "aws_route53_resolver_rules" "test" { owner_id = "Route 53 Resolver" @@ -101,7 +101,7 @@ data "aws_route53_resolver_rules" "test" { } ` -func testAccRulesDataSource_resolverEndpointID(rName1, rName2 string) string { +func testAccRulesDataSourceConfig_resolverEndpointID(rName1, rName2 string) string { return testAccRuleConfig_resolverEndpoint(rName1) + fmt.Sprintf(` resource "aws_route53_resolver_rule" "forward" { domain_name = "%[1]s.example.com" @@ -140,7 +140,7 @@ data "aws_route53_resolver_rules" "by_invalid_owner_id" { `, rName1, rName2) } -func testAccRulesDataSource_nameRegex(rCount int, rName string) string { +func testAccRulesDataSourceConfig_nameRegex(rCount int, rName string) string { return fmt.Sprintf(` resource "aws_route53_resolver_rule" "test" { count = %[1]d @@ -157,7 +157,7 @@ data "aws_route53_resolver_rules" "test" { `, rCount, rName) } -const testAccRulesDataSource_nonExistentNameRegex = ` +const testAccRulesDataSourceConfig_nonExistentNameRegex = ` data "aws_route53_resolver_rules" "test" { name_regex = "dne-regex" } diff --git a/internal/service/route53resolver/status.go b/internal/service/route53resolver/status.go index b0ca9ee226c..aca47e390f2 100644 --- a/internal/service/route53resolver/status.go +++ b/internal/service/route53resolver/status.go @@ -14,8 +14,8 @@ const ( resolverQueryLogConfigStatusNotFound = "NotFound" resolverQueryLogConfigStatusUnknown = "Unknown" - resolverDnssecConfigStatusNotFound = "NotFound" - resolverDnssecConfigStatusUnknown = "Unknown" + dnssecConfigStatusNotFound = "NotFound" + dnssecConfigStatusUnknown = "Unknown" firewallDomainListStatusNotFound = "NotFound" firewallDomainListStatusUnknown = "Unknown" @@ -72,15 +72,15 @@ func StatusDNSSECConfig(conn *route53resolver.Route53Resolver, dnssecConfigID st dnssecConfig, err := FindResolverDNSSECConfigByID(conn, dnssecConfigID) if tfawserr.ErrCodeEquals(err, route53resolver.ErrCodeResourceNotFoundException) { - return nil, resolverDnssecConfigStatusNotFound, nil + return nil, dnssecConfigStatusNotFound, nil } if err != nil { - return nil, resolverDnssecConfigStatusUnknown, err + return nil, dnssecConfigStatusUnknown, err } if dnssecConfig == nil { - return nil, resolverDnssecConfigStatusNotFound, nil + return nil, dnssecConfigStatusNotFound, nil } return dnssecConfig, aws.StringValue(dnssecConfig.ValidationStatus), nil diff --git a/internal/service/route53resolver/sweep.go b/internal/service/route53resolver/sweep.go index 9bb91cc7198..82146f27045 100644 --- a/internal/service/route53resolver/sweep.go +++ b/internal/service/route53resolver/sweep.go @@ -32,10 +32,7 @@ func init() { resource.AddTestSweepers("aws_route53_resolver_firewall_config", &resource.Sweeper{ Name: "aws_route53_resolver_firewall_config", - F: sweepFirewallsConfig, - Dependencies: []string{ - "aws_route53_resolver_firewall_config_association", - }, + F: sweepFirewallConfig, }) resource.AddTestSweepers("aws_route53_resolver_firewall_domain_list", &resource.Sweeper{ @@ -198,7 +195,7 @@ func sweepEndpoints(region string) error { return errors } -func sweepFirewallsConfig(region string) error { +func sweepFirewallConfig(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { return fmt.Errorf("error getting client: %s", err) @@ -211,13 +208,14 @@ func sweepFirewallsConfig(region string) error { return !lastPage } - for _, firewallRuleGroup := range page.FirewallConfigs { - id := aws.StringValue(firewallRuleGroup.Id) + for _, firewallConfig := range page.FirewallConfigs { + id := aws.StringValue(firewallConfig.Id) log.Printf("[INFO] Deleting Route53 Resolver DNS Firewall config: %s", id) r := ResourceFirewallConfig() d := r.Data(nil) d.SetId(id) + d.Set("resource_id", firewallConfig.ResourceId) err := r.Delete(d, client) if err != nil { diff --git a/internal/service/rum/README.md b/internal/service/rum/README.md new file mode 100644 index 00000000000..26370ec8bc4 --- /dev/null +++ b/internal/service/rum/README.md @@ -0,0 +1,11 @@ +# Terraform AWS Provider CloudWatch RUM Package + +This area is primarily for AWS provider contributors and maintainers. For information on _using_ Terraform and the AWS provider, see the links below. + + +## Handy Links + +* [Find out about contributing](../../../docs/contributing) to the AWS provider! +* AWS Provider Docs: [Home](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) +* AWS Provider Docs: [One of the CloudWatch RUM resources](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatchrum_app_monitor) +* AWS Docs: [AWS SDK for Go CloudWatch RUM](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchrum/) diff --git a/internal/service/rum/app_monitor.go b/internal/service/rum/app_monitor.go new file mode 100644 index 00000000000..8518c9b58b1 --- /dev/null +++ b/internal/service/rum/app_monitor.go @@ -0,0 +1,346 @@ +package rum + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" + "github.com/aws/aws-sdk-go/service/cloudwatchrum" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) + +func ResourceAppMonitor() *schema.Resource { + return &schema.Resource{ + Create: resourceAppMonitorCreate, + Read: resourceAppMonitorRead, + Update: resourceAppMonitorUpdate, + Delete: resourceAppMonitorDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "app_monitor_configuration": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "allow_cookies": { + Type: schema.TypeBool, + Optional: true, + }, + "enable_xray": { + Type: schema.TypeBool, + Optional: true, + }, + "excluded_pages": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 50, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "favorite_pages": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 50, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "guest_role_arn": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: verify.ValidARN, + }, + "identity_pool_id": { + Type: schema.TypeString, + Optional: true, + }, + "included_pages": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 50, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "session_sample_rate": { + Type: schema.TypeFloat, + Optional: true, + Default: 0.1, + ValidateFunc: validation.FloatBetween(0, 1), + }, + "telemetries": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice(cloudwatchrum.Telemetry_Values(), false), + }, + }, + }, + }, + }, + "cw_log_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "cw_log_group": { + Type: schema.TypeString, + Computed: true, + }, + "domain": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 253), + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 255), + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + }, + CustomizeDiff: verify.SetTagsDiff, + } +} + +func resourceAppMonitorCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RUMConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + name := d.Get("name").(string) + input := &cloudwatchrum.CreateAppMonitorInput{ + Name: aws.String(name), + CwLogEnabled: aws.Bool(d.Get("cw_log_enabled").(bool)), + Domain: aws.String(d.Get("domain").(string)), + } + + if v, ok := d.GetOk("app_monitor_configuration"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + input.AppMonitorConfiguration = expandAppMonitorConfiguration(v.([]interface{})[0].(map[string]interface{})) + } + + if len(tags) > 0 { + input.Tags = Tags(tags.IgnoreAWS()) + } + + _, err := conn.CreateAppMonitor(input) + + if err != nil { + return fmt.Errorf("error creating CloudWatch RUM App Monitor %s: %w", name, err) + } + + d.SetId(name) + + return resourceAppMonitorRead(d, meta) +} + +func resourceAppMonitorRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RUMConn + defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + appMon, err := FindAppMonitorByName(conn, d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Unable to find CloudWatch RUM App Monitor (%s); removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error reading CloudWatch RUM App Monitor (%s): %w", d.Id(), err) + } + + arn := arn.ARN{ + AccountID: meta.(*conns.AWSClient).AccountID, + Partition: meta.(*conns.AWSClient).Partition, + Region: meta.(*conns.AWSClient).Region, + Resource: fmt.Sprintf("appmonitor/%s", aws.StringValue(appMon.Name)), + Service: "rum", + }.String() + + d.Set("name", appMon.Name) + d.Set("arn", arn) + d.Set("domain", appMon.Domain) + + d.Set("cw_log_enabled", appMon.DataStorage.CwLog.CwLogEnabled) + d.Set("cw_log_group", appMon.DataStorage.CwLog.CwLogGroup) + + if err := d.Set("app_monitor_configuration", []interface{}{flattenAppMonitorConfiguration(appMon.AppMonitorConfiguration)}); err != nil { + return fmt.Errorf("error setting app_monitor_configuration for CloudWatch RUM App Monitor (%s): %w", d.Id(), err) + } + + tags := KeyValueTags(appMon.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + + //lintignore:AWSR002 + if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %w", err) + } + + if err := d.Set("tags_all", tags.Map()); err != nil { + return fmt.Errorf("error setting tags_all: %w", err) + } + + return nil +} + +func resourceAppMonitorUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RUMConn + + if d.HasChangesExcept("tags", "tags_all") { + input := &cloudwatchrum.UpdateAppMonitorInput{ + Name: aws.String(d.Id()), + } + + if d.HasChange("cw_log_enabled") { + input.CwLogEnabled = aws.Bool(d.Get("cw_log_enabled").(bool)) + } + + if d.HasChange("app_monitor_configuration") { + input.AppMonitorConfiguration = expandAppMonitorConfiguration(d.Get("app_monitor_configuration").([]interface{})[0].(map[string]interface{})) + } + + if d.HasChange("domain") { + input.Domain = aws.String(d.Get("domain").(string)) + } + + log.Printf("[DEBUG] cloudwatchrum AppMonitor update config: %s", input.String()) + _, err := conn.UpdateAppMonitor(input) + if err != nil { + return fmt.Errorf("error updating CloudWatch RUM App Monitor: %w", err) + } + } + + if d.HasChange("tags_all") { + o, n := d.GetChange("tags_all") + + if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating CloudWatch RUM App Monitor (%s) tags: %w", d.Id(), err) + } + } + + return resourceAppMonitorRead(d, meta) +} + +func resourceAppMonitorDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).RUMConn + + input := &cloudwatchrum.DeleteAppMonitorInput{ + Name: aws.String(d.Id()), + } + + if _, err := conn.DeleteAppMonitor(input); err != nil { + if tfawserr.ErrCodeEquals(err, cloudwatchrum.ErrCodeResourceNotFoundException) { + return nil + } + return fmt.Errorf("error deleting CloudWatch RUM App Monitor (%s): %w", d.Id(), err) + } + + return nil +} + +func expandAppMonitorConfiguration(tfMap map[string]interface{}) *cloudwatchrum.AppMonitorConfiguration { + if tfMap == nil { + return nil + } + + config := &cloudwatchrum.AppMonitorConfiguration{} + + if v, ok := tfMap["guest_role_arn"].(string); ok && v != "" { + config.GuestRoleArn = aws.String(v) + } + + if v, ok := tfMap["identity_pool_id"].(string); ok && v != "" { + config.IdentityPoolId = aws.String(v) + } + + if v, ok := tfMap["session_sample_rate"].(float64); ok { + config.SessionSampleRate = aws.Float64(v) + } + + if v, ok := tfMap["allow_cookies"].(bool); ok { + config.AllowCookies = aws.Bool(v) + } + + if v, ok := tfMap["enable_xray"].(bool); ok { + config.EnableXRay = aws.Bool(v) + } + + if v, ok := tfMap["excluded_pages"].(*schema.Set); ok && v.Len() > 0 { + config.ExcludedPages = flex.ExpandStringSet(v) + } + + if v, ok := tfMap["favorite_pages"].(*schema.Set); ok && v.Len() > 0 { + config.FavoritePages = flex.ExpandStringSet(v) + } + + if v, ok := tfMap["included_pages"].(*schema.Set); ok && v.Len() > 0 { + config.IncludedPages = flex.ExpandStringSet(v) + } + + if v, ok := tfMap["telemetries"].(*schema.Set); ok && v.Len() > 0 { + config.Telemetries = flex.ExpandStringSet(v) + } + + return config +} + +func flattenAppMonitorConfiguration(apiObject *cloudwatchrum.AppMonitorConfiguration) map[string]interface{} { + if apiObject == nil { + return nil + } + + tfMap := map[string]interface{}{} + + if v := apiObject.GuestRoleArn; v != nil { + tfMap["guest_role_arn"] = aws.StringValue(v) + } + + if v := apiObject.IdentityPoolId; v != nil { + tfMap["identity_pool_id"] = aws.StringValue(v) + } + + if v := apiObject.SessionSampleRate; v != nil { + tfMap["session_sample_rate"] = aws.Float64Value(v) + } + + if v := apiObject.AllowCookies; v != nil { + tfMap["allow_cookies"] = aws.BoolValue(v) + } + + if v := apiObject.EnableXRay; v != nil { + tfMap["enable_xray"] = aws.BoolValue(v) + } + + if v := apiObject.Telemetries; v != nil { + tfMap["telemetries"] = flex.FlattenStringSet(v) + } + + if v := apiObject.IncludedPages; v != nil { + tfMap["included_pages"] = flex.FlattenStringSet(v) + } + + if v := apiObject.FavoritePages; v != nil { + tfMap["favorite_pages"] = flex.FlattenStringSet(v) + } + + if v := apiObject.ExcludedPages; v != nil { + tfMap["excluded_pages"] = flex.FlattenStringSet(v) + } + + return tfMap +} diff --git a/internal/service/rum/app_monitor_test.go b/internal/service/rum/app_monitor_test.go new file mode 100644 index 00000000000..af84d7277b9 --- /dev/null +++ b/internal/service/rum/app_monitor_test.go @@ -0,0 +1,226 @@ +package rum_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/cloudwatchrum" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfcloudwatchrum "github.com/hashicorp/terraform-provider-aws/internal/service/rum" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func TestAccRUMAppMonitor_basic(t *testing.T) { + var appMon cloudwatchrum.AppMonitor + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_rum_app_monitor.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, cloudwatchrum.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAppMonitorDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAppMonitorConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAppMonitorExists(resourceName, &appMon), + resource.TestCheckResourceAttr(resourceName, "name", rName), + acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "rum", fmt.Sprintf("appmonitor/%s", rName)), + resource.TestCheckResourceAttr(resourceName, "domain", "localhost"), + resource.TestCheckResourceAttr(resourceName, "cw_log_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "app_monitor_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "app_monitor_configuration.0.session_sample_rate", "0.1"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAppMonitorConfig_updated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAppMonitorExists(resourceName, &appMon), + resource.TestCheckResourceAttr(resourceName, "name", rName), + acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "rum", fmt.Sprintf("appmonitor/%s", rName)), + resource.TestCheckResourceAttr(resourceName, "domain", "localhost"), + resource.TestCheckResourceAttr(resourceName, "cw_log_enabled", "true"), + resource.TestCheckResourceAttrSet(resourceName, "cw_log_group"), + resource.TestCheckResourceAttr(resourceName, "app_monitor_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "app_monitor_configuration.0.session_sample_rate", "0.1"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + }, + }) +} + +func TestAccRUMAppMonitor_tags(t *testing.T) { + var appMon cloudwatchrum.AppMonitor + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_rum_app_monitor.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, cloudwatchrum.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAppMonitorDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAppMonitorConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAppMonitorExists(resourceName, &appMon), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAppMonitorConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAppMonitorExists(resourceName, &appMon), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccAppMonitorConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAppMonitorExists(resourceName, &appMon), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func TestAccRUMAppMonitor_disappears(t *testing.T) { + var appMon cloudwatchrum.AppMonitor + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_rum_app_monitor.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, cloudwatchrum.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckAppMonitorDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAppMonitorConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAppMonitorExists(resourceName, &appMon), + acctest.CheckResourceDisappears(acctest.Provider, tfcloudwatchrum.ResourceAppMonitor(), resourceName), + acctest.CheckResourceDisappears(acctest.Provider, tfcloudwatchrum.ResourceAppMonitor(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckAppMonitorDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).RUMConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_rum_app_monitor" { + continue + } + + appMon, err := tfcloudwatchrum.FindAppMonitorByName(conn, rs.Primary.ID) + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + if aws.StringValue(appMon.Name) == rs.Primary.ID { + return fmt.Errorf("cloudwatchrum App Monitor %q still exists", rs.Primary.ID) + } + } + + return nil +} + +func testAccCheckAppMonitorExists(n string, appMon *cloudwatchrum.AppMonitor) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No cloudwatchrum App Monitor ID is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).RUMConn + resp, err := tfcloudwatchrum.FindAppMonitorByName(conn, rs.Primary.ID) + if err != nil { + return err + } + + *appMon = *resp + + return nil + } +} + +func testAccAppMonitorConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_rum_app_monitor" "test" { + name = %[1]q + domain = "localhost" +} +`, rName) +} + +func testAccAppMonitorConfig_updated(rName string) string { + return fmt.Sprintf(` +resource "aws_rum_app_monitor" "test" { + name = %[1]q + domain = "localhost" + cw_log_enabled = true +} +`, rName) +} + +func testAccAppMonitorConfig_tags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_rum_app_monitor" "test" { + name = %[1]q + domain = "localhost" + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccAppMonitorConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_rum_app_monitor" "test" { + name = %[1]q + domain = "localhost" + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/internal/service/rum/find.go b/internal/service/rum/find.go new file mode 100644 index 00000000000..a05f912f4da --- /dev/null +++ b/internal/service/rum/find.go @@ -0,0 +1,34 @@ +package rum + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/cloudwatchrum" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" +) + +func FindAppMonitorByName(conn *cloudwatchrum.CloudWatchRUM, name string) (*cloudwatchrum.AppMonitor, error) { + input := cloudwatchrum.GetAppMonitorInput{ + Name: aws.String(name), + } + + output, err := conn.GetAppMonitor(&input) + + if tfawserr.ErrCodeEquals(err, cloudwatchrum.ErrCodeResourceNotFoundException) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || output.AppMonitor == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.AppMonitor, nil +} diff --git a/internal/service/rum/generate.go b/internal/service/rum/generate.go new file mode 100644 index 00000000000..e399d2928af --- /dev/null +++ b/internal/service/rum/generate.go @@ -0,0 +1,4 @@ +//go:generate go run ../../generate/tags/main.go -ServiceTagsMap -UpdateTags +// ONLY generate directives and package declaration! Do not add anything else to this file. + +package rum diff --git a/internal/service/rum/sweep.go b/internal/service/rum/sweep.go new file mode 100644 index 00000000000..5c35da8ddba --- /dev/null +++ b/internal/service/rum/sweep.go @@ -0,0 +1,68 @@ +//go:build sweep +// +build sweep + +package rum + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/cloudwatchrum" + "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" +) + +func init() { + resource.AddTestSweepers("aws_rum_app_monitor", &resource.Sweeper{ + Name: "aws_rum_app_monitor", + F: sweepAppMonitors, + }) +} + +func sweepAppMonitors(region string) error { + client, err := sweep.SharedRegionalSweepClient(region) + + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + + conn := client.(*conns.AWSClient).RUMConn + sweepResources := make([]*sweep.SweepResource, 0) + var errs *multierror.Error + + err = conn.ListAppMonitorsPages(&cloudwatchrum.ListAppMonitorsInput{}, func(resp *cloudwatchrum.ListAppMonitorsOutput, lastPage bool) bool { + if len(resp.AppMonitorSummaries) == 0 { + log.Print("[DEBUG] No RUM App Monitors to sweep") + return !lastPage + } + + for _, c := range resp.AppMonitorSummaries { + r := ResourceAppMonitor() + d := r.Data(nil) + d.SetId(aws.StringValue(c.Name)) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + + return !lastPage + }) + + if err != nil { + errs = multierror.Append(errs, fmt.Errorf("error describing RUM App Monitors: %w", err)) + // in case work can be done, don't jump out yet + } + + if err = sweep.SweepOrchestrator(sweepResources); err != nil { + errs = multierror.Append(errs, fmt.Errorf("error sweeping RUM App Monitors for %s: %w", region, err)) + } + + if sweep.SkipSweepError(errs.ErrorOrNil()) { + log.Printf("[WARN] Skipping RUM App Monitor sweep for %s: %s", region, err) + return nil + } + + return errs.ErrorOrNil() +} diff --git a/internal/service/rum/tags_gen.go b/internal/service/rum/tags_gen.go new file mode 100644 index 00000000000..23ce02fe646 --- /dev/null +++ b/internal/service/rum/tags_gen.go @@ -0,0 +1,58 @@ +// Code generated by internal/generate/tags/main.go; DO NOT EDIT. +package rum + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/cloudwatchrum" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" +) + +// map[string]*string handling + +// Tags returns rum service tags. +func Tags(tags tftags.KeyValueTags) map[string]*string { + return aws.StringMap(tags.Map()) +} + +// KeyValueTags creates KeyValueTags from rum service tags. +func KeyValueTags(tags map[string]*string) tftags.KeyValueTags { + return tftags.New(tags) +} + +// UpdateTags updates rum service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func UpdateTags(conn *cloudwatchrum.CloudWatchRUM, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error { + oldTags := tftags.New(oldTagsMap) + newTags := tftags.New(newTagsMap) + + if removedTags := oldTags.Removed(newTags); len(removedTags) > 0 { + input := &cloudwatchrum.UntagResourceInput{ + ResourceArn: aws.String(identifier), + TagKeys: aws.StringSlice(removedTags.IgnoreAWS().Keys()), + } + + _, err := conn.UntagResource(input) + + if err != nil { + return fmt.Errorf("error untagging resource (%s): %w", identifier, err) + } + } + + if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 { + input := &cloudwatchrum.TagResourceInput{ + ResourceArn: aws.String(identifier), + Tags: Tags(updatedTags.IgnoreAWS()), + } + + _, err := conn.TagResource(input) + + if err != nil { + return fmt.Errorf("error tagging resource (%s): %w", identifier, err) + } + } + + return nil +} diff --git a/internal/service/s3/bucket.go b/internal/service/s3/bucket.go index a067ce43373..048418def7e 100644 --- a/internal/service/s3/bucket.go +++ b/internal/service/s3/bucket.go @@ -1006,7 +1006,7 @@ func resourceBucketRead(d *schema.ResourceData, meta interface{}) error { return nil } - if err != nil && !tfawserr.ErrCodeEquals(err, ErrCodeNoSuchCORSConfiguration) { + if err != nil && !tfawserr.ErrCodeEquals(err, ErrCodeNoSuchCORSConfiguration, ErrCodeNotImplemented, ErrCodeXNotImplemented) { return fmt.Errorf("error getting S3 Bucket CORS configuration: %s", err) } diff --git a/internal/service/s3/bucket_accelerate_configuration_test.go b/internal/service/s3/bucket_accelerate_configuration_test.go index 34402ec75dd..bbae7bbe044 100644 --- a/internal/service/s3/bucket_accelerate_configuration_test.go +++ b/internal/service/s3/bucket_accelerate_configuration_test.go @@ -30,7 +30,7 @@ func TestAccS3BucketAccelerateConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckBucketAccelerateConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAccelerateConfigurationBasicConfig(bucketName, s3.BucketAccelerateStatusEnabled), + Config: testAccBucketAccelerateConfigurationConfig_basic(bucketName, s3.BucketAccelerateStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAccelerateConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -60,7 +60,7 @@ func TestAccS3BucketAccelerateConfiguration_update(t *testing.T) { CheckDestroy: testAccCheckBucketAccelerateConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAccelerateConfigurationBasicConfig(bucketName, s3.BucketAccelerateStatusEnabled), + Config: testAccBucketAccelerateConfigurationConfig_basic(bucketName, s3.BucketAccelerateStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAccelerateConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -68,7 +68,7 @@ func TestAccS3BucketAccelerateConfiguration_update(t *testing.T) { ), }, { - Config: testAccBucketAccelerateConfigurationBasicConfig(bucketName, s3.BucketAccelerateStatusSuspended), + Config: testAccBucketAccelerateConfigurationConfig_basic(bucketName, s3.BucketAccelerateStatusSuspended), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAccelerateConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -98,7 +98,7 @@ func TestAccS3BucketAccelerateConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketAccelerateConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAccelerateConfigurationBasicConfig(bucketName, s3.BucketAccelerateStatusEnabled), + Config: testAccBucketAccelerateConfigurationConfig_basic(bucketName, s3.BucketAccelerateStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAccelerateConfigurationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketAccelerateConfiguration(), resourceName), @@ -121,14 +121,14 @@ func TestAccS3BucketAccelerateConfiguration_migrate_noChange(t *testing.T) { CheckDestroy: testAccCheckBucketAccelerateConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withAcceleration(rName, s3.BucketAccelerateStatusEnabled), + Config: testAccBucketConfig_acceleration(rName, s3.BucketAccelerateStatusEnabled), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "acceleration_status", s3.BucketAccelerateStatusEnabled), ), }, { - Config: testAccBucketAccelerateConfigurationBasicConfig(rName, s3.BucketAccelerateStatusEnabled), + Config: testAccBucketAccelerateConfigurationConfig_basic(rName, s3.BucketAccelerateStatusEnabled), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketAccelerateConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "id"), @@ -151,14 +151,14 @@ func TestAccS3BucketAccelerateConfiguration_migrate_withChange(t *testing.T) { CheckDestroy: testAccCheckBucketAccelerateConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withAcceleration(rName, s3.BucketAccelerateStatusEnabled), + Config: testAccBucketConfig_acceleration(rName, s3.BucketAccelerateStatusEnabled), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "acceleration_status", s3.BucketAccelerateStatusEnabled), ), }, { - Config: testAccBucketAccelerateConfigurationBasicConfig(rName, s3.BucketAccelerateStatusSuspended), + Config: testAccBucketAccelerateConfigurationConfig_basic(rName, s3.BucketAccelerateStatusSuspended), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketAccelerateConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "id"), @@ -248,7 +248,7 @@ func testAccCheckBucketAccelerateConfigurationExists(resourceName string) resour } } -func testAccBucketAccelerateConfigurationBasicConfig(bucketName, status string) string { +func testAccBucketAccelerateConfigurationConfig_basic(bucketName, status string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_acl_test.go b/internal/service/s3/bucket_acl_test.go index ace31b7f59b..d704ecd8fa9 100644 --- a/internal/service/s3/bucket_acl_test.go +++ b/internal/service/s3/bucket_acl_test.go @@ -315,14 +315,14 @@ func TestAccS3BucketACL_migrate_aclNoChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withACL(bucketName, s3.BucketCannedACLPublicRead), + Config: testAccBucketConfig_acl(bucketName, s3.BucketCannedACLPublicRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "acl", s3.BucketCannedACLPublicRead), ), }, { - Config: testAccBucketACLConfig_Migrate_acl(bucketName, s3.BucketCannedACLPublicRead), + Config: testAccBucketACLConfig_migrate(bucketName, s3.BucketCannedACLPublicRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acl", s3.BucketCannedACLPublicRead), @@ -344,14 +344,14 @@ func TestAccS3BucketACL_migrate_aclWithChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withACL(bucketName, s3.BucketCannedACLPublicRead), + Config: testAccBucketConfig_acl(bucketName, s3.BucketCannedACLPublicRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "acl", s3.BucketCannedACLPublicRead), ), }, { - Config: testAccBucketACLConfig_Migrate_acl(bucketName, s3.BucketCannedACLPrivate), + Config: testAccBucketACLConfig_migrate(bucketName, s3.BucketCannedACLPrivate), Check: resource.ComposeTestCheckFunc( testAccCheckBucketACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acl", s3.BucketCannedACLPrivate), @@ -373,7 +373,7 @@ func TestAccS3BucketACL_migrate_grantsNoChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withGrants(bucketName), + Config: testAccBucketConfig_aclGrants(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "grant.#", "1"), @@ -386,7 +386,7 @@ func TestAccS3BucketACL_migrate_grantsNoChange(t *testing.T) { ), }, { - Config: testAccBucketACLConfig_Migrate_grantsNoChange(bucketName), + Config: testAccBucketACLConfig_migrateGrantsNoChange(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "access_control_policy.#", "1"), @@ -422,14 +422,14 @@ func TestAccS3BucketACL_migrate_grantsWithChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withACL(bucketName, s3.BucketCannedACLPublicRead), + Config: testAccBucketConfig_acl(bucketName, s3.BucketCannedACLPublicRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "acl", s3.BucketCannedACLPublicRead), ), }, { - Config: testAccBucketACLConfig_Migrate_grantsChange(bucketName), + Config: testAccBucketACLConfig_migrateGrantsChange(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketACLExists(resourceName), resource.TestCheckResourceAttr(resourceName, "access_control_policy.#", "1"), @@ -753,7 +753,7 @@ resource "aws_s3_bucket_acl" "test" { `, bucketName) } -func testAccBucketACLConfig_Migrate_acl(rName, acl string) string { +func testAccBucketACLConfig_migrate(rName, acl string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -766,7 +766,7 @@ resource "aws_s3_bucket_acl" "test" { `, rName, acl) } -func testAccBucketACLConfig_Migrate_grantsNoChange(rName string) string { +func testAccBucketACLConfig_migrateGrantsNoChange(rName string) string { return fmt.Sprintf(` data "aws_canonical_user_id" "current" {} @@ -801,7 +801,7 @@ resource "aws_s3_bucket_acl" "test" { `, rName) } -func testAccBucketACLConfig_Migrate_grantsChange(rName string) string { +func testAccBucketACLConfig_migrateGrantsChange(rName string) string { return fmt.Sprintf(` data "aws_canonical_user_id" "current" {} diff --git a/internal/service/s3/bucket_analytics_configuration_test.go b/internal/service/s3/bucket_analytics_configuration_test.go index 0c5f0459b6f..c6cf6931731 100644 --- a/internal/service/s3/bucket_analytics_configuration_test.go +++ b/internal/service/s3/bucket_analytics_configuration_test.go @@ -30,7 +30,7 @@ func TestAccS3BucketAnalyticsConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfiguration(rName, rName), + Config: testAccBucketAnalyticsConfigurationConfig_basic(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -60,13 +60,13 @@ func TestAccS3BucketAnalyticsConfiguration_removed(t *testing.T) { CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfiguration(rName, rName), + Config: testAccBucketAnalyticsConfigurationConfig_basic(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), ), }, { - Config: testAccBucketAnalyticsConfiguration_removed(rName), + Config: testAccBucketAnalyticsConfigurationConfig_removed(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationRemoved(rName, rName), ), @@ -90,7 +90,7 @@ func TestAccS3BucketAnalyticsConfiguration_updateBasic(t *testing.T) { CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfiguration(originalACName, originalBucketName), + Config: testAccBucketAnalyticsConfigurationConfig_basic(originalACName, originalBucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "name", originalACName), @@ -100,7 +100,7 @@ func TestAccS3BucketAnalyticsConfiguration_updateBasic(t *testing.T) { ), }, { - Config: testAccBucketAnalyticsConfiguration(updatedACName, originalBucketName), + Config: testAccBucketAnalyticsConfigurationConfig_basic(updatedACName, originalBucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), testAccCheckBucketAnalyticsConfigurationRemoved(originalACName, originalBucketName), @@ -111,7 +111,7 @@ func TestAccS3BucketAnalyticsConfiguration_updateBasic(t *testing.T) { ), }, { - Config: testAccBucketAnalyticsConfigurationUpdateBucket(updatedACName, originalBucketName, updatedBucketName), + Config: testAccBucketAnalyticsConfigurationConfig_update(updatedACName, originalBucketName, updatedBucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), testAccCheckBucketAnalyticsConfigurationRemoved(updatedACName, originalBucketName), @@ -140,7 +140,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_empty(t *testing.T) { CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfigurationWithEmptyFilter(rName, rName), + Config: testAccBucketAnalyticsConfigurationConfig_emptyFilter(rName, rName), ExpectError: regexp.MustCompile(`one of .* must be specified`), }, }, @@ -163,7 +163,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_prefix(t *testing.T) { CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfigurationWithFilterPrefix(rName, rName, prefix), + Config: testAccBucketAnalyticsConfigurationConfig_filterPrefix(rName, rName, prefix), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -172,7 +172,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_prefix(t *testing.T) { ), }, { - Config: testAccBucketAnalyticsConfigurationWithFilterPrefix(rName, rName, prefixUpdate), + Config: testAccBucketAnalyticsConfigurationConfig_filterPrefix(rName, rName, prefixUpdate), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -205,7 +205,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_singleTag(t *testing.T) { CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfigurationWithFilterSingleTag(rName, rName, tag1), + Config: testAccBucketAnalyticsConfigurationConfig_filterSingleTag(rName, rName, tag1), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -215,7 +215,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_singleTag(t *testing.T) { ), }, { - Config: testAccBucketAnalyticsConfigurationWithFilterSingleTag(rName, rName, tag1Update), + Config: testAccBucketAnalyticsConfigurationConfig_filterSingleTag(rName, rName, tag1Update), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -251,7 +251,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_multipleTags(t *testing.T) CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfigurationWithFilterMultipleTags(rName, rName, tag1, tag2), + Config: testAccBucketAnalyticsConfigurationConfig_filterMultipleTags(rName, rName, tag1, tag2), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -262,7 +262,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_multipleTags(t *testing.T) ), }, { - Config: testAccBucketAnalyticsConfigurationWithFilterMultipleTags(rName, rName, tag1Update, tag2Update), + Config: testAccBucketAnalyticsConfigurationConfig_filterMultipleTags(rName, rName, tag1Update, tag2Update), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -301,7 +301,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_prefixAndTags(t *testing.T CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfigurationWithFilterPrefixAndTags(rName, rName, prefix, tag1, tag2), + Config: testAccBucketAnalyticsConfigurationConfig_filterPrefixAndTags(rName, rName, prefix, tag1, tag2), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -312,7 +312,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_prefixAndTags(t *testing.T ), }, { - Config: testAccBucketAnalyticsConfigurationWithFilterPrefixAndTags(rName, rName, prefixUpdate, tag1Update, tag2Update), + Config: testAccBucketAnalyticsConfigurationConfig_filterPrefixAndTags(rName, rName, prefixUpdate, tag1Update, tag2Update), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -346,13 +346,13 @@ func TestAccS3BucketAnalyticsConfiguration_WithFilter_remove(t *testing.T) { CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfigurationWithFilterPrefix(rName, rName, prefix), + Config: testAccBucketAnalyticsConfigurationConfig_filterPrefix(rName, rName, prefix), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), ), }, { - Config: testAccBucketAnalyticsConfiguration(rName, rName), + Config: testAccBucketAnalyticsConfigurationConfig_basic(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "filter.#", "0"), @@ -377,7 +377,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithStorageClassAnalysis_empty(t *tes CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfigurationWithEmptyStorageClassAnalysis(rName, rName), + Config: testAccBucketAnalyticsConfigurationConfig_emptyStorageClassAnalysis(rName, rName), ExpectError: regexp.MustCompile(`running pre-apply refresh`), }, }, @@ -397,7 +397,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithStorageClassAnalysis_default(t *t CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfigurationWithDefaultStorageClassAnalysis(rName, rName), + Config: testAccBucketAnalyticsConfigurationConfig_defaultStorageClassAnalysis(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "storage_class_analysis.#", "1"), @@ -433,7 +433,7 @@ func TestAccS3BucketAnalyticsConfiguration_WithStorageClassAnalysis_full(t *test CheckDestroy: testAccCheckBucketAnalyticsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketAnalyticsConfigurationWithFullStorageClassAnalysis(rName, rName, prefix), + Config: testAccBucketAnalyticsConfigurationConfig_fullStorageClassAnalysis(rName, rName, prefix), Check: resource.ComposeTestCheckFunc( testAccCheckBucketAnalyticsConfigurationExists(resourceName, &ac), resource.TestCheckResourceAttr(resourceName, "storage_class_analysis.#", "1"), @@ -508,7 +508,7 @@ func testAccCheckBucketAnalyticsConfigurationRemoved(name, bucket string) resour } } -func testAccBucketAnalyticsConfiguration(name, bucket string) string { +func testAccBucketAnalyticsConfigurationConfig_basic(name, bucket string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -521,7 +521,7 @@ resource "aws_s3_bucket" "test" { `, name, bucket) } -func testAccBucketAnalyticsConfiguration_removed(bucket string) string { +func testAccBucketAnalyticsConfigurationConfig_removed(bucket string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = "%s" @@ -529,7 +529,7 @@ resource "aws_s3_bucket" "test" { `, bucket) } -func testAccBucketAnalyticsConfigurationUpdateBucket(name, originalBucket, updatedBucket string) string { +func testAccBucketAnalyticsConfigurationConfig_update(name, originalBucket, updatedBucket string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test_2.bucket @@ -546,7 +546,7 @@ resource "aws_s3_bucket" "test_2" { `, name, originalBucket, updatedBucket) } -func testAccBucketAnalyticsConfigurationWithEmptyFilter(name, bucket string) string { +func testAccBucketAnalyticsConfigurationConfig_emptyFilter(name, bucket string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -562,7 +562,7 @@ resource "aws_s3_bucket" "test" { `, name, bucket) } -func testAccBucketAnalyticsConfigurationWithFilterPrefix(name, bucket, prefix string) string { +func testAccBucketAnalyticsConfigurationConfig_filterPrefix(name, bucket, prefix string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -579,7 +579,7 @@ resource "aws_s3_bucket" "test" { `, name, prefix, bucket) } -func testAccBucketAnalyticsConfigurationWithFilterSingleTag(name, bucket, tag string) string { +func testAccBucketAnalyticsConfigurationConfig_filterSingleTag(name, bucket, tag string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -598,7 +598,7 @@ resource "aws_s3_bucket" "test" { `, name, tag, bucket) } -func testAccBucketAnalyticsConfigurationWithFilterMultipleTags(name, bucket, tag1, tag2 string) string { +func testAccBucketAnalyticsConfigurationConfig_filterMultipleTags(name, bucket, tag1, tag2 string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -618,7 +618,7 @@ resource "aws_s3_bucket" "test" { `, name, tag1, tag2, bucket) } -func testAccBucketAnalyticsConfigurationWithFilterPrefixAndTags(name, bucket, prefix, tag1, tag2 string) string { +func testAccBucketAnalyticsConfigurationConfig_filterPrefixAndTags(name, bucket, prefix, tag1, tag2 string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -640,7 +640,7 @@ resource "aws_s3_bucket" "test" { `, name, prefix, tag1, tag2, bucket) } -func testAccBucketAnalyticsConfigurationWithEmptyStorageClassAnalysis(name, bucket string) string { +func testAccBucketAnalyticsConfigurationConfig_emptyStorageClassAnalysis(name, bucket string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -656,7 +656,7 @@ resource "aws_s3_bucket" "test" { `, name, bucket) } -func testAccBucketAnalyticsConfigurationWithDefaultStorageClassAnalysis(name, bucket string) string { +func testAccBucketAnalyticsConfigurationConfig_defaultStorageClassAnalysis(name, bucket string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -683,7 +683,7 @@ resource "aws_s3_bucket" "destination" { `, name, bucket) } -func testAccBucketAnalyticsConfigurationWithFullStorageClassAnalysis(name, bucket, prefix string) string { +func testAccBucketAnalyticsConfigurationConfig_fullStorageClassAnalysis(name, bucket, prefix string) string { return fmt.Sprintf(` resource "aws_s3_bucket_analytics_configuration" "test" { bucket = aws_s3_bucket.test.bucket diff --git a/internal/service/s3/bucket_cors_configuration_test.go b/internal/service/s3/bucket_cors_configuration_test.go index 8dc4085463c..9411f4dd8f6 100644 --- a/internal/service/s3/bucket_cors_configuration_test.go +++ b/internal/service/s3/bucket_cors_configuration_test.go @@ -28,7 +28,7 @@ func TestAccS3BucketCorsConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckBucketCorsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketCorsConfigurationBasicConfig(rName), + Config: testAccBucketCORSConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketCorsConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -61,7 +61,7 @@ func TestAccS3BucketCorsConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketCorsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketCorsConfigurationBasicConfig(rName), + Config: testAccBucketCORSConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketCorsConfigurationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketCorsConfiguration(), resourceName), @@ -84,7 +84,7 @@ func TestAccS3BucketCorsConfiguration_update(t *testing.T) { Steps: []resource.TestStep{ { - Config: testAccBucketCorsConfigurationCompleteConfig_SingleRule(rName), + Config: testAccBucketCORSConfigurationConfig_completeSingleRule(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketCorsConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -100,7 +100,7 @@ func TestAccS3BucketCorsConfiguration_update(t *testing.T) { ), }, { - Config: testAccBucketCorsConfigurationConfig_MultipleRules(rName), + Config: testAccBucketCORSConfigurationConfig_multipleRules(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketCorsConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -122,7 +122,7 @@ func TestAccS3BucketCorsConfiguration_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketCorsConfigurationBasicConfig(rName), + Config: testAccBucketCORSConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketCorsConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cors_rule.#", "1"), @@ -147,7 +147,7 @@ func TestAccS3BucketCorsConfiguration_SingleRule(t *testing.T) { CheckDestroy: testAccCheckBucketCorsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketCorsConfigurationCompleteConfig_SingleRule(rName), + Config: testAccBucketCORSConfigurationConfig_completeSingleRule(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketCorsConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -188,7 +188,7 @@ func TestAccS3BucketCorsConfiguration_MultipleRules(t *testing.T) { CheckDestroy: testAccCheckBucketCorsConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketCorsConfigurationConfig_MultipleRules(rName), + Config: testAccBucketCORSConfigurationConfig_multipleRules(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketCorsConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -232,7 +232,7 @@ func TestAccS3BucketCorsConfiguration_migrate_corsRuleNoChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withCORS(bucketName), + Config: testAccBucketConfig_cors(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "cors_rule.#", "1"), @@ -244,7 +244,7 @@ func TestAccS3BucketCorsConfiguration_migrate_corsRuleNoChange(t *testing.T) { ), }, { - Config: testAccBucketCorsConfigurationConfig_Migrate_CorsRuleNoChange(bucketName), + Config: testAccBucketCORSConfigurationConfig_migrateRuleNoChange(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketCorsConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "id"), @@ -274,7 +274,7 @@ func TestAccS3BucketCorsConfiguration_migrate_corsRuleWithChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withCORS(bucketName), + Config: testAccBucketConfig_cors(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "cors_rule.#", "1"), @@ -286,7 +286,7 @@ func TestAccS3BucketCorsConfiguration_migrate_corsRuleWithChange(t *testing.T) { ), }, { - Config: testAccBucketCorsConfigurationConfig_Migrate_CorsRuleWithChange(bucketName), + Config: testAccBucketCORSConfigurationConfig_migrateRuleChange(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketCorsConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "id"), @@ -384,7 +384,7 @@ func testAccCheckBucketCorsConfigurationExists(resourceName string) resource.Tes } } -func testAccBucketCorsConfigurationBasicConfig(rName string) string { +func testAccBucketCORSConfigurationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -401,7 +401,7 @@ resource "aws_s3_bucket_cors_configuration" "test" { `, rName) } -func testAccBucketCorsConfigurationCompleteConfig_SingleRule(rName string) string { +func testAccBucketCORSConfigurationConfig_completeSingleRule(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -422,7 +422,7 @@ resource "aws_s3_bucket_cors_configuration" "test" { `, rName) } -func testAccBucketCorsConfigurationConfig_MultipleRules(rName string) string { +func testAccBucketCORSConfigurationConfig_multipleRules(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -445,7 +445,7 @@ resource "aws_s3_bucket_cors_configuration" "test" { `, rName) } -func testAccBucketCorsConfigurationConfig_Migrate_CorsRuleNoChange(rName string) string { +func testAccBucketCORSConfigurationConfig_migrateRuleNoChange(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -465,7 +465,7 @@ resource "aws_s3_bucket_cors_configuration" "test" { `, rName) } -func testAccBucketCorsConfigurationConfig_Migrate_CorsRuleWithChange(rName string) string { +func testAccBucketCORSConfigurationConfig_migrateRuleChange(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_data_source_test.go b/internal/service/s3/bucket_data_source_test.go index 6016b500459..9779d8b3cd7 100644 --- a/internal/service/s3/bucket_data_source_test.go +++ b/internal/service/s3/bucket_data_source_test.go @@ -46,7 +46,7 @@ func TestAccS3BucketDataSource_website(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteDataSourceConfig(bucketName), + Config: testAccBucketDataSourceConfig_website(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists("data.aws_s3_bucket.bucket"), resource.TestCheckResourceAttrPair("data.aws_s3_bucket.bucket", "bucket", "aws_s3_bucket.bucket", "id"), @@ -70,7 +70,7 @@ data "aws_s3_bucket" "bucket" { `, bucketName) } -func testAccBucketWebsiteDataSourceConfig(bucketName string) string { +func testAccBucketDataSourceConfig_website(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "bucket" { bucket = %[1]q diff --git a/internal/service/s3/bucket_intelligent_tiering_configuration_test.go b/internal/service/s3/bucket_intelligent_tiering_configuration_test.go index 73061029193..4b604f6e124 100644 --- a/internal/service/s3/bucket_intelligent_tiering_configuration_test.go +++ b/internal/service/s3/bucket_intelligent_tiering_configuration_test.go @@ -27,7 +27,7 @@ func TestAccS3BucketIntelligentTieringConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckBucketIntelligentTieringConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketIntelligentTieringConfigurationConfig(rName), + Config: testAccBucketIntelligentTieringConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketIntelligentTieringConfigurationExists(resourceName, &itc), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -60,7 +60,7 @@ func TestAccS3BucketIntelligentTieringConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketIntelligentTieringConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketIntelligentTieringConfigurationConfig(rName), + Config: testAccBucketIntelligentTieringConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketIntelligentTieringConfigurationExists(resourceName, &itc), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketIntelligentTieringConfiguration(), resourceName), @@ -84,7 +84,7 @@ func TestAccS3BucketIntelligentTieringConfiguration_Filter(t *testing.T) { CheckDestroy: testAccCheckBucketIntelligentTieringConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketIntelligentTieringConfigurationFilterPrefixConfig(rName), + Config: testAccBucketIntelligentTieringConfigurationConfig_filterPrefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketIntelligentTieringConfigurationExists(resourceName, &itc), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -106,7 +106,7 @@ func TestAccS3BucketIntelligentTieringConfiguration_Filter(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketIntelligentTieringConfigurationFilterPrefixAndTagConfig(rName), + Config: testAccBucketIntelligentTieringConfigurationConfig_filterPrefixAndTag(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketIntelligentTieringConfigurationExists(resourceName, &itc), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -128,7 +128,7 @@ func TestAccS3BucketIntelligentTieringConfiguration_Filter(t *testing.T) { ), }, { - Config: testAccBucketIntelligentTieringConfigurationFilterTagConfig(rName), + Config: testAccBucketIntelligentTieringConfigurationConfig_filterTag(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketIntelligentTieringConfigurationExists(resourceName, &itc), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -146,7 +146,7 @@ func TestAccS3BucketIntelligentTieringConfiguration_Filter(t *testing.T) { ), }, { - Config: testAccBucketIntelligentTieringConfigurationFilterPrefixAndTagsConfig(rName), + Config: testAccBucketIntelligentTieringConfigurationConfig_filterPrefixAndTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketIntelligentTieringConfigurationExists(resourceName, &itc), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -165,7 +165,7 @@ func TestAccS3BucketIntelligentTieringConfiguration_Filter(t *testing.T) { ), }, { - Config: testAccBucketIntelligentTieringConfigurationFilterTagsConfig(rName), + Config: testAccBucketIntelligentTieringConfigurationConfig_filterTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketIntelligentTieringConfigurationExists(resourceName, &itc), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -187,7 +187,7 @@ func TestAccS3BucketIntelligentTieringConfiguration_Filter(t *testing.T) { }) } -func testAccBucketIntelligentTieringConfigurationConfig(rName string) string { +func testAccBucketIntelligentTieringConfigurationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket_intelligent_tiering_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -205,7 +205,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccBucketIntelligentTieringConfigurationFilterPrefixConfig(rName string) string { +func testAccBucketIntelligentTieringConfigurationConfig_filterPrefix(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket_intelligent_tiering_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -229,7 +229,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccBucketIntelligentTieringConfigurationFilterPrefixAndTagConfig(rName string) string { +func testAccBucketIntelligentTieringConfigurationConfig_filterPrefixAndTag(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket_intelligent_tiering_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -262,7 +262,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccBucketIntelligentTieringConfigurationFilterTagConfig(rName string) string { +func testAccBucketIntelligentTieringConfigurationConfig_filterTag(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket_intelligent_tiering_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -288,7 +288,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccBucketIntelligentTieringConfigurationFilterPrefixAndTagsConfig(rName string) string { +func testAccBucketIntelligentTieringConfigurationConfig_filterPrefixAndTags(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket_intelligent_tiering_configuration" "test" { bucket = aws_s3_bucket.test.bucket @@ -315,7 +315,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccBucketIntelligentTieringConfigurationFilterTagsConfig(rName string) string { +func testAccBucketIntelligentTieringConfigurationConfig_filterTags(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket_intelligent_tiering_configuration" "test" { bucket = aws_s3_bucket.test.bucket diff --git a/internal/service/s3/bucket_inventory_test.go b/internal/service/s3/bucket_inventory_test.go index 0cc00f7a463..5887128fbf3 100644 --- a/internal/service/s3/bucket_inventory_test.go +++ b/internal/service/s3/bucket_inventory_test.go @@ -33,7 +33,7 @@ func TestAccS3BucketInventory_basic(t *testing.T) { CheckDestroy: testAccCheckBucketInventoryDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketInventoryConfig(bucketName, inventoryName), + Config: testAccBucketInventoryConfig_basic(bucketName, inventoryName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketInventoryExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "bucket", bucketName), @@ -109,7 +109,7 @@ func TestAccS3BucketInventory_encryptWithSSEKMS(t *testing.T) { CheckDestroy: testAccCheckBucketInventoryDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketInventoryEncryptWithSSEKMSConfig(bucketName, inventoryName), + Config: testAccBucketInventoryConfig_encryptSSEKMS(bucketName, inventoryName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketInventoryExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "destination.0.bucket.0.encryption.0.sse_kms.#", "1"), @@ -209,7 +209,7 @@ resource "aws_s3_bucket_acl" "test" { `, name) } -func testAccBucketInventoryConfig(bucketName, inventoryName string) string { +func testAccBucketInventoryConfig_basic(bucketName, inventoryName string) string { return testAccBucketInventoryBucketConfig(bucketName) + fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -270,7 +270,7 @@ resource "aws_s3_bucket_inventory" "test" { `, inventoryName) } -func testAccBucketInventoryEncryptWithSSEKMSConfig(bucketName, inventoryName string) string { +func testAccBucketInventoryConfig_encryptSSEKMS(bucketName, inventoryName string) string { return testAccBucketInventoryBucketConfig(bucketName) + fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Terraform acc test S3 inventory SSE-KMS encryption: %[1]s" diff --git a/internal/service/s3/bucket_lifecycle_configuration_test.go b/internal/service/s3/bucket_lifecycle_configuration_test.go index eae664270d8..c0713ef51ab 100644 --- a/internal/service/s3/bucket_lifecycle_configuration_test.go +++ b/internal/service/s3/bucket_lifecycle_configuration_test.go @@ -28,7 +28,7 @@ func TestAccS3BucketLifecycleConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationBasicConfig(rName), + Config: testAccBucketLifecycleConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "bucket"), @@ -63,7 +63,7 @@ func TestAccS3BucketLifecycleConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationBasicConfig(rName), + Config: testAccBucketLifecycleConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketLifecycleConfiguration(), resourceName), @@ -88,7 +88,7 @@ func TestAccS3BucketLifecycleConfiguration_filterWithPrefix(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_Basic_updateConfig(rName, date, "logs/"), + Config: testAccBucketLifecycleConfigurationConfig_basicUpdate(rName, date, "logs/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -107,7 +107,7 @@ func TestAccS3BucketLifecycleConfiguration_filterWithPrefix(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfiguration_Basic_updateConfig(rName, dateUpdated, "tmp/"), + Config: testAccBucketLifecycleConfigurationConfig_basicUpdate(rName, dateUpdated, "tmp/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -142,7 +142,7 @@ func TestAccS3BucketLifecycleConfiguration_Filter_ObjectSizeGreaterThan(t *testi CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_filterWithObjectSizeGreaterThanConfig(rName, date, 100), + Config: testAccBucketLifecycleConfigurationConfig_filterObjectSizeGreaterThan(rName, date, 100), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -177,7 +177,7 @@ func TestAccS3BucketLifecycleConfiguration_Filter_ObjectSizeLessThan(t *testing. CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_filterWithObjectSizeLessThanConfig(rName, date, 500), + Config: testAccBucketLifecycleConfigurationConfig_filterObjectSizeLessThan(rName, date, 500), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -212,7 +212,7 @@ func TestAccS3BucketLifecycleConfiguration_Filter_ObjectSizeRange(t *testing.T) CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_filterWithObjectSizeRangeConfig(rName, date, 500, 64000), + Config: testAccBucketLifecycleConfigurationConfig_filterObjectSizeRange(rName, date, 500, 64000), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -249,7 +249,7 @@ func TestAccS3BucketLifecycleConfiguration_Filter_ObjectSizeRangeAndPrefix(t *te CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_filterWithObjectSizeRangeAndPrefixConfig(rName, date, 500, 64000), + Config: testAccBucketLifecycleConfigurationConfig_filterObjectSizeRangeAndPrefix(rName, date, 500, 64000), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -285,13 +285,13 @@ func TestAccS3BucketLifecycleConfiguration_disableRule(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_Basic_statusConfig(rName, tfs3.LifecycleRuleStatusEnabled), + Config: testAccBucketLifecycleConfigurationConfig_basicStatus(rName, tfs3.LifecycleRuleStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), ), }, { - Config: testAccBucketLifecycleConfiguration_Basic_statusConfig(rName, tfs3.LifecycleRuleStatusDisabled), + Config: testAccBucketLifecycleConfigurationConfig_basicStatus(rName, tfs3.LifecycleRuleStatusDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -305,7 +305,7 @@ func TestAccS3BucketLifecycleConfiguration_disableRule(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfiguration_Basic_statusConfig(rName, tfs3.LifecycleRuleStatusEnabled), + Config: testAccBucketLifecycleConfigurationConfig_basicStatus(rName, tfs3.LifecycleRuleStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -330,7 +330,7 @@ func TestAccS3BucketLifecycleConfiguration_multipleRules(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_multipleRulesConfig(rName, expirationDate), + Config: testAccBucketLifecycleConfigurationConfig_multipleRules(rName, expirationDate), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "2"), @@ -384,7 +384,7 @@ func TestAccS3BucketLifecycleConfiguration_multipleRules_noFilterOrPrefix(t *tes CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_MultipleRules_noFilterOrPrefixConfig(rName, s3.ReplicationRuleStatusEnabled), + Config: testAccBucketLifecycleConfigurationConfig_multipleRulesNoFilterOrPrefix(rName, s3.ReplicationRuleStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "2"), @@ -414,7 +414,7 @@ func TestAccS3BucketLifecycleConfiguration_nonCurrentVersionExpiration(t *testin CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_nonCurrentVersionExpirationConfig(rName), + Config: testAccBucketLifecycleConfigurationConfig_nonCurrentVersionExpiration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -443,7 +443,7 @@ func TestAccS3BucketLifecycleConfiguration_nonCurrentVersionTransition(t *testin CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_nonCurrentVersionTransitionConfig(rName), + Config: testAccBucketLifecycleConfigurationConfig_nonCurrentVersionTransition(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -480,7 +480,7 @@ func TestAccS3BucketLifecycleConfiguration_prefix(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_Basic_prefixConfig(rName, "path1/"), + Config: testAccBucketLifecycleConfigurationConfig_basicPrefix(rName, "path1/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "bucket"), @@ -515,7 +515,7 @@ func TestAccS3BucketLifecycleConfiguration_Filter_Tag(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_Filter_TagConfig(rName, "key1", "value1"), + Config: testAccBucketLifecycleConfigurationConfig_filterTag(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -551,7 +551,7 @@ func TestAccS3BucketLifecycleConfiguration_RuleExpiration_expireMarkerOnly(t *te CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_RuleExpiration_expiredDeleteMarkerConfig(rName, true), + Config: testAccBucketLifecycleConfigurationConfig_ruleExpirationExpiredDeleteMarker(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -566,7 +566,7 @@ func TestAccS3BucketLifecycleConfiguration_RuleExpiration_expireMarkerOnly(t *te ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfiguration_RuleExpiration_expiredDeleteMarkerConfig(rName, false), + Config: testAccBucketLifecycleConfigurationConfig_ruleExpirationExpiredDeleteMarker(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -596,7 +596,7 @@ func TestAccS3BucketLifecycleConfiguration_RuleExpiration_emptyBlock(t *testing. CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_RuleExpiration_emptyConfigurationBlockConfig(rName), + Config: testAccBucketLifecycleConfigurationConfig_ruleExpirationEmptyBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -625,7 +625,7 @@ func TestAccS3BucketLifecycleConfiguration_ruleAbortIncompleteMultipartUpload(t CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_ruleAbortIncompleteMultipartUploadConfig(rName, 7), + Config: testAccBucketLifecycleConfigurationConfig_ruleAbortIncompleteMultipartUpload(rName, 7), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -640,7 +640,7 @@ func TestAccS3BucketLifecycleConfiguration_ruleAbortIncompleteMultipartUpload(t ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfiguration_ruleAbortIncompleteMultipartUploadConfig(rName, 5), + Config: testAccBucketLifecycleConfigurationConfig_ruleAbortIncompleteMultipartUpload(rName, 5), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -675,7 +675,7 @@ func TestAccS3BucketLifecycleConfiguration_TransitionDate_standardIa(t *testing. CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_dateTransitionConfig(rName, date, s3.TransitionStorageClassStandardIa), + Config: testAccBucketLifecycleConfigurationConfig_dateTransition(rName, date, s3.TransitionStorageClassStandardIa), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), ), @@ -706,7 +706,7 @@ func TestAccS3BucketLifecycleConfiguration_TransitionDate_intelligentTiering(t * CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_dateTransitionConfig(rName, date, s3.StorageClassIntelligentTiering), + Config: testAccBucketLifecycleConfigurationConfig_dateTransition(rName, date, s3.StorageClassIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), ), @@ -732,7 +732,7 @@ func TestAccS3BucketLifecycleConfiguration_TransitionStorageClassOnly_intelligen CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_transitionStorageClassOnlyConfig(rName, s3.StorageClassIntelligentTiering), + Config: testAccBucketLifecycleConfigurationConfig_transitionStorageClassOnly(rName, s3.StorageClassIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.0.transition.*", map[string]string{ @@ -763,7 +763,7 @@ func TestAccS3BucketLifecycleConfiguration_TransitionZeroDays_intelligentTiering CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_zeroDaysTransitionConfig(rName, s3.StorageClassIntelligentTiering), + Config: testAccBucketLifecycleConfigurationConfig_zeroDaysTransition(rName, s3.StorageClassIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), ), @@ -791,13 +791,13 @@ func TestAccS3BucketLifecycleConfiguration_TransitionUpdateBetweenDaysAndDate_in CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_zeroDaysTransitionConfig(rName, s3.StorageClassIntelligentTiering), + Config: testAccBucketLifecycleConfigurationConfig_zeroDaysTransition(rName, s3.StorageClassIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), ), }, { - Config: testAccBucketLifecycleConfiguration_dateTransitionConfig(rName, date, s3.StorageClassIntelligentTiering), + Config: testAccBucketLifecycleConfigurationConfig_dateTransition(rName, date, s3.StorageClassIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), ), @@ -808,7 +808,7 @@ func TestAccS3BucketLifecycleConfiguration_TransitionUpdateBetweenDaysAndDate_in ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfiguration_zeroDaysTransitionConfig(rName, s3.StorageClassIntelligentTiering), + Config: testAccBucketLifecycleConfigurationConfig_zeroDaysTransition(rName, s3.StorageClassIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), ), @@ -829,7 +829,7 @@ func TestAccS3BucketLifecycleConfiguration_EmptyFilter_NonCurrentVersions(t *tes CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_EmptyFilter_NonCurrentVersionsConfig(rName), + Config: testAccBucketLifecycleConfigurationConfig_emptyFilterNonCurrentVersions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), ), @@ -854,7 +854,7 @@ func TestAccS3BucketLifecycleConfiguration_migrate_noChange(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLifecycleExpireMarker(rName), + Config: testAccBucketConfig_lifecycleExpireMarker(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "lifecycle_rule.#", "1"), @@ -867,7 +867,7 @@ func TestAccS3BucketLifecycleConfiguration_migrate_noChange(t *testing.T) { ), }, { - Config: testAccBucketLifecycleConfiguration_Migrate_NoChangeConfig(rName), + Config: testAccBucketLifecycleConfigurationConfig_migrateNoChange(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -896,7 +896,7 @@ func TestAccS3BucketLifecycleConfiguration_migrate_withChange(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLifecycleExpireMarker(rName), + Config: testAccBucketConfig_lifecycleExpireMarker(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "lifecycle_rule.#", "1"), @@ -909,7 +909,7 @@ func TestAccS3BucketLifecycleConfiguration_migrate_withChange(t *testing.T) { ), }, { - Config: testAccBucketLifecycleConfiguration_Migrate_WithChangeConfig(rName), + Config: testAccBucketLifecycleConfigurationConfig_migrateChange(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -938,7 +938,7 @@ func TestAccS3BucketLifecycleConfiguration_Update_filterWithAndToFilterWithPrefi CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfiguration_Filter_ObjectSizeGreaterThanAndPrefixConfig(rName, "prefix1"), + Config: testAccBucketLifecycleConfigurationConfig_filterObjectSizeGreaterThanAndPrefix(rName, "prefix1"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -949,7 +949,7 @@ func TestAccS3BucketLifecycleConfiguration_Update_filterWithAndToFilterWithPrefi ), }, { - Config: testAccBucketLifecycleConfiguration_Filter_PrefixConfig(rName, "prefix2"), + Config: testAccBucketLifecycleConfigurationConfig_filterPrefix(rName, "prefix2"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -1045,7 +1045,7 @@ func testAccCheckBucketLifecycleConfigurationExists(n string) resource.TestCheck } } -func testAccBucketLifecycleConfigurationBasicConfig(rName string) string { +func testAccBucketLifecycleConfigurationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1070,7 +1070,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName) } -func testAccBucketLifecycleConfiguration_MultipleRules_noFilterOrPrefixConfig(rName, status string) string { +func testAccBucketLifecycleConfigurationConfig_multipleRulesNoFilterOrPrefix(rName, status string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1105,7 +1105,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, status) } -func testAccBucketLifecycleConfiguration_Basic_statusConfig(rName, status string) string { +func testAccBucketLifecycleConfigurationConfig_basicStatus(rName, status string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1130,7 +1130,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, status) } -func testAccBucketLifecycleConfiguration_Basic_updateConfig(rName, date, prefix string) string { +func testAccBucketLifecycleConfigurationConfig_basicUpdate(rName, date, prefix string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1160,7 +1160,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, date, prefix) } -func testAccBucketLifecycleConfiguration_Basic_prefixConfig(rName, prefix string) string { +func testAccBucketLifecycleConfigurationConfig_basicPrefix(rName, prefix string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1188,7 +1188,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, prefix) } -func testAccBucketLifecycleConfiguration_Filter_TagConfig(rName, key, value string) string { +func testAccBucketLifecycleConfigurationConfig_filterTag(rName, key, value string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1220,7 +1220,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, key, value) } -func testAccBucketLifecycleConfiguration_RuleExpiration_expiredDeleteMarkerConfig(rName string, expired bool) string { +func testAccBucketLifecycleConfigurationConfig_ruleExpirationExpiredDeleteMarker(rName string, expired bool) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1246,7 +1246,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, expired) } -func testAccBucketLifecycleConfiguration_RuleExpiration_emptyConfigurationBlockConfig(rName string) string { +func testAccBucketLifecycleConfigurationConfig_ruleExpirationEmptyBlock(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1270,7 +1270,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName) } -func testAccBucketLifecycleConfiguration_ruleAbortIncompleteMultipartUploadConfig(rName string, days int) string { +func testAccBucketLifecycleConfigurationConfig_ruleAbortIncompleteMultipartUpload(rName string, days int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1296,7 +1296,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, days) } -func testAccBucketLifecycleConfiguration_multipleRulesConfig(rName, date string) string { +func testAccBucketLifecycleConfigurationConfig_multipleRules(rName, date string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1358,7 +1358,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, date) } -func testAccBucketLifecycleConfiguration_nonCurrentVersionExpirationConfig(rName string) string { +func testAccBucketLifecycleConfigurationConfig_nonCurrentVersionExpiration(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1390,7 +1390,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName) } -func testAccBucketLifecycleConfiguration_nonCurrentVersionTransitionConfig(rName string) string { +func testAccBucketLifecycleConfigurationConfig_nonCurrentVersionTransition(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1428,7 +1428,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName) } -func testAccBucketLifecycleConfiguration_transitionStorageClassOnlyConfig(rName, storageClass string) string { +func testAccBucketLifecycleConfigurationConfig_transitionStorageClassOnly(rName, storageClass string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1464,7 +1464,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, storageClass) } -func testAccBucketLifecycleConfiguration_zeroDaysTransitionConfig(rName, storageClass string) string { +func testAccBucketLifecycleConfigurationConfig_zeroDaysTransition(rName, storageClass string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1501,7 +1501,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, storageClass) } -func testAccBucketLifecycleConfiguration_dateTransitionConfig(rName, transitionDate, storageClass string) string { +func testAccBucketLifecycleConfigurationConfig_dateTransition(rName, transitionDate, storageClass string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1538,7 +1538,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, transitionDate, storageClass) } -func testAccBucketLifecycleConfiguration_EmptyFilter_NonCurrentVersionsConfig(rName string) string { +func testAccBucketLifecycleConfigurationConfig_emptyFilterNonCurrentVersions(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1573,7 +1573,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName) } -func testAccBucketLifecycleConfiguration_filterWithObjectSizeGreaterThanConfig(rName, date string, sizeGreaterThan int) string { +func testAccBucketLifecycleConfigurationConfig_filterObjectSizeGreaterThan(rName, date string, sizeGreaterThan int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1604,7 +1604,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, date, sizeGreaterThan) } -func testAccBucketLifecycleConfiguration_filterWithObjectSizeLessThanConfig(rName, date string, sizeLessThan int) string { +func testAccBucketLifecycleConfigurationConfig_filterObjectSizeLessThan(rName, date string, sizeLessThan int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1635,7 +1635,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, date, sizeLessThan) } -func testAccBucketLifecycleConfiguration_filterWithObjectSizeRangeConfig(rName, date string, sizeGreaterThan, sizeLessThan int) string { +func testAccBucketLifecycleConfigurationConfig_filterObjectSizeRange(rName, date string, sizeGreaterThan, sizeLessThan int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1669,7 +1669,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, date, sizeGreaterThan, sizeLessThan) } -func testAccBucketLifecycleConfiguration_filterWithObjectSizeRangeAndPrefixConfig(rName, date string, sizeGreaterThan, sizeLessThan int) string { +func testAccBucketLifecycleConfigurationConfig_filterObjectSizeRangeAndPrefix(rName, date string, sizeGreaterThan, sizeLessThan int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1704,7 +1704,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName, date, sizeGreaterThan, sizeLessThan) } -func testAccBucketLifecycleConfiguration_Filter_ObjectSizeGreaterThanAndPrefixConfig(rName, prefix string) string { +func testAccBucketLifecycleConfigurationConfig_filterObjectSizeGreaterThanAndPrefix(rName, prefix string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1737,7 +1737,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { }`, rName, prefix) } -func testAccBucketLifecycleConfiguration_Filter_PrefixConfig(rName, prefix string) string { +func testAccBucketLifecycleConfigurationConfig_filterPrefix(rName, prefix string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1767,7 +1767,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { }`, rName, prefix) } -func testAccBucketLifecycleConfiguration_Migrate_NoChangeConfig(rName string) string { +func testAccBucketLifecycleConfigurationConfig_migrateNoChange(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1794,7 +1794,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "test" { `, rName) } -func testAccBucketLifecycleConfiguration_Migrate_WithChangeConfig(rName string) string { +func testAccBucketLifecycleConfigurationConfig_migrateChange(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_logging_test.go b/internal/service/s3/bucket_logging_test.go index 74f7c544556..dd1f08cce52 100644 --- a/internal/service/s3/bucket_logging_test.go +++ b/internal/service/s3/bucket_logging_test.go @@ -27,7 +27,7 @@ func TestAccS3BucketLogging_basic(t *testing.T) { CheckDestroy: testAccCheckBucketLoggingDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLoggingBasicConfig(rName), + Config: testAccBucketLoggingConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bucket", rName), @@ -56,7 +56,7 @@ func TestAccS3BucketLogging_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketLoggingDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLoggingBasicConfig(rName), + Config: testAccBucketLoggingConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketLogging(), resourceName), @@ -79,14 +79,14 @@ func TestAccS3BucketLogging_update(t *testing.T) { CheckDestroy: testAccCheckBucketLoggingDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLoggingBasicConfig(rName), + Config: testAccBucketLoggingConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), ), }, { // Test updating "target_prefix" - Config: testAccBucketLoggingUpdateConfig(rName, rName, "tmp/"), + Config: testAccBucketLoggingConfig_update(rName, rName, "tmp/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bucket", rName), @@ -102,7 +102,7 @@ func TestAccS3BucketLogging_update(t *testing.T) { }, { // Test updating "target_bucket" and "target_prefix" - Config: testAccBucketLoggingUpdateConfig(rName, targetBucketName, "log/"), + Config: testAccBucketLoggingConfig_update(rName, targetBucketName, "log/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bucket", rName), @@ -131,7 +131,7 @@ func TestAccS3BucketLogging_TargetGrantByID(t *testing.T) { CheckDestroy: testAccCheckBucketLoggingDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLoggingTargetGrantConfig_ById(rName, s3.BucketLogsPermissionFullControl), + Config: testAccBucketLoggingConfig_targetGrantByID(rName, s3.BucketLogsPermissionFullControl), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_grant.#", "1"), @@ -150,7 +150,7 @@ func TestAccS3BucketLogging_TargetGrantByID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLoggingTargetGrantConfig_ById(rName, s3.BucketLogsPermissionRead), + Config: testAccBucketLoggingConfig_targetGrantByID(rName, s3.BucketLogsPermissionRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_grant.#", "1"), @@ -168,7 +168,7 @@ func TestAccS3BucketLogging_TargetGrantByID(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLoggingBasicConfig(rName), + Config: testAccBucketLoggingConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_grant.#", "0"), @@ -195,7 +195,7 @@ func TestAccS3BucketLogging_TargetGrantByEmail(t *testing.T) { CheckDestroy: testAccCheckBucketLoggingDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLoggingTargetGrantConfig_ByEmail(rName, rEmail, s3.BucketLogsPermissionFullControl), + Config: testAccBucketLoggingConfig_targetGrantByEmail(rName, rEmail, s3.BucketLogsPermissionFullControl), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_grant.#", "1"), @@ -213,7 +213,7 @@ func TestAccS3BucketLogging_TargetGrantByEmail(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLoggingTargetGrantConfig_ByEmail(rName, rEmail, s3.BucketLogsPermissionRead), + Config: testAccBucketLoggingConfig_targetGrantByEmail(rName, rEmail, s3.BucketLogsPermissionRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_grant.#", "1"), @@ -231,7 +231,7 @@ func TestAccS3BucketLogging_TargetGrantByEmail(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLoggingBasicConfig(rName), + Config: testAccBucketLoggingConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_grant.#", "0"), @@ -252,7 +252,7 @@ func TestAccS3BucketLogging_TargetGrantByGroup(t *testing.T) { CheckDestroy: testAccCheckBucketLoggingDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLoggingTargetGrantConfig_ByGroup(rName, s3.BucketLogsPermissionFullControl), + Config: testAccBucketLoggingConfig_targetGrantByGroup(rName, s3.BucketLogsPermissionFullControl), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_grant.#", "1"), @@ -270,7 +270,7 @@ func TestAccS3BucketLogging_TargetGrantByGroup(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLoggingTargetGrantConfig_ByGroup(rName, s3.BucketLogsPermissionRead), + Config: testAccBucketLoggingConfig_targetGrantByGroup(rName, s3.BucketLogsPermissionRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_grant.#", "1"), @@ -288,7 +288,7 @@ func TestAccS3BucketLogging_TargetGrantByGroup(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLoggingBasicConfig(rName), + Config: testAccBucketLoggingConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_grant.#", "0"), @@ -310,7 +310,7 @@ func TestAccS3BucketLogging_migrate_loggingNoChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLogging(bucketName), + Config: testAccBucketConfig_logging(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "logging.#", "1"), @@ -319,7 +319,7 @@ func TestAccS3BucketLogging_migrate_loggingNoChange(t *testing.T) { ), }, { - Config: testAccBucketLogging_Migrate_LoggingConfig(bucketName, "log/"), + Config: testAccBucketLoggingConfig_migrate(bucketName, "log/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "target_bucket", "aws_s3_bucket.log_bucket", "id"), @@ -342,7 +342,7 @@ func TestAccS3BucketLogging_migrate_loggingWithChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLogging(bucketName), + Config: testAccBucketConfig_logging(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "logging.#", "1"), @@ -351,7 +351,7 @@ func TestAccS3BucketLogging_migrate_loggingWithChange(t *testing.T) { ), }, { - Config: testAccBucketLogging_Migrate_LoggingConfig(bucketName, "tmp/"), + Config: testAccBucketLoggingConfig_migrate(bucketName, "tmp/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLoggingExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "target_bucket", "aws_s3_bucket.log_bucket", "id"), @@ -450,7 +450,7 @@ func testAccCheckBucketLoggingTargetGrantGranteeURI(resourceName string) resourc } } -func testAccBucketLoggingBasicConfig(rName string) string { +func testAccBucketLoggingConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "log_bucket" { bucket = "%[1]s-log" @@ -479,7 +479,7 @@ resource "aws_s3_bucket_logging" "test" { `, rName) } -func testAccBucketLoggingUpdateConfig(rName, targetBucketName, targetPrefix string) string { +func testAccBucketLoggingConfig_update(rName, targetBucketName, targetPrefix string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -508,7 +508,7 @@ resource "aws_s3_bucket_logging" "test" { `, rName, targetBucketName, targetPrefix) } -func testAccBucketLoggingTargetGrantConfig_ById(rName, permission string) string { +func testAccBucketLoggingConfig_targetGrantByID(rName, permission string) string { return fmt.Sprintf(` data "aws_canonical_user_id" "current" {} @@ -549,7 +549,7 @@ resource "aws_s3_bucket_logging" "test" { `, rName, permission) } -func testAccBucketLoggingTargetGrantConfig_ByEmail(rName, email, permission string) string { +func testAccBucketLoggingConfig_targetGrantByEmail(rName, email, permission string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "log_bucket" { bucket = "%[1]s-log" @@ -586,7 +586,7 @@ resource "aws_s3_bucket_logging" "test" { `, rName, email, permission) } -func testAccBucketLoggingTargetGrantConfig_ByGroup(rName, permission string) string { +func testAccBucketLoggingConfig_targetGrantByGroup(rName, permission string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -626,7 +626,7 @@ resource "aws_s3_bucket_logging" "test" { `, rName, permission) } -func testAccBucketLogging_Migrate_LoggingConfig(rName, targetPrefix string) string { +func testAccBucketLoggingConfig_migrate(rName, targetPrefix string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "log_bucket" { bucket = "%[1]s-log" diff --git a/internal/service/s3/bucket_metric.go b/internal/service/s3/bucket_metric.go index d44d545f5b3..7f72be95f07 100644 --- a/internal/service/s3/bucket_metric.go +++ b/internal/service/s3/bucket_metric.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "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" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -52,9 +53,10 @@ func ResourceBucketMetric() *schema.Resource { }, }, "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 64), }, }, } diff --git a/internal/service/s3/bucket_metric_test.go b/internal/service/s3/bucket_metric_test.go index 2c893125995..048cab35bdc 100644 --- a/internal/service/s3/bucket_metric_test.go +++ b/internal/service/s3/bucket_metric_test.go @@ -280,7 +280,7 @@ func TestAccS3BucketMetric_basic(t *testing.T) { CheckDestroy: testAccCheckBucketMetricDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketMetricsWithoutFilterConfig(bucketName, metricName), + Config: testAccBucketMetricConfig_noFilter(bucketName, metricName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "bucket", bucketName), @@ -314,7 +314,7 @@ func TestAccS3BucketMetric_withEmptyFilter(t *testing.T) { CheckDestroy: testAccCheckBucketMetricDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketMetricsWithEmptyFilterConfig(bucketName, metricName), + Config: testAccBucketMetricConfig_emptyFilter(bucketName, metricName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), ), @@ -341,7 +341,7 @@ func TestAccS3BucketMetric_withFilterPrefix(t *testing.T) { CheckDestroy: testAccCheckBucketMetricDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketMetricsWithFilterPrefixConfig(bucketName, metricName, prefix), + Config: testAccBucketMetricConfig_filterPrefix(bucketName, metricName, prefix), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -350,7 +350,7 @@ func TestAccS3BucketMetric_withFilterPrefix(t *testing.T) { ), }, { - Config: testAccBucketMetricsWithFilterPrefixConfig(bucketName, metricName, prefixUpdate), + Config: testAccBucketMetricConfig_filterPrefix(bucketName, metricName, prefixUpdate), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -388,7 +388,7 @@ func TestAccS3BucketMetric_withFilterPrefixAndMultipleTags(t *testing.T) { CheckDestroy: testAccCheckBucketMetricDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketMetricsWithFilterPrefixAndMultipleTagsConfig(bucketName, metricName, prefix, tag1, tag2), + Config: testAccBucketMetricConfig_filterPrefixAndMultipleTags(bucketName, metricName, prefix, tag1, tag2), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -399,7 +399,7 @@ func TestAccS3BucketMetric_withFilterPrefixAndMultipleTags(t *testing.T) { ), }, { - Config: testAccBucketMetricsWithFilterPrefixAndMultipleTagsConfig(bucketName, metricName, prefixUpdate, tag1Update, tag2Update), + Config: testAccBucketMetricConfig_filterPrefixAndMultipleTags(bucketName, metricName, prefixUpdate, tag1Update, tag2Update), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -437,7 +437,7 @@ func TestAccS3BucketMetric_withFilterPrefixAndSingleTag(t *testing.T) { CheckDestroy: testAccCheckBucketMetricDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketMetricsWithFilterPrefixAndSingleTagConfig(bucketName, metricName, prefix, tag1), + Config: testAccBucketMetricConfig_filterPrefixAndSingleTag(bucketName, metricName, prefix, tag1), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -447,7 +447,7 @@ func TestAccS3BucketMetric_withFilterPrefixAndSingleTag(t *testing.T) { ), }, { - Config: testAccBucketMetricsWithFilterPrefixAndSingleTagConfig(bucketName, metricName, prefixUpdate, tag1Update), + Config: testAccBucketMetricConfig_filterPrefixAndSingleTag(bucketName, metricName, prefixUpdate, tag1Update), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -484,7 +484,7 @@ func TestAccS3BucketMetric_withFilterMultipleTags(t *testing.T) { CheckDestroy: testAccCheckBucketMetricDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketMetricsWithFilterMultipleTagsConfig(bucketName, metricName, tag1, tag2), + Config: testAccBucketMetricConfig_filterMultipleTags(bucketName, metricName, tag1, tag2), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -495,7 +495,7 @@ func TestAccS3BucketMetric_withFilterMultipleTags(t *testing.T) { ), }, { - Config: testAccBucketMetricsWithFilterMultipleTagsConfig(bucketName, metricName, tag1Update, tag2Update), + Config: testAccBucketMetricConfig_filterMultipleTags(bucketName, metricName, tag1Update, tag2Update), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -531,7 +531,7 @@ func TestAccS3BucketMetric_withFilterSingleTag(t *testing.T) { CheckDestroy: testAccCheckBucketMetricDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketMetricsWithFilterSingleTagConfig(bucketName, metricName, tag1), + Config: testAccBucketMetricConfig_filterSingleTag(bucketName, metricName, tag1), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -541,7 +541,7 @@ func TestAccS3BucketMetric_withFilterSingleTag(t *testing.T) { ), }, { - Config: testAccBucketMetricsWithFilterSingleTagConfig(bucketName, metricName, tag1Update), + Config: testAccBucketMetricConfig_filterSingleTag(bucketName, metricName, tag1Update), Check: resource.ComposeTestCheckFunc( testAccCheckBucketMetricsExistsConfig(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "filter.#", "1"), @@ -645,7 +645,7 @@ resource "aws_s3_bucket_acl" "test" { `, name) } -func testAccBucketMetricsWithEmptyFilterConfig(bucketName, metricName string) string { +func testAccBucketMetricConfig_emptyFilter(bucketName, metricName string) string { return fmt.Sprintf(` %s @@ -658,7 +658,7 @@ resource "aws_s3_bucket_metric" "test" { `, testAccBucketMetricsBucketConfig(bucketName), metricName) } -func testAccBucketMetricsWithFilterPrefixConfig(bucketName, metricName, prefix string) string { +func testAccBucketMetricConfig_filterPrefix(bucketName, metricName, prefix string) string { return fmt.Sprintf(` %s @@ -673,7 +673,7 @@ resource "aws_s3_bucket_metric" "test" { `, testAccBucketMetricsBucketConfig(bucketName), metricName, prefix) } -func testAccBucketMetricsWithFilterPrefixAndMultipleTagsConfig(bucketName, metricName, prefix, tag1, tag2 string) string { +func testAccBucketMetricConfig_filterPrefixAndMultipleTags(bucketName, metricName, prefix, tag1, tag2 string) string { return fmt.Sprintf(` %s @@ -693,7 +693,7 @@ resource "aws_s3_bucket_metric" "test" { `, testAccBucketMetricsBucketConfig(bucketName), metricName, prefix, tag1, tag2) } -func testAccBucketMetricsWithFilterPrefixAndSingleTagConfig(bucketName, metricName, prefix, tag string) string { +func testAccBucketMetricConfig_filterPrefixAndSingleTag(bucketName, metricName, prefix, tag string) string { return fmt.Sprintf(` %s @@ -712,7 +712,7 @@ resource "aws_s3_bucket_metric" "test" { `, testAccBucketMetricsBucketConfig(bucketName), metricName, prefix, tag) } -func testAccBucketMetricsWithFilterMultipleTagsConfig(bucketName, metricName, tag1, tag2 string) string { +func testAccBucketMetricConfig_filterMultipleTags(bucketName, metricName, tag1, tag2 string) string { return fmt.Sprintf(` %s @@ -730,7 +730,7 @@ resource "aws_s3_bucket_metric" "test" { `, testAccBucketMetricsBucketConfig(bucketName), metricName, tag1, tag2) } -func testAccBucketMetricsWithFilterSingleTagConfig(bucketName, metricName, tag string) string { +func testAccBucketMetricConfig_filterSingleTag(bucketName, metricName, tag string) string { return fmt.Sprintf(` %s @@ -747,7 +747,7 @@ resource "aws_s3_bucket_metric" "test" { `, testAccBucketMetricsBucketConfig(bucketName), metricName, tag) } -func testAccBucketMetricsWithoutFilterConfig(bucketName, metricName string) string { +func testAccBucketMetricConfig_noFilter(bucketName, metricName string) string { return fmt.Sprintf(` %s diff --git a/internal/service/s3/bucket_notification_test.go b/internal/service/s3/bucket_notification_test.go index 8adc8925325..3bbfbc19642 100644 --- a/internal/service/s3/bucket_notification_test.go +++ b/internal/service/s3/bucket_notification_test.go @@ -28,7 +28,7 @@ func TestAccS3BucketNotification_eventbridge(t *testing.T) { CheckDestroy: testAccCheckBucketNotificationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketNotificationEventBridgeConfig(rName), + Config: testAccBucketNotificationConfig_eventBridge(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketEventBridgeNotification("aws_s3_bucket.bucket")), }, @@ -52,7 +52,7 @@ func TestAccS3BucketNotification_lambdaFunction(t *testing.T) { CheckDestroy: testAccCheckBucketNotificationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketNotificationLambdaFunctionConfig(rName), + Config: testAccBucketNotificationConfig_lambdaFunction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLambdaFunctionConfiguration( "aws_s3_bucket.bucket", @@ -94,7 +94,7 @@ func TestAccS3BucketNotification_LambdaFunctionLambdaFunctionARN_alias(t *testin CheckDestroy: testAccCheckBucketNotificationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketNotificationLambdaFunctionLambdaFunctionARNAliasConfig(rName), + Config: testAccBucketNotificationConfig_lambdaFunctionLambdaFunctionARNAlias(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLambdaFunctionConfiguration( "aws_s3_bucket.test", @@ -125,7 +125,7 @@ func TestAccS3BucketNotification_queue(t *testing.T) { CheckDestroy: testAccCheckBucketNotificationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketNotificationQueueConfig(rName), + Config: testAccBucketNotificationConfig_queue(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketQueueNotification( "aws_s3_bucket.bucket", @@ -167,7 +167,7 @@ func TestAccS3BucketNotification_topic(t *testing.T) { CheckDestroy: testAccCheckBucketNotificationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketNotificationTopicConfig(rName), + Config: testAccBucketNotificationConfig_topic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketTopicNotification( "aws_s3_bucket.bucket", @@ -198,7 +198,7 @@ func TestAccS3BucketNotification_Topic_multiple(t *testing.T) { CheckDestroy: testAccCheckBucketNotificationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketNotificationTopicMultipleConfig(rName), + Config: testAccBucketNotificationConfig_topicMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketTopicNotification( "aws_s3_bucket.bucket", @@ -253,7 +253,7 @@ func TestAccS3BucketNotification_update(t *testing.T) { CheckDestroy: testAccCheckBucketNotificationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketNotificationTopicConfig(rName), + Config: testAccBucketNotificationConfig_topic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketTopicNotification( "aws_s3_bucket.bucket", @@ -265,7 +265,7 @@ func TestAccS3BucketNotification_update(t *testing.T) { ), }, { - Config: testAccBucketNotificationQueueConfig(rName), + Config: testAccBucketNotificationConfig_queue(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketQueueNotification( "aws_s3_bucket.bucket", @@ -527,7 +527,7 @@ func testAccCheckBucketLambdaFunctionConfiguration(n, i, t string, events []stri } } -func testAccBucketNotificationEventBridgeConfig(rName string) string { +func testAccBucketNotificationConfig_eventBridge(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -548,7 +548,7 @@ resource "aws_s3_bucket_notification" "notification" { `, rName) } -func testAccBucketNotificationTopicMultipleConfig(rName string) string { +func testAccBucketNotificationConfig_topicMultiple(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -616,7 +616,7 @@ resource "aws_s3_bucket_notification" "notification" { `, rName) } -func testAccBucketNotificationQueueConfig(rName string) string { +func testAccBucketNotificationConfig_queue(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -671,7 +671,7 @@ resource "aws_s3_bucket_notification" "notification" { `, rName) } -func testAccBucketNotificationLambdaFunctionConfig(rName string) string { +func testAccBucketNotificationConfig_lambdaFunction(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -739,7 +739,7 @@ resource "aws_s3_bucket_notification" "notification" { `, rName) } -func testAccBucketNotificationLambdaFunctionLambdaFunctionARNAliasConfig(rName string) string { +func testAccBucketNotificationConfig_lambdaFunctionLambdaFunctionARNAlias(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -806,7 +806,7 @@ resource "aws_s3_bucket_notification" "test" { `, rName) } -func testAccBucketNotificationTopicConfig(rName string) string { +func testAccBucketNotificationConfig_topic(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/s3/bucket_object_data_source_test.go b/internal/service/s3/bucket_object_data_source_test.go index ba678108ec5..d13321c5d82 100644 --- a/internal/service/s3/bucket_object_data_source_test.go +++ b/internal/service/s3/bucket_object_data_source_test.go @@ -163,7 +163,7 @@ func TestAccS3BucketObjectDataSource_bucketKeyEnabled(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectDataSourceConfig_bucketKeyEnabled(rInt), + Config: testAccBucketObjectDataSourceConfig_keyEnabled(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &rObj), testAccCheckObjectExistsDataSource(dataSourceName, &dsObj), @@ -251,7 +251,7 @@ func TestAccS3BucketObjectDataSource_objectLockLegalHoldOff(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectDataSourceConfig_objectLockLegalHoldOff(rInt), + Config: testAccBucketObjectDataSourceConfig_lockLegalHoldOff(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &rObj), testAccCheckObjectExistsDataSource(dataSourceName, &dsObj), @@ -286,7 +286,7 @@ func TestAccS3BucketObjectDataSource_objectLockLegalHoldOn(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectDataSourceConfig_objectLockLegalHoldOn(rInt, retainUntilDate), + Config: testAccBucketObjectDataSourceConfig_lockLegalHoldOn(rInt, retainUntilDate), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &rObj), testAccCheckObjectExistsDataSource(dataSourceName, &dsObj), @@ -322,13 +322,13 @@ func TestAccS3BucketObjectDataSource_leadingSlash(t *testing.T) { ProviderFactories: acctest.ProviderFactories, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ - { + { // nosemgrep:test-config-funcs-correct-form Config: resourceOnlyConf, Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &rObj), ), }, - { + { // nosemgrep:test-config-funcs-correct-form Config: conf, Check: resource.ComposeTestCheckFunc( testAccCheckObjectExistsDataSource(dataSourceName1, &dsObj1), @@ -376,14 +376,14 @@ func TestAccS3BucketObjectDataSource_multipleSlashes(t *testing.T) { ProviderFactories: acctest.ProviderFactories, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ - { + { // nosemgrep:test-config-funcs-correct-form Config: resourceOnlyConf, Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName1, &rObj1), testAccCheckObjectExists(resourceName2, &rObj2), ), }, - { + { // nosemgrep:test-config-funcs-correct-form Config: conf, Check: resource.ComposeTestCheckFunc( @@ -419,7 +419,7 @@ func TestAccS3BucketObjectDataSource_singleSlashAsKey(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectSingleSlashAsKeyDataSourceConfig(rName), + Config: testAccBucketObjectDataSourceConfig_singleSlashAsKey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExistsDataSource(dataSourceName, &dsObj), ), @@ -517,7 +517,7 @@ data "aws_s3_object" "obj" { `, randInt) } -func testAccBucketObjectDataSourceConfig_bucketKeyEnabled(randInt int) string { +func testAccBucketObjectDataSourceConfig_keyEnabled(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "object_bucket" { bucket = "tf-object-test-bucket-%[1]d" @@ -587,7 +587,7 @@ data "aws_s3_object" "obj" { `, randInt) } -func testAccBucketObjectDataSourceConfig_objectLockLegalHoldOff(randInt int) string { +func testAccBucketObjectDataSourceConfig_lockLegalHoldOff(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "object_bucket" { bucket = "tf-object-test-bucket-%[1]d" @@ -619,7 +619,7 @@ data "aws_s3_object" "obj" { `, randInt) } -func testAccBucketObjectDataSourceConfig_objectLockLegalHoldOn(randInt int, retainUntilDate string) string { +func testAccBucketObjectDataSourceConfig_lockLegalHoldOn(randInt int, retainUntilDate string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "object_bucket" { bucket = "tf-object-test-bucket-%[1]d" @@ -734,7 +734,7 @@ data "aws_s3_object" "obj3" { return resources, both } -func testAccBucketObjectSingleSlashAsKeyDataSourceConfig(rName string) string { +func testAccBucketObjectDataSourceConfig_singleSlashAsKey(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_object_lock_configuration_test.go b/internal/service/s3/bucket_object_lock_configuration_test.go index 71390ea6131..ee212c5b5fc 100644 --- a/internal/service/s3/bucket_object_lock_configuration_test.go +++ b/internal/service/s3/bucket_object_lock_configuration_test.go @@ -26,7 +26,7 @@ func TestAccS3BucketObjectLockConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckBucketObjectLockConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectLockConfigurationBasicConfig(rName), + Config: testAccBucketObjectLockConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectLockConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "object_lock_enabled", s3.ObjectLockEnabledEnabled), @@ -56,7 +56,7 @@ func TestAccS3BucketObjectLockConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketObjectLockConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectLockConfigurationBasicConfig(rName), + Config: testAccBucketObjectLockConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectLockConfigurationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketObjectLockConfiguration(), resourceName), @@ -78,13 +78,13 @@ func TestAccS3BucketObjectLockConfiguration_update(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectLockConfigurationBasicConfig(rName), + Config: testAccBucketObjectLockConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectLockConfigurationExists(resourceName), ), }, { - Config: testAccBucketObjectLockConfigurationUpdateConfig(rName), + Config: testAccBucketObjectLockConfigurationConfig_update(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "object_lock_enabled", s3.ObjectLockEnabledEnabled), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -114,7 +114,7 @@ func TestAccS3BucketObjectLockConfiguration_migrate_noChange(t *testing.T) { CheckDestroy: testAccCheckBucketObjectLockConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_ObjectLockEnabledWithDefaultRetention(rName), + Config: testAccBucketConfig_objectLockEnabledDefaultRetention(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "object_lock_configuration.#", "1"), @@ -125,7 +125,7 @@ func TestAccS3BucketObjectLockConfiguration_migrate_noChange(t *testing.T) { ), }, { - Config: testAccBucketObjectLockConfigurationBasicConfig(rName), + Config: testAccBucketObjectLockConfigurationConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketObjectLockConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "object_lock_enabled", s3.ObjectLockEnabledEnabled), @@ -151,7 +151,7 @@ func TestAccS3BucketObjectLockConfiguration_migrate_withChange(t *testing.T) { CheckDestroy: testAccCheckBucketObjectLockConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_ObjectLockEnabledNoDefaultRetention(rName), + Config: testAccBucketConfig_objectLockEnabledNoDefaultRetention(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "object_lock_configuration.#", "1"), @@ -160,7 +160,7 @@ func TestAccS3BucketObjectLockConfiguration_migrate_withChange(t *testing.T) { ), }, { - Config: testAccBucketObjectLockConfigurationBasicConfig(rName), + Config: testAccBucketObjectLockConfigurationConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketObjectLockConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "object_lock_enabled", s3.ObjectLockEnabledEnabled), @@ -253,7 +253,7 @@ func testAccCheckBucketObjectLockConfigurationExists(resourceName string) resour } } -func testAccBucketObjectLockConfigurationBasicConfig(bucketName string) string { +func testAccBucketObjectLockConfigurationConfig_basic(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -274,7 +274,7 @@ resource "aws_s3_bucket_object_lock_configuration" "test" { `, bucketName, s3.ObjectLockRetentionModeCompliance) } -func testAccBucketObjectLockConfigurationUpdateConfig(bucketName string) string { +func testAccBucketObjectLockConfigurationConfig_update(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_object_test.go b/internal/service/s3/bucket_object_test.go index 40f49930f8d..44e43b793a6 100644 --- a/internal/service/s3/bucket_object_test.go +++ b/internal/service/s3/bucket_object_test.go @@ -41,12 +41,12 @@ func TestAccS3BucketObject_noNameNoKey(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectBasicConfig("", "a key"), + Config: testAccBucketObjectConfig_basic("", "a key"), ExpectError: bucketError, }, { PreConfig: func() {}, - Config: testAccBucketObjectBasicConfig("a name", ""), + Config: testAccBucketObjectConfig_basic("a name", ""), ExpectError: keyError, }, }, @@ -66,7 +66,7 @@ func TestAccS3BucketObject_empty(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectEmptyConfig(rName), + Config: testAccBucketObjectConfig_empty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, ""), @@ -98,7 +98,7 @@ func TestAccS3BucketObject_source(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectSourceConfig(rName, source), + Config: testAccBucketObjectConfig_source(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, "{anything will do }"), @@ -128,7 +128,7 @@ func TestAccS3BucketObject_content(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectContentConfig(rName, "some_bucket_content"), + Config: testAccBucketObjectConfig_content(rName, "some_bucket_content"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, "some_bucket_content"), @@ -160,7 +160,7 @@ func TestAccS3BucketObject_etagEncryption(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectEtagEncryption(rName, source), + Config: testAccBucketObjectConfig_etagEncryption(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, "{anything will do }"), @@ -191,7 +191,7 @@ func TestAccS3BucketObject_contentBase64(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectContentBase64Config(rName, base64.StdEncoding.EncodeToString([]byte("some_bucket_content"))), + Config: testAccBucketObjectConfig_contentBase64(rName, base64.StdEncoding.EncodeToString([]byte("some_bucket_content"))), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, "some_bucket_content"), @@ -272,7 +272,7 @@ func TestAccS3BucketObject_withContentCharacteristics(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectConfig_withContentCharacteristics(rName, source), + Config: testAccBucketObjectConfig_contentCharacteristics(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, "{anything will do }"), @@ -511,7 +511,7 @@ func TestAccS3BucketObject_kms(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withKMSID(rName, source), + Config: testAccBucketObjectConfig_kmsID(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectSSE(resourceName, "aws:kms"), @@ -545,7 +545,7 @@ func TestAccS3BucketObject_sse(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withSSE(rName, source), + Config: testAccBucketObjectConfig_sse(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectSSE(resourceName, "AES256"), @@ -626,7 +626,7 @@ func TestAccS3BucketObject_metadata(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectConfig_withMetadata(rName, "key1", "value1", "key2", "value2"), + Config: testAccBucketObjectConfig_metadata(rName, "key1", "value1", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), resource.TestCheckResourceAttr(resourceName, "metadata.%", "2"), @@ -635,7 +635,7 @@ func TestAccS3BucketObject_metadata(t *testing.T) { ), }, { - Config: testAccBucketObjectConfig_withMetadata(rName, "key1", "value1updated", "key3", "value3"), + Config: testAccBucketObjectConfig_metadata(rName, "key1", "value1updated", "key3", "value3"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), resource.TestCheckResourceAttr(resourceName, "metadata.%", "2"), @@ -644,7 +644,7 @@ func TestAccS3BucketObject_metadata(t *testing.T) { ), }, { - Config: testAccBucketObjectEmptyConfig(rName), + Config: testAccBucketObjectConfig_empty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), resource.TestCheckResourceAttr(resourceName, "metadata.%", "0"), @@ -674,7 +674,7 @@ func TestAccS3BucketObject_storageClass(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectContentConfig(rName, "some_bucket_content"), + Config: testAccBucketObjectConfig_content(rName, "some_bucket_content"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), resource.TestCheckResourceAttr(resourceName, "storage_class", "STANDARD"), @@ -738,7 +738,7 @@ func TestAccS3BucketObject_tags(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_tags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj1), testAccCheckBucketObjectBody(&obj1, "stuff"), @@ -750,7 +750,7 @@ func TestAccS3BucketObject_tags(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withUpdatedTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_updatedTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj2), testAccCheckBucketObjectVersionIdEquals(&obj2, &obj1), @@ -764,7 +764,7 @@ func TestAccS3BucketObject_tags(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withNoTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_noTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj3), testAccCheckBucketObjectVersionIdEquals(&obj3, &obj2), @@ -774,7 +774,7 @@ func TestAccS3BucketObject_tags(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withTags(rName, key, "changed stuff"), + Config: testAccBucketObjectConfig_tags(rName, key, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj4), testAccCheckBucketObjectVersionIdDiffers(&obj4, &obj3), @@ -810,7 +810,7 @@ func TestAccS3BucketObject_tagsLeadingSingleSlash(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_tags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj1), testAccCheckBucketObjectBody(&obj1, "stuff"), @@ -822,7 +822,7 @@ func TestAccS3BucketObject_tagsLeadingSingleSlash(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withUpdatedTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_updatedTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj2), testAccCheckBucketObjectVersionIdEquals(&obj2, &obj1), @@ -836,7 +836,7 @@ func TestAccS3BucketObject_tagsLeadingSingleSlash(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withNoTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_noTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj3), testAccCheckBucketObjectVersionIdEquals(&obj3, &obj2), @@ -846,7 +846,7 @@ func TestAccS3BucketObject_tagsLeadingSingleSlash(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withTags(rName, key, "changed stuff"), + Config: testAccBucketObjectConfig_tags(rName, key, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj4), testAccCheckBucketObjectVersionIdDiffers(&obj4, &obj3), @@ -882,7 +882,7 @@ func TestAccS3BucketObject_tagsLeadingMultipleSlashes(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_tags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj1), testAccCheckBucketObjectBody(&obj1, "stuff"), @@ -894,7 +894,7 @@ func TestAccS3BucketObject_tagsLeadingMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withUpdatedTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_updatedTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj2), testAccCheckBucketObjectVersionIdEquals(&obj2, &obj1), @@ -908,7 +908,7 @@ func TestAccS3BucketObject_tagsLeadingMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withNoTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_noTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj3), testAccCheckBucketObjectVersionIdEquals(&obj3, &obj2), @@ -918,7 +918,7 @@ func TestAccS3BucketObject_tagsLeadingMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withTags(rName, key, "changed stuff"), + Config: testAccBucketObjectConfig_tags(rName, key, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj4), testAccCheckBucketObjectVersionIdDiffers(&obj4, &obj3), @@ -947,7 +947,7 @@ func TestAccS3BucketObject_tagsMultipleSlashes(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_tags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj1), testAccCheckBucketObjectBody(&obj1, "stuff"), @@ -959,7 +959,7 @@ func TestAccS3BucketObject_tagsMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withUpdatedTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_updatedTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj2), testAccCheckBucketObjectVersionIdEquals(&obj2, &obj1), @@ -973,7 +973,7 @@ func TestAccS3BucketObject_tagsMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withNoTags(rName, key, "stuff"), + Config: testAccBucketObjectConfig_noTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj3), testAccCheckBucketObjectVersionIdEquals(&obj3, &obj2), @@ -983,7 +983,7 @@ func TestAccS3BucketObject_tagsMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccBucketObjectConfig_withTags(rName, key, "changed stuff"), + Config: testAccBucketObjectConfig_tags(rName, key, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj4), testAccCheckBucketObjectVersionIdDiffers(&obj4, &obj3), @@ -1010,7 +1010,7 @@ func TestAccS3BucketObject_objectLockLegalHoldStartWithNone(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectConfig_noObjectLockLegalHold(rName, "stuff"), + Config: testAccBucketObjectConfig_noLockLegalHold(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj1), testAccCheckBucketObjectBody(&obj1, "stuff"), @@ -1020,7 +1020,7 @@ func TestAccS3BucketObject_objectLockLegalHoldStartWithNone(t *testing.T) { ), }, { - Config: testAccBucketObjectConfig_withObjectLockLegalHold(rName, "stuff", "ON"), + Config: testAccBucketObjectConfig_lockLegalHold(rName, "stuff", "ON"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj2), testAccCheckBucketObjectVersionIdEquals(&obj2, &obj1), @@ -1032,7 +1032,7 @@ func TestAccS3BucketObject_objectLockLegalHoldStartWithNone(t *testing.T) { }, // Remove legal hold but create a new object version to test force_destroy { - Config: testAccBucketObjectConfig_withObjectLockLegalHold(rName, "changed stuff", "OFF"), + Config: testAccBucketObjectConfig_lockLegalHold(rName, "changed stuff", "OFF"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj3), testAccCheckBucketObjectVersionIdDiffers(&obj3, &obj2), @@ -1058,7 +1058,7 @@ func TestAccS3BucketObject_objectLockLegalHoldStartWithOn(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectConfig_withObjectLockLegalHold(rName, "stuff", "ON"), + Config: testAccBucketObjectConfig_lockLegalHold(rName, "stuff", "ON"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj1), testAccCheckBucketObjectBody(&obj1, "stuff"), @@ -1068,7 +1068,7 @@ func TestAccS3BucketObject_objectLockLegalHoldStartWithOn(t *testing.T) { ), }, { - Config: testAccBucketObjectConfig_withObjectLockLegalHold(rName, "stuff", "OFF"), + Config: testAccBucketObjectConfig_lockLegalHold(rName, "stuff", "OFF"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj2), testAccCheckBucketObjectVersionIdEquals(&obj2, &obj1), @@ -1095,7 +1095,7 @@ func TestAccS3BucketObject_objectLockRetentionStartWithNone(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectConfig_noObjectLockRetention(rName, "stuff"), + Config: testAccBucketObjectConfig_noLockRetention(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj1), testAccCheckBucketObjectBody(&obj1, "stuff"), @@ -1105,7 +1105,7 @@ func TestAccS3BucketObject_objectLockRetentionStartWithNone(t *testing.T) { ), }, { - Config: testAccBucketObjectConfig_withObjectLockRetention(rName, "stuff", retainUntilDate), + Config: testAccBucketObjectConfig_lockRetention(rName, "stuff", retainUntilDate), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj2), testAccCheckBucketObjectVersionIdEquals(&obj2, &obj1), @@ -1117,7 +1117,7 @@ func TestAccS3BucketObject_objectLockRetentionStartWithNone(t *testing.T) { }, // Remove retention period but create a new object version to test force_destroy { - Config: testAccBucketObjectConfig_noObjectLockRetention(rName, "changed stuff"), + Config: testAccBucketObjectConfig_noLockRetention(rName, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj3), testAccCheckBucketObjectVersionIdDiffers(&obj3, &obj2), @@ -1146,7 +1146,7 @@ func TestAccS3BucketObject_objectLockRetentionStartWithSet(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectConfig_withObjectLockRetention(rName, "stuff", retainUntilDate1), + Config: testAccBucketObjectConfig_lockRetention(rName, "stuff", retainUntilDate1), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj1), testAccCheckBucketObjectBody(&obj1, "stuff"), @@ -1156,7 +1156,7 @@ func TestAccS3BucketObject_objectLockRetentionStartWithSet(t *testing.T) { ), }, { - Config: testAccBucketObjectConfig_withObjectLockRetention(rName, "stuff", retainUntilDate2), + Config: testAccBucketObjectConfig_lockRetention(rName, "stuff", retainUntilDate2), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj2), testAccCheckBucketObjectVersionIdEquals(&obj2, &obj1), @@ -1167,7 +1167,7 @@ func TestAccS3BucketObject_objectLockRetentionStartWithSet(t *testing.T) { ), }, { - Config: testAccBucketObjectConfig_withObjectLockRetention(rName, "stuff", retainUntilDate3), + Config: testAccBucketObjectConfig_lockRetention(rName, "stuff", retainUntilDate3), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj3), testAccCheckBucketObjectVersionIdEquals(&obj3, &obj2), @@ -1178,7 +1178,7 @@ func TestAccS3BucketObject_objectLockRetentionStartWithSet(t *testing.T) { ), }, { - Config: testAccBucketObjectConfig_noObjectLockRetention(rName, "stuff"), + Config: testAccBucketObjectConfig_noLockRetention(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj4), testAccCheckBucketObjectVersionIdEquals(&obj4, &obj3), @@ -1204,7 +1204,7 @@ func TestAccS3BucketObject_objectBucketKeyEnabled(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectConfig_objectBucketKeyEnabled(rName, "stuff"), + Config: testAccBucketObjectConfig_objectKeyEnabled(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, "stuff"), @@ -1227,7 +1227,7 @@ func TestAccS3BucketObject_bucketBucketKeyEnabled(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectConfig_bucketBucketKeyEnabled(rName, "stuff"), + Config: testAccBucketObjectConfig_bucketKeyEnabled(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, "stuff"), @@ -1250,7 +1250,7 @@ func TestAccS3BucketObject_defaultBucketSSE(t *testing.T) { CheckDestroy: testAccCheckBucketObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketObjectConfig_defaultBucketSSE(rName, "stuff"), + Config: testAccBucketObjectConfig_defaultSSE(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj1), testAccCheckBucketObjectBody(&obj1, "stuff"), @@ -1277,7 +1277,7 @@ func TestAccS3BucketObject_ignoreTags(t *testing.T) { PreConfig: func() {}, Config: acctest.ConfigCompose( acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey"), - testAccBucketObjectConfig_withNoTags(rName, key, "stuff")), + testAccBucketObjectConfig_noTags(rName, key, "stuff")), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, "stuff"), @@ -1292,7 +1292,7 @@ func TestAccS3BucketObject_ignoreTags(t *testing.T) { PreConfig: func() {}, Config: acctest.ConfigCompose( acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey"), - testAccBucketObjectConfig_withTags(rName, key, "stuff")), + testAccBucketObjectConfig_tags(rName, key, "stuff")), Check: resource.ComposeTestCheckFunc( testAccCheckBucketObjectExists(resourceName, &obj), testAccCheckBucketObjectBody(&obj, "stuff"), @@ -1564,7 +1564,7 @@ func testAccCheckBucketObjectCheckTags(n string, expectedTags map[string]string) } } -func testAccBucketObjectBasicConfig(bucket, key string) string { +func testAccBucketObjectConfig_basic(bucket, key string) string { return fmt.Sprintf(` resource "aws_s3_bucket_object" "object" { bucket = %[1]q @@ -1573,7 +1573,7 @@ resource "aws_s3_bucket_object" "object" { `, bucket, key) } -func testAccBucketObjectEmptyConfig(rName string) string { +func testAccBucketObjectConfig_empty(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1586,7 +1586,7 @@ resource "aws_s3_bucket_object" "object" { `, rName) } -func testAccBucketObjectSourceConfig(rName string, source string) string { +func testAccBucketObjectConfig_source(rName string, source string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1601,7 +1601,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, source) } -func testAccBucketObjectConfig_withContentCharacteristics(rName string, source string) string { +func testAccBucketObjectConfig_contentCharacteristics(rName string, source string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1618,7 +1618,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, source) } -func testAccBucketObjectContentConfig(rName string, content string) string { +func testAccBucketObjectConfig_content(rName string, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1632,7 +1632,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, content) } -func testAccBucketObjectEtagEncryption(rName string, source string) string { +func testAccBucketObjectConfig_etagEncryption(rName string, source string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1648,7 +1648,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, source) } -func testAccBucketObjectContentBase64Config(rName string, contentBase64 string) string { +func testAccBucketObjectConfig_contentBase64(rName string, contentBase64 string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1732,7 +1732,7 @@ resource "aws_s3_bucket_object" "test" { `, rName, bucketVersioning, source) } -func testAccBucketObjectConfig_withKMSID(rName string, source string) string { +func testAccBucketObjectConfig_kmsID(rName string, source string) string { return fmt.Sprintf(` resource "aws_kms_key" "kms_key_1" {} @@ -1749,7 +1749,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, source) } -func testAccBucketObjectConfig_withSSE(rName string, source string) string { +func testAccBucketObjectConfig_sse(rName string, source string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1804,7 +1804,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, storage_class) } -func testAccBucketObjectConfig_withTags(rName, key, content string) string { +func testAccBucketObjectConfig_tags(rName, key, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1834,7 +1834,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, key, content) } -func testAccBucketObjectConfig_withUpdatedTags(rName, key, content string) string { +func testAccBucketObjectConfig_updatedTags(rName, key, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1865,7 +1865,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, key, content) } -func testAccBucketObjectConfig_withNoTags(rName, key, content string) string { +func testAccBucketObjectConfig_noTags(rName, key, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1889,7 +1889,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, key, content) } -func testAccBucketObjectConfig_withMetadata(rName string, metadataKey1, metadataValue1, metadataKey2, metadataValue2 string) string { +func testAccBucketObjectConfig_metadata(rName string, metadataKey1, metadataValue1, metadataKey2, metadataValue2 string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1907,7 +1907,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, metadataKey1, metadataValue1, metadataKey2, metadataValue2) } -func testAccBucketObjectConfig_noObjectLockLegalHold(rName string, content string) string { +func testAccBucketObjectConfig_noLockLegalHold(rName string, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1934,7 +1934,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, content) } -func testAccBucketObjectConfig_withObjectLockLegalHold(rName string, content, legalHoldStatus string) string { +func testAccBucketObjectConfig_lockLegalHold(rName string, content, legalHoldStatus string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1962,7 +1962,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, content, legalHoldStatus) } -func testAccBucketObjectConfig_noObjectLockRetention(rName string, content string) string { +func testAccBucketObjectConfig_noLockRetention(rName string, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1989,7 +1989,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, content) } -func testAccBucketObjectConfig_withObjectLockRetention(rName string, content, retainUntilDate string) string { +func testAccBucketObjectConfig_lockRetention(rName string, content, retainUntilDate string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -2054,7 +2054,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, source) } -func testAccBucketObjectConfig_objectBucketKeyEnabled(rName string, content string) string { +func testAccBucketObjectConfig_objectKeyEnabled(rName string, content string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Encrypts test objects" @@ -2075,7 +2075,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, content) } -func testAccBucketObjectConfig_bucketBucketKeyEnabled(rName string, content string) string { +func testAccBucketObjectConfig_bucketKeyEnabled(rName string, content string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Encrypts test objects" @@ -2109,7 +2109,7 @@ resource "aws_s3_bucket_object" "object" { `, rName, content) } -func testAccBucketObjectConfig_defaultBucketSSE(rName string, content string) string { +func testAccBucketObjectConfig_defaultSSE(rName string, content string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Encrypts test objects" diff --git a/internal/service/s3/bucket_objects_data_source_test.go b/internal/service/s3/bucket_objects_data_source_test.go index 1cd9eb443f3..2a9a25594b6 100644 --- a/internal/service/s3/bucket_objects_data_source_test.go +++ b/internal/service/s3/bucket_objects_data_source_test.go @@ -24,11 +24,11 @@ func TestAccS3BucketObjectsDataSource_basic(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccBucketObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccBucketObjectsBasicDataSourceConfig(rInt), + Config: testAccBucketObjectsDataSourceConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -50,11 +50,11 @@ func TestAccS3BucketObjectsDataSource_basicViaAccessPoint(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectsResourcesPlusAccessPointDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccBucketObjectsDataSourceConfig_resourcesPlusAccessPoint(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccBucketObjectsBasicViaAccessPointDataSourceConfig(rInt), + Config: testAccBucketObjectsDataSourceConfig_basicViaAccessPoint(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -76,11 +76,11 @@ func TestAccS3BucketObjectsDataSource_all(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccBucketObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccBucketObjectsAllDataSourceConfig(rInt), + Config: testAccBucketObjectsDataSourceConfig_all(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "7"), @@ -107,11 +107,11 @@ func TestAccS3BucketObjectsDataSource_prefixes(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccBucketObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccBucketObjectsPrefixesDataSourceConfig(rInt), + Config: testAccBucketObjectsDataSourceConfig_prefixes(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "1"), @@ -137,11 +137,11 @@ func TestAccS3BucketObjectsDataSource_encoded(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectsExtraResourceDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccBucketObjectsDataSourceConfig_extraResource(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccBucketObjectsEncodedDataSourceConfig(rInt), + Config: testAccBucketObjectsDataSourceConfig_encoded(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -163,11 +163,11 @@ func TestAccS3BucketObjectsDataSource_maxKeys(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccBucketObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccBucketObjectsMaxKeysDataSourceConfig(rInt), + Config: testAccBucketObjectsDataSourceConfig_maxKeys(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -189,11 +189,11 @@ func TestAccS3BucketObjectsDataSource_startAfter(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccBucketObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccBucketObjectsStartAfterDataSourceConfig(rInt), + Config: testAccBucketObjectsDataSourceConfig_startAfter(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "1"), @@ -214,11 +214,11 @@ func TestAccS3BucketObjectsDataSource_fetchOwner(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccBucketObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccBucketObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccBucketObjectsOwnersDataSourceConfig(rInt), + Config: testAccBucketObjectsDataSourceConfig_owners(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -229,7 +229,7 @@ func TestAccS3BucketObjectsDataSource_fetchOwner(t *testing.T) { }) } -func testAccBucketObjectsResourcesDataSourceConfig(randInt int) string { +func testAccBucketObjectsDataSourceConfig_resources(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "objects_bucket" { bucket = "tf-acc-objects-test-bucket-%d" @@ -279,8 +279,8 @@ resource "aws_s3_object" "object7" { `, randInt) } -func testAccBucketObjectsResourcesPlusAccessPointDataSourceConfig(randInt int) string { - return testAccBucketObjectsResourcesDataSourceConfig(randInt) + fmt.Sprintf(` +func testAccBucketObjectsDataSourceConfig_resourcesPlusAccessPoint(randInt int) string { + return testAccBucketObjectsDataSourceConfig_resources(randInt) + fmt.Sprintf(` resource "aws_s3_access_point" "test" { bucket = aws_s3_bucket.objects_bucket.bucket name = "tf-objects-test-access-point-%[1]d" @@ -288,7 +288,7 @@ resource "aws_s3_access_point" "test" { `, randInt) } -func testAccBucketObjectsBasicDataSourceConfig(randInt int) string { +func testAccBucketObjectsDataSourceConfig_basic(randInt int) string { return fmt.Sprintf(` %s @@ -297,11 +297,11 @@ data "aws_s3_objects" "yesh" { prefix = "arch/navajo/" delimiter = "/" } -`, testAccBucketObjectsResourcesDataSourceConfig(randInt)) +`, testAccBucketObjectsDataSourceConfig_resources(randInt)) } -func testAccBucketObjectsBasicViaAccessPointDataSourceConfig(randInt int) string { - return testAccBucketObjectsResourcesPlusAccessPointDataSourceConfig(randInt) + ` +func testAccBucketObjectsDataSourceConfig_basicViaAccessPoint(randInt int) string { + return testAccBucketObjectsDataSourceConfig_resourcesPlusAccessPoint(randInt) + ` data "aws_s3_objects" "yesh" { bucket = aws_s3_access_point.test.arn prefix = "arch/navajo/" @@ -310,17 +310,17 @@ data "aws_s3_objects" "yesh" { ` } -func testAccBucketObjectsAllDataSourceConfig(randInt int) string { +func testAccBucketObjectsDataSourceConfig_all(randInt int) string { return fmt.Sprintf(` %s data "aws_s3_objects" "yesh" { bucket = aws_s3_bucket.objects_bucket.id } -`, testAccBucketObjectsResourcesDataSourceConfig(randInt)) +`, testAccBucketObjectsDataSourceConfig_resources(randInt)) } -func testAccBucketObjectsPrefixesDataSourceConfig(randInt int) string { +func testAccBucketObjectsDataSourceConfig_prefixes(randInt int) string { return fmt.Sprintf(` %s @@ -329,10 +329,10 @@ data "aws_s3_objects" "yesh" { prefix = "arch/" delimiter = "/" } -`, testAccBucketObjectsResourcesDataSourceConfig(randInt)) +`, testAccBucketObjectsDataSourceConfig_resources(randInt)) } -func testAccBucketObjectsExtraResourceDataSourceConfig(randInt int) string { +func testAccBucketObjectsDataSourceConfig_extraResource(randInt int) string { return fmt.Sprintf(` %s @@ -341,10 +341,10 @@ resource "aws_s3_object" "object8" { key = "arch/ru b ic on" content = "Goose Island" } -`, testAccBucketObjectsResourcesDataSourceConfig(randInt)) +`, testAccBucketObjectsDataSourceConfig_resources(randInt)) } -func testAccBucketObjectsEncodedDataSourceConfig(randInt int) string { +func testAccBucketObjectsDataSourceConfig_encoded(randInt int) string { return fmt.Sprintf(` %s @@ -353,10 +353,10 @@ data "aws_s3_objects" "yesh" { encoding_type = "url" prefix = "arch/ru" } -`, testAccBucketObjectsExtraResourceDataSourceConfig(randInt)) +`, testAccBucketObjectsDataSourceConfig_extraResource(randInt)) } -func testAccBucketObjectsMaxKeysDataSourceConfig(randInt int) string { +func testAccBucketObjectsDataSourceConfig_maxKeys(randInt int) string { return fmt.Sprintf(` %s @@ -364,10 +364,10 @@ data "aws_s3_objects" "yesh" { bucket = aws_s3_bucket.objects_bucket.id max_keys = 2 } -`, testAccBucketObjectsResourcesDataSourceConfig(randInt)) +`, testAccBucketObjectsDataSourceConfig_resources(randInt)) } -func testAccBucketObjectsStartAfterDataSourceConfig(randInt int) string { +func testAccBucketObjectsDataSourceConfig_startAfter(randInt int) string { return fmt.Sprintf(` %s @@ -375,10 +375,10 @@ data "aws_s3_objects" "yesh" { bucket = aws_s3_bucket.objects_bucket.id start_after = "arch/three_gossips/broken" } -`, testAccBucketObjectsResourcesDataSourceConfig(randInt)) +`, testAccBucketObjectsDataSourceConfig_resources(randInt)) } -func testAccBucketObjectsOwnersDataSourceConfig(randInt int) string { +func testAccBucketObjectsDataSourceConfig_owners(randInt int) string { return fmt.Sprintf(` %s @@ -387,5 +387,5 @@ data "aws_s3_objects" "yesh" { prefix = "arch/three_gossips/" fetch_owner = true } -`, testAccBucketObjectsResourcesDataSourceConfig(randInt)) +`, testAccBucketObjectsDataSourceConfig_resources(randInt)) } diff --git a/internal/service/s3/bucket_ownership_controls_test.go b/internal/service/s3/bucket_ownership_controls_test.go index 9b75ef57a05..95942c062cc 100644 --- a/internal/service/s3/bucket_ownership_controls_test.go +++ b/internal/service/s3/bucket_ownership_controls_test.go @@ -26,7 +26,7 @@ func TestAccS3BucketOwnershipControls_basic(t *testing.T) { CheckDestroy: testAccCheckBucketOwnershipControlsDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketOwnershipControlsConfig_Rule_ObjectOwnership(rName, s3.ObjectOwnershipBucketOwnerPreferred), + Config: testAccBucketOwnershipControlsConfig_ruleObject(rName, s3.ObjectOwnershipBucketOwnerPreferred), Check: resource.ComposeTestCheckFunc( testAccCheckBucketOwnershipControlsExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bucket", rName), @@ -54,7 +54,7 @@ func TestAccS3BucketOwnershipControls_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketOwnershipControlsDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketOwnershipControlsConfig_Rule_ObjectOwnership(rName, s3.ObjectOwnershipBucketOwnerPreferred), + Config: testAccBucketOwnershipControlsConfig_ruleObject(rName, s3.ObjectOwnershipBucketOwnerPreferred), Check: resource.ComposeTestCheckFunc( testAccCheckBucketOwnershipControlsExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketOwnershipControls(), resourceName), @@ -77,7 +77,7 @@ func TestAccS3BucketOwnershipControls_Disappears_bucket(t *testing.T) { CheckDestroy: testAccCheckBucketOwnershipControlsDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketOwnershipControlsConfig_Rule_ObjectOwnership(rName, s3.ObjectOwnershipBucketOwnerPreferred), + Config: testAccBucketOwnershipControlsConfig_ruleObject(rName, s3.ObjectOwnershipBucketOwnerPreferred), Check: resource.ComposeTestCheckFunc( testAccCheckBucketOwnershipControlsExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucket(), s3BucketResourceName), @@ -99,7 +99,7 @@ func TestAccS3BucketOwnershipControls_Rule_objectOwnership(t *testing.T) { CheckDestroy: testAccCheckBucketOwnershipControlsDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketOwnershipControlsConfig_Rule_ObjectOwnership(rName, s3.ObjectOwnershipObjectWriter), + Config: testAccBucketOwnershipControlsConfig_ruleObject(rName, s3.ObjectOwnershipObjectWriter), Check: resource.ComposeTestCheckFunc( testAccCheckBucketOwnershipControlsExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bucket", rName), @@ -113,7 +113,7 @@ func TestAccS3BucketOwnershipControls_Rule_objectOwnership(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketOwnershipControlsConfig_Rule_ObjectOwnership(rName, s3.ObjectOwnershipBucketOwnerPreferred), + Config: testAccBucketOwnershipControlsConfig_ruleObject(rName, s3.ObjectOwnershipBucketOwnerPreferred), Check: resource.ComposeTestCheckFunc( testAccCheckBucketOwnershipControlsExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bucket", rName), @@ -184,7 +184,7 @@ func testAccCheckBucketOwnershipControlsExists(resourceName string) resource.Tes } } -func testAccBucketOwnershipControlsConfig_Rule_ObjectOwnership(rName, objectOwnership string) string { +func testAccBucketOwnershipControlsConfig_ruleObject(rName, objectOwnership string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_policy_data_source_test.go b/internal/service/s3/bucket_policy_data_source_test.go index 2264fef3fd3..9da304598aa 100644 --- a/internal/service/s3/bucket_policy_data_source_test.go +++ b/internal/service/s3/bucket_policy_data_source_test.go @@ -26,7 +26,7 @@ func TestAccS3BucketPolicyDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccDataSourceBucketPolicyConfigBasicConfig(rName), + Config: testAccBucketPolicyDataSourceConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketPolicyExists(resourceName, &conf), testAccCheckBucketPolicyMatch(dataSourceName, "policy", resourceName, "policy"), @@ -137,7 +137,7 @@ data "aws_iam_policy_document" "test" { `, rName) } -func testAccDataSourceBucketPolicyConfigBasicConfig(rName string) string { +func testAccBucketPolicyDataSourceConfig_basic(rName string) string { return acctest.ConfigCompose(testAccDataSourceBucketPolicyBaseConfig(rName), ` data "aws_s3_bucket_policy" "test" { bucket = aws_s3_bucket.test.id diff --git a/internal/service/s3/bucket_policy_test.go b/internal/service/s3/bucket_policy_test.go index 9b4a3f42209..6fde912446e 100644 --- a/internal/service/s3/bucket_policy_test.go +++ b/internal/service/s3/bucket_policy_test.go @@ -45,7 +45,7 @@ func TestAccS3BucketPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyConfig(name), + Config: testAccBucketPolicyConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists("aws_s3_bucket.bucket"), testAccCheckBucketHasPolicy("aws_s3_bucket.bucket", expectedPolicyText), @@ -91,7 +91,7 @@ func TestAccS3BucketPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyConfig(name), + Config: testAccBucketPolicyConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), testAccCheckBucketHasPolicy(bucketResourceName, expectedPolicyText), @@ -133,7 +133,7 @@ func TestAccS3BucketPolicy_disappears_bucket(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyConfig(name), + Config: testAccBucketPolicyConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), testAccCheckBucketHasPolicy(bucketResourceName, expectedPolicyText), @@ -196,7 +196,7 @@ func TestAccS3BucketPolicy_policyUpdate(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyConfig(name), + Config: testAccBucketPolicyConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists("aws_s3_bucket.bucket"), testAccCheckBucketHasPolicy("aws_s3_bucket.bucket", expectedPolicyText1), @@ -232,21 +232,21 @@ func TestAccS3BucketPolicy_IAMRoleOrder_policyDoc(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyIAMRoleOrderIAMPolicyDocConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderIAMDoc(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), }, { - Config: testAccBucketPolicyIAMRoleOrderIAMPolicyDocConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderIAMDoc(rName), PlanOnly: true, }, { - Config: testAccBucketPolicyIAMRoleOrderIAMPolicyDocConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderIAMDoc(rName), PlanOnly: true, }, { - Config: testAccBucketPolicyIAMRoleOrderIAMPolicyDocConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderIAMDoc(rName), PlanOnly: true, }, }, @@ -266,23 +266,23 @@ func TestAccS3BucketPolicy_IAMRoleOrder_policyDocNotPrincipal(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyIAMRoleOrderIAMPolicyDocNotPrincipalConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderIAMDocNotPrincipal(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), }, { - Config: testAccBucketPolicyIAMRoleOrderIAMPolicyDocNotPrincipalConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderIAMDocNotPrincipal(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), }, { - Config: testAccBucketPolicyIAMRoleOrderIAMPolicyDocNotPrincipalConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderIAMDocNotPrincipal(rName), PlanOnly: true, }, { - Config: testAccBucketPolicyIAMRoleOrderIAMPolicyDocNotPrincipalConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderIAMDocNotPrincipal(rName), PlanOnly: true, }, }, @@ -303,33 +303,33 @@ func TestAccS3BucketPolicy_IAMRoleOrder_jsonEncode(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyIAMRoleOrderJSONEncodeConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderJSONEncode(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), }, { - Config: testAccBucketPolicyIAMRoleOrderJSONEncodeConfig(rName), + Config: testAccBucketPolicyConfig_iamRoleOrderJSONEncode(rName), PlanOnly: true, }, { - Config: testAccBucketPolicyIAMRoleOrderJSONEncodeOrder2Config(rName2), + Config: testAccBucketPolicyConfig_iamRoleOrderJSONEncodeOrder2(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), }, { - Config: testAccBucketPolicyIAMRoleOrderJSONEncodeConfig(rName2), + Config: testAccBucketPolicyConfig_iamRoleOrderJSONEncode(rName2), PlanOnly: true, }, { - Config: testAccBucketPolicyIAMRoleOrderJSONEncodeOrder3Config(rName3), + Config: testAccBucketPolicyConfig_iamRoleOrderJSONEncodeOrder3(rName3), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), }, { - Config: testAccBucketPolicyIAMRoleOrderJSONEncodeConfig(rName3), + Config: testAccBucketPolicyConfig_iamRoleOrderJSONEncode(rName3), PlanOnly: true, }, }, @@ -349,14 +349,14 @@ func TestAccS3BucketPolicy_migrate_noChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withPolicy(rName, partition), + Config: testAccBucketConfig_policy(rName, partition), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), testAccCheckBucketPolicy(bucketResourceName, testAccBucketPolicy(rName, partition)), ), }, { - Config: testAccBucketPolicy_Migrate_NoChangeConfig(rName, partition), + Config: testAccBucketPolicyConfig_migrateNoChange(rName, partition), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), testAccCheckBucketPolicy(resourceName, testAccBucketPolicy(rName, partition)), @@ -379,14 +379,14 @@ func TestAccS3BucketPolicy_migrate_withChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withPolicy(rName, partition), + Config: testAccBucketConfig_policy(rName, partition), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), testAccCheckBucketPolicy(bucketResourceName, testAccBucketPolicy(rName, partition)), ), }, { - Config: testAccBucketPolicy_Migrate_WithChangeConfig(rName, partition), + Config: testAccBucketPolicyConfig_migrateChange(rName, partition), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(resourceName), testAccCheckBucketPolicy(resourceName, testAccBucketPolicyUpdated(rName, partition)), @@ -431,7 +431,7 @@ func testAccCheckBucketHasPolicy(n string, expectedPolicyText string) resource.T } } -func testAccBucketPolicyConfig(bucketName string) string { +func testAccBucketPolicyConfig_basic(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "bucket" { bucket = %[1]q @@ -596,7 +596,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccBucketPolicyIAMRoleOrderIAMPolicyDocConfig(rName string) string { +func testAccBucketPolicyConfig_iamRoleOrderIAMDoc(rName string) string { return acctest.ConfigCompose( testAccBucketPolicyIAMRoleOrderBaseConfig(rName), fmt.Sprintf(` @@ -634,7 +634,7 @@ resource "aws_s3_bucket_policy" "bucket" { `, rName)) } -func testAccBucketPolicyIAMRoleOrderJSONEncodeConfig(rName string) string { +func testAccBucketPolicyConfig_iamRoleOrderJSONEncode(rName string) string { return acctest.ConfigCompose( testAccBucketPolicyIAMRoleOrderBaseConfig(rName), fmt.Sprintf(` @@ -671,7 +671,7 @@ resource "aws_s3_bucket_policy" "bucket" { `, rName)) } -func testAccBucketPolicyIAMRoleOrderJSONEncodeOrder2Config(rName string) string { +func testAccBucketPolicyConfig_iamRoleOrderJSONEncodeOrder2(rName string) string { return acctest.ConfigCompose( testAccBucketPolicyIAMRoleOrderBaseConfig(rName), fmt.Sprintf(` @@ -708,7 +708,7 @@ resource "aws_s3_bucket_policy" "bucket" { `, rName)) } -func testAccBucketPolicyIAMRoleOrderJSONEncodeOrder3Config(rName string) string { +func testAccBucketPolicyConfig_iamRoleOrderJSONEncodeOrder3(rName string) string { return acctest.ConfigCompose( testAccBucketPolicyIAMRoleOrderBaseConfig(rName), fmt.Sprintf(` @@ -745,7 +745,7 @@ resource "aws_s3_bucket_policy" "bucket" { `, rName)) } -func testAccBucketPolicyIAMRoleOrderIAMPolicyDocNotPrincipalConfig(rName string) string { +func testAccBucketPolicyConfig_iamRoleOrderIAMDocNotPrincipal(rName string) string { return acctest.ConfigCompose( testAccBucketPolicyIAMRoleOrderBaseConfig(rName), ` @@ -788,7 +788,7 @@ resource "aws_s3_bucket_policy" "bucket" { `) } -func testAccBucketPolicy_Migrate_NoChangeConfig(bucketName, partition string) string { +func testAccBucketPolicyConfig_migrateNoChange(bucketName, partition string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -806,7 +806,7 @@ resource "aws_s3_bucket_policy" "test" { `, bucketName, strconv.Quote(testAccBucketPolicy(bucketName, partition))) } -func testAccBucketPolicy_Migrate_WithChangeConfig(bucketName, partition string) string { +func testAccBucketPolicyConfig_migrateChange(bucketName, partition string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_public_access_block.go b/internal/service/s3/bucket_public_access_block.go index 613b338d318..9af056173e3 100644 --- a/internal/service/s3/bucket_public_access_block.go +++ b/internal/service/s3/bucket_public_access_block.go @@ -173,19 +173,6 @@ func resourceBucketPublicAccessBlockUpdate(d *schema.ResourceData, meta interfac log.Printf("[DEBUG] Updating S3 bucket Public Access Block: %s", input) _, err := conn.PutPublicAccessBlock(input) - - if tfawserr.ErrCodeEquals(err, ErrCodeNoSuchPublicAccessBlockConfiguration) { - log.Printf("[WARN] S3 Bucket Public Access Block (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - - if tfawserr.ErrCodeEquals(err, s3.ErrCodeNoSuchBucket) { - log.Printf("[WARN] S3 Bucket (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - if err != nil { return fmt.Errorf("error updating S3 Bucket Public Access Block (%s): %s", d.Id(), err) } diff --git a/internal/service/s3/bucket_public_access_block_test.go b/internal/service/s3/bucket_public_access_block_test.go index c76093995bb..999b471e5a8 100644 --- a/internal/service/s3/bucket_public_access_block_test.go +++ b/internal/service/s3/bucket_public_access_block_test.go @@ -28,7 +28,7 @@ func TestAccS3BucketPublicAccessBlock_basic(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists("aws_s3_bucket.bucket"), testAccCheckBucketPublicAccessBlockExists(resourceName, &config), @@ -60,7 +60,7 @@ func TestAccS3BucketPublicAccessBlock_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config), testAccCheckBucketPublicAccessBlockDisappears(resourceName), @@ -84,7 +84,7 @@ func TestAccS3BucketPublicAccessBlock_Disappears_bucket(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucket(), bucketResourceName), @@ -107,7 +107,7 @@ func TestAccS3BucketPublicAccessBlock_blockPublicACLs(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPublicAccessBlockConfig(name, "true", "false", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "true", "false", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config1), resource.TestCheckResourceAttr(resourceName, "block_public_acls", "true"), @@ -119,14 +119,14 @@ func TestAccS3BucketPublicAccessBlock_blockPublicACLs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config2), resource.TestCheckResourceAttr(resourceName, "block_public_acls", "false"), ), }, { - Config: testAccBucketPublicAccessBlockConfig(name, "true", "false", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "true", "false", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config3), resource.TestCheckResourceAttr(resourceName, "block_public_acls", "true"), @@ -148,7 +148,7 @@ func TestAccS3BucketPublicAccessBlock_blockPublicPolicy(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "true", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "true", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config1), resource.TestCheckResourceAttr(resourceName, "block_public_policy", "true"), @@ -160,14 +160,14 @@ func TestAccS3BucketPublicAccessBlock_blockPublicPolicy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config2), resource.TestCheckResourceAttr(resourceName, "block_public_policy", "false"), ), }, { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "true", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "true", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config3), resource.TestCheckResourceAttr(resourceName, "block_public_policy", "true"), @@ -189,7 +189,7 @@ func TestAccS3BucketPublicAccessBlock_ignorePublicACLs(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "true", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "true", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config1), resource.TestCheckResourceAttr(resourceName, "ignore_public_acls", "true"), @@ -201,14 +201,14 @@ func TestAccS3BucketPublicAccessBlock_ignorePublicACLs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config2), resource.TestCheckResourceAttr(resourceName, "ignore_public_acls", "false"), ), }, { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "true", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "true", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config3), resource.TestCheckResourceAttr(resourceName, "ignore_public_acls", "true"), @@ -230,7 +230,7 @@ func TestAccS3BucketPublicAccessBlock_restrictPublicBuckets(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "false", "true"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "false", "true"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config1), resource.TestCheckResourceAttr(resourceName, "restrict_public_buckets", "true"), @@ -242,14 +242,14 @@ func TestAccS3BucketPublicAccessBlock_restrictPublicBuckets(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "false", "false"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "false", "false"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config2), resource.TestCheckResourceAttr(resourceName, "restrict_public_buckets", "false"), ), }, { - Config: testAccBucketPublicAccessBlockConfig(name, "false", "false", "false", "true"), + Config: testAccBucketPublicAccessBlockConfig_basic(name, "false", "false", "false", "true"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPublicAccessBlockExists(resourceName, &config3), resource.TestCheckResourceAttr(resourceName, "restrict_public_buckets", "true"), @@ -347,7 +347,7 @@ func testAccCheckBucketPublicAccessBlockDisappears(n string) resource.TestCheckF } } -func testAccBucketPublicAccessBlockConfig(bucketName, blockPublicAcls, blockPublicPolicy, ignorePublicAcls, restrictPublicBuckets string) string { +func testAccBucketPublicAccessBlockConfig_basic(bucketName, blockPublicAcls, blockPublicPolicy, ignorePublicAcls, restrictPublicBuckets string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "bucket" { bucket = %[1]q diff --git a/internal/service/s3/bucket_replication_configuration_test.go b/internal/service/s3/bucket_replication_configuration_test.go index 81d3b5207a7..f4959c90e8c 100644 --- a/internal/service/s3/bucket_replication_configuration_test.go +++ b/internal/service/s3/bucket_replication_configuration_test.go @@ -37,7 +37,7 @@ func TestAccS3BucketReplicationConfiguration_basic(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationBasic(rName, s3.StorageClassStandard), + Config: testAccBucketReplicationConfigurationConfig_basic(rName, s3.StorageClassStandard), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -53,7 +53,7 @@ func TestAccS3BucketReplicationConfiguration_basic(t *testing.T) { ), }, { - Config: testAccBucketReplicationConfigurationBasic(rName, s3.StorageClassGlacier), + Config: testAccBucketReplicationConfigurationConfig_basic(rName, s3.StorageClassGlacier), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -108,7 +108,7 @@ func TestAccS3BucketReplicationConfiguration_disappears(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationBasic(rName, s3.StorageClassStandard), + Config: testAccBucketReplicationConfigurationConfig_basic(rName, s3.StorageClassStandard), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketReplicationConfiguration(), resourceName), @@ -136,7 +136,7 @@ func TestAccS3BucketReplicationConfiguration_multipleDestinationsEmptyFilter(t * CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationWithMultipleDestinationsEmptyFilter(rName), + Config: testAccBucketReplicationConfigurationConfig_multipleDestinationsEmptyFilter(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "3"), @@ -195,7 +195,7 @@ func TestAccS3BucketReplicationConfiguration_multipleDestinationsNonEmptyFilter( CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationWithMultipleDestinationsNonEmptyFilter(rName), + Config: testAccBucketReplicationConfigurationConfig_multipleDestinationsNonEmptyFilter(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "3"), @@ -260,7 +260,7 @@ func TestAccS3BucketReplicationConfiguration_twoDestination(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationWithMultipleDestinationsTwoDestination(rName), + Config: testAccBucketReplicationConfigurationConfig_multipleDestinationsTwoDestination(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "2"), @@ -314,7 +314,7 @@ func TestAccS3BucketReplicationConfiguration_configurationRuleDestinationAccessC CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationWithAccessControlTranslation(rName), + Config: testAccBucketReplicationConfigurationConfig_accessControlTranslation(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -391,7 +391,7 @@ func TestAccS3BucketReplicationConfiguration_configurationRuleDestinationAddAcce CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationRulesDestination(rName), + Config: testAccBucketReplicationConfigurationConfig_rulesDestination(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -413,7 +413,7 @@ func TestAccS3BucketReplicationConfiguration_configurationRuleDestinationAddAcce ImportStateVerify: true, }, { - Config: testAccBucketReplicationConfigurationWithAccessControlTranslation(rName), + Config: testAccBucketReplicationConfigurationConfig_accessControlTranslation(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -459,7 +459,7 @@ func TestAccS3BucketReplicationConfiguration_replicationTimeControl(t *testing.T CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationRTC(rName), + Config: testAccBucketReplicationConfigurationConfig_rtc(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -512,7 +512,7 @@ func TestAccS3BucketReplicationConfiguration_replicaModifications(t *testing.T) CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationReplicaMods(rName), + Config: testAccBucketReplicationConfigurationConfig_replicaMods(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -560,7 +560,7 @@ func TestAccS3BucketReplicationConfiguration_withoutId(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfiguration_prefix_withoutIdConfig(rName), + Config: testAccBucketReplicationConfigurationConfig_prefixNoID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -601,7 +601,7 @@ func TestAccS3BucketReplicationConfiguration_withoutStorageClass(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationWithoutStorageClass(rName), + Config: testAccBucketReplicationConfigurationConfig_noStorageClass(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -643,7 +643,7 @@ func TestAccS3BucketReplicationConfiguration_schemaV2(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationWithV2ConfigurationNoTags(rName), + Config: testAccBucketReplicationConfigurationConfig_v2NoTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -687,7 +687,7 @@ func TestAccS3BucketReplicationConfiguration_schemaV2SameRegion(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfiguration_schemaV2SameRegion(rName, rNameDestination), + Config: testAccBucketReplicationConfigurationConfig_schemaV2SameRegion(rName, rNameDestination), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -731,7 +731,7 @@ func TestAccS3BucketReplicationConfiguration_schemaV2DestinationMetrics(t *testi CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfiguration_schemaV2DestinationMetrics_statusOnly(rName, s3.StorageClassStandard), + Config: testAccBucketReplicationConfigurationConfig_schemaV2DestinationMetricsStatusOnly(rName, s3.StorageClassStandard), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ @@ -770,7 +770,7 @@ func TestAccS3BucketReplicationConfiguration_existingObjectReplication(t *testin CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfiguration_existingObjectReplication(rName, rNameDestination), + Config: testAccBucketReplicationConfigurationConfig_existingObject(rName, rNameDestination), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -816,7 +816,7 @@ func TestAccS3BucketReplicationConfiguration_filter_emptyConfigurationBlock(t *t CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfiguration_filter_emptyConfigurationBlock(rName), + Config: testAccBucketReplicationConfigurationConfig_filterEmptyBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -858,7 +858,7 @@ func TestAccS3BucketReplicationConfiguration_filter_emptyPrefix(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfiguration_filter_emptyPrefix(rName), + Config: testAccBucketReplicationConfigurationConfig_filterEmptyPrefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -904,7 +904,7 @@ func TestAccS3BucketReplicationConfiguration_filter_tagFilter(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfiguration_filter_tag(rName, "testkey", "testvalue"), + Config: testAccBucketReplicationConfigurationConfig_filterTag(rName, "testkey", "testvalue"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -948,7 +948,7 @@ func TestAccS3BucketReplicationConfiguration_filter_andOperator(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfiguration_filter_andOperator_prefixAndTags(rName, "testkey1", "testvalue1", "testkey2", "testvalue2"), + Config: testAccBucketReplicationConfigurationConfig_filterAndOperatorPrefixAndTags(rName, "testkey1", "testvalue1", "testkey2", "testvalue2"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -975,7 +975,7 @@ func TestAccS3BucketReplicationConfiguration_filter_andOperator(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketReplicationConfiguration_filter_andOperator_tags(rName, "testkey1", "testvalue1", "testkey2", "testvalue2"), + Config: testAccBucketReplicationConfigurationConfig_filterAndOperatorTags(rName, "testkey1", "testvalue1", "testkey2", "testvalue2"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -1023,7 +1023,7 @@ func TestAccS3BucketReplicationConfiguration_filter_withoutId(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfiguration_filter_withoutIdConfig(rName), + Config: testAccBucketReplicationConfigurationConfig_filterNoID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "role", iamRoleResourceName, "arn"), @@ -1060,7 +1060,7 @@ func TestAccS3BucketReplicationConfiguration_withoutPrefix(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketReplicationConfigurationWithoutPrefix(rName), + Config: testAccBucketReplicationConfigurationConfig_noPrefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), ), @@ -1090,7 +1090,7 @@ func TestAccS3BucketReplicationConfiguration_migrate_noChange(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplicationV2_PrefixAndTags(rName), + Config: testAccBucketConfig_replicationV2PrefixAndTags(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExistsWithProvider(bucketResourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(bucketResourceName, "replication_configuration.0.rules.#", "1"), @@ -1102,7 +1102,7 @@ func TestAccS3BucketReplicationConfiguration_migrate_noChange(t *testing.T) { ), }, { - Config: testAccBucketReplicationConfiguration_Migrate_NoChangeConfig(rName), + Config: testAccBucketReplicationConfigurationConfig_migrateNoChange(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -1132,7 +1132,7 @@ func TestAccS3BucketReplicationConfiguration_migrate_withChange(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketReplicationConfigurationDestroy, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplicationV2_PrefixAndTags(rName), + Config: testAccBucketConfig_replicationV2PrefixAndTags(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExistsWithProvider(bucketResourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(bucketResourceName, "replication_configuration.0.rules.#", "1"), @@ -1144,7 +1144,7 @@ func TestAccS3BucketReplicationConfiguration_migrate_withChange(t *testing.T) { ), }, { - Config: testAccBucketReplicationConfiguration_Migrate_WithChangeConfig(rName), + Config: testAccBucketReplicationConfigurationConfig_migrateChange(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketReplicationConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -1263,7 +1263,7 @@ resource "aws_s3_bucket_versioning" "source" { `, rName) } -func testAccBucketReplicationConfigurationBasic(rName, storageClass string) string { +func testAccBucketReplicationConfigurationConfig_basic(rName, storageClass string) string { return testAccBucketReplicationConfigurationBase(rName) + fmt.Sprintf(` resource "aws_s3_bucket_replication_configuration" "test" { depends_on = [ @@ -1287,7 +1287,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`, storageClass) } -func testAccBucketReplicationConfiguration_prefix_withoutIdConfig(rName string) string { +func testAccBucketReplicationConfigurationConfig_prefixNoID(rName string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), ` resource "aws_s3_bucket_replication_configuration" "test" { @@ -1310,7 +1310,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`) } -func testAccBucketReplicationConfiguration_filter_withoutIdConfig(rName string) string { +func testAccBucketReplicationConfigurationConfig_filterNoID(rName string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), ` resource "aws_s3_bucket_replication_configuration" "test" { @@ -1338,7 +1338,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`) } -func testAccBucketReplicationConfigurationRTC(rName string) string { +func testAccBucketReplicationConfigurationConfig_rtc(rName string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), ` @@ -1379,7 +1379,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`) } -func testAccBucketReplicationConfigurationReplicaMods(rName string) string { +func testAccBucketReplicationConfigurationConfig_replicaMods(rName string) string { return testAccBucketReplicationConfigurationBase(rName) + ` resource "aws_s3_bucket_replication_configuration" "test" { depends_on = [ @@ -1412,7 +1412,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }` } -func testAccBucketReplicationConfigurationWithMultipleDestinationsEmptyFilter(rName string) string { +func testAccBucketReplicationConfigurationConfig_multipleDestinationsEmptyFilter(rName string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), fmt.Sprintf(` @@ -1505,7 +1505,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`, rName)) } -func testAccBucketReplicationConfigurationWithMultipleDestinationsNonEmptyFilter(rName string) string { +func testAccBucketReplicationConfigurationConfig_multipleDestinationsNonEmptyFilter(rName string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), fmt.Sprintf(` @@ -1611,7 +1611,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`, rName)) } -func testAccBucketReplicationConfigurationWithMultipleDestinationsTwoDestination(rName string) string { +func testAccBucketReplicationConfigurationConfig_multipleDestinationsTwoDestination(rName string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), fmt.Sprintf(` @@ -1718,7 +1718,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }` } -func testAccBucketReplicationConfigurationWithAccessControlTranslation(rName string) string { +func testAccBucketReplicationConfigurationConfig_accessControlTranslation(rName string) string { return testAccBucketReplicationConfigurationBase(rName) + ` data "aws_caller_identity" "current" {} @@ -1749,7 +1749,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }` } -func testAccBucketReplicationConfigurationRulesDestination(rName string) string { +func testAccBucketReplicationConfigurationConfig_rulesDestination(rName string) string { return testAccBucketReplicationConfigurationBase(rName) + ` data "aws_caller_identity" "current" {} @@ -1822,7 +1822,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }` } -func testAccBucketReplicationConfigurationWithoutStorageClass(rName string) string { +func testAccBucketReplicationConfigurationConfig_noStorageClass(rName string) string { return testAccBucketReplicationConfigurationBase(rName) + ` resource "aws_s3_bucket_replication_configuration" "test" { depends_on = [ @@ -1845,7 +1845,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }` } -func testAccBucketReplicationConfigurationWithV2ConfigurationNoTags(rName string) string { +func testAccBucketReplicationConfigurationConfig_v2NoTags(rName string) string { return testAccBucketReplicationConfigurationBase(rName) + ` resource "aws_s3_bucket_replication_configuration" "test" { depends_on = [ @@ -1876,7 +1876,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }` } -func testAccBucketReplicationConfiguration_schemaV2SameRegion(rName, rNameDestination string) string { +func testAccBucketReplicationConfigurationConfig_schemaV2SameRegion(rName, rNameDestination string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -1954,7 +1954,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`, rName, rNameDestination) } -func testAccBucketReplicationConfiguration_existingObjectReplication(rName, rNameDestination string) string { +func testAccBucketReplicationConfigurationConfig_existingObject(rName, rNameDestination string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -2039,7 +2039,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { `, rName, rNameDestination) } -func testAccBucketReplicationConfiguration_filter_emptyConfigurationBlock(rName string) string { +func testAccBucketReplicationConfigurationConfig_filterEmptyBlock(rName string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), ` @@ -2067,7 +2067,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`) } -func testAccBucketReplicationConfiguration_filter_emptyPrefix(rName string) string { +func testAccBucketReplicationConfigurationConfig_filterEmptyPrefix(rName string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), ` resource "aws_s3_bucket_replication_configuration" "test" { @@ -2097,7 +2097,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { ) } -func testAccBucketReplicationConfiguration_filter_tag(rName, key, value string) string { +func testAccBucketReplicationConfigurationConfig_filterTag(rName, key, value string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), fmt.Sprintf(` @@ -2133,7 +2133,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`, key, value)) } -func testAccBucketReplicationConfiguration_filter_andOperator_tags(rName, key1, value1, key2, value2 string) string { +func testAccBucketReplicationConfigurationConfig_filterAndOperatorTags(rName, key1, value1, key2, value2 string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), fmt.Sprintf(` @@ -2171,7 +2171,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`, key1, value1, key2, value2)) } -func testAccBucketReplicationConfiguration_filter_andOperator_prefixAndTags(rName, key1, value1, key2, value2 string) string { +func testAccBucketReplicationConfigurationConfig_filterAndOperatorPrefixAndTags(rName, key1, value1, key2, value2 string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), fmt.Sprintf(` @@ -2210,7 +2210,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`, key1, value1, key2, value2)) } -func testAccBucketReplicationConfiguration_schemaV2DestinationMetrics_statusOnly(rName, storageClass string) string { +func testAccBucketReplicationConfigurationConfig_schemaV2DestinationMetricsStatusOnly(rName, storageClass string) string { return testAccBucketReplicationConfigurationBase(rName) + fmt.Sprintf(` resource "aws_s3_bucket_replication_configuration" "test" { depends_on = [ @@ -2244,7 +2244,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { }`, storageClass) } -func testAccBucketReplicationConfigurationWithoutPrefix(rName string) string { +func testAccBucketReplicationConfigurationConfig_noPrefix(rName string) string { return acctest.ConfigCompose( testAccBucketReplicationConfigurationBase(rName), ` @@ -2324,7 +2324,7 @@ resource "aws_s3_bucket_versioning" "destination" { `, rName) } -func testAccBucketReplicationConfiguration_Migrate_NoChangeConfig(rName string) string { +func testAccBucketReplicationConfigurationConfig_migrateNoChange(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), testAccBucketReplicationConfigurationMigrationBase(rName), ` @@ -2367,7 +2367,7 @@ resource "aws_s3_bucket_replication_configuration" "test" { ) } -func testAccBucketReplicationConfiguration_Migrate_WithChangeConfig(rName string) string { +func testAccBucketReplicationConfigurationConfig_migrateChange(rName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(2), testAccBucketReplicationConfigurationMigrationBase(rName), ` diff --git a/internal/service/s3/bucket_request_payment_configuration_test.go b/internal/service/s3/bucket_request_payment_configuration_test.go index ef4c2472696..c24706ca6f3 100644 --- a/internal/service/s3/bucket_request_payment_configuration_test.go +++ b/internal/service/s3/bucket_request_payment_configuration_test.go @@ -26,7 +26,7 @@ func TestAccS3BucketRequestPaymentConfiguration_Basic_BucketOwner(t *testing.T) CheckDestroy: testAccCheckBucketRequestPaymentConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketRequestPaymentConfigurationBasicConfig(rName, s3.PayerBucketOwner), + Config: testAccBucketRequestPaymentConfigurationConfig_basic(rName, s3.PayerBucketOwner), Check: resource.ComposeTestCheckFunc( testAccCheckBucketRequestPaymentConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -53,7 +53,7 @@ func TestAccS3BucketRequestPaymentConfiguration_Basic_Requester(t *testing.T) { CheckDestroy: testAccCheckBucketRequestPaymentConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketRequestPaymentConfigurationBasicConfig(rName, s3.PayerRequester), + Config: testAccBucketRequestPaymentConfigurationConfig_basic(rName, s3.PayerRequester), Check: resource.ComposeTestCheckFunc( testAccCheckBucketRequestPaymentConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -80,13 +80,13 @@ func TestAccS3BucketRequestPaymentConfiguration_update(t *testing.T) { CheckDestroy: testAccCheckBucketRequestPaymentConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketRequestPaymentConfigurationBasicConfig(rName, s3.PayerRequester), + Config: testAccBucketRequestPaymentConfigurationConfig_basic(rName, s3.PayerRequester), Check: resource.ComposeTestCheckFunc( testAccCheckBucketRequestPaymentConfigurationExists(resourceName), ), }, { - Config: testAccBucketRequestPaymentConfigurationBasicConfig(rName, s3.PayerBucketOwner), + Config: testAccBucketRequestPaymentConfigurationConfig_basic(rName, s3.PayerBucketOwner), Check: resource.ComposeTestCheckFunc( testAccCheckBucketRequestPaymentConfigurationExists(resourceName), ), @@ -97,7 +97,7 @@ func TestAccS3BucketRequestPaymentConfiguration_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketRequestPaymentConfigurationBasicConfig(rName, s3.PayerRequester), + Config: testAccBucketRequestPaymentConfigurationConfig_basic(rName, s3.PayerRequester), Check: resource.ComposeTestCheckFunc( testAccCheckBucketRequestPaymentConfigurationExists(resourceName), ), @@ -118,14 +118,14 @@ func TestAccS3BucketRequestPaymentConfiguration_migrate_noChange(t *testing.T) { CheckDestroy: testAccCheckBucketRequestPaymentConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withRequestPayer(rName, s3.PayerRequester), + Config: testAccBucketConfig_requestPayer(rName, s3.PayerRequester), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "request_payer", s3.PayerRequester), ), }, { - Config: testAccBucketRequestPaymentConfigurationBasicConfig(rName, s3.PayerRequester), + Config: testAccBucketRequestPaymentConfigurationConfig_basic(rName, s3.PayerRequester), Check: resource.ComposeTestCheckFunc( testAccCheckBucketRequestPaymentConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "payer", s3.PayerRequester), @@ -147,14 +147,14 @@ func TestAccS3BucketRequestPaymentConfiguration_migrate_withChange(t *testing.T) CheckDestroy: testAccCheckBucketRequestPaymentConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withRequestPayer(rName, s3.PayerRequester), + Config: testAccBucketConfig_requestPayer(rName, s3.PayerRequester), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "request_payer", s3.PayerRequester), ), }, { - Config: testAccBucketRequestPaymentConfigurationBasicConfig(rName, s3.PayerBucketOwner), + Config: testAccBucketRequestPaymentConfigurationConfig_basic(rName, s3.PayerBucketOwner), Check: resource.ComposeTestCheckFunc( testAccCheckBucketRequestPaymentConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "payer", s3.PayerBucketOwner), @@ -243,7 +243,7 @@ func testAccCheckBucketRequestPaymentConfigurationExists(resourceName string) re } } -func testAccBucketRequestPaymentConfigurationBasicConfig(rName, payer string) string { +func testAccBucketRequestPaymentConfigurationConfig_basic(rName, payer string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_server_side_encryption_configuration_test.go b/internal/service/s3/bucket_server_side_encryption_configuration_test.go index 0c7553e8fe7..562b619e7a9 100644 --- a/internal/service/s3/bucket_server_side_encryption_configuration_test.go +++ b/internal/service/s3/bucket_server_side_encryption_configuration_test.go @@ -26,7 +26,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketServerSideEncryptionConfigurationBasicConfig(rName), + Config: testAccBucketServerSideEncryptionConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "bucket"), @@ -55,7 +55,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketServerSideEncryptionConfigurationBasicConfig(rName), + Config: testAccBucketServerSideEncryptionConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketServerSideEncryptionConfiguration(), resourceName), @@ -77,7 +77,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_ApplySEEByDefault_AES256(t CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_SSEAlgorithm(rName, s3.ServerSideEncryptionAes256), + Config: testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultSSEAlgorithm(rName, s3.ServerSideEncryptionAes256), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -106,7 +106,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_ApplySSEByDefault_KMS(t *t CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_SSEAlgorithm(rName, s3.ServerSideEncryptionAwsKms), + Config: testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultSSEAlgorithm(rName, s3.ServerSideEncryptionAwsKms), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -135,7 +135,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_ApplySSEByDefault_UpdateSS CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_SSEAlgorithm(rName, s3.ServerSideEncryptionAwsKms), + Config: testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultSSEAlgorithm(rName, s3.ServerSideEncryptionAwsKms), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -149,7 +149,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_ApplySSEByDefault_UpdateSS ImportStateVerify: true, }, { - Config: testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_SSEAlgorithm(rName, s3.ServerSideEncryptionAes256), + Config: testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultSSEAlgorithm(rName, s3.ServerSideEncryptionAes256), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -177,7 +177,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_ApplySSEByDefault_KMSWithM CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_kmsMasterKeyARN(rName), + Config: testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultKMSMasterKeyARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -206,7 +206,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_ApplySSEByDefault_KMSWithM CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_KMSWithMasterKeyID(rName), + Config: testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultKMSMasterKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -235,7 +235,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_BucketKeyEnabled(t *testin CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketServerSideEncryptionConfigurationConfig_BucketKeyEnabled(rName, true), + Config: testAccBucketServerSideEncryptionConfigurationConfig_keyEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "bucket"), @@ -249,7 +249,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_BucketKeyEnabled(t *testin ImportStateVerify: true, }, { - Config: testAccBucketServerSideEncryptionConfigurationConfig_BucketKeyEnabled(rName, false), + Config: testAccBucketServerSideEncryptionConfigurationConfig_keyEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "bucket"), @@ -277,7 +277,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_ApplySSEByDefault_BucketKe CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_BucketKeyEnabled(rName, true), + Config: testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultKeyEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "bucket"), @@ -294,7 +294,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_ApplySSEByDefault_BucketKe ImportStateVerify: true, }, { - Config: testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_BucketKeyEnabled(rName, false), + Config: testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultKeyEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "bucket"), @@ -326,7 +326,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_migrate_noChange(t *testin CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withDefaultEncryption_defaultKey(rName, s3.ServerSideEncryptionAwsKms), + Config: testAccBucketConfig_defaultEncryptionDefaultKey(rName, s3.ServerSideEncryptionAwsKms), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "server_side_encryption_configuration.#", "1"), @@ -337,7 +337,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_migrate_noChange(t *testin ), }, { - Config: testAccBucketServerSideEncryptionConfigurationConfig_migrate_noChange(rName), + Config: testAccBucketServerSideEncryptionConfigurationConfig_migrateNoChange(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -363,7 +363,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_migrate_withChange(t *test CheckDestroy: testAccCheckBucketServerSideEncryptionConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withDefaultEncryption_defaultKey(rName, s3.ServerSideEncryptionAwsKms), + Config: testAccBucketConfig_defaultEncryptionDefaultKey(rName, s3.ServerSideEncryptionAwsKms), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "server_side_encryption_configuration.#", "1"), @@ -374,7 +374,7 @@ func TestAccS3BucketServerSideEncryptionConfiguration_migrate_withChange(t *test ), }, { - Config: testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_SSEAlgorithm(rName, s3.ServerSideEncryptionAes256), + Config: testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultSSEAlgorithm(rName, s3.ServerSideEncryptionAes256), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", bucketResourceName, "bucket"), @@ -467,7 +467,7 @@ func testAccCheckBucketServerSideEncryptionConfigurationExists(resourceName stri } } -func testAccBucketServerSideEncryptionConfigurationBasicConfig(rName string) string { +func testAccBucketServerSideEncryptionConfigurationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -481,7 +481,7 @@ resource "aws_s3_bucket_server_side_encryption_configuration" "test" { `, rName) } -func testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_kmsMasterKeyARN(rName string) string { +func testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultKMSMasterKeyARN(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "KMS Key for Bucket %[1]s" @@ -505,7 +505,7 @@ resource "aws_s3_bucket_server_side_encryption_configuration" "test" { `, rName) } -func testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_KMSWithMasterKeyID(rName string) string { +func testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultKMSMasterKeyID(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "KMS Key for Bucket %[1]s" @@ -529,7 +529,7 @@ resource "aws_s3_bucket_server_side_encryption_configuration" "test" { `, rName) } -func testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_SSEAlgorithm(rName, sseAlgorithm string) string { +func testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultSSEAlgorithm(rName, sseAlgorithm string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -547,7 +547,7 @@ resource "aws_s3_bucket_server_side_encryption_configuration" "test" { `, rName, sseAlgorithm) } -func testAccBucketServerSideEncryptionConfigurationConfig_BucketKeyEnabled(rName string, enabled bool) string { +func testAccBucketServerSideEncryptionConfigurationConfig_keyEnabled(rName string, enabled bool) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -563,7 +563,7 @@ resource "aws_s3_bucket_server_side_encryption_configuration" "test" { `, rName, enabled) } -func testAccBucketServerSideEncryptionConfigurationConfig_ApplySSEByDefault_BucketKeyEnabled(rName string, enabled bool) string { +func testAccBucketServerSideEncryptionConfigurationConfig_applySSEByDefaultKeyEnabled(rName string, enabled bool) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "KMS Key for Bucket %[1]s" @@ -588,7 +588,7 @@ resource "aws_s3_bucket_server_side_encryption_configuration" "test" { `, rName, enabled) } -func testAccBucketServerSideEncryptionConfigurationConfig_migrate_noChange(rName string) string { +func testAccBucketServerSideEncryptionConfigurationConfig_migrateNoChange(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_test.go b/internal/service/s3/bucket_test.go index d001a73429e..fa52abcb7ee 100644 --- a/internal/service/s3/bucket_test.go +++ b/internal/service/s3/bucket_test.go @@ -54,7 +54,7 @@ func TestAccS3Bucket_Basic_basic(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "hosted_zone_id", hostedZoneID), @@ -93,7 +93,7 @@ func TestAccS3Bucket_Basic_emptyString(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketBucketEmptyStringConfig, + Config: testAccBucketConfig_emptyString, Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestMatchResourceAttr(resourceName, "bucket", regexp.MustCompile("^terraform-")), @@ -218,7 +218,7 @@ func TestAccS3Bucket_Basic_forceDestroyWithObjectLockEnabled(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_forceDestroyWithObjectLockEnabled(bucketName), + Config: testAccBucketConfig_forceDestroyObjectLockEnabled(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), testAccCheckBucketAddObjectsWithLegalHold(resourceName, "data.txt", "prefix/more_data.txt"), @@ -242,7 +242,7 @@ func TestAccS3Bucket_Basic_acceleration(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withAcceleration(bucketName, s3.BucketAccelerateStatusEnabled), + Config: testAccBucketConfig_acceleration(bucketName, s3.BucketAccelerateStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acceleration_status", s3.BucketAccelerateStatusEnabled), @@ -255,7 +255,7 @@ func TestAccS3Bucket_Basic_acceleration(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccBucketConfig_withAcceleration(bucketName, s3.BucketAccelerateStatusSuspended), + Config: testAccBucketConfig_acceleration(bucketName, s3.BucketAccelerateStatusSuspended), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acceleration_status", s3.BucketAccelerateStatusSuspended), @@ -276,7 +276,7 @@ func TestAccS3Bucket_Basic_keyEnabled(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_DefaultEncryption_bucketKeyEnabledKMSMasterKey(bucketName), + Config: testAccBucketConfig_defaultEncryptionKeyEnabledKMSMasterKey(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "server_side_encryption_configuration.#", "1"), @@ -308,7 +308,7 @@ func TestAccS3Bucket_Basic_requestPayer(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withRequestPayer(bucketName, s3.PayerBucketOwner), + Config: testAccBucketConfig_requestPayer(bucketName, s3.PayerBucketOwner), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "request_payer", s3.PayerBucketOwner), @@ -321,7 +321,7 @@ func TestAccS3Bucket_Basic_requestPayer(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy", "acl"}, }, { - Config: testAccBucketConfig_withRequestPayer(bucketName, s3.PayerRequester), + Config: testAccBucketConfig_requestPayer(bucketName, s3.PayerRequester), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "request_payer", s3.PayerRequester), @@ -345,7 +345,7 @@ func TestAccS3Bucket_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucket(), resourceName), @@ -367,7 +367,7 @@ func TestAccS3Bucket_Tags_basic(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccMultiBucketWithTagsConfig(rInt), + Config: testAccBucketConfig_multiTags(rInt), }, { ResourceName: resourceName, @@ -390,7 +390,7 @@ func TestAccS3Bucket_Tags_withNoSystemTags(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withTags(bucketName), + Config: testAccBucketConfig_tags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -406,7 +406,7 @@ func TestAccS3Bucket_Tags_withNoSystemTags(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccBucketConfig_withUpdatedTags(bucketName), + Config: testAccBucketConfig_updatedTags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "4"), @@ -417,7 +417,7 @@ func TestAccS3Bucket_Tags_withNoSystemTags(t *testing.T) { ), }, { - Config: testAccBucketConfig_withNoTags(bucketName), + Config: testAccBucketConfig_noTags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -425,7 +425,7 @@ func TestAccS3Bucket_Tags_withNoSystemTags(t *testing.T) { }, // Verify update from 0 tags. { - Config: testAccBucketConfig_withTags(bucketName), + Config: testAccBucketConfig_tags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -474,7 +474,7 @@ func TestAccS3Bucket_Tags_withSystemTags(t *testing.T) { ), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withNoTags(bucketName), + Config: testAccBucketConfig_noTags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -489,7 +489,7 @@ func TestAccS3Bucket_Tags_withSystemTags(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccBucketConfig_withTags(bucketName), + Config: testAccBucketConfig_tags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -500,7 +500,7 @@ func TestAccS3Bucket_Tags_withSystemTags(t *testing.T) { ), }, { - Config: testAccBucketConfig_withUpdatedTags(bucketName), + Config: testAccBucketConfig_updatedTags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "4"), @@ -512,7 +512,7 @@ func TestAccS3Bucket_Tags_withSystemTags(t *testing.T) { ), }, { - Config: testAccBucketConfig_withNoTags(bucketName), + Config: testAccBucketConfig_noTags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -536,7 +536,7 @@ func TestAccS3Bucket_Tags_ignoreTags(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey"), - testAccBucketConfig_withNoTags(bucketName)), + testAccBucketConfig_noTags(bucketName)), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), testAccCheckBucketUpdateTags(resourceName, nil, map[string]string{"ignorekey1": "ignorevalue1"}), @@ -549,7 +549,7 @@ func TestAccS3Bucket_Tags_ignoreTags(t *testing.T) { { Config: acctest.ConfigCompose( acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey"), - testAccBucketConfig_withTags(bucketName)), + testAccBucketConfig_tags(bucketName)), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), @@ -579,7 +579,7 @@ func TestAccS3Bucket_Manage_lifecycleBasic(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLifecycle(bucketName), + Config: testAccBucketConfig_lifecycle(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.#", "6"), @@ -649,7 +649,7 @@ func TestAccS3Bucket_Manage_lifecycleBasic(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy", "acl"}, }, { - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), @@ -669,7 +669,7 @@ func TestAccS3Bucket_Manage_lifecycleExpireMarkerOnly(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLifecycleExpireMarker(bucketName), + Config: testAccBucketConfig_lifecycleExpireMarker(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.id", "id1"), @@ -686,7 +686,7 @@ func TestAccS3Bucket_Manage_lifecycleExpireMarkerOnly(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy", "acl"}, }, { - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), @@ -707,7 +707,7 @@ func TestAccS3Bucket_Manage_lifecycleRuleExpirationEmptyBlock(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLifecycleRuleExpirationEmptyConfigurationBlock(rName), + Config: testAccBucketConfig_lifecycleRuleExpirationEmptyBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), @@ -728,7 +728,7 @@ func TestAccS3Bucket_Manage_lifecycleRuleAbortIncompleteMultipartUploadDaysNoExp CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLifecycleRuleAbortIncompleteMultipartUploadDays(rName), + Config: testAccBucketConfig_lifecycleRuleAbortIncompleteMultipartUploadDays(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), @@ -754,14 +754,14 @@ func TestAccS3Bucket_Manage_lifecycleRemove(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLifecycle(bucketName), + Config: testAccBucketConfig_lifecycle(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.#", "6"), ), }, { - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), // As Lifecycle Rule is a Computed field, removing them from terraform will not @@ -784,7 +784,7 @@ func TestAccS3Bucket_Manage_objectLock(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_ObjectLockEnabledNoDefaultRetention(bucketName), + Config: testAccBucketConfig_objectLockEnabledNoDefaultRetention(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "object_lock_enabled", "true"), @@ -800,7 +800,7 @@ func TestAccS3Bucket_Manage_objectLock(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccBucketConfig_ObjectLockEnabledWithDefaultRetention(bucketName), + Config: testAccBucketConfig_objectLockEnabledDefaultRetention(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "object_lock_configuration.#", "1"), @@ -825,7 +825,7 @@ func TestAccS3Bucket_Manage_objectLock_deprecatedEnabled(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_ObjectLockEnabledNoDefaultRetention_deprecatedEnabled(bucketName), + Config: testAccBucketConfig_objectLockEnabledNoDefaultRetentionDeprecatedEnabled(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "object_lock_enabled", "true"), @@ -855,7 +855,7 @@ func TestAccS3Bucket_Manage_objectLock_migrate(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_ObjectLockEnabledNoDefaultRetention_deprecatedEnabled(bucketName), + Config: testAccBucketConfig_objectLockEnabledNoDefaultRetentionDeprecatedEnabled(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "object_lock_enabled", "true"), @@ -864,7 +864,7 @@ func TestAccS3Bucket_Manage_objectLock_migrate(t *testing.T) { ), }, { - Config: testAccBucketConfig_ObjectLockEnabledNoDefaultRetention(bucketName), + Config: testAccBucketConfig_objectLockEnabledNoDefaultRetention(bucketName), PlanOnly: true, }, }, @@ -882,7 +882,7 @@ func TestAccS3Bucket_Manage_objectLockWithVersioning(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_objectLockEnabledWithVersioning(bucketName), + Config: testAccBucketConfig_objectLockEnabledVersioning(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "object_lock_enabled", "true"), @@ -911,7 +911,7 @@ func TestAccS3Bucket_Manage_objectLockWithVersioning_deprecatedEnabled(t *testin CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_objectLockEnabledWithVersioning_deprecatedEnabled(bucketName), + Config: testAccBucketConfig_objectLockEnabledVersioningDeprecatedEnabled(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "object_lock_enabled", "true"), @@ -940,7 +940,7 @@ func TestAccS3Bucket_Manage_versioning(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withVersioning(bucketName, true), + Config: testAccBucketConfig_versioning(bucketName, true), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning.#", "1"), @@ -955,7 +955,7 @@ func TestAccS3Bucket_Manage_versioning(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy", "acl"}, }, { - Config: testAccBucketConfig_withVersioning(bucketName, false), + Config: testAccBucketConfig_versioning(bucketName, false), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning.#", "1"), @@ -984,7 +984,7 @@ func TestAccS3Bucket_Manage_versioningDisabled(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withVersioning(bucketName, false), + Config: testAccBucketConfig_versioning(bucketName, false), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning.#", "1"), @@ -1080,7 +1080,7 @@ func TestAccS3Bucket_Replication_basic(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplication(bucketName, s3.StorageClassStandard), + Config: testAccBucketConfig_replication(bucketName, s3.StorageClassStandard), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1090,7 +1090,7 @@ func TestAccS3Bucket_Replication_basic(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplication(bucketName, s3.StorageClassGlacier), + Config: testAccBucketConfig_replication(bucketName, s3.StorageClassGlacier), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1100,7 +1100,7 @@ func TestAccS3Bucket_Replication_basic(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplication_SseKMSEncryptedObjects(bucketName), + Config: testAccBucketConfig_replicationSSEKMSEncryptedObjects(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1131,7 +1131,7 @@ func TestAccS3Bucket_Replication_multipleDestinationsEmptyFilter(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplication_MultipleDestinations_EmptyFilter(bucketName), + Config: testAccBucketConfig_replicationMultipleDestinationsEmptyFilter(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), testAccCheckBucketExistsWithProvider("aws_s3_bucket.destination", acctest.RegionProviderFunc(alternateRegion, &providers)), @@ -1169,7 +1169,7 @@ func TestAccS3Bucket_Replication_multipleDestinationsEmptyFilter(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplication_MultipleDestinations_EmptyFilter(bucketName), + Config: testAccBucketConfig_replicationMultipleDestinationsEmptyFilter(bucketName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1198,7 +1198,7 @@ func TestAccS3Bucket_Replication_multipleDestinationsNonEmptyFilter(t *testing.T CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplication_MultipleDestinations_NonEmptyFilter(bucketName), + Config: testAccBucketConfig_replicationMultipleDestinationsNonEmptyFilter(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), testAccCheckBucketExistsWithProvider("aws_s3_bucket.destination", acctest.RegionProviderFunc(alternateRegion, &providers)), @@ -1239,7 +1239,7 @@ func TestAccS3Bucket_Replication_multipleDestinationsNonEmptyFilter(t *testing.T ), }, { - Config: testAccBucketConfig_withReplication_MultipleDestinations_NonEmptyFilter(bucketName), + Config: testAccBucketConfig_replicationMultipleDestinationsNonEmptyFilter(bucketName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1269,7 +1269,7 @@ func TestAccS3Bucket_Replication_twoDestination(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplication_MultipleDestinations_TwoDestination(bucketName), + Config: testAccBucketConfig_replicationMultipleDestinationsTwoDestination(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), testAccCheckBucketExistsWithProvider("aws_s3_bucket.destination", acctest.RegionProviderFunc(alternateRegion, &providers)), @@ -1298,7 +1298,7 @@ func TestAccS3Bucket_Replication_twoDestination(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplication_MultipleDestinations_TwoDestination(bucketName), + Config: testAccBucketConfig_replicationMultipleDestinationsTwoDestination(bucketName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1327,7 +1327,7 @@ func TestAccS3Bucket_Replication_ruleDestinationAccessControlTranslation(t *test CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplication_AccessControlTranslation(bucketName), + Config: testAccBucketConfig_replicationAccessControlTranslation(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1336,14 +1336,14 @@ func TestAccS3Bucket_Replication_ruleDestinationAccessControlTranslation(t *test ), }, { - Config: testAccBucketConfig_withReplication_AccessControlTranslation(bucketName), + Config: testAccBucketConfig_replicationAccessControlTranslation(bucketName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"force_destroy", "acl", "versioning"}, }, { - Config: testAccBucketConfig_withReplication_SseKMSEncryptedObjectsAndAccessControlTranslation(bucketName), + Config: testAccBucketConfig_replicationSSEKMSEncryptedObjectsAndAccessControlTranslation(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1375,7 +1375,7 @@ func TestAccS3Bucket_Replication_ruleDestinationAddAccessControlTranslation(t *t CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplication_RulesDestination(bucketName), + Config: testAccBucketConfig_replicationRulesDestination(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1384,14 +1384,14 @@ func TestAccS3Bucket_Replication_ruleDestinationAddAccessControlTranslation(t *t ), }, { - Config: testAccBucketConfig_withReplication_AccessControlTranslation(bucketName), + Config: testAccBucketConfig_replicationAccessControlTranslation(bucketName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"force_destroy", "acl", "versioning"}, }, { - Config: testAccBucketConfig_withReplication_AccessControlTranslation(bucketName), + Config: testAccBucketConfig_replicationAccessControlTranslation(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1423,14 +1423,14 @@ func TestAccS3Bucket_Replication_withoutStorageClass(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplication_WithoutStorageClass(bucketName), + Config: testAccBucketConfig_replicationNoStorageClass(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), testAccCheckBucketExistsWithProvider("aws_s3_bucket.destination", acctest.RegionProviderFunc(alternateRegion, &providers)), ), }, { - Config: testAccBucketConfig_withReplication_WithoutStorageClass(bucketName), + Config: testAccBucketConfig_replicationNoStorageClass(bucketName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1456,7 +1456,7 @@ func TestAccS3Bucket_Replication_expectVersioningValidationError(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplication_NoVersioning(bucketName), + Config: testAccBucketConfig_replicationNoVersioning(bucketName), ExpectError: regexp.MustCompile(`versioning must be enabled to allow S3 bucket replication`), }, }, @@ -1483,14 +1483,14 @@ func TestAccS3Bucket_Replication_withoutPrefix(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplication_WithoutPrefix(bucketName), + Config: testAccBucketConfig_replicationNoPrefix(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), testAccCheckBucketExistsWithProvider("aws_s3_bucket.destination", acctest.RegionProviderFunc(alternateRegion, &providers)), ), }, { - Config: testAccBucketConfig_withReplication_WithoutPrefix(bucketName), + Config: testAccBucketConfig_replicationNoPrefix(bucketName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1520,7 +1520,7 @@ func TestAccS3Bucket_Replication_schemaV2(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplicationV2_DeleteMarkerReplicationDisabled(bucketName), + Config: testAccBucketConfig_replicationV2DeleteMarkerReplicationDisabled(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1530,7 +1530,7 @@ func TestAccS3Bucket_Replication_schemaV2(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplicationV2_NoTags(bucketName), + Config: testAccBucketConfig_replicationV2NoTags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1540,14 +1540,14 @@ func TestAccS3Bucket_Replication_schemaV2(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplicationV2_NoTags(bucketName), + Config: testAccBucketConfig_replicationV2NoTags(bucketName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"force_destroy", "acl"}, }, { - Config: testAccBucketConfig_withReplicationV2_OnlyOneTag(bucketName), + Config: testAccBucketConfig_replicationV2OnlyOneTag(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1557,7 +1557,7 @@ func TestAccS3Bucket_Replication_schemaV2(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplicationV2_PrefixAndTags(bucketName), + Config: testAccBucketConfig_replicationV2PrefixAndTags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1567,7 +1567,7 @@ func TestAccS3Bucket_Replication_schemaV2(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplicationV2_MultipleTags(bucketName), + Config: testAccBucketConfig_replicationV2MultipleTags(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1592,7 +1592,7 @@ func TestAccS3Bucket_Replication_schemaV2SameRegion(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplicationV2_SameRegionNoTags(rName), + Config: testAccBucketConfig_replicationV2SameRegionNoTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1602,7 +1602,7 @@ func TestAccS3Bucket_Replication_schemaV2SameRegion(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplicationV2_SameRegionNoTags(rName), + Config: testAccBucketConfig_replicationV2SameRegionNoTags(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1635,7 +1635,7 @@ func TestAccS3Bucket_Replication_RTC_valid(t *testing.T) { CheckDestroy: acctest.CheckWithProviders(testAccCheckBucketDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withReplicationV2_RTC(bucketName, 15), + Config: testAccBucketConfig_replicationV2RTC(bucketName, 15), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1645,7 +1645,7 @@ func TestAccS3Bucket_Replication_RTC_valid(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplicationV2_RTCNoMinutes(bucketName), + Config: testAccBucketConfig_replicationV2RTCNoMinutes(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1655,7 +1655,7 @@ func TestAccS3Bucket_Replication_RTC_valid(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplicationV2_RTCNoStatus(bucketName), + Config: testAccBucketConfig_replicationV2RTCNoStatus(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1665,7 +1665,7 @@ func TestAccS3Bucket_Replication_RTC_valid(t *testing.T) { ), }, { - Config: testAccBucketConfig_withReplicationV2_RTCNoConfig(bucketName), + Config: testAccBucketConfig_replicationV2RTCNotConfigured(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExistsWithProvider(resourceName, acctest.RegionProviderFunc(region, &providers)), resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), @@ -1692,7 +1692,7 @@ func TestAccS3Bucket_Security_updateACL(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withACL(bucketName, s3.BucketCannedACLPublicRead), + Config: testAccBucketConfig_acl(bucketName, s3.BucketCannedACLPublicRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acl", s3.BucketCannedACLPublicRead), @@ -1705,7 +1705,7 @@ func TestAccS3Bucket_Security_updateACL(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy", "acl"}, }, { - Config: testAccBucketConfig_withACL(bucketName, s3.BucketCannedACLPrivate), + Config: testAccBucketConfig_acl(bucketName, s3.BucketCannedACLPrivate), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acl", s3.BucketCannedACLPrivate), @@ -1726,7 +1726,7 @@ func TestAccS3Bucket_Security_updateGrant(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withGrants(bucketName), + Config: testAccBucketConfig_aclGrants(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "grant.#", "1"), @@ -1745,7 +1745,7 @@ func TestAccS3Bucket_Security_updateGrant(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy"}, }, { - Config: testAccBucketConfig_withUpdatedGrants(bucketName), + Config: testAccBucketConfig_updatedGrants(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "grant.#", "2"), @@ -1765,7 +1765,7 @@ func TestAccS3Bucket_Security_updateGrant(t *testing.T) { { // As Grant is a Computed field, removing them from terraform will not // trigger an update to remove them from the S3 bucket. - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "grant.#", "2"), @@ -1786,7 +1786,7 @@ func TestAccS3Bucket_Security_aclToGrant(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withACL(bucketName, s3.BucketCannedACLPublicRead), + Config: testAccBucketConfig_acl(bucketName, s3.BucketCannedACLPublicRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acl", s3.BucketCannedACLPublicRead), @@ -1795,7 +1795,7 @@ func TestAccS3Bucket_Security_aclToGrant(t *testing.T) { ), }, { - Config: testAccBucketConfig_withGrants(bucketName), + Config: testAccBucketConfig_aclGrants(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "grant.#", "1"), @@ -1816,14 +1816,14 @@ func TestAccS3Bucket_Security_grantToACL(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withGrants(bucketName), + Config: testAccBucketConfig_aclGrants(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "grant.#", "1"), ), }, { - Config: testAccBucketConfig_withACL(bucketName, s3.BucketCannedACLPublicRead), + Config: testAccBucketConfig_acl(bucketName, s3.BucketCannedACLPublicRead), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "acl", s3.BucketCannedACLPublicRead), @@ -1872,7 +1872,7 @@ func TestAccS3Bucket_Security_corsUpdate(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withCORS(bucketName), + Config: testAccBucketConfig_cors(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cors_rule.#", "1"), @@ -1898,7 +1898,7 @@ func TestAccS3Bucket_Security_corsUpdate(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy", "acl"}, }, { - Config: testAccBucketConfig_withCORS(bucketName), + Config: testAccBucketConfig_cors(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cors_rule.#", "1"), @@ -1948,7 +1948,7 @@ func TestAccS3Bucket_Security_corsDelete(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withCORS(bucketName), + Config: testAccBucketConfig_cors(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), deleteBucketCors(resourceName), @@ -1970,7 +1970,7 @@ func TestAccS3Bucket_Security_corsEmptyOrigin(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withCORSEmptyOrigin(bucketName), + Config: testAccBucketConfig_corsEmptyOrigin(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "cors_rule.#", "1"), @@ -2008,7 +2008,7 @@ func TestAccS3Bucket_Security_corsSingleMethodAndEmptyOrigin(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withCORSSingleMethodAndEmptyOrigin(bucketName), + Config: testAccBucketConfig_corsSingleMethodAndEmptyOrigin(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), ), @@ -2034,7 +2034,7 @@ func TestAccS3Bucket_Security_logging(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withLogging(bucketName), + Config: testAccBucketConfig_logging(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "logging.#", "1"), @@ -2062,7 +2062,7 @@ func TestAccS3Bucket_Security_enableDefaultEncryptionWhenTypical(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_DefaultEncryption_kmsMasterKey(bucketName), + Config: testAccBucketConfig_defaultEncryptionKMSMasterKey(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "server_side_encryption_configuration.#", "1"), @@ -2093,7 +2093,7 @@ func TestAccS3Bucket_Security_enableDefaultEncryptionWhenAES256IsUsed(t *testing CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withDefaultEncryption_defaultKey(bucketName, s3.ServerSideEncryptionAes256), + Config: testAccBucketConfig_defaultEncryptionDefaultKey(bucketName, s3.ServerSideEncryptionAes256), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "server_side_encryption_configuration.#", "1"), @@ -2124,7 +2124,7 @@ func TestAccS3Bucket_Security_disableDefaultEncryptionWhenDefaultEncryptionIsEna CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withDefaultEncryption_defaultKey(bucketName, s3.ServerSideEncryptionAwsKms), + Config: testAccBucketConfig_defaultEncryptionDefaultKey(bucketName, s3.ServerSideEncryptionAwsKms), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(resourceName), ), @@ -2138,7 +2138,7 @@ func TestAccS3Bucket_Security_disableDefaultEncryptionWhenDefaultEncryptionIsEna { // As ServerSide Encryption Configuration is a Computed field, removing them from terraform will not // trigger an update to remove it from the S3 bucket. - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "server_side_encryption_configuration.#", "1"), @@ -2160,7 +2160,7 @@ func TestAccS3Bucket_Security_policy(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withPolicy(bucketName, partition), + Config: testAccBucketConfig_policy(bucketName, partition), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), testAccCheckBucketPolicy(resourceName, testAccBucketPolicy(bucketName, partition)), @@ -2185,7 +2185,7 @@ func TestAccS3Bucket_Security_policy(t *testing.T) { { // As Policy is a Computed field, removing it from terraform will not // trigger an update to remove it from the S3 bucket. - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), testAccCheckBucketPolicy(resourceName, testAccBucketPolicy(bucketName, partition)), @@ -2194,7 +2194,7 @@ func TestAccS3Bucket_Security_policy(t *testing.T) { { // As Policy is a Computed field, setting it to the empty String will not // trigger an update to remove it from the S3 bucket. - Config: testAccBucketConfig_withEmptyPolicy(bucketName), + Config: testAccBucketConfig_emptyPolicy(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), testAccCheckBucketPolicy(resourceName, testAccBucketPolicy(bucketName, partition)), @@ -2216,7 +2216,7 @@ func TestAccS3Bucket_Web_simple(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withWebsite(bucketName), + Config: testAccBucketConfig_website(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "website.#", "1"), @@ -2231,7 +2231,7 @@ func TestAccS3Bucket_Web_simple(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy", "acl", "grant"}, }, { - Config: testAccBucketConfig_withWebsiteAndError(bucketName), + Config: testAccBucketConfig_websiteAndError(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "website.#", "1"), @@ -2243,7 +2243,7 @@ func TestAccS3Bucket_Web_simple(t *testing.T) { { // As Website is a Computed field, removing them from terraform will not // trigger an update to remove them from the S3 bucket. - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "website.#", "1"), @@ -2268,7 +2268,7 @@ func TestAccS3Bucket_Web_redirect(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withWebsiteAndRedirect(bucketName), + Config: testAccBucketConfig_websiteAndRedirect(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "website.#", "1"), @@ -2283,7 +2283,7 @@ func TestAccS3Bucket_Web_redirect(t *testing.T) { ImportStateVerifyIgnore: []string{"force_destroy", "acl", "grant"}, }, { - Config: testAccBucketConfig_withWebsiteAndHTTPSRedirect(bucketName), + Config: testAccBucketConfig_websiteAndHTTPSRedirect(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "website.#", "1"), @@ -2294,7 +2294,7 @@ func TestAccS3Bucket_Web_redirect(t *testing.T) { { // As Website is a Computed field, removing them from terraform will not // trigger an update to remove them from the S3 bucket. - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "website.#", "1"), @@ -2318,7 +2318,7 @@ func TestAccS3Bucket_Web_routingRules(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withWebsiteAndRoutingRules(bucketName), + Config: testAccBucketConfig_websiteAndRoutingRules(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "website.#", "1"), @@ -2337,7 +2337,7 @@ func TestAccS3Bucket_Web_routingRules(t *testing.T) { { // As Website is a Computed field, removing them from terraform will not // trigger an update to remove them from the S3 bucket. - Config: testAccBucketConfig_Basic(bucketName), + Config: testAccBucketConfig_basic(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "website.#", "1"), @@ -2931,7 +2931,7 @@ func testAccBucketPolicy(bucketName, partition string) string { }`, partition, bucketName) } -func testAccBucketConfig_Basic(bucketName string) string { +func testAccBucketConfig_basic(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -2939,7 +2939,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withAcceleration(bucketName, acceleration string) string { +func testAccBucketConfig_acceleration(bucketName, acceleration string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -2948,7 +2948,7 @@ resource "aws_s3_bucket" "test" { `, bucketName, acceleration) } -func testAccBucketConfig_withACL(bucketName, acl string) string { +func testAccBucketConfig_acl(bucketName, acl string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -2957,7 +2957,7 @@ resource "aws_s3_bucket" "test" { `, bucketName, acl) } -func testAccBucketConfig_withCORS(bucketName string) string { +func testAccBucketConfig_cors(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -2973,7 +2973,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withCORSSingleMethodAndEmptyOrigin(bucketName string) string { +func testAccBucketConfig_corsSingleMethodAndEmptyOrigin(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -2986,7 +2986,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withCORSEmptyOrigin(bucketName string) string { +func testAccBucketConfig_corsEmptyOrigin(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -3002,7 +3002,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withDefaultEncryption_defaultKey(bucketName, sseAlgorithm string) string { +func testAccBucketConfig_defaultEncryptionDefaultKey(bucketName, sseAlgorithm string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -3018,7 +3018,7 @@ resource "aws_s3_bucket" "test" { `, bucketName, sseAlgorithm) } -func testAccBucketConfig_DefaultEncryption_kmsMasterKey(bucketName string) string { +func testAccBucketConfig_defaultEncryptionKMSMasterKey(bucketName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "KMS Key for Bucket %[1]s" @@ -3040,7 +3040,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_DefaultEncryption_bucketKeyEnabledKMSMasterKey(bucketName string) string { +func testAccBucketConfig_defaultEncryptionKeyEnabledKMSMasterKey(bucketName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "KMS Key for Bucket %[1]s" @@ -3063,7 +3063,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withGrants(bucketName string) string { +func testAccBucketConfig_aclGrants(bucketName string) string { return fmt.Sprintf(` data "aws_canonical_user_id" "current" {} @@ -3079,7 +3079,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withUpdatedGrants(bucketName string) string { +func testAccBucketConfig_updatedGrants(bucketName string) string { return fmt.Sprintf(` data "aws_canonical_user_id" "current" {} @@ -3101,7 +3101,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withLifecycle(bucketName string) string { +func testAccBucketConfig_lifecycle(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -3210,7 +3210,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withLifecycleExpireMarker(bucketName string) string { +func testAccBucketConfig_lifecycleExpireMarker(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -3229,7 +3229,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withLifecycleRuleExpirationEmptyConfigurationBlock(rName string) string { +func testAccBucketConfig_lifecycleRuleExpirationEmptyBlock(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -3244,7 +3244,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccBucketConfig_withLifecycleRuleAbortIncompleteMultipartUploadDays(rName string) string { +func testAccBucketConfig_lifecycleRuleAbortIncompleteMultipartUploadDays(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -3258,7 +3258,7 @@ resource "aws_s3_bucket" "test" { `, rName) } -func testAccBucketConfig_withLogging(bucketName string) string { +func testAccBucketConfig_logging(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "log_bucket" { bucket = "%[1]s-log" @@ -3277,7 +3277,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withEmptyPolicy(bucketName string) string { +func testAccBucketConfig_emptyPolicy(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -3287,7 +3287,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withPolicy(bucketName, partition string) string { +func testAccBucketConfig_policy(bucketName, partition string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -3334,7 +3334,7 @@ resource "aws_s3_bucket" "destination" { `, bucketName)) } -func testAccBucketConfig_withReplication(bucketName, storageClass string) string { +func testAccBucketConfig_replication(bucketName, storageClass string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3364,7 +3364,7 @@ resource "aws_s3_bucket" "source" { `, bucketName, storageClass)) } -func testAccBucketConfig_withReplication_AccessControlTranslation(bucketName string) string { +func testAccBucketConfig_replicationAccessControlTranslation(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3401,7 +3401,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplication_MultipleDestinations_EmptyFilter(bucketName string) string { +func testAccBucketConfig_replicationMultipleDestinationsEmptyFilter(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3477,7 +3477,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplication_MultipleDestinations_NonEmptyFilter(bucketName string) string { +func testAccBucketConfig_replicationMultipleDestinationsNonEmptyFilter(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3565,7 +3565,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplication_MultipleDestinations_TwoDestination(bucketName string) string { +func testAccBucketConfig_replicationMultipleDestinationsTwoDestination(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3625,7 +3625,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplication_NoVersioning(bucketName string) string { +func testAccBucketConfig_replicationNoVersioning(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3651,7 +3651,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplication_RulesDestination(bucketName string) string { +func testAccBucketConfig_replicationRulesDestination(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3684,7 +3684,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplication_SseKMSEncryptedObjects(bucketName string) string { +func testAccBucketConfig_replicationSSEKMSEncryptedObjects(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3727,7 +3727,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplication_SseKMSEncryptedObjectsAndAccessControlTranslation(bucketName string) string { +func testAccBucketConfig_replicationSSEKMSEncryptedObjectsAndAccessControlTranslation(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3777,7 +3777,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplication_WithoutPrefix(bucketName string) string { +func testAccBucketConfig_replicationNoPrefix(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3806,7 +3806,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplication_WithoutStorageClass(bucketName string) string { +func testAccBucketConfig_replicationNoStorageClass(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3835,7 +3835,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplicationV2_SameRegionNoTags(rName string) string { +func testAccBucketConfig_replicationV2SameRegionNoTags(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -3896,7 +3896,7 @@ resource "aws_s3_bucket" "destination" { `, rName) } -func testAccBucketConfig_withReplicationV2_DeleteMarkerReplicationDisabled(bucketName string) string { +func testAccBucketConfig_replicationV2DeleteMarkerReplicationDisabled(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3929,7 +3929,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplicationV2_NoTags(bucketName string) string { +func testAccBucketConfig_replicationV2NoTags(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -3964,7 +3964,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplicationV2_OnlyOneTag(bucketName string) string { +func testAccBucketConfig_replicationV2OnlyOneTag(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -4001,7 +4001,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplicationV2_PrefixAndTags(bucketName string) string { +func testAccBucketConfig_replicationV2PrefixAndTags(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -4041,7 +4041,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplicationV2_MultipleTags(bucketName string) string { +func testAccBucketConfig_replicationV2MultipleTags(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -4078,7 +4078,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplicationV2_RTC(bucketName string, minutes int) string { +func testAccBucketConfig_replicationV2RTC(bucketName string, minutes int) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -4116,7 +4116,7 @@ resource "aws_s3_bucket" "source" { `, bucketName, minutes)) } -func testAccBucketConfig_withReplicationV2_RTCNoMinutes(bucketName string) string { +func testAccBucketConfig_replicationV2RTCNoMinutes(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -4150,7 +4150,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplicationV2_RTCNoStatus(bucketName string) string { +func testAccBucketConfig_replicationV2RTCNoStatus(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -4184,7 +4184,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withReplicationV2_RTCNoConfig(bucketName string) string { +func testAccBucketConfig_replicationV2RTCNotConfigured(bucketName string) string { return acctest.ConfigCompose( testAccBucketConfig_ReplicationBase(bucketName), fmt.Sprintf(` @@ -4214,7 +4214,7 @@ resource "aws_s3_bucket" "source" { `, bucketName)) } -func testAccBucketConfig_withRequestPayer(bucketName, requestPayer string) string { +func testAccBucketConfig_requestPayer(bucketName, requestPayer string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4223,7 +4223,7 @@ resource "aws_s3_bucket" "test" { `, bucketName, requestPayer) } -func testAccBucketConfig_withVersioning(bucketName string, enabled bool) string { +func testAccBucketConfig_versioning(bucketName string, enabled bool) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4260,7 +4260,7 @@ resource "aws_s3_bucket" "test" { `, bucketName, mfaDelete) } -func testAccBucketConfig_withWebsite(bucketName string) string { +func testAccBucketConfig_website(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4273,7 +4273,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withWebsiteAndError(bucketName string) string { +func testAccBucketConfig_websiteAndError(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4287,7 +4287,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withWebsiteAndRedirect(bucketName string) string { +func testAccBucketConfig_websiteAndRedirect(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4300,7 +4300,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withWebsiteAndHTTPSRedirect(bucketName string) string { +func testAccBucketConfig_websiteAndHTTPSRedirect(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4313,7 +4313,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_withWebsiteAndRoutingRules(bucketName string) string { +func testAccBucketConfig_websiteAndRoutingRules(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4341,7 +4341,7 @@ EOF `, bucketName) } -func testAccBucketConfig_withNoTags(bucketName string) string { +func testAccBucketConfig_noTags(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4355,7 +4355,7 @@ resource "aws_s3_bucket_acl" "test" { `, bucketName) } -func testAccBucketConfig_withTags(bucketName string) string { +func testAccBucketConfig_tags(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4375,7 +4375,7 @@ resource "aws_s3_bucket_acl" "test" { `, bucketName) } -func testAccBucketConfig_withUpdatedTags(bucketName string) string { +func testAccBucketConfig_updatedTags(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4396,7 +4396,7 @@ resource "aws_s3_bucket_acl" "test" { `, bucketName) } -func testAccMultiBucketWithTagsConfig(randInt int) string { +func testAccBucketConfig_multiTags(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "bucket1" { bucket = "tf-test-bucket-1-%[1]d" @@ -4490,7 +4490,7 @@ resource "aws_s3_bucket_acl" "test6" { `, randInt) } -func testAccBucketConfig_ObjectLockEnabledNoDefaultRetention(bucketName string) string { +func testAccBucketConfig_objectLockEnabledNoDefaultRetention(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4500,7 +4500,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_ObjectLockEnabledWithDefaultRetention(bucketName string) string { +func testAccBucketConfig_objectLockEnabledDefaultRetention(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4519,7 +4519,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_ObjectLockEnabledNoDefaultRetention_deprecatedEnabled(bucketName string) string { +func testAccBucketConfig_objectLockEnabledNoDefaultRetentionDeprecatedEnabled(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4531,7 +4531,7 @@ resource "aws_s3_bucket" "test" { `, bucketName) } -func testAccBucketConfig_objectLockEnabledWithVersioning(bucketName string) string { +func testAccBucketConfig_objectLockEnabledVersioning(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4554,7 +4554,7 @@ resource "aws_s3_bucket_versioning" "test" { `, bucketName) } -func testAccBucketConfig_objectLockEnabledWithVersioning_deprecatedEnabled(bucketName string) string { +func testAccBucketConfig_objectLockEnabledVersioningDeprecatedEnabled(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -4593,7 +4593,7 @@ resource "aws_s3_bucket_acl" "test" { `, bucketName) } -func testAccBucketConfig_forceDestroyWithObjectLockEnabled(bucketName string) string { +func testAccBucketConfig_forceDestroyObjectLockEnabled(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = "%s" @@ -4616,7 +4616,7 @@ resource "aws_s3_bucket_versioning" "bucket" { `, bucketName) } -const testAccBucketBucketEmptyStringConfig = ` +const testAccBucketConfig_emptyString = ` resource "aws_s3_bucket" "test" { bucket = "" } diff --git a/internal/service/s3/bucket_versioning_test.go b/internal/service/s3/bucket_versioning_test.go index 18336b74e9d..aeea48a258c 100644 --- a/internal/service/s3/bucket_versioning_test.go +++ b/internal/service/s3/bucket_versioning_test.go @@ -27,7 +27,7 @@ func TestAccS3BucketVersioning_basic(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusEnabled), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -55,7 +55,7 @@ func TestAccS3BucketVersioning_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusEnabled), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketVersioning(), resourceName), @@ -78,7 +78,7 @@ func TestAccS3BucketVersioning_disappears_bucket(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusEnabled), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucket(), bucketResourceName), @@ -100,13 +100,13 @@ func TestAccS3BucketVersioning_update(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusEnabled), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), ), }, { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusSuspended), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusSuspended), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.0.status", s3.BucketVersioningStatusSuspended), @@ -118,7 +118,7 @@ func TestAccS3BucketVersioning_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusEnabled), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.0.status", s3.BucketVersioningStatusEnabled), @@ -141,7 +141,7 @@ func TestAccS3BucketVersioning_MFADelete(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningConfig_MFADelete(rName, s3.MFADeleteDisabled), + Config: testAccBucketVersioningConfig_mfaDelete(rName, s3.MFADeleteDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -170,7 +170,7 @@ func TestAccS3BucketVersioning_migrate_versioningDisabledNoChange(t *testing.T) CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withVersioning(bucketName, false), + Config: testAccBucketConfig_versioning(bucketName, false), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "versioning.#", "1"), @@ -178,7 +178,7 @@ func TestAccS3BucketVersioning_migrate_versioningDisabledNoChange(t *testing.T) ), }, { - Config: testAccBucketVersioning_Migrate_VersioningEnabledConfig(bucketName, tfs3.BucketVersioningStatusDisabled), + Config: testAccBucketVersioningConfig_migrateEnabled(bucketName, tfs3.BucketVersioningStatusDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -201,7 +201,7 @@ func TestAccS3BucketVersioning_migrate_versioningDisabledWithChange(t *testing.T CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withVersioning(bucketName, false), + Config: testAccBucketConfig_versioning(bucketName, false), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "versioning.#", "1"), @@ -209,7 +209,7 @@ func TestAccS3BucketVersioning_migrate_versioningDisabledWithChange(t *testing.T ), }, { - Config: testAccBucketVersioning_Migrate_VersioningEnabledConfig(bucketName, s3.BucketVersioningStatusEnabled), + Config: testAccBucketVersioningConfig_migrateEnabled(bucketName, s3.BucketVersioningStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -232,7 +232,7 @@ func TestAccS3BucketVersioning_migrate_versioningEnabledNoChange(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withVersioning(bucketName, true), + Config: testAccBucketConfig_versioning(bucketName, true), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "versioning.#", "1"), @@ -240,7 +240,7 @@ func TestAccS3BucketVersioning_migrate_versioningEnabledNoChange(t *testing.T) { ), }, { - Config: testAccBucketVersioning_Migrate_VersioningEnabledConfig(bucketName, s3.BucketVersioningStatusEnabled), + Config: testAccBucketVersioningConfig_migrateEnabled(bucketName, s3.BucketVersioningStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -263,7 +263,7 @@ func TestAccS3BucketVersioning_migrate_versioningEnabledWithChange(t *testing.T) CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withVersioning(bucketName, true), + Config: testAccBucketConfig_versioning(bucketName, true), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "versioning.#", "1"), @@ -271,7 +271,7 @@ func TestAccS3BucketVersioning_migrate_versioningEnabledWithChange(t *testing.T) ), }, { - Config: testAccBucketVersioning_Migrate_VersioningEnabledConfig(bucketName, s3.BucketVersioningStatusSuspended), + Config: testAccBucketVersioningConfig_migrateEnabled(bucketName, s3.BucketVersioningStatusSuspended), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -304,7 +304,7 @@ func TestAccS3BucketVersioning_migrate_mfaDeleteNoChange(t *testing.T) { ), }, { - Config: testAccBucketVersioningConfig_Migrate_mfaDelete(bucketName, s3.MFADeleteDisabled), + Config: testAccBucketVersioningConfig_migrateMFADelete(bucketName, s3.MFADeleteDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -326,7 +326,7 @@ func TestAccS3BucketVersioning_Status_disabled(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningBasicConfig(rName, tfs3.BucketVersioningStatusDisabled), + Config: testAccBucketVersioningConfig_basic(rName, tfs3.BucketVersioningStatusDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -353,7 +353,7 @@ func TestAccS3BucketVersioning_Status_disabledToEnabled(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningBasicConfig(rName, tfs3.BucketVersioningStatusDisabled), + Config: testAccBucketVersioningConfig_basic(rName, tfs3.BucketVersioningStatusDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -361,7 +361,7 @@ func TestAccS3BucketVersioning_Status_disabledToEnabled(t *testing.T) { ), }, { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusEnabled), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -388,7 +388,7 @@ func TestAccS3BucketVersioning_Status_disabledToSuspended(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningBasicConfig(rName, tfs3.BucketVersioningStatusDisabled), + Config: testAccBucketVersioningConfig_basic(rName, tfs3.BucketVersioningStatusDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -396,7 +396,7 @@ func TestAccS3BucketVersioning_Status_disabledToSuspended(t *testing.T) { ), }, { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusSuspended), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusSuspended), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -423,7 +423,7 @@ func TestAccS3BucketVersioning_Status_enabledToDisabled(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusEnabled), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -431,7 +431,7 @@ func TestAccS3BucketVersioning_Status_enabledToDisabled(t *testing.T) { ), }, { - Config: testAccBucketVersioningBasicConfig(rName, tfs3.BucketVersioningStatusDisabled), + Config: testAccBucketVersioningConfig_basic(rName, tfs3.BucketVersioningStatusDisabled), ExpectError: regexp.MustCompile(`versioning_configuration.status cannot be updated from 'Enabled' to 'Disabled'`), }, }, @@ -449,7 +449,7 @@ func TestAccS3BucketVersioning_Status_suspendedToDisabled(t *testing.T) { CheckDestroy: testAccCheckBucketVersioningDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketVersioningBasicConfig(rName, s3.BucketVersioningStatusSuspended), + Config: testAccBucketVersioningConfig_basic(rName, s3.BucketVersioningStatusSuspended), Check: resource.ComposeTestCheckFunc( testAccCheckBucketVersioningExists(resourceName), resource.TestCheckResourceAttr(resourceName, "versioning_configuration.#", "1"), @@ -457,7 +457,7 @@ func TestAccS3BucketVersioning_Status_suspendedToDisabled(t *testing.T) { ), }, { - Config: testAccBucketVersioningBasicConfig(rName, tfs3.BucketVersioningStatusDisabled), + Config: testAccBucketVersioningConfig_basic(rName, tfs3.BucketVersioningStatusDisabled), ExpectError: regexp.MustCompile(`versioning_configuration.status cannot be updated from 'Suspended' to 'Disabled'`), }, }, @@ -525,7 +525,7 @@ func testAccCheckBucketVersioningExists(resourceName string) resource.TestCheckF } } -func testAccBucketVersioningBasicConfig(rName, status string) string { +func testAccBucketVersioningConfig_basic(rName, status string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -545,7 +545,7 @@ resource "aws_s3_bucket_versioning" "test" { `, rName, status) } -func testAccBucketVersioningConfig_MFADelete(rName, mfaDelete string) string { +func testAccBucketVersioningConfig_mfaDelete(rName, mfaDelete string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -566,7 +566,7 @@ resource "aws_s3_bucket_versioning" "test" { `, rName, mfaDelete) } -func testAccBucketVersioning_Migrate_VersioningEnabledConfig(rName, status string) string { +func testAccBucketVersioningConfig_migrateEnabled(rName, status string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -581,7 +581,7 @@ resource "aws_s3_bucket_versioning" "test" { `, rName, status) } -func testAccBucketVersioningConfig_Migrate_mfaDelete(rName, mfaDelete string) string { +func testAccBucketVersioningConfig_migrateMFADelete(rName, mfaDelete string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/bucket_website_configuration_test.go b/internal/service/s3/bucket_website_configuration_test.go index 688b8341122..940d21c8288 100644 --- a/internal/service/s3/bucket_website_configuration_test.go +++ b/internal/service/s3/bucket_website_configuration_test.go @@ -26,7 +26,7 @@ func TestAccS3BucketWebsiteConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationBasicConfig(rName), + Config: testAccBucketWebsiteConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -56,7 +56,7 @@ func TestAccS3BucketWebsiteConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationBasicConfig(rName), + Config: testAccBucketWebsiteConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3.ResourceBucketWebsiteConfiguration(), resourceName), @@ -78,13 +78,13 @@ func TestAccS3BucketWebsiteConfiguration_update(t *testing.T) { CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationBasicConfig(rName), + Config: testAccBucketWebsiteConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), ), }, { - Config: testAccBucketWebsiteConfigurationUpdateConfig(rName), + Config: testAccBucketWebsiteConfigurationConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -114,7 +114,7 @@ func TestAccS3BucketWebsiteConfiguration_Redirect(t *testing.T) { CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationConfig_Redirect(rName), + Config: testAccBucketWebsiteConfigurationConfig_redirect(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3_bucket.test", "id"), @@ -142,7 +142,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRule_ConditionAndRedirect(t *tes CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRule_OptionalRedirection(rName), + Config: testAccBucketWebsiteConfigurationConfig_routingRuleOptionalRedirection(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -161,7 +161,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRule_ConditionAndRedirect(t *tes ImportStateVerify: true, }, { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRule_RedirectErrors(rName), + Config: testAccBucketWebsiteConfigurationConfig_routingRuleRedirectErrors(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -180,7 +180,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRule_ConditionAndRedirect(t *tes ImportStateVerify: true, }, { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRule_RedirectToPage(rName), + Config: testAccBucketWebsiteConfigurationConfig_routingRuleRedirectToPage(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -213,7 +213,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRule_MultipleRules(t *testing.T) CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRule_MultipleRules(rName), + Config: testAccBucketWebsiteConfigurationConfig_routingRuleMultipleRules(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "2"), @@ -238,7 +238,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRule_MultipleRules(t *testing.T) ImportStateVerify: true, }, { - Config: testAccBucketWebsiteConfigurationBasicConfig(rName), + Config: testAccBucketWebsiteConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), ), @@ -258,7 +258,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRule_RedirectOnly(t *testing.T) CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRule_RedirectOnly(rName), + Config: testAccBucketWebsiteConfigurationConfig_routingRuleRedirectOnly(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -290,7 +290,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRules_ConditionAndRedirect(t *te CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRules_ConditionAndRedirect(rName, "documents/"), + Config: testAccBucketWebsiteConfigurationConfig_routingRulesConditionAndRedirect(rName, "documents/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -317,7 +317,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRules_ConditionAndRedirectWithEm CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRules_ConditionAndRedirect(rName, ""), + Config: testAccBucketWebsiteConfigurationConfig_routingRulesConditionAndRedirect(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -344,7 +344,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRules_updateConditionAndRedirect CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRules_ConditionAndRedirect(rName, "documents/"), + Config: testAccBucketWebsiteConfigurationConfig_routingRulesConditionAndRedirect(rName, "documents/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -352,7 +352,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRules_updateConditionAndRedirect ), }, { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRules_ConditionAndRedirect(rName, ""), + Config: testAccBucketWebsiteConfigurationConfig_routingRulesConditionAndRedirect(rName, ""), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -374,7 +374,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRuleToRoutingRules(t *testing.T) CheckDestroy: testAccCheckBucketWebsiteConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRule_OptionalRedirection(rName), + Config: testAccBucketWebsiteConfigurationConfig_routingRuleOptionalRedirection(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -382,7 +382,7 @@ func TestAccS3BucketWebsiteConfiguration_RoutingRuleToRoutingRules(t *testing.T) ), }, { - Config: testAccBucketWebsiteConfigurationConfig_RoutingRules_ConditionAndRedirect(rName, "documents/"), + Config: testAccBucketWebsiteConfigurationConfig_routingRulesConditionAndRedirect(rName, "documents/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -405,7 +405,7 @@ func TestAccS3BucketWebsiteConfiguration_migrate_websiteWithIndexDocumentNoChang CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withWebsite(bucketName), + Config: testAccBucketConfig_website(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "website.#", "1"), @@ -413,7 +413,7 @@ func TestAccS3BucketWebsiteConfiguration_migrate_websiteWithIndexDocumentNoChang ), }, { - Config: testAccBucketWebsiteConfigurationConfig_Migrate_WebsiteWithIndexDocumentNoChange(bucketName), + Config: testAccBucketWebsiteConfigurationConfig_migrateIndexDocumentNoChange(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "index_document.#", "1"), @@ -436,7 +436,7 @@ func TestAccS3BucketWebsiteConfiguration_migrate_websiteWithIndexDocumentWithCha CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withWebsite(bucketName), + Config: testAccBucketConfig_website(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "website.#", "1"), @@ -444,7 +444,7 @@ func TestAccS3BucketWebsiteConfiguration_migrate_websiteWithIndexDocumentWithCha ), }, { - Config: testAccBucketWebsiteConfigurationConfig_Migrate_WebsiteWithIndexDocumentWithChange(bucketName), + Config: testAccBucketWebsiteConfigurationConfig_migrateIndexDocumentChange(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "index_document.#", "1"), @@ -467,7 +467,7 @@ func TestAccS3BucketWebsiteConfiguration_migrate_websiteWithRoutingRuleNoChange( CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withWebsiteAndRoutingRules(bucketName), + Config: testAccBucketConfig_websiteAndRoutingRules(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "website.#", "1"), @@ -475,7 +475,7 @@ func TestAccS3BucketWebsiteConfiguration_migrate_websiteWithRoutingRuleNoChange( ), }, { - Config: testAccBucketWebsiteConfigurationConfig_Migrate_WebsiteWithRoutingRuleNoChange(bucketName), + Config: testAccBucketWebsiteConfigurationConfig_migrateRoutingRuleNoChange(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -497,7 +497,7 @@ func TestAccS3BucketWebsiteConfiguration_migrate_websiteWithRoutingRuleWithChang CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_withWebsiteAndRoutingRules(bucketName), + Config: testAccBucketConfig_websiteAndRoutingRules(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(bucketResourceName), resource.TestCheckResourceAttr(bucketResourceName, "website.#", "1"), @@ -505,7 +505,7 @@ func TestAccS3BucketWebsiteConfiguration_migrate_websiteWithRoutingRuleWithChang ), }, { - Config: testAccBucketWebsiteConfigurationConfig_Migrate_WebsiteWithRoutingRuleWithChange(bucketName), + Config: testAccBucketWebsiteConfigurationConfig_migrateRoutingRuleChange(bucketName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketWebsiteConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "routing_rule.#", "1"), @@ -597,7 +597,7 @@ func testAccCheckBucketWebsiteConfigurationExists(resourceName string) resource. } } -func testAccBucketWebsiteConfigurationBasicConfig(rName string) string { +func testAccBucketWebsiteConfigurationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -617,7 +617,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationUpdateConfig(rName string) string { +func testAccBucketWebsiteConfigurationConfig_update(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -643,7 +643,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationConfig_Redirect(rName string) string { +func testAccBucketWebsiteConfigurationConfig_redirect(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -664,7 +664,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationConfig_RoutingRule_OptionalRedirection(rName string) string { +func testAccBucketWebsiteConfigurationConfig_routingRuleOptionalRedirection(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -699,9 +699,9 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationConfig_RoutingRule_RedirectErrors(rName string) string { +func testAccBucketWebsiteConfigurationConfig_routingRuleRedirectErrors(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -736,7 +736,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName)) } -func testAccBucketWebsiteConfigurationConfig_RoutingRule_RedirectToPage(rName string) string { +func testAccBucketWebsiteConfigurationConfig_routingRuleRedirectToPage(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -771,7 +771,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationConfig_RoutingRule_RedirectOnly(rName string) string { +func testAccBucketWebsiteConfigurationConfig_routingRuleRedirectOnly(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -803,7 +803,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationConfig_RoutingRule_MultipleRules(rName string) string { +func testAccBucketWebsiteConfigurationConfig_routingRuleMultipleRules(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -846,7 +846,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationConfig_RoutingRules_ConditionAndRedirect(bucketName, replaceKeyPrefixWith string) string { +func testAccBucketWebsiteConfigurationConfig_routingRulesConditionAndRedirect(bucketName, replaceKeyPrefixWith string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -884,7 +884,7 @@ EOF `, bucketName, replaceKeyPrefixWith) } -func testAccBucketWebsiteConfigurationConfig_Migrate_WebsiteWithIndexDocumentNoChange(rName string) string { +func testAccBucketWebsiteConfigurationConfig_migrateIndexDocumentNoChange(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -905,7 +905,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationConfig_Migrate_WebsiteWithIndexDocumentWithChange(rName string) string { +func testAccBucketWebsiteConfigurationConfig_migrateIndexDocumentChange(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -926,7 +926,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationConfig_Migrate_WebsiteWithRoutingRuleNoChange(rName string) string { +func testAccBucketWebsiteConfigurationConfig_migrateRoutingRuleNoChange(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -960,7 +960,7 @@ resource "aws_s3_bucket_website_configuration" "test" { `, rName) } -func testAccBucketWebsiteConfigurationConfig_Migrate_WebsiteWithRoutingRuleWithChange(rName string) string { +func testAccBucketWebsiteConfigurationConfig_migrateRoutingRuleChange(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/canonical_user_id_data_source_test.go b/internal/service/s3/canonical_user_id_data_source_test.go index 9c3fe2d831f..e4f600fb5dd 100644 --- a/internal/service/s3/canonical_user_id_data_source_test.go +++ b/internal/service/s3/canonical_user_id_data_source_test.go @@ -17,7 +17,7 @@ func TestAccS3CanonicalUserIDDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCanonicalUserIdDataSourceConfig, + Config: testAccCanonicalUserIDDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCanonicalUserIdCheckExistsDataSource("data.aws_canonical_user_id.current"), ), @@ -44,6 +44,6 @@ func testAccCanonicalUserIdCheckExistsDataSource(name string) resource.TestCheck } } -const testAccCanonicalUserIdDataSourceConfig = ` +const testAccCanonicalUserIDDataSourceConfig_basic = ` data "aws_canonical_user_id" "current" {} ` diff --git a/internal/service/s3/object_copy_test.go b/internal/service/s3/object_copy_test.go index c62ad401e8d..cf1824a0476 100644 --- a/internal/service/s3/object_copy_test.go +++ b/internal/service/s3/object_copy_test.go @@ -52,7 +52,7 @@ func TestAccS3ObjectCopy_BucketKeyEnabled_bucket(t *testing.T) { CheckDestroy: testAccCheckObjectCopyDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectCopyConfig_BucketKeyEnabled_Bucket(rName), + Config: testAccObjectCopyConfig_bucketKeyEnabledBucket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectCopyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bucket_key_enabled", "true"), @@ -73,7 +73,7 @@ func TestAccS3ObjectCopy_BucketKeyEnabled_object(t *testing.T) { CheckDestroy: testAccCheckObjectCopyDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectCopyConfig_BucketKeyEnabled_Object(rName), + Config: testAccObjectCopyConfig_bucketKeyEnabled(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectCopyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "bucket_key_enabled", "true"), @@ -160,7 +160,7 @@ resource "aws_s3_object_copy" "test" { `, rName1, sourceKey, rName2, key) } -func testAccObjectCopyConfig_BucketKeyEnabled_Bucket(rName string) string { +func testAccObjectCopyConfig_bucketKeyEnabledBucket(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Encrypts test objects" @@ -204,7 +204,7 @@ resource "aws_s3_object_copy" "test" { `, rName) } -func testAccObjectCopyConfig_BucketKeyEnabled_Object(rName string) string { +func testAccObjectCopyConfig_bucketKeyEnabled(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Encrypts test objects" diff --git a/internal/service/s3/object_data_source_test.go b/internal/service/s3/object_data_source_test.go index cefa3692e18..d986a54b033 100644 --- a/internal/service/s3/object_data_source_test.go +++ b/internal/service/s3/object_data_source_test.go @@ -252,7 +252,7 @@ func TestAccS3ObjectDataSource_objectLockLegalHoldOff(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectDataSourceConfig_objectLockLegalHoldOff(rInt), + Config: testAccObjectDataSourceConfig_lockLegalHoldOff(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &rObj), testAccCheckObjectExistsDataSource(dataSourceName, &dsObj), @@ -287,7 +287,7 @@ func TestAccS3ObjectDataSource_objectLockLegalHoldOn(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectDataSourceConfig_objectLockLegalHoldOn(rInt, retainUntilDate), + Config: testAccObjectDataSourceConfig_lockLegalHoldOn(rInt, retainUntilDate), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &rObj), testAccCheckObjectExistsDataSource(dataSourceName, &dsObj), @@ -323,13 +323,13 @@ func TestAccS3ObjectDataSource_leadingSlash(t *testing.T) { ProviderFactories: acctest.ProviderFactories, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ - { + { // nosemgrep:test-config-funcs-correct-form Config: resourceOnlyConf, Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &rObj), ), }, - { + { // nosemgrep:test-config-funcs-correct-form Config: conf, Check: resource.ComposeTestCheckFunc( testAccCheckObjectExistsDataSource(dataSourceName1, &dsObj1), @@ -377,14 +377,14 @@ func TestAccS3ObjectDataSource_multipleSlashes(t *testing.T) { ProviderFactories: acctest.ProviderFactories, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ - { + { // nosemgrep:test-config-funcs-correct-form Config: resourceOnlyConf, Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName1, &rObj1), testAccCheckObjectExists(resourceName2, &rObj2), ), }, - { + { // nosemgrep:test-config-funcs-correct-form Config: conf, Check: resource.ComposeTestCheckFunc( @@ -420,7 +420,7 @@ func TestAccS3ObjectDataSource_singleSlashAsKey(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectSingleSlashAsKeyDataSourceConfig(rName), + Config: testAccObjectDataSourceConfig_singleSlashAsKey(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExistsDataSource(dataSourceName, &dsObj), ), @@ -616,7 +616,7 @@ data "aws_s3_object" "obj" { `, randInt) } -func testAccObjectDataSourceConfig_objectLockLegalHoldOff(randInt int) string { +func testAccObjectDataSourceConfig_lockLegalHoldOff(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "object_bucket" { bucket = "tf-object-test-bucket-%[1]d" @@ -646,7 +646,7 @@ data "aws_s3_object" "obj" { `, randInt) } -func testAccObjectDataSourceConfig_objectLockLegalHoldOn(randInt int, retainUntilDate string) string { +func testAccObjectDataSourceConfig_lockLegalHoldOn(randInt int, retainUntilDate string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "object_bucket" { bucket = "tf-object-test-bucket-%[1]d" @@ -759,7 +759,7 @@ data "aws_s3_object" "obj3" { return resources, both } -func testAccObjectSingleSlashAsKeyDataSourceConfig(rName string) string { +func testAccObjectDataSourceConfig_singleSlashAsKey(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3/object_test.go b/internal/service/s3/object_test.go index 07744baf3a5..6ba810608f0 100644 --- a/internal/service/s3/object_test.go +++ b/internal/service/s3/object_test.go @@ -37,12 +37,12 @@ func TestAccS3Object_noNameNoKey(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectBasicConfig("", "a key"), + Config: testAccObjectConfig_basic("", "a key"), ExpectError: bucketError, }, { PreConfig: func() {}, - Config: testAccObjectBasicConfig("a name", ""), + Config: testAccObjectConfig_basic("a name", ""), ExpectError: keyError, }, }, @@ -62,7 +62,7 @@ func TestAccS3Object_empty(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectEmptyConfig(rName), + Config: testAccObjectConfig_empty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectBody(&obj, ""), @@ -94,7 +94,7 @@ func TestAccS3Object_source(t *testing.T) { CheckDestroy: testAccCheckObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectSourceConfig(rName, source), + Config: testAccObjectConfig_source(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectBody(&obj, "{anything will do }"), @@ -124,7 +124,7 @@ func TestAccS3Object_content(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectContentConfig(rName, "some_bucket_content"), + Config: testAccObjectConfig_content(rName, "some_bucket_content"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectBody(&obj, "some_bucket_content"), @@ -156,7 +156,7 @@ func TestAccS3Object_etagEncryption(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectEtagEncryption(rName, source), + Config: testAccObjectConfig_etagEncryption(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectBody(&obj, "{anything will do }"), @@ -187,7 +187,7 @@ func TestAccS3Object_contentBase64(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectContentBase64Config(rName, base64.StdEncoding.EncodeToString([]byte("some_bucket_content"))), + Config: testAccObjectConfig_contentBase64(rName, base64.StdEncoding.EncodeToString([]byte("some_bucket_content"))), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectBody(&obj, "some_bucket_content"), @@ -268,7 +268,7 @@ func TestAccS3Object_withContentCharacteristics(t *testing.T) { CheckDestroy: testAccCheckObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectConfig_withContentCharacteristics(rName, source), + Config: testAccObjectConfig_contentCharacteristics(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectBody(&obj, "{anything will do }"), @@ -507,7 +507,7 @@ func TestAccS3Object_kms(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectConfig_withKMSID(rName, source), + Config: testAccObjectConfig_kmsID(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectSSE(resourceName, "aws:kms"), @@ -541,7 +541,7 @@ func TestAccS3Object_sse(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectConfig_withSSE(rName, source), + Config: testAccObjectConfig_sse(rName, source), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectSSE(resourceName, "AES256"), @@ -622,7 +622,7 @@ func TestAccS3Object_metadata(t *testing.T) { CheckDestroy: testAccCheckObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectConfig_withMetadata(rName, "key1", "value1", "key2", "value2"), + Config: testAccObjectConfig_metadata(rName, "key1", "value1", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), resource.TestCheckResourceAttr(resourceName, "metadata.%", "2"), @@ -631,7 +631,7 @@ func TestAccS3Object_metadata(t *testing.T) { ), }, { - Config: testAccObjectConfig_withMetadata(rName, "key1", "value1updated", "key3", "value3"), + Config: testAccObjectConfig_metadata(rName, "key1", "value1updated", "key3", "value3"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), resource.TestCheckResourceAttr(resourceName, "metadata.%", "2"), @@ -640,7 +640,7 @@ func TestAccS3Object_metadata(t *testing.T) { ), }, { - Config: testAccObjectEmptyConfig(rName), + Config: testAccObjectConfig_empty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), resource.TestCheckResourceAttr(resourceName, "metadata.%", "0"), @@ -670,7 +670,7 @@ func TestAccS3Object_storageClass(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectContentConfig(rName, "some_bucket_content"), + Config: testAccObjectConfig_content(rName, "some_bucket_content"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), resource.TestCheckResourceAttr(resourceName, "storage_class", "STANDARD"), @@ -734,7 +734,7 @@ func TestAccS3Object_tags(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectConfig_withTags(rName, key, "stuff"), + Config: testAccObjectConfig_tags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj1), testAccCheckObjectBody(&obj1, "stuff"), @@ -746,7 +746,7 @@ func TestAccS3Object_tags(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withUpdatedTags(rName, key, "stuff"), + Config: testAccObjectConfig_updatedTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj2), testAccCheckObjectVersionIdEquals(&obj2, &obj1), @@ -760,7 +760,7 @@ func TestAccS3Object_tags(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withNoTags(rName, key, "stuff"), + Config: testAccObjectConfig_noTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj3), testAccCheckObjectVersionIdEquals(&obj3, &obj2), @@ -770,7 +770,7 @@ func TestAccS3Object_tags(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withTags(rName, key, "changed stuff"), + Config: testAccObjectConfig_tags(rName, key, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj4), testAccCheckObjectVersionIdDiffers(&obj4, &obj3), @@ -806,7 +806,7 @@ func TestAccS3Object_tagsLeadingSingleSlash(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectConfig_withTags(rName, key, "stuff"), + Config: testAccObjectConfig_tags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj1), testAccCheckObjectBody(&obj1, "stuff"), @@ -818,7 +818,7 @@ func TestAccS3Object_tagsLeadingSingleSlash(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withUpdatedTags(rName, key, "stuff"), + Config: testAccObjectConfig_updatedTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj2), testAccCheckObjectVersionIdEquals(&obj2, &obj1), @@ -832,7 +832,7 @@ func TestAccS3Object_tagsLeadingSingleSlash(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withNoTags(rName, key, "stuff"), + Config: testAccObjectConfig_noTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj3), testAccCheckObjectVersionIdEquals(&obj3, &obj2), @@ -842,7 +842,7 @@ func TestAccS3Object_tagsLeadingSingleSlash(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withTags(rName, key, "changed stuff"), + Config: testAccObjectConfig_tags(rName, key, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj4), testAccCheckObjectVersionIdDiffers(&obj4, &obj3), @@ -878,7 +878,7 @@ func TestAccS3Object_tagsLeadingMultipleSlashes(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectConfig_withTags(rName, key, "stuff"), + Config: testAccObjectConfig_tags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj1), testAccCheckObjectBody(&obj1, "stuff"), @@ -890,7 +890,7 @@ func TestAccS3Object_tagsLeadingMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withUpdatedTags(rName, key, "stuff"), + Config: testAccObjectConfig_updatedTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj2), testAccCheckObjectVersionIdEquals(&obj2, &obj1), @@ -904,7 +904,7 @@ func TestAccS3Object_tagsLeadingMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withNoTags(rName, key, "stuff"), + Config: testAccObjectConfig_noTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj3), testAccCheckObjectVersionIdEquals(&obj3, &obj2), @@ -914,7 +914,7 @@ func TestAccS3Object_tagsLeadingMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withTags(rName, key, "changed stuff"), + Config: testAccObjectConfig_tags(rName, key, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj4), testAccCheckObjectVersionIdDiffers(&obj4, &obj3), @@ -943,7 +943,7 @@ func TestAccS3Object_tagsMultipleSlashes(t *testing.T) { Steps: []resource.TestStep{ { PreConfig: func() {}, - Config: testAccObjectConfig_withTags(rName, key, "stuff"), + Config: testAccObjectConfig_tags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj1), testAccCheckObjectBody(&obj1, "stuff"), @@ -955,7 +955,7 @@ func TestAccS3Object_tagsMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withUpdatedTags(rName, key, "stuff"), + Config: testAccObjectConfig_updatedTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj2), testAccCheckObjectVersionIdEquals(&obj2, &obj1), @@ -969,7 +969,7 @@ func TestAccS3Object_tagsMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withNoTags(rName, key, "stuff"), + Config: testAccObjectConfig_noTags(rName, key, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj3), testAccCheckObjectVersionIdEquals(&obj3, &obj2), @@ -979,7 +979,7 @@ func TestAccS3Object_tagsMultipleSlashes(t *testing.T) { }, { PreConfig: func() {}, - Config: testAccObjectConfig_withTags(rName, key, "changed stuff"), + Config: testAccObjectConfig_tags(rName, key, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj4), testAccCheckObjectVersionIdDiffers(&obj4, &obj3), @@ -1006,7 +1006,7 @@ func TestAccS3Object_objectLockLegalHoldStartWithNone(t *testing.T) { CheckDestroy: testAccCheckObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectConfig_noObjectLockLegalHold(rName, "stuff"), + Config: testAccObjectConfig_noLockLegalHold(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj1), testAccCheckObjectBody(&obj1, "stuff"), @@ -1016,7 +1016,7 @@ func TestAccS3Object_objectLockLegalHoldStartWithNone(t *testing.T) { ), }, { - Config: testAccObjectConfig_withObjectLockLegalHold(rName, "stuff", "ON"), + Config: testAccObjectConfig_lockLegalHold(rName, "stuff", "ON"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj2), testAccCheckObjectVersionIdEquals(&obj2, &obj1), @@ -1028,7 +1028,7 @@ func TestAccS3Object_objectLockLegalHoldStartWithNone(t *testing.T) { }, // Remove legal hold but create a new object version to test force_destroy { - Config: testAccObjectConfig_withObjectLockLegalHold(rName, "changed stuff", "OFF"), + Config: testAccObjectConfig_lockLegalHold(rName, "changed stuff", "OFF"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj3), testAccCheckObjectVersionIdDiffers(&obj3, &obj2), @@ -1054,7 +1054,7 @@ func TestAccS3Object_objectLockLegalHoldStartWithOn(t *testing.T) { CheckDestroy: testAccCheckObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectConfig_withObjectLockLegalHold(rName, "stuff", "ON"), + Config: testAccObjectConfig_lockLegalHold(rName, "stuff", "ON"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj1), testAccCheckObjectBody(&obj1, "stuff"), @@ -1064,7 +1064,7 @@ func TestAccS3Object_objectLockLegalHoldStartWithOn(t *testing.T) { ), }, { - Config: testAccObjectConfig_withObjectLockLegalHold(rName, "stuff", "OFF"), + Config: testAccObjectConfig_lockLegalHold(rName, "stuff", "OFF"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj2), testAccCheckObjectVersionIdEquals(&obj2, &obj1), @@ -1091,7 +1091,7 @@ func TestAccS3Object_objectLockRetentionStartWithNone(t *testing.T) { CheckDestroy: testAccCheckObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectConfig_noObjectLockRetention(rName, "stuff"), + Config: testAccObjectConfig_noLockRetention(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj1), testAccCheckObjectBody(&obj1, "stuff"), @@ -1101,7 +1101,7 @@ func TestAccS3Object_objectLockRetentionStartWithNone(t *testing.T) { ), }, { - Config: testAccObjectConfig_withObjectLockRetention(rName, "stuff", retainUntilDate), + Config: testAccObjectConfig_lockRetention(rName, "stuff", retainUntilDate), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj2), testAccCheckObjectVersionIdEquals(&obj2, &obj1), @@ -1113,7 +1113,7 @@ func TestAccS3Object_objectLockRetentionStartWithNone(t *testing.T) { }, // Remove retention period but create a new object version to test force_destroy { - Config: testAccObjectConfig_noObjectLockRetention(rName, "changed stuff"), + Config: testAccObjectConfig_noLockRetention(rName, "changed stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj3), testAccCheckObjectVersionIdDiffers(&obj3, &obj2), @@ -1142,7 +1142,7 @@ func TestAccS3Object_objectLockRetentionStartWithSet(t *testing.T) { CheckDestroy: testAccCheckObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectConfig_withObjectLockRetention(rName, "stuff", retainUntilDate1), + Config: testAccObjectConfig_lockRetention(rName, "stuff", retainUntilDate1), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj1), testAccCheckObjectBody(&obj1, "stuff"), @@ -1152,7 +1152,7 @@ func TestAccS3Object_objectLockRetentionStartWithSet(t *testing.T) { ), }, { - Config: testAccObjectConfig_withObjectLockRetention(rName, "stuff", retainUntilDate2), + Config: testAccObjectConfig_lockRetention(rName, "stuff", retainUntilDate2), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj2), testAccCheckObjectVersionIdEquals(&obj2, &obj1), @@ -1163,7 +1163,7 @@ func TestAccS3Object_objectLockRetentionStartWithSet(t *testing.T) { ), }, { - Config: testAccObjectConfig_withObjectLockRetention(rName, "stuff", retainUntilDate3), + Config: testAccObjectConfig_lockRetention(rName, "stuff", retainUntilDate3), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj3), testAccCheckObjectVersionIdEquals(&obj3, &obj2), @@ -1174,7 +1174,7 @@ func TestAccS3Object_objectLockRetentionStartWithSet(t *testing.T) { ), }, { - Config: testAccObjectConfig_noObjectLockRetention(rName, "stuff"), + Config: testAccObjectConfig_noLockRetention(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj4), testAccCheckObjectVersionIdEquals(&obj4, &obj3), @@ -1200,7 +1200,7 @@ func TestAccS3Object_objectBucketKeyEnabled(t *testing.T) { CheckDestroy: testAccCheckObjectDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectConfig_objectBucketKeyEnabled(rName, "stuff"), + Config: testAccObjectConfig_bucketKeyEnabled(rName, "stuff"), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectBody(&obj, "stuff"), @@ -1273,7 +1273,7 @@ func TestAccS3Object_ignoreTags(t *testing.T) { PreConfig: func() {}, Config: acctest.ConfigCompose( acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey"), - testAccObjectConfig_withNoTags(rName, key, "stuff")), + testAccObjectConfig_noTags(rName, key, "stuff")), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectBody(&obj, "stuff"), @@ -1288,7 +1288,7 @@ func TestAccS3Object_ignoreTags(t *testing.T) { PreConfig: func() {}, Config: acctest.ConfigCompose( acctest.ConfigIgnoreTagsKeyPrefixes1("ignorekey"), - testAccObjectConfig_withTags(rName, key, "stuff")), + testAccObjectConfig_tags(rName, key, "stuff")), Check: resource.ComposeTestCheckFunc( testAccCheckObjectExists(resourceName, &obj), testAccCheckObjectBody(&obj, "stuff"), @@ -1560,7 +1560,7 @@ func testAccCheckObjectCheckTags(n string, expectedTags map[string]string) resou } } -func testAccObjectBasicConfig(bucket, key string) string { +func testAccObjectConfig_basic(bucket, key string) string { return fmt.Sprintf(` resource "aws_s3_object" "object" { bucket = %[1]q @@ -1569,7 +1569,7 @@ resource "aws_s3_object" "object" { `, bucket, key) } -func testAccObjectEmptyConfig(rName string) string { +func testAccObjectConfig_empty(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1582,7 +1582,7 @@ resource "aws_s3_object" "object" { `, rName) } -func testAccObjectSourceConfig(rName string, source string) string { +func testAccObjectConfig_source(rName string, source string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1597,7 +1597,7 @@ resource "aws_s3_object" "object" { `, rName, source) } -func testAccObjectConfig_withContentCharacteristics(rName string, source string) string { +func testAccObjectConfig_contentCharacteristics(rName string, source string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1614,7 +1614,7 @@ resource "aws_s3_object" "object" { `, rName, source) } -func testAccObjectContentConfig(rName string, content string) string { +func testAccObjectConfig_content(rName string, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1628,7 +1628,7 @@ resource "aws_s3_object" "object" { `, rName, content) } -func testAccObjectEtagEncryption(rName string, source string) string { +func testAccObjectConfig_etagEncryption(rName string, source string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1644,7 +1644,7 @@ resource "aws_s3_object" "object" { `, rName, source) } -func testAccObjectContentBase64Config(rName string, contentBase64 string) string { +func testAccObjectConfig_contentBase64(rName string, contentBase64 string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1724,7 +1724,7 @@ resource "aws_s3_object" "test" { `, rName, bucketVersioning, source) } -func testAccObjectConfig_withKMSID(rName string, source string) string { +func testAccObjectConfig_kmsID(rName string, source string) string { return fmt.Sprintf(` resource "aws_kms_key" "kms_key_1" {} @@ -1741,7 +1741,7 @@ resource "aws_s3_object" "object" { `, rName, source) } -func testAccObjectConfig_withSSE(rName string, source string) string { +func testAccObjectConfig_sse(rName string, source string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1794,7 +1794,7 @@ resource "aws_s3_object" "object" { `, rName, storage_class) } -func testAccObjectConfig_withTags(rName, key, content string) string { +func testAccObjectConfig_tags(rName, key, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1822,7 +1822,7 @@ resource "aws_s3_object" "object" { `, rName, key, content) } -func testAccObjectConfig_withUpdatedTags(rName, key, content string) string { +func testAccObjectConfig_updatedTags(rName, key, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1851,7 +1851,7 @@ resource "aws_s3_object" "object" { `, rName, key, content) } -func testAccObjectConfig_withNoTags(rName, key, content string) string { +func testAccObjectConfig_noTags(rName, key, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1873,7 +1873,7 @@ resource "aws_s3_object" "object" { `, rName, key, content) } -func testAccObjectConfig_withMetadata(rName string, metadataKey1, metadataValue1, metadataKey2, metadataValue2 string) string { +func testAccObjectConfig_metadata(rName string, metadataKey1, metadataValue1, metadataKey2, metadataValue2 string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1891,7 +1891,7 @@ resource "aws_s3_object" "object" { `, rName, metadataKey1, metadataValue1, metadataKey2, metadataValue2) } -func testAccObjectConfig_noObjectLockLegalHold(rName string, content string) string { +func testAccObjectConfig_noLockLegalHold(rName string, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1916,7 +1916,7 @@ resource "aws_s3_object" "object" { `, rName, content) } -func testAccObjectConfig_withObjectLockLegalHold(rName string, content, legalHoldStatus string) string { +func testAccObjectConfig_lockLegalHold(rName string, content, legalHoldStatus string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1942,7 +1942,7 @@ resource "aws_s3_object" "object" { `, rName, content, legalHoldStatus) } -func testAccObjectConfig_noObjectLockRetention(rName string, content string) string { +func testAccObjectConfig_noLockRetention(rName string, content string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1967,7 +1967,7 @@ resource "aws_s3_object" "object" { `, rName, content) } -func testAccObjectConfig_withObjectLockRetention(rName string, content, retainUntilDate string) string { +func testAccObjectConfig_lockRetention(rName string, content, retainUntilDate string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -2030,7 +2030,7 @@ resource "aws_s3_object" "object" { `, rName, source) } -func testAccObjectConfig_objectBucketKeyEnabled(rName string, content string) string { +func testAccObjectConfig_bucketKeyEnabled(rName string, content string) string { return fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Encrypts test objects" diff --git a/internal/service/s3/objects_data_source_test.go b/internal/service/s3/objects_data_source_test.go index a0056a30c3b..b8dd281f9a5 100644 --- a/internal/service/s3/objects_data_source_test.go +++ b/internal/service/s3/objects_data_source_test.go @@ -21,11 +21,11 @@ func TestAccS3ObjectsDataSource_basic(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccObjectsBasicDataSourceConfig(rInt), + Config: testAccObjectsDataSourceConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -47,11 +47,11 @@ func TestAccS3ObjectsDataSource_basicViaAccessPoint(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectsResourcesPlusAccessPointDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccObjectsDataSourceConfig_resourcesPlusAccessPoint(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccObjectsBasicViaAccessPointDataSourceConfig(rInt), + Config: testAccObjectsDataSourceConfig_basicViaAccessPoint(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -73,11 +73,11 @@ func TestAccS3ObjectsDataSource_all(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccObjectsAllDataSourceConfig(rInt), + Config: testAccObjectsDataSourceConfig_all(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "7"), @@ -104,11 +104,11 @@ func TestAccS3ObjectsDataSource_prefixes(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccObjectsPrefixesDataSourceConfig(rInt), + Config: testAccObjectsDataSourceConfig_prefixes(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "1"), @@ -134,11 +134,11 @@ func TestAccS3ObjectsDataSource_encoded(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectsExtraResourceDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccObjectsDataSourceConfig_extraResource(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccObjectsEncodedDataSourceConfig(rInt), + Config: testAccObjectsDataSourceConfig_encoded(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -160,11 +160,11 @@ func TestAccS3ObjectsDataSource_maxKeys(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccObjectsMaxKeysDataSourceConfig(rInt), + Config: testAccObjectsDataSourceConfig_maxKeys(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -186,11 +186,11 @@ func TestAccS3ObjectsDataSource_startAfter(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccObjectsStartAfterDataSourceConfig(rInt), + Config: testAccObjectsDataSourceConfig_startAfter(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "1"), @@ -211,11 +211,11 @@ func TestAccS3ObjectsDataSource_fetchOwner(t *testing.T) { PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: testAccObjectsResourcesDataSourceConfig(rInt), // NOTE: contains no data source + Config: testAccObjectsDataSourceConfig_resources(rInt), // NOTE: contains no data source // Does not need Check }, { - Config: testAccObjectsOwnersDataSourceConfig(rInt), + Config: testAccObjectsDataSourceConfig_owners(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckObjectsExistsDataSource("data.aws_s3_objects.yesh"), resource.TestCheckResourceAttr("data.aws_s3_objects.yesh", "keys.#", "2"), @@ -241,7 +241,7 @@ func testAccCheckObjectsExistsDataSource(addr string) resource.TestCheckFunc { } } -func testAccObjectsResourcesDataSourceConfig(randInt int) string { +func testAccObjectsDataSourceConfig_resources(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "objects_bucket" { bucket = "tf-acc-objects-test-bucket-%d" @@ -291,8 +291,8 @@ resource "aws_s3_object" "object7" { `, randInt) } -func testAccObjectsResourcesPlusAccessPointDataSourceConfig(randInt int) string { - return testAccObjectsResourcesDataSourceConfig(randInt) + fmt.Sprintf(` +func testAccObjectsDataSourceConfig_resourcesPlusAccessPoint(randInt int) string { + return testAccObjectsDataSourceConfig_resources(randInt) + fmt.Sprintf(` resource "aws_s3_access_point" "test" { bucket = aws_s3_bucket.objects_bucket.bucket name = "tf-objects-test-access-point-%[1]d" @@ -300,7 +300,7 @@ resource "aws_s3_access_point" "test" { `, randInt) } -func testAccObjectsBasicDataSourceConfig(randInt int) string { +func testAccObjectsDataSourceConfig_basic(randInt int) string { return fmt.Sprintf(` %s @@ -309,11 +309,11 @@ data "aws_s3_objects" "yesh" { prefix = "arch/navajo/" delimiter = "/" } -`, testAccObjectsResourcesDataSourceConfig(randInt)) +`, testAccObjectsDataSourceConfig_resources(randInt)) } -func testAccObjectsBasicViaAccessPointDataSourceConfig(randInt int) string { - return testAccObjectsResourcesPlusAccessPointDataSourceConfig(randInt) + ` +func testAccObjectsDataSourceConfig_basicViaAccessPoint(randInt int) string { + return testAccObjectsDataSourceConfig_resourcesPlusAccessPoint(randInt) + ` data "aws_s3_objects" "yesh" { bucket = aws_s3_access_point.test.arn prefix = "arch/navajo/" @@ -322,17 +322,17 @@ data "aws_s3_objects" "yesh" { ` } -func testAccObjectsAllDataSourceConfig(randInt int) string { +func testAccObjectsDataSourceConfig_all(randInt int) string { return fmt.Sprintf(` %s data "aws_s3_objects" "yesh" { bucket = aws_s3_bucket.objects_bucket.id } -`, testAccObjectsResourcesDataSourceConfig(randInt)) +`, testAccObjectsDataSourceConfig_resources(randInt)) } -func testAccObjectsPrefixesDataSourceConfig(randInt int) string { +func testAccObjectsDataSourceConfig_prefixes(randInt int) string { return fmt.Sprintf(` %s @@ -341,10 +341,10 @@ data "aws_s3_objects" "yesh" { prefix = "arch/" delimiter = "/" } -`, testAccObjectsResourcesDataSourceConfig(randInt)) +`, testAccObjectsDataSourceConfig_resources(randInt)) } -func testAccObjectsExtraResourceDataSourceConfig(randInt int) string { +func testAccObjectsDataSourceConfig_extraResource(randInt int) string { return fmt.Sprintf(` %s @@ -353,10 +353,10 @@ resource "aws_s3_object" "object8" { key = "arch/ru b ic on" content = "Goose Island" } -`, testAccObjectsResourcesDataSourceConfig(randInt)) +`, testAccObjectsDataSourceConfig_resources(randInt)) } -func testAccObjectsEncodedDataSourceConfig(randInt int) string { +func testAccObjectsDataSourceConfig_encoded(randInt int) string { return fmt.Sprintf(` %s @@ -365,10 +365,10 @@ data "aws_s3_objects" "yesh" { encoding_type = "url" prefix = "arch/ru" } -`, testAccObjectsExtraResourceDataSourceConfig(randInt)) +`, testAccObjectsDataSourceConfig_extraResource(randInt)) } -func testAccObjectsMaxKeysDataSourceConfig(randInt int) string { +func testAccObjectsDataSourceConfig_maxKeys(randInt int) string { return fmt.Sprintf(` %s @@ -376,10 +376,10 @@ data "aws_s3_objects" "yesh" { bucket = aws_s3_bucket.objects_bucket.id max_keys = 2 } -`, testAccObjectsResourcesDataSourceConfig(randInt)) +`, testAccObjectsDataSourceConfig_resources(randInt)) } -func testAccObjectsStartAfterDataSourceConfig(randInt int) string { +func testAccObjectsDataSourceConfig_startAfter(randInt int) string { return fmt.Sprintf(` %s @@ -387,10 +387,10 @@ data "aws_s3_objects" "yesh" { bucket = aws_s3_bucket.objects_bucket.id start_after = "arch/three_gossips/broken" } -`, testAccObjectsResourcesDataSourceConfig(randInt)) +`, testAccObjectsDataSourceConfig_resources(randInt)) } -func testAccObjectsOwnersDataSourceConfig(randInt int) string { +func testAccObjectsDataSourceConfig_owners(randInt int) string { return fmt.Sprintf(` %s @@ -399,5 +399,5 @@ data "aws_s3_objects" "yesh" { prefix = "arch/three_gossips/" fetch_owner = true } -`, testAccObjectsResourcesDataSourceConfig(randInt)) +`, testAccObjectsDataSourceConfig_resources(randInt)) } diff --git a/internal/service/s3control/access_point_policy_test.go b/internal/service/s3control/access_point_policy_test.go index cf9e42f7f21..3e55f6c937a 100644 --- a/internal/service/s3control/access_point_policy_test.go +++ b/internal/service/s3control/access_point_policy_test.go @@ -26,7 +26,7 @@ func TestAccS3ControlAccessPointPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckAccessPointPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointPolicyConfig(rName), + Config: testAccAccessPointPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "has_public_access_policy", "true"), @@ -54,7 +54,7 @@ func TestAccS3ControlAccessPointPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckAccessPointPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointPolicyConfig(rName), + Config: testAccAccessPointPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3control.ResourceAccessPointPolicy(), resourceName), @@ -77,7 +77,7 @@ func TestAccS3ControlAccessPointPolicy_disappears_AccessPoint(t *testing.T) { CheckDestroy: testAccCheckAccessPointPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointPolicyConfig(rName), + Config: testAccAccessPointPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3control.ResourceAccessPoint(), accessPointResourceName), @@ -99,7 +99,7 @@ func TestAccS3ControlAccessPointPolicy_update(t *testing.T) { CheckDestroy: testAccCheckAccessPointPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointPolicyConfig(rName), + Config: testAccAccessPointPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "has_public_access_policy", "true"), @@ -113,7 +113,7 @@ func TestAccS3ControlAccessPointPolicy_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAccessPointPolicyUpdatedConfig(rName), + Config: testAccAccessPointPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointPolicyExists(resourceName), resource.TestCheckResourceAttr(resourceName, "has_public_access_policy", "true"), @@ -194,7 +194,7 @@ func testAccCheckAccessPointPolicyExists(n string) resource.TestCheckFunc { } } -func testAccAccessPointPolicyConfig(rName string) string { +func testAccAccessPointPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -234,7 +234,7 @@ resource "aws_s3control_access_point_policy" "test" { `, rName) } -func testAccAccessPointPolicyUpdatedConfig(rName string) string { +func testAccAccessPointPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3control/access_point_test.go b/internal/service/s3control/access_point_test.go index 83e2743e1de..06bfb4bed7b 100644 --- a/internal/service/s3control/access_point_test.go +++ b/internal/service/s3control/access_point_test.go @@ -96,7 +96,7 @@ func TestAccS3ControlAccessPoint_Bucket_arn(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointConfig_Bucket_ARN(rName), + Config: testAccAccessPointConfig_bucketARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &v), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -231,7 +231,7 @@ func TestAccS3ControlAccessPoint_publicAccessBlock(t *testing.T) { CheckDestroy: testAccCheckAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccAccessPointConfig_publicAccessBlock(rName), + Config: testAccAccessPointConfig_publicBlock(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccessPointExists(resourceName, &v), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -412,7 +412,7 @@ resource "aws_s3_access_point" "test" { `, bucketName, accessPointName) } -func testAccAccessPointConfig_Bucket_ARN(rName string) string { +func testAccAccessPointConfig_bucketARN(rName string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -555,7 +555,7 @@ resource "aws_s3_access_point" "test" { `, rName) } -func testAccAccessPointConfig_publicAccessBlock(rName string) string { +func testAccAccessPointConfig_publicBlock(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3control/account_public_access_block_test.go b/internal/service/s3control/account_public_access_block_test.go index 5c4b281b949..7fb27502295 100644 --- a/internal/service/s3control/account_public_access_block_test.go +++ b/internal/service/s3control/account_public_access_block_test.go @@ -55,7 +55,7 @@ func testAccAccountPublicAccessBlock_basic(t *testing.T) { CheckDestroy: testAccCheckAccountPublicAccessBlockDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountPublicAccessBlockConfig(), + Config: testAccAccountPublicAccessBlockConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration1), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -85,7 +85,7 @@ func testAccAccountPublicAccessBlock_disappears(t *testing.T) { CheckDestroy: testAccCheckAccountPublicAccessBlockDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountPublicAccessBlockConfig(), + Config: testAccAccountPublicAccessBlockConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration1), testAccCheckAccountPublicAccessBlockDisappears(), @@ -107,7 +107,7 @@ func testAccAccountPublicAccessBlock_AccountID(t *testing.T) { CheckDestroy: testAccCheckAccountPublicAccessBlockDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountPublicAccessBlockAccountIDConfig(), + Config: testAccAccountPublicAccessBlockConfig_id(), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration1), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -133,7 +133,7 @@ func testAccAccountPublicAccessBlock_BlockPublicACLs(t *testing.T) { CheckDestroy: testAccCheckAccountPublicAccessBlockDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountPublicAccessBlockBlockPublicACLsConfig(true), + Config: testAccAccountPublicAccessBlockConfig_acls(true), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration1), resource.TestCheckResourceAttr(resourceName, "block_public_acls", "true"), @@ -145,14 +145,14 @@ func testAccAccountPublicAccessBlock_BlockPublicACLs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAccountPublicAccessBlockBlockPublicACLsConfig(false), + Config: testAccAccountPublicAccessBlockConfig_acls(false), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration2), resource.TestCheckResourceAttr(resourceName, "block_public_acls", "false"), ), }, { - Config: testAccAccountPublicAccessBlockBlockPublicACLsConfig(true), + Config: testAccAccountPublicAccessBlockConfig_acls(true), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration3), resource.TestCheckResourceAttr(resourceName, "block_public_acls", "true"), @@ -173,7 +173,7 @@ func testAccAccountPublicAccessBlock_BlockPublicPolicy(t *testing.T) { CheckDestroy: testAccCheckAccountPublicAccessBlockDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountPublicAccessBlockBlockPublicPolicyConfig(true), + Config: testAccAccountPublicAccessBlockConfig_policy(true), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration1), resource.TestCheckResourceAttr(resourceName, "block_public_policy", "true"), @@ -185,14 +185,14 @@ func testAccAccountPublicAccessBlock_BlockPublicPolicy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAccountPublicAccessBlockBlockPublicPolicyConfig(false), + Config: testAccAccountPublicAccessBlockConfig_policy(false), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration2), resource.TestCheckResourceAttr(resourceName, "block_public_policy", "false"), ), }, { - Config: testAccAccountPublicAccessBlockBlockPublicPolicyConfig(true), + Config: testAccAccountPublicAccessBlockConfig_policy(true), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration3), resource.TestCheckResourceAttr(resourceName, "block_public_policy", "true"), @@ -213,7 +213,7 @@ func testAccAccountPublicAccessBlock_IgnorePublicACLs(t *testing.T) { CheckDestroy: testAccCheckAccountPublicAccessBlockDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountPublicAccessBlockIgnorePublicACLsConfig(true), + Config: testAccAccountPublicAccessBlockConfig_ignoreACLs(true), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration1), resource.TestCheckResourceAttr(resourceName, "ignore_public_acls", "true"), @@ -225,14 +225,14 @@ func testAccAccountPublicAccessBlock_IgnorePublicACLs(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAccountPublicAccessBlockIgnorePublicACLsConfig(false), + Config: testAccAccountPublicAccessBlockConfig_ignoreACLs(false), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration2), resource.TestCheckResourceAttr(resourceName, "ignore_public_acls", "false"), ), }, { - Config: testAccAccountPublicAccessBlockIgnorePublicACLsConfig(true), + Config: testAccAccountPublicAccessBlockConfig_ignoreACLs(true), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration3), resource.TestCheckResourceAttr(resourceName, "ignore_public_acls", "true"), @@ -253,7 +253,7 @@ func testAccAccountPublicAccessBlock_RestrictPublicBuckets(t *testing.T) { CheckDestroy: testAccCheckAccountPublicAccessBlockDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountPublicAccessBlockRestrictPublicBucketsConfig(true), + Config: testAccAccountPublicAccessBlockConfig_restrictBuckets(true), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration1), resource.TestCheckResourceAttr(resourceName, "restrict_public_buckets", "true"), @@ -265,14 +265,14 @@ func testAccAccountPublicAccessBlock_RestrictPublicBuckets(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAccountPublicAccessBlockRestrictPublicBucketsConfig(false), + Config: testAccAccountPublicAccessBlockConfig_restrictBuckets(false), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration2), resource.TestCheckResourceAttr(resourceName, "restrict_public_buckets", "false"), ), }, { - Config: testAccAccountPublicAccessBlockRestrictPublicBucketsConfig(true), + Config: testAccAccountPublicAccessBlockConfig_restrictBuckets(true), Check: resource.ComposeTestCheckFunc( testAccCheckAccountPublicAccessBlockExists(resourceName, &configuration3), resource.TestCheckResourceAttr(resourceName, "restrict_public_buckets", "true"), @@ -401,11 +401,11 @@ func testAccCheckAccountPublicAccessBlockDisappears() resource.TestCheckFunc { } } -func testAccAccountPublicAccessBlockConfig() string { +func testAccAccountPublicAccessBlockConfig_basic() string { return `resource "aws_s3_account_public_access_block" "test" {}` } -func testAccAccountPublicAccessBlockAccountIDConfig() string { +func testAccAccountPublicAccessBlockConfig_id() string { return ` data "aws_caller_identity" "test" {} @@ -415,7 +415,7 @@ resource "aws_s3_account_public_access_block" "test" { ` } -func testAccAccountPublicAccessBlockBlockPublicACLsConfig(blockPublicAcls bool) string { +func testAccAccountPublicAccessBlockConfig_acls(blockPublicAcls bool) string { return fmt.Sprintf(` resource "aws_s3_account_public_access_block" "test" { block_public_acls = %t @@ -423,7 +423,7 @@ resource "aws_s3_account_public_access_block" "test" { `, blockPublicAcls) } -func testAccAccountPublicAccessBlockBlockPublicPolicyConfig(blockPublicPolicy bool) string { +func testAccAccountPublicAccessBlockConfig_policy(blockPublicPolicy bool) string { return fmt.Sprintf(` resource "aws_s3_account_public_access_block" "test" { block_public_policy = %t @@ -431,7 +431,7 @@ resource "aws_s3_account_public_access_block" "test" { `, blockPublicPolicy) } -func testAccAccountPublicAccessBlockIgnorePublicACLsConfig(ignorePublicAcls bool) string { +func testAccAccountPublicAccessBlockConfig_ignoreACLs(ignorePublicAcls bool) string { return fmt.Sprintf(` resource "aws_s3_account_public_access_block" "test" { ignore_public_acls = %t @@ -439,7 +439,7 @@ resource "aws_s3_account_public_access_block" "test" { `, ignorePublicAcls) } -func testAccAccountPublicAccessBlockRestrictPublicBucketsConfig(restrictPublicBuckets bool) string { +func testAccAccountPublicAccessBlockConfig_restrictBuckets(restrictPublicBuckets bool) string { return fmt.Sprintf(` resource "aws_s3_account_public_access_block" "test" { restrict_public_buckets = %t diff --git a/internal/service/s3control/bucket_lifecycle_configuration_test.go b/internal/service/s3control/bucket_lifecycle_configuration_test.go index 97fa04279ab..aed773f6229 100644 --- a/internal/service/s3control/bucket_lifecycle_configuration_test.go +++ b/internal/service/s3control/bucket_lifecycle_configuration_test.go @@ -28,7 +28,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_ID(rName, "test"), + Config: testAccBucketLifecycleConfigurationConfig_ruleID(rName, "test"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3control_bucket.test", "arn"), @@ -61,7 +61,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_ID(rName, "test"), + Config: testAccBucketLifecycleConfigurationConfig_ruleID(rName, "test"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3control.ResourceBucketLifecycleConfiguration(), resourceName), @@ -83,7 +83,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleAbortIncompleteMultipartUp CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_AbortIncompleteMultipartUpload_DaysAfterInitiation(rName, 1), + Config: testAccBucketLifecycleConfigurationConfig_ruleAbortIncompleteMultipartUploadDaysAfterInitiation(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -99,7 +99,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleAbortIncompleteMultipartUp ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfigurationConfig_Rule_AbortIncompleteMultipartUpload_DaysAfterInitiation(rName, 2), + Config: testAccBucketLifecycleConfigurationConfig_ruleAbortIncompleteMultipartUploadDaysAfterInitiation(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -126,7 +126,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleExpiration_date(t *testing CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Expiration_Date(rName, date1), + Config: testAccBucketLifecycleConfigurationConfig_ruleExpirationDate(rName, date1), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -142,7 +142,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleExpiration_date(t *testing ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Expiration_Date(rName, date2), + Config: testAccBucketLifecycleConfigurationConfig_ruleExpirationDate(rName, date2), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -167,7 +167,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleExpiration_days(t *testing CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Expiration_Days(rName, 7), + Config: testAccBucketLifecycleConfigurationConfig_ruleExpirationDays(rName, 7), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -183,7 +183,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleExpiration_days(t *testing ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Expiration_Days(rName, 30), + Config: testAccBucketLifecycleConfigurationConfig_ruleExpirationDays(rName, 30), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -209,7 +209,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleExpiration_expiredObjectDe CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Expiration_ExpiredObjectDeleteMarker(rName, true), + Config: testAccBucketLifecycleConfigurationConfig_ruleExpirationExpiredObjectDeleteMarker(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -225,7 +225,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleExpiration_expiredObjectDe ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Expiration_ExpiredObjectDeleteMarker(rName, false), + Config: testAccBucketLifecycleConfigurationConfig_ruleExpirationExpiredObjectDeleteMarker(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -250,7 +250,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleFilter_prefix(t *testing.T CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Filter_Prefix(rName, "test1/"), + Config: testAccBucketLifecycleConfigurationConfig_ruleFilterPrefix(rName, "test1/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -266,7 +266,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleFilter_prefix(t *testing.T ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Filter_Prefix(rName, "test2/"), + Config: testAccBucketLifecycleConfigurationConfig_ruleFilterPrefix(rName, "test2/"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -291,7 +291,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleFilter_tags(t *testing.T) CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Filter_Tags1(rName, "key1", "value1"), + Config: testAccBucketLifecycleConfigurationConfig_ruleFilterTags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -311,7 +311,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleFilter_tags(t *testing.T) // does not get populated from the XML response. Reference: // https://github.com/aws/aws-sdk-go/issues/3591 // { - // Config: testAccBucketLifecycleConfigurationConfig_Rule_Filter_tags2(rName, "key1", "value1updated", "key2", "value2"), + // Config: testAccBucketLifecycleConfigurationConfig_ruleFilterTags2(rName, "key1", "value1updated", "key2", "value2"), // Check: resource.ComposeTestCheckFunc( // testAccCheckBucketLifecycleConfigurationExists(resourceName), // resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -324,7 +324,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_RuleFilter_tags(t *testing.T) // ), // }, { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Filter_Tags1(rName, "key2", "value2"), + Config: testAccBucketLifecycleConfigurationConfig_ruleFilterTags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -350,7 +350,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_Rule_id(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_ID(rName, "test1"), + Config: testAccBucketLifecycleConfigurationConfig_ruleID(rName, "test1"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -365,7 +365,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_Rule_id(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfigurationConfig_Rule_ID(rName, "test2"), + Config: testAccBucketLifecycleConfigurationConfig_ruleID(rName, "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -389,7 +389,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_Rule_status(t *testing.T) { CheckDestroy: testAccCheckBucketLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Status(rName, s3control.ExpirationStatusDisabled), + Config: testAccBucketLifecycleConfigurationConfig_ruleStatus(rName, s3control.ExpirationStatusDisabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -404,7 +404,7 @@ func TestAccS3ControlBucketLifecycleConfiguration_Rule_status(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketLifecycleConfigurationConfig_Rule_Status(rName, s3control.ExpirationStatusEnabled), + Config: testAccBucketLifecycleConfigurationConfig_ruleStatus(rName, s3control.ExpirationStatusEnabled), Check: resource.ComposeTestCheckFunc( testAccCheckBucketLifecycleConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), @@ -494,7 +494,7 @@ func testAccCheckBucketLifecycleConfigurationExists(resourceName string) resourc } } -func testAccBucketLifecycleConfigurationConfig_Rule_AbortIncompleteMultipartUpload_DaysAfterInitiation(rName string, daysAfterInitiation int) string { +func testAccBucketLifecycleConfigurationConfig_ruleAbortIncompleteMultipartUploadDaysAfterInitiation(rName string, daysAfterInitiation int) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -525,7 +525,7 @@ resource "aws_s3control_bucket_lifecycle_configuration" "test" { `, rName, daysAfterInitiation) } -func testAccBucketLifecycleConfigurationConfig_Rule_Expiration_Date(rName string, date string) string { +func testAccBucketLifecycleConfigurationConfig_ruleExpirationDate(rName string, date string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -552,7 +552,7 @@ resource "aws_s3control_bucket_lifecycle_configuration" "test" { `, rName, date) } -func testAccBucketLifecycleConfigurationConfig_Rule_Expiration_Days(rName string, days int) string { +func testAccBucketLifecycleConfigurationConfig_ruleExpirationDays(rName string, days int) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -579,7 +579,7 @@ resource "aws_s3control_bucket_lifecycle_configuration" "test" { `, rName, days) } -func testAccBucketLifecycleConfigurationConfig_Rule_Expiration_ExpiredObjectDeleteMarker(rName string, expiredObjectDeleteMarker bool) string { +func testAccBucketLifecycleConfigurationConfig_ruleExpirationExpiredObjectDeleteMarker(rName string, expiredObjectDeleteMarker bool) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -607,7 +607,7 @@ resource "aws_s3control_bucket_lifecycle_configuration" "test" { `, rName, expiredObjectDeleteMarker) } -func testAccBucketLifecycleConfigurationConfig_Rule_Filter_Prefix(rName, prefix string) string { +func testAccBucketLifecycleConfigurationConfig_ruleFilterPrefix(rName, prefix string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -638,7 +638,7 @@ resource "aws_s3control_bucket_lifecycle_configuration" "test" { `, rName, prefix) } -func testAccBucketLifecycleConfigurationConfig_Rule_Filter_Tags1(rName, tagKey1, tagValue1 string) string { +func testAccBucketLifecycleConfigurationConfig_ruleFilterTags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -672,7 +672,7 @@ resource "aws_s3control_bucket_lifecycle_configuration" "test" { } // See TestAccS3ControlBucketLifecycleConfiguration_RuleFilter_tags note about XML handling bug. -// func testAccBucketLifecycleConfigurationConfig_Rule_Filter_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +// func testAccBucketLifecycleConfigurationConfig_ruleFilterTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { // return fmt.Sprintf(` // data "aws_outposts_outposts" "test" {} @@ -706,7 +706,7 @@ resource "aws_s3control_bucket_lifecycle_configuration" "test" { // `, rName, tagKey1, tagValue1, tagKey2, tagValue2) // } -func testAccBucketLifecycleConfigurationConfig_Rule_ID(rName, id string) string { +func testAccBucketLifecycleConfigurationConfig_ruleID(rName, id string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -733,7 +733,7 @@ resource "aws_s3control_bucket_lifecycle_configuration" "test" { `, rName, id) } -func testAccBucketLifecycleConfigurationConfig_Rule_Status(rName, status string) string { +func testAccBucketLifecycleConfigurationConfig_ruleStatus(rName, status string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/s3control/bucket_policy_test.go b/internal/service/s3control/bucket_policy_test.go index aab698c4ca0..3836093e317 100644 --- a/internal/service/s3control/bucket_policy_test.go +++ b/internal/service/s3control/bucket_policy_test.go @@ -28,7 +28,7 @@ func TestAccS3ControlBucketPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckBucketPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyConfig_Policy(rName, "s3-outposts:*"), + Config: testAccBucketPolicyConfig_basic(rName, "s3-outposts:*"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPolicyExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "bucket", "aws_s3control_bucket.test", "arn"), @@ -55,7 +55,7 @@ func TestAccS3ControlBucketPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyConfig_Policy(rName, "s3-outposts:*"), + Config: testAccBucketPolicyConfig_basic(rName, "s3-outposts:*"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3control.ResourceBucketPolicy(), resourceName), @@ -77,7 +77,7 @@ func TestAccS3ControlBucketPolicy_policy(t *testing.T) { CheckDestroy: testAccCheckBucketPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketPolicyConfig_Policy(rName, "s3-outposts:GetObject"), + Config: testAccBucketPolicyConfig_basic(rName, "s3-outposts:GetObject"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPolicyExists(resourceName), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(`s3-outposts:GetObject`)), @@ -89,7 +89,7 @@ func TestAccS3ControlBucketPolicy_policy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketPolicyConfig_Policy(rName, "s3-outposts:PutObject"), + Config: testAccBucketPolicyConfig_basic(rName, "s3-outposts:PutObject"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketPolicyExists(resourceName), resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(`s3-outposts:PutObject`)), @@ -176,7 +176,7 @@ func testAccCheckBucketPolicyExists(resourceName string) resource.TestCheckFunc } } -func testAccBucketPolicyConfig_Policy(rName, action string) string { +func testAccBucketPolicyConfig_basic(rName, action string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/s3control/bucket_test.go b/internal/service/s3control/bucket_test.go index 9ba9cf392a8..96e6f0530aa 100644 --- a/internal/service/s3control/bucket_test.go +++ b/internal/service/s3control/bucket_test.go @@ -28,7 +28,7 @@ func TestAccS3ControlBucket_basic(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_Bucket(rName), + Config: testAccBucketConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "s3-outposts", regexp.MustCompile(fmt.Sprintf("outpost/[^/]+/bucket/%s", rName))), @@ -59,7 +59,7 @@ func TestAccS3ControlBucket_disappears(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_Bucket(rName), + Config: testAccBucketConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3control.ResourceBucket(), resourceName), @@ -83,7 +83,7 @@ func TestAccS3ControlBucket_tags(t *testing.T) { CheckDestroy: testAccCheckBucketDestroy, Steps: []resource.TestStep{ { - Config: testAccBucketConfig_Tags1(rName, "key1", "value1"), + Config: testAccBucketConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -96,7 +96,7 @@ func TestAccS3ControlBucket_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccBucketConfig_Tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccBucketConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -105,7 +105,7 @@ func TestAccS3ControlBucket_tags(t *testing.T) { ), }, { - Config: testAccBucketConfig_Tags1(rName, "key2", "value2"), + Config: testAccBucketConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckBucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -185,7 +185,7 @@ func testAccCheckBucketExists(resourceName string) resource.TestCheckFunc { } } -func testAccBucketConfig_Bucket(rName string) string { +func testAccBucketConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -200,7 +200,7 @@ resource "aws_s3control_bucket" "test" { `, rName) } -func testAccBucketConfig_Tags1(rName, tagKey1, tagValue1 string) string { +func testAccBucketConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} @@ -219,7 +219,7 @@ resource "aws_s3control_bucket" "test" { `, rName, tagKey1, tagValue1) } -func testAccBucketConfig_Tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccBucketConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/s3control/multi_region_access_point_test.go b/internal/service/s3control/multi_region_access_point_test.go index ac591ea428b..f28a5e8683b 100644 --- a/internal/service/s3control/multi_region_access_point_test.go +++ b/internal/service/s3control/multi_region_access_point_test.go @@ -109,7 +109,7 @@ func TestAccS3ControlMultiRegionAccessPoint_PublicAccessBlock(t *testing.T) { CheckDestroy: testAccCheckMultiRegionAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccMultiRegionAccessPointConfig_publicAccessBlock(bucketName, rName), + Config: testAccMultiRegionAccessPointConfig_publicBlock(bucketName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckMultiRegionAccessPointExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "details.0.public_access_block.#", "1"), @@ -189,7 +189,7 @@ func TestAccS3ControlMultiRegionAccessPoint_threeRegions(t *testing.T) { CheckDestroy: testAccCheckMultiRegionAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccMultiRegionAccessPointConfig_threeRegions(bucket1Name, bucket2Name, bucket3Name, rName), + Config: testAccMultiRegionAccessPointConfig_three(bucket1Name, bucket2Name, bucket3Name, rName), Check: resource.ComposeTestCheckFunc( testAccCheckMultiRegionAccessPointExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "details.0.region.#", "3"), @@ -315,7 +315,7 @@ resource "aws_s3control_multi_region_access_point" "test" { `, bucketName, multiRegionAccessPointName) } -func testAccMultiRegionAccessPointConfig_publicAccessBlock(bucketName, multiRegionAccessPointName string) string { +func testAccMultiRegionAccessPointConfig_publicBlock(bucketName, multiRegionAccessPointName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -341,7 +341,7 @@ resource "aws_s3control_multi_region_access_point" "test" { `, bucketName, multiRegionAccessPointName) } -func testAccMultiRegionAccessPointConfig_threeRegions(bucketName1, bucketName2, bucketName3, multiRegionAccessPointName string) string { +func testAccMultiRegionAccessPointConfig_three(bucketName1, bucketName2, bucketName3, multiRegionAccessPointName string) string { return acctest.ConfigCompose( acctest.ConfigMultipleRegionProvider(3), fmt.Sprintf(` diff --git a/internal/service/s3control/object_lambda_access_point_policy_test.go b/internal/service/s3control/object_lambda_access_point_policy_test.go index fe3cf9bb38c..a17fec52479 100644 --- a/internal/service/s3control/object_lambda_access_point_policy_test.go +++ b/internal/service/s3control/object_lambda_access_point_policy_test.go @@ -25,7 +25,7 @@ func TestAccS3ControlObjectLambdaAccessPointPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckObjectLambdaAccessPointPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectLambdaAccessPointPolicyConfig(rName), + Config: testAccObjectLambdaAccessPointPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectLambdaAccessPointPolicyExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -54,7 +54,7 @@ func TestAccS3ControlObjectLambdaAccessPointPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckObjectLambdaAccessPointPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectLambdaAccessPointPolicyConfig(rName), + Config: testAccObjectLambdaAccessPointPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectLambdaAccessPointPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3control.ResourceObjectLambdaAccessPointPolicy(), resourceName), @@ -77,7 +77,7 @@ func TestAccS3ControlObjectLambdaAccessPointPolicy_Disappears_accessPoint(t *tes CheckDestroy: testAccCheckObjectLambdaAccessPointPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectLambdaAccessPointPolicyConfig(rName), + Config: testAccObjectLambdaAccessPointPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectLambdaAccessPointPolicyExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3control.ResourceObjectLambdaAccessPoint(), accessPointResourceName), @@ -99,7 +99,7 @@ func TestAccS3ControlObjectLambdaAccessPointPolicy_update(t *testing.T) { CheckDestroy: testAccCheckObjectLambdaAccessPointPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectLambdaAccessPointPolicyConfig(rName), + Config: testAccObjectLambdaAccessPointPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectLambdaAccessPointPolicyExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -114,7 +114,7 @@ func TestAccS3ControlObjectLambdaAccessPointPolicy_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccObjectLambdaAccessPointPolicyUpdatedConfig(rName), + Config: testAccObjectLambdaAccessPointPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectLambdaAccessPointPolicyExists(resourceName), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -186,7 +186,7 @@ func testAccCheckObjectLambdaAccessPointPolicyExists(n string) resource.TestChec } } -func testAccObjectLambdaAccessPointPolicyConfig(rName string) string { +func testAccObjectLambdaAccessPointPolicyConfig_basic(rName string) string { return acctest.ConfigCompose(testAccObjectLambdaAccessPointBaseConfig(rName), fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -235,7 +235,7 @@ resource "aws_s3control_object_lambda_access_point_policy" "test" { `, rName)) } -func testAccObjectLambdaAccessPointPolicyUpdatedConfig(rName string) string { +func testAccObjectLambdaAccessPointPolicyConfig_updated(rName string) string { return acctest.ConfigCompose(testAccObjectLambdaAccessPointBaseConfig(rName), fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/s3control/object_lambda_access_point_test.go b/internal/service/s3control/object_lambda_access_point_test.go index d4499456e5b..24745ca6559 100644 --- a/internal/service/s3control/object_lambda_access_point_test.go +++ b/internal/service/s3control/object_lambda_access_point_test.go @@ -28,7 +28,7 @@ func TestAccS3ControlObjectLambdaAccessPoint_basic(t *testing.T) { CheckDestroy: testAccCheckObjectLambdaAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectLambdaAccessPointConfig(rName), + Config: testAccObjectLambdaAccessPointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectLambdaAccessPointExists(resourceName, &v), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -69,7 +69,7 @@ func TestAccS3ControlObjectLambdaAccessPoint_disappears(t *testing.T) { CheckDestroy: testAccCheckObjectLambdaAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectLambdaAccessPointConfig(rName), + Config: testAccObjectLambdaAccessPointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectLambdaAccessPointExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfs3control.ResourceObjectLambdaAccessPoint(), resourceName), @@ -94,7 +94,7 @@ func TestAccS3ControlObjectLambdaAccessPoint_update(t *testing.T) { CheckDestroy: testAccCheckObjectLambdaAccessPointDestroy, Steps: []resource.TestStep{ { - Config: testAccObjectLambdaAccessPointOptionalsConfig(rName), + Config: testAccObjectLambdaAccessPointConfig_optionals(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectLambdaAccessPointExists(resourceName, &v), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -122,7 +122,7 @@ func TestAccS3ControlObjectLambdaAccessPoint_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccObjectLambdaAccessPointConfig(rName), + Config: testAccObjectLambdaAccessPointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckObjectLambdaAccessPointExists(resourceName, &v), acctest.CheckResourceAttrAccountID(resourceName, "account_id"), @@ -219,7 +219,7 @@ resource "aws_lambda_function" "test" { `, rName)) } -func testAccObjectLambdaAccessPointConfig(rName string) string { +func testAccObjectLambdaAccessPointConfig_basic(rName string) string { return acctest.ConfigCompose(testAccObjectLambdaAccessPointBaseConfig(rName), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -250,7 +250,7 @@ resource "aws_s3control_object_lambda_access_point" "test" { `, rName)) } -func testAccObjectLambdaAccessPointOptionalsConfig(rName string) string { +func testAccObjectLambdaAccessPointConfig_optionals(rName string) string { return acctest.ConfigCompose(testAccObjectLambdaAccessPointBaseConfig(rName), fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q diff --git a/internal/service/s3outposts/endpoint_test.go b/internal/service/s3outposts/endpoint_test.go index 23d15bc3473..84f4dbd399f 100644 --- a/internal/service/s3outposts/endpoint_test.go +++ b/internal/service/s3outposts/endpoint_test.go @@ -25,7 +25,7 @@ func TestAccS3OutpostsEndpoint_basic(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig(rInt), + Config: testAccEndpointConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "s3-outposts", regexp.MustCompile(`outpost/[^/]+/endpoint/[a-z0-9]+`)), @@ -58,7 +58,7 @@ func TestAccS3OutpostsEndpoint_disappears(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig(rInt), + Config: testAccEndpointConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfs3outposts.ResourceEndpoint(), resourceName), @@ -129,7 +129,7 @@ func testAccEndpointImportStateIdFunc(resourceName string) resource.ImportStateI } } -func testAccEndpointConfig(rInt int) string { +func testAccEndpointConfig_basic(rInt int) string { return fmt.Sprintf(` data "aws_outposts_outposts" "test" {} diff --git a/internal/service/sagemaker/app_image_config_test.go b/internal/service/sagemaker/app_image_config_test.go index b0f61b1c219..219bed7ebef 100644 --- a/internal/service/sagemaker/app_image_config_test.go +++ b/internal/service/sagemaker/app_image_config_test.go @@ -27,7 +27,7 @@ func TestAccSageMakerAppImageConfig_basic(t *testing.T) { CheckDestroy: testAccCheckAppImageDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccAppImageBasicConfig(rName), + Config: testAccAppImageConfigConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppImageExistsConfig(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "app_image_config_name", rName), @@ -57,7 +57,7 @@ func TestAccSageMakerAppImageConfig_KernelGatewayImage_kernelSpecs(t *testing.T) CheckDestroy: testAccCheckAppImageDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccAppImageKernelGatewayImageKernalSpecs1Config(rName), + Config: testAccAppImageConfigConfig_kernelGatewayKernalSpecs1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppImageExistsConfig(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "app_image_config_name", rName), @@ -73,7 +73,7 @@ func TestAccSageMakerAppImageConfig_KernelGatewayImage_kernelSpecs(t *testing.T) ImportStateVerify: true, }, { - Config: testAccAppImageKernelGatewayImageKernalSpecs2Config(rName), + Config: testAccAppImageConfigConfig_kernelGatewayKernalSpecs2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppImageExistsConfig(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "app_image_config_name", rName), @@ -100,7 +100,7 @@ func TestAccSageMakerAppImageConfig_KernelGatewayImage_fileSystem(t *testing.T) CheckDestroy: testAccCheckAppImageDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccAppImageKernelGatewayImageFileSystem1Config(rName), + Config: testAccAppImageConfigConfig_kernelGatewayFileSystem1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppImageExistsConfig(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "app_image_config_name", rName), @@ -118,7 +118,7 @@ func TestAccSageMakerAppImageConfig_KernelGatewayImage_fileSystem(t *testing.T) ImportStateVerify: true, }, { - Config: testAccAppImageKernelGatewayImageFileSystem2Config(rName), + Config: testAccAppImageConfigConfig_kernelGatewayFileSystem2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppImageExistsConfig(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "app_image_config_name", rName), @@ -146,7 +146,7 @@ func TestAccSageMakerAppImageConfig_tags(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppImageTags1Config(rName, "key1", "value1"), + Config: testAccAppImageConfigConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAppImageExistsConfig(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -159,7 +159,7 @@ func TestAccSageMakerAppImageConfig_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAppImageTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAppImageConfigConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAppImageExistsConfig(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -168,7 +168,7 @@ func TestAccSageMakerAppImageConfig_tags(t *testing.T) { ), }, { - Config: testAccAppImageTags1Config(rName, "key2", "value2"), + Config: testAccAppImageConfigConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAppImageExistsConfig(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -191,7 +191,7 @@ func TestAccSageMakerAppImageConfig_disappears(t *testing.T) { CheckDestroy: testAccCheckAppImageDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccAppImageBasicConfig(rName), + Config: testAccAppImageConfigConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppImageExistsConfig(resourceName, &config), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceAppImageConfig(), resourceName), @@ -251,7 +251,7 @@ func testAccCheckAppImageExistsConfig(n string, config *sagemaker.DescribeAppIma } } -func testAccAppImageBasicConfig(rName string) string { +func testAccAppImageConfigConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_app_image_config" "test" { app_image_config_name = %[1]q @@ -259,7 +259,7 @@ resource "aws_sagemaker_app_image_config" "test" { `, rName) } -func testAccAppImageKernelGatewayImageKernalSpecs1Config(rName string) string { +func testAccAppImageConfigConfig_kernelGatewayKernalSpecs1(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_app_image_config" "test" { app_image_config_name = %[1]q @@ -273,7 +273,7 @@ resource "aws_sagemaker_app_image_config" "test" { `, rName) } -func testAccAppImageKernelGatewayImageKernalSpecs2Config(rName string) string { +func testAccAppImageConfigConfig_kernelGatewayKernalSpecs2(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_app_image_config" "test" { app_image_config_name = %[1]q @@ -288,7 +288,7 @@ resource "aws_sagemaker_app_image_config" "test" { `, rName) } -func testAccAppImageKernelGatewayImageFileSystem1Config(rName string) string { +func testAccAppImageConfigConfig_kernelGatewayFileSystem1(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_app_image_config" "test" { app_image_config_name = %[1]q @@ -304,7 +304,7 @@ resource "aws_sagemaker_app_image_config" "test" { `, rName) } -func testAccAppImageKernelGatewayImageFileSystem2Config(rName string) string { +func testAccAppImageConfigConfig_kernelGatewayFileSystem2(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_app_image_config" "test" { app_image_config_name = %[1]q @@ -324,7 +324,7 @@ resource "aws_sagemaker_app_image_config" "test" { `, rName) } -func testAccAppImageTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAppImageConfigConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_sagemaker_app_image_config" "test" { app_image_config_name = %[1]q @@ -336,7 +336,7 @@ resource "aws_sagemaker_app_image_config" "test" { `, rName, tagKey1, tagValue1) } -func testAccAppImageTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAppImageConfigConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_sagemaker_app_image_config" "test" { app_image_config_name = %[1]q diff --git a/internal/service/sagemaker/app_test.go b/internal/service/sagemaker/app_test.go index 6d48f063936..9550e75ddd7 100644 --- a/internal/service/sagemaker/app_test.go +++ b/internal/service/sagemaker/app_test.go @@ -32,7 +32,7 @@ func testAccApp_basic(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppBasicConfig(rName), + Config: testAccAppConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "app_name", rName), @@ -70,7 +70,7 @@ func testAccApp_resourceSpec(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppResourceSpecConfig(rName), + Config: testAccAppConfig_resourceSpec(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "app_name", rName), @@ -105,7 +105,7 @@ func testAccApp_resourceSpecLifecycle(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppResourceSpecLifecycleConfig(rName, uName), + Config: testAccAppConfig_resourceSpecLifecycle(rName, uName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "app_name", rName), @@ -140,7 +140,7 @@ func testAccApp_tags(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppTags1Config(rName, "key1", "value1"), + Config: testAccAppConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -153,7 +153,7 @@ func testAccApp_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAppTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccAppConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -162,7 +162,7 @@ func testAccApp_tags(t *testing.T) { ), }, { - Config: testAccAppTags1Config(rName, "key2", "value2"), + Config: testAccAppConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -189,7 +189,7 @@ func testAccApp_disappears(t *testing.T) { CheckDestroy: testAccCheckAppDestroy, Steps: []resource.TestStep{ { - Config: testAccAppBasicConfig(rName), + Config: testAccAppConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAppExists(resourceName, &app), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceApp(), resourceName), @@ -330,7 +330,7 @@ resource "aws_sagemaker_user_profile" "test" { `, rName) } -func testAccAppBasicConfig(rName string) string { +func testAccAppConfig_basic(rName string) string { return testAccAppBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_app" "test" { domain_id = aws_sagemaker_domain.test.id @@ -341,7 +341,7 @@ resource "aws_sagemaker_app" "test" { `, rName) } -func testAccAppTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccAppConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccAppBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_app" "test" { domain_id = aws_sagemaker_domain.test.id @@ -356,7 +356,7 @@ resource "aws_sagemaker_app" "test" { `, rName, tagKey1, tagValue1) } -func testAccAppTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccAppConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccAppBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_app" "test" { domain_id = aws_sagemaker_domain.test.id @@ -372,7 +372,7 @@ resource "aws_sagemaker_app" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccAppResourceSpecConfig(rName string) string { +func testAccAppConfig_resourceSpec(rName string) string { return testAccAppBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_app" "test" { domain_id = aws_sagemaker_domain.test.id @@ -387,7 +387,7 @@ resource "aws_sagemaker_app" "test" { `, rName) } -func testAccAppResourceSpecLifecycleConfig(rName, uName string) string { +func testAccAppConfig_resourceSpecLifecycle(rName, uName string) string { return testAccAppBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_studio_lifecycle_config" "test" { studio_lifecycle_config_name = %[1]q diff --git a/internal/service/sagemaker/code_repository_test.go b/internal/service/sagemaker/code_repository_test.go index fc75e728186..ac21e922191 100644 --- a/internal/service/sagemaker/code_repository_test.go +++ b/internal/service/sagemaker/code_repository_test.go @@ -27,7 +27,7 @@ func TestAccSageMakerCodeRepository_basic(t *testing.T) { CheckDestroy: testAccCheckCodeRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccCodeRepositoryBasicConfig(rName), + Config: testAccCodeRepositoryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCodeRepositoryExists(resourceName, &repo), resource.TestCheckResourceAttr(resourceName, "code_repository_name", rName), @@ -58,7 +58,7 @@ func TestAccSageMakerCodeRepository_Git_branch(t *testing.T) { CheckDestroy: testAccCheckCodeRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccCodeRepositoryGitBranchConfig(rName), + Config: testAccCodeRepositoryConfig_gitBranch(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCodeRepositoryExists(resourceName, &repo), resource.TestCheckResourceAttr(resourceName, "code_repository_name", rName), @@ -89,7 +89,7 @@ func TestAccSageMakerCodeRepository_Git_secret(t *testing.T) { CheckDestroy: testAccCheckCodeRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccCodeRepositoryGitSecretConfig(rName), + Config: testAccCodeRepositoryConfig_gitSecret(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCodeRepositoryExists(resourceName, &repo), resource.TestCheckResourceAttr(resourceName, "code_repository_name", rName), @@ -105,7 +105,7 @@ func TestAccSageMakerCodeRepository_Git_secret(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCodeRepositoryGitSecretUpdatedConfig(rName), + Config: testAccCodeRepositoryConfig_gitSecretUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCodeRepositoryExists(resourceName, &repo), resource.TestCheckResourceAttr(resourceName, "code_repository_name", rName), @@ -131,7 +131,7 @@ func TestAccSageMakerCodeRepository_tags(t *testing.T) { CheckDestroy: testAccCheckDeviceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccCodeRepositoryBasicConfigTags1(rName, "key1", "value1"), + Config: testAccCodeRepositoryConfig_basicTags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckCodeRepositoryExists(resourceName, &repo), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -144,7 +144,7 @@ func TestAccSageMakerCodeRepository_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCodeRepositoryBasicConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccCodeRepositoryConfig_basicTags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCodeRepositoryExists(resourceName, &repo), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -153,7 +153,7 @@ func TestAccSageMakerCodeRepository_tags(t *testing.T) { ), }, { - Config: testAccCodeRepositoryBasicConfigTags1(rName, "key2", "value2"), + Config: testAccCodeRepositoryConfig_basicTags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCodeRepositoryExists(resourceName, &repo), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -176,7 +176,7 @@ func TestAccSageMakerCodeRepository_disappears(t *testing.T) { CheckDestroy: testAccCheckCodeRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccCodeRepositoryBasicConfig(rName), + Config: testAccCodeRepositoryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCodeRepositoryExists(resourceName, &repo), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceCodeRepository(), resourceName), @@ -237,7 +237,7 @@ func testAccCheckCodeRepositoryExists(n string, codeRepo *sagemaker.DescribeCode } } -func testAccCodeRepositoryBasicConfig(rName string) string { +func testAccCodeRepositoryConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_code_repository" "test" { code_repository_name = %[1]q @@ -249,7 +249,7 @@ resource "aws_sagemaker_code_repository" "test" { `, rName) } -func testAccCodeRepositoryGitBranchConfig(rName string) string { +func testAccCodeRepositoryConfig_gitBranch(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_code_repository" "test" { code_repository_name = %[1]q @@ -262,7 +262,7 @@ resource "aws_sagemaker_code_repository" "test" { `, rName) } -func testAccCodeRepositoryGitSecretConfig(rName string) string { +func testAccCodeRepositoryConfig_gitSecret(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = %[1]q @@ -286,7 +286,7 @@ resource "aws_sagemaker_code_repository" "test" { `, rName) } -func testAccCodeRepositoryGitSecretUpdatedConfig(rName string) string { +func testAccCodeRepositoryConfig_gitSecretUpdated(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test2" { name = "%[1]s-2" @@ -310,7 +310,7 @@ resource "aws_sagemaker_code_repository" "test" { `, rName) } -func testAccCodeRepositoryBasicConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccCodeRepositoryConfig_basicTags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_sagemaker_code_repository" "test" { code_repository_name = %[1]q @@ -326,7 +326,7 @@ resource "aws_sagemaker_code_repository" "test" { `, rName, tagKey1, tagValue1) } -func testAccCodeRepositoryBasicConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccCodeRepositoryConfig_basicTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_sagemaker_code_repository" "test" { code_repository_name = %[1]q diff --git a/internal/service/sagemaker/device_fleet_test.go b/internal/service/sagemaker/device_fleet_test.go index e85e9c76097..71efecbbfb5 100644 --- a/internal/service/sagemaker/device_fleet_test.go +++ b/internal/service/sagemaker/device_fleet_test.go @@ -27,7 +27,7 @@ func TestAccSageMakerDeviceFleet_basic(t *testing.T) { CheckDestroy: testAccCheckDeviceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceFleetBasicConfig(rName), + Config: testAccDeviceFleetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceFleetExists(resourceName, &deviceFleet), resource.TestCheckResourceAttr(resourceName, "device_fleet_name", rName), @@ -61,7 +61,7 @@ func TestAccSageMakerDeviceFleet_description(t *testing.T) { CheckDestroy: testAccCheckDeviceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceFleetDescription(rName, rName), + Config: testAccDeviceFleetConfig_description(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceFleetExists(resourceName, &deviceFleet), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -73,7 +73,7 @@ func TestAccSageMakerDeviceFleet_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeviceFleetDescription(rName, "test"), + Config: testAccDeviceFleetConfig_description(rName, "test"), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceFleetExists(resourceName, &deviceFleet), resource.TestCheckResourceAttr(resourceName, "description", "test"), @@ -95,7 +95,7 @@ func TestAccSageMakerDeviceFleet_tags(t *testing.T) { CheckDestroy: testAccCheckDeviceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceFleetTags1Config(rName, "key1", "value1"), + Config: testAccDeviceFleetConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceFleetExists(resourceName, &deviceFleet), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -108,7 +108,7 @@ func TestAccSageMakerDeviceFleet_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeviceFleetTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDeviceFleetConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceFleetExists(resourceName, &deviceFleet), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -117,7 +117,7 @@ func TestAccSageMakerDeviceFleet_tags(t *testing.T) { ), }, { - Config: testAccDeviceFleetTags1Config(rName, "key2", "value2"), + Config: testAccDeviceFleetConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceFleetExists(resourceName, &deviceFleet), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -140,7 +140,7 @@ func TestAccSageMakerDeviceFleet_disappears(t *testing.T) { CheckDestroy: testAccCheckDeviceFleetDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceFleetBasicConfig(rName), + Config: testAccDeviceFleetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceFleetExists(resourceName, &deviceFleet), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceDeviceFleet(), resourceName), @@ -267,7 +267,7 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName) } -func testAccDeviceFleetBasicConfig(rName string) string { +func testAccDeviceFleetConfig_basic(rName string) string { return testAccDeviceFleetBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_device_fleet" "test" { device_fleet_name = %[1]q @@ -280,7 +280,7 @@ resource "aws_sagemaker_device_fleet" "test" { `, rName) } -func testAccDeviceFleetDescription(rName, desc string) string { +func testAccDeviceFleetConfig_description(rName, desc string) string { return testAccDeviceFleetBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_device_fleet" "test" { device_fleet_name = %[1]q @@ -294,7 +294,7 @@ resource "aws_sagemaker_device_fleet" "test" { `, rName, desc) } -func testAccDeviceFleetTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccDeviceFleetConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccDeviceFleetBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_device_fleet" "test" { device_fleet_name = %[1]q @@ -311,7 +311,7 @@ resource "aws_sagemaker_device_fleet" "test" { `, rName, tagKey1, tagValue1) } -func testAccDeviceFleetTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDeviceFleetConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccDeviceFleetBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_device_fleet" "test" { device_fleet_name = %[1]q diff --git a/internal/service/sagemaker/device_test.go b/internal/service/sagemaker/device_test.go index 5eaa4518001..4184e6cde1a 100644 --- a/internal/service/sagemaker/device_test.go +++ b/internal/service/sagemaker/device_test.go @@ -27,7 +27,7 @@ func TestAccSageMakerDevice_basic(t *testing.T) { CheckDestroy: testAccCheckDeviceDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceBasicConfig(rName), + Config: testAccDeviceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceExists(resourceName, &device), resource.TestCheckResourceAttr(resourceName, "device_fleet_name", rName), @@ -57,7 +57,7 @@ func TestAccSageMakerDevice_description(t *testing.T) { CheckDestroy: testAccCheckDeviceDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceDescription(rName, rName), + Config: testAccDeviceConfig_description(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceExists(resourceName, &device), resource.TestCheckResourceAttr(resourceName, "device.0.description", rName), @@ -69,7 +69,7 @@ func TestAccSageMakerDevice_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDeviceDescription(rName, "test"), + Config: testAccDeviceConfig_description(rName, "test"), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceExists(resourceName, &device), resource.TestCheckResourceAttr(resourceName, "device.0.description", "test"), @@ -91,7 +91,7 @@ func TestAccSageMakerDevice_disappears(t *testing.T) { CheckDestroy: testAccCheckDeviceDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceBasicConfig(rName), + Config: testAccDeviceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceExists(resourceName, &device), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceDevice(), resourceName), @@ -115,7 +115,7 @@ func TestAccSageMakerDevice_disappears_fleet(t *testing.T) { CheckDestroy: testAccCheckDeviceDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceBasicConfig(rName), + Config: testAccDeviceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDeviceExists(resourceName, &device), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceDeviceFleet(), "aws_sagemaker_device_fleet.test"), @@ -262,7 +262,7 @@ resource "aws_sagemaker_device_fleet" "test" { `, rName) } -func testAccDeviceBasicConfig(rName string) string { +func testAccDeviceConfig_basic(rName string) string { return testAccDeviceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_device" "test" { device_fleet_name = aws_sagemaker_device_fleet.test.device_fleet_name @@ -274,7 +274,7 @@ resource "aws_sagemaker_device" "test" { `, rName) } -func testAccDeviceDescription(rName, desc string) string { +func testAccDeviceConfig_description(rName, desc string) string { return testAccDeviceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_device" "test" { device_fleet_name = aws_sagemaker_device_fleet.test.device_fleet_name diff --git a/internal/service/sagemaker/domain.go b/internal/service/sagemaker/domain.go index f651b71e308..fd08228c3b8 100644 --- a/internal/service/sagemaker/domain.go +++ b/internal/service/sagemaker/domain.go @@ -93,7 +93,6 @@ func ResourceDomain() *schema.Resource { "sharing_settings": { Type: schema.TypeList, Optional: true, - ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -118,7 +117,6 @@ func ResourceDomain() *schema.Resource { "tensor_board_app_settings": { Type: schema.TypeList, Optional: true, - ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -157,7 +155,6 @@ func ResourceDomain() *schema.Resource { "jupyter_server_app_settings": { Type: schema.TypeList, Optional: true, - ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -204,7 +201,6 @@ func ResourceDomain() *schema.Resource { "kernel_gateway_app_settings": { Type: schema.TypeList, Optional: true, - ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ diff --git a/internal/service/sagemaker/domain_test.go b/internal/service/sagemaker/domain_test.go index 850648d8ee1..59be0cfb424 100644 --- a/internal/service/sagemaker/domain_test.go +++ b/internal/service/sagemaker/domain_test.go @@ -29,7 +29,7 @@ func testAccDomain_basic(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainBasicConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "domain_name", rName), @@ -67,7 +67,7 @@ func testAccDomain_kms(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainKMSConfig(rName), + Config: testAccDomainConfig_kms(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", "aws_kms_key.test", "arn"), @@ -95,7 +95,7 @@ func testAccDomain_tags(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainTags1Config(rName, "key1", "value1"), + Config: testAccDomainConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -109,7 +109,7 @@ func testAccDomain_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"retention_policy"}, }, { - Config: testAccDomainTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDomainConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -118,7 +118,7 @@ func testAccDomain_tags(t *testing.T) { ), }, { - Config: testAccDomainTags1Config(rName, "key2", "value2"), + Config: testAccDomainConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -141,7 +141,7 @@ func testAccDomain_securityGroup(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSecurityGroup1Config(rName), + Config: testAccDomainConfig_securityGroup1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -155,7 +155,7 @@ func testAccDomain_securityGroup(t *testing.T) { ImportStateVerifyIgnore: []string{"retention_policy"}, }, { - Config: testAccDomainSecurityGroup2Config(rName), + Config: testAccDomainConfig_securityGroup2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -178,7 +178,7 @@ func testAccDomain_sharingSettings(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainSharingSettingsConfig(rName), + Config: testAccDomainConfig_sharingSettings(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -210,7 +210,7 @@ func testAccDomain_tensorboardAppSettings(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainTensorBoardAppSettingsConfig(rName), + Config: testAccDomainConfig_tensorBoardAppSettings(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -241,7 +241,7 @@ func testAccDomain_tensorboardAppSettingsWithImage(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainTensorBoardAppSettingsWithImageConfig(rName), + Config: testAccDomainConfig_tensorBoardAppSettingsImage(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -273,7 +273,7 @@ func testAccDomain_kernelGatewayAppSettings(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainKernelGatewayAppSettingsConfig(rName), + Config: testAccDomainConfig_kernelGatewayAppSettings(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -304,7 +304,7 @@ func testAccDomain_kernelGatewayAppSettings_lifecycleConfig(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainKernelGatewayAppSettingsLifecycleConfig(rName), + Config: testAccDomainConfig_kernelGatewayAppSettingsLifecycle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -343,7 +343,7 @@ func testAccDomain_kernelGatewayAppSettings_customImage(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainKernelGatewayAppSettingsCustomImageConfig(rName, baseImage), + Config: testAccDomainConfig_kernelGatewayAppSettingsCustomImage(rName, baseImage), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -382,7 +382,7 @@ func testAccDomain_kernelGatewayAppSettings_defaultResourceSpecAndCustomImage(t CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainKernelGatewayAppSettingsDefaultResourceSpecAndCustomImageConfig(rName, baseImage), + Config: testAccDomainConfig_kernelGatewayAppSettingsDefaultResourceSpecAndCustomImage(rName, baseImage), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -416,7 +416,7 @@ func testAccDomain_jupyterServerAppSettings(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainJupyterServerAppSettingsConfig(rName), + Config: testAccDomainConfig_jupyterServerAppSettings(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), @@ -447,7 +447,7 @@ func testAccDomain_disappears(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainBasicConfig(rName), + Config: testAccDomainConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName, &domain), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceDomain(), resourceName), @@ -458,6 +458,61 @@ func testAccDomain_disappears(t *testing.T) { }) } +func testAccDomain_defaultUserSettingsUpdated(t *testing.T) { + var domain sagemaker.DescribeDomainOutput + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_sagemaker_domain.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, sagemaker.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckDomainDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDomainConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckDomainExists(resourceName, &domain), + resource.TestCheckResourceAttr(resourceName, "domain_name", rName), + resource.TestCheckResourceAttr(resourceName, "auth_mode", "IAM"), + resource.TestCheckResourceAttr(resourceName, "app_network_access_type", "PublicInternetOnly"), + resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "default_user_settings.0.execution_role", "aws_iam_role.test", "arn"), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "sagemaker", regexp.MustCompile(`domain/.+`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttrPair(resourceName, "vpc_id", "aws_vpc.test", "id"), + resource.TestCheckResourceAttrSet(resourceName, "url"), + resource.TestCheckResourceAttrSet(resourceName, "home_efs_file_system_id"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"retention_policy"}, + }, + { + Config: testAccDomainConfig_sharingSettings(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckDomainExists(resourceName, &domain), + resource.TestCheckResourceAttr(resourceName, "default_user_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_user_settings.0.sharing_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_user_settings.0.sharing_settings.0.notebook_output_option", "Allowed"), + resource.TestCheckResourceAttrPair(resourceName, "default_user_settings.0.sharing_settings.0.s3_kms_key_id", "aws_kms_key.test", "arn"), + resource.TestCheckResourceAttrSet(resourceName, "default_user_settings.0.sharing_settings.0.s3_output_path"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"retention_policy"}, + }, + }, + }) +} + func testAccCheckDomainDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).SageMakerConn @@ -558,7 +613,7 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName) } -func testAccDomainBasicConfig(rName string) string { +func testAccDomainConfig_basic(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_domain" "test" { domain_name = %[1]q @@ -577,7 +632,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainKMSConfig(rName string) string { +func testAccDomainConfig_kms(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Terraform acc test" @@ -602,7 +657,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainSecurityGroup1Config(rName string) string { +func testAccDomainConfig_securityGroup1(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_security_group" "test" { name = "%[1]s" @@ -626,7 +681,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainSecurityGroup2Config(rName string) string { +func testAccDomainConfig_securityGroup2(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -654,7 +709,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccDomainConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_domain" "test" { domain_name = %[1]q @@ -677,7 +732,7 @@ resource "aws_sagemaker_domain" "test" { `, rName, tagKey1, tagValue1) } -func testAccDomainTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDomainConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_domain" "test" { domain_name = %[1]q @@ -701,7 +756,7 @@ resource "aws_sagemaker_domain" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccDomainSharingSettingsConfig(rName string) string { +func testAccDomainConfig_sharingSettings(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -737,7 +792,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainTensorBoardAppSettingsConfig(rName string) string { +func testAccDomainConfig_tensorBoardAppSettings(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_domain" "test" { domain_name = %[1]q @@ -762,7 +817,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainTensorBoardAppSettingsWithImageConfig(rName string) string { +func testAccDomainConfig_tensorBoardAppSettingsImage(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_image" "test" { image_name = %[1]q @@ -793,7 +848,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainJupyterServerAppSettingsConfig(rName string) string { +func testAccDomainConfig_jupyterServerAppSettings(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_domain" "test" { domain_name = %[1]q @@ -818,7 +873,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainKernelGatewayAppSettingsConfig(rName string) string { +func testAccDomainConfig_kernelGatewayAppSettings(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_domain" "test" { domain_name = %[1]q @@ -843,7 +898,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainKernelGatewayAppSettingsLifecycleConfig(rName string) string { +func testAccDomainConfig_kernelGatewayAppSettingsLifecycle(rName string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_studio_lifecycle_config" "test" { studio_lifecycle_config_name = %[1]q @@ -877,7 +932,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccDomainKernelGatewayAppSettingsCustomImageConfig(rName, baseImage string) string { +func testAccDomainConfig_kernelGatewayAppSettingsCustomImage(rName, baseImage string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_image" "test" { image_name = %[1]q @@ -925,7 +980,7 @@ resource "aws_sagemaker_domain" "test" { `, rName, baseImage) } -func testAccDomainKernelGatewayAppSettingsDefaultResourceSpecAndCustomImageConfig(rName, baseImage string) string { +func testAccDomainConfig_kernelGatewayAppSettingsDefaultResourceSpecAndCustomImage(rName, baseImage string) string { return testAccDomainBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_image" "test" { image_name = %[1]q diff --git a/internal/service/sagemaker/endpoint_configuration.go b/internal/service/sagemaker/endpoint_configuration.go index 985f688c7e4..27365321719 100644 --- a/internal/service/sagemaker/endpoint_configuration.go +++ b/internal/service/sagemaker/endpoint_configuration.go @@ -106,75 +106,6 @@ func ResourceEndpointConfiguration() *schema.Resource { }, }, }, - - "name": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - ValidateFunc: validName, - }, - - "production_variants": { - Type: schema.TypeList, - Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "variant_name": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - }, - - "model_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "initial_instance_count": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, - ValidateFunc: validation.IntAtLeast(1), - }, - - "instance_type": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(sagemaker.ProductionVariantInstanceType_Values(), false), - }, - - "initial_variant_weight": { - Type: schema.TypeFloat, - Optional: true, - ForceNew: true, - ValidateFunc: validation.FloatAtLeast(0), - Default: 1, - }, - - "accelerator_type": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(sagemaker.ProductionVariantAcceleratorType_Values(), false), - }, - }, - }, - }, - - "kms_key_arn": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: verify.ValidARN, - }, - - "tags": tftags.TagsSchema(), - "tags_all": tftags.TagsSchemaComputed(), - "data_capture_config": { Type: schema.TypeList, MaxItems: 1, @@ -270,6 +201,89 @@ func ResourceEndpointConfiguration() *schema.Resource { }, }, }, + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: validName, + }, + "kms_key_arn": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: verify.ValidARN, + }, + "production_variants": { + Type: schema.TypeList, + Required: true, + MinItems: 1, + MaxItems: 10, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "accelerator_type": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(sagemaker.ProductionVariantAcceleratorType_Values(), false), + }, + "initial_instance_count": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + ValidateFunc: validation.IntAtLeast(1), + }, + "initial_variant_weight": { + Type: schema.TypeFloat, + Optional: true, + ForceNew: true, + ValidateFunc: validation.FloatAtLeast(0), + Default: 1, + }, + "instance_type": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(sagemaker.ProductionVariantInstanceType_Values(), false), + }, + "model_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "serverless_config": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "max_concurrency": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + ValidateFunc: validation.IntBetween(1, 200), + }, + "memory_size_in_mb": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + ValidateFunc: validation.IntInSlice([]int{1024, 2048, 3072, 4096, 5120, 6144}), + }, + }, + }, + }, + "variant_name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + }, + }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), }, CustomizeDiff: verify.SetTagsDiff, @@ -412,9 +426,15 @@ func expandProductionVariants(configured []interface{}) []*sagemaker.ProductionV data := lRaw.(map[string]interface{}) l := &sagemaker.ProductionVariant{ - InstanceType: aws.String(data["instance_type"].(string)), - ModelName: aws.String(data["model_name"].(string)), - InitialInstanceCount: aws.Int64(int64(data["initial_instance_count"].(int))), + ModelName: aws.String(data["model_name"].(string)), + } + + if v, ok := data["initial_instance_count"].(int); ok && v > 0 { + l.InitialInstanceCount = aws.Int64(int64(v)) + } + + if v, ok := data["instance_type"].(string); ok && v != "" { + l.InstanceType = aws.String(v) } if v, ok := data["variant_name"]; ok { @@ -431,6 +451,10 @@ func expandProductionVariants(configured []interface{}) []*sagemaker.ProductionV l.AcceleratorType = aws.String(v) } + if v, ok := data["serverless_config"].([]interface{}); ok && len(v) > 0 { + l.ServerlessConfig = expandServerlessConfig(v) + } + containers = append(containers, l) } @@ -443,13 +467,23 @@ func flattenProductionVariants(list []*sagemaker.ProductionVariant) []map[string for _, i := range list { l := map[string]interface{}{ "accelerator_type": aws.StringValue(i.AcceleratorType), - "initial_instance_count": aws.Int64Value(i.InitialInstanceCount), "initial_variant_weight": aws.Float64Value(i.InitialVariantWeight), - "instance_type": aws.StringValue(i.InstanceType), "model_name": aws.StringValue(i.ModelName), "variant_name": aws.StringValue(i.VariantName), } + if i.InitialInstanceCount != nil { + l["initial_instance_count"] = aws.Int64Value(i.InitialInstanceCount) + } + + if i.InstanceType != nil { + l["instance_type"] = aws.StringValue(i.InstanceType) + } + + if i.ServerlessConfig != nil { + l["serverless_config"] = flattenServerlessConfig(i.ServerlessConfig) + } + result = append(result, l) } return result @@ -646,6 +680,26 @@ func expandEndpointConfigNotificationConfig(configured []interface{}) *sagemaker return c } +func expandServerlessConfig(configured []interface{}) *sagemaker.ProductionVariantServerlessConfig { + if len(configured) == 0 { + return nil + } + + m := configured[0].(map[string]interface{}) + + c := &sagemaker.ProductionVariantServerlessConfig{} + + if v, ok := m["max_concurrency"].(int); ok { + c.MaxConcurrency = aws.Int64(int64(v)) + } + + if v, ok := m["memory_size_in_mb"].(int); ok { + c.MemorySizeInMB = aws.Int64(int64(v)) + } + + return c +} + func flattenEndpointConfigAsyncInferenceConfig(config *sagemaker.AsyncInferenceConfig) []map[string]interface{} { if config == nil { return []map[string]interface{}{} @@ -715,3 +769,21 @@ func flattenEndpointConfigNotificationConfig(config *sagemaker.AsyncInferenceNot return []map[string]interface{}{cfg} } + +func flattenServerlessConfig(config *sagemaker.ProductionVariantServerlessConfig) []map[string]interface{} { + if config == nil { + return []map[string]interface{}{} + } + + cfg := map[string]interface{}{} + + if config.MaxConcurrency != nil { + cfg["max_concurrency"] = aws.Int64Value(config.MaxConcurrency) + } + + if config.MemorySizeInMB != nil { + cfg["memory_size_in_mb"] = aws.Int64Value(config.MemorySizeInMB) + } + + return []map[string]interface{}{cfg} +} diff --git a/internal/service/sagemaker/endpoint_configuration_test.go b/internal/service/sagemaker/endpoint_configuration_test.go index f22658effa5..b0cf9c16af2 100644 --- a/internal/service/sagemaker/endpoint_configuration_test.go +++ b/internal/service/sagemaker/endpoint_configuration_test.go @@ -25,7 +25,7 @@ func TestAccSageMakerEndpointConfiguration_basic(t *testing.T) { CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfig_Basic(rName), + Config: testAccEndpointConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -35,7 +35,7 @@ func TestAccSageMakerEndpointConfiguration_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "production_variants.0.initial_instance_count", "2"), resource.TestCheckResourceAttr(resourceName, "production_variants.0.instance_type", "ml.t2.medium"), resource.TestCheckResourceAttr(resourceName, "production_variants.0.initial_variant_weight", "1"), - resource.TestCheckResourceAttr(resourceName, "production_variants.0.code_dump_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "production_variants.0.serverless_config.#", "0"), resource.TestCheckResourceAttr(resourceName, "data_capture_config.#", "0"), resource.TestCheckResourceAttr(resourceName, "async_inference_config.#", "0"), ), @@ -49,6 +49,35 @@ func TestAccSageMakerEndpointConfiguration_basic(t *testing.T) { }) } +func TestAccSageMakerEndpointConfiguration_ProductionVariants_serverless(t *testing.T) { + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_sagemaker_endpoint_configuration.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, sagemaker.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckEndpointConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEndpointConfigurationConfig_serverless(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEndpointConfigurationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "production_variants.#", "1"), + resource.TestCheckResourceAttr(resourceName, "production_variants.0.serverless_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "production_variants.0.serverless_config.0.max_concurrency", "1"), + resource.TestCheckResourceAttr(resourceName, "production_variants.0.serverless_config.0.memory_size_in_mb", "1024"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestAccSageMakerEndpointConfiguration_ProductionVariants_initialVariantWeight(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_sagemaker_endpoint_configuration.test" @@ -60,7 +89,7 @@ func TestAccSageMakerEndpointConfiguration_ProductionVariants_initialVariantWeig CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfig_ProductionVariants_InitialVariantWeight(rName), + Config: testAccEndpointConfigurationConfig_productionVariantsInitialVariantWeight(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr( @@ -87,7 +116,7 @@ func TestAccSageMakerEndpointConfiguration_ProductionVariants_acceleratorType(t CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfig_ProductionVariant_AcceleratorType(rName), + Config: testAccEndpointConfigurationConfig_productionVariantAcceleratorType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "production_variants.0.accelerator_type", "ml.eia1.medium"), @@ -113,7 +142,7 @@ func TestAccSageMakerEndpointConfiguration_kmsKeyID(t *testing.T) { CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfig_kmsKeyId(rName), + Config: testAccEndpointConfigurationConfig_kmsKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "kms_key_arn", "aws_kms_key.test", "arn"), @@ -139,7 +168,7 @@ func TestAccSageMakerEndpointConfiguration_tags(t *testing.T) { CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfigTags1(rName, "key1", "value1"), + Config: testAccEndpointConfigurationConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -152,7 +181,7 @@ func TestAccSageMakerEndpointConfiguration_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEndpointConfigurationConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccEndpointConfigurationConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -161,7 +190,7 @@ func TestAccSageMakerEndpointConfiguration_tags(t *testing.T) { ), }, { - Config: testAccEndpointConfigurationConfigTags1(rName, "key2", "value2"), + Config: testAccEndpointConfigurationConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -183,7 +212,7 @@ func TestAccSageMakerEndpointConfiguration_dataCapture(t *testing.T) { CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationDataCaptureConfig(rName), + Config: testAccEndpointConfigurationConfig_dataCapture(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "data_capture_config.#", "1"), @@ -216,7 +245,7 @@ func TestAccSageMakerEndpointConfiguration_disappears(t *testing.T) { CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfig_Basic(rName), + Config: testAccEndpointConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceEndpointConfiguration(), resourceName), @@ -239,7 +268,7 @@ func TestAccSageMakerEndpointConfiguration_async(t *testing.T) { CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfigAsyncConfig(rName), + Config: testAccEndpointConfigurationConfig_async(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -271,7 +300,7 @@ func TestAccSageMakerEndpointConfiguration_async_kms(t *testing.T) { CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfigAsyncKMSConfig(rName), + Config: testAccEndpointConfigurationConfig_asyncKMS(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -303,7 +332,7 @@ func TestAccSageMakerEndpointConfiguration_Async_notif(t *testing.T) { CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfigAsyncNotifConfig(rName), + Config: testAccEndpointConfigurationConfig_asyncNotif(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -336,7 +365,7 @@ func TestAccSageMakerEndpointConfiguration_Async_client(t *testing.T) { CheckDestroy: testAccCheckEndpointConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigurationConfigAsyncClientConfig(rName), + Config: testAccEndpointConfigurationConfig_asyncClient(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -436,7 +465,7 @@ data "aws_iam_policy_document" "assume_role" { `, rName) } -func testAccEndpointConfigurationConfig_Basic(rName string) string { +func testAccEndpointConfigurationConfig_basic(rName string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint_configuration" "test" { name = %q @@ -452,7 +481,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName) } -func testAccEndpointConfigurationConfig_ProductionVariants_InitialVariantWeight(rName string) string { +func testAccEndpointConfigurationConfig_productionVariantsInitialVariantWeight(rName string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint_configuration" "test" { name = %q @@ -475,7 +504,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName) } -func testAccEndpointConfigurationConfig_ProductionVariant_AcceleratorType(rName string) string { +func testAccEndpointConfigurationConfig_productionVariantAcceleratorType(rName string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint_configuration" "test" { name = %q @@ -492,7 +521,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName) } -func testAccEndpointConfigurationConfig_kmsKeyId(rName string) string { +func testAccEndpointConfigurationConfig_kmsKeyID(rName string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint_configuration" "test" { name = %[1]q @@ -514,7 +543,7 @@ resource "aws_kms_key" "test" { `, rName) } -func testAccEndpointConfigurationConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccEndpointConfigurationConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint_configuration" "test" { name = %[1]q @@ -534,7 +563,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName, tagKey1, tagValue1) } -func testAccEndpointConfigurationConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccEndpointConfigurationConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint_configuration" "test" { name = %[1]q @@ -555,7 +584,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccEndpointConfigurationDataCaptureConfig(rName string) string { +func testAccEndpointConfigurationConfig_dataCapture(rName string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -599,7 +628,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName) } -func testAccEndpointConfigurationConfigAsyncKMSConfig(rName string) string { +func testAccEndpointConfigurationConfig_asyncKMS(rName string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -637,7 +666,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName) } -func testAccEndpointConfigurationConfigAsyncConfig(rName string) string { +func testAccEndpointConfigurationConfig_async(rName string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -665,7 +694,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName) } -func testAccEndpointConfigurationConfigAsyncNotifConfig(rName string) string { +func testAccEndpointConfigurationConfig_asyncNotif(rName string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -712,7 +741,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName) } -func testAccEndpointConfigurationConfigAsyncClientConfig(rName string) string { +func testAccEndpointConfigurationConfig_asyncClient(rName string) string { return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -753,3 +782,21 @@ resource "aws_sagemaker_endpoint_configuration" "test" { } `, rName) } + +func testAccEndpointConfigurationConfig_serverless(rName string) string { + return testAccEndpointConfigurationConfig_Base(rName) + fmt.Sprintf(` +resource "aws_sagemaker_endpoint_configuration" "test" { + name = %q + + production_variants { + variant_name = "variant-1" + model_name = aws_sagemaker_model.test.name + + serverless_config { + max_concurrency = 1 + memory_size_in_mb = 1024 + } + } +} +`, rName) +} diff --git a/internal/service/sagemaker/endpoint_test.go b/internal/service/sagemaker/endpoint_test.go index b29e39d0df7..d765d7de794 100644 --- a/internal/service/sagemaker/endpoint_test.go +++ b/internal/service/sagemaker/endpoint_test.go @@ -25,7 +25,7 @@ func TestAccSageMakerEndpoint_basic(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig(rName), + Config: testAccEndpointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -62,14 +62,14 @@ func TestAccSageMakerEndpoint_endpointName(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig(rName), + Config: testAccEndpointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "endpoint_config_name", sagemakerEndpointConfigurationResourceName1, "name"), ), }, { - Config: testAccEndpointConfigEndpointConfigNameUpdate(rName), + Config: testAccEndpointConfig_nameUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "endpoint_config_name", sagemakerEndpointConfigurationResourceName2, "name"), @@ -99,7 +99,7 @@ func TestAccSageMakerEndpoint_tags(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfigTags(rName), + Config: testAccEndpointConfig_tags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -107,7 +107,7 @@ func TestAccSageMakerEndpoint_tags(t *testing.T) { ), }, { - Config: testAccEndpointConfigTagsUpdate(rName), + Config: testAccEndpointConfig_tagsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -138,7 +138,7 @@ func TestAccSageMakerEndpoint_deploymentConfig(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointDeploymentBasicConfig(rName, "ALL_AT_ONCE", 60), + Config: testAccEndpointConfig_deploymentBasic(rName, "ALL_AT_ONCE", 60), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -178,7 +178,7 @@ func TestAccSageMakerEndpoint_deploymentConfig_full(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointDeploymentFullConfig(rName), + Config: testAccEndpointConfig_deploymentFull(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -217,7 +217,7 @@ func TestAccSageMakerEndpoint_disappears(t *testing.T) { CheckDestroy: testAccCheckEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccEndpointConfig(rName), + Config: testAccEndpointConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckEndpointExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceEndpoint(), resourceName), @@ -365,7 +365,7 @@ resource "aws_sagemaker_endpoint_configuration" "test" { `, rName) } -func testAccEndpointConfig(rName string) string { +func testAccEndpointConfig_basic(rName string) string { return testAccEndpointConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint" "test" { endpoint_config_name = aws_sagemaker_endpoint_configuration.test.name @@ -374,7 +374,7 @@ resource "aws_sagemaker_endpoint" "test" { `, rName) } -func testAccEndpointConfigEndpointConfigNameUpdate(rName string) string { +func testAccEndpointConfig_nameUpdate(rName string) string { return testAccEndpointConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint_configuration" "test2" { name = "%[1]s2" @@ -395,7 +395,7 @@ resource "aws_sagemaker_endpoint" "test" { `, rName) } -func testAccEndpointConfigTags(rName string) string { +func testAccEndpointConfig_tags(rName string) string { return testAccEndpointConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint" "test" { endpoint_config_name = aws_sagemaker_endpoint_configuration.test.name @@ -408,7 +408,7 @@ resource "aws_sagemaker_endpoint" "test" { `, rName) } -func testAccEndpointConfigTagsUpdate(rName string) string { +func testAccEndpointConfig_tagsUpdate(rName string) string { return testAccEndpointConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint" "test" { endpoint_config_name = aws_sagemaker_endpoint_configuration.test.name @@ -421,7 +421,7 @@ resource "aws_sagemaker_endpoint" "test" { `, rName) } -func testAccEndpointDeploymentBasicConfig(rName, tType string, wait int) string { +func testAccEndpointConfig_deploymentBasic(rName, tType string, wait int) string { return testAccEndpointConfig_Base(rName) + fmt.Sprintf(` resource "aws_sagemaker_endpoint" "test" { endpoint_config_name = aws_sagemaker_endpoint_configuration.test.name @@ -439,7 +439,7 @@ resource "aws_sagemaker_endpoint" "test" { `, rName, tType, wait) } -func testAccEndpointDeploymentFullConfig(rName string) string { +func testAccEndpointConfig_deploymentFull(rName string) string { return testAccEndpointConfig_Base(rName) + fmt.Sprintf(` resource "aws_cloudwatch_metric_alarm" "test" { alarm_name = %[1]q diff --git a/internal/service/sagemaker/feature_group_test.go b/internal/service/sagemaker/feature_group_test.go index e6894bd23f0..579500c1bd0 100644 --- a/internal/service/sagemaker/feature_group_test.go +++ b/internal/service/sagemaker/feature_group_test.go @@ -48,7 +48,7 @@ func testAccFeatureGroup_basic(t *testing.T) { CheckDestroy: testAccCheckFeatureGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccFeatureGroupBasicConfig(rName), + Config: testAccFeatureGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -84,7 +84,7 @@ func testAccFeatureGroup_description(t *testing.T) { CheckDestroy: testAccCheckFeatureGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccFeatureGroupDescriptionConfig(rName), + Config: testAccFeatureGroupConfig_description(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -112,7 +112,7 @@ func testAccFeatureGroup_tags(t *testing.T) { CheckDestroy: testAccCheckFeatureGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccFeatureGroupTags1(rName, "key1", "value1"), + Config: testAccFeatureGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -126,7 +126,7 @@ func testAccFeatureGroup_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFeatureGroupTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccFeatureGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -136,7 +136,7 @@ func testAccFeatureGroup_tags(t *testing.T) { ), }, { - Config: testAccFeatureGroupTags1(rName, "key2", "value2"), + Config: testAccFeatureGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -160,7 +160,7 @@ func testAccFeatureGroup_multipleFeatures(t *testing.T) { CheckDestroy: testAccCheckFeatureGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccFeatureGroupMultiFeatureConfig(rName), + Config: testAccFeatureGroupConfig_multi(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -192,7 +192,7 @@ func testAccFeatureGroup_onlineConfigSecurityConfig(t *testing.T) { CheckDestroy: testAccCheckFeatureGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccFeatureGroupOnlineSecurityConfig(rName), + Config: testAccFeatureGroupConfig_onlineSecurity(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -223,7 +223,7 @@ func testAccFeatureGroup_offlineConfig_basic(t *testing.T) { CheckDestroy: testAccCheckFeatureGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccFeatureGroupOfflineBasicConfig(rName), + Config: testAccFeatureGroupConfig_offlineBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -255,7 +255,7 @@ func testAccFeatureGroup_offlineConfig_createCatalog(t *testing.T) { CheckDestroy: testAccCheckFeatureGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccFeatureGroupOfflineCreateGlueCatalogConfig(rName), + Config: testAccFeatureGroupConfig_offlineCreateGlueCatalog(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -291,7 +291,7 @@ func TestAccSageMakerFeatureGroup_Offline_providedCatalog(t *testing.T) { CheckDestroy: testAccCheckFeatureGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccFeatureGroupOfflineCreateGlueCatalogProvidedCatalogConfig(rName), + Config: testAccFeatureGroupConfig_offlineCreateGlueCatalogProvidedCatalog(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), resource.TestCheckResourceAttr(resourceName, "feature_group_name", rName), @@ -326,7 +326,7 @@ func TestAccSageMakerFeatureGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckFeatureGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccFeatureGroupBasicConfig(rName), + Config: testAccFeatureGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFeatureGroupExists(resourceName, &featureGroup), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceFeatureGroup(), resourceName), @@ -444,7 +444,7 @@ resource "aws_iam_policy" "test" { `, rName) } -func testAccFeatureGroupBasicConfig(rName string) string { +func testAccFeatureGroupConfig_basic(rName string) string { return acctest.ConfigCompose(testAccFeatureGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_feature_group" "test" { feature_group_name = %[1]q @@ -464,7 +464,7 @@ resource "aws_sagemaker_feature_group" "test" { `, rName)) } -func testAccFeatureGroupDescriptionConfig(rName string) string { +func testAccFeatureGroupConfig_description(rName string) string { return acctest.ConfigCompose(testAccFeatureGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_feature_group" "test" { feature_group_name = %[1]q @@ -485,7 +485,7 @@ resource "aws_sagemaker_feature_group" "test" { `, rName)) } -func testAccFeatureGroupMultiFeatureConfig(rName string) string { +func testAccFeatureGroupConfig_multi(rName string) string { return acctest.ConfigCompose(testAccFeatureGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_feature_group" "test" { feature_group_name = %[1]q @@ -510,7 +510,7 @@ resource "aws_sagemaker_feature_group" "test" { `, rName)) } -func testAccFeatureGroupOnlineSecurityConfig(rName string) string { +func testAccFeatureGroupConfig_onlineSecurity(rName string) string { return acctest.ConfigCompose(testAccFeatureGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -539,7 +539,7 @@ resource "aws_sagemaker_feature_group" "test" { `, rName)) } -func testAccFeatureGroupOfflineBasicConfig(rName string) string { +func testAccFeatureGroupConfig_offlineBasic(rName string) string { return acctest.ConfigCompose( testAccFeatureGroupBaseConfig(rName), testAccFeatureGroupOfflineBaseConfig(rName), @@ -568,7 +568,7 @@ resource "aws_sagemaker_feature_group" "test" { `, rName)) } -func testAccFeatureGroupOfflineCreateGlueCatalogConfig(rName string) string { +func testAccFeatureGroupConfig_offlineCreateGlueCatalog(rName string) string { return acctest.ConfigCompose( testAccFeatureGroupBaseConfig(rName), testAccFeatureGroupOfflineBaseConfig(rName), @@ -597,7 +597,7 @@ resource "aws_sagemaker_feature_group" "test" { `, rName)) } -func testAccFeatureGroupOfflineCreateGlueCatalogProvidedCatalogConfig(rName string) string { +func testAccFeatureGroupConfig_offlineCreateGlueCatalogProvidedCatalog(rName string) string { return acctest.ConfigCompose( testAccFeatureGroupBaseConfig(rName), testAccFeatureGroupOfflineBaseConfig(rName), @@ -641,7 +641,7 @@ resource "aws_sagemaker_feature_group" "test" { `, rName)) } -func testAccFeatureGroupTags1(rName, tag1Key, tag1Value string) string { +func testAccFeatureGroupConfig_tags1(rName, tag1Key, tag1Value string) string { return acctest.ConfigCompose(testAccFeatureGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_feature_group" "test" { feature_group_name = %[1]q @@ -665,7 +665,7 @@ resource "aws_sagemaker_feature_group" "test" { `, rName, tag1Key, tag1Value)) } -func testAccFeatureGroupTags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccFeatureGroupConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return acctest.ConfigCompose(testAccFeatureGroupBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_feature_group" "test" { feature_group_name = %[1]q diff --git a/internal/service/sagemaker/find.go b/internal/service/sagemaker/find.go index b028abc9e7a..e9b6f5462c4 100644 --- a/internal/service/sagemaker/find.go +++ b/internal/service/sagemaker/find.go @@ -488,3 +488,28 @@ func FindProjectByName(conn *sagemaker.SageMaker, name string) (*sagemaker.Descr return output, nil } + +func FindNotebookInstanceByName(conn *sagemaker.SageMaker, name string) (*sagemaker.DescribeNotebookInstanceOutput, error) { + input := &sagemaker.DescribeNotebookInstanceInput{ + NotebookInstanceName: aws.String(name), + } + + output, err := conn.DescribeNotebookInstance(input) + + if tfawserr.ErrMessageContains(err, "ValidationException", "RecordNotFound") { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} diff --git a/internal/service/sagemaker/flow_definition_test.go b/internal/service/sagemaker/flow_definition_test.go index 88a3968b227..c6e62ca6f92 100644 --- a/internal/service/sagemaker/flow_definition_test.go +++ b/internal/service/sagemaker/flow_definition_test.go @@ -26,7 +26,7 @@ func testAccFlowDefinition_basic(t *testing.T) { CheckDestroy: testAccCheckFlowDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowDefinitionBasicConfig(rName), + Config: testAccFlowDefinitionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowDefinitionExists(resourceName, &flowDefinition), resource.TestCheckResourceAttr(resourceName, "flow_definition_name", rName), @@ -68,7 +68,7 @@ func testAccFlowDefinition_humanLoopConfig_publicWorkforce(t *testing.T) { CheckDestroy: testAccCheckFlowDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowDefinitionPublicWorkforceConfig(rName), + Config: testAccFlowDefinitionConfig_publicWorkforce(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowDefinitionExists(resourceName, &flowDefinition), resource.TestCheckResourceAttr(resourceName, "flow_definition_name", rName), @@ -100,7 +100,7 @@ func testAccFlowDefinition_humanLoopRequestSource(t *testing.T) { CheckDestroy: testAccCheckFlowDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowDefinitionHumanLoopRequestSourceConfig(rName), + Config: testAccFlowDefinitionConfig_humanLoopRequestSource(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowDefinitionExists(resourceName, &flowDefinition), resource.TestCheckResourceAttr(resourceName, "flow_definition_name", rName), @@ -132,7 +132,7 @@ func testAccFlowDefinition_tags(t *testing.T) { CheckDestroy: testAccCheckFlowDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowDefinitionTags1Config(rName, "key1", "value1"), + Config: testAccFlowDefinitionConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFlowDefinitionExists(resourceName, &flowDefinition), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -145,7 +145,7 @@ func testAccFlowDefinition_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFlowDefinitionTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccFlowDefinitionConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFlowDefinitionExists(resourceName, &flowDefinition), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -154,7 +154,7 @@ func testAccFlowDefinition_tags(t *testing.T) { ), }, { - Config: testAccFlowDefinitionTags1Config(rName, "key2", "value2"), + Config: testAccFlowDefinitionConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFlowDefinitionExists(resourceName, &flowDefinition), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -177,7 +177,7 @@ func testAccFlowDefinition_disappears(t *testing.T) { CheckDestroy: testAccCheckFlowDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccFlowDefinitionBasicConfig(rName), + Config: testAccFlowDefinitionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckFlowDefinitionExists(resourceName, &flowDefinition), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceFlowDefinition(), resourceName), @@ -308,9 +308,9 @@ EOF `, rName) } -func testAccFlowDefinitionBasicConfig(rName string) string { +func testAccFlowDefinitionConfig_basic(rName string) string { return acctest.ConfigCompose(testAccFlowDefinitionBaseConfig(rName), - testAccWorkteamCognitoConfig(rName), + testAccWorkteamConfig_cognito(rName), fmt.Sprintf(` resource "aws_sagemaker_flow_definition" "test" { flow_definition_name = %[1]q @@ -332,7 +332,7 @@ resource "aws_sagemaker_flow_definition" "test" { `, rName)) } -func testAccFlowDefinitionPublicWorkforceConfig(rName string) string { +func testAccFlowDefinitionConfig_publicWorkforce(rName string) string { return acctest.ConfigCompose(testAccFlowDefinitionBaseConfig(rName), fmt.Sprintf(` data "aws_region" "current" {} @@ -366,9 +366,9 @@ resource "aws_sagemaker_flow_definition" "test" { `, rName)) } -func testAccFlowDefinitionHumanLoopRequestSourceConfig(rName string) string { +func testAccFlowDefinitionConfig_humanLoopRequestSource(rName string) string { return acctest.ConfigCompose(testAccFlowDefinitionBaseConfig(rName), - testAccWorkteamCognitoConfig(rName), + testAccWorkteamConfig_cognito(rName), fmt.Sprintf(` resource "aws_sagemaker_flow_definition" "test" { flow_definition_name = %[1]q @@ -411,9 +411,9 @@ resource "aws_sagemaker_flow_definition" "test" { `, rName)) } -func testAccFlowDefinitionTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccFlowDefinitionConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccFlowDefinitionBaseConfig(rName), - testAccWorkteamCognitoConfig(rName), + testAccWorkteamConfig_cognito(rName), fmt.Sprintf(` resource "aws_sagemaker_flow_definition" "test" { flow_definition_name = %[1]q @@ -439,9 +439,9 @@ resource "aws_sagemaker_flow_definition" "test" { `, rName, tagKey1, tagValue1)) } -func testAccFlowDefinitionTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccFlowDefinitionConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccFlowDefinitionBaseConfig(rName), - testAccWorkteamCognitoConfig(rName), + testAccWorkteamConfig_cognito(rName), fmt.Sprintf(` resource "aws_sagemaker_flow_definition" "test" { flow_definition_name = %[1]q diff --git a/internal/service/sagemaker/human_task_ui_test.go b/internal/service/sagemaker/human_task_ui_test.go index d0e93298493..3a54c59d887 100644 --- a/internal/service/sagemaker/human_task_ui_test.go +++ b/internal/service/sagemaker/human_task_ui_test.go @@ -26,7 +26,7 @@ func TestAccSageMakerHumanTaskUI_basic(t *testing.T) { CheckDestroy: testAccCheckHumanTaskUIDestroy, Steps: []resource.TestStep{ { - Config: testAccHumanTaskUICognitoBasicConfig(rName), + Config: testAccHumanTaskUIConfig_cognitoBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckHumanTaskUIExists(resourceName, &humanTaskUi), resource.TestCheckResourceAttr(resourceName, "human_task_ui_name", rName), @@ -57,7 +57,7 @@ func TestAccSageMakerHumanTaskUI_tags(t *testing.T) { CheckDestroy: testAccCheckHumanTaskUIDestroy, Steps: []resource.TestStep{ { - Config: testAccHumanTaskUITags1Config(rName, "key1", "value1"), + Config: testAccHumanTaskUIConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckHumanTaskUIExists(resourceName, &humanTaskUi), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -71,7 +71,7 @@ func TestAccSageMakerHumanTaskUI_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"ui_template.0.content", "ui_template.0.url"}, }, { - Config: testAccHumanTaskUITags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccHumanTaskUIConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckHumanTaskUIExists(resourceName, &humanTaskUi), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -80,7 +80,7 @@ func TestAccSageMakerHumanTaskUI_tags(t *testing.T) { ), }, { - Config: testAccHumanTaskUITags1Config(rName, "key2", "value2"), + Config: testAccHumanTaskUIConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckHumanTaskUIExists(resourceName, &humanTaskUi), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -103,7 +103,7 @@ func TestAccSageMakerHumanTaskUI_disappears(t *testing.T) { CheckDestroy: testAccCheckHumanTaskUIDestroy, Steps: []resource.TestStep{ { - Config: testAccHumanTaskUICognitoBasicConfig(rName), + Config: testAccHumanTaskUIConfig_cognitoBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckHumanTaskUIExists(resourceName, &humanTaskUi), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceHumanTaskUI(), resourceName), @@ -163,7 +163,7 @@ func testAccCheckHumanTaskUIExists(n string, humanTaskUi *sagemaker.DescribeHuma } } -func testAccHumanTaskUICognitoBasicConfig(rName string) string { +func testAccHumanTaskUIConfig_cognitoBasic(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_human_task_ui" "test" { human_task_ui_name = %[1]q @@ -175,7 +175,7 @@ resource "aws_sagemaker_human_task_ui" "test" { `, rName) } -func testAccHumanTaskUITags1Config(rName, tagKey1, tagValue1 string) string { +func testAccHumanTaskUIConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_sagemaker_human_task_ui" "test" { human_task_ui_name = %[1]q @@ -191,7 +191,7 @@ resource "aws_sagemaker_human_task_ui" "test" { `, rName, tagKey1, tagValue1) } -func testAccHumanTaskUITags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccHumanTaskUIConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_sagemaker_human_task_ui" "test" { human_task_ui_name = %[1]q diff --git a/internal/service/sagemaker/image_test.go b/internal/service/sagemaker/image_test.go index e5f65f4146e..e8158a19a03 100644 --- a/internal/service/sagemaker/image_test.go +++ b/internal/service/sagemaker/image_test.go @@ -27,7 +27,7 @@ func TestAccSageMakerImage_basic(t *testing.T) { CheckDestroy: testAccCheckImageDestroy, Steps: []resource.TestStep{ { - Config: testAccImageBasicConfig(rName), + Config: testAccImageConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "image_name", rName), @@ -57,7 +57,7 @@ func TestAccSageMakerImage_description(t *testing.T) { CheckDestroy: testAccCheckImageDestroy, Steps: []resource.TestStep{ { - Config: testAccImageDescription(rName), + Config: testAccImageConfig_description(rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -69,14 +69,14 @@ func TestAccSageMakerImage_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccImageBasicConfig(rName), + Config: testAccImageConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "description", ""), ), }, { - Config: testAccImageDescription(rName), + Config: testAccImageConfig_description(rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -98,7 +98,7 @@ func TestAccSageMakerImage_displayName(t *testing.T) { CheckDestroy: testAccCheckImageDestroy, Steps: []resource.TestStep{ { - Config: testAccImageDisplayName(rName), + Config: testAccImageConfig_displayName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "display_name", rName), @@ -110,14 +110,14 @@ func TestAccSageMakerImage_displayName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccImageBasicConfig(rName), + Config: testAccImageConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "display_name", ""), ), }, { - Config: testAccImageDisplayName(rName), + Config: testAccImageConfig_displayName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "display_name", rName), @@ -139,7 +139,7 @@ func TestAccSageMakerImage_tags(t *testing.T) { CheckDestroy: testAccCheckImageDestroy, Steps: []resource.TestStep{ { - Config: testAccImageTags1Config(rName, "key1", "value1"), + Config: testAccImageConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -152,7 +152,7 @@ func TestAccSageMakerImage_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccImageTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccImageConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -161,7 +161,7 @@ func TestAccSageMakerImage_tags(t *testing.T) { ), }, { - Config: testAccImageTags1Config(rName, "key2", "value2"), + Config: testAccImageConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -184,7 +184,7 @@ func TestAccSageMakerImage_disappears(t *testing.T) { CheckDestroy: testAccCheckImageDestroy, Steps: []resource.TestStep{ { - Config: testAccImageBasicConfig(rName), + Config: testAccImageConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckImageExists(resourceName, &image), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceImage(), resourceName), @@ -266,7 +266,7 @@ data "aws_iam_policy_document" "test" { `, rName) } -func testAccImageBasicConfig(rName string) string { +func testAccImageConfig_basic(rName string) string { return testAccImageBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_image" "test" { image_name = %[1]q @@ -275,7 +275,7 @@ resource "aws_sagemaker_image" "test" { `, rName) } -func testAccImageDescription(rName string) string { +func testAccImageConfig_description(rName string) string { return testAccImageBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_image" "test" { image_name = %[1]q @@ -285,7 +285,7 @@ resource "aws_sagemaker_image" "test" { `, rName) } -func testAccImageDisplayName(rName string) string { +func testAccImageConfig_displayName(rName string) string { return testAccImageBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_image" "test" { image_name = %[1]q @@ -295,7 +295,7 @@ resource "aws_sagemaker_image" "test" { `, rName) } -func testAccImageTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccImageConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccImageBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_image" "test" { image_name = %[1]q @@ -308,7 +308,7 @@ resource "aws_sagemaker_image" "test" { `, rName, tagKey1, tagValue1) } -func testAccImageTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccImageConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccImageBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_image" "test" { image_name = %[1]q diff --git a/internal/service/sagemaker/image_version_test.go b/internal/service/sagemaker/image_version_test.go index f5511fbeee7..cc78ce7928e 100644 --- a/internal/service/sagemaker/image_version_test.go +++ b/internal/service/sagemaker/image_version_test.go @@ -34,7 +34,7 @@ func TestAccSageMakerImageVersion_basic(t *testing.T) { CheckDestroy: testAccCheckImageVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccImageVersionBasicConfig(rName, baseImage), + Config: testAccImageVersionConfig_basic(rName, baseImage), Check: resource.ComposeTestCheckFunc( testAccCheckImageVersionExists(resourceName, &image), resource.TestCheckResourceAttr(resourceName, "image_name", rName), @@ -72,7 +72,7 @@ func TestAccSageMakerImageVersion_disappears(t *testing.T) { CheckDestroy: testAccCheckImageVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccImageVersionBasicConfig(rName, baseImage), + Config: testAccImageVersionConfig_basic(rName, baseImage), Check: resource.ComposeTestCheckFunc( testAccCheckImageVersionExists(resourceName, &image), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceImageVersion(), resourceName), @@ -101,7 +101,7 @@ func TestAccSageMakerImageVersion_Disappears_image(t *testing.T) { CheckDestroy: testAccCheckImageVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccImageVersionBasicConfig(rName, baseImage), + Config: testAccImageVersionConfig_basic(rName, baseImage), Check: resource.ComposeTestCheckFunc( testAccCheckImageVersionExists(resourceName, &image), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceImage(), "aws_sagemaker_image.test"), @@ -161,7 +161,7 @@ func testAccCheckImageVersionExists(n string, image *sagemaker.DescribeImageVers } } -func testAccImageVersionBasicConfig(rName, baseImage string) string { +func testAccImageVersionConfig_basic(rName, baseImage string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/sagemaker/model_package_group_policy_test.go b/internal/service/sagemaker/model_package_group_policy_test.go index 1a07b46fb4c..c8fe31bbaea 100644 --- a/internal/service/sagemaker/model_package_group_policy_test.go +++ b/internal/service/sagemaker/model_package_group_policy_test.go @@ -26,7 +26,7 @@ func TestAccSageMakerModelPackageGroupPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckModelPackageGroupPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccModelPackageGroupPolicyBasicConfig(rName), + Config: testAccModelPackageGroupPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelPackageGroupPolicyExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "model_package_group_name", rName), @@ -53,7 +53,7 @@ func TestAccSageMakerModelPackageGroupPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckModelPackageGroupPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccModelPackageGroupPolicyBasicConfig(rName), + Config: testAccModelPackageGroupPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelPackageGroupPolicyExists(resourceName, &mpg), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceModelPackageGroupPolicy(), resourceName), @@ -77,7 +77,7 @@ func TestAccSageMakerModelPackageGroupPolicy_Disappears_modelPackageGroup(t *tes CheckDestroy: testAccCheckModelPackageGroupPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccModelPackageGroupPolicyBasicConfig(rName), + Config: testAccModelPackageGroupPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelPackageGroupPolicyExists(resourceName, &mpg), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceModelPackageGroup(), "aws_sagemaker_model_package_group.test"), @@ -133,7 +133,7 @@ func testAccCheckModelPackageGroupPolicyExists(n string, mpg *sagemaker.GetModel } } -func testAccModelPackageGroupPolicyBasicConfig(rName string) string { +func testAccModelPackageGroupPolicyConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} data "aws_partition" "current" {} diff --git a/internal/service/sagemaker/model_package_group_test.go b/internal/service/sagemaker/model_package_group_test.go index 4c64ef40039..482b0954d9f 100644 --- a/internal/service/sagemaker/model_package_group_test.go +++ b/internal/service/sagemaker/model_package_group_test.go @@ -27,7 +27,7 @@ func TestAccSageMakerModelPackageGroup_basic(t *testing.T) { CheckDestroy: testAccCheckModelPackageGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccModelPackageGroupBasicConfig(rName), + Config: testAccModelPackageGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelPackageGroupExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "model_package_group_name", rName), @@ -56,7 +56,7 @@ func TestAccSageMakerModelPackageGroup_description(t *testing.T) { CheckDestroy: testAccCheckModelPackageGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccModelPackageGroupDescription(rName), + Config: testAccModelPackageGroupConfig_description(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelPackageGroupExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "model_package_group_description", rName), @@ -83,7 +83,7 @@ func TestAccSageMakerModelPackageGroup_tags(t *testing.T) { CheckDestroy: testAccCheckModelPackageGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccModelPackageGroupTags1Config(rName, "key1", "value1"), + Config: testAccModelPackageGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckModelPackageGroupExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -96,7 +96,7 @@ func TestAccSageMakerModelPackageGroup_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccModelPackageGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccModelPackageGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckModelPackageGroupExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -105,7 +105,7 @@ func TestAccSageMakerModelPackageGroup_tags(t *testing.T) { ), }, { - Config: testAccModelPackageGroupTags1Config(rName, "key2", "value2"), + Config: testAccModelPackageGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckModelPackageGroupExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -128,7 +128,7 @@ func TestAccSageMakerModelPackageGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckModelPackageGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccModelPackageGroupBasicConfig(rName), + Config: testAccModelPackageGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelPackageGroupExists(resourceName, &mpg), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceModelPackageGroup(), resourceName), @@ -188,7 +188,7 @@ func testAccCheckModelPackageGroupExists(n string, mpg *sagemaker.DescribeModelP } } -func testAccModelPackageGroupBasicConfig(rName string) string { +func testAccModelPackageGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_model_package_group" "test" { model_package_group_name = %[1]q @@ -196,7 +196,7 @@ resource "aws_sagemaker_model_package_group" "test" { `, rName) } -func testAccModelPackageGroupDescription(rName string) string { +func testAccModelPackageGroupConfig_description(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_model_package_group" "test" { model_package_group_name = %[1]q @@ -205,7 +205,7 @@ resource "aws_sagemaker_model_package_group" "test" { `, rName) } -func testAccModelPackageGroupTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccModelPackageGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_sagemaker_model_package_group" "test" { model_package_group_name = %[1]q @@ -217,7 +217,7 @@ resource "aws_sagemaker_model_package_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccModelPackageGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccModelPackageGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_sagemaker_model_package_group" "test" { model_package_group_name = %[1]q diff --git a/internal/service/sagemaker/model_test.go b/internal/service/sagemaker/model_test.go index 178d2c22540..665a5d304bf 100644 --- a/internal/service/sagemaker/model_test.go +++ b/internal/service/sagemaker/model_test.go @@ -26,7 +26,7 @@ func TestAccSageMakerModel_basic(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccModelConfig(rName), + Config: testAccModelConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -61,7 +61,7 @@ func TestAccSageMakerModel_inferenceExecution(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccModelInferenceExecutionConfig(rName), + Config: testAccModelConfig_inferenceExecution(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "inference_execution_config.#", "1"), @@ -88,7 +88,7 @@ func TestAccSageMakerModel_tags(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccModelConfigTags1(rName, "key1", "value1"), + Config: testAccModelConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -96,7 +96,7 @@ func TestAccSageMakerModel_tags(t *testing.T) { ), }, { - Config: testAccModelConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccModelConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -105,7 +105,7 @@ func TestAccSageMakerModel_tags(t *testing.T) { ), }, { - Config: testAccModelConfigTags1(rName, "key2", "value2"), + Config: testAccModelConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -132,7 +132,7 @@ func TestAccSageMakerModel_primaryContainerModelDataURL(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccPrimaryContainerModelDataURLConfig(rName), + Config: testAccModelConfig_primaryContainerDataURL(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "primary_container.0.model_data_url"), @@ -158,7 +158,7 @@ func TestAccSageMakerModel_primaryContainerHostname(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccPrimaryContainerHostnameConfig(rName), + Config: testAccModelConfig_primaryContainerHostname(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "primary_container.0.container_hostname", "test"), @@ -184,7 +184,7 @@ func TestAccSageMakerModel_primaryContainerImage(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccPrimaryContainerImageConfigConfig(rName), + Config: testAccModelConfig_primaryContainerImage(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "primary_container.0.image_config.#", "1"), @@ -211,7 +211,7 @@ func TestAccSageMakerModel_primaryContainerEnvironment(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccPrimaryContainerEnvironmentConfig(rName), + Config: testAccModelConfig_primaryContainerEnvironment(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "primary_container.0.environment.%", "1"), @@ -238,7 +238,7 @@ func TestAccSageMakerModel_primaryContainerModeSingle(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccPrimaryContainerModeSingle(rName), + Config: testAccModelConfig_primaryContainerModeSingle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "primary_container.0.mode", "SingleModel"), @@ -264,7 +264,7 @@ func TestAccSageMakerModel_containers(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccModelContainers(rName), + Config: testAccModelConfig_containers(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "container.#", "2"), @@ -292,7 +292,7 @@ func TestAccSageMakerModel_vpc(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccModelVPCConfig_basic(rName), + Config: testAccModelConfig_vpcBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), @@ -320,7 +320,7 @@ func TestAccSageMakerModel_networkIsolation(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccModelNetworkIsolation(rName), + Config: testAccModelConfig_networkIsolation(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), resource.TestCheckResourceAttr(resourceName, "enable_network_isolation", "true"), @@ -346,7 +346,7 @@ func TestAccSageMakerModel_disappears(t *testing.T) { CheckDestroy: testAccCheckModelDestroy, Steps: []resource.TestStep{ { - Config: testAccModelConfig(rName), + Config: testAccModelConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckModelExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceModel(), resourceName), @@ -437,7 +437,7 @@ data "aws_sagemaker_prebuilt_ecr_image" "test" { `, rName) } -func testAccModelConfig(rName string) string { +func testAccModelConfig_basic(rName string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -450,7 +450,7 @@ resource "aws_sagemaker_model" "test" { `, rName) } -func testAccModelInferenceExecutionConfig(rName string) string { +func testAccModelConfig_inferenceExecution(rName string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -471,7 +471,7 @@ resource "aws_sagemaker_model" "test" { `, rName) } -func testAccModelConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccModelConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -488,7 +488,7 @@ resource "aws_sagemaker_model" "test" { `, rName, tagKey1, tagValue1) } -func testAccModelConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccModelConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -506,7 +506,7 @@ resource "aws_sagemaker_model" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccPrimaryContainerModelDataURLConfig(rName string) string { +func testAccModelConfig_primaryContainerDataURL(rName string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -581,7 +581,7 @@ resource "aws_s3_object" "test" { `, rName) } -func testAccPrimaryContainerHostnameConfig(rName string) string { +func testAccModelConfig_primaryContainerHostname(rName string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -595,7 +595,7 @@ resource "aws_sagemaker_model" "test" { `, rName) } -func testAccPrimaryContainerImageConfigConfig(rName string) string { +func testAccModelConfig_primaryContainerImage(rName string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -612,7 +612,7 @@ resource "aws_sagemaker_model" "test" { `, rName) } -func testAccPrimaryContainerEnvironmentConfig(rName string) string { +func testAccModelConfig_primaryContainerEnvironment(rName string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -629,7 +629,7 @@ resource "aws_sagemaker_model" "test" { `, rName) } -func testAccPrimaryContainerModeSingle(rName string) string { +func testAccModelConfig_primaryContainerModeSingle(rName string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -643,7 +643,7 @@ resource "aws_sagemaker_model" "test" { `, rName) } -func testAccModelContainers(rName string) string { +func testAccModelConfig_containers(rName string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -660,7 +660,7 @@ resource "aws_sagemaker_model" "test" { `, rName) } -func testAccModelNetworkIsolation(rName string) string { +func testAccModelConfig_networkIsolation(rName string) string { return testAccModelConfigBase(rName) + fmt.Sprintf(` resource "aws_sagemaker_model" "test" { name = %[1]q @@ -674,7 +674,7 @@ resource "aws_sagemaker_model" "test" { `, rName) } -func testAccModelVPCConfig_basic(rName string) string { +func testAccModelConfig_vpcBasic(rName string) string { return testAccModelConfigBase(rName) + acctest.ConfigAvailableAZsNoOptIn() + fmt.Sprintf(` diff --git a/internal/service/sagemaker/notebook_instance.go b/internal/service/sagemaker/notebook_instance.go index bcd4159d53f..6620c763ae7 100644 --- a/internal/service/sagemaker/notebook_instance.go +++ b/internal/service/sagemaker/notebook_instance.go @@ -9,7 +9,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sagemaker" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -42,103 +41,105 @@ func ResourceNotebookInstance() *schema.Resource { Type: schema.TypeString, Computed: true, }, - - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validName, - }, - - "role_arn": { - Type: schema.TypeString, - Required: true, - ValidateFunc: verify.ValidARN, - }, - - "instance_type": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(sagemaker.InstanceType_Values(), false), - }, - - "platform_identifier": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - ValidateFunc: validation.StringMatch(regexp.MustCompile(`^(notebook-al1-v1|notebook-al2-v1)$`), ""), - }, - "additional_code_repositories": { Type: schema.TypeSet, Optional: true, MaxItems: 3, Elem: &schema.Schema{Type: schema.TypeString}, }, - - "volume_size": { - Type: schema.TypeInt, - Optional: true, - Default: 5, - }, - - "subnet_id": { + "default_code_repository": { Type: schema.TypeString, Optional: true, - ForceNew: true, }, - - "security_groups": { - Type: schema.TypeSet, - MinItems: 1, - Optional: true, - Computed: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, + "direct_internet_access": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: sagemaker.DirectInternetAccessEnabled, + ValidateFunc: validation.StringInSlice(sagemaker.DirectInternetAccess_Values(), false), + }, + "instance_metadata_service_configuration": { + Type: schema.TypeList, + Optional: true, + DiffSuppressFunc: verify.SuppressMissingOptionalConfigurationBlock, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "minimum_instance_metadata_service_version": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"1", "2"}, false), + }, + }, + }, + }, + "instance_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(sagemaker.InstanceType_Values(), false), }, - "kms_key_id": { Type: schema.TypeString, Optional: true, ForceNew: true, }, - "lifecycle_config_name": { Type: schema.TypeString, Optional: true, }, - + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validName, + }, + "network_interface_id": { + Type: schema.TypeString, + Computed: true, + }, + "platform_identifier": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: validation.StringMatch(regexp.MustCompile(`^(notebook-al1-v1|notebook-al2-v1|notebook-al2-v2)$`), ""), + }, + "role_arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidARN, + }, "root_access": { Type: schema.TypeString, Optional: true, Default: sagemaker.RootAccessEnabled, ValidateFunc: validation.StringInSlice(sagemaker.RootAccess_Values(), false), }, - - "direct_internet_access": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Default: sagemaker.DirectInternetAccessEnabled, - ValidateFunc: validation.StringInSlice(sagemaker.DirectInternetAccess_Values(), false), + "security_groups": { + Type: schema.TypeSet, + MinItems: 1, + Optional: true, + Computed: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, - - "default_code_repository": { + "subnet_id": { Type: schema.TypeString, Optional: true, + ForceNew: true, }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), "url": { Type: schema.TypeString, Computed: true, }, - "network_interface_id": { - Type: schema.TypeString, - Computed: true, + "volume_size": { + Type: schema.TypeInt, + Optional: true, + Default: 5, }, - "tags": tftags.TagsSchema(), - "tags_all": tftags.TagsSchemaComputed(), }, } } @@ -151,10 +152,11 @@ func resourceNotebookInstanceCreate(d *schema.ResourceData, meta interface{}) er name := d.Get("name").(string) createOpts := &sagemaker.CreateNotebookInstanceInput{ - SecurityGroupIds: flex.ExpandStringSet(d.Get("security_groups").(*schema.Set)), - NotebookInstanceName: aws.String(name), - RoleArn: aws.String(d.Get("role_arn").(string)), - InstanceType: aws.String(d.Get("instance_type").(string)), + SecurityGroupIds: flex.ExpandStringSet(d.Get("security_groups").(*schema.Set)), + NotebookInstanceName: aws.String(name), + RoleArn: aws.String(d.Get("role_arn").(string)), + InstanceType: aws.String(d.Get("instance_type").(string)), + InstanceMetadataServiceConfiguration: expandNotebookInstanceMetadataServiceConfiguration(d.Get("instance_metadata_service_configuration").([]interface{})), } if v, ok := d.GetOk("root_access"); ok { @@ -218,85 +220,43 @@ func resourceNotebookInstanceRead(d *schema.ResourceData, meta interface{}) erro defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - describeNotebookInput := &sagemaker.DescribeNotebookInstanceInput{ - NotebookInstanceName: aws.String(d.Id()), - } - notebookInstance, err := conn.DescribeNotebookInstance(describeNotebookInput) - if err != nil { - if tfawserr.ErrMessageContains(err, "ValidationException", "RecordNotFound") { - d.SetId("") - log.Printf("[WARN] Unable to find sageMaker notebook instance (%s); removing from state", d.Id()) - return nil - } - return fmt.Errorf("error finding sagemaker notebook instance (%s): %s", d.Id(), err) - - } - - if err := d.Set("security_groups", flex.FlattenStringList(notebookInstance.SecurityGroups)); err != nil { - return fmt.Errorf("error setting security groups for sagemaker notebook instance (%s): %s", d.Id(), err) - } - if err := d.Set("name", notebookInstance.NotebookInstanceName); err != nil { - return fmt.Errorf("error setting name for sagemaker notebook instance (%s): %s", d.Id(), err) - } - if err := d.Set("role_arn", notebookInstance.RoleArn); err != nil { - return fmt.Errorf("error setting role_arn for sagemaker notebook instance (%s): %s", d.Id(), err) - } - if err := d.Set("instance_type", notebookInstance.InstanceType); err != nil { - return fmt.Errorf("error setting instance_type for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("platform_identifier", notebookInstance.PlatformIdentifier); err != nil { - return fmt.Errorf("error setting platform_identifier for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("subnet_id", notebookInstance.SubnetId); err != nil { - return fmt.Errorf("error setting subnet_id for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("kms_key_id", notebookInstance.KmsKeyId); err != nil { - return fmt.Errorf("error setting kms_key_id for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("volume_size", notebookInstance.VolumeSizeInGB); err != nil { - return fmt.Errorf("error setting volume_size for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("lifecycle_config_name", notebookInstance.NotebookInstanceLifecycleConfigName); err != nil { - return fmt.Errorf("error setting lifecycle_config_name for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("arn", notebookInstance.NotebookInstanceArn); err != nil { - return fmt.Errorf("error setting arn for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("root_access", notebookInstance.RootAccess); err != nil { - return fmt.Errorf("error setting root_access for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("direct_internet_access", notebookInstance.DirectInternetAccess); err != nil { - return fmt.Errorf("error setting direct_internet_access for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("default_code_repository", notebookInstance.DefaultCodeRepository); err != nil { - return fmt.Errorf("error setting default_code_repository for sagemaker notebook instance (%s): %s", d.Id(), err) - } - - if err := d.Set("url", notebookInstance.Url); err != nil { - return fmt.Errorf("error setting url for sagemaker notebook instance (%s): %w", d.Id(), err) - } + notebookInstance, err := FindNotebookInstanceByName(conn, d.Id()) - if err := d.Set("network_interface_id", notebookInstance.NetworkInterfaceId); err != nil { - return fmt.Errorf("error setting network_interface_id for sagemaker notebook instance (%s): %w", d.Id(), err) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] SageMaker Notebook Instance (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } - if err := d.Set("additional_code_repositories", flex.FlattenStringSet(notebookInstance.AdditionalCodeRepositories)); err != nil { - return fmt.Errorf("error setting additional_code_repositories for sagemaker notebook instance (%s): %s", d.Id(), err) + if err != nil { + return fmt.Errorf("error reading SageMaker Notebook Instance (%s): %w", d.Id(), err) + } + + d.Set("name", notebookInstance.NotebookInstanceName) + d.Set("role_arn", notebookInstance.RoleArn) + d.Set("instance_type", notebookInstance.InstanceType) + d.Set("platform_identifier", notebookInstance.PlatformIdentifier) + d.Set("subnet_id", notebookInstance.SubnetId) + d.Set("kms_key_id", notebookInstance.KmsKeyId) + d.Set("volume_size", notebookInstance.VolumeSizeInGB) + d.Set("lifecycle_config_name", notebookInstance.NotebookInstanceLifecycleConfigName) + d.Set("arn", notebookInstance.NotebookInstanceArn) + d.Set("root_access", notebookInstance.RootAccess) + d.Set("direct_internet_access", notebookInstance.DirectInternetAccess) + d.Set("default_code_repository", notebookInstance.DefaultCodeRepository) + d.Set("url", notebookInstance.Url) + d.Set("network_interface_id", notebookInstance.NetworkInterfaceId) + d.Set("additional_code_repositories", flex.FlattenStringSet(notebookInstance.AdditionalCodeRepositories)) + d.Set("security_groups", flex.FlattenStringList(notebookInstance.SecurityGroups)) + + if err := d.Set("instance_metadata_service_configuration", flattenNotebookInstanceMetadataServiceConfiguration(notebookInstance.InstanceMetadataServiceConfiguration)); err != nil { + return fmt.Errorf("error setting instance_metadata_service_configuration for sagemaker notebook instance (%s): %w", d.Id(), err) } tags, err := ListTags(conn, aws.StringValue(notebookInstance.NotebookInstanceArn)) if err != nil { - return fmt.Errorf("error listing tags for SageMaker Notebook Instance (%s): %s", d.Id(), err) + return fmt.Errorf("error listing tags for SageMaker Notebook Instance (%s): %w", d.Id(), err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -324,63 +284,57 @@ func resourceNotebookInstanceUpdate(d *schema.ResourceData, meta interface{}) er } } - hasChanged := false - // Update - updateOpts := &sagemaker.UpdateNotebookInstanceInput{ - NotebookInstanceName: aws.String(d.Get("name").(string)), - } + if d.HasChangesExcept("tags", "tags_all") { + updateOpts := &sagemaker.UpdateNotebookInstanceInput{ + NotebookInstanceName: aws.String(d.Get("name").(string)), + } - if d.HasChange("role_arn") { - updateOpts.RoleArn = aws.String(d.Get("role_arn").(string)) - hasChanged = true - } + if d.HasChange("role_arn") { + updateOpts.RoleArn = aws.String(d.Get("role_arn").(string)) + } - if d.HasChange("instance_type") { - updateOpts.InstanceType = aws.String(d.Get("instance_type").(string)) - hasChanged = true - } + if d.HasChange("instance_type") { + updateOpts.InstanceType = aws.String(d.Get("instance_type").(string)) + } - if d.HasChange("volume_size") { - updateOpts.VolumeSizeInGB = aws.Int64(int64(d.Get("volume_size").(int))) - hasChanged = true - } + if d.HasChange("volume_size") { + updateOpts.VolumeSizeInGB = aws.Int64(int64(d.Get("volume_size").(int))) + } - if d.HasChange("lifecycle_config_name") { - if v, ok := d.GetOk("lifecycle_config_name"); ok { - updateOpts.LifecycleConfigName = aws.String(v.(string)) - } else { - updateOpts.DisassociateLifecycleConfig = aws.Bool(true) + if d.HasChange("lifecycle_config_name") { + if v, ok := d.GetOk("lifecycle_config_name"); ok { + updateOpts.LifecycleConfigName = aws.String(v.(string)) + } else { + updateOpts.DisassociateLifecycleConfig = aws.Bool(true) + } } - hasChanged = true - } - if d.HasChange("default_code_repository") { - if v, ok := d.GetOk("default_code_repository"); ok { - updateOpts.DefaultCodeRepository = aws.String(v.(string)) - } else { - updateOpts.DisassociateDefaultCodeRepository = aws.Bool(true) + if d.HasChange("default_code_repository") { + if v, ok := d.GetOk("default_code_repository"); ok { + updateOpts.DefaultCodeRepository = aws.String(v.(string)) + } else { + updateOpts.DisassociateDefaultCodeRepository = aws.Bool(true) + } } - hasChanged = true - } - if d.HasChange("root_access") { - updateOpts.RootAccess = aws.String(d.Get("root_access").(string)) - hasChanged = true - } + if d.HasChange("instance_metadata_service_configuration") { + updateOpts.InstanceMetadataServiceConfiguration = expandNotebookInstanceMetadataServiceConfiguration(d.Get("instance_metadata_service_configuration").([]interface{})) + } - if d.HasChange("additional_code_repositories") { - if v, ok := d.GetOk("additional_code_repositories"); ok { - updateOpts.AdditionalCodeRepositories = flex.ExpandStringSet(v.(*schema.Set)) - } else { - updateOpts.DisassociateAdditionalCodeRepositories = aws.Bool(true) + if d.HasChange("root_access") { + updateOpts.RootAccess = aws.String(d.Get("root_access").(string)) } - hasChanged = true - } - if hasChanged { + if d.HasChange("additional_code_repositories") { + if v, ok := d.GetOk("additional_code_repositories"); ok { + updateOpts.AdditionalCodeRepositories = flex.ExpandStringSet(v.(*schema.Set)) + } else { + updateOpts.DisassociateAdditionalCodeRepositories = aws.Bool(true) + } + } // Stop notebook - _, previousStatus, _ := notebookInstanceStateRefreshFunc(conn, d.Id())() + _, previousStatus, _ := StatusNotebookInstance(conn, d.Id())() if previousStatus != sagemaker.NotebookInstanceStatusStopped { if err := StopNotebookInstance(conn, d.Id()); err != nil { return fmt.Errorf("error stopping sagemaker notebook instance prior to updating: %s", err) @@ -404,8 +358,11 @@ func resourceNotebookInstanceUpdate(d *schema.ResourceData, meta interface{}) er Pending: []string{ sagemaker.NotebookInstanceStatusStopped, }, - Target: []string{sagemaker.NotebookInstanceStatusInService, sagemaker.NotebookInstanceStatusPending}, - Refresh: notebookInstanceStateRefreshFunc(conn, d.Id()), + Target: []string{ + sagemaker.NotebookInstanceStatusInService, + sagemaker.NotebookInstanceStatusPending, + }, + Refresh: StatusNotebookInstance(conn, d.Id()), Timeout: 30 * time.Second, } // StartNotebookInstance sometimes doesn't take so we'll check for a state change and if @@ -447,15 +404,13 @@ func resourceNotebookInstanceUpdate(d *schema.ResourceData, meta interface{}) er func resourceNotebookInstanceDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SageMakerConn - describeNotebookInput := &sagemaker.DescribeNotebookInstanceInput{ - NotebookInstanceName: aws.String(d.Id()), - } - notebook, err := conn.DescribeNotebookInstance(describeNotebookInput) + notebook, err := FindNotebookInstanceByName(conn, d.Id()) + if err != nil { - if tfawserr.ErrMessageContains(err, "ValidationException", "RecordNotFound") { + if tfresource.NotFound(err) { return nil } - return fmt.Errorf("unable to find sagemaker notebook instance to delete (%s): %s", d.Id(), err) + return fmt.Errorf("error reading SageMaker Notebook Instance (%s): %w", d.Id(), err) } if aws.StringValue(notebook.NotebookInstanceStatus) != sagemaker.NotebookInstanceStatusFailed && @@ -474,9 +429,6 @@ func resourceNotebookInstanceDelete(d *schema.ResourceData, meta interface{}) er } if _, err := WaitNotebookInstanceDeleted(conn, d.Id()); err != nil { - if tfawserr.ErrMessageContains(err, "ValidationException", "RecordNotFound") { - return nil - } return fmt.Errorf("error waiting for sagemaker notebook instance (%s) to delete: %w", d.Id(), err) } @@ -484,16 +436,15 @@ func resourceNotebookInstanceDelete(d *schema.ResourceData, meta interface{}) er } func StopNotebookInstance(conn *sagemaker.SageMaker, id string) error { - describeNotebookInput := &sagemaker.DescribeNotebookInstanceInput{ - NotebookInstanceName: aws.String(id), - } - notebook, err := conn.DescribeNotebookInstance(describeNotebookInput) + notebook, err := FindNotebookInstanceByName(conn, id) + if err != nil { - if tfawserr.ErrMessageContains(err, "ValidationException", "RecordNotFound") { + if tfresource.NotFound(err) { return nil } - return fmt.Errorf("unable to find sagemaker notebook instance (%s): %s", id, err) + return fmt.Errorf("error reading SageMaker Notebook Instance (%s): %w", id, err) } + if aws.StringValue(notebook.NotebookInstanceStatus) == sagemaker.NotebookInstanceStatusStopped { return nil } @@ -513,23 +464,28 @@ func StopNotebookInstance(conn *sagemaker.SageMaker, id string) error { return nil } -func notebookInstanceStateRefreshFunc(conn *sagemaker.SageMaker, name string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - describeNotebookInput := &sagemaker.DescribeNotebookInstanceInput{ - NotebookInstanceName: aws.String(name), - } - notebook, err := conn.DescribeNotebookInstance(describeNotebookInput) - if err != nil { - if tfawserr.ErrMessageContains(err, "ValidationException", "RecordNotFound") { - return 1, "", nil - } - return nil, "", err - } +func expandNotebookInstanceMetadataServiceConfiguration(l []interface{}) *sagemaker.InstanceMetadataServiceConfiguration { + if len(l) == 0 || l[0] == nil { + return nil + } - if notebook == nil { - return nil, "", nil - } + m := l[0].(map[string]interface{}) - return notebook, *notebook.NotebookInstanceStatus, nil + config := &sagemaker.InstanceMetadataServiceConfiguration{ + MinimumInstanceMetadataServiceVersion: aws.String(m["minimum_instance_metadata_service_version"].(string)), } + + return config +} + +func flattenNotebookInstanceMetadataServiceConfiguration(config *sagemaker.InstanceMetadataServiceConfiguration) []map[string]interface{} { + if config == nil { + return []map[string]interface{}{} + } + + m := map[string]interface{}{ + "minimum_instance_metadata_service_version": aws.StringValue(config.MinimumInstanceMetadataServiceVersion), + } + + return []map[string]interface{}{m} } diff --git a/internal/service/sagemaker/notebook_instance_lifecycle_configuration_test.go b/internal/service/sagemaker/notebook_instance_lifecycle_configuration_test.go index 417ab3b49c5..9fd90edb027 100644 --- a/internal/service/sagemaker/notebook_instance_lifecycle_configuration_test.go +++ b/internal/service/sagemaker/notebook_instance_lifecycle_configuration_test.go @@ -27,7 +27,7 @@ func TestAccSageMakerNotebookInstanceLifecycleConfiguration_basic(t *testing.T) CheckDestroy: testAccCheckNotebookInstanceLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceLifecycleConfigurationConfig_Basic(rName), + Config: testAccNotebookInstanceLifecycleConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceLifecycleConfigurationExists(resourceName, &lifecycleConfig), @@ -58,7 +58,7 @@ func TestAccSageMakerNotebookInstanceLifecycleConfiguration_update(t *testing.T) CheckDestroy: testAccCheckNotebookInstanceLifecycleConfigurationDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceLifecycleConfigurationConfig_Basic(rName), + Config: testAccNotebookInstanceLifecycleConfigurationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceLifecycleConfigurationExists(resourceName, &lifecycleConfig), @@ -66,7 +66,7 @@ func TestAccSageMakerNotebookInstanceLifecycleConfiguration_update(t *testing.T) ), }, { - Config: testAccNotebookInstanceLifecycleConfigurationConfig_Update(rName), + Config: testAccNotebookInstanceLifecycleConfigurationConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceLifecycleConfigurationExists(resourceName, &lifecycleConfig), @@ -138,7 +138,7 @@ func testAccCheckNotebookInstanceLifecycleConfigurationDestroy(s *terraform.Stat return nil } -func testAccNotebookInstanceLifecycleConfigurationConfig_Basic(rName string) string { +func testAccNotebookInstanceLifecycleConfigurationConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_notebook_instance_lifecycle_configuration" "test" { name = %q @@ -146,7 +146,7 @@ resource "aws_sagemaker_notebook_instance_lifecycle_configuration" "test" { `, rName) } -func testAccNotebookInstanceLifecycleConfigurationConfig_Update(rName string) string { +func testAccNotebookInstanceLifecycleConfigurationConfig_update(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_notebook_instance_lifecycle_configuration" "test" { name = %q diff --git a/internal/service/sagemaker/notebook_instance_test.go b/internal/service/sagemaker/notebook_instance_test.go index 18e1cd1cb87..95355e4ae2a 100644 --- a/internal/service/sagemaker/notebook_instance_test.go +++ b/internal/service/sagemaker/notebook_instance_test.go @@ -8,13 +8,13 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sagemaker" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfsagemaker "github.com/hashicorp/terraform-provider-aws/internal/service/sagemaker" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func TestAccSageMakerNotebookInstance_basic(t *testing.T) { @@ -33,7 +33,7 @@ func TestAccSageMakerNotebookInstance_basic(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceBasicConfig(rName), + Config: testAccNotebookInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -45,6 +45,8 @@ func TestAccSageMakerNotebookInstance_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "volume_size", "5"), resource.TestCheckResourceAttr(resourceName, "default_code_repository", ""), resource.TestCheckResourceAttr(resourceName, "additional_code_repositories.#", "0"), + resource.TestCheckResourceAttr(resourceName, "instance_metadata_service_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "instance_metadata_service_configuration.0.minimum_instance_metadata_service_version", "1"), resource.TestCheckResourceAttr(resourceName, "security_groups.#", "0"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), resource.TestCheckResourceAttrSet(resourceName, "url"), @@ -59,6 +61,46 @@ func TestAccSageMakerNotebookInstance_basic(t *testing.T) { }) } +func TestAccSageMakerNotebookInstance_imds(t *testing.T) { + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var notebook sagemaker.DescribeNotebookInstanceOutput + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_sagemaker_notebook_instance.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, sagemaker.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckNotebookInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccNotebookInstanceConfig_imds(rName, "2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckNotebookInstanceExists(resourceName, ¬ebook), + resource.TestCheckResourceAttr(resourceName, "instance_metadata_service_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "instance_metadata_service_configuration.0.minimum_instance_metadata_service_version", "2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccNotebookInstanceConfig_imds(rName, "1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckNotebookInstanceExists(resourceName, ¬ebook), + resource.TestCheckResourceAttr(resourceName, "instance_metadata_service_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "instance_metadata_service_configuration.0.minimum_instance_metadata_service_version", "1"), + ), + }, + }, + }) +} + func TestAccSageMakerNotebookInstance_update(t *testing.T) { if testing.Short() { t.Skip("skipping long-running test in short mode") @@ -75,7 +117,7 @@ func TestAccSageMakerNotebookInstance_update(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceBasicConfig(rName), + Config: testAccNotebookInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "instance_type", "ml.t2.medium"), @@ -83,7 +125,7 @@ func TestAccSageMakerNotebookInstance_update(t *testing.T) { }, { - Config: testAccNotebookInstanceUpdateConfig(rName), + Config: testAccNotebookInstanceConfig_update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "instance_type", "ml.m4.xlarge"), @@ -113,14 +155,14 @@ func TestAccSageMakerNotebookInstance_volumeSize(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceBasicConfig(rName), + Config: testAccNotebookInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook1), resource.TestCheckResourceAttr(resourceName, "volume_size", "5"), ), }, { - Config: testAccNotebookInstanceVolumeConfig(rName), + Config: testAccNotebookInstanceConfig_volume(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook2), resource.TestCheckResourceAttr(resourceName, "volume_size", "8"), @@ -133,7 +175,7 @@ func TestAccSageMakerNotebookInstance_volumeSize(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotebookInstanceBasicConfig(rName), + Config: testAccNotebookInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook3), resource.TestCheckResourceAttr(resourceName, "volume_size", "5"), @@ -161,7 +203,7 @@ func TestAccSageMakerNotebookInstance_lifecycleName(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceLifecycleNameConfig(rName), + Config: testAccNotebookInstanceConfig_lifecycleName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttrPair(resourceName, "lifecycle_config_name", sagemakerLifecycleConfigResourceName, "name"), @@ -173,14 +215,14 @@ func TestAccSageMakerNotebookInstance_lifecycleName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotebookInstanceBasicConfig(rName), + Config: testAccNotebookInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "lifecycle_config_name", ""), ), }, { - Config: testAccNotebookInstanceLifecycleNameConfig(rName), + Config: testAccNotebookInstanceConfig_lifecycleName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttrPair(resourceName, "lifecycle_config_name", sagemakerLifecycleConfigResourceName, "name"), @@ -206,7 +248,7 @@ func TestAccSageMakerNotebookInstance_tags(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceTags1Config(rName, "key1", "value1"), + Config: testAccNotebookInstanceConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -219,7 +261,7 @@ func TestAccSageMakerNotebookInstance_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotebookInstanceTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccNotebookInstanceConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -228,7 +270,7 @@ func TestAccSageMakerNotebookInstance_tags(t *testing.T) { ), }, { - Config: testAccNotebookInstanceTags1Config(rName, "key2", "value2"), + Config: testAccNotebookInstanceConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -255,7 +297,7 @@ func TestAccSageMakerNotebookInstance_kms(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceKMSConfig(rName), + Config: testAccNotebookInstanceConfig_kms(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", "aws_kms_key.test", "id"), @@ -286,7 +328,7 @@ func TestAccSageMakerNotebookInstance_disappears(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceBasicConfig(rName), + Config: testAccNotebookInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceNotebookInstance(), resourceName), @@ -305,21 +347,14 @@ func testAccCheckNotebookInstanceDestroy(s *terraform.State) error { continue } - describeNotebookInput := &sagemaker.DescribeNotebookInstanceInput{ - NotebookInstanceName: aws.String(rs.Primary.ID), - } - notebookInstance, err := conn.DescribeNotebookInstance(describeNotebookInput) + _, err := tfsagemaker.FindNotebookInstanceByName(conn, rs.Primary.ID) - if tfawserr.ErrMessageContains(err, tfsagemaker.ErrCodeValidationException, "RecordNotFound") { + if tfresource.NotFound(err) { continue } if err != nil { - return fmt.Errorf("error reading SageMaker Notebook Instance (%s): %w", rs.Primary.ID, err) - } - - if aws.StringValue(notebookInstance.NotebookInstanceName) == rs.Primary.ID { - return fmt.Errorf("sagemaker notebook instance %q still exists", rs.Primary.ID) + return err } } @@ -338,15 +373,13 @@ func testAccCheckNotebookInstanceExists(n string, notebook *sagemaker.DescribeNo } conn := acctest.Provider.Meta().(*conns.AWSClient).SageMakerConn - opts := &sagemaker.DescribeNotebookInstanceInput{ - NotebookInstanceName: aws.String(rs.Primary.ID), - } - resp, err := conn.DescribeNotebookInstance(opts) + output, err := tfsagemaker.FindNotebookInstanceByName(conn, rs.Primary.ID) + if err != nil { return err } - *notebook = *resp + *notebook = *output return nil } @@ -388,7 +421,7 @@ func TestAccSageMakerNotebookInstance_Root_access(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceRootAccessConfig(rName, "Disabled"), + Config: testAccNotebookInstanceConfig_rootAccess(rName, "Disabled"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "root_access", "Disabled"), @@ -400,7 +433,7 @@ func TestAccSageMakerNotebookInstance_Root_access(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotebookInstanceRootAccessConfig(rName, "Enabled"), + Config: testAccNotebookInstanceConfig_rootAccess(rName, "Enabled"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "root_access", "Enabled"), @@ -426,7 +459,7 @@ func TestAccSageMakerNotebookInstance_Platform_identifier(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstancePlatformIdentifierConfig(rName, "notebook-al2-v1"), + Config: testAccNotebookInstanceConfig_platformIdentifier(rName, "notebook-al2-v1"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "platform_identifier", "notebook-al2-v1"), @@ -438,7 +471,7 @@ func TestAccSageMakerNotebookInstance_Platform_identifier(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotebookInstancePlatformIdentifierConfig(rName, "notebook-al1-v1"), + Config: testAccNotebookInstanceConfig_platformIdentifier(rName, "notebook-al1-v1"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "platform_identifier", "notebook-al1-v1"), @@ -464,7 +497,7 @@ func TestAccSageMakerNotebookInstance_DirectInternet_access(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceDirectInternetAccessConfig(rName, "Disabled"), + Config: testAccNotebookInstanceConfig_directInternetAccess(rName, "Disabled"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "direct_internet_access", "Disabled"), @@ -479,7 +512,7 @@ func TestAccSageMakerNotebookInstance_DirectInternet_access(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotebookInstanceDirectInternetAccessConfig(rName, "Enabled"), + Config: testAccNotebookInstanceConfig_directInternetAccess(rName, "Enabled"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "direct_internet_access", "Enabled"), @@ -507,7 +540,7 @@ func TestAccSageMakerNotebookInstance_DefaultCode_repository(t *testing.T) { CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceDefaultCodeRepositoryConfig(rName, "https://github.com/hashicorp/terraform-provider-aws.git"), + Config: testAccNotebookInstanceConfig_defaultCodeRepository(rName, "https://github.com/hashicorp/terraform-provider-aws.git"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "default_code_repository", "https://github.com/hashicorp/terraform-provider-aws.git"), @@ -519,14 +552,14 @@ func TestAccSageMakerNotebookInstance_DefaultCode_repository(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNotebookInstanceBasicConfig(rName), + Config: testAccNotebookInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "default_code_repository", ""), ), }, { - Config: testAccNotebookInstanceDefaultCodeRepositoryConfig(rName, "https://github.com/hashicorp/terraform-provider-aws.git"), + Config: testAccNotebookInstanceConfig_defaultCodeRepository(rName, "https://github.com/hashicorp/terraform-provider-aws.git"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "default_code_repository", "https://github.com/hashicorp/terraform-provider-aws.git"), @@ -551,7 +584,7 @@ func TestAccSageMakerNotebookInstance_AdditionalCode_repositories(t *testing.T) CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceAdditionalCodeRepository1Config(rName, "https://github.com/hashicorp/terraform-provider-aws.git"), + Config: testAccNotebookInstanceConfig_additionalCodeRepository1(rName, "https://github.com/hashicorp/terraform-provider-aws.git"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "additional_code_repositories.#", "1"), @@ -564,14 +597,14 @@ func TestAccSageMakerNotebookInstance_AdditionalCode_repositories(t *testing.T) ImportStateVerify: true, }, { - Config: testAccNotebookInstanceBasicConfig(rName), + Config: testAccNotebookInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "additional_code_repositories.#", "0"), ), }, { - Config: testAccNotebookInstanceAdditionalCodeRepository2Config(rName, "https://github.com/hashicorp/terraform-provider-aws.git", "https://github.com/hashicorp/terraform.git"), + Config: testAccNotebookInstanceConfig_additionalCodeRepository2(rName, "https://github.com/hashicorp/terraform-provider-aws.git", "https://github.com/hashicorp/terraform.git"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "additional_code_repositories.#", "2"), @@ -580,7 +613,7 @@ func TestAccSageMakerNotebookInstance_AdditionalCode_repositories(t *testing.T) ), }, { - Config: testAccNotebookInstanceAdditionalCodeRepository1Config(rName, "https://github.com/hashicorp/terraform-provider-aws.git"), + Config: testAccNotebookInstanceConfig_additionalCodeRepository1(rName, "https://github.com/hashicorp/terraform-provider-aws.git"), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "additional_code_repositories.#", "1"), @@ -606,7 +639,7 @@ func TestAccSageMakerNotebookInstance_DefaultCodeRepository_sageMakerRepo(t *tes CheckDestroy: testAccCheckNotebookInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccNotebookInstanceDefaultCodeRepositoryRepoConfig(rName), + Config: testAccNotebookInstanceConfig_defaultCodeRepositoryRepo(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttrPair(resourceName, "default_code_repository", "aws_sagemaker_code_repository.test", "code_repository_name"), @@ -618,14 +651,14 @@ func TestAccSageMakerNotebookInstance_DefaultCodeRepository_sageMakerRepo(t *tes ImportStateVerify: true, }, { - Config: testAccNotebookInstanceBasicConfig(rName), + Config: testAccNotebookInstanceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttr(resourceName, "default_code_repository", ""), ), }, { - Config: testAccNotebookInstanceDefaultCodeRepositoryRepoConfig(rName), + Config: testAccNotebookInstanceConfig_defaultCodeRepositoryRepo(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNotebookInstanceExists(resourceName, ¬ebook), resource.TestCheckResourceAttrPair(resourceName, "default_code_repository", "aws_sagemaker_code_repository.test", "code_repository_name")), @@ -655,7 +688,7 @@ data "aws_iam_policy_document" "test" { `, rName) } -func testAccNotebookInstanceBasicConfig(rName string) string { +func testAccNotebookInstanceConfig_basic(rName string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -665,7 +698,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName) } -func testAccNotebookInstanceUpdateConfig(rName string) string { +func testAccNotebookInstanceConfig_update(rName string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -675,7 +708,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName) } -func testAccNotebookInstanceLifecycleNameConfig(rName string) string { +func testAccNotebookInstanceConfig_lifecycleName(rName string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance_lifecycle_configuration" "test" { name = %[1]q @@ -690,7 +723,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName) } -func testAccNotebookInstanceTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccNotebookInstanceConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -704,7 +737,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName, tagKey1, tagValue1) } -func testAccNotebookInstanceTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccNotebookInstanceConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -719,7 +752,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccNotebookInstanceRootAccessConfig(rName string, rootAccess string) string { +func testAccNotebookInstanceConfig_rootAccess(rName string, rootAccess string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -730,7 +763,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName, rootAccess) } -func testAccNotebookInstancePlatformIdentifierConfig(rName string, platformIdentifier string) string { +func testAccNotebookInstanceConfig_platformIdentifier(rName string, platformIdentifier string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -740,7 +773,7 @@ resource "aws_sagemaker_notebook_instance" "test" { } `, rName, platformIdentifier) } -func testAccNotebookInstanceDirectInternetAccessConfig(rName string, directInternetAccess string) string { +func testAccNotebookInstanceConfig_directInternetAccess(rName string, directInternetAccess string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { @@ -779,7 +812,7 @@ resource "aws_security_group" "test" { `, rName, directInternetAccess) } -func testAccNotebookInstanceVolumeConfig(rName string) string { +func testAccNotebookInstanceConfig_volume(rName string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -790,7 +823,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName) } -func testAccNotebookInstanceDefaultCodeRepositoryConfig(rName string, defaultCodeRepository string) string { +func testAccNotebookInstanceConfig_defaultCodeRepository(rName string, defaultCodeRepository string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -801,7 +834,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName, defaultCodeRepository) } -func testAccNotebookInstanceAdditionalCodeRepository1Config(rName, repo1 string) string { +func testAccNotebookInstanceConfig_additionalCodeRepository1(rName, repo1 string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -812,7 +845,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName, repo1) } -func testAccNotebookInstanceAdditionalCodeRepository2Config(rName, repo1, repo2 string) string { +func testAccNotebookInstanceConfig_additionalCodeRepository2(rName, repo1, repo2 string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_notebook_instance" "test" { name = %[1]q @@ -823,7 +856,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName, repo1, repo2) } -func testAccNotebookInstanceDefaultCodeRepositoryRepoConfig(rName string) string { +func testAccNotebookInstanceConfig_defaultCodeRepositoryRepo(rName string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_code_repository" "test" { code_repository_name = %[1]q @@ -842,7 +875,7 @@ resource "aws_sagemaker_notebook_instance" "test" { `, rName) } -func testAccNotebookInstanceKMSConfig(rName string) string { +func testAccNotebookInstanceConfig_kms(rName string) string { return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Terraform acc test %[1]s" @@ -874,3 +907,16 @@ resource "aws_sagemaker_notebook_instance" "test" { } `, rName) } + +func testAccNotebookInstanceConfig_imds(rName, version string) string { + return testAccNotebookInstanceBaseConfig(rName) + fmt.Sprintf(` +resource "aws_sagemaker_notebook_instance" "test" { + name = %[1]q + role_arn = aws_iam_role.test.arn + instance_type = "ml.t2.medium" + instance_metadata_service_configuration { + minimum_instance_metadata_service_version = %[2]q + } +} +`, rName, version) +} diff --git a/internal/service/sagemaker/prebuilt_ecr_image_data_source_test.go b/internal/service/sagemaker/prebuilt_ecr_image_data_source_test.go index 276d9034bc3..2f958dcb11f 100644 --- a/internal/service/sagemaker/prebuilt_ecr_image_data_source_test.go +++ b/internal/service/sagemaker/prebuilt_ecr_image_data_source_test.go @@ -20,7 +20,7 @@ func TestAccSageMakerPrebuiltECRImageDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPrebuiltECRImageConfig_basic, + Config: testAccPrebuiltECRImageDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", expectedID), resource.TestCheckResourceAttr(dataSourceName, "registry_id", expectedID), @@ -42,7 +42,7 @@ func TestAccSageMakerPrebuiltECRImageDataSource_region(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPrebuiltECRImageConfig_explicitRegion, + Config: testAccPrebuiltECRImageDataSourceConfig_explicitRegion, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "id", expectedID), resource.TestCheckResourceAttr(dataSourceName, "registry_id", expectedID), @@ -53,13 +53,13 @@ func TestAccSageMakerPrebuiltECRImageDataSource_region(t *testing.T) { }) } -const testAccPrebuiltECRImageConfig_basic = ` +const testAccPrebuiltECRImageDataSourceConfig_basic = ` data "aws_sagemaker_prebuilt_ecr_image" "test" { repository_name = "kmeans" } ` -const testAccPrebuiltECRImageConfig_explicitRegion = ` +const testAccPrebuiltECRImageDataSourceConfig_explicitRegion = ` data "aws_region" "current" {} data "aws_sagemaker_prebuilt_ecr_image" "test" { diff --git a/internal/service/sagemaker/project_test.go b/internal/service/sagemaker/project_test.go index 4243e968d4d..a26867469b2 100644 --- a/internal/service/sagemaker/project_test.go +++ b/internal/service/sagemaker/project_test.go @@ -27,7 +27,7 @@ func TestAccSageMakerProject_basic(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectBasicConfig(rName), + Config: testAccProjectConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "project_name", rName), @@ -44,7 +44,7 @@ func TestAccSageMakerProject_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectBaseConfig(rName), + Config: testAccProjectConfig_base(rName), }, }, }) @@ -63,7 +63,7 @@ func TestAccSageMakerProject_description(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectDescription(rName, rName), + Config: testAccProjectConfig_description(rName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "project_name", rName), @@ -76,7 +76,7 @@ func TestAccSageMakerProject_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectDescription(rName, rNameUpdated), + Config: testAccProjectConfig_description(rName, rNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "project_name", rName), @@ -84,7 +84,7 @@ func TestAccSageMakerProject_description(t *testing.T) { ), }, { - Config: testAccProjectBaseConfig(rName), + Config: testAccProjectConfig_base(rName), }, }, }) @@ -102,7 +102,7 @@ func TestAccSageMakerProject_tags(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectTagsConfig1(rName, "key1", "value1"), + Config: testAccProjectConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -115,7 +115,7 @@ func TestAccSageMakerProject_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccProjectTagsConfig2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccProjectConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -124,7 +124,7 @@ func TestAccSageMakerProject_tags(t *testing.T) { ), }, { - Config: testAccProjectTagsConfig1(rName, "key2", "value2"), + Config: testAccProjectConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &mpg), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -132,7 +132,7 @@ func TestAccSageMakerProject_tags(t *testing.T) { ), }, { - Config: testAccProjectBaseConfig(rName), + Config: testAccProjectConfig_base(rName), }, }, }) @@ -150,7 +150,7 @@ func TestAccSageMakerProject_disappears(t *testing.T) { CheckDestroy: testAccCheckProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccProjectBasicConfig(rName), + Config: testAccProjectConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckProjectExists(resourceName, &mpg), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceProject(), resourceName), @@ -211,7 +211,7 @@ func testAccCheckProjectExists(n string, mpg *sagemaker.DescribeProjectOutput) r } } -func testAccProjectBaseConfig(rName string) string { +func testAccProjectConfig_base(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -355,8 +355,8 @@ resource "aws_servicecatalog_principal_portfolio_association" "test" { `, rName) } -func testAccProjectBasicConfig(rName string) string { - return acctest.ConfigCompose(testAccProjectBaseConfig(rName), fmt.Sprintf(` +func testAccProjectConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccProjectConfig_base(rName), fmt.Sprintf(` resource "aws_sagemaker_project" "test" { project_name = %[1]q @@ -367,8 +367,8 @@ resource "aws_sagemaker_project" "test" { `, rName)) } -func testAccProjectDescription(rName, desc string) string { - return acctest.ConfigCompose(testAccProjectBaseConfig(rName), fmt.Sprintf(` +func testAccProjectConfig_description(rName, desc string) string { + return acctest.ConfigCompose(testAccProjectConfig_base(rName), fmt.Sprintf(` resource "aws_sagemaker_project" "test" { project_name = %[1]q project_description = %[2]q @@ -380,8 +380,8 @@ resource "aws_sagemaker_project" "test" { `, rName, desc)) } -func testAccProjectTagsConfig1(rName, tagKey1, tagValue1 string) string { - return acctest.ConfigCompose(testAccProjectBaseConfig(rName), fmt.Sprintf(` +func testAccProjectConfig_tags1(rName, tagKey1, tagValue1 string) string { + return acctest.ConfigCompose(testAccProjectConfig_base(rName), fmt.Sprintf(` resource "aws_sagemaker_project" "test" { project_name = %[1]q @@ -396,8 +396,8 @@ resource "aws_sagemaker_project" "test" { `, rName, tagKey1, tagValue1)) } -func testAccProjectTagsConfig2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return acctest.ConfigCompose(testAccProjectBaseConfig(rName), fmt.Sprintf(` +func testAccProjectConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return acctest.ConfigCompose(testAccProjectConfig_base(rName), fmt.Sprintf(` resource "aws_sagemaker_project" "test" { project_name = %[1]q diff --git a/internal/service/sagemaker/sagemaker_test.go b/internal/service/sagemaker/sagemaker_test.go index 90548a7f9e1..442aab59f3d 100644 --- a/internal/service/sagemaker/sagemaker_test.go +++ b/internal/service/sagemaker/sagemaker_test.go @@ -45,6 +45,7 @@ func TestAccSageMaker_serial(t *testing.T) { "kms": testAccDomain_kms, "securityGroup": testAccDomain_securityGroup, "sharingSettings": testAccDomain_sharingSettings, + "defaultUserSettingsUpdated": testAccDomain_defaultUserSettingsUpdated, }, "FlowDefinition": { "basic": testAccFlowDefinition_basic, diff --git a/internal/service/sagemaker/status.go b/internal/service/sagemaker/status.go index b753c07d787..c8f24d13ea3 100644 --- a/internal/service/sagemaker/status.go +++ b/internal/service/sagemaker/status.go @@ -25,22 +25,18 @@ const ( // StatusNotebookInstance fetches the NotebookInstance and its Status func StatusNotebookInstance(conn *sagemaker.SageMaker, notebookName string) resource.StateRefreshFunc { return func() (interface{}, string, error) { - input := &sagemaker.DescribeNotebookInstanceInput{ - NotebookInstanceName: aws.String(notebookName), - } - - output, err := conn.DescribeNotebookInstance(input) + output, err := FindNotebookInstanceByName(conn, notebookName) - if tfawserr.ErrMessageContains(err, "ValidationException", "RecordNotFound") { - return nil, notebookInstanceStatusNotFound, nil + if tfresource.NotFound(err) { + return nil, "", nil } if err != nil { - return nil, sagemaker.NotebookInstanceStatusFailed, err + return nil, "", err } - if output == nil { - return nil, notebookInstanceStatusNotFound, nil + if aws.StringValue(output.NotebookInstanceStatus) == sagemaker.NotebookInstanceStatusFailed { + return output, sagemaker.NotebookInstanceStatusFailed, fmt.Errorf("%s", aws.StringValue(output.FailureReason)) } return output, aws.StringValue(output.NotebookInstanceStatus), nil diff --git a/internal/service/sagemaker/studio_lifecycle_config_test.go b/internal/service/sagemaker/studio_lifecycle_config_test.go index d6fe6cbc1b4..401208b7d8c 100644 --- a/internal/service/sagemaker/studio_lifecycle_config_test.go +++ b/internal/service/sagemaker/studio_lifecycle_config_test.go @@ -26,7 +26,7 @@ func TestAccSageMakerStudioLifecycleConfig_basic(t *testing.T) { CheckDestroy: testAccCheckStudioLifecycleDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccStudioLifecycleBasicConfig(rName), + Config: testAccStudioLifecycleConfigConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStudioLifecycleExistsConfig(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "studio_lifecycle_config_name", rName), @@ -57,7 +57,7 @@ func TestAccSageMakerStudioLifecycleConfig_tags(t *testing.T) { CheckDestroy: testAccCheckStudioLifecycleDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccStudioLifecycleTags1Config(rName, "key1", "value1"), + Config: testAccStudioLifecycleConfigConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckStudioLifecycleExistsConfig(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -70,7 +70,7 @@ func TestAccSageMakerStudioLifecycleConfig_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStudioLifecycleTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccStudioLifecycleConfigConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStudioLifecycleExistsConfig(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -79,7 +79,7 @@ func TestAccSageMakerStudioLifecycleConfig_tags(t *testing.T) { ), }, { - Config: testAccStudioLifecycleTags1Config(rName, "key2", "value2"), + Config: testAccStudioLifecycleConfigConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStudioLifecycleExistsConfig(resourceName, &config), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -102,7 +102,7 @@ func TestAccSageMakerStudioLifecycleConfig_disappears(t *testing.T) { CheckDestroy: testAccCheckStudioLifecycleDestroyConfig, Steps: []resource.TestStep{ { - Config: testAccStudioLifecycleBasicConfig(rName), + Config: testAccStudioLifecycleConfigConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStudioLifecycleExistsConfig(resourceName, &config), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceStudioLifecycleConfig(), resourceName), @@ -163,7 +163,7 @@ func testAccCheckStudioLifecycleExistsConfig(n string, config *sagemaker.Describ } } -func testAccStudioLifecycleBasicConfig(rName string) string { +func testAccStudioLifecycleConfigConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sagemaker_studio_lifecycle_config" "test" { studio_lifecycle_config_name = %[1]q @@ -173,7 +173,7 @@ resource "aws_sagemaker_studio_lifecycle_config" "test" { `, rName) } -func testAccStudioLifecycleTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccStudioLifecycleConfigConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_sagemaker_studio_lifecycle_config" "test" { studio_lifecycle_config_name = %[1]q @@ -187,7 +187,7 @@ resource "aws_sagemaker_studio_lifecycle_config" "test" { `, rName, tagKey1, tagValue1) } -func testAccStudioLifecycleTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccStudioLifecycleConfigConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_sagemaker_studio_lifecycle_config" "test" { studio_lifecycle_config_name = %[1]q diff --git a/internal/service/sagemaker/sweep.go b/internal/service/sagemaker/sweep.go index ceaa492ee62..32287e6340b 100644 --- a/internal/service/sagemaker/sweep.go +++ b/internal/service/sagemaker/sweep.go @@ -735,32 +735,19 @@ func sweepNotebookInstances(region string) error { return fmt.Errorf("error getting client: %s", err) } conn := client.(*conns.AWSClient).SageMakerConn + var sweeperErrs *multierror.Error err = conn.ListNotebookInstancesPages(&sagemaker.ListNotebookInstancesInput{}, func(page *sagemaker.ListNotebookInstancesOutput, lastPage bool) bool { for _, instance := range page.NotebookInstances { name := aws.StringValue(instance.NotebookInstanceName) - status := aws.StringValue(instance.NotebookInstanceStatus) - - input := &sagemaker.DeleteNotebookInstanceInput{ - NotebookInstanceName: instance.NotebookInstanceName, - } - - log.Printf("[INFO] Stopping SageMaker Notebook Instance: %s", name) - if status != sagemaker.NotebookInstanceStatusFailed && status != sagemaker.NotebookInstanceStatusStopped { - if err := StopNotebookInstance(conn, name); err != nil { - log.Printf("[ERROR] Error stopping SageMaker Notebook Instance (%s): %s", name, err) - continue - } - } - log.Printf("[INFO] Deleting SageMaker Notebook Instance: %s", name) - if _, err := conn.DeleteNotebookInstance(input); err != nil { - log.Printf("[ERROR] Error deleting SageMaker Notebook Instance (%s): %s", name, err) - continue - } - - if _, err := WaitNotebookInstanceDeleted(conn, name); err != nil { - log.Printf("error waiting for sagemaker notebook instance (%s) to delete: %s", name, err) + r := ResourceNotebookInstance() + d := r.Data(nil) + d.SetId(name) + err = r.Delete(d, client) + if err != nil { + log.Printf("[ERROR] %s", err) + sweeperErrs = multierror.Append(sweeperErrs, err) continue } } @@ -770,14 +757,14 @@ func sweepNotebookInstances(region string) error { if sweep.SkipSweepError(err) { log.Printf("[WARN] Skipping SageMaker Notebook Instance sweep for %s: %s", region, err) - return nil + return sweeperErrs.ErrorOrNil() } if err != nil { - return fmt.Errorf("Error retrieving SageMaker Notebook Instances: %s", err) + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving SageMaker Notbook Instances: %w", err)) } - return nil + return sweeperErrs.ErrorOrNil() } func sweepStudioLifecyclesConfig(region string) error { diff --git a/internal/service/sagemaker/user_profile_test.go b/internal/service/sagemaker/user_profile_test.go index a4510445c4c..3a7457c2487 100644 --- a/internal/service/sagemaker/user_profile_test.go +++ b/internal/service/sagemaker/user_profile_test.go @@ -29,7 +29,7 @@ func testAccUserProfile_basic(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileBasicConfig(rName), + Config: testAccUserProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "user_profile_name", rName), @@ -61,7 +61,7 @@ func testAccUserProfile_tags(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileTags1Config(rName, "key1", "value1"), + Config: testAccUserProfileConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -74,7 +74,7 @@ func testAccUserProfile_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccUserProfileTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccUserProfileConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -83,7 +83,7 @@ func testAccUserProfile_tags(t *testing.T) { ), }, { - Config: testAccUserProfileTags1Config(rName, "key2", "value2"), + Config: testAccUserProfileConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -106,7 +106,7 @@ func testAccUserProfile_tensorboardAppSettings(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileTensorBoardAppSettingsConfig(rName), + Config: testAccUserProfileConfig_tensorBoardAppSettings(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "user_settings.#", "1"), @@ -136,7 +136,7 @@ func testAccUserProfile_tensorboardAppSettingsWithImage(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileTensorBoardAppSettingsWithImageConfig(rName), + Config: testAccUserProfileConfig_tensorBoardAppSettingsImage(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "user_settings.#", "1"), @@ -167,7 +167,7 @@ func testAccUserProfile_kernelGatewayAppSettings(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileKernelGatewayAppSettingsConfig(rName), + Config: testAccUserProfileConfig_kernelGatewayAppSettings(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "user_settings.#", "1"), @@ -197,7 +197,7 @@ func testAccUserProfile_kernelGatewayAppSettings_lifecycleconfig(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileKernelGatewayAppSettingsLifecycleConfig(rName), + Config: testAccUserProfileConfig_kernelGatewayAppSettingsLifecycle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "user_settings.#", "1"), @@ -235,7 +235,7 @@ func testAccUserProfile_kernelGatewayAppSettings_imageconfig(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileKernelGatewayAppSettingsImageConfig(rName, baseImage), + Config: testAccUserProfileConfig_kernelGatewayAppSettingsImage(rName, baseImage), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "user_settings.#", "1"), @@ -267,7 +267,7 @@ func testAccUserProfile_jupyterServerAppSettings(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileJupyterServerAppSettingsConfig(rName), + Config: testAccUserProfileConfig_jupyterServerAppSettings(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "user_settings.#", "1"), @@ -297,7 +297,7 @@ func testAccUserProfile_disappears(t *testing.T) { CheckDestroy: testAccCheckUserProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccUserProfileBasicConfig(rName), + Config: testAccUserProfileConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUserProfileExists(resourceName, &domain), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceUserProfile(), resourceName), @@ -418,7 +418,7 @@ resource "aws_sagemaker_domain" "test" { `, rName) } -func testAccUserProfileBasicConfig(rName string) string { +func testAccUserProfileConfig_basic(rName string) string { return testAccUserProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_user_profile" "test" { domain_id = aws_sagemaker_domain.test.id @@ -427,7 +427,7 @@ resource "aws_sagemaker_user_profile" "test" { `, rName) } -func testAccUserProfileTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccUserProfileConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccUserProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_user_profile" "test" { domain_id = aws_sagemaker_domain.test.id @@ -440,7 +440,7 @@ resource "aws_sagemaker_user_profile" "test" { `, rName, tagKey1, tagValue1) } -func testAccUserProfileTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccUserProfileConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccUserProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_user_profile" "test" { domain_id = aws_sagemaker_domain.test.id @@ -454,7 +454,7 @@ resource "aws_sagemaker_user_profile" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccUserProfileTensorBoardAppSettingsConfig(rName string) string { +func testAccUserProfileConfig_tensorBoardAppSettings(rName string) string { return testAccUserProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_user_profile" "test" { domain_id = aws_sagemaker_domain.test.id @@ -473,7 +473,7 @@ resource "aws_sagemaker_user_profile" "test" { `, rName) } -func testAccUserProfileTensorBoardAppSettingsWithImageConfig(rName string) string { +func testAccUserProfileConfig_tensorBoardAppSettingsImage(rName string) string { return testAccUserProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_image" "test" { image_name = %[1]q @@ -498,7 +498,7 @@ resource "aws_sagemaker_user_profile" "test" { `, rName) } -func testAccUserProfileJupyterServerAppSettingsConfig(rName string) string { +func testAccUserProfileConfig_jupyterServerAppSettings(rName string) string { return testAccUserProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_user_profile" "test" { domain_id = aws_sagemaker_domain.test.id @@ -517,7 +517,7 @@ resource "aws_sagemaker_user_profile" "test" { `, rName) } -func testAccUserProfileKernelGatewayAppSettingsConfig(rName string) string { +func testAccUserProfileConfig_kernelGatewayAppSettings(rName string) string { return testAccUserProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_user_profile" "test" { domain_id = aws_sagemaker_domain.test.id @@ -536,7 +536,7 @@ resource "aws_sagemaker_user_profile" "test" { `, rName) } -func testAccUserProfileKernelGatewayAppSettingsLifecycleConfig(rName string) string { +func testAccUserProfileConfig_kernelGatewayAppSettingsLifecycle(rName string) string { return testAccUserProfileBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_studio_lifecycle_config" "test" { studio_lifecycle_config_name = %[1]q @@ -564,7 +564,7 @@ resource "aws_sagemaker_user_profile" "test" { `, rName) } -func testAccUserProfileKernelGatewayAppSettingsImageConfig(rName, baseImage string) string { +func testAccUserProfileConfig_kernelGatewayAppSettingsImage(rName, baseImage string) string { return testAccUserProfileBaseConfig(rName) + fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/sagemaker/workforce_test.go b/internal/service/sagemaker/workforce_test.go index 2066b28cace..c25094861b8 100644 --- a/internal/service/sagemaker/workforce_test.go +++ b/internal/service/sagemaker/workforce_test.go @@ -27,7 +27,7 @@ func testAccWorkforce_cognitoConfig(t *testing.T) { CheckDestroy: testAccCheckWorkforceDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkforceCognitoConfig(rName), + Config: testAccWorkforceConfig_cognito(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkforceExists(resourceName, &workforce), resource.TestCheckResourceAttr(resourceName, "workforce_name", rName), @@ -64,7 +64,7 @@ func testAccWorkforce_oidcConfig(t *testing.T) { CheckDestroy: testAccCheckWorkforceDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkforceOIDCConfig(rName, endpoint1), + Config: testAccWorkforceConfig_oidc(rName, endpoint1), Check: resource.ComposeTestCheckFunc( testAccCheckWorkforceExists(resourceName, &workforce), resource.TestCheckResourceAttr(resourceName, "workforce_name", rName), @@ -91,7 +91,7 @@ func testAccWorkforce_oidcConfig(t *testing.T) { ImportStateVerifyIgnore: []string{"oidc_config.0.client_secret"}, }, { - Config: testAccWorkforceOIDCConfig(rName, endpoint2), + Config: testAccWorkforceConfig_oidc(rName, endpoint2), Check: resource.ComposeTestCheckFunc( testAccCheckWorkforceExists(resourceName, &workforce), resource.TestCheckResourceAttr(resourceName, "workforce_name", rName), @@ -126,7 +126,7 @@ func testAccWorkforce_sourceIPConfig(t *testing.T) { CheckDestroy: testAccCheckWorkforceDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkforceSourceIP1Config(rName, "1.1.1.1/32"), + Config: testAccWorkforceConfig_sourceIP1(rName, "1.1.1.1/32"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkforceExists(resourceName, &workforce), resource.TestCheckResourceAttr(resourceName, "source_ip_config.#", "1"), @@ -140,7 +140,7 @@ func testAccWorkforce_sourceIPConfig(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccWorkforceSourceIP2Config(rName, "2.2.2.2/32", "3.3.3.3/32"), + Config: testAccWorkforceConfig_sourceIP2(rName, "2.2.2.2/32", "3.3.3.3/32"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkforceExists(resourceName, &workforce), resource.TestCheckResourceAttr(resourceName, "source_ip_config.#", "1"), @@ -149,7 +149,7 @@ func testAccWorkforce_sourceIPConfig(t *testing.T) { ), }, { - Config: testAccWorkforceSourceIP1Config(rName, "2.2.2.2/32"), + Config: testAccWorkforceConfig_sourceIP1(rName, "2.2.2.2/32"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkforceExists(resourceName, &workforce), resource.TestCheckResourceAttr(resourceName, "source_ip_config.#", "1"), @@ -173,7 +173,7 @@ func testAccWorkforce_disappears(t *testing.T) { CheckDestroy: testAccCheckWorkforceDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkforceCognitoConfig(rName), + Config: testAccWorkforceConfig_cognito(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkforceExists(resourceName, &workforce), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceWorkforce(), resourceName), @@ -252,7 +252,7 @@ resource "aws_cognito_user_pool_domain" "test" { `, rName) } -func testAccWorkforceCognitoConfig(rName string) string { +func testAccWorkforceConfig_cognito(rName string) string { return testAccWorkforceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_workforce" "test" { workforce_name = %[1]q @@ -265,7 +265,7 @@ resource "aws_sagemaker_workforce" "test" { `, rName) } -func testAccWorkforceSourceIP1Config(rName, cidr1 string) string { +func testAccWorkforceConfig_sourceIP1(rName, cidr1 string) string { return testAccWorkforceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_workforce" "test" { workforce_name = %[1]q @@ -282,7 +282,7 @@ resource "aws_sagemaker_workforce" "test" { `, rName, cidr1) } -func testAccWorkforceSourceIP2Config(rName, cidr1, cidr2 string) string { +func testAccWorkforceConfig_sourceIP2(rName, cidr1, cidr2 string) string { return testAccWorkforceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_workforce" "test" { workforce_name = %[1]q @@ -299,7 +299,7 @@ resource "aws_sagemaker_workforce" "test" { `, rName, cidr1, cidr2) } -func testAccWorkforceOIDCConfig(rName, endpoint string) string { +func testAccWorkforceConfig_oidc(rName, endpoint string) string { return testAccWorkforceBaseConfig(rName) + fmt.Sprintf(` resource "aws_sagemaker_workforce" "test" { workforce_name = %[1]q diff --git a/internal/service/sagemaker/workteam_test.go b/internal/service/sagemaker/workteam_test.go index 7396ea19a8d..7be2a5b0784 100644 --- a/internal/service/sagemaker/workteam_test.go +++ b/internal/service/sagemaker/workteam_test.go @@ -27,7 +27,7 @@ func testAccWorkteam_cognitoConfig(t *testing.T) { CheckDestroy: testAccCheckWorkteamDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkteamCognitoConfig(rName), + Config: testAccWorkteamConfig_cognito(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "workteam_name", rName), @@ -49,7 +49,7 @@ func testAccWorkteam_cognitoConfig(t *testing.T) { ImportStateVerifyIgnore: []string{"workforce_name"}, }, { - Config: testAccWorkteamCognitoUpdatedConfig(rName), + Config: testAccWorkteamConfig_cognitoUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "workteam_name", rName), @@ -68,7 +68,7 @@ func testAccWorkteam_cognitoConfig(t *testing.T) { ), }, { - Config: testAccWorkteamCognitoConfig(rName), + Config: testAccWorkteamConfig_cognito(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "workteam_name", rName), @@ -98,7 +98,7 @@ func testAccWorkteam_oidcConfig(t *testing.T) { CheckDestroy: testAccCheckWorkteamDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkteamOIDCConfig(rName), + Config: testAccWorkteamConfig_oidc(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "workteam_name", rName), @@ -116,7 +116,7 @@ func testAccWorkteam_oidcConfig(t *testing.T) { ImportStateVerifyIgnore: []string{"workforce_name"}, }, { - Config: testAccWorkteamOIDC2Config(rName, "test"), + Config: testAccWorkteamConfig_oidc2(rName, "test"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "workteam_name", rName), @@ -129,7 +129,7 @@ func testAccWorkteam_oidcConfig(t *testing.T) { ), }, { - Config: testAccWorkteamOIDCConfig(rName), + Config: testAccWorkteamConfig_oidc(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "workteam_name", rName), @@ -155,7 +155,7 @@ func testAccWorkteam_tags(t *testing.T) { CheckDestroy: testAccCheckWorkteamDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkteamTags1Config(rName, "key1", "value1"), + Config: testAccWorkteamConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -169,7 +169,7 @@ func testAccWorkteam_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"workforce_name"}, }, { - Config: testAccWorkteamTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccWorkteamConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -178,7 +178,7 @@ func testAccWorkteam_tags(t *testing.T) { ), }, { - Config: testAccWorkteamTags1Config(rName, "key2", "value2"), + Config: testAccWorkteamConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -201,7 +201,7 @@ func testAccWorkteam_notificationConfig(t *testing.T) { CheckDestroy: testAccCheckWorkteamDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkteamNotificationConfig(rName), + Config: testAccWorkteamConfig_notification(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "workteam_name", rName), @@ -218,7 +218,7 @@ func testAccWorkteam_notificationConfig(t *testing.T) { ImportStateVerifyIgnore: []string{"workforce_name"}, }, { - Config: testAccWorkteamOIDCConfig(rName), + Config: testAccWorkteamConfig_oidc(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "workteam_name", rName), @@ -228,7 +228,7 @@ func testAccWorkteam_notificationConfig(t *testing.T) { ), }, { - Config: testAccWorkteamNotificationConfig(rName), + Config: testAccWorkteamConfig_notification(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), resource.TestCheckResourceAttr(resourceName, "workteam_name", rName), @@ -254,7 +254,7 @@ func testAccWorkteam_disappears(t *testing.T) { CheckDestroy: testAccCheckWorkteamDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkteamOIDCConfig(rName), + Config: testAccWorkteamConfig_oidc(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkteamExists(resourceName, &workteam), acctest.CheckResourceDisappears(acctest.Provider, tfsagemaker.ResourceWorkteam(), resourceName), @@ -347,7 +347,7 @@ resource "aws_sagemaker_workforce" "test" { `, rName) } -func testAccWorkteamCognitoConfig(rName string) string { +func testAccWorkteamConfig_cognito(rName string) string { return acctest.ConfigCompose(testAccWorkteamCognitoBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_workteam" "test" { workteam_name = %[1]q @@ -365,7 +365,7 @@ resource "aws_sagemaker_workteam" "test" { `, rName)) } -func testAccWorkteamCognitoUpdatedConfig(rName string) string { +func testAccWorkteamConfig_cognitoUpdated(rName string) string { return acctest.ConfigCompose(testAccWorkteamCognitoBaseConfig(rName), fmt.Sprintf(` resource "aws_cognito_user_group" "test2" { name = "%[1]s-2" @@ -415,7 +415,7 @@ resource "aws_sagemaker_workforce" "test" { `, rName) } -func testAccWorkteamOIDCConfig(rName string) string { +func testAccWorkteamConfig_oidc(rName string) string { return acctest.ConfigCompose(testAccWorkteamOIDCBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_workteam" "test" { workteam_name = %[1]q @@ -431,7 +431,7 @@ resource "aws_sagemaker_workteam" "test" { `, rName)) } -func testAccWorkteamOIDC2Config(rName, group string) string { +func testAccWorkteamConfig_oidc2(rName, group string) string { return acctest.ConfigCompose(testAccWorkteamOIDCBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_workteam" "test" { workteam_name = %[1]q @@ -447,7 +447,7 @@ resource "aws_sagemaker_workteam" "test" { `, rName, group)) } -func testAccWorkteamNotificationConfig(rName string) string { +func testAccWorkteamConfig_notification(rName string) string { return acctest.ConfigCompose(testAccWorkteamOIDCBaseConfig(rName), fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -493,7 +493,7 @@ resource "aws_sagemaker_workteam" "test" { `, rName)) } -func testAccWorkteamTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccWorkteamConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccWorkteamOIDCBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_workteam" "test" { workteam_name = %[1]q @@ -513,7 +513,7 @@ resource "aws_sagemaker_workteam" "test" { `, rName, tagKey1, tagValue1)) } -func testAccWorkteamTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccWorkteamConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccWorkteamOIDCBaseConfig(rName), fmt.Sprintf(` resource "aws_sagemaker_workteam" "test" { workteam_name = %[1]q diff --git a/internal/service/schemas/discoverer_test.go b/internal/service/schemas/discoverer_test.go index df8d264c1bc..dd6fa4bbdcb 100644 --- a/internal/service/schemas/discoverer_test.go +++ b/internal/service/schemas/discoverer_test.go @@ -26,7 +26,7 @@ func TestAccSchemasDiscoverer_basic(t *testing.T) { CheckDestroy: testAccCheckDiscovererDestroy, Steps: []resource.TestStep{ { - Config: testAccDiscovererConfig(rName), + Config: testAccDiscovererConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDiscovererExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "schemas", fmt.Sprintf("discoverer/events-event-bus-%s", rName)), @@ -55,7 +55,7 @@ func TestAccSchemasDiscoverer_disappears(t *testing.T) { CheckDestroy: testAccCheckDiscovererDestroy, Steps: []resource.TestStep{ { - Config: testAccDiscovererConfig(rName), + Config: testAccDiscovererConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDiscovererExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfschemas.ResourceDiscoverer(), resourceName), @@ -78,7 +78,7 @@ func TestAccSchemasDiscoverer_description(t *testing.T) { CheckDestroy: testAccCheckDiscovererDestroy, Steps: []resource.TestStep{ { - Config: testAccDiscovererDescriptionConfig(rName, "description1"), + Config: testAccDiscovererConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckDiscovererExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -90,14 +90,14 @@ func TestAccSchemasDiscoverer_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDiscovererDescriptionConfig(rName, "description2"), + Config: testAccDiscovererConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckDiscovererExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", "description2"), ), }, { - Config: testAccDiscovererConfig(rName), + Config: testAccDiscovererConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDiscovererExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -119,7 +119,7 @@ func TestAccSchemasDiscoverer_tags(t *testing.T) { CheckDestroy: testAccCheckDiscovererDestroy, Steps: []resource.TestStep{ { - Config: testAccDiscovererTags1Config(rName, "key1", "value1"), + Config: testAccDiscovererConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDiscovererExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -132,7 +132,7 @@ func TestAccSchemasDiscoverer_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDiscovererTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDiscovererConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDiscovererExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -141,7 +141,7 @@ func TestAccSchemasDiscoverer_tags(t *testing.T) { ), }, { - Config: testAccDiscovererTags1Config(rName, "key2", "value2"), + Config: testAccDiscovererConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDiscovererExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -201,7 +201,7 @@ func testAccCheckDiscovererExists(n string, v *schemas.DescribeDiscovererOutput) } } -func testAccDiscovererConfig(rName string) string { +func testAccDiscovererConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q @@ -213,7 +213,7 @@ resource "aws_schemas_discoverer" "test" { `, rName) } -func testAccDiscovererDescriptionConfig(rName, description string) string { +func testAccDiscovererConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q @@ -227,7 +227,7 @@ resource "aws_schemas_discoverer" "test" { `, rName, description) } -func testAccDiscovererTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccDiscovererConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q @@ -243,7 +243,7 @@ resource "aws_schemas_discoverer" "test" { `, rName, tagKey1, tagValue1) } -func testAccDiscovererTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDiscovererConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_cloudwatch_event_bus" "test" { name = %[1]q diff --git a/internal/service/schemas/registry_test.go b/internal/service/schemas/registry_test.go index d454dc190c4..b9380485db3 100644 --- a/internal/service/schemas/registry_test.go +++ b/internal/service/schemas/registry_test.go @@ -26,7 +26,7 @@ func TestAccSchemasRegistry_basic(t *testing.T) { CheckDestroy: testAccCheckRegistryDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryConfig(rName), + Config: testAccRegistryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "schemas", fmt.Sprintf("registry/%s", rName)), @@ -56,7 +56,7 @@ func TestAccSchemasRegistry_disappears(t *testing.T) { CheckDestroy: testAccCheckRegistryDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryConfig(rName), + Config: testAccRegistryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfschemas.ResourceRegistry(), resourceName), @@ -79,7 +79,7 @@ func TestAccSchemasRegistry_description(t *testing.T) { CheckDestroy: testAccCheckRegistryDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryDescriptionConfig(rName, "description1"), + Config: testAccRegistryConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -91,14 +91,14 @@ func TestAccSchemasRegistry_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRegistryDescriptionConfig(rName, "description2"), + Config: testAccRegistryConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", "description2"), ), }, { - Config: testAccRegistryConfig(rName), + Config: testAccRegistryConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -120,7 +120,7 @@ func TestAccSchemasRegistry_tags(t *testing.T) { CheckDestroy: testAccCheckRegistryDestroy, Steps: []resource.TestStep{ { - Config: testAccRegistryTags1Config(rName, "key1", "value1"), + Config: testAccRegistryConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -133,7 +133,7 @@ func TestAccSchemasRegistry_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccRegistryTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccRegistryConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -142,7 +142,7 @@ func TestAccSchemasRegistry_tags(t *testing.T) { ), }, { - Config: testAccRegistryTags1Config(rName, "key2", "value2"), + Config: testAccRegistryConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckRegistryExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -202,7 +202,7 @@ func testAccCheckRegistryExists(n string, v *schemas.DescribeRegistryOutput) res } } -func testAccRegistryConfig(rName string) string { +func testAccRegistryConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_schemas_registry" "test" { name = %[1]q @@ -210,7 +210,7 @@ resource "aws_schemas_registry" "test" { `, rName) } -func testAccRegistryDescriptionConfig(rName, description string) string { +func testAccRegistryConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_schemas_registry" "test" { name = %[1]q @@ -219,7 +219,7 @@ resource "aws_schemas_registry" "test" { `, rName, description) } -func testAccRegistryTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccRegistryConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_schemas_registry" "test" { name = %[1]q @@ -231,7 +231,7 @@ resource "aws_schemas_registry" "test" { `, rName, tagKey1, tagValue1) } -func testAccRegistryTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccRegistryConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_schemas_registry" "test" { name = %[1]q diff --git a/internal/service/schemas/schema_test.go b/internal/service/schemas/schema_test.go index 29dfa1734e5..59cb58b0d9e 100644 --- a/internal/service/schemas/schema_test.go +++ b/internal/service/schemas/schema_test.go @@ -78,7 +78,7 @@ func TestAccSchemasSchema_basic(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaConfig(rName), + Config: testAccSchemaConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &v), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "schemas", fmt.Sprintf("schema/%s/%s", rName, rName)), @@ -114,7 +114,7 @@ func TestAccSchemasSchema_disappears(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaConfig(rName), + Config: testAccSchemaConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &v), acctest.CheckResourceDisappears(acctest.Provider, tfschemas.ResourceSchema(), resourceName), @@ -137,7 +137,7 @@ func TestAccSchemasSchema_contentDescription(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaContentDescriptionConfig(rName, testAccSchemaContent, "description1"), + Config: testAccSchemaConfig_contentDescription(rName, testAccSchemaContent, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "content", testAccSchemaContent), @@ -151,7 +151,7 @@ func TestAccSchemasSchema_contentDescription(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSchemaContentDescriptionConfig(rName, testAccSchemaContentUpdated, "description2"), + Config: testAccSchemaConfig_contentDescription(rName, testAccSchemaContentUpdated, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "content", testAccSchemaContentUpdated), @@ -160,7 +160,7 @@ func TestAccSchemasSchema_contentDescription(t *testing.T) { ), }, { - Config: testAccSchemaConfig(rName), + Config: testAccSchemaConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -183,7 +183,7 @@ func TestAccSchemasSchema_tags(t *testing.T) { CheckDestroy: testAccCheckSchemaDestroy, Steps: []resource.TestStep{ { - Config: testAccSchemaTags1Config(rName, "key1", "value1"), + Config: testAccSchemaConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -196,7 +196,7 @@ func TestAccSchemasSchema_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSchemaTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccSchemaConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -205,7 +205,7 @@ func TestAccSchemasSchema_tags(t *testing.T) { ), }, { - Config: testAccSchemaTags1Config(rName, "key2", "value2"), + Config: testAccSchemaConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSchemaExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -277,7 +277,7 @@ func testAccCheckSchemaExists(n string, v *schemas.DescribeSchemaOutput) resourc } } -func testAccSchemaConfig(rName string) string { +func testAccSchemaConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_schemas_registry" "test" { name = %[1]q @@ -292,7 +292,7 @@ resource "aws_schemas_schema" "test" { `, rName, testAccSchemaContent) } -func testAccSchemaContentDescriptionConfig(rName, content, description string) string { +func testAccSchemaConfig_contentDescription(rName, content, description string) string { return fmt.Sprintf(` resource "aws_schemas_registry" "test" { name = %[1]q @@ -308,7 +308,7 @@ resource "aws_schemas_schema" "test" { `, rName, content, description) } -func testAccSchemaTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccSchemaConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_schemas_registry" "test" { name = %[1]q @@ -327,7 +327,7 @@ resource "aws_schemas_schema" "test" { `, rName, testAccSchemaContent, tagKey1, tagValue1) } -func testAccSchemaTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSchemaConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_schemas_registry" "test" { name = %[1]q diff --git a/internal/service/secretsmanager/secret_data_source_test.go b/internal/service/secretsmanager/secret_data_source_test.go index fedcc95befb..8392c1292c7 100644 --- a/internal/service/secretsmanager/secret_data_source_test.go +++ b/internal/service/secretsmanager/secret_data_source_test.go @@ -19,15 +19,15 @@ func TestAccSecretsManagerSecretDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecretDataSourceConfig_MissingRequired, + Config: testAccSecretDataSourceConfig_missingRequired, ExpectError: regexp.MustCompile(`must specify either arn or name`), }, { - Config: testAccSecretDataSourceConfig_MultipleSpecified, + Config: testAccSecretDataSourceConfig_multipleSpecified, ExpectError: regexp.MustCompile(`specify only arn or name`), }, { - Config: testAccSecretDataSourceConfig_NonExistent, + Config: testAccSecretDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`not found`), }, }, @@ -45,7 +45,7 @@ func TestAccSecretsManagerSecretDataSource_arn(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecretDataSourceConfig_ARN(rName), + Config: testAccSecretDataSourceConfig_arn(rName), Check: resource.ComposeTestCheckFunc( testAccSecretCheckDataSource(datasourceName, resourceName), ), @@ -65,7 +65,7 @@ func TestAccSecretsManagerSecretDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecretDataSourceConfig_Name(rName), + Config: testAccSecretDataSourceConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccSecretCheckDataSource(datasourceName, resourceName), ), @@ -85,7 +85,7 @@ func TestAccSecretsManagerSecretDataSource_policy(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecretDataSourceConfig_Policy(rName), + Config: testAccSecretDataSourceConfig_policy(rName), Check: resource.ComposeTestCheckFunc( testAccSecretCheckDataSource(datasourceName, resourceName), ), @@ -133,7 +133,7 @@ func testAccSecretCheckDataSource(datasourceName, resourceName string) resource. } } -func testAccSecretDataSourceConfig_ARN(rName string) string { +func testAccSecretDataSourceConfig_arn(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "wrong" { name = "%[1]s-wrong" @@ -149,19 +149,19 @@ data "aws_secretsmanager_secret" "test" { `, rName) } -const testAccSecretDataSourceConfig_MissingRequired = ` +const testAccSecretDataSourceConfig_missingRequired = ` data "aws_secretsmanager_secret" "test" {} ` //lintignore:AWSAT003,AWSAT005 -const testAccSecretDataSourceConfig_MultipleSpecified = ` +const testAccSecretDataSourceConfig_multipleSpecified = ` data "aws_secretsmanager_secret" "test" { arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:tf-acc-test-does-not-exist" name = "tf-acc-test-does-not-exist" } ` -func testAccSecretDataSourceConfig_Name(rName string) string { +func testAccSecretDataSourceConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "wrong" { name = "%[1]s-wrong" @@ -177,7 +177,7 @@ data "aws_secretsmanager_secret" "test" { `, rName) } -func testAccSecretDataSourceConfig_Policy(rName string) string { +func testAccSecretDataSourceConfig_policy(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%[1]s" @@ -206,7 +206,7 @@ data "aws_secretsmanager_secret" "test" { `, rName) } -const testAccSecretDataSourceConfig_NonExistent = ` +const testAccSecretDataSourceConfig_nonExistent = ` data "aws_secretsmanager_secret" "test" { name = "tf-acc-test-does-not-exist" } diff --git a/internal/service/secretsmanager/secret_policy_test.go b/internal/service/secretsmanager/secret_policy_test.go index 9119ef86927..49cb6586abe 100644 --- a/internal/service/secretsmanager/secret_policy_test.go +++ b/internal/service/secretsmanager/secret_policy_test.go @@ -29,7 +29,7 @@ func TestAccSecretsManagerSecretPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckSecretPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretPolicyBasicConfig(rName), + Config: testAccSecretPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretPolicyExists(resourceName, &policy), resource.TestMatchResourceAttr(resourceName, "policy", @@ -43,7 +43,7 @@ func TestAccSecretsManagerSecretPolicy_basic(t *testing.T) { ImportStateVerifyIgnore: []string{"block_public_policy"}, }, { - Config: testAccSecretPolicyUpdatedConfig(rName), + Config: testAccSecretPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretPolicyExists(resourceName, &policy), resource.TestMatchResourceAttr(resourceName, "policy", @@ -66,7 +66,7 @@ func TestAccSecretsManagerSecretPolicy_blockPublicPolicy(t *testing.T) { CheckDestroy: testAccCheckSecretPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretPolicyBlockConfig(rName, true), + Config: testAccSecretPolicyConfig_block(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSecretPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "block_public_policy", "true"), @@ -79,14 +79,14 @@ func TestAccSecretsManagerSecretPolicy_blockPublicPolicy(t *testing.T) { ImportStateVerifyIgnore: []string{"block_public_policy"}, }, { - Config: testAccSecretPolicyBlockConfig(rName, false), + Config: testAccSecretPolicyConfig_block(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSecretPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "block_public_policy", "false"), ), }, { - Config: testAccSecretPolicyBlockConfig(rName, true), + Config: testAccSecretPolicyConfig_block(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSecretPolicyExists(resourceName, &policy), resource.TestCheckResourceAttr(resourceName, "block_public_policy", "true"), @@ -108,7 +108,7 @@ func TestAccSecretsManagerSecretPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckSecretPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretPolicyBasicConfig(rName), + Config: testAccSecretPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretPolicyExists(resourceName, &policy), acctest.CheckResourceDisappears(acctest.Provider, tfsecretsmanager.ResourceSecretPolicy(), resourceName), @@ -213,7 +213,7 @@ func testAccCheckSecretPolicyExists(resourceName string, policy *secretsmanager. } } -func testAccSecretPolicyBasicConfig(rName string) string { +func testAccSecretPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -261,7 +261,7 @@ POLICY `, rName) } -func testAccSecretPolicyUpdatedConfig(rName string) string { +func testAccSecretPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = %[1]q @@ -290,7 +290,7 @@ POLICY `, rName) } -func testAccSecretPolicyBlockConfig(rName string, block bool) string { +func testAccSecretPolicyConfig_block(rName string, block bool) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q diff --git a/internal/service/secretsmanager/secret_rotation_data_source_test.go b/internal/service/secretsmanager/secret_rotation_data_source_test.go index e91953311e7..371ce7a0ee1 100644 --- a/internal/service/secretsmanager/secret_rotation_data_source_test.go +++ b/internal/service/secretsmanager/secret_rotation_data_source_test.go @@ -22,11 +22,11 @@ func TestAccSecretsManagerSecretRotationDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecretRotationDataSourceConfig_NonExistent, + Config: testAccSecretRotationDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`ResourceNotFoundException`), }, { - Config: testAccSecretRotationDataSourceConfig_Default(rName, 7), + Config: testAccSecretRotationDataSourceConfig_default(rName, 7), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "rotation_enabled", resourceName, "rotation_enabled"), resource.TestCheckResourceAttrPair(datasourceName, "rotation_lambda_arn", resourceName, "rotation_lambda_arn"), @@ -37,13 +37,13 @@ func TestAccSecretsManagerSecretRotationDataSource_basic(t *testing.T) { }) } -const testAccSecretRotationDataSourceConfig_NonExistent = ` +const testAccSecretRotationDataSourceConfig_nonExistent = ` data "aws_secretsmanager_secret_rotation" "test" { secret_id = "tf-acc-test-does-not-exist" } ` -func testAccSecretRotationDataSourceConfig_Default(rName string, automaticallyAfterDays int) string { +func testAccSecretRotationDataSourceConfig_default(rName string, automaticallyAfterDays int) string { return acctest.ConfigLambdaBase(rName, rName, rName) + fmt.Sprintf(` # Not a real rotation function resource "aws_lambda_function" "test" { diff --git a/internal/service/secretsmanager/secret_rotation_test.go b/internal/service/secretsmanager/secret_rotation_test.go index 5c6fa70f849..f0a02be67be 100644 --- a/internal/service/secretsmanager/secret_rotation_test.go +++ b/internal/service/secretsmanager/secret_rotation_test.go @@ -28,7 +28,7 @@ func TestAccSecretsManagerSecretRotation_basic(t *testing.T) { Steps: []resource.TestStep{ // Test creating secret rotation resource { - Config: testAccSecretRotationConfig(rName, 7), + Config: testAccSecretRotationConfig_basic(rName, 7), Check: resource.ComposeTestCheckFunc( testAccCheckSecretRotationExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), @@ -42,7 +42,7 @@ func TestAccSecretsManagerSecretRotation_basic(t *testing.T) { // InvalidRequestException: A previous rotation isn’t complete. That rotation will be reattempted. /* { - Config: testAccSecretsManagerSecretConfig_Updated(rName), + Config: testAccSecretRotationConfig_managerUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretRotationExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), @@ -121,7 +121,7 @@ func testAccCheckSecretRotationExists(resourceName string, secret *secretsmanage } } -func testAccSecretRotationConfig(rName string, automaticallyAfterDays int) string { +func testAccSecretRotationConfig_basic(rName string, automaticallyAfterDays int) string { return acctest.ConfigLambdaBase(rName, rName, rName) + fmt.Sprintf(` # Not a real rotation function resource "aws_lambda_function" "test1" { diff --git a/internal/service/secretsmanager/secret_test.go b/internal/service/secretsmanager/secret_test.go index 99399096f10..59a136a0036 100644 --- a/internal/service/secretsmanager/secret_test.go +++ b/internal/service/secretsmanager/secret_test.go @@ -29,7 +29,7 @@ func TestAccSecretsManagerSecret_basic(t *testing.T) { CheckDestroy: testAccCheckSecretDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretConfig_Name(rName), + Config: testAccSecretConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "secretsmanager", regexp.MustCompile(fmt.Sprintf("secret:%s-[[:alnum:]]+$", rName))), @@ -66,7 +66,7 @@ func TestAccSecretsManagerSecret_withNamePrefix(t *testing.T) { CheckDestroy: testAccCheckSecretDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretConfig_withNamePrefix("tf-acc-test-prefix-"), + Config: testAccSecretConfig_namePrefix("tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), @@ -95,14 +95,14 @@ func TestAccSecretsManagerSecret_description(t *testing.T) { CheckDestroy: testAccCheckSecretDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretConfig_Description(rName, "description1"), + Config: testAccSecretConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "description", "description1"), ), }, { - Config: testAccSecretConfig_Description(rName, "description2"), + Config: testAccSecretConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -191,14 +191,14 @@ func TestAccSecretsManagerSecret_kmsKeyID(t *testing.T) { CheckDestroy: testAccCheckSecretDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretConfig_KMSKeyID(rName), + Config: testAccSecretConfig_kmsKeyID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttrSet(resourceName, "kms_key_id"), ), }, { - Config: testAccSecretConfig_KMSKeyID_Updated(rName), + Config: testAccSecretConfig_kmsKeyIDUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttrSet(resourceName, "kms_key_id"), @@ -226,14 +226,14 @@ func TestAccSecretsManagerSecret_RecoveryWindowInDays_recreate(t *testing.T) { CheckDestroy: testAccCheckSecretDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretConfig_RecoveryWindowInDays(rName, 0), + Config: testAccSecretConfig_recoveryWindowInDays(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "recovery_window_in_days", "0"), ), }, { - Config: testAccSecretConfig_RecoveryWindowInDays(rName, 0), + Config: testAccSecretConfig_recoveryWindowInDays(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "recovery_window_in_days", "0"), @@ -264,7 +264,7 @@ func TestAccSecretsManagerSecret_rotationLambdaARN(t *testing.T) { Steps: []resource.TestStep{ // Test enabling rotation on resource creation { - Config: testAccSecretConfig_RotationLambdaARN(rName), + Config: testAccSecretConfig_rotationLambdaARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), @@ -276,7 +276,7 @@ func TestAccSecretsManagerSecret_rotationLambdaARN(t *testing.T) { // InvalidRequestException: A previous rotation isn’t complete. That rotation will be reattempted. /* { - Config: testAccSecretsManagerSecretConfig_RotationLambdaARN_Updated(rName), + Config: testAccSecretConfig_managerRotationLambdaARNUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), @@ -293,7 +293,7 @@ func TestAccSecretsManagerSecret_rotationLambdaARN(t *testing.T) { }, // Test removing rotation on resource update { - Config: testAccSecretConfig_Name(rName), + Config: testAccSecretConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), // Must be removed with aws_secretsmanager_secret_rotation after version 2.67.0 @@ -316,7 +316,7 @@ func TestAccSecretsManagerSecret_rotationRules(t *testing.T) { Steps: []resource.TestStep{ // Test creating rotation rules on resource creation { - Config: testAccSecretConfig_RotationRules(rName, 7), + Config: testAccSecretConfig_rotationRules(rName, 7), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), @@ -329,7 +329,7 @@ func TestAccSecretsManagerSecret_rotationRules(t *testing.T) { // InvalidRequestException: A previous rotation isn’t complete. That rotation will be reattempted. /* { - Config: testAccSecretConfig_RotationRules(rName, 1), + Config: testAccSecretConfig_rotationRules(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), @@ -347,7 +347,7 @@ func TestAccSecretsManagerSecret_rotationRules(t *testing.T) { }, // Test removing rotation rules on resource update { - Config: testAccSecretConfig_Name(rName), + Config: testAccSecretConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), // Must be removed with aws_secretsmanager_secret_rotation after version 2.67.0 @@ -369,7 +369,7 @@ func TestAccSecretsManagerSecret_tags(t *testing.T) { CheckDestroy: testAccCheckSecretDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretConfig_Tags_Single(rName), + Config: testAccSecretConfig_tagsSingle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -377,7 +377,7 @@ func TestAccSecretsManagerSecret_tags(t *testing.T) { ), }, { - Config: testAccSecretConfig_Tags_SingleUpdated(rName), + Config: testAccSecretConfig_tagsSingleUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -385,7 +385,7 @@ func TestAccSecretsManagerSecret_tags(t *testing.T) { ), }, { - Config: testAccSecretConfig_Tags_Multiple(rName), + Config: testAccSecretConfig_tagsMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -394,7 +394,7 @@ func TestAccSecretsManagerSecret_tags(t *testing.T) { ), }, { - Config: testAccSecretConfig_Tags_Single(rName), + Config: testAccSecretConfig_tagsSingle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -423,7 +423,7 @@ func TestAccSecretsManagerSecret_policy(t *testing.T) { CheckDestroy: testAccCheckSecretDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretPolicyConfig(rName), + Config: testAccSecretConfig_policy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "description", "San Holo feat. Duskus"), @@ -432,7 +432,7 @@ func TestAccSecretsManagerSecret_policy(t *testing.T) { ), }, { - Config: testAccSecretPolicyEmptyConfig(rName), + Config: testAccSecretConfig_policyEmpty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestCheckResourceAttr(resourceName, "description", "Poliça"), @@ -440,7 +440,7 @@ func TestAccSecretsManagerSecret_policy(t *testing.T) { ), }, { - Config: testAccSecretPolicyConfig(rName), + Config: testAccSecretConfig_policy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretExists(resourceName, &secret), resource.TestMatchResourceAttr(resourceName, "policy", @@ -517,7 +517,7 @@ func testAccPreCheck(t *testing.T) { } } -func testAccSecretConfig_Description(rName, description string) string { +func testAccSecretConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { description = "%s" @@ -604,7 +604,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName, force_overwrite_replica_secret)) } -func testAccSecretConfig_Name(rName string) string { +func testAccSecretConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%s" @@ -612,7 +612,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName) } -func testAccSecretConfig_withNamePrefix(rName string) string { +func testAccSecretConfig_namePrefix(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name_prefix = %[1]q @@ -620,7 +620,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName) } -func testAccSecretConfig_KMSKeyID(rName string) string { +func testAccSecretConfig_kmsKeyID(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test1" { deletion_window_in_days = 7 @@ -637,7 +637,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName) } -func testAccSecretConfig_KMSKeyID_Updated(rName string) string { +func testAccSecretConfig_kmsKeyIDUpdated(rName string) string { return fmt.Sprintf(` resource "aws_kms_key" "test1" { deletion_window_in_days = 7 @@ -654,7 +654,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName) } -func testAccSecretConfig_RecoveryWindowInDays(rName string, recoveryWindowInDays int) string { +func testAccSecretConfig_recoveryWindowInDays(rName string, recoveryWindowInDays int) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = %q @@ -663,7 +663,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName, recoveryWindowInDays) } -func testAccSecretConfig_RotationLambdaARN(rName string) string { +func testAccSecretConfig_rotationLambdaARN(rName string) string { return acctest.ConfigLambdaBase(rName, rName, rName) + fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%[1]s" @@ -706,7 +706,7 @@ resource "aws_lambda_permission" "test2" { `, rName) } -func testAccSecretConfig_RotationRules(rName string, automaticallyAfterDays int) string { +func testAccSecretConfig_rotationRules(rName string, automaticallyAfterDays int) string { return acctest.ConfigLambdaBase(rName, rName, rName) + fmt.Sprintf(` # Not a real rotation function resource "aws_lambda_function" "test" { @@ -737,7 +737,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName, automaticallyAfterDays) } -func testAccSecretConfig_Tags_Single(rName string) string { +func testAccSecretConfig_tagsSingle(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%s" @@ -749,7 +749,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName) } -func testAccSecretConfig_Tags_SingleUpdated(rName string) string { +func testAccSecretConfig_tagsSingleUpdated(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%s" @@ -761,7 +761,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName) } -func testAccSecretConfig_Tags_Multiple(rName string) string { +func testAccSecretConfig_tagsMultiple(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%s" @@ -774,7 +774,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName) } -func testAccSecretPolicyConfig(rName string) string { +func testAccSecretConfig_policy(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -812,7 +812,7 @@ resource "aws_secretsmanager_secret" "test" { `, rName) } -func testAccSecretPolicyEmptyConfig(rName string) string { +func testAccSecretConfig_policyEmpty(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q diff --git a/internal/service/secretsmanager/secret_version_data_source_test.go b/internal/service/secretsmanager/secret_version_data_source_test.go index 203db961481..3df07bc444c 100644 --- a/internal/service/secretsmanager/secret_version_data_source_test.go +++ b/internal/service/secretsmanager/secret_version_data_source_test.go @@ -23,11 +23,11 @@ func TestAccSecretsManagerSecretVersionDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecretVersionDataSourceConfig_NonExistent, + Config: testAccSecretVersionDataSourceConfig_nonExistent, ExpectError: regexp.MustCompile(`not found`), }, { - Config: testAccSecretVersionDataSourceConfig_VersionStage_Default(rName), + Config: testAccSecretVersionDataSourceConfig_stageDefault(rName), Check: resource.ComposeTestCheckFunc( testAccSecretVersionCheckDataSource(datasourceName, resourceName), ), @@ -47,7 +47,7 @@ func TestAccSecretsManagerSecretVersionDataSource_versionID(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecretVersionDataSourceConfig_VersionID(rName), + Config: testAccSecretVersionDataSourceConfig_id(rName), Check: resource.ComposeTestCheckFunc( testAccSecretVersionCheckDataSource(datasourceName, resourceName), ), @@ -67,7 +67,7 @@ func TestAccSecretsManagerSecretVersionDataSource_versionStage(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSecretVersionDataSourceConfig_VersionStage_Custom(rName), + Config: testAccSecretVersionDataSourceConfig_stageCustom(rName), Check: resource.ComposeTestCheckFunc( testAccSecretVersionCheckDataSource(datasourceName, resourceName), ), @@ -108,13 +108,13 @@ func testAccSecretVersionCheckDataSource(datasourceName, resourceName string) re } } -const testAccSecretVersionDataSourceConfig_NonExistent = ` +const testAccSecretVersionDataSourceConfig_nonExistent = ` data "aws_secretsmanager_secret_version" "test" { secret_id = "tf-acc-test-does-not-exist" } ` -func testAccSecretVersionDataSourceConfig_VersionID(rName string) string { +func testAccSecretVersionDataSourceConfig_id(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%[1]s" @@ -132,7 +132,7 @@ data "aws_secretsmanager_secret_version" "test" { `, rName) } -func testAccSecretVersionDataSourceConfig_VersionStage_Custom(rName string) string { +func testAccSecretVersionDataSourceConfig_stageCustom(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%[1]s" @@ -151,7 +151,7 @@ data "aws_secretsmanager_secret_version" "test" { `, rName) } -func testAccSecretVersionDataSourceConfig_VersionStage_Default(rName string) string { +func testAccSecretVersionDataSourceConfig_stageDefault(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%[1]s" diff --git a/internal/service/secretsmanager/secret_version_test.go b/internal/service/secretsmanager/secret_version_test.go index 3d501bfcd4d..b8011653535 100644 --- a/internal/service/secretsmanager/secret_version_test.go +++ b/internal/service/secretsmanager/secret_version_test.go @@ -29,7 +29,7 @@ func TestAccSecretsManagerSecretVersion_basicString(t *testing.T) { CheckDestroy: testAccCheckSecretVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretVersionConfig_SecretString(rName), + Config: testAccSecretVersionConfig_string(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretVersionExists(resourceName, &version), resource.TestCheckResourceAttr(resourceName, "secret_string", "test-string"), @@ -61,7 +61,7 @@ func TestAccSecretsManagerSecretVersion_base64Binary(t *testing.T) { CheckDestroy: testAccCheckSecretVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretVersionConfig_SecretBinary(rName), + Config: testAccSecretVersionConfig_binary(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretVersionExists(resourceName, &version), resource.TestCheckResourceAttr(resourceName, "secret_binary", verify.Base64Encode([]byte("test-binary"))), @@ -92,7 +92,7 @@ func TestAccSecretsManagerSecretVersion_versionStages(t *testing.T) { CheckDestroy: testAccCheckSecretVersionDestroy, Steps: []resource.TestStep{ { - Config: testAccSecretVersionConfig_VersionStages_Single(rName), + Config: testAccSecretVersionConfig_stagesSingle(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretVersionExists(resourceName, &version), resource.TestCheckResourceAttr(resourceName, "secret_string", "test-string"), @@ -102,7 +102,7 @@ func TestAccSecretsManagerSecretVersion_versionStages(t *testing.T) { ), }, { - Config: testAccSecretVersionConfig_VersionStages_SingleUpdated(rName), + Config: testAccSecretVersionConfig_stagesSingleUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretVersionExists(resourceName, &version), resource.TestCheckResourceAttr(resourceName, "secret_string", "test-string"), @@ -112,7 +112,7 @@ func TestAccSecretsManagerSecretVersion_versionStages(t *testing.T) { ), }, { - Config: testAccSecretVersionConfig_VersionStages_Multiple(rName), + Config: testAccSecretVersionConfig_stagesMultiple(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecretVersionExists(resourceName, &version), resource.TestCheckResourceAttr(resourceName, "secret_string", "test-string"), @@ -215,7 +215,7 @@ func testAccCheckSecretVersionExists(resourceName string, version *secretsmanage } } -func testAccSecretVersionConfig_SecretString(rName string) string { +func testAccSecretVersionConfig_string(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%s" @@ -228,7 +228,7 @@ resource "aws_secretsmanager_secret_version" "test" { `, rName) } -func testAccSecretVersionConfig_SecretBinary(rName string) string { +func testAccSecretVersionConfig_binary(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%s" @@ -241,7 +241,7 @@ resource "aws_secretsmanager_secret_version" "test" { `, rName) } -func testAccSecretVersionConfig_VersionStages_Single(rName string) string { +func testAccSecretVersionConfig_stagesSingle(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%s" @@ -256,7 +256,7 @@ resource "aws_secretsmanager_secret_version" "test" { `, rName) } -func testAccSecretVersionConfig_VersionStages_SingleUpdated(rName string) string { +func testAccSecretVersionConfig_stagesSingleUpdated(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%s" @@ -271,7 +271,7 @@ resource "aws_secretsmanager_secret_version" "test" { `, rName) } -func testAccSecretVersionConfig_VersionStages_Multiple(rName string) string { +func testAccSecretVersionConfig_stagesMultiple(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = "%s" diff --git a/internal/service/secretsmanager/secrets_data_source_test.go b/internal/service/secretsmanager/secrets_data_source_test.go index cbd2ebbafc2..7de6fd39024 100644 --- a/internal/service/secretsmanager/secrets_data_source_test.go +++ b/internal/service/secretsmanager/secrets_data_source_test.go @@ -33,11 +33,11 @@ func TestAccSecretsManagerSecretsDataSource_filter(t *testing.T) { CheckDestroy: testAccCheckSecretDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigSecrets_filter(rName), + Config: testAccSecretsDataSourceConfig_filter2(rName), Check: propagationSleep(), }, { - Config: testAccConfigSecretsWithDataSource_filter(rName), + Config: testAccSecretsDataSourceConfig_filter(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "arns.#", "1"), resource.TestCheckResourceAttr(dataSourceName, "names.#", "1"), @@ -49,7 +49,7 @@ func TestAccSecretsManagerSecretsDataSource_filter(t *testing.T) { }) } -func testAccConfigSecrets_filter(rName string) string { +func testAccSecretsDataSourceConfig_filter2(rName string) string { return fmt.Sprintf(` resource "aws_secretsmanager_secret" "test" { name = %[1]q @@ -57,9 +57,9 @@ resource "aws_secretsmanager_secret" "test" { `, rName) } -func testAccConfigSecretsWithDataSource_filter(rName string) string { +func testAccSecretsDataSourceConfig_filter(rName string) string { return acctest.ConfigCompose( - testAccConfigSecrets_filter(rName), + testAccSecretsDataSourceConfig_filter2(rName), ` data "aws_secretsmanager_secrets" "test" { filter { diff --git a/internal/service/securityhub/account_test.go b/internal/service/securityhub/account_test.go index afc42df6fd9..a3d6b88f4b0 100644 --- a/internal/service/securityhub/account_test.go +++ b/internal/service/securityhub/account_test.go @@ -20,7 +20,7 @@ func testAccAccount_basic(t *testing.T) { CheckDestroy: testAccCheckAccountDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountConfig(), + Config: testAccAccountConfig_basic(), Check: resource.ComposeTestCheckFunc( testAccCheckAccountExists("aws_securityhub_account.example"), ), @@ -81,7 +81,7 @@ func testAccCheckAccountDestroy(s *terraform.State) error { return nil } -func testAccAccountConfig() string { +func testAccAccountConfig_basic() string { return ` resource "aws_securityhub_account" "example" {} ` diff --git a/internal/service/securityhub/action_target_test.go b/internal/service/securityhub/action_target_test.go index fb545c73819..2c72966d72e 100644 --- a/internal/service/securityhub/action_target_test.go +++ b/internal/service/securityhub/action_target_test.go @@ -23,7 +23,7 @@ func testAccActionTarget_basic(t *testing.T) { CheckDestroy: testAccCheckActionTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccActionTargetIdentifierConfig("testaction"), + Config: testAccActionTargetConfig_identifier("testaction"), Check: resource.ComposeTestCheckFunc( testAccCheckActionTargetExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "securityhub", "action/custom/testaction"), @@ -51,7 +51,7 @@ func testAccActionTarget_disappears(t *testing.T) { CheckDestroy: testAccCheckActionTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccActionTargetIdentifierConfig("testaction"), + Config: testAccActionTargetConfig_identifier("testaction"), Check: resource.ComposeTestCheckFunc( testAccCheckActionTargetExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfsecurityhub.ResourceActionTarget(), resourceName), @@ -72,7 +72,7 @@ func testAccActionTarget_Description(t *testing.T) { CheckDestroy: testAccCheckActionTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccActionTargetDescriptionConfig("description1"), + Config: testAccActionTargetConfig_description("description1"), Check: resource.ComposeTestCheckFunc( testAccCheckActionTargetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -84,7 +84,7 @@ func testAccActionTarget_Description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccActionTargetDescriptionConfig("description2"), + Config: testAccActionTargetConfig_description("description2"), Check: resource.ComposeTestCheckFunc( testAccCheckActionTargetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -104,7 +104,7 @@ func testAccActionTarget_Name(t *testing.T) { CheckDestroy: testAccCheckActionTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccActionTargetNameConfig("name1"), + Config: testAccActionTargetConfig_name("name1"), Check: resource.ComposeTestCheckFunc( testAccCheckActionTargetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", "name1"), @@ -116,7 +116,7 @@ func testAccActionTarget_Name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccActionTargetNameConfig("name2"), + Config: testAccActionTargetConfig_name("name2"), Check: resource.ComposeTestCheckFunc( testAccCheckActionTargetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", "name2"), @@ -179,7 +179,7 @@ func testAccCheckActionTargetDestroy(s *terraform.State) error { return nil } -func testAccActionTargetDescriptionConfig(description string) string { +func testAccActionTargetConfig_description(description string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -192,7 +192,7 @@ resource "aws_securityhub_action_target" "test" { `, description) } -func testAccActionTargetIdentifierConfig(identifier string) string { +func testAccActionTargetConfig_identifier(identifier string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -205,7 +205,7 @@ resource "aws_securityhub_action_target" "test" { `, identifier) } -func testAccActionTargetNameConfig(name string) string { +func testAccActionTargetConfig_name(name string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} diff --git a/internal/service/securityhub/finding_aggregator_test.go b/internal/service/securityhub/finding_aggregator_test.go index 538afbbaafb..28e0f59dedb 100644 --- a/internal/service/securityhub/finding_aggregator_test.go +++ b/internal/service/securityhub/finding_aggregator_test.go @@ -24,7 +24,7 @@ func testAccFindingAggregator_basic(t *testing.T) { CheckDestroy: testAccCheckFindingAggregatorDestroy, Steps: []resource.TestStep{ { - Config: testAccFindingAggregatorAllRegionsConfig(), + Config: testAccFindingAggregatorConfig_allRegions(), Check: resource.ComposeTestCheckFunc( testAccCheckFindingAggregatorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "linking_mode", "ALL_REGIONS"), @@ -37,7 +37,7 @@ func testAccFindingAggregator_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFindingAggregatorSpecifiedRegionsConfig(), + Config: testAccFindingAggregatorConfig_specifiedRegions(), Check: resource.ComposeTestCheckFunc( testAccCheckFindingAggregatorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "linking_mode", "SPECIFIED_REGIONS"), @@ -45,7 +45,7 @@ func testAccFindingAggregator_basic(t *testing.T) { ), }, { - Config: testAccFindingAggregatorAllRegionsExceptSpecifiedConfig(), + Config: testAccFindingAggregatorConfig_allRegionsExceptSpecified(), Check: resource.ComposeTestCheckFunc( testAccCheckFindingAggregatorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "linking_mode", "ALL_REGIONS_EXCEPT_SPECIFIED"), @@ -66,7 +66,7 @@ func testAccFindingAggregator_disappears(t *testing.T) { CheckDestroy: testAccCheckFindingAggregatorDestroy, Steps: []resource.TestStep{ { - Config: testAccFindingAggregatorAllRegionsConfig(), + Config: testAccFindingAggregatorConfig_allRegions(), Check: resource.ComposeTestCheckFunc( testAccCheckFindingAggregatorExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfsecurityhub.ResourceFindingAggregator(), resourceName), @@ -128,7 +128,7 @@ func testAccCheckFindingAggregatorDestroy(s *terraform.State) error { return nil } -func testAccFindingAggregatorAllRegionsConfig() string { +func testAccFindingAggregatorConfig_allRegions() string { return ` resource "aws_securityhub_account" "example" {} @@ -140,7 +140,7 @@ resource "aws_securityhub_finding_aggregator" "test_aggregator" { ` } -func testAccFindingAggregatorSpecifiedRegionsConfig() string { +func testAccFindingAggregatorConfig_specifiedRegions() string { return fmt.Sprintf(` resource "aws_securityhub_account" "example" {} @@ -153,7 +153,7 @@ resource "aws_securityhub_finding_aggregator" "test_aggregator" { `, endpoints.EuWest1RegionID, endpoints.EuWest2RegionID, endpoints.UsEast1RegionID) } -func testAccFindingAggregatorAllRegionsExceptSpecifiedConfig() string { +func testAccFindingAggregatorConfig_allRegionsExceptSpecified() string { return fmt.Sprintf(` resource "aws_securityhub_account" "example" {} diff --git a/internal/service/securityhub/insight_test.go b/internal/service/securityhub/insight_test.go index 8bc1846ec2e..f5926a90cdc 100644 --- a/internal/service/securityhub/insight_test.go +++ b/internal/service/securityhub/insight_test.go @@ -28,7 +28,7 @@ func testAccInsight_basic(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig(rName), + Config: testAccInsightConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), testAccCheckInsightARN(resourceName), @@ -62,7 +62,7 @@ func testAccInsight_disappears(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig(rName), + Config: testAccInsightConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfsecurityhub.ResourceInsight(), resourceName), @@ -87,7 +87,7 @@ func testAccInsight_DateFilters(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig_DateFilters_DateRange(rName), + Config: testAccInsightConfig_dateFiltersDateRange(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -105,7 +105,7 @@ func testAccInsight_DateFilters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccInsightConfig_DateFilters_StartEnd(rName, startDate, endDate), + Config: testAccInsightConfig_dateFiltersStartEnd(rName, startDate, endDate), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -136,7 +136,7 @@ func testAccInsight_IPFilters(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig_IPFilters(rName), + Config: testAccInsightConfig_ipFilters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -166,7 +166,7 @@ func testAccInsight_KeywordFilters(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig_KeywordFilters(rName), + Config: testAccInsightConfig_keywordFilters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -196,7 +196,7 @@ func testAccInsight_MapFilters(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig_MapFilters(rName), + Config: testAccInsightConfig_mapFilters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -228,7 +228,7 @@ func testAccInsight_MultipleFilters(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig_MultipleFilters(rName), + Config: testAccInsightConfig_multipleFilters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -260,7 +260,7 @@ func testAccInsight_MultipleFilters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccInsightConfig(rName), + Config: testAccInsightConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -288,7 +288,7 @@ func testAccInsight_Name(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig(rName), + Config: testAccInsightConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), testAccCheckInsightARN(resourceName), @@ -296,7 +296,7 @@ func testAccInsight_Name(t *testing.T) { ), }, { - Config: testAccInsightConfig(rNameUpdated), + Config: testAccInsightConfig_basic(rNameUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), testAccCheckInsightARN(resourceName), @@ -323,7 +323,7 @@ func testAccInsight_NumberFilters(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig_NumberFilters(rName, "eq = 50.5"), + Config: testAccInsightConfig_numberFilters(rName, "eq = 50.5"), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -339,7 +339,7 @@ func testAccInsight_NumberFilters(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccInsightConfig_NumberFilters(rName, "gte = 50.5"), + Config: testAccInsightConfig_numberFilters(rName, "gte = 50.5"), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -350,7 +350,7 @@ func testAccInsight_NumberFilters(t *testing.T) { ), }, { - Config: testAccInsightConfig_NumberFilters(rName, "lte = 50.5"), + Config: testAccInsightConfig_numberFilters(rName, "lte = 50.5"), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -380,7 +380,7 @@ func testAccInsight_GroupByAttribute(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig(rName), + Config: testAccInsightConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -388,7 +388,7 @@ func testAccInsight_GroupByAttribute(t *testing.T) { ), }, { - Config: testAccInsightConfig_UpdateGroupByAttribute(rName), + Config: testAccInsightConfig_updateGroupByAttribute(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -415,7 +415,7 @@ func testAccInsight_WorkflowStatus(t *testing.T) { CheckDestroy: testAccCheckInsightDestroy, Steps: []resource.TestStep{ { - Config: testAccInsightConfig_WorkflowStatus(rName), + Config: testAccInsightConfig_workflowStatus(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInsightExists(resourceName), resource.TestCheckResourceAttr(resourceName, "filters.#", "1"), @@ -498,7 +498,7 @@ func testAccCheckInsightARN(resourceName string) resource.TestCheckFunc { } } -func testAccInsightConfig(rName string) string { +func testAccInsightConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -519,7 +519,7 @@ resource "aws_securityhub_insight" "test" { `, rName) } -func testAccInsightConfig_DateFilters_DateRange(rName string) string { +func testAccInsightConfig_dateFiltersDateRange(rName string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -542,7 +542,7 @@ resource "aws_securityhub_insight" "test" { `, rName) } -func testAccInsightConfig_DateFilters_StartEnd(rName, startDate, endDate string) string { +func testAccInsightConfig_dateFiltersStartEnd(rName, startDate, endDate string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -563,7 +563,7 @@ resource "aws_securityhub_insight" "test" { `, startDate, endDate, rName) } -func testAccInsightConfig_IPFilters(rName string) string { +func testAccInsightConfig_ipFilters(rName string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -583,7 +583,7 @@ resource "aws_securityhub_insight" "test" { `, rName) } -func testAccInsightConfig_KeywordFilters(rName string) string { +func testAccInsightConfig_keywordFilters(rName string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -603,7 +603,7 @@ resource "aws_securityhub_insight" "test" { `, rName) } -func testAccInsightConfig_MapFilters(rName string) string { +func testAccInsightConfig_mapFilters(rName string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -625,7 +625,7 @@ resource "aws_securityhub_insight" "test" { `, rName) } -func testAccInsightConfig_MultipleFilters(rName string) string { +func testAccInsightConfig_multipleFilters(rName string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -663,7 +663,7 @@ resource "aws_securityhub_insight" "test" { `, rName) } -func testAccInsightConfig_NumberFilters(rName, value string) string { +func testAccInsightConfig_numberFilters(rName, value string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -683,7 +683,7 @@ resource "aws_securityhub_insight" "test" { `, value, rName) } -func testAccInsightConfig_UpdateGroupByAttribute(rName string) string { +func testAccInsightConfig_updateGroupByAttribute(rName string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} @@ -704,7 +704,7 @@ resource "aws_securityhub_insight" "test" { `, rName) } -func testAccInsightConfig_WorkflowStatus(rName string) string { +func testAccInsightConfig_workflowStatus(rName string) string { return fmt.Sprintf(` resource "aws_securityhub_account" "test" {} diff --git a/internal/service/securityhub/organization_configuration_test.go b/internal/service/securityhub/organization_configuration_test.go index bbf7b068969..731a8ba2880 100644 --- a/internal/service/securityhub/organization_configuration_test.go +++ b/internal/service/securityhub/organization_configuration_test.go @@ -21,7 +21,7 @@ func testAccOrganizationConfiguration_basic(t *testing.T) { CheckDestroy: nil, //lintignore:AT001 Steps: []resource.TestStep{ { - Config: testAccOrganizationConfigurationConfig(true), + Config: testAccOrganizationConfigurationConfig_basic(true), Check: resource.ComposeTestCheckFunc( testAccOrganizationConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "auto_enable", "true"), @@ -33,7 +33,7 @@ func testAccOrganizationConfiguration_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccOrganizationConfigurationConfig(false), + Config: testAccOrganizationConfigurationConfig_basic(false), Check: resource.ComposeTestCheckFunc( testAccOrganizationConfigurationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "auto_enable", "false"), @@ -58,7 +58,7 @@ func testAccOrganizationConfigurationExists(n string) resource.TestCheckFunc { } } -func testAccOrganizationConfigurationConfig(autoEnable bool) string { +func testAccOrganizationConfigurationConfig_basic(autoEnable bool) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/securityhub/standards_control_test.go b/internal/service/securityhub/standards_control_test.go index 0f313c00b72..456fb741af5 100644 --- a/internal/service/securityhub/standards_control_test.go +++ b/internal/service/securityhub/standards_control_test.go @@ -54,7 +54,7 @@ func testAccStandardsControl_disabledControlStatus(t *testing.T) { CheckDestroy: nil, //lintignore:AT001 Steps: []resource.TestStep{ { - Config: testAccStandardsControlConfig_disabledControlStatus(), + Config: testAccStandardsControlConfig_disabledStatus(), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckStandardsControlExists(resourceName, &standardsControl), resource.TestCheckResourceAttr(resourceName, "control_status", "DISABLED"), @@ -73,7 +73,7 @@ func testAccStandardsControl_enabledControlStatusAndDisabledReason(t *testing.T) CheckDestroy: nil, //lintignore:AT001 Steps: []resource.TestStep{ { - Config: testAccStandardsControlConfig_enabledControlStatus(), + Config: testAccStandardsControlConfig_enabledStatus(), ExpectError: regexp.MustCompile("InvalidInputException: DisabledReason should not be given for action other than disabling control"), }, }, @@ -122,7 +122,7 @@ resource aws_securityhub_standards_control test { `) } -func testAccStandardsControlConfig_disabledControlStatus() string { +func testAccStandardsControlConfig_disabledStatus() string { return acctest.ConfigCompose( testAccStandardsSubscriptionConfig_basic, ` @@ -134,7 +134,7 @@ resource aws_securityhub_standards_control test { `) } -func testAccStandardsControlConfig_enabledControlStatus() string { +func testAccStandardsControlConfig_enabledStatus() string { return acctest.ConfigCompose( testAccStandardsSubscriptionConfig_basic, ` diff --git a/internal/service/serverlessrepo/application_data_source_test.go b/internal/service/serverlessrepo/application_data_source_test.go index 9054a3d86af..d861bdcac24 100644 --- a/internal/service/serverlessrepo/application_data_source_test.go +++ b/internal/service/serverlessrepo/application_data_source_test.go @@ -21,7 +21,7 @@ func TestAccServerlessRepoApplicationDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckApplicationDataSourceConfig(appARN), + Config: testAccApplicationDataSourceConfig_basic(appARN), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationIDDataSource(datasourceName), resource.TestCheckResourceAttr(datasourceName, "name", "SecretsManagerRDSPostgreSQLRotationSingleUser"), @@ -32,7 +32,7 @@ func TestAccServerlessRepoApplicationDataSource_basic(t *testing.T) { ), }, { - Config: testAccCheckApplicationDataSourceConfig_NonExistent(), + Config: testAccApplicationDataSourceConfig_nonExistent(), ExpectError: regexp.MustCompile(`error getting Serverless Application Repository application`), }, }, @@ -54,7 +54,7 @@ func TestAccServerlessRepoApplicationDataSource_versioned(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckApplicationDataSourceConfig_Versioned(appARN, version1), + Config: testAccApplicationDataSourceConfig_versioned(appARN, version1), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationIDDataSource(datasourceName), resource.TestCheckResourceAttr(datasourceName, "name", "SecretsManagerRDSPostgreSQLRotationSingleUser"), @@ -65,7 +65,7 @@ func TestAccServerlessRepoApplicationDataSource_versioned(t *testing.T) { ), }, { - Config: testAccCheckApplicationDataSourceConfig_Versioned(appARN, version2), + Config: testAccApplicationDataSourceConfig_versioned(appARN, version2), Check: resource.ComposeTestCheckFunc( testAccCheckApplicationIDDataSource(datasourceName), resource.TestCheckResourceAttr(datasourceName, "name", "SecretsManagerRDSPostgreSQLRotationSingleUser"), @@ -78,7 +78,7 @@ func TestAccServerlessRepoApplicationDataSource_versioned(t *testing.T) { ), }, { - Config: testAccCheckApplicationDataSourceConfig_Versioned_NonExistent(appARN), + Config: testAccApplicationDataSourceConfig_versionedNonExistent(appARN), ExpectError: regexp.MustCompile(`error getting Serverless Application Repository application`), }, }, @@ -99,7 +99,7 @@ func testAccCheckApplicationIDDataSource(n string) resource.TestCheckFunc { } } -func testAccCheckApplicationDataSourceConfig(appARN string) string { +func testAccApplicationDataSourceConfig_basic(appARN string) string { return fmt.Sprintf(` data "aws_serverlessapplicationrepository_application" "secrets_manager_postgres_single_user_rotator" { application_id = %[1]q @@ -107,7 +107,7 @@ data "aws_serverlessapplicationrepository_application" "secrets_manager_postgres `, appARN) } -func testAccCheckApplicationDataSourceConfig_NonExistent() string { +func testAccApplicationDataSourceConfig_nonExistent() string { return ` data "aws_caller_identity" "current" {} @@ -121,7 +121,7 @@ data "aws_serverlessapplicationrepository_application" "no_such_function" { ` } -func testAccCheckApplicationDataSourceConfig_Versioned(appARN, version string) string { +func testAccApplicationDataSourceConfig_versioned(appARN, version string) string { return fmt.Sprintf(` data "aws_serverlessapplicationrepository_application" "secrets_manager_postgres_single_user_rotator" { application_id = %[1]q @@ -130,7 +130,7 @@ data "aws_serverlessapplicationrepository_application" "secrets_manager_postgres `, appARN, version) } -func testAccCheckApplicationDataSourceConfig_Versioned_NonExistent(appARN string) string { +func testAccApplicationDataSourceConfig_versionedNonExistent(appARN string) string { return fmt.Sprintf(` data "aws_serverlessapplicationrepository_application" "secrets_manager_postgres_single_user_rotator" { application_id = %[1]q diff --git a/internal/service/serverlessrepo/cloudformation_stack_test.go b/internal/service/serverlessrepo/cloudformation_stack_test.go index fb5d0b8aa21..ffad4711b5a 100644 --- a/internal/service/serverlessrepo/cloudformation_stack_test.go +++ b/internal/service/serverlessrepo/cloudformation_stack_test.go @@ -36,7 +36,7 @@ func TestAccServerlessRepoCloudFormationStack_basic(t *testing.T) { CheckDestroy: testAccCheckCloudFormationDestroy, Steps: []resource.TestStep{ { - Config: testAccCloudFormationStackConfig(stackName, appARN), + Config: testAccCloudFormationStackConfig_basic(stackName, appARN), Check: resource.ComposeTestCheckFunc( testAccCheckCloudFormationStackExists(resourceName, &stack), resource.TestCheckResourceAttr(resourceName, "name", stackName), @@ -87,7 +87,7 @@ func TestAccServerlessRepoCloudFormationStack_disappears(t *testing.T) { CheckDestroy: testAccCheckAMIDestroy, Steps: []resource.TestStep{ { - Config: testAccCloudFormationStackConfig(stackName, appARN), + Config: testAccCloudFormationStackConfig_basic(stackName, appARN), Check: resource.ComposeTestCheckFunc( testAccCheckCloudFormationStackExists(resourceName, &stack), acctest.CheckResourceDisappears(acctest.Provider, tfserverlessrepo.ResourceCloudFormationStack(), resourceName), @@ -198,7 +198,7 @@ func TestAccServerlessRepoCloudFormationStack_tags(t *testing.T) { CheckDestroy: testAccCheckCloudFormationDestroy, Steps: []resource.TestStep{ { - Config: testAccCloudFormationStackTags1Config(stackName, appARN, "key1", "value1"), + Config: testAccCloudFormationStackConfig_tags1(stackName, appARN, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckCloudFormationStackExists(resourceName, &stack), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -211,7 +211,7 @@ func TestAccServerlessRepoCloudFormationStack_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCloudFormationStackTags2Config(stackName, appARN, "key1", "value1updated", "key2", "value2"), + Config: testAccCloudFormationStackConfig_tags2(stackName, appARN, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCloudFormationStackExists(resourceName, &stack), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), @@ -219,7 +219,7 @@ func TestAccServerlessRepoCloudFormationStack_tags(t *testing.T) { ), }, { - Config: testAccCloudFormationStackTags1Config(stackName, appARN, "key2", "value2"), + Config: testAccCloudFormationStackConfig_tags1(stackName, appARN, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCloudFormationStackExists(resourceName, &stack), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -331,7 +331,7 @@ func testAccCloudFormationApplicationID() string { }.String() } -func testAccCloudFormationStackConfig(stackName, appARN string) string { +func testAccCloudFormationStackConfig_basic(stackName, appARN string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -482,7 +482,7 @@ data "aws_serverlessapplicationrepository_application" "secrets_manager_postgres `, stackName, appARN, version) } -func testAccCloudFormationStackTags1Config(rName, appARN, tagKey1, tagValue1 string) string { +func testAccCloudFormationStackConfig_tags1(rName, appARN, tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -509,7 +509,7 @@ resource "aws_serverlessapplicationrepository_cloudformation_stack" "postgres-ro `, rName, appARN, tagKey1, tagValue1) } -func testAccCloudFormationStackTags2Config(rName, appARN, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccCloudFormationStackConfig_tags2(rName, appARN, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/servicecatalog/portfolio_constraints_data_source_test.go b/internal/service/servicecatalog/portfolio_constraints_data_source_test.go index 7446073eb49..bc3af339906 100644 --- a/internal/service/servicecatalog/portfolio_constraints_data_source_test.go +++ b/internal/service/servicecatalog/portfolio_constraints_data_source_test.go @@ -20,7 +20,7 @@ func TestAccServiceCatalogPortfolioConstraintsDataSource_Constraint_basic(t *tes ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccPortfolioConstraintDataSourceConfig_basic(rName, rName), + Config: testAccPortfolioConstraintsDataSourceConfig_constraintBasic(rName, rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "accept_language", resourceName, "accept_language"), resource.TestCheckResourceAttr(dataSourceName, "details.#", "1"), @@ -37,7 +37,7 @@ func TestAccServiceCatalogPortfolioConstraintsDataSource_Constraint_basic(t *tes }) } -func testAccPortfolioConstraintDataSourceConfig_basic(rName, description string) string { +func testAccPortfolioConstraintsDataSourceConfig_constraintBasic(rName, description string) string { return acctest.ConfigCompose(testAccConstraintConfig_basic(rName, description), ` data "aws_servicecatalog_portfolio_constraints" "test" { portfolio_id = aws_servicecatalog_constraint.test.portfolio_id diff --git a/internal/service/servicecatalog/portfolio_data_source_test.go b/internal/service/servicecatalog/portfolio_data_source_test.go index 31d5e329c7a..975179be106 100644 --- a/internal/service/servicecatalog/portfolio_data_source_test.go +++ b/internal/service/servicecatalog/portfolio_data_source_test.go @@ -21,7 +21,7 @@ func TestAccServiceCatalogPortfolioDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckServiceCatlaogPortfolioDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPortfolioBasicDataSourceConfig(rName), + Config: testAccPortfolioDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "created_time", dataSourceName, "created_time"), @@ -36,8 +36,8 @@ func TestAccServiceCatalogPortfolioDataSource_basic(t *testing.T) { }) } -func testAccCheckPortfolioBasicDataSourceConfig(rName string) string { - return acctest.ConfigCompose(testAccCheckPortfolioResourceTags1Config(rName, "Chicane", "Nick"), ` +func testAccPortfolioDataSourceConfig_basic(rName string) string { + return acctest.ConfigCompose(testAccPortfolioConfig_tags1(rName, "Chicane", "Nick"), ` data "aws_servicecatalog_portfolio" "test" { id = aws_servicecatalog_portfolio.test.id } diff --git a/internal/service/servicecatalog/portfolio_test.go b/internal/service/servicecatalog/portfolio_test.go index 845123e66c2..0035dfff1fc 100644 --- a/internal/service/servicecatalog/portfolio_test.go +++ b/internal/service/servicecatalog/portfolio_test.go @@ -26,7 +26,7 @@ func TestAccServiceCatalogPortfolio_basic(t *testing.T) { CheckDestroy: testAccCheckServiceCatlaogPortfolioDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPortfolioResourceBasicConfig(name), + Config: testAccPortfolioConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckPortfolio(resourceName, &dpo), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "catalog", regexp.MustCompile(`portfolio/.+`)), @@ -58,7 +58,7 @@ func TestAccServiceCatalogPortfolio_disappears(t *testing.T) { CheckDestroy: testAccCheckServiceCatlaogPortfolioDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPortfolioResourceBasicConfig(name), + Config: testAccPortfolioConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckPortfolio(resourceName, &dpo), testAccCheckServiceCatlaogPortfolioDisappears(&dpo), @@ -81,7 +81,7 @@ func TestAccServiceCatalogPortfolio_tags(t *testing.T) { CheckDestroy: testAccCheckServiceCatlaogPortfolioDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPortfolioResourceTags1Config(name, "key1", "value1"), + Config: testAccPortfolioConfig_tags1(name, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckPortfolio(resourceName, &dpo), resource.TestCheckResourceAttr(resourceName, "name", name), @@ -95,7 +95,7 @@ func TestAccServiceCatalogPortfolio_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCheckPortfolioResourceTags2Config(name, "key1", "value1updated", "key2", "value2"), + Config: testAccPortfolioConfig_tags2(name, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckPortfolio(resourceName, &dpo), resource.TestCheckResourceAttr(resourceName, "name", name), @@ -105,7 +105,7 @@ func TestAccServiceCatalogPortfolio_tags(t *testing.T) { ), }, { - Config: testAccCheckPortfolioResourceTags1Config(name, "key2", "value2"), + Config: testAccPortfolioConfig_tags1(name, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckPortfolio(resourceName, &dpo), resource.TestCheckResourceAttr(resourceName, "name", name), @@ -173,7 +173,7 @@ func testAccCheckServiceCatlaogPortfolioDestroy(s *terraform.State) error { return nil } -func testAccCheckPortfolioResourceBasicConfig(name string) string { +func testAccPortfolioConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_servicecatalog_portfolio" "test" { name = "%s" @@ -183,7 +183,7 @@ resource "aws_servicecatalog_portfolio" "test" { `, name) } -func testAccCheckPortfolioResourceTags1Config(name, tagKey1, tagValue1 string) string { +func testAccPortfolioConfig_tags1(name, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_servicecatalog_portfolio" "test" { name = %[1]q @@ -197,7 +197,7 @@ resource "aws_servicecatalog_portfolio" "test" { `, name, tagKey1, tagValue1) } -func testAccCheckPortfolioResourceTags2Config(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccPortfolioConfig_tags2(name, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_servicecatalog_portfolio" "test" { name = %[1]q diff --git a/internal/service/servicecatalog/provisioned_product.go b/internal/service/servicecatalog/provisioned_product.go index 4383c15d953..6f45b7714f0 100644 --- a/internal/service/servicecatalog/provisioned_product.go +++ b/internal/service/servicecatalog/provisioned_product.go @@ -8,6 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicecatalog" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -415,9 +416,16 @@ func resourceProvisionedProductRead(d *schema.ResourceData, meta interface{}) er d.Set("status_message", detail.StatusMessage) d.Set("type", detail.Type) - // tags are only available from the record tied to the provisioned product + // Previously, we waited for the record to only return a target state of 'SUCCEEDED' or 'AVAILABLE' + // but this can interfere complete reads of this resource when an error occurs after initial creation + // or after an invalid update that returns a 'FAILED' record state. Thus, waiters are now present in the CREATE and UPDATE methods of this resource instead. + // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/24574#issuecomment-1126339193 + recordInput := &servicecatalog.DescribeRecordInput{ + Id: detail.LastProvisioningRecordId, + AcceptLanguage: aws.String(acceptLanguage), + } - recordOutput, err := WaitRecordReady(conn, acceptLanguage, aws.StringValue(detail.LastProvisioningRecordId), RecordReadyTimeout) + recordOutput, err := conn.DescribeRecord(recordInput) if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, servicecatalog.ErrCodeResourceNotFoundException) { log.Printf("[WARN] Service Catalog Provisioned Product (%s) Record (%s) not found, unable to set tags", d.Id(), aws.StringValue(detail.LastProvisioningRecordId)) @@ -432,12 +440,27 @@ func resourceProvisionedProductRead(d *schema.ResourceData, meta interface{}) er return fmt.Errorf("error getting Service Catalog Provisioned Product (%s) Record (%s): empty response", d.Id(), aws.StringValue(detail.LastProvisioningRecordId)) } + // To enable debugging of potential errors, log as a warning + // instead of exiting prematurely with an error, e.g. + // errors can be present after update to a new version failed and the stack + // rolled back to the current version. + if errors := recordOutput.RecordDetail.RecordErrors; len(errors) > 0 { + var errs *multierror.Error + + for _, err := range errors { + errs = multierror.Append(errs, fmt.Errorf("%s: %s", aws.StringValue(err.Code), aws.StringValue(err.Description))) + } + + log.Printf("[WARN] Errors found when describing Service Catalog Provisioned Product (%s) Record (%s): %s", d.Id(), aws.StringValue(detail.LastProvisioningRecordId), errs.ErrorOrNil()) + } + if err := d.Set("outputs", flattenRecordOutputs(recordOutput.RecordOutputs)); err != nil { return fmt.Errorf("error setting outputs: %w", err) } d.Set("path_id", recordOutput.RecordDetail.PathId) + // tags are only available from the record tied to the provisioned product tags := recordKeyValueTags(recordOutput.RecordDetail.RecordTags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 diff --git a/internal/service/servicecatalog/provisioned_product_test.go b/internal/service/servicecatalog/provisioned_product_test.go index 8fb422a21fb..0c917e7859d 100644 --- a/internal/service/servicecatalog/provisioned_product_test.go +++ b/internal/service/servicecatalog/provisioned_product_test.go @@ -195,6 +195,38 @@ func TestAccServiceCatalogProvisionedProduct_tags(t *testing.T) { }) } +// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/24574 +func TestAccServiceCatalogProvisionedProduct_tainted(t *testing.T) { + resourceName := "aws_servicecatalog_provisioned_product.test" + + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + domain := fmt.Sprintf("http://%s", acctest.RandomDomainName()) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, servicecatalog.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckProvisionedProductDestroy, + Steps: []resource.TestStep{ + { + Config: testAccProvisionedProductConfig_basic(rName, domain, acctest.DefaultEmailAddress, "10.1.0.0/16"), + Check: resource.ComposeTestCheckFunc( + testAccCheckProvisionedProductExists(resourceName), + ), + }, + { + Config: testAccProvisionedProductConfig_updateTainted(rName, domain, acctest.DefaultEmailAddress, "10.1.0.0/16"), + ExpectError: regexp.MustCompile(`unexpected state 'TAINTED', wanted target 'AVAILABLE'`), + }, + { + // Check we can still run a complete plan after the previous update error + Config: testAccProvisionedProductConfig_updateTainted(rName, domain, acctest.DefaultEmailAddress, "10.1.0.0/16"), + PlanOnly: true, + }, + }, + }) +} + func testAccCheckProvisionedProductDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).ServiceCatalogConn @@ -385,6 +417,28 @@ resource "aws_servicecatalog_provisioned_product" "test" { `, rName, vpcCidr)) } +func testAccProvisionedProductConfig_updateTainted(rName, domain, email, vpcCidr string) string { + return acctest.ConfigCompose(testAccProvisionedProductTemplateURLBaseConfig(rName, domain, email), + fmt.Sprintf(` +resource "aws_servicecatalog_provisioned_product" "test" { + name = %[1]q + product_id = aws_servicecatalog_product.test.id + provisioning_artifact_name = %[1]q + path_id = data.aws_servicecatalog_launch_paths.test.summaries[0].path_id + + provisioning_parameters { + key = "VPCPrimaryCIDR" + value = %[2]q + } + + provisioning_parameters { + key = "LeaveMeEmpty" + value = "NotEmpty" + } +} +`, rName, vpcCidr)) +} + func testAccProvisionedProductConfig_tags(rName, tagKey, tagValue, domain, email string) string { return acctest.ConfigCompose(testAccProvisionedProductTemplateURLBaseConfig(rName, domain, email), fmt.Sprintf(` diff --git a/internal/service/servicecatalog/status.go b/internal/service/servicecatalog/status.go index 00120bd0c58..71d563d2e8e 100644 --- a/internal/service/servicecatalog/status.go +++ b/internal/service/servicecatalog/status.go @@ -388,34 +388,6 @@ func StatusProvisionedProduct(conn *servicecatalog.ServiceCatalog, acceptLanguag } } -func StatusRecord(conn *servicecatalog.ServiceCatalog, acceptLanguage, id string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - input := &servicecatalog.DescribeRecordInput{ - Id: aws.String(id), - } - - if acceptLanguage != "" { - input.AcceptLanguage = aws.String(acceptLanguage) - } - - output, err := conn.DescribeRecord(input) - - if tfawserr.ErrCodeEquals(err, servicecatalog.ErrCodeResourceNotFoundException) { - return nil, StatusNotFound, err - } - - if err != nil { - return nil, servicecatalog.StatusFailed, err - } - - if output == nil || output.RecordDetail == nil { - return nil, StatusNotFound, err - } - - return output, aws.StringValue(output.RecordDetail.Status), err - } -} - func StatusPortfolioConstraints(conn *servicecatalog.ServiceCatalog, acceptLanguage, portfolioID, productID string) resource.StateRefreshFunc { return func() (interface{}, string, error) { input := &servicecatalog.ListConstraintsForPortfolioInput{ diff --git a/internal/service/servicecatalog/sweep.go b/internal/service/servicecatalog/sweep.go index 4bc21fa978e..28e403f0714 100644 --- a/internal/service/servicecatalog/sweep.go +++ b/internal/service/servicecatalog/sweep.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/servicecatalog" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -85,7 +86,7 @@ func sweepBudgetResourceAssociations(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -196,7 +197,7 @@ func sweepConstraints(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -265,7 +266,7 @@ func sweepPrincipalPortfolioAssociations(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -337,7 +338,7 @@ func sweepProductPortfolioAssociations(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -429,7 +430,7 @@ func sweepProducts(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -480,7 +481,7 @@ func sweepProvisionedProducts(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -534,7 +535,7 @@ func sweepProvisioningArtifacts(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -615,7 +616,7 @@ func sweepServiceActions(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -666,7 +667,7 @@ func sweepTagOptionResourceAssociations(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -713,6 +714,10 @@ func sweepTagOptionResourceAssociations(region string) error { return !lastPage }) + if tfawserr.ErrCodeEquals(err, servicecatalog.ErrCodeTagOptionNotMigratedException) { + log.Printf("[WARN] Skipping Service Catalog Tag Option Resource Associations sweep for %s: %s", region, err) + return nil + } if err != nil { errs = multierror.Append(errs, fmt.Errorf("error describing Service Catalog Tag Option Resource Associations for %s: %w", region, err)) } @@ -733,7 +738,7 @@ func sweepTagOptions(region string) error { client, err := sweep.SharedRegionalSweepClient(region) if err != nil { - return fmt.Errorf("error getting client: %s", err) + return fmt.Errorf("error getting client: %w", err) } conn := client.(*conns.AWSClient).ServiceCatalogConn @@ -764,6 +769,10 @@ func sweepTagOptions(region string) error { return !lastPage }) + if tfawserr.ErrCodeEquals(err, servicecatalog.ErrCodeTagOptionNotMigratedException) { + log.Printf("[WARN] Skipping Service Catalog Tag Options sweep for %s: %s", region, err) + return nil + } if err != nil { errs = multierror.Append(errs, fmt.Errorf("error describing Service Catalog Tag Options for %s: %w", region, err)) } diff --git a/internal/service/servicecatalog/wait.go b/internal/service/servicecatalog/wait.go index b160389a1e6..90b0a9cbb27 100644 --- a/internal/service/servicecatalog/wait.go +++ b/internal/service/servicecatalog/wait.go @@ -2,13 +2,11 @@ package servicecatalog import ( "errors" - "fmt" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicecatalog" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" - "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) @@ -50,7 +48,6 @@ const ( ProvisioningArtifactReadTimeout = 10 * time.Minute ProvisioningArtifactReadyTimeout = 3 * time.Minute ProvisioningArtifactUpdateTimeout = 3 * time.Minute - RecordReadyTimeout = 30 * time.Minute ServiceActionDeleteTimeout = 3 * time.Minute ServiceActionReadTimeout = 10 * time.Minute ServiceActionReadyTimeout = 3 * time.Minute @@ -517,7 +514,14 @@ func WaitProvisionedProductReady(conn *servicecatalog.ServiceCatalog, acceptLang outputRaw, err := stateConf.WaitForState() if output, ok := outputRaw.(*servicecatalog.DescribeProvisionedProductOutput); ok { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.ProvisionedProductDetail.StatusMessage))) + if detail := output.ProvisionedProductDetail; detail != nil { + status := aws.StringValue(detail.Status) + // Note: "TAINTED" is described as a stable state per API docs, though can result from a failed update + // such that the stack rolls back to a previous version + if status == servicecatalog.ProvisionedProductStatusError || status == servicecatalog.ProvisionedProductStatusTainted { + tfresource.SetLastError(err, errors.New(aws.StringValue(detail.StatusMessage))) + } + } return output, err } @@ -537,36 +541,6 @@ func WaitProvisionedProductTerminated(conn *servicecatalog.ServiceCatalog, accep return err } -func WaitRecordReady(conn *servicecatalog.ServiceCatalog, acceptLanguage, id string, timeout time.Duration) (*servicecatalog.DescribeRecordOutput, error) { - stateConf := &resource.StateChangeConf{ - Pending: []string{StatusNotFound, StatusUnavailable, servicecatalog.ProvisionedProductStatusUnderChange, servicecatalog.ProvisionedProductStatusPlanInProgress}, - Target: []string{servicecatalog.RecordStatusSucceeded, servicecatalog.StatusAvailable}, - Refresh: StatusRecord(conn, acceptLanguage, id), - Timeout: timeout, - ContinuousTargetOccurence: ContinuousTargetOccurrence, - NotFoundChecks: NotFoundChecks, - MinTimeout: MinTimeout, - } - - outputRaw, err := stateConf.WaitForState() - - if output, ok := outputRaw.(*servicecatalog.DescribeRecordOutput); ok { - if errors := output.RecordDetail.RecordErrors; len(errors) > 0 { - var errs *multierror.Error - - for _, err := range output.RecordDetail.RecordErrors { - errs = multierror.Append(errs, fmt.Errorf("%s: %s", aws.StringValue(err.Code), aws.StringValue(err.Description))) - } - - tfresource.SetLastError(err, errs.ErrorOrNil()) - } - - return output, err - } - - return nil, err -} - func WaitPortfolioConstraintsReady(conn *servicecatalog.ServiceCatalog, acceptLanguage, portfolioID, productID string, timeout time.Duration) ([]*servicecatalog.ConstraintDetail, error) { stateConf := &resource.StateChangeConf{ Pending: []string{StatusNotFound}, diff --git a/internal/service/servicediscovery/dns_namespace_data_source_test.go b/internal/service/servicediscovery/dns_namespace_data_source_test.go index 63d9386482d..e474134e321 100644 --- a/internal/service/servicediscovery/dns_namespace_data_source_test.go +++ b/internal/service/servicediscovery/dns_namespace_data_source_test.go @@ -25,7 +25,7 @@ func TestAccServiceDiscoveryDNSNamespaceDataSource_private(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckPrivateDNSNamespaceConfig(rName), + Config: testAccDNSNamespaceDataSourceConfig_private(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), @@ -52,7 +52,7 @@ func TestAccServiceDiscoveryDNSNamespaceDataSource_public(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckPublicDNSNamespaceConfig(rName), + Config: testAccDNSNamespaceDataSourceConfig_public(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), @@ -64,7 +64,7 @@ func TestAccServiceDiscoveryDNSNamespaceDataSource_public(t *testing.T) { }) } -func testAccCheckPrivateDNSNamespaceConfig(rName string) string { +func testAccDNSNamespaceDataSourceConfig_private(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -82,7 +82,7 @@ data "aws_service_discovery_dns_namespace" "test" { `, rName) } -func testAccCheckPublicDNSNamespaceConfig(rName string) string { +func testAccDNSNamespaceDataSourceConfig_public(rName string) string { return fmt.Sprintf(` resource "aws_service_discovery_public_dns_namespace" "test" { name = "%[1]s.tf" diff --git a/internal/service/servicediscovery/instance_test.go b/internal/service/servicediscovery/instance_test.go index eec351045a6..f16b568f521 100644 --- a/internal/service/servicediscovery/instance_test.go +++ b/internal/service/servicediscovery/instance_test.go @@ -30,11 +30,7 @@ func TestAccServiceDiscoveryInstance_private(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: acctest.ConfigCompose( - testAccInstanceBaseConfig(rName), - testAccInstancePrivateNamespaceConfig(rName, domainName), - testAccInstanceConfig(rName, "AWS_INSTANCE_IPV4 = \"10.0.0.1\" \n AWS_INSTANCE_IPV6 = \"2001:0db8:85a3:0000:0000:abcd:0001:2345\""), - ), + Config: testAccInstanceConfig_private(rName, domainName, "AWS_INSTANCE_IPV4 = \"10.0.0.1\" \n AWS_INSTANCE_IPV6 = \"2001:0db8:85a3:0000:0000:abcd:0001:2345\""), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "service_id"), @@ -44,11 +40,7 @@ func TestAccServiceDiscoveryInstance_private(t *testing.T) { ), }, { - Config: acctest.ConfigCompose( - testAccInstanceBaseConfig(rName), - testAccInstancePrivateNamespaceConfig(rName, domainName), - testAccInstanceConfig(rName, "AWS_INSTANCE_IPV4 = \"10.0.0.2\" \n AWS_INSTANCE_IPV6 = \"2001:0db8:85a3:0000:0000:abcd:0001:2345\""), - ), + Config: testAccInstanceConfig_private(rName, domainName, "AWS_INSTANCE_IPV4 = \"10.0.0.2\" \n AWS_INSTANCE_IPV6 = \"2001:0db8:85a3:0000:0000:abcd:0001:2345\""), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "service_id"), @@ -83,11 +75,7 @@ func TestAccServiceDiscoveryInstance_public(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: acctest.ConfigCompose( - testAccInstanceBaseConfig(rName), - testAccInstancePublicNamespaceConfig(rName, domainName), - testAccInstanceConfig(rName, "AWS_INSTANCE_IPV4 = \"52.18.0.2\" \n CUSTOM_KEY = \"this is a custom value\""), - ), + Config: testAccInstanceConfig_public(rName, domainName, "AWS_INSTANCE_IPV4 = \"52.18.0.2\" \n CUSTOM_KEY = \"this is a custom value\""), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "service_id"), @@ -97,11 +85,7 @@ func TestAccServiceDiscoveryInstance_public(t *testing.T) { ), }, { - Config: acctest.ConfigCompose( - testAccInstanceBaseConfig(rName), - testAccInstancePublicNamespaceConfig(rName, domainName), - testAccInstanceConfig(rName, "AWS_INSTANCE_IPV4 = \"52.18.0.2\" \n CUSTOM_KEY = \"this is a custom value updated\""), - ), + Config: testAccInstanceConfig_public(rName, domainName, "AWS_INSTANCE_IPV4 = \"52.18.0.2\" \n CUSTOM_KEY = \"this is a custom value updated\""), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "service_id"), @@ -136,11 +120,7 @@ func TestAccServiceDiscoveryInstance_http(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: acctest.ConfigCompose( - testAccInstanceBaseConfig(rName), - testAccInstanceHTTPNamespaceConfig(rName, domainName), - testAccInstanceConfig(rName, "AWS_EC2_INSTANCE_ID = aws_instance.test_instance.id"), - ), + Config: testAccInstanceConfig_http(rName, domainName, "AWS_EC2_INSTANCE_ID = aws_instance.test_instance.id"), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "service_id"), @@ -149,11 +129,7 @@ func TestAccServiceDiscoveryInstance_http(t *testing.T) { ), }, { - Config: acctest.ConfigCompose( - testAccInstanceBaseConfig(rName), - testAccInstanceHTTPNamespaceConfig(rName, domainName), - testAccInstanceConfig(rName, "AWS_INSTANCE_IPV4 = \"172.18.0.12\""), - ), + Config: testAccInstanceConfig_http(rName, domainName, "AWS_INSTANCE_IPV4 = \"172.18.0.12\""), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "service_id"), @@ -171,7 +147,65 @@ func TestAccServiceDiscoveryInstance_http(t *testing.T) { }) } -func testAccInstanceBaseConfig(rName string) string { +func testAccCheckInstanceExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Service Discovery Instance ID is set") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).ServiceDiscoveryConn + + _, err := tfservicediscovery.FindInstanceByServiceIDAndInstanceID(conn, rs.Primary.Attributes["service_id"], rs.Primary.Attributes["instance_id"]) + + if err != nil { + return err + } + + return nil + } +} + +func testAccInstanceImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { + return func(s *terraform.State) (string, error) { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return "", fmt.Errorf("Not found: %s", resourceName) + } + + return fmt.Sprintf("%s/%s", rs.Primary.Attributes["service_id"], rs.Primary.Attributes["instance_id"]), nil + } +} + +func testAccCheckInstanceDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).ServiceDiscoveryConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_service_discovery_instance" { + continue + } + + _, err := tfservicediscovery.FindInstanceByServiceIDAndInstanceID(conn, rs.Primary.Attributes["service_id"], rs.Primary.Attributes["instance_id"]) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("Service Discovery Instance %s still exists", rs.Primary.ID) + } + + return nil +} + +func testAccInstanceConfig_base(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "sd_register_instance" { cidr_block = "10.0.0.0/16" @@ -184,7 +218,31 @@ resource "aws_vpc" "sd_register_instance" { }`, rName) } -func testAccInstancePrivateNamespaceConfig(rName, domainName string) string { +func testAccInstanceConfig_private(rName, domainName, attributes string) string { + return acctest.ConfigCompose( + testAccInstanceConfig_base(rName), + testAccInstanceConfig_privateNamespace(rName, domainName), + testAccInstanceConfig_basic(rName, attributes), + ) +} + +func testAccInstanceConfig_public(rName, domainName, attributes string) string { + return acctest.ConfigCompose( + testAccInstanceConfig_base(rName), + testAccInstanceConfig_publicNamespace(rName, domainName), + testAccInstanceConfig_basic(rName, attributes), + ) +} + +func testAccInstanceConfig_http(rName, domainName, attributes string) string { + return acctest.ConfigCompose( + testAccInstanceConfig_base(rName), + testAccInstanceConfig_httpNamespace(rName, domainName), + testAccInstanceConfig_basic(rName, attributes), + ) +} + +func testAccInstanceConfig_privateNamespace(rName, domainName string) string { return fmt.Sprintf(` resource "aws_service_discovery_private_dns_namespace" "sd_register_instance" { name = %[2]q @@ -212,7 +270,7 @@ resource "aws_service_discovery_service" "sd_register_instance" { }`, rName, domainName) } -func testAccInstancePublicNamespaceConfig(rName, domainName string) string { +func testAccInstanceConfig_publicNamespace(rName, domainName string) string { return fmt.Sprintf(` resource "aws_service_discovery_public_dns_namespace" "sd_register_instance" { name = %[2]q @@ -238,8 +296,8 @@ resource "aws_service_discovery_service" "sd_register_instance" { }`, rName, domainName) } -func testAccInstanceHTTPNamespaceConfig(rName, domainName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccInstanceConfig_httpNamespace(rName, domainName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_instance" "test_instance" { instance_type = "t2.micro" ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id @@ -259,7 +317,7 @@ resource "aws_service_discovery_service" "sd_register_instance" { }`, rName, domainName)) } -func testAccInstanceConfig(instanceID string, attributes string) string { +func testAccInstanceConfig_basic(instanceID string, attributes string) string { return fmt.Sprintf(` resource "aws_service_discovery_instance" "instance" { service_id = aws_service_discovery_service.sd_register_instance.id @@ -270,61 +328,3 @@ resource "aws_service_discovery_instance" "instance" { } }`, instanceID, attributes) } - -func testAccCheckInstanceExists(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No Service Discovery Instance ID is set") - } - - conn := acctest.Provider.Meta().(*conns.AWSClient).ServiceDiscoveryConn - - _, err := tfservicediscovery.FindInstanceByServiceIDAndInstanceID(conn, rs.Primary.Attributes["service_id"], rs.Primary.Attributes["instance_id"]) - - if err != nil { - return err - } - - return nil - } -} - -func testAccInstanceImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { - return func(s *terraform.State) (string, error) { - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return "", fmt.Errorf("Not found: %s", resourceName) - } - - return fmt.Sprintf("%s/%s", rs.Primary.Attributes["service_id"], rs.Primary.Attributes["instance_id"]), nil - } -} - -func testAccCheckInstanceDestroy(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ServiceDiscoveryConn - - for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_service_discovery_instance" { - continue - } - - _, err := tfservicediscovery.FindInstanceByServiceIDAndInstanceID(conn, rs.Primary.Attributes["service_id"], rs.Primary.Attributes["instance_id"]) - - if tfresource.NotFound(err) { - continue - } - - if err != nil { - return err - } - - return fmt.Errorf("Service Discovery Instance %s still exists", rs.Primary.ID) - } - - return nil -} diff --git a/internal/service/servicequotas/service_data_source_test.go b/internal/service/servicequotas/service_data_source_test.go index eb4067ff925..ed73f4db032 100644 --- a/internal/service/servicequotas/service_data_source_test.go +++ b/internal/service/servicequotas/service_data_source_test.go @@ -18,7 +18,7 @@ func TestAccServiceQuotasServiceDataSource_serviceName(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccServiceServiceNameDataSourceConfig("Amazon Virtual Private Cloud (Amazon VPC)"), + Config: testAccServiceDataSourceConfig_name("Amazon Virtual Private Cloud (Amazon VPC)"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "service_code", "vpc"), ), @@ -27,7 +27,7 @@ func TestAccServiceQuotasServiceDataSource_serviceName(t *testing.T) { }) } -func testAccServiceServiceNameDataSourceConfig(serviceName string) string { +func testAccServiceDataSourceConfig_name(serviceName string) string { return fmt.Sprintf(` data "aws_servicequotas_service" "test" { service_name = %[1]q diff --git a/internal/service/servicequotas/service_quota_data_source_test.go b/internal/service/servicequotas/service_quota_data_source_test.go index 4f1b519faae..0da9f7d854b 100644 --- a/internal/service/servicequotas/service_quota_data_source_test.go +++ b/internal/service/servicequotas/service_quota_data_source_test.go @@ -23,7 +23,7 @@ func TestAccServiceQuotasServiceQuotaDataSource_quotaCode(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaQuotaCodeDataSourceConfig(setQuotaServiceCode, setQuotaQuotaCode), + Config: testAccServiceQuotaDataSourceConfig_code(setQuotaServiceCode, setQuotaQuotaCode), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "adjustable", "true"), acctest.CheckResourceAttrRegionalARN(dataSourceName, "arn", "servicequotas", fmt.Sprintf("%s/%s", setQuotaServiceCode, setQuotaQuotaCode)), @@ -53,7 +53,7 @@ func TestAccServiceQuotasServiceQuotaDataSource_quotaCode_Unset(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaQuotaCodeDataSourceConfig(unsetQuotaServiceCode, unsetQuotaQuotaCode), + Config: testAccServiceQuotaDataSourceConfig_code(unsetQuotaServiceCode, unsetQuotaQuotaCode), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckResourceAttrRegionalARNNoAccount(dataSourceName, "arn", "servicequotas", fmt.Sprintf("%s/%s", unsetQuotaServiceCode, unsetQuotaQuotaCode)), resource.TestCheckResourceAttr(dataSourceName, "adjustable", "true"), @@ -83,7 +83,7 @@ func TestAccServiceQuotasServiceQuotaDataSource_PermissionError_quotaCode(t *tes CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaDataSourceConfig_PermissionError_QuotaCode("elasticloadbalancing", "L-53DA6B97"), + Config: testAccServiceQuotaDataSourceConfig_permissionErrorCode("elasticloadbalancing", "L-53DA6B97"), ExpectError: regexp.MustCompile(`DEPENDENCY_ACCESS_DENIED_ERROR`), }, }, @@ -103,7 +103,7 @@ func TestAccServiceQuotasServiceQuotaDataSource_quotaName(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaQuotaNameDataSourceConfig("vpc", setQuotaQuotaName), + Config: testAccServiceQuotaDataSourceConfig_name("vpc", setQuotaQuotaName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "adjustable", "true"), acctest.CheckResourceAttrRegionalARN(dataSourceName, "arn", "servicequotas", fmt.Sprintf("%s/%s", setQuotaServiceCode, setQuotaQuotaCode)), @@ -133,7 +133,7 @@ func TestAccServiceQuotasServiceQuotaDataSource_quotaName_Unset(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaQuotaNameDataSourceConfig(unsetQuotaServiceCode, unsetQuotaQuotaName), + Config: testAccServiceQuotaDataSourceConfig_name(unsetQuotaServiceCode, unsetQuotaQuotaName), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckResourceAttrRegionalARNNoAccount(dataSourceName, "arn", "servicequotas", fmt.Sprintf("%s/%s", unsetQuotaServiceCode, unsetQuotaQuotaCode)), resource.TestCheckResourceAttr(dataSourceName, "adjustable", "true"), @@ -163,14 +163,14 @@ func TestAccServiceQuotasServiceQuotaDataSource_PermissionError_quotaName(t *tes CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaDataSourceConfig_PermissionError_QuotaName("elasticloadbalancing", "Application Load Balancers per Region"), + Config: testAccServiceQuotaDataSourceConfig_permissionErrorName("elasticloadbalancing", "Application Load Balancers per Region"), ExpectError: regexp.MustCompile(`DEPENDENCY_ACCESS_DENIED_ERROR`), }, }, }) } -func testAccServiceQuotaQuotaCodeDataSourceConfig(serviceCode, quotaCode string) string { +func testAccServiceQuotaDataSourceConfig_code(serviceCode, quotaCode string) string { return fmt.Sprintf(` data "aws_servicequotas_service_quota" "test" { quota_code = %[1]q @@ -179,7 +179,7 @@ data "aws_servicequotas_service_quota" "test" { `, quotaCode, serviceCode) } -func testAccServiceQuotaDataSourceConfig_PermissionError_QuotaCode(serviceCode, quotaCode string) string { +func testAccServiceQuotaDataSourceConfig_permissionErrorCode(serviceCode, quotaCode string) string { policy := `{ "Version": "2012-10-17", "Statement": [ @@ -210,7 +210,7 @@ data "aws_servicequotas_service_quota" "test" { `, serviceCode, quotaCode)) } -func testAccServiceQuotaQuotaNameDataSourceConfig(serviceCode, quotaName string) string { +func testAccServiceQuotaDataSourceConfig_name(serviceCode, quotaName string) string { return fmt.Sprintf(` data "aws_servicequotas_service_quota" "test" { quota_name = %[1]q @@ -219,7 +219,7 @@ data "aws_servicequotas_service_quota" "test" { `, quotaName, serviceCode) } -func testAccServiceQuotaDataSourceConfig_PermissionError_QuotaName(serviceCode, quotaName string) string { +func testAccServiceQuotaDataSourceConfig_permissionErrorName(serviceCode, quotaName string) string { policy := `{ "Version": "2012-10-17", "Statement": [ diff --git a/internal/service/servicequotas/service_quota_test.go b/internal/service/servicequotas/service_quota_test.go index 6cbc309fb5d..4a412149912 100644 --- a/internal/service/servicequotas/service_quota_test.go +++ b/internal/service/servicequotas/service_quota_test.go @@ -30,7 +30,7 @@ func TestAccServiceQuotasServiceQuota_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaSameValueConfig(setQuotaServiceCode, setQuotaQuotaCode), + Config: testAccServiceQuotaConfig_sameValue(setQuotaServiceCode, setQuotaQuotaCode), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "adjustable", dataSourceName, "adjustable"), resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), @@ -67,7 +67,7 @@ func TestAccServiceQuotasServiceQuota_basic_Unset(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaSameValueConfig(unsetQuotaServiceCode, unsetQuotaQuotaCode), + Config: testAccServiceQuotaConfig_sameValue(unsetQuotaServiceCode, unsetQuotaQuotaCode), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "adjustable", dataSourceName, "adjustable"), resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), @@ -120,7 +120,7 @@ func TestAccServiceQuotasServiceQuota_Value_increaseOnCreate(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaValueConfig(serviceCode, quotaCode, value), + Config: testAccServiceQuotaConfig_value(serviceCode, quotaCode, value), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "quota_code", quotaCode), resource.TestCheckResourceAttr(resourceName, "service_code", serviceCode), @@ -164,7 +164,7 @@ func TestAccServiceQuotasServiceQuota_Value_increaseOnUpdate(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaSameValueConfig(serviceCode, quotaCode), + Config: testAccServiceQuotaConfig_sameValue(serviceCode, quotaCode), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "quota_code", quotaCode), resource.TestCheckResourceAttr(resourceName, "service_code", serviceCode), @@ -173,7 +173,7 @@ func TestAccServiceQuotasServiceQuota_Value_increaseOnUpdate(t *testing.T) { ), }, { - Config: testAccServiceQuotaValueConfig(serviceCode, quotaCode, value), + Config: testAccServiceQuotaConfig_value(serviceCode, quotaCode, value), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "quota_code", quotaCode), resource.TestCheckResourceAttr(resourceName, "service_code", serviceCode), @@ -193,7 +193,7 @@ func TestAccServiceQuotasServiceQuota_permissionError(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccServiceQuotaConfig_PermissionError("elasticloadbalancing", "L-53DA6B97"), + Config: testAccServiceQuotaConfig_permissionError("elasticloadbalancing", "L-53DA6B97"), ExpectError: regexp.MustCompile(`DEPENDENCY_ACCESS_DENIED_ERROR`), }, }, @@ -201,7 +201,7 @@ func TestAccServiceQuotasServiceQuota_permissionError(t *testing.T) { } // nosemgrep: servicequotas-in-func-name -func testAccServiceQuotaSameValueConfig(serviceCode, quotaCode string) string { +func testAccServiceQuotaConfig_sameValue(serviceCode, quotaCode string) string { return fmt.Sprintf(` data "aws_servicequotas_service_quota" "test" { quota_code = %[1]q @@ -216,7 +216,7 @@ resource "aws_servicequotas_service_quota" "test" { `, quotaCode, serviceCode) } -func testAccServiceQuotaValueConfig(serviceCode, quotaCode, value string) string { +func testAccServiceQuotaConfig_value(serviceCode, quotaCode, value string) string { return fmt.Sprintf(` resource "aws_servicequotas_service_quota" "test" { quota_code = %[1]q @@ -226,7 +226,7 @@ resource "aws_servicequotas_service_quota" "test" { `, quotaCode, serviceCode, value) } -func testAccServiceQuotaConfig_PermissionError(serviceCode, quotaCode string) string { +func testAccServiceQuotaConfig_permissionError(serviceCode, quotaCode string) string { policy := `{ "Version": "2012-10-17", "Statement": [ diff --git a/internal/service/ses/active_receipt_rule_set_data_source_test.go b/internal/service/ses/active_receipt_rule_set_data_source_test.go index 70d46978bb3..268059b98ed 100644 --- a/internal/service/ses/active_receipt_rule_set_data_source_test.go +++ b/internal/service/ses/active_receipt_rule_set_data_source_test.go @@ -25,7 +25,7 @@ func testAccActiveReceiptRuleSetDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckActiveReceiptRuleSetDestroy, Steps: []resource.TestStep{ { - Config: testAccActiveReceiptRuleSetDataSourceConfig(rName), + Config: testAccActiveReceiptRuleSetDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckActiveReceiptRuleSetExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ses", fmt.Sprintf("receipt-rule-set/%s", rName)), @@ -35,7 +35,7 @@ func testAccActiveReceiptRuleSetDataSource_basic(t *testing.T) { }) } -func testAccActiveReceiptRuleSetDataSourceConfig(name string) string { +func testAccActiveReceiptRuleSetDataSourceConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q diff --git a/internal/service/ses/active_receipt_rule_set_test.go b/internal/service/ses/active_receipt_rule_set_test.go index 346872ea807..5751b8e5358 100644 --- a/internal/service/ses/active_receipt_rule_set_test.go +++ b/internal/service/ses/active_receipt_rule_set_test.go @@ -55,7 +55,7 @@ func testAccActiveReceiptRuleSet_basic(t *testing.T) { CheckDestroy: testAccCheckActiveReceiptRuleSetDestroy, Steps: []resource.TestStep{ { - Config: testAccActiveReceiptRuleSetConfig(rName), + Config: testAccActiveReceiptRuleSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckActiveReceiptRuleSetExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ses", fmt.Sprintf("receipt-rule-set/%s", rName)), @@ -80,7 +80,7 @@ func testAccActiveReceiptRuleSet_disappears(t *testing.T) { CheckDestroy: testAccCheckActiveReceiptRuleSetDestroy, Steps: []resource.TestStep{ { - Config: testAccActiveReceiptRuleSetConfig(rName), + Config: testAccActiveReceiptRuleSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckActiveReceiptRuleSetExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfses.ResourceActiveReceiptRuleSet(), resourceName), @@ -140,7 +140,7 @@ func testAccCheckActiveReceiptRuleSetExists(n string) resource.TestCheckFunc { } } -func testAccActiveReceiptRuleSetConfig(name string) string { +func testAccActiveReceiptRuleSetConfig_basic(name string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q diff --git a/internal/service/ses/configuration_set_test.go b/internal/service/ses/configuration_set_test.go index c06d6c5899e..33927310e8c 100644 --- a/internal/service/ses/configuration_set_test.go +++ b/internal/service/ses/configuration_set_test.go @@ -29,7 +29,7 @@ func TestAccSESConfigurationSet_basic(t *testing.T) { CheckDestroy: testAccCheckConfigurationSetDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationSetBasicConfig(rName), + Config: testAccConfigurationSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ses", fmt.Sprintf("configuration-set/%s", rName)), @@ -63,7 +63,7 @@ func TestAccSESConfigurationSet_sendingEnabled(t *testing.T) { CheckDestroy: testAccCheckConfigurationSetDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationSetSendingConfig(rName, false), + Config: testAccConfigurationSetConfig_sending(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "sending_enabled", "false"), @@ -76,7 +76,7 @@ func TestAccSESConfigurationSet_sendingEnabled(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationSetSendingConfig(rName, true), + Config: testAccConfigurationSetConfig_sending(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "sending_enabled", "true"), @@ -84,7 +84,7 @@ func TestAccSESConfigurationSet_sendingEnabled(t *testing.T) { ), }, { - Config: testAccConfigurationSetSendingConfig(rName, false), + Config: testAccConfigurationSetConfig_sending(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "sending_enabled", "false"), @@ -109,7 +109,7 @@ func TestAccSESConfigurationSet_reputationMetricsEnabled(t *testing.T) { CheckDestroy: testAccCheckConfigurationSetDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationSetReputationMetricsConfig(rName, false), + Config: testAccConfigurationSetConfig_reputationMetrics(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "reputation_metrics_enabled", "false"), @@ -121,14 +121,14 @@ func TestAccSESConfigurationSet_reputationMetricsEnabled(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationSetReputationMetricsConfig(rName, true), + Config: testAccConfigurationSetConfig_reputationMetrics(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "reputation_metrics_enabled", "true"), ), }, { - Config: testAccConfigurationSetReputationMetricsConfig(rName, false), + Config: testAccConfigurationSetConfig_reputationMetrics(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "reputation_metrics_enabled", "false"), @@ -152,7 +152,7 @@ func TestAccSESConfigurationSet_deliveryOptions(t *testing.T) { CheckDestroy: testAccCheckConfigurationSetDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationSetDeliveryOptionsConfig(rName, ses.TlsPolicyRequire), + Config: testAccConfigurationSetConfig_deliveryOptions(rName, ses.TlsPolicyRequire), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "delivery_options.#", "1"), @@ -182,13 +182,13 @@ func TestAccSESConfigurationSet_Update_deliveryOptions(t *testing.T) { CheckDestroy: testAccCheckConfigurationSetDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationSetBasicConfig(rName), + Config: testAccConfigurationSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), ), }, { - Config: testAccConfigurationSetDeliveryOptionsConfig(rName, ses.TlsPolicyRequire), + Config: testAccConfigurationSetConfig_deliveryOptions(rName, ses.TlsPolicyRequire), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "delivery_options.#", "1"), @@ -201,7 +201,7 @@ func TestAccSESConfigurationSet_Update_deliveryOptions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationSetDeliveryOptionsConfig(rName, ses.TlsPolicyOptional), + Config: testAccConfigurationSetConfig_deliveryOptions(rName, ses.TlsPolicyOptional), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "delivery_options.#", "1"), @@ -209,7 +209,7 @@ func TestAccSESConfigurationSet_Update_deliveryOptions(t *testing.T) { ), }, { - Config: testAccConfigurationSetBasicConfig(rName), + Config: testAccConfigurationSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "delivery_options.#", "0"), @@ -238,7 +238,7 @@ func TestAccSESConfigurationSet_emptyDeliveryOptions(t *testing.T) { CheckDestroy: testAccCheckConfigurationSetDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationSetEmptyDeliveryOptionsConfig(rName), + Config: testAccConfigurationSetConfig_emptyDeliveryOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "delivery_options.#", "1"), @@ -268,14 +268,14 @@ func TestAccSESConfigurationSet_Update_emptyDeliveryOptions(t *testing.T) { CheckDestroy: testAccCheckConfigurationSetDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationSetBasicConfig(rName), + Config: testAccConfigurationSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "delivery_options.#", "0"), ), }, { - Config: testAccConfigurationSetEmptyDeliveryOptionsConfig(rName), + Config: testAccConfigurationSetConfig_emptyDeliveryOptions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "delivery_options.#", "1"), @@ -288,7 +288,7 @@ func TestAccSESConfigurationSet_Update_emptyDeliveryOptions(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccConfigurationSetBasicConfig(rName), + Config: testAccConfigurationSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "delivery_options.#", "0"), @@ -317,7 +317,7 @@ func TestAccSESConfigurationSet_disappears(t *testing.T) { CheckDestroy: testAccCheckConfigurationSetDestroy, Steps: []resource.TestStep{ { - Config: testAccConfigurationSetBasicConfig(rName), + Config: testAccConfigurationSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckConfigurationSetExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfses.ResourceConfigurationSet(), resourceName), @@ -379,7 +379,7 @@ func testAccCheckConfigurationSetDestroy(s *terraform.State) error { return nil } -func testAccConfigurationSetBasicConfig(rName string) string { +func testAccConfigurationSetConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ses_configuration_set" "test" { name = %[1]q @@ -387,7 +387,7 @@ resource "aws_ses_configuration_set" "test" { `, rName) } -func testAccConfigurationSetSendingConfig(rName string, enabled bool) string { +func testAccConfigurationSetConfig_sending(rName string, enabled bool) string { return fmt.Sprintf(` resource "aws_ses_configuration_set" "test" { name = %[1]q @@ -396,7 +396,7 @@ resource "aws_ses_configuration_set" "test" { `, rName, enabled) } -func testAccConfigurationSetReputationMetricsConfig(rName string, enabled bool) string { +func testAccConfigurationSetConfig_reputationMetrics(rName string, enabled bool) string { return fmt.Sprintf(` resource "aws_ses_configuration_set" "test" { name = %[1]q @@ -405,7 +405,7 @@ resource "aws_ses_configuration_set" "test" { `, rName, enabled) } -func testAccConfigurationSetDeliveryOptionsConfig(rName, tlsPolicy string) string { +func testAccConfigurationSetConfig_deliveryOptions(rName, tlsPolicy string) string { return fmt.Sprintf(` resource "aws_ses_configuration_set" "test" { name = %[1]q @@ -417,7 +417,7 @@ resource "aws_ses_configuration_set" "test" { `, rName, tlsPolicy) } -func testAccConfigurationSetEmptyDeliveryOptionsConfig(rName string) string { +func testAccConfigurationSetConfig_emptyDeliveryOptions(rName string) string { return fmt.Sprintf(` resource "aws_ses_configuration_set" "test" { name = %[1]q diff --git a/internal/service/ses/domain_dkim_test.go b/internal/service/ses/domain_dkim_test.go index e703db1856a..2c1fce54e9f 100644 --- a/internal/service/ses/domain_dkim_test.go +++ b/internal/service/ses/domain_dkim_test.go @@ -27,7 +27,7 @@ func TestAccSESDomainDKIM_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckDomainDKIMDestroy, Steps: []resource.TestStep{ - { + { // nosemgrep:test-config-funcs-correct-form Config: fmt.Sprintf(testAccDomainDKIMConfig, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainDKIMExists(resourceName), diff --git a/internal/service/ses/domain_identity_data_source_test.go b/internal/service/ses/domain_identity_data_source_test.go index 48112f62417..88977d037fd 100644 --- a/internal/service/ses/domain_identity_data_source_test.go +++ b/internal/service/ses/domain_identity_data_source_test.go @@ -19,7 +19,7 @@ func TestAccSESDomainIdentityDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckDomainIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainIdentityDataSourceConfig(domain), + Config: testAccDomainIdentityDataSourceConfig_basic(domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainIdentityExists("aws_ses_domain_identity.test"), testAccCheckDomainIdentityARN("data.aws_ses_domain_identity.test", domain), @@ -29,7 +29,7 @@ func TestAccSESDomainIdentityDataSource_basic(t *testing.T) { }) } -func testAccDomainIdentityDataSourceConfig(domain string) string { +func testAccDomainIdentityDataSourceConfig_basic(domain string) string { return fmt.Sprintf(` resource "aws_ses_domain_identity" "test" { domain = "%s" diff --git a/internal/service/ses/domain_identity_test.go b/internal/service/ses/domain_identity_test.go index d0f7521a680..4c3b57f0592 100644 --- a/internal/service/ses/domain_identity_test.go +++ b/internal/service/ses/domain_identity_test.go @@ -25,7 +25,7 @@ func TestAccSESDomainIdentity_basic(t *testing.T) { CheckDestroy: testAccCheckDomainIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainIdentityConfig(domain), + Config: testAccDomainIdentityConfig_basic(domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainIdentityExists("aws_ses_domain_identity.test"), testAccCheckDomainIdentityARN("aws_ses_domain_identity.test", domain), @@ -45,7 +45,7 @@ func TestAccSESDomainIdentity_disappears(t *testing.T) { CheckDestroy: testAccCheckDomainIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainIdentityConfig(domain), + Config: testAccDomainIdentityConfig_basic(domain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainIdentityExists("aws_ses_domain_identity.test"), testAccCheckDomainIdentityDisappears(domain), @@ -68,7 +68,7 @@ func TestAccSESDomainIdentity_trailingPeriod(t *testing.T) { CheckDestroy: testAccCheckDomainIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainIdentityConfig(domain), + Config: testAccDomainIdentityConfig_basic(domain), ExpectError: regexp.MustCompile(`invalid value for domain \(cannot end with a period\)`), }, }, @@ -187,7 +187,7 @@ func testAccPreCheck(t *testing.T) { } } -func testAccDomainIdentityConfig(domain string) string { +func testAccDomainIdentityConfig_basic(domain string) string { return fmt.Sprintf(` resource "aws_ses_domain_identity" "test" { domain = "%s" diff --git a/internal/service/ses/domain_identity_verification_test.go b/internal/service/ses/domain_identity_verification_test.go index 7c59acb5da4..32d0609ef85 100644 --- a/internal/service/ses/domain_identity_verification_test.go +++ b/internal/service/ses/domain_identity_verification_test.go @@ -38,7 +38,7 @@ func TestAccSESDomainIdentityVerification_basic(t *testing.T) { CheckDestroy: testAccCheckDomainIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainIdentityVerification_basic(rootDomain, domain), + Config: testAccDomainIdentityVerificationConfig_basic(rootDomain, domain), Check: testAccCheckDomainIdentityVerificationPassed("aws_ses_domain_identity_verification.test"), }, }, @@ -55,7 +55,7 @@ func TestAccSESDomainIdentityVerification_timeout(t *testing.T) { CheckDestroy: testAccCheckDomainIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainIdentityVerification_timeout(domain), + Config: testAccDomainIdentityVerificationConfig_timeout(domain), ExpectError: regexp.MustCompile("Expected domain verification Success, but was in state Pending"), }, }, @@ -72,7 +72,7 @@ func TestAccSESDomainIdentityVerification_nonexistent(t *testing.T) { CheckDestroy: testAccCheckDomainIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainIdentityVerification_nonexistent(domain), + Config: testAccDomainIdentityVerificationConfig_nonexistent(domain), ExpectError: regexp.MustCompile(fmt.Sprintf("SES Domain Identity %s not found in AWS", domain)), }, }, @@ -128,7 +128,7 @@ func testAccCheckDomainIdentityVerificationPassed(n string) resource.TestCheckFu } } -func testAccDomainIdentityVerification_basic(rootDomain string, domain string) string { +func testAccDomainIdentityVerificationConfig_basic(rootDomain string, domain string) string { return fmt.Sprintf(` data "aws_route53_zone" "test" { name = "%s." @@ -155,7 +155,7 @@ resource "aws_ses_domain_identity_verification" "test" { `, rootDomain, domain) } -func testAccDomainIdentityVerification_timeout(domain string) string { +func testAccDomainIdentityVerificationConfig_timeout(domain string) string { return fmt.Sprintf(` resource "aws_ses_domain_identity" "test" { domain = "%s" @@ -171,7 +171,7 @@ resource "aws_ses_domain_identity_verification" "test" { `, domain) } -func testAccDomainIdentityVerification_nonexistent(domain string) string { +func testAccDomainIdentityVerificationConfig_nonexistent(domain string) string { return fmt.Sprintf(` resource "aws_ses_domain_identity_verification" "test" { domain = "%s" diff --git a/internal/service/ses/domain_mail_from_test.go b/internal/service/ses/domain_mail_from_test.go index 650556a131d..e450c605fe9 100644 --- a/internal/service/ses/domain_mail_from_test.go +++ b/internal/service/ses/domain_mail_from_test.go @@ -26,7 +26,7 @@ func TestAccSESDomainMailFrom_basic(t *testing.T) { CheckDestroy: testAccCheckDomainMailFromDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainMailFromConfig(domain, mailFromDomain1), + Config: testAccDomainMailFromConfig_basic(domain, mailFromDomain1), Check: resource.ComposeTestCheckFunc( testAccCheckDomainMailFromExists(resourceName), resource.TestCheckResourceAttr(resourceName, "behavior_on_mx_failure", ses.BehaviorOnMXFailureUseDefaultValue), @@ -35,7 +35,7 @@ func TestAccSESDomainMailFrom_basic(t *testing.T) { ), }, { - Config: testAccDomainMailFromConfig(domain, mailFromDomain2), + Config: testAccDomainMailFromConfig_basic(domain, mailFromDomain2), Check: resource.ComposeTestCheckFunc( testAccCheckDomainMailFromExists(resourceName), resource.TestCheckResourceAttr(resourceName, "behavior_on_mx_failure", ses.BehaviorOnMXFailureUseDefaultValue), @@ -65,7 +65,7 @@ func TestAccSESDomainMailFrom_disappears(t *testing.T) { CheckDestroy: testAccCheckDomainMailFromDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainMailFromConfig(domain, mailFromDomain), + Config: testAccDomainMailFromConfig_basic(domain, mailFromDomain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainMailFromExists(resourceName), testAccCheckDomainMailFromDisappears(domain), @@ -89,7 +89,7 @@ func TestAccSESDomainMailFrom_Disappears_identity(t *testing.T) { CheckDestroy: testAccCheckDomainMailFromDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainMailFromConfig(domain, mailFromDomain), + Config: testAccDomainMailFromConfig_basic(domain, mailFromDomain), Check: resource.ComposeTestCheckFunc( testAccCheckDomainMailFromExists(resourceName), testAccCheckDomainIdentityDisappears(domain), @@ -205,7 +205,7 @@ func testAccCheckDomainMailFromDisappears(identity string) resource.TestCheckFun } } -func testAccDomainMailFromConfig(domain, mailFromDomain string) string { +func testAccDomainMailFromConfig_basic(domain, mailFromDomain string) string { return fmt.Sprintf(` resource "aws_ses_domain_identity" "test" { domain = "%s" diff --git a/internal/service/ses/email_identity_data_dource_test.go b/internal/service/ses/email_identity_data_dource_test.go index 52c7ba8042a..8fd270f174b 100644 --- a/internal/service/ses/email_identity_data_dource_test.go +++ b/internal/service/ses/email_identity_data_dource_test.go @@ -21,7 +21,7 @@ func TestAccSESEmailIdentityDataSource_basic(t *testing.T) { CheckDestroy: testAccCheckEmailIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccEmailIdentityDataSourceConfig(email), + Config: testAccEmailIdentityDataDourceConfig_source(email), Check: resource.ComposeTestCheckFunc( testAccCheckEmailIdentityExists("aws_ses_email_identity.test"), acctest.MatchResourceAttrRegionalARN("data.aws_ses_email_identity.test", "arn", "ses", regexp.MustCompile(fmt.Sprintf("identity/%s$", regexp.QuoteMeta(email)))), @@ -41,7 +41,7 @@ func TestAccSESEmailIdentityDataSource_trailingPeriod(t *testing.T) { CheckDestroy: testAccCheckEmailIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccEmailIdentityDataSourceConfig(email), + Config: testAccEmailIdentityDataDourceConfig_source(email), Check: resource.ComposeTestCheckFunc( testAccCheckEmailIdentityExists("aws_ses_email_identity.test"), acctest.MatchResourceAttrRegionalARN("data.aws_ses_email_identity.test", "arn", "ses", regexp.MustCompile(fmt.Sprintf("identity/%s$", regexp.QuoteMeta(strings.TrimSuffix(email, "."))))), @@ -51,7 +51,7 @@ func TestAccSESEmailIdentityDataSource_trailingPeriod(t *testing.T) { }) } -func testAccEmailIdentityDataSourceConfig(email string) string { +func testAccEmailIdentityDataDourceConfig_source(email string) string { return fmt.Sprintf(` resource "aws_ses_email_identity" "test" { email = %q diff --git a/internal/service/ses/email_identity_test.go b/internal/service/ses/email_identity_test.go index 2fbc3b2075a..8e39a0add60 100644 --- a/internal/service/ses/email_identity_test.go +++ b/internal/service/ses/email_identity_test.go @@ -25,7 +25,7 @@ func TestAccSESEmailIdentity_basic(t *testing.T) { CheckDestroy: testAccCheckEmailIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccEmailIdentityConfig(email), + Config: testAccEmailIdentityConfig_basic(email), Check: resource.ComposeTestCheckFunc( testAccCheckEmailIdentityExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ses", regexp.MustCompile(fmt.Sprintf("identity/%s$", regexp.QuoteMeta(email)))), @@ -51,7 +51,7 @@ func TestAccSESEmailIdentity_trailingPeriod(t *testing.T) { CheckDestroy: testAccCheckEmailIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccEmailIdentityConfig(email), + Config: testAccEmailIdentityConfig_basic(email), Check: resource.ComposeTestCheckFunc( testAccCheckEmailIdentityExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ses", regexp.MustCompile(fmt.Sprintf("identity/%s$", regexp.QuoteMeta(strings.TrimSuffix(email, "."))))), @@ -127,7 +127,7 @@ func testAccCheckEmailIdentityExists(n string) resource.TestCheckFunc { } } -func testAccEmailIdentityConfig(email string) string { +func testAccEmailIdentityConfig_basic(email string) string { return fmt.Sprintf(` resource "aws_ses_email_identity" "test" { email = %q diff --git a/internal/service/ses/event_destination_test.go b/internal/service/ses/event_destination_test.go index d152d0916b7..a7a8733c17a 100644 --- a/internal/service/ses/event_destination_test.go +++ b/internal/service/ses/event_destination_test.go @@ -33,7 +33,7 @@ func TestAccSESEventDestination_basic(t *testing.T) { CheckDestroy: testAccCheckEventDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccEventDestinationConfig(rName1, rName2, rName3), + Config: testAccEventDestinationConfig_basic(rName1, rName2, rName3), Check: resource.ComposeTestCheckFunc( testAccCheckEventDestinationExists(cloudwatchDestinationResourceName, &v1), testAccCheckEventDestinationExists(kinesisDestinationResourceName, &v2), @@ -87,7 +87,7 @@ func TestAccSESEventDestination_disappears(t *testing.T) { CheckDestroy: testAccCheckEventDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccEventDestinationConfig(rName1, rName2, rName3), + Config: testAccEventDestinationConfig_basic(rName1, rName2, rName3), Check: resource.ComposeTestCheckFunc( testAccCheckEventDestinationExists(cloudwatchDestinationResourceName, &v1), testAccCheckEventDestinationExists(kinesisDestinationResourceName, &v2), @@ -164,7 +164,7 @@ func testAccCheckEventDestinationExists(n string, v *ses.EventDestination) resou } } -func testAccEventDestinationConfig(rName1, rName2, rName3 string) string { +func testAccEventDestinationConfig_basic(rName1, rName2, rName3 string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "test" { bucket = %[2]q diff --git a/internal/service/ses/identity_policy_test.go b/internal/service/ses/identity_policy_test.go index cdea522bfba..fbb6b47fcee 100644 --- a/internal/service/ses/identity_policy_test.go +++ b/internal/service/ses/identity_policy_test.go @@ -25,7 +25,7 @@ func TestAccSESIdentityPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckIdentityPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccIdentityPolicyIdentityDomainConfig(domain), + Config: testAccIdentityPolicyConfig_domain(domain), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityPolicyExists(resourceName), ), @@ -51,7 +51,7 @@ func TestAccSESIdentityPolicy_Identity_email(t *testing.T) { CheckDestroy: testAccCheckIdentityPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccIdentityPolicyIdentityEmailConfig(email), + Config: testAccIdentityPolicyConfig_email(email), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityPolicyExists(resourceName), ), @@ -76,13 +76,13 @@ func TestAccSESIdentityPolicy_policy(t *testing.T) { CheckDestroy: testAccCheckIdentityPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccIdentityPolicyPolicy1Config(domain), + Config: testAccIdentityPolicyConfig_1(domain), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityPolicyExists(resourceName), ), }, { - Config: testAccIdentityPolicyPolicy2Config(domain), + Config: testAccIdentityPolicyConfig_2(domain), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityPolicyExists(resourceName), ), @@ -108,13 +108,13 @@ func TestAccSESIdentityPolicy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckIdentityPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccIdentityPolicyEquivalentConfig(rName, domain), + Config: testAccIdentityPolicyConfig_equivalent(rName, domain), Check: resource.ComposeTestCheckFunc( testAccCheckIdentityPolicyExists(resourceName), ), }, { - Config: testAccIdentityPolicyEquivalent2Config(rName, domain), + Config: testAccIdentityPolicyConfig_equivalent2(rName, domain), PlanOnly: true, }, }, @@ -190,7 +190,7 @@ func testAccCheckIdentityPolicyExists(resourceName string) resource.TestCheckFun } } -func testAccIdentityPolicyIdentityDomainConfig(domain string) string { +func testAccIdentityPolicyConfig_domain(domain string) string { return fmt.Sprintf(` data "aws_iam_policy_document" "test" { statement { @@ -216,7 +216,7 @@ resource "aws_ses_identity_policy" "test" { `, domain) } -func testAccIdentityPolicyIdentityEmailConfig(email string) string { +func testAccIdentityPolicyConfig_email(email string) string { return fmt.Sprintf(` data "aws_iam_policy_document" "test" { statement { @@ -242,7 +242,7 @@ resource "aws_ses_identity_policy" "test" { `, email) } -func testAccIdentityPolicyPolicy1Config(domain string) string { +func testAccIdentityPolicyConfig_1(domain string) string { return fmt.Sprintf(` data "aws_iam_policy_document" "test" { statement { @@ -268,7 +268,7 @@ resource "aws_ses_identity_policy" "test" { `, domain) } -func testAccIdentityPolicyPolicy2Config(domain string) string { +func testAccIdentityPolicyConfig_2(domain string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -298,7 +298,7 @@ resource "aws_ses_identity_policy" "test" { `, domain) } -func testAccIdentityPolicyEquivalentConfig(rName, domain string) string { +func testAccIdentityPolicyConfig_equivalent(rName, domain string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} @@ -330,7 +330,7 @@ resource "aws_ses_identity_policy" "test" { `, domain, rName) } -func testAccIdentityPolicyEquivalent2Config(rName, domain string) string { +func testAccIdentityPolicyConfig_equivalent2(rName, domain string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/ses/receipt_filter_test.go b/internal/service/ses/receipt_filter_test.go index a48b6fdb0e5..b97a2b73533 100644 --- a/internal/service/ses/receipt_filter_test.go +++ b/internal/service/ses/receipt_filter_test.go @@ -25,7 +25,7 @@ func TestAccSESReceiptFilter_basic(t *testing.T) { CheckDestroy: testAccCheckReceiptFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptFilterConfig(rName), + Config: testAccReceiptFilterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptFilterExists(resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ses", fmt.Sprintf("receipt-filter/%s", rName)), @@ -54,7 +54,7 @@ func TestAccSESReceiptFilter_disappears(t *testing.T) { CheckDestroy: testAccCheckReceiptFilterDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptFilterConfig(rName), + Config: testAccReceiptFilterConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptFilterExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfses.ResourceReceiptFilter(), resourceName), @@ -117,7 +117,7 @@ func testAccCheckReceiptFilterExists(n string) resource.TestCheckFunc { } } -func testAccReceiptFilterConfig(rName string) string { +func testAccReceiptFilterConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ses_receipt_filter" "test" { cidr = "10.10.10.10" diff --git a/internal/service/ses/receipt_rule_set_test.go b/internal/service/ses/receipt_rule_set_test.go index 7b1addf2231..de0b324d639 100644 --- a/internal/service/ses/receipt_rule_set_test.go +++ b/internal/service/ses/receipt_rule_set_test.go @@ -26,7 +26,7 @@ func TestAccSESReceiptRuleSet_basic(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleSetDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleSetConfig(rName), + Config: testAccReceiptRuleSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "rule_set_name", rName), @@ -53,7 +53,7 @@ func TestAccSESReceiptRuleSet_disappears(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleSetDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleSetConfig(rName), + Config: testAccReceiptRuleSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleSetExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfses.ResourceReceiptRuleSet(), resourceName), @@ -115,7 +115,7 @@ func testAccCheckReceiptRuleSetExists(n string) resource.TestCheckFunc { } } -func testAccReceiptRuleSetConfig(rName string) string { +func testAccReceiptRuleSetConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %q diff --git a/internal/service/ses/receipt_rule_test.go b/internal/service/ses/receipt_rule_test.go index ce5d2afd7bc..1506842a54c 100644 --- a/internal/service/ses/receipt_rule_test.go +++ b/internal/service/ses/receipt_rule_test.go @@ -33,7 +33,7 @@ func TestAccSESReceiptRule_basic(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleBasicConfig(rName, acctest.DefaultEmailAddress), + Config: testAccReceiptRuleConfig_basic(rName, acctest.DefaultEmailAddress), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -79,7 +79,7 @@ func TestAccSESReceiptRule_s3Action(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleS3ActionConfig(rName), + Config: testAccReceiptRuleConfig_s3Action(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -116,7 +116,7 @@ func TestAccSESReceiptRule_snsAction(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleSNSActionConfig(rName), + Config: testAccReceiptRuleConfig_snsAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "sns_action.#", "1"), @@ -153,7 +153,7 @@ func TestAccSESReceiptRule_snsActionEncoding(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleSNSActionEncodingConfig(rName), + Config: testAccReceiptRuleConfig_snsActionEncoding(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "sns_action.#", "1"), @@ -190,7 +190,7 @@ func TestAccSESReceiptRule_lambdaAction(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleLambdaActionConfig(rName), + Config: testAccReceiptRuleConfig_lambdaAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "lambda_action.#", "1"), @@ -227,7 +227,7 @@ func TestAccSESReceiptRule_stopAction(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleStopActionConfig(rName), + Config: testAccReceiptRuleConfig_stopAction(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "stop_action.#", "1"), @@ -263,7 +263,7 @@ func TestAccSESReceiptRule_order(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleOrderConfig(rName), + Config: testAccReceiptRuleConfig_order(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), resource.TestCheckResourceAttr(resourceName, "name", "second"), @@ -296,7 +296,7 @@ func TestAccSESReceiptRule_actions(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleActionsConfig(rName), + Config: testAccReceiptRuleConfig_actions(rName), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "add_header_action.*", map[string]string{ @@ -339,7 +339,7 @@ func TestAccSESReceiptRule_disappears(t *testing.T) { CheckDestroy: testAccCheckReceiptRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccReceiptRuleBasicConfig(rName, acctest.DefaultEmailAddress), + Config: testAccReceiptRuleConfig_basic(rName, acctest.DefaultEmailAddress), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), acctest.CheckResourceDisappears(acctest.Provider, tfses.ResourceReceiptRuleSet(), ruleSetResourceName), @@ -347,7 +347,7 @@ func TestAccSESReceiptRule_disappears(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: testAccReceiptRuleBasicConfig(rName, acctest.DefaultEmailAddress), + Config: testAccReceiptRuleConfig_basic(rName, acctest.DefaultEmailAddress), Check: resource.ComposeTestCheckFunc( testAccCheckReceiptRuleExists(resourceName, &rule), acctest.CheckResourceDisappears(acctest.Provider, tfses.ResourceReceiptRule(), resourceName), @@ -451,7 +451,7 @@ func testAccPreCheckReceiptRule(t *testing.T) { } } -func testAccReceiptRuleBasicConfig(rName, email string) string { +func testAccReceiptRuleConfig_basic(rName, email string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q @@ -468,7 +468,7 @@ resource "aws_ses_receipt_rule" "test" { `, rName, email) } -func testAccReceiptRuleS3ActionConfig(rName string) string { +func testAccReceiptRuleConfig_s3Action(rName string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q @@ -500,7 +500,7 @@ resource "aws_ses_receipt_rule" "test" { `, rName, acctest.DefaultEmailAddress) } -func testAccReceiptRuleSNSActionConfig(rName string) string { +func testAccReceiptRuleConfig_snsAction(rName string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q @@ -526,7 +526,7 @@ resource "aws_ses_receipt_rule" "test" { `, rName, acctest.DefaultEmailAddress) } -func testAccReceiptRuleSNSActionEncodingConfig(rName string) string { +func testAccReceiptRuleConfig_snsActionEncoding(rName string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q @@ -553,7 +553,7 @@ resource "aws_ses_receipt_rule" "test" { `, rName, acctest.DefaultEmailAddress) } -func testAccReceiptRuleLambdaActionConfig(rName string) string { +func testAccReceiptRuleConfig_lambdaAction(rName string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q @@ -610,7 +610,7 @@ resource "aws_ses_receipt_rule" "test" { `, rName, acctest.DefaultEmailAddress) } -func testAccReceiptRuleStopActionConfig(rName string) string { +func testAccReceiptRuleConfig_stopAction(rName string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q @@ -637,7 +637,7 @@ resource "aws_ses_receipt_rule" "test" { `, rName, acctest.DefaultEmailAddress) } -func testAccReceiptRuleOrderConfig(rName string) string { +func testAccReceiptRuleConfig_order(rName string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q @@ -656,7 +656,7 @@ resource "aws_ses_receipt_rule" "test1" { `, rName) } -func testAccReceiptRuleActionsConfig(rName string) string { +func testAccReceiptRuleConfig_actions(rName string) string { return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { rule_set_name = %[1]q diff --git a/internal/service/ses/template_test.go b/internal/service/ses/template_test.go index bae364ef77a..e360d1949d4 100644 --- a/internal/service/ses/template_test.go +++ b/internal/service/ses/template_test.go @@ -28,7 +28,7 @@ func TestAccSESTemplate_basic(t *testing.T) { CheckDestroy: testAccCheckTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckTemplateResourceBasic1Config(rName), + Config: testAccTemplateConfig_resourceBasic1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -59,7 +59,7 @@ func TestAccSESTemplate_update(t *testing.T) { CheckDestroy: testAccCheckTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckTemplateResourceBasic1Config(rName), + Config: testAccTemplateConfig_resourceBasic1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTemplateExists(resourceName, &template), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ses", fmt.Sprintf("template/%s", rName)), @@ -75,7 +75,7 @@ func TestAccSESTemplate_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCheckTemplateResourceBasic2Config(rName), + Config: testAccTemplateConfig_resourceBasic2(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -85,7 +85,7 @@ func TestAccSESTemplate_update(t *testing.T) { ), }, { - Config: testAccCheckTemplateResourceBasic3Config(rName), + Config: testAccTemplateConfig_resourceBasic3(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -110,7 +110,7 @@ func TestAccSESTemplate_disappears(t *testing.T) { CheckDestroy: testAccCheckTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckTemplateResourceBasic1Config(rName), + Config: testAccTemplateConfig_resourceBasic1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTemplateExists(resourceName, &template), acctest.CheckResourceDisappears(acctest.Provider, tfses.ResourceTemplate(), resourceName), @@ -186,7 +186,7 @@ func testAccCheckTemplateDestroy(s *terraform.State) error { return nil } -func testAccCheckTemplateResourceBasic1Config(name string) string { +func testAccTemplateConfig_resourceBasic1(name string) string { return fmt.Sprintf(` resource "aws_ses_template" "test" { name = "%s" @@ -196,7 +196,7 @@ resource "aws_ses_template" "test" { `, name) } -func testAccCheckTemplateResourceBasic2Config(name string) string { +func testAccTemplateConfig_resourceBasic2(name string) string { return fmt.Sprintf(` resource "aws_ses_template" "test" { name = "%s" @@ -207,7 +207,7 @@ resource "aws_ses_template" "test" { `, name) } -func testAccCheckTemplateResourceBasic3Config(name string) string { +func testAccTemplateConfig_resourceBasic3(name string) string { return fmt.Sprintf(` resource "aws_ses_template" "test" { name = "%s" diff --git a/internal/service/sfn/activity_data_source_test.go b/internal/service/sfn/activity_data_source_test.go index 2cab9921ad8..e0e00470ace 100644 --- a/internal/service/sfn/activity_data_source_test.go +++ b/internal/service/sfn/activity_data_source_test.go @@ -21,7 +21,7 @@ func TestAccSFNActivityDataSource_StepFunctions_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccActivityDataSourceConfig_checkActivityARN(rName), + Config: testAccActivityDataSourceConfig_checkARN(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataName, "id"), resource.TestCheckResourceAttrPair(resourceName, "creation_date", dataName, "creation_date"), @@ -29,7 +29,7 @@ func TestAccSFNActivityDataSource_StepFunctions_basic(t *testing.T) { ), }, { - Config: testAccActivityDataSourceConfig_checkActivityName(rName), + Config: testAccActivityDataSourceConfig_checkName(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataName, "id"), resource.TestCheckResourceAttrPair(resourceName, "creation_date", dataName, "creation_date"), @@ -40,7 +40,7 @@ func TestAccSFNActivityDataSource_StepFunctions_basic(t *testing.T) { }) } -func testAccActivityDataSourceConfig_checkActivityARN(rName string) string { +func testAccActivityDataSourceConfig_checkARN(rName string) string { return fmt.Sprintf(` resource aws_sfn_activity "test" { name = "%s" @@ -52,7 +52,7 @@ data aws_sfn_activity "test" { `, rName) } -func testAccActivityDataSourceConfig_checkActivityName(rName string) string { +func testAccActivityDataSourceConfig_checkName(rName string) string { return fmt.Sprintf(` resource aws_sfn_activity "test" { name = "%s" diff --git a/internal/service/sfn/activity_test.go b/internal/service/sfn/activity_test.go index 2f14f9f5e6c..31815714e32 100644 --- a/internal/service/sfn/activity_test.go +++ b/internal/service/sfn/activity_test.go @@ -26,7 +26,7 @@ func TestAccSFNActivity_basic(t *testing.T) { CheckDestroy: testAccCheckActivityDestroy, Steps: []resource.TestStep{ { - Config: testAccActivityBasicConfig(name), + Config: testAccActivityConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckActivityExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", name), @@ -53,7 +53,7 @@ func TestAccSFNActivity_tags(t *testing.T) { CheckDestroy: testAccCheckActivityDestroy, Steps: []resource.TestStep{ { - Config: testAccActivityBasicTags1Config(name, "key1", "value1"), + Config: testAccActivityConfig_basicTags1(name, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckActivityExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -66,7 +66,7 @@ func TestAccSFNActivity_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccActivityBasicTags2Config(name, "key1", "value1updated", "key2", "value2"), + Config: testAccActivityConfig_basicTags2(name, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckActivityExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -75,7 +75,7 @@ func TestAccSFNActivity_tags(t *testing.T) { ), }, { - Config: testAccActivityBasicTags1Config(name, "key2", "value2"), + Config: testAccActivityConfig_basicTags1(name, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckActivityExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -142,7 +142,7 @@ func testAccCheckActivityDestroy(s *terraform.State) error { return fmt.Errorf("Default error in Step Function Test") } -func testAccActivityBasicConfig(rName string) string { +func testAccActivityConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sfn_activity" "test" { name = "%s" @@ -150,7 +150,7 @@ resource "aws_sfn_activity" "test" { `, rName) } -func testAccActivityBasicTags1Config(rName, tag1Key, tag1Value string) string { +func testAccActivityConfig_basicTags1(rName, tag1Key, tag1Value string) string { return fmt.Sprintf(` resource "aws_sfn_activity" "test" { name = "%s" @@ -162,7 +162,7 @@ resource "aws_sfn_activity" "test" { `, rName, tag1Key, tag1Value) } -func testAccActivityBasicTags2Config(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccActivityConfig_basicTags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return fmt.Sprintf(` resource "aws_sfn_activity" "test" { name = "%s" diff --git a/internal/service/sfn/state_machine_data_source_test.go b/internal/service/sfn/state_machine_data_source_test.go index 0a05b2b0c9a..603637a660f 100644 --- a/internal/service/sfn/state_machine_data_source_test.go +++ b/internal/service/sfn/state_machine_data_source_test.go @@ -21,7 +21,7 @@ func TestAccSFNStateMachineDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccStateMachineDataSourceConfig(rName), + Config: testAccStateMachineDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "id", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "creation_date", dataSourceName, "creation_date"), @@ -35,7 +35,7 @@ func TestAccSFNStateMachineDataSource_basic(t *testing.T) { }) } -func testAccStateMachineDataSourceConfig(rName string) string { +func testAccStateMachineDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_region" "current" {} diff --git a/internal/service/sfn/state_machine_test.go b/internal/service/sfn/state_machine_test.go index 2db41ec89e4..2d29ee4abc8 100644 --- a/internal/service/sfn/state_machine_test.go +++ b/internal/service/sfn/state_machine_test.go @@ -28,7 +28,7 @@ func TestAccSFNStateMachine_createUpdate(t *testing.T) { CheckDestroy: testAccCheckStateMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccStateMachineConfig(rName, 5), + Config: testAccStateMachineConfig_basic(rName, 5), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "states", fmt.Sprintf("stateMachine:%s", rName)), @@ -54,7 +54,7 @@ func TestAccSFNStateMachine_createUpdate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStateMachineConfig(rName, 10), + Config: testAccStateMachineConfig_basic(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "states", fmt.Sprintf("stateMachine:%s", rName)), @@ -89,7 +89,7 @@ func TestAccSFNStateMachine_expressUpdate(t *testing.T) { CheckDestroy: testAccCheckStateMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccStateMachineTypedConfig(rName, "EXPRESS", 5), + Config: testAccStateMachineConfig_typed(rName, "EXPRESS", 5), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "status", sfn.StateMachineStatusActive), @@ -102,7 +102,7 @@ func TestAccSFNStateMachine_expressUpdate(t *testing.T) { ), }, { - Config: testAccStateMachineTypedConfig(rName, "EXPRESS", 10), + Config: testAccStateMachineConfig_typed(rName, "EXPRESS", 10), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "status", sfn.StateMachineStatusActive), @@ -129,7 +129,7 @@ func TestAccSFNStateMachine_standardUpdate(t *testing.T) { CheckDestroy: testAccCheckStateMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccStateMachineTypedConfig(rName, "STANDARD", 5), + Config: testAccStateMachineConfig_typed(rName, "STANDARD", 5), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "status", sfn.StateMachineStatusActive), @@ -142,7 +142,7 @@ func TestAccSFNStateMachine_standardUpdate(t *testing.T) { ), }, { - Config: testAccStateMachineTypedConfig(rName, "STANDARD", 10), + Config: testAccStateMachineConfig_typed(rName, "STANDARD", 10), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "status", sfn.StateMachineStatusActive), @@ -169,7 +169,7 @@ func TestAccSFNStateMachine_tags(t *testing.T) { CheckDestroy: testAccCheckStateMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccStateMachineTags1Config(rName, "key1", "value1"), + Config: testAccStateMachineConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -182,7 +182,7 @@ func TestAccSFNStateMachine_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStateMachineTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccStateMachineConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -191,7 +191,7 @@ func TestAccSFNStateMachine_tags(t *testing.T) { ), }, { - Config: testAccStateMachineTags1Config(rName, "key2", "value2"), + Config: testAccStateMachineConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -214,7 +214,7 @@ func TestAccSFNStateMachine_tracing(t *testing.T) { CheckDestroy: testAccCheckStateMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccStateMachineTracingDisableConfig(rName), + Config: testAccStateMachineConfig_tracingDisable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "tracing_configuration.#", "1"), @@ -227,7 +227,7 @@ func TestAccSFNStateMachine_tracing(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStateMachineTracingEnableConfig(rName), + Config: testAccStateMachineConfig_tracingEnable(rName), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "tracing_configuration.#", "1"), @@ -250,7 +250,7 @@ func TestAccSFNStateMachine_disappears(t *testing.T) { CheckDestroy: testAccCheckStateMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccStateMachineConfig(rName, 5), + Config: testAccStateMachineConfig_basic(rName, 5), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), acctest.CheckResourceDisappears(acctest.Provider, tfsfn.ResourceStateMachine(), resourceName), @@ -273,7 +273,7 @@ func TestAccSFNStateMachine_expressLogging(t *testing.T) { CheckDestroy: testAccCheckStateMachineDestroy, Steps: []resource.TestStep{ { - Config: testAccStateMachineExpressLogConfigurationConfig(rName, sfn.LogLevelError), + Config: testAccStateMachineConfig_expressLogConfiguration(rName, sfn.LogLevelError), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "status", sfn.StateMachineStatusActive), @@ -287,7 +287,7 @@ func TestAccSFNStateMachine_expressLogging(t *testing.T) { ), }, { - Config: testAccStateMachineExpressLogConfigurationConfig(rName, sfn.LogLevelAll), + Config: testAccStateMachineConfig_expressLogConfiguration(rName, sfn.LogLevelAll), Check: resource.ComposeTestCheckFunc( testAccCheckExists(resourceName, &sm), resource.TestCheckResourceAttr(resourceName, "status", sfn.StateMachineStatusActive), @@ -452,7 +452,7 @@ EOF `, rName) } -func testAccStateMachineConfig(rName string, rMaxAttempts int) string { +func testAccStateMachineConfig_basic(rName string, rMaxAttempts int) string { return acctest.ConfigCompose(testAccStateMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_sfn_state_machine" "test" { name = %[1]q @@ -485,7 +485,7 @@ EOF `, rName, rMaxAttempts)) } -func testAccStateMachineTags1Config(rName, tag1Key, tag1Value string) string { +func testAccStateMachineConfig_tags1(rName, tag1Key, tag1Value string) string { return acctest.ConfigCompose(testAccStateMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_sfn_state_machine" "test" { name = %[1]q @@ -522,7 +522,7 @@ EOF `, rName, tag1Key, tag1Value)) } -func testAccStateMachineTags2Config(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccStateMachineConfig_tags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return acctest.ConfigCompose(testAccStateMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_sfn_state_machine" "test" { name = %[1]q @@ -560,7 +560,7 @@ EOF `, rName, tag1Key, tag1Value, tag2Key, tag2Value)) } -func testAccStateMachineTypedConfig(rName, rType string, rMaxAttempts int) string { +func testAccStateMachineConfig_typed(rName, rType string, rMaxAttempts int) string { return acctest.ConfigCompose(testAccStateMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_sfn_state_machine" "test" { name = %[1]q @@ -592,7 +592,7 @@ EOF `, rName, rType, rMaxAttempts)) } -func testAccStateMachineExpressLogConfigurationConfig(rName string, rLevel string) string { +func testAccStateMachineConfig_expressLogConfiguration(rName string, rLevel string) string { return acctest.ConfigCompose(testAccStateMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = %[1]q @@ -636,7 +636,7 @@ EOF `, rName, rLevel)) } -func testAccStateMachineTracingEnableConfig(rName string) string { +func testAccStateMachineConfig_tracingEnable(rName string) string { return acctest.ConfigCompose(testAccStateMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_sfn_state_machine" "test" { name = %[1]q @@ -673,7 +673,7 @@ EOF `, rName)) } -func testAccStateMachineTracingDisableConfig(rName string) string { +func testAccStateMachineConfig_tracingDisable(rName string) string { return acctest.ConfigCompose(testAccStateMachineBaseConfig(rName), fmt.Sprintf(` resource "aws_sfn_state_machine" "test" { name = %[1]q diff --git a/internal/service/signer/signing_job_data_source_test.go b/internal/service/signer/signing_job_data_source_test.go index 8b606cbc255..343bac22704 100644 --- a/internal/service/signer/signing_job_data_source_test.go +++ b/internal/service/signer/signing_job_data_source_test.go @@ -21,7 +21,7 @@ func TestAccSignerSigningJobDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSigningJobBasicDataSourceConfig(rName), + Config: testAccSigningJobDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "status", resourceName, "status"), resource.TestCheckResourceAttrPair(dataSourceName, "job_owner", resourceName, "job_owner"), @@ -33,7 +33,7 @@ func TestAccSignerSigningJobDataSource_basic(t *testing.T) { }) } -func testAccSigningJobBasicDataSourceConfig(rName string) string { +func testAccSigningJobDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/signer/signing_job_test.go b/internal/service/signer/signing_job_test.go index 88ff369d965..d54c170551c 100644 --- a/internal/service/signer/signing_job_test.go +++ b/internal/service/signer/signing_job_test.go @@ -28,7 +28,7 @@ func TestAccSignerSigningJob_basic(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccSigningJobConfig(rName), + Config: testAccSigningJobConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(profileResourceName, &conf), testAccCheckSigningJobExists(resourceName, &job), @@ -42,7 +42,7 @@ func TestAccSignerSigningJob_basic(t *testing.T) { } -func testAccSigningJobConfig(rName string) string { +func testAccSigningJobConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} diff --git a/internal/service/signer/signing_profile_data_source_test.go b/internal/service/signer/signing_profile_data_source_test.go index acbd935a26b..a27a429f2b5 100644 --- a/internal/service/signer/signing_profile_data_source_test.go +++ b/internal/service/signer/signing_profile_data_source_test.go @@ -22,7 +22,7 @@ func TestAccSignerSigningProfileDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSigningProfileBasicDataSourceConfig(profileName), + Config: testAccSigningProfileDataSourceConfig_basic(profileName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(dataSourceName, "platform_id", resourceName, "platform_id"), @@ -38,7 +38,7 @@ func TestAccSignerSigningProfileDataSource_basic(t *testing.T) { }) } -func testAccSigningProfileBasicDataSourceConfig(profileName string) string { +func testAccSigningProfileDataSourceConfig_basic(profileName string) string { return fmt.Sprintf(` resource "aws_signer_signing_profile" "test" { platform_id = "AWSLambda-SHA384-ECDSA" diff --git a/internal/service/signer/signing_profile_permission_test.go b/internal/service/signer/signing_profile_permission_test.go index 7d8f537ddbd..49bc235ffd9 100644 --- a/internal/service/signer/signing_profile_permission_test.go +++ b/internal/service/signer/signing_profile_permission_test.go @@ -30,7 +30,7 @@ func TestAccSignerSigningProfilePermission_basic(t *testing.T) { CheckDestroy: testAccCheckSigningProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSigningProfilePermissionConfig(profileName), + Config: testAccSigningProfilePermissionConfig_basic(profileName), Destroy: false, Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(profileResourceName, &conf), @@ -64,7 +64,7 @@ func TestAccSignerSigningProfilePermission_getSigningProfile(t *testing.T) { CheckDestroy: testAccCheckSigningProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSigningProfilePermissionGetSP(profileName), + Config: testAccSigningProfilePermissionConfig_getSP(profileName), Destroy: false, Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(profileResourceName, &conf), @@ -78,7 +78,7 @@ func TestAccSignerSigningProfilePermission_getSigningProfile(t *testing.T) { ImportStateVerifyIgnore: []string{"name_prefix"}, }, { - Config: testAccSigningProfilePermissionRevokeSignature(profileName), + Config: testAccSigningProfilePermissionConfig_revokeSignature(profileName), Destroy: false, Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(profileResourceName, &conf), @@ -106,7 +106,7 @@ func TestAccSignerSigningProfilePermission_StartSigningJob_getSP(t *testing.T) { CheckDestroy: testAccCheckSigningProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSigningProfilePermissionStartSigningJobGetSP(profileName), + Config: testAccSigningProfilePermissionConfig_startJobGetSP(profileName), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(profileResourceName, &conf), testAccCheckSigningProfilePermissionExists(resourceName1, profileName, &sppconf), @@ -140,7 +140,7 @@ func TestAccSignerSigningProfilePermission_statementPrefix(t *testing.T) { CheckDestroy: testAccCheckSigningProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSigningProfilePermissionStatementPrefix(statementNamePrefix, profileName), + Config: testAccSigningProfilePermissionConfig_statementPrefix(statementNamePrefix, profileName), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfilePermissionExists(resourceName, profileName, &sppconf), create.TestCheckResourceAttrNameFromPrefix(resourceName, "statement_id", statementNamePrefix), @@ -156,7 +156,7 @@ func TestAccSignerSigningProfilePermission_statementPrefix(t *testing.T) { }) } -func testAccSigningProfilePermissionConfig(profileName string) string { +func testAccSigningProfilePermissionConfig_basic(profileName string) string { return fmt.Sprintf(testAccSigningProfilePermissionConfig_base(profileName) + ` data "aws_caller_identity" "current" {} @@ -167,7 +167,7 @@ resource "aws_signer_signing_profile_permission" "test_sp_permission" { }`) } -func testAccSigningProfilePermissionStartSigningJobGetSP(profileName string) string { +func testAccSigningProfilePermissionConfig_startJobGetSP(profileName string) string { return fmt.Sprintf(testAccSigningProfilePermissionConfig_base(profileName) + ` data "aws_caller_identity" "current" {} @@ -186,7 +186,7 @@ resource "aws_signer_signing_profile_permission" "sp2_perm" { }`) } -func testAccSigningProfilePermissionStatementPrefix(statementNamePrefix, profileName string) string { +func testAccSigningProfilePermissionConfig_statementPrefix(statementNamePrefix, profileName string) string { return fmt.Sprintf(testAccSigningProfilePermissionConfig_base(profileName)+` data "aws_caller_identity" "current" {} @@ -198,7 +198,7 @@ resource "aws_signer_signing_profile_permission" "sp1_perm" { }`, statementNamePrefix) } -func testAccSigningProfilePermissionGetSP(profileName string) string { +func testAccSigningProfilePermissionConfig_getSP(profileName string) string { return fmt.Sprintf(testAccSigningProfilePermissionConfig_base(profileName) + ` data "aws_caller_identity" "current" {} @@ -209,7 +209,7 @@ resource "aws_signer_signing_profile_permission" "test_sp_permission" { }`) } -func testAccSigningProfilePermissionRevokeSignature(profileName string) string { +func testAccSigningProfilePermissionConfig_revokeSignature(profileName string) string { return fmt.Sprintf(testAccSigningProfilePermissionConfig_base(profileName) + ` data "aws_caller_identity" "current" {} diff --git a/internal/service/signer/signing_profile_test.go b/internal/service/signer/signing_profile_test.go index 27a01a7a9a5..19c36d3054e 100644 --- a/internal/service/signer/signing_profile_test.go +++ b/internal/service/signer/signing_profile_test.go @@ -29,7 +29,7 @@ func TestAccSignerSigningProfile_basic(t *testing.T) { CheckDestroy: testAccCheckSigningProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSigningProfileProvidedNameConfig(profileName), + Config: testAccSigningProfileConfig_providedName(profileName), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(resourceName, &conf), resource.TestMatchResourceAttr(resourceName, "name", @@ -60,7 +60,7 @@ func TestAccSignerSigningProfile_generateNameWithNamePrefix(t *testing.T) { CheckDestroy: testAccCheckSigningProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSigningProfileConfig(namePrefix), + Config: testAccSigningProfileConfig_basic(namePrefix), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "platform_id", "AWSLambda-SHA384-ECDSA"), @@ -82,7 +82,7 @@ func TestAccSignerSigningProfile_generateName(t *testing.T) { CheckDestroy: testAccCheckSigningProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSigningProfileGenerateNameConfig(), + Config: testAccSigningProfileConfig_generateName(), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "platform_id", "AWSLambda-SHA384-ECDSA"), @@ -105,7 +105,7 @@ func TestAccSignerSigningProfile_tags(t *testing.T) { CheckDestroy: testAccCheckSigningProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSigningProfileTagsConfig(namePrefix), + Config: testAccSigningProfileConfig_tags(namePrefix), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.tag1", "value1"), @@ -113,7 +113,7 @@ func TestAccSignerSigningProfile_tags(t *testing.T) { ), }, { - Config: testAccSigningProfileUpdateTags(), + Config: testAccSigningProfileConfig_updateTags(), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.tag1", "prod"), @@ -136,7 +136,7 @@ func TestAccSignerSigningProfile_signatureValidityPeriod(t *testing.T) { CheckDestroy: testAccCheckSigningProfileDestroy, Steps: []resource.TestStep{ { - Config: testAccSigningProfileSVPConfig(namePrefix), + Config: testAccSigningProfileConfig_svp(namePrefix), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "signature_validity_period.0.type", "DAYS"), @@ -144,7 +144,7 @@ func TestAccSignerSigningProfile_signatureValidityPeriod(t *testing.T) { ), }, { - Config: testAccSigningProfileUpdateSVP(), + Config: testAccSigningProfileConfig_updateSVP(), Check: resource.ComposeTestCheckFunc( testAccCheckSigningProfileExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "signature_validity_period.0.type", "MONTHS"), @@ -187,18 +187,18 @@ func testAccPreCheckSingerSigningProfile(t *testing.T, platformID string) { t.Skipf("skipping acceptance testing: Signing Platform (%s) not found", platformID) } -func testAccSigningProfileConfig(namePrefix string) string { +func testAccSigningProfileConfig_basic(namePrefix string) string { return testAccSigningProfileBaseConfig(namePrefix) } -func testAccSigningProfileGenerateNameConfig() string { +func testAccSigningProfileConfig_generateName() string { return ` resource "aws_signer_signing_profile" "test_sp" { platform_id = "AWSLambda-SHA384-ECDSA" }` } -func testAccSigningProfileProvidedNameConfig(profileName string) string { +func testAccSigningProfileConfig_providedName(profileName string) string { return fmt.Sprintf(` resource "aws_signer_signing_profile" "test_sp" { platform_id = "AWSLambda-SHA384-ECDSA" @@ -206,7 +206,7 @@ resource "aws_signer_signing_profile" "test_sp" { }`, profileName) } -func testAccSigningProfileTagsConfig(namePrefix string) string { +func testAccSigningProfileConfig_tags(namePrefix string) string { return fmt.Sprintf(` resource "aws_signer_signing_profile" "test_sp" { platform_id = "AWSLambda-SHA384-ECDSA" @@ -218,7 +218,7 @@ resource "aws_signer_signing_profile" "test_sp" { }`, namePrefix) } -func testAccSigningProfileSVPConfig(namePrefix string) string { +func testAccSigningProfileConfig_svp(namePrefix string) string { return fmt.Sprintf(` resource "aws_signer_signing_profile" "test_sp" { platform_id = "AWSLambda-SHA384-ECDSA" @@ -232,7 +232,7 @@ resource "aws_signer_signing_profile" "test_sp" { `, namePrefix) } -func testAccSigningProfileUpdateSVP() string { +func testAccSigningProfileConfig_updateSVP() string { return ` resource "aws_signer_signing_profile" "test_sp" { platform_id = "AWSLambda-SHA384-ECDSA" @@ -245,7 +245,7 @@ resource "aws_signer_signing_profile" "test_sp" { ` } -func testAccSigningProfileUpdateTags() string { +func testAccSigningProfileConfig_updateTags() string { return ` resource "aws_signer_signing_profile" "test_sp" { platform_id = "AWSLambda-SHA384-ECDSA" diff --git a/internal/service/simpledb/domain_test.go b/internal/service/simpledb/domain_test.go index 47b3238d271..e4038497ce0 100644 --- a/internal/service/simpledb/domain_test.go +++ b/internal/service/simpledb/domain_test.go @@ -23,7 +23,7 @@ func TestAccSimpleDBDomain_basic(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig, + Config: testAccDomainConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(resourceName), ), @@ -83,7 +83,7 @@ func testAccCheckDomainExists(n string) resource.TestCheckFunc { } } -var testAccDomainConfig = ` +var testAccDomainConfig_basic = ` resource "aws_simpledb_domain" "test_domain" { name = "terraform-test-domain" } diff --git a/internal/service/sns/sms_preferences.go b/internal/service/sns/sms_preferences.go index 6977b428494..aa6bddd2ca4 100644 --- a/internal/service/sns/sms_preferences.go +++ b/internal/service/sns/sms_preferences.go @@ -138,7 +138,7 @@ func ResourceSMSPreferences() *schema.Resource { func resourceSMSPreferencesSet(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SNSConn - attributes, err := SMSPreferencesAttributeMap.ResourceDataToApiAttributesCreate(d) + attributes, err := SMSPreferencesAttributeMap.ResourceDataToAPIAttributesCreate(d) if err != nil { return err @@ -167,7 +167,7 @@ func resourceSMSPreferencesGet(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error getting SNS SMS Preferences: %w", err) } - err = SMSPreferencesAttributeMap.ApiAttributesToResourceData(aws.StringValueMap(output.Attributes), d) + err = SMSPreferencesAttributeMap.APIAttributesToResourceData(aws.StringValueMap(output.Attributes), d) if err != nil { return err @@ -181,7 +181,7 @@ func resourceSMSPreferencesDelete(d *schema.ResourceData, meta interface{}) erro // Reset the attributes to their default value. attributes := make(map[string]string) - for _, apiAttributeName := range SMSPreferencesAttributeMap.ApiAttributeNames() { + for _, apiAttributeName := range SMSPreferencesAttributeMap.APIAttributeNames() { attributes[apiAttributeName] = "" } diff --git a/internal/service/sns/sms_preferences_test.go b/internal/service/sns/sms_preferences_test.go index 9eb73b03e76..d81ca0eb4fd 100644 --- a/internal/service/sns/sms_preferences_test.go +++ b/internal/service/sns/sms_preferences_test.go @@ -41,7 +41,7 @@ func testAccSMSPreferences_defaultSMSType(t *testing.T) { CheckDestroy: testAccCheckSMSPrefsDestroy, Steps: []resource.TestStep{ { - Config: testAccSMSPreferencesConfig_defSMSType, + Config: testAccSMSPreferencesConfig_defType, Check: resource.ComposeTestCheckFunc( resource.TestCheckNoResourceAttr(resourceName, "monthly_spend_limit"), resource.TestCheckNoResourceAttr(resourceName, "delivery_status_iam_role_arn"), @@ -116,7 +116,7 @@ func testAccCheckSMSPrefsDestroy(s *terraform.State) error { var attrErrs *multierror.Error // The API is returning undocumented keys, e.g. "UsageReportS3Enabled". Only check the keys we're aware of. - for _, snsAttrName := range tfsns.SMSPreferencesAttributeMap.ApiAttributeNames() { + for _, snsAttrName := range tfsns.SMSPreferencesAttributeMap.APIAttributeNames() { v := aws.StringValue(attrs.Attributes[snsAttrName]) if snsAttrName != "MonthlySpendLimit" { if v != "" { @@ -131,7 +131,7 @@ func testAccCheckSMSPrefsDestroy(s *terraform.State) error { return nil } -const testAccSMSPreferencesConfig_defSMSType = ` +const testAccSMSPreferencesConfig_defType = ` resource "aws_sns_sms_preferences" "test" { default_sms_type = "Transactional" } diff --git a/internal/service/sns/topic.go b/internal/service/sns/topic.go index c2f30e73dc3..9b8d8f84db2 100644 --- a/internal/service/sns/topic.go +++ b/internal/service/sns/topic.go @@ -227,7 +227,7 @@ func resourceTopicCreate(d *schema.ResourceData, meta interface{}) error { Name: aws.String(name), } - attributes, err := topicAttributeMap.ResourceDataToApiAttributesCreate(d) + attributes, err := topicAttributeMap.ResourceDataToAPIAttributesCreate(d) if err != nil { return err @@ -250,7 +250,7 @@ func resourceTopicCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateTopic(input) // Some partitions may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating SNS Topic (%s) with tags: %s. Trying create without tags.", name, err) input.Tags = nil output, err = conn.CreateTopic(input) @@ -272,7 +272,7 @@ func resourceTopicCreate(d *schema.ResourceData, meta interface{}) error { if input.Tags == nil && len(tags) > 0 { err := UpdateTags(conn, d.Id(), nil, tags) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // if default tags only, log and continue (i.e., should error if explicitly setting tags and they can't be) log.Printf("[WARN] failed adding tags after create for SNS Topic (%s): %s", d.Id(), err) return resourceTopicRead(d, meta) @@ -303,7 +303,7 @@ func resourceTopicRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error reading SNS Topic (%s): %w", d.Id(), err) } - err = topicAttributeMap.ApiAttributesToResourceData(attributes, d) + err = topicAttributeMap.APIAttributesToResourceData(attributes, d) if err != nil { return err @@ -325,7 +325,7 @@ func resourceTopicRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, d.Id()) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // ISO partitions may not support tagging, giving error log.Printf("[WARN] failed listing tags for SNS Topic (%s): %s", d.Id(), err) return nil @@ -353,7 +353,7 @@ func resourceTopicUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SNSConn if d.HasChangesExcept("tags", "tags_all") { - attributes, err := topicAttributeMap.ResourceDataToApiAttributesUpdate(d) + attributes, err := topicAttributeMap.ResourceDataToAPIAttributesUpdate(d) if err != nil { return err @@ -371,7 +371,7 @@ func resourceTopicUpdate(d *schema.ResourceData, meta interface{}) error { err := UpdateTags(conn, d.Id(), o, n) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // ISO partitions may not support tagging, giving error log.Printf("[WARN] failed updating tags for SNS Topic (%s): %s", d.Id(), err) return resourceTopicRead(d, meta) diff --git a/internal/service/sns/topic_data_source_test.go b/internal/service/sns/topic_data_source_test.go index d2aa22ee4a3..a3f6196479d 100644 --- a/internal/service/sns/topic_data_source_test.go +++ b/internal/service/sns/topic_data_source_test.go @@ -21,7 +21,7 @@ func TestAccSNSTopicDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccTopicDataSourceConfig(rName), + Config: testAccTopicDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(datasourceName, "arn", resourceName, "arn"), @@ -31,7 +31,7 @@ func TestAccSNSTopicDataSource_basic(t *testing.T) { }) } -func testAccTopicDataSourceConfig(rName string) string { +func testAccTopicDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q diff --git a/internal/service/sns/topic_policy_test.go b/internal/service/sns/topic_policy_test.go index 4b90f67d24d..a8bea5f8ba0 100644 --- a/internal/service/sns/topic_policy_test.go +++ b/internal/service/sns/topic_policy_test.go @@ -27,7 +27,7 @@ func TestAccSNSTopicPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckTopicPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicPolicyBasicConfig(rName), + Config: testAccTopicPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists("aws_sns_topic.test", &attributes), resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_sns_topic.test", "arn"), @@ -57,7 +57,7 @@ func TestAccSNSTopicPolicy_updated(t *testing.T) { CheckDestroy: testAccCheckTopicPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicPolicyBasicConfig(rName), + Config: testAccTopicPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists("aws_sns_topic.test", &attributes), resource.TestMatchResourceAttr(resourceName, "policy", @@ -70,7 +70,7 @@ func TestAccSNSTopicPolicy_updated(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTopicPolicyUpdatedConfig(rName), + Config: testAccTopicPolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists("aws_sns_topic.test", &attributes), resource.TestMatchResourceAttr(resourceName, "policy", @@ -95,7 +95,7 @@ func TestAccSNSTopicPolicy_Disappears_topic(t *testing.T) { CheckDestroy: testAccCheckTopicPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicPolicyBasicConfig(rName), + Config: testAccTopicPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(topicResourceName, &attributes), acctest.CheckResourceDisappears(acctest.Provider, tfsns.ResourceTopic(), topicResourceName), @@ -118,7 +118,7 @@ func TestAccSNSTopicPolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckTopicPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicPolicyBasicConfig(rName), + Config: testAccTopicPolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists("aws_sns_topic.test", &attributes), acctest.CheckResourceDisappears(acctest.Provider, tfsns.ResourceTopicPolicy(), resourceName), @@ -141,7 +141,7 @@ func TestAccSNSTopicPolicy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckTopicPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicPolicyEquivalentConfig(rName), + Config: testAccTopicPolicyConfig_equivalent(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists("aws_sns_topic.test", &attributes), resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_sns_topic.test", "arn"), @@ -151,7 +151,7 @@ func TestAccSNSTopicPolicy_ignoreEquivalent(t *testing.T) { ), }, { - Config: testAccTopicPolicyEquivalent2Config(rName), + Config: testAccTopicPolicyConfig_equivalent2(rName), PlanOnly: true, }, }, @@ -182,7 +182,7 @@ func testAccCheckTopicPolicyDestroy(s *terraform.State) error { return nil } -func testAccTopicPolicyBasicConfig(rName string) string { +func testAccTopicPolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -216,7 +216,7 @@ POLICY `, rName) } -func testAccTopicPolicyUpdatedConfig(rName string) string { +func testAccTopicPolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -251,7 +251,7 @@ POLICY `, rName) } -func testAccTopicPolicyEquivalentConfig(rName string) string { +func testAccTopicPolicyConfig_equivalent(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -282,7 +282,7 @@ resource "aws_sns_topic_policy" "test" { `, rName) } -func testAccTopicPolicyEquivalent2Config(rName string) string { +func testAccTopicPolicyConfig_equivalent2(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q diff --git a/internal/service/sns/topic_subscription.go b/internal/service/sns/topic_subscription.go index d03b208028c..3a3cae1e232 100644 --- a/internal/service/sns/topic_subscription.go +++ b/internal/service/sns/topic_subscription.go @@ -133,7 +133,7 @@ func ResourceTopicSubscription() *schema.Resource { func resourceTopicSubscriptionCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SNSConn - attributes, err := subscriptionAttributeMap.ResourceDataToApiAttributesCreate(d) + attributes, err := subscriptionAttributeMap.ResourceDataToAPIAttributesCreate(d) if err != nil { return err @@ -204,7 +204,7 @@ func resourceTopicSubscriptionRead(d *schema.ResourceData, meta interface{}) err attributes := outputRaw.(map[string]string) - err = subscriptionAttributeMap.ApiAttributesToResourceData(attributes, d) + err = subscriptionAttributeMap.APIAttributesToResourceData(attributes, d) if err != nil { return err @@ -216,7 +216,7 @@ func resourceTopicSubscriptionRead(d *schema.ResourceData, meta interface{}) err func resourceTopicSubscriptionUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SNSConn - attributes, err := subscriptionAttributeMap.ResourceDataToApiAttributesUpdate(d) + attributes, err := subscriptionAttributeMap.ResourceDataToAPIAttributesUpdate(d) if err != nil { return err diff --git a/internal/service/sns/topic_subscription_test.go b/internal/service/sns/topic_subscription_test.go index c27e958d96f..d18f965a312 100644 --- a/internal/service/sns/topic_subscription_test.go +++ b/internal/service/sns/topic_subscription_test.go @@ -79,7 +79,7 @@ func TestAccSNSTopicSubscription_basic(t *testing.T) { CheckDestroy: testAccCheckTopicSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicSubscriptionConfig(rName), + Config: testAccTopicSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicSubscriptionExists(resourceName, &attributes), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", sns.ServiceName, regexp.MustCompile(fmt.Sprintf("%s:.+", rName))), @@ -145,7 +145,7 @@ func TestAccSNSTopicSubscription_filterPolicy(t *testing.T) { }, // Test attribute removal { - Config: testAccTopicSubscriptionConfig(rName), + Config: testAccTopicSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicSubscriptionExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "filter_policy", ""), @@ -204,7 +204,7 @@ func TestAccSNSTopicSubscription_deliveryPolicy(t *testing.T) { }, // Test attribute removal { - Config: testAccTopicSubscriptionConfig(rName), + Config: testAccTopicSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicSubscriptionExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "delivery_policy", ""), @@ -262,7 +262,7 @@ func TestAccSNSTopicSubscription_redrivePolicy(t *testing.T) { }, // Test attribute removal { - Config: testAccTopicSubscriptionConfig(rName), + Config: testAccTopicSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicSubscriptionExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "redrive_policy", ""), @@ -309,7 +309,7 @@ func TestAccSNSTopicSubscription_rawMessageDelivery(t *testing.T) { }, // Test attribute removal { - Config: testAccTopicSubscriptionConfig(rName), + Config: testAccTopicSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicSubscriptionExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "raw_message_delivery", "false"), @@ -391,7 +391,7 @@ func TestAccSNSTopicSubscription_email(t *testing.T) { CheckDestroy: testAccCheckTopicSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicSubscriptionEmailConfig(rName, acctest.DefaultEmailAddress), + Config: testAccTopicSubscriptionConfig_email(rName, acctest.DefaultEmailAddress), Check: resource.ComposeTestCheckFunc( testAccCheckTopicSubscriptionExists(resourceName, &attributes), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", sns.ServiceName, regexp.MustCompile(fmt.Sprintf("%s:.+", rName))), @@ -450,7 +450,7 @@ func TestAccSNSTopicSubscription_disappears(t *testing.T) { CheckDestroy: testAccCheckTopicSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicSubscriptionConfig(rName), + Config: testAccTopicSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicSubscriptionExists(resourceName, &attributes), acctest.CheckResourceDisappears(acctest.Provider, tfsns.ResourceTopicSubscription(), resourceName), @@ -473,7 +473,7 @@ func TestAccSNSTopicSubscription_Disappears_topic(t *testing.T) { CheckDestroy: testAccCheckTopicSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicSubscriptionConfig(rName), + Config: testAccTopicSubscriptionConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicSubscriptionExists(resourceName, &attributes), acctest.CheckResourceDisappears(acctest.Provider, tfsns.ResourceTopic(), "aws_sns_topic.test"), @@ -625,7 +625,7 @@ func TestObfuscateEndpointPassword(t *testing.T) { } } -func testAccTopicSubscriptionConfig(rName string) string { +func testAccTopicSubscriptionConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -1050,7 +1050,7 @@ resource "aws_sns_topic_subscription" "test" { `, rName) } -func testAccTopicSubscriptionEmailConfig(rName, email string) string { +func testAccTopicSubscriptionConfig_email(rName, email string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q diff --git a/internal/service/sns/topic_test.go b/internal/service/sns/topic_test.go index 5deac2969b4..4198df40f07 100644 --- a/internal/service/sns/topic_test.go +++ b/internal/service/sns/topic_test.go @@ -41,7 +41,7 @@ func TestAccSNSTopic_basic(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicNameGeneratedConfig, + Config: testAccTopicConfig_nameGenerated, Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "application_failure_feedback_role_arn", ""), @@ -93,7 +93,7 @@ func TestAccSNSTopic_name(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicNameConfig(rName), + Config: testAccTopicConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -121,7 +121,7 @@ func TestAccSNSTopic_namePrefix(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicNamePrefixConfig(rName), + Config: testAccTopicConfig_namePrefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", rName), @@ -151,7 +151,7 @@ func TestAccSNSTopic_policy(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicWithPolicy(rName), + Config: testAccTopicConfig_policy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), testAccCheckNSTopicHasPolicy(resourceName, expectedPolicy), @@ -178,7 +178,7 @@ func TestAccSNSTopic_withIAMRole(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicConfig_withIAMRole(rName), + Config: testAccTopicConfig_iamRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), ), @@ -201,7 +201,7 @@ func TestAccSNSTopic_withFakeIAMRole(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicConfig_withFakeIAMRole(rName), + Config: testAccTopicConfig_fakeIAMRole(rName), ExpectError: regexp.MustCompile(`PrincipalNotFound`), }, }, @@ -221,7 +221,7 @@ func TestAccSNSTopic_withDeliveryPolicy(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicConfig_withDeliveryPolicy(rName), + Config: testAccTopicConfig_deliveryPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), testAccCheckNSTopicHasDeliveryPolicy(resourceName, expectedPolicy), @@ -290,7 +290,7 @@ func TestAccSNSTopic_NameGenerated_fifoTopic(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicNameGeneratedFIFOTopicConfig, + Config: testAccTopicConfig_nameGeneratedFIFO, Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), create.TestCheckResourceAttrNameWithSuffixGenerated(resourceName, "name", tfsns.FIFOTopicNameSuffix), @@ -319,7 +319,7 @@ func TestAccSNSTopic_Name_fifoTopic(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicNameFIFOTopicConfig(rName), + Config: testAccTopicConfig_nameFIFO(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -347,7 +347,7 @@ func TestAccSNSTopic_NamePrefix_fifoTopic(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicNamePrefixFIFOTopicConfig(rName), + Config: testAccTopicConfig_namePrefixFIFO(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), create.TestCheckResourceAttrNameWithSuffixFromPrefix(resourceName, "name", rName, tfsns.FIFOTopicNameSuffix), @@ -376,7 +376,7 @@ func TestAccSNSTopic_fifoWithContentBasedDeduplication(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicWithFIFOContentBasedDeduplicationConfig(rName, true), + Config: testAccTopicConfig_fifoContentBasedDeduplication(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "fifo_topic", "true"), @@ -390,7 +390,7 @@ func TestAccSNSTopic_fifoWithContentBasedDeduplication(t *testing.T) { }, // Test attribute update { - Config: testAccTopicWithFIFOContentBasedDeduplicationConfig(rName, false), + Config: testAccTopicConfig_fifoContentBasedDeduplication(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "content_based_deduplication", "false"), @@ -409,7 +409,7 @@ func TestAccSNSTopic_fifoExpectContentBasedDeduplicationError(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicExpectContentBasedDeduplicationError(rName), + Config: testAccTopicConfig_expectContentBasedDeduplicationError(rName), ExpectError: regexp.MustCompile(`content-based deduplication can only be set for FIFO topics`), }, }, @@ -428,7 +428,7 @@ func TestAccSNSTopic_encryption(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicConfig_withEncryption(rName), + Config: testAccTopicConfig_encryption(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "kms_master_key_id", "alias/aws/sns"), @@ -440,7 +440,7 @@ func TestAccSNSTopic_encryption(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTopicNameConfig(rName), + Config: testAccTopicConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "kms_master_key_id", ""), @@ -462,7 +462,7 @@ func TestAccSNSTopic_tags(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicTags1Config(rName, "key1", "value1"), + Config: testAccTopicConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -475,7 +475,7 @@ func TestAccSNSTopic_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTopicTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTopicConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -484,7 +484,7 @@ func TestAccSNSTopic_tags(t *testing.T) { ), }, { - Config: testAccTopicTags1Config(rName, "key2", "value2"), + Config: testAccTopicConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -506,7 +506,7 @@ func TestAccSNSTopic_disappears(t *testing.T) { CheckDestroy: testAccCheckTopicDestroy, Steps: []resource.TestStep{ { - Config: testAccTopicNameGeneratedConfig, + Config: testAccTopicConfig_nameGenerated, Check: resource.ComposeTestCheckFunc( testAccCheckTopicExists(resourceName, &attributes), acctest.CheckResourceDisappears(acctest.Provider, tfsns.ResourceTopic(), resourceName), @@ -656,17 +656,17 @@ func testAccCheckTopicExists(n string, v *map[string]string) resource.TestCheckF } } -const testAccTopicNameGeneratedConfig = ` +const testAccTopicConfig_nameGenerated = ` resource "aws_sns_topic" "test" {} ` -const testAccTopicNameGeneratedFIFOTopicConfig = ` +const testAccTopicConfig_nameGeneratedFIFO = ` resource "aws_sns_topic" "test" { fifo_topic = true } ` -func testAccTopicNameConfig(rName string) string { +func testAccTopicConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -674,7 +674,7 @@ resource "aws_sns_topic" "test" { `, rName) } -func testAccTopicNameFIFOTopicConfig(rName string) string { +func testAccTopicConfig_nameFIFO(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -683,7 +683,7 @@ resource "aws_sns_topic" "test" { `, rName) } -func testAccTopicNamePrefixConfig(prefix string) string { +func testAccTopicConfig_namePrefix(prefix string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name_prefix = %[1]q @@ -691,7 +691,7 @@ resource "aws_sns_topic" "test" { `, prefix) } -func testAccTopicNamePrefixFIFOTopicConfig(prefix string) string { +func testAccTopicConfig_namePrefixFIFO(prefix string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name_prefix = %[1]q @@ -700,7 +700,7 @@ resource "aws_sns_topic" "test" { `, prefix) } -func testAccTopicWithPolicy(r string) string { +func testAccTopicConfig_policy(r string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -731,7 +731,7 @@ EOF } // Test for https://github.com/hashicorp/terraform/issues/3660 -func testAccTopicConfig_withIAMRole(r string) string { +func testAccTopicConfig_iamRole(r string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -783,7 +783,7 @@ EOF } // Test for https://github.com/hashicorp/terraform/issues/14024 -func testAccTopicConfig_withDeliveryPolicy(r string) string { +func testAccTopicConfig_deliveryPolicy(r string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = "tf_acc_test_delivery_policy_%s" @@ -809,7 +809,7 @@ EOF } // Test for https://github.com/hashicorp/terraform/issues/3660 -func testAccTopicConfig_withFakeIAMRole(r string) string { +func testAccTopicConfig_fakeIAMRole(r string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -911,7 +911,7 @@ EOF `, r) } -func testAccTopicConfig_withEncryption(rName string) string { +func testAccTopicConfig_encryption(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -920,7 +920,7 @@ resource "aws_sns_topic" "test" { `, rName) } -func testAccTopicWithFIFOContentBasedDeduplicationConfig(r string, cbd bool) string { +func testAccTopicConfig_fifoContentBasedDeduplication(r string, cbd bool) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = "terraform-test-topic-%s.fifo" @@ -930,7 +930,7 @@ resource "aws_sns_topic" "test" { `, r, cbd) } -func testAccTopicExpectContentBasedDeduplicationError(r string) string { +func testAccTopicConfig_expectContentBasedDeduplicationError(r string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = "terraform-test-topic-%s" @@ -939,7 +939,7 @@ resource "aws_sns_topic" "test" { `, r) } -func testAccTopicTags1Config(r, tag1Key, tag1Value string) string { +func testAccTopicConfig_tags1(r, tag1Key, tag1Value string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = "terraform-test-topic-%s" @@ -951,7 +951,7 @@ resource "aws_sns_topic" "test" { `, r, tag1Key, tag1Value) } -func testAccTopicTags2Config(r, tag1Key, tag1Value, tag2Key, tag2Value string) string { +func testAccTopicConfig_tags2(r, tag1Key, tag1Value, tag2Key, tag2Value string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = "terraform-test-topic-%s" diff --git a/internal/service/sqs/queue.go b/internal/service/sqs/queue.go index 0bbf8d5dbcc..4ef0792707c 100644 --- a/internal/service/sqs/queue.go +++ b/internal/service/sqs/queue.go @@ -201,7 +201,7 @@ func resourceQueueCreate(d *schema.ResourceData, meta interface{}) error { QueueName: aws.String(name), } - attributes, err := queueAttributeMap.ResourceDataToApiAttributesCreate(d) + attributes, err := queueAttributeMap.ResourceDataToAPIAttributesCreate(d) if err != nil { return err @@ -219,7 +219,7 @@ func resourceQueueCreate(d *schema.ResourceData, meta interface{}) error { }, sqs.ErrCodeQueueDeletedRecently) // Some partitions may not support tag-on-create - if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(err) { + if input.Tags != nil && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { log.Printf("[WARN] failed creating SQS Queue (%s) with tags: %s. Trying create without tags.", name, err) input.Tags = nil @@ -244,7 +244,7 @@ func resourceQueueCreate(d *schema.ResourceData, meta interface{}) error { if input.Tags == nil && len(tags) > 0 { err := UpdateTags(conn, d.Id(), nil, tags) - if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(err) { + if v, ok := d.GetOk("tags"); (!ok || len(v.(map[string]interface{})) == 0) && verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // if default tags only, log and continue (i.e., should error if explicitly setting tags and they can't be) log.Printf("[WARN] failed adding tags after create for SQS Queue (%s): %s", d.Id(), err) return resourceQueueRead(d, meta) @@ -285,7 +285,7 @@ func resourceQueueRead(d *schema.ResourceData, meta interface{}) error { output := outputRaw.(map[string]string) - err = queueAttributeMap.ApiAttributesToResourceData(output, d) + err = queueAttributeMap.APIAttributesToResourceData(output, d) if err != nil { return err @@ -308,7 +308,7 @@ func resourceQueueRead(d *schema.ResourceData, meta interface{}) error { return ListTags(conn, d.Id()) }, sqs.ErrCodeQueueDoesNotExist) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // Some partitions may not support tagging, giving error log.Printf("[WARN] failed listing tags for SQS Queue (%s): %s", d.Id(), err) return nil @@ -336,7 +336,7 @@ func resourceQueueUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SQSConn if d.HasChangesExcept("tags", "tags_all") { - attributes, err := queueAttributeMap.ResourceDataToApiAttributesUpdate(d) + attributes, err := queueAttributeMap.ResourceDataToAPIAttributesUpdate(d) if err != nil { return err @@ -365,7 +365,7 @@ func resourceQueueUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") err := UpdateTags(conn, d.Id(), o, n) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // Some partitions may not support tagging, giving error log.Printf("[WARN] failed updating tags for SQS Queue (%s): %s", d.Id(), err) return resourceQueueRead(d, meta) diff --git a/internal/service/sqs/queue_data_source.go b/internal/service/sqs/queue_data_source.go index c0ccb7ba425..d5b4fdd14cf 100644 --- a/internal/service/sqs/queue_data_source.go +++ b/internal/service/sqs/queue_data_source.go @@ -62,7 +62,7 @@ func dataSourceQueueRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, queueURL) - if verify.CheckISOErrorTagsUnsupported(err) { + if verify.CheckISOErrorTagsUnsupported(conn.PartitionID, err) { // Some partitions may not support tagging, giving error log.Printf("[WARN] failed listing tags for SQS Queue (%s): %s", d.Id(), err) return nil diff --git a/internal/service/sqs/queue_data_source_test.go b/internal/service/sqs/queue_data_source_test.go index 23e1c415dd8..7f1d74e8155 100644 --- a/internal/service/sqs/queue_data_source_test.go +++ b/internal/service/sqs/queue_data_source_test.go @@ -22,7 +22,7 @@ func TestAccSQSQueueDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccQueueDataSourceConfig(rName), + Config: testAccQueueDataSourceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccQueueCheckDataSource(datasourceName, resourceName), resource.TestCheckResourceAttr(datasourceName, "tags.%", "0"), @@ -43,7 +43,7 @@ func TestAccSQSQueueDataSource_tags(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccQueueTagsDataSourceConfig(rName), + Config: testAccQueueDataSourceConfig_tags(rName), Check: resource.ComposeTestCheckFunc( testAccQueueCheckDataSource(datasourceName, resourceName), resource.TestCheckResourceAttr(datasourceName, "tags.%", "3"), @@ -88,7 +88,7 @@ func testAccQueueCheckDataSource(datasourceName, resourceName string) resource.T } } -func testAccQueueDataSourceConfig(rName string) string { +func testAccQueueDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "wrong" { name = "%[1]s_wrong" @@ -104,7 +104,7 @@ data "aws_sqs_queue" "by_name" { `, rName) } -func testAccQueueTagsDataSourceConfig(rName string) string { +func testAccQueueDataSourceConfig_tags(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = "%[1]s" diff --git a/internal/service/sqs/queue_policy_test.go b/internal/service/sqs/queue_policy_test.go index 6a70c32f167..35e7eb7e5c0 100644 --- a/internal/service/sqs/queue_policy_test.go +++ b/internal/service/sqs/queue_policy_test.go @@ -24,7 +24,7 @@ func TestAccSQSQueuePolicy_basic(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueuePolicyConfig(rName), + Config: testAccQueuePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(queueResourceName, &queueAttributes), resource.TestCheckResourceAttrSet(resourceName, "policy"), @@ -36,7 +36,7 @@ func TestAccSQSQueuePolicy_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccQueuePolicyConfig(rName), + Config: testAccQueuePolicyConfig_basic(rName), PlanOnly: true, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "policy", queueResourceName, "policy"), @@ -59,7 +59,7 @@ func TestAccSQSQueuePolicy_disappears(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueuePolicyConfig(rName), + Config: testAccQueuePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(queueResourceName, &queueAttributes), acctest.CheckResourceDisappears(acctest.Provider, tfsqs.ResourceQueuePolicy(), resourceName), @@ -82,7 +82,7 @@ func TestAccSQSQueuePolicy_Disappears_queue(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueuePolicyConfig(rName), + Config: testAccQueuePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(queueResourceName, &queueAttributes), acctest.CheckResourceDisappears(acctest.Provider, tfsqs.ResourceQueue(), queueResourceName), @@ -106,7 +106,7 @@ func TestAccSQSQueuePolicy_update(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueuePolicyConfig(rName), + Config: testAccQueuePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(queueResourceName, &queueAttributes), resource.TestCheckResourceAttrSet(resourceName, "policy"), @@ -118,7 +118,7 @@ func TestAccSQSQueuePolicy_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPolicyUpdatedConfig(rName), + Config: testAccQueuePolicyConfig_updated(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "policy"), ), @@ -127,7 +127,7 @@ func TestAccSQSQueuePolicy_update(t *testing.T) { }) } -func testAccQueuePolicyConfig(rName string) string { +func testAccQueuePolicyConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -156,7 +156,7 @@ POLICY `, rName) } -func testAccPolicyUpdatedConfig(rName string) string { +func testAccQueuePolicyConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q diff --git a/internal/service/sqs/queue_test.go b/internal/service/sqs/queue_test.go index 2c321986ac5..58f1ac7c72c 100644 --- a/internal/service/sqs/queue_test.go +++ b/internal/service/sqs/queue_test.go @@ -40,7 +40,7 @@ func TestAccSQSQueue_basic(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccNameConfig(rName), + Config: testAccQueueConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "sqs", rName), @@ -85,7 +85,7 @@ func TestAccSQSQueue_disappears(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccNameConfig(rName), + Config: testAccQueueConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), acctest.CheckResourceDisappears(acctest.Provider, tfsqs.ResourceQueue(), resourceName), @@ -107,7 +107,7 @@ func TestAccSQSQueue_Name_generated(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueNameGeneratedConfig, + Config: testAccQueueConfig_nameGenerated, Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -135,7 +135,7 @@ func TestAccSQSQueue_NameGenerated_fifoQueue(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueNameGeneratedFIFOQueueConfig, + Config: testAccQueueConfig_nameGeneratedFIFO, Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), create.TestCheckResourceAttrNameWithSuffixGenerated(resourceName, "name", tfsqs.FIFOQueueNameSuffix), @@ -163,7 +163,7 @@ func TestAccSQSQueue_namePrefix(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueNamePrefixConfig("tf-acc-test-prefix-"), + Config: testAccQueueConfig_namePrefix("tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), @@ -191,7 +191,7 @@ func TestAccSQSQueue_NamePrefix_fifoQueue(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueueNamePrefixFIFOQueueConfig("tf-acc-test-prefix-"), + Config: testAccQueueConfig_namePrefixFIFO("tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), create.TestCheckResourceAttrNameWithSuffixFromPrefix(resourceName, "name", "tf-acc-test-prefix-", tfsqs.FIFOQueueNameSuffix), @@ -220,7 +220,7 @@ func TestAccSQSQueue_tags(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccTags1Config(rName, "key1", "value1"), + Config: testAccQueueConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -233,7 +233,7 @@ func TestAccSQSQueue_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccQueueConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -242,7 +242,7 @@ func TestAccSQSQueue_tags(t *testing.T) { ), }, { - Config: testAccTags1Config(rName, "key2", "value2"), + Config: testAccQueueConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -265,7 +265,7 @@ func TestAccSQSQueue_update(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccNameConfig(rName), + Config: testAccQueueConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "sqs", rName), @@ -288,7 +288,7 @@ func TestAccSQSQueue_update(t *testing.T) { ), }, { - Config: testAccUpdatedConfig(rName), + Config: testAccQueueConfig_updated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "sqs", rName), @@ -348,7 +348,7 @@ func TestAccSQSQueue_Policy_basic(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccPolicyConfig(rName), + Config: testAccQueueConfig_policy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), testAccCheckQueuePolicyAttribute(&queueAttributes, rName, expectedPolicy), @@ -401,7 +401,7 @@ func TestAccSQSQueue_Policy_ignoreEquivalent(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccQueuePolicyEquivalentConfig(rName), + Config: testAccQueueConfig_policyEquivalent(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), testAccCheckQueuePolicyAttribute(&queueAttributes, rName, expectedPolicy), @@ -413,7 +413,7 @@ func TestAccSQSQueue_Policy_ignoreEquivalent(t *testing.T) { ), }, { - Config: testAccQueuePolicyNewEquivalentConfig(rName), + Config: testAccQueueConfig_policyNewEquivalent(rName), PlanOnly: true, }, }, @@ -432,7 +432,7 @@ func TestAccSQSQueue_recentlyDeleted(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccNameConfig(rName), + Config: testAccQueueConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), acctest.CheckResourceDisappears(acctest.Provider, tfsqs.ResourceQueue(), resourceName), @@ -440,7 +440,7 @@ func TestAccSQSQueue_recentlyDeleted(t *testing.T) { ExpectNonEmptyPlan: true, }, { - Config: testAccNameConfig(rName), + Config: testAccQueueConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), ), @@ -461,7 +461,7 @@ func TestAccSQSQueue_redrivePolicy(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccRedrivePolicyConfig(rName), + Config: testAccQueueConfig_redrivePolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "delay_seconds", "0"), @@ -490,7 +490,7 @@ func TestAccSQSQueue_redriveAllowPolicy(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccRedriveAllowPolicyConfig(rName), + Config: testAccQueueConfig_redriveAllowPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "delay_seconds", "0"), @@ -519,7 +519,7 @@ func TestAccSQSQueue_fifoQueue(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccFIFOQueueConfig(rName), + Config: testAccQueueConfig_fifo(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "deduplication_scope", "queue"), @@ -546,7 +546,7 @@ func TestAccSQSQueue_FIFOQueue_expectNameError(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccFIFOQueueConfig(rName), + Config: testAccQueueConfig_fifo(rName), ExpectError: regexp.MustCompile(`invalid queue name:`), }, }, @@ -565,7 +565,7 @@ func TestAccSQSQueue_FIFOQueue_contentBasedDeduplication(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccFIFOQueueContentBasedDeduplicationConfig(rName), + Config: testAccQueueConfig_fifoContentBasedDeduplication(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "content_based_deduplication", "true"), @@ -593,7 +593,7 @@ func TestAccSQSQueue_FIFOQueue_highThroughputMode(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccFIFOQueueHighThroughputModeConfig(rName, "null", "null"), + Config: testAccQueueConfig_fifoHighThroughputMode(rName, "null", "null"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "deduplication_scope", "queue"), @@ -607,7 +607,7 @@ func TestAccSQSQueue_FIFOQueue_highThroughputMode(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccFIFOQueueHighThroughputModeConfig(rName, "messageGroup", "perMessageGroupId"), + Config: testAccQueueConfig_fifoHighThroughputMode(rName, "messageGroup", "perMessageGroupId"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "deduplication_scope", "messageGroup"), @@ -629,7 +629,7 @@ func TestAccSQSQueue_StandardQueue_expectContentBasedDeduplicationError(t *testi CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccStandardQueueExpectContentBasedDeduplicationErrorConfig(rName), + Config: testAccQueueConfig_standardExpectContentBasedDeduplicationError(rName), ExpectError: regexp.MustCompile(`content-based deduplication can only be set for FIFO queue`), }, }, @@ -648,7 +648,7 @@ func TestAccSQSQueue_encryption(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccEncryptionConfig(rName, "null"), + Config: testAccQueueConfig_encryption(rName, "null"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "kms_data_key_reuse_period_seconds", "300"), @@ -661,7 +661,7 @@ func TestAccSQSQueue_encryption(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccEncryptionConfig(rName, "3600"), + Config: testAccQueueConfig_encryption(rName, "3600"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "kms_data_key_reuse_period_seconds", "3600"), @@ -669,7 +669,7 @@ func TestAccSQSQueue_encryption(t *testing.T) { ), }, { - Config: testAccManagedEncryptionConfig(rName, "true"), + Config: testAccQueueConfig_managedEncryption(rName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "sqs_managed_sse_enabled", "true"), @@ -691,7 +691,7 @@ func TestAccSQSQueue_zeroVisibilityTimeoutSeconds(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccZeroVisibilityTimeoutSecondsConfig(rName), + Config: testAccQueueConfig_zeroVisibilityTimeoutSeconds(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "visibility_timeout_seconds", "0"), @@ -719,7 +719,7 @@ func TestAccSQSQueue_defaultKMSDataKeyReusePeriodSeconds(t *testing.T) { CheckDestroy: testAccCheckQueueDestroy, Steps: []resource.TestStep{ { - Config: testAccDefaultKMSDataKeyReusePeriodSecondsConfig(rName), + Config: testAccQueueConfig_defaultKMSDataKeyReusePeriodSeconds(rName), Check: resource.ComposeTestCheckFunc( testAccCheckQueueExists(resourceName, &queueAttributes), resource.TestCheckResourceAttr(resourceName, "kms_data_key_reuse_period_seconds", strconv.Itoa(tfsqs.DefaultQueueKMSDataKeyReusePeriodSeconds)), @@ -807,17 +807,17 @@ func testAccCheckQueueDestroy(s *terraform.State) error { return nil } -const testAccQueueNameGeneratedConfig = ` +const testAccQueueConfig_nameGenerated = ` resource "aws_sqs_queue" "test" {} ` -const testAccQueueNameGeneratedFIFOQueueConfig = ` +const testAccQueueConfig_nameGeneratedFIFO = ` resource "aws_sqs_queue" "test" { fifo_queue = true } ` -func testAccNameConfig(rName string) string { +func testAccQueueConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -825,7 +825,7 @@ resource "aws_sqs_queue" "test" { `, rName) } -func testAccQueueNamePrefixConfig(prefix string) string { +func testAccQueueConfig_namePrefix(prefix string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name_prefix = %[1]q @@ -833,7 +833,7 @@ resource "aws_sqs_queue" "test" { `, prefix) } -func testAccQueueNamePrefixFIFOQueueConfig(prefix string) string { +func testAccQueueConfig_namePrefixFIFO(prefix string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name_prefix = %[1]q @@ -842,7 +842,7 @@ resource "aws_sqs_queue" "test" { `, prefix) } -func testAccTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccQueueConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -854,7 +854,7 @@ resource "aws_sqs_queue" "test" { `, rName, tagKey1, tagValue1) } -func testAccTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccQueueConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -867,7 +867,7 @@ resource "aws_sqs_queue" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccUpdatedConfig(rName string) string { +func testAccQueueConfig_updated(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -880,7 +880,7 @@ resource "aws_sqs_queue" "test" { `, rName) } -func testAccPolicyConfig(rName string) string { +func testAccQueueConfig_policy(rName string) string { return fmt.Sprintf(` locals { queue_name = %[1]q @@ -934,7 +934,7 @@ resource "aws_sns_topic_subscription" "test" { `, rName) } -func testAccQueuePolicyEquivalentConfig(rName string) string { +func testAccQueueConfig_policyEquivalent(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -984,7 +984,7 @@ resource "aws_sns_topic_subscription" "test" { `, rName) } -func testAccQueuePolicyNewEquivalentConfig(rName string) string { +func testAccQueueConfig_policyNewEquivalent(rName string) string { return fmt.Sprintf(` resource "aws_sns_topic" "test" { name = %[1]q @@ -1034,7 +1034,7 @@ resource "aws_sns_topic_subscription" "test" { `, rName) } -func testAccRedrivePolicyConfig(rName string) string { +func testAccQueueConfig_redrivePolicy(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = "%[1]s-1" @@ -1055,7 +1055,7 @@ resource "aws_sqs_queue" "dlq" { `, rName) } -func testAccRedriveAllowPolicyConfig(rName string) string { +func testAccQueueConfig_redriveAllowPolicy(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = "%[1]s-1" @@ -1076,7 +1076,7 @@ resource "aws_sqs_queue" "dlq" { `, rName) } -func testAccFIFOQueueConfig(rName string) string { +func testAccQueueConfig_fifo(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -1085,7 +1085,7 @@ resource "aws_sqs_queue" "test" { `, rName) } -func testAccFIFOQueueContentBasedDeduplicationConfig(rName string) string { +func testAccQueueConfig_fifoContentBasedDeduplication(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -1095,7 +1095,7 @@ resource "aws_sqs_queue" "test" { `, rName) } -func testAccFIFOQueueHighThroughputModeConfig(rName, deduplicationScope, fifoThroughputLimit string) string { +func testAccQueueConfig_fifoHighThroughputMode(rName, deduplicationScope, fifoThroughputLimit string) string { if deduplicationScope != "null" { deduplicationScope = strconv.Quote(deduplicationScope) } @@ -1115,7 +1115,7 @@ resource "aws_sqs_queue" "test" { `, rName, deduplicationScope, fifoThroughputLimit) } -func testAccStandardQueueExpectContentBasedDeduplicationErrorConfig(rName string) string { +func testAccQueueConfig_standardExpectContentBasedDeduplicationError(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -1124,7 +1124,7 @@ resource "aws_sqs_queue" "test" { `, rName) } -func testAccEncryptionConfig(rName, kmsDataKeyReusePeriodSeconds string) string { +func testAccQueueConfig_encryption(rName, kmsDataKeyReusePeriodSeconds string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -1134,7 +1134,7 @@ resource "aws_sqs_queue" "test" { `, rName, kmsDataKeyReusePeriodSeconds) } -func testAccManagedEncryptionConfig(rName, sqsManagedSseEnabled string) string { +func testAccQueueConfig_managedEncryption(rName, sqsManagedSseEnabled string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -1143,7 +1143,7 @@ resource "aws_sqs_queue" "test" { `, rName, sqsManagedSseEnabled) } -func testAccZeroVisibilityTimeoutSecondsConfig(rName string) string { +func testAccQueueConfig_zeroVisibilityTimeoutSeconds(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q @@ -1152,7 +1152,7 @@ resource "aws_sqs_queue" "test" { `, rName) } -func testAccDefaultKMSDataKeyReusePeriodSecondsConfig(rName string) string { +func testAccQueueConfig_defaultKMSDataKeyReusePeriodSeconds(rName string) string { return fmt.Sprintf(` resource "aws_sqs_queue" "test" { name = %[1]q diff --git a/internal/service/ssm/activation.go b/internal/service/ssm/activation.go index d806d239247..7c8bb026e18 100644 --- a/internal/service/ssm/activation.go +++ b/internal/service/ssm/activation.go @@ -168,7 +168,7 @@ func resourceActivationRead(d *schema.ResourceData, meta interface{}) error { if err != nil { return fmt.Errorf("Error reading SSM activation: %s", err) } - if resp.ActivationList == nil || len(resp.ActivationList) == 0 { + if !d.IsNewResource() && (resp.ActivationList == nil || len(resp.ActivationList) == 0) { log.Printf("[WARN] SSM Activation (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/internal/service/ssm/activation_test.go b/internal/service/ssm/activation_test.go index 1888fe0bccc..cd25663a1f8 100644 --- a/internal/service/ssm/activation_test.go +++ b/internal/service/ssm/activation_test.go @@ -27,7 +27,7 @@ func TestAccSSMActivation_basic(t *testing.T) { CheckDestroy: testAccCheckActivationDestroy, Steps: []resource.TestStep{ { - Config: testAccActivationBasicConfig(name, tag), + Config: testAccActivationConfig_basic(name, tag), Check: resource.ComposeTestCheckFunc( testAccCheckActivationExists(resourceName, &ssmActivation), resource.TestCheckResourceAttrSet(resourceName, "activation_code"), @@ -59,7 +59,7 @@ func TestAccSSMActivation_update(t *testing.T) { CheckDestroy: testAccCheckActivationDestroy, Steps: []resource.TestStep{ { - Config: testAccActivationBasicConfig(name, "My Activation"), + Config: testAccActivationConfig_basic(name, "My Activation"), Check: resource.ComposeTestCheckFunc( testAccCheckActivationExists(resourceName, &ssmActivation1), resource.TestCheckResourceAttrSet(resourceName, "activation_code"), @@ -76,7 +76,7 @@ func TestAccSSMActivation_update(t *testing.T) { }, }, { - Config: testAccActivationBasicConfig(name, "Foo"), + Config: testAccActivationConfig_basic(name, "Foo"), Check: resource.ComposeTestCheckFunc( testAccCheckActivationExists(resourceName, &ssmActivation2), resource.TestCheckResourceAttrSet(resourceName, "activation_code"), @@ -142,7 +142,7 @@ func TestAccSSMActivation_disappears(t *testing.T) { CheckDestroy: testAccCheckActivationDestroy, Steps: []resource.TestStep{ { - Config: testAccActivationBasicConfig(name, tag), + Config: testAccActivationConfig_basic(name, tag), Check: resource.ComposeTestCheckFunc( testAccCheckActivationExists(resourceName, &ssmActivation), testAccCheckActivationDisappears(&ssmActivation), @@ -278,7 +278,7 @@ resource "aws_iam_role_policy_attachment" "test_attach" { `, rName) } -func testAccActivationBasicConfig(rName string, rTag string) string { +func testAccActivationConfig_basic(rName string, rTag string) string { return testAccActivationBasicBaseConfig(rName) + fmt.Sprintf(` resource "aws_ssm_activation" "test" { name = %[1]q diff --git a/internal/service/ssm/association_test.go b/internal/service/ssm/association_test.go index 41c812faf80..d35736f0f97 100644 --- a/internal/service/ssm/association_test.go +++ b/internal/service/ssm/association_test.go @@ -27,7 +27,7 @@ func TestAccSSMAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicConfig(rName), + Config: testAccAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ssm", regexp.MustCompile(`association/.+`)), @@ -63,7 +63,7 @@ func TestAccSSMAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicConfig(rName), + Config: testAccAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfssm.ResourceAssociation(), resourceName), @@ -85,7 +85,7 @@ func TestAccSSMAssociation_disappears_document(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicConfig(rName), + Config: testAccAssociationConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfssm.ResourceDocument(), "aws_ssm_document.test"), @@ -107,7 +107,7 @@ func TestAccSSMAssociation_applyOnlyAtCronInterval(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicWithApplyOnlyAtCronIntervalConfig(rName, true), + Config: testAccAssociationConfig_basicApplyOnlyAtCronInterval(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "apply_only_at_cron_interval", "true"), @@ -119,7 +119,7 @@ func TestAccSSMAssociation_applyOnlyAtCronInterval(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAssociationBasicWithApplyOnlyAtCronIntervalConfig(rName, false), + Config: testAccAssociationConfig_basicApplyOnlyAtCronInterval(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "apply_only_at_cron_interval", "false"), @@ -160,7 +160,7 @@ targets { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicWithTargetsConfig(rName, oneTarget), + Config: testAccAssociationConfig_basicTargets(rName, oneTarget), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "targets.#", "1"), @@ -174,7 +174,7 @@ targets { ImportStateVerify: true, }, { - Config: testAccAssociationBasicWithTargetsConfig(rName, twoTargets), + Config: testAccAssociationConfig_basicTargets(rName, twoTargets), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "targets.#", "2"), @@ -185,7 +185,7 @@ targets { ), }, { - Config: testAccAssociationBasicWithTargetsConfig(rName, oneTarget), + Config: testAccAssociationConfig_basicTargets(rName, oneTarget), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "targets.#", "1"), @@ -208,7 +208,7 @@ func TestAccSSMAssociation_withParameters(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicWithParametersConfig(rName), + Config: testAccAssociationConfig_basicParameters(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameters.Directory", "myWorkSpace"), @@ -221,7 +221,7 @@ func TestAccSSMAssociation_withParameters(t *testing.T) { ImportStateVerifyIgnore: []string{"parameters"}, }, { - Config: testAccAssociationBasicWithParametersUpdatedConfig(rName), + Config: testAccAssociationConfig_basicParametersUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameters.Directory", "myWorkSpaceUpdated"), @@ -244,7 +244,7 @@ func TestAccSSMAssociation_withAssociationName(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicWithAssociationNameConfig(rName, assocName1), + Config: testAccAssociationConfig_basicName(rName, assocName1), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "association_name", assocName1), @@ -256,7 +256,7 @@ func TestAccSSMAssociation_withAssociationName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAssociationBasicWithAssociationNameConfig(rName, assocName2), + Config: testAccAssociationConfig_basicName(rName, assocName2), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "association_name", assocName2), @@ -280,7 +280,7 @@ func TestAccSSMAssociation_withAssociationNameAndScheduleExpression(t *testing.T CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationWithAssociationNameAndScheduleExpressionConfig(rName, assocName, scheduleExpression1), + Config: testAccAssociationConfig_nameAndScheduleExpression(rName, assocName, scheduleExpression1), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "association_name", assocName), @@ -293,7 +293,7 @@ func TestAccSSMAssociation_withAssociationNameAndScheduleExpression(t *testing.T ImportStateVerify: true, }, { - Config: testAccAssociationWithAssociationNameAndScheduleExpressionConfig(rName, assocName, scheduleExpression2), + Config: testAccAssociationConfig_nameAndScheduleExpression(rName, assocName, scheduleExpression2), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "association_name", assocName), @@ -315,7 +315,7 @@ func TestAccSSMAssociation_withDocumentVersion(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicWithDocumentVersionConfig(rName), + Config: testAccAssociationConfig_basicDocumentVersion(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "document_version", "1"), @@ -341,7 +341,7 @@ func TestAccSSMAssociation_withOutputLocation(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicWithOutPutLocationConfig(rName), + Config: testAccAssociationConfig_basicOutPutLocation(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "output_location.0.s3_bucket_name", "aws_s3_bucket.output_location", "bucket"), @@ -354,7 +354,7 @@ func TestAccSSMAssociation_withOutputLocation(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAssociationBasicWithOutPutLocationUpdateBucketNameConfig(rName), + Config: testAccAssociationConfig_basicOutPutLocationUpdateBucketName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "output_location.0.s3_bucket_name", "aws_s3_bucket.output_location_updated", "bucket"), @@ -362,7 +362,7 @@ func TestAccSSMAssociation_withOutputLocation(t *testing.T) { ), }, { - Config: testAccAssociationBasicWithOutPutLocationUpdateKeyPrefixConfig(rName), + Config: testAccAssociationConfig_basicOutPutLocationUpdateKeyPrefix(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "output_location.0.s3_bucket_name", "aws_s3_bucket.output_location_updated", "bucket"), @@ -384,7 +384,7 @@ func TestAccSSMAssociation_withOutputLocation_s3Region(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationWithOutputLocationS3RegionConfig(rName), + Config: testAccAssociationConfig_outputLocationS3Region(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "output_location.#", "1"), @@ -398,7 +398,7 @@ func TestAccSSMAssociation_withOutputLocation_s3Region(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAssociationWithOutputLocationUpdateS3RegionConfig(rName), + Config: testAccAssociationConfig_outputLocationUpdateS3Region(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "output_location.#", "1"), @@ -412,7 +412,7 @@ func TestAccSSMAssociation_withOutputLocation_s3Region(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAssociationWithOutputLocationNoS3RegionConfig(rName), + Config: testAccAssociationConfig_outputLocationNoS3Region(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "output_location.#", "1"), @@ -434,7 +434,7 @@ func TestAccSSMAssociation_withOutputLocation_waitForSuccessTimeout(t *testing.T CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationWithOutputLocationAndWaitForSuccessConfig(rName), + Config: testAccAssociationConfig_outputLocationAndWaitForSuccess(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), ), @@ -462,7 +462,7 @@ func TestAccSSMAssociation_withAutomationTargetParamName(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicWithAutomationTargetParamNameConfig(rName), + Config: testAccAssociationConfig_basicAutomationTargetParamName(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameters.Directory", "myWorkSpace"), @@ -475,7 +475,7 @@ func TestAccSSMAssociation_withAutomationTargetParamName(t *testing.T) { ImportStateVerifyIgnore: []string{"parameters"}, }, { - Config: testAccAssociationBasicWithParametersUpdatedConfig(rName), + Config: testAccAssociationConfig_basicParametersUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameters.Directory", "myWorkSpaceUpdated"), @@ -496,7 +496,7 @@ func TestAccSSMAssociation_withScheduleExpression(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicWithScheduleExpressionConfig(rName), + Config: testAccAssociationConfig_basicScheduleExpression(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "schedule_expression", "cron(0 16 ? * TUE *)"), @@ -508,7 +508,7 @@ func TestAccSSMAssociation_withScheduleExpression(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAssociationBasicWithScheduleExpressionUpdatedConfig(rName), + Config: testAccAssociationConfig_basicScheduleExpressionUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "schedule_expression", "cron(0 16 ? * WED *)"), @@ -532,7 +532,7 @@ func TestAccSSMAssociation_withComplianceSeverity(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationBasicWithComplianceSeverityConfig(compSeverity1, rName, assocName), + Config: testAccAssociationConfig_basicComplianceSeverity(compSeverity1, rName, assocName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "association_name", assocName), @@ -545,7 +545,7 @@ func TestAccSSMAssociation_withComplianceSeverity(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAssociationBasicWithComplianceSeverityConfig(compSeverity2, rName, assocName), + Config: testAccAssociationConfig_basicComplianceSeverity(compSeverity2, rName, assocName), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "association_name", assocName), @@ -567,7 +567,7 @@ func TestAccSSMAssociation_rateControl(t *testing.T) { CheckDestroy: testAccCheckAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccAssociationRateControlConfig(rName, "10%"), + Config: testAccAssociationConfig_rateControl(rName, "10%"), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "max_concurrency", "10%"), @@ -580,7 +580,7 @@ func TestAccSSMAssociation_rateControl(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAssociationRateControlConfig(rName, "20%"), + Config: testAccAssociationConfig_rateControl(rName, "20%"), Check: resource.ComposeTestCheckFunc( testAccCheckAssociationExists(resourceName), resource.TestCheckResourceAttr(resourceName, "max_concurrency", "20%"), @@ -639,7 +639,7 @@ func testAccCheckAssociationDestroy(s *terraform.State) error { return nil } -func testAccAssociationBasicWithApplyOnlyAtCronIntervalConfig(rName string, applyOnlyAtCronInterval bool) string { +func testAccAssociationConfig_basicApplyOnlyAtCronInterval(rName string, applyOnlyAtCronInterval bool) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -680,8 +680,8 @@ resource "aws_ssm_association" "test" { `, rName, applyOnlyAtCronInterval) } -func testAccAssociationBasicWithAutomationTargetParamNameConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccAssociationConfig_basicAutomationTargetParamName(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_iam_instance_profile" "ssm_profile" { name = %[1]q role = aws_iam_role.ssm_role.name @@ -792,7 +792,7 @@ resource "aws_ssm_association" "test" { `, rName)) } -func testAccAssociationBasicWithParametersUpdatedConfig(rName string) string { +func testAccAssociationConfig_basicParametersUpdated(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "%[1]s-2" @@ -842,7 +842,7 @@ resource "aws_ssm_association" "test" { `, rName) } -func testAccAssociationBasicWithParametersConfig(rName string) string { +func testAccAssociationConfig_basicParameters(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -892,7 +892,7 @@ resource "aws_ssm_association" "test" { `, rName) } -func testAccAssociationBasicWithTargetsConfig(rName, targetsStr string) string { +func testAccAssociationConfig_basicTargets(rName, targetsStr string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -927,7 +927,7 @@ resource "aws_ssm_association" "test" { `, rName, targetsStr) } -func testAccAssociationBasicConfig(rName string) string { +func testAccAssociationConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1020,7 +1020,7 @@ resource "aws_ssm_association" "test" { `, rName) } -func testAccAssociationBasicWithDocumentVersionConfig(rName string) string { +func testAccAssociationConfig_basicDocumentVersion(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -1060,7 +1060,7 @@ resource "aws_ssm_association" "test" { `, rName) } -func testAccAssociationBasicWithScheduleExpressionConfig(rName string) string { +func testAccAssociationConfig_basicScheduleExpression(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -1100,7 +1100,7 @@ resource "aws_ssm_association" "test" { `, rName) } -func testAccAssociationBasicWithScheduleExpressionUpdatedConfig(rName string) string { +func testAccAssociationConfig_basicScheduleExpressionUpdated(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -1140,7 +1140,7 @@ resource "aws_ssm_association" "test" { `, rName) } -func testAccAssociationBasicWithOutPutLocationConfig(rName string) string { +func testAccAssociationConfig_basicOutPutLocation(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "output_location" { bucket = %[1]q @@ -1223,7 +1223,7 @@ DOC `, rName) } -func testAccAssociationWithOutputLocationS3RegionConfig(rName string) string { +func testAccAssociationConfig_outputLocationS3Region(rName string) string { return acctest.ConfigCompose( testAccAssociationWithOutputLocationS3RegionConfigBase(rName), ` @@ -1243,7 +1243,7 @@ resource "aws_ssm_association" "test" { `) } -func testAccAssociationWithOutputLocationUpdateS3RegionConfig(rName string) string { +func testAccAssociationConfig_outputLocationUpdateS3Region(rName string) string { return acctest.ConfigCompose( testAccAssociationWithOutputLocationS3RegionConfigBase(rName), fmt.Sprintf(` @@ -1263,7 +1263,7 @@ resource "aws_ssm_association" "test" { `, acctest.AlternateRegion())) } -func testAccAssociationWithOutputLocationNoS3RegionConfig(rName string) string { +func testAccAssociationConfig_outputLocationNoS3Region(rName string) string { return acctest.ConfigCompose( testAccAssociationWithOutputLocationS3RegionConfigBase(rName), ` @@ -1282,7 +1282,7 @@ resource "aws_ssm_association" "test" { `) } -func testAccAssociationBasicWithOutPutLocationUpdateBucketNameConfig(rName string) string { +func testAccAssociationConfig_basicOutPutLocationUpdateBucketName(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "output_location" { bucket = %[1]q @@ -1336,7 +1336,7 @@ resource "aws_ssm_association" "test" { `, rName) } -func testAccAssociationBasicWithOutPutLocationUpdateKeyPrefixConfig(rName string) string { +func testAccAssociationConfig_basicOutPutLocationUpdateKeyPrefix(rName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "output_location" { bucket = %[1]q @@ -1390,7 +1390,7 @@ resource "aws_ssm_association" "test" { `, rName) } -func testAccAssociationBasicWithAssociationNameConfig(rName, assocName string) string { +func testAccAssociationConfig_basicName(rName, assocName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -1430,7 +1430,7 @@ resource "aws_ssm_association" "test" { `, rName, assocName) } -func testAccAssociationWithAssociationNameAndScheduleExpressionConfig(rName, associationName, scheduleExpression string) string { +func testAccAssociationConfig_nameAndScheduleExpression(rName, associationName, scheduleExpression string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -1471,7 +1471,7 @@ resource "aws_ssm_association" "test" { `, rName, associationName, scheduleExpression) } -func testAccAssociationBasicWithComplianceSeverityConfig(compSeverity, rName, assocName string) string { +func testAccAssociationConfig_basicComplianceSeverity(compSeverity, rName, assocName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -1512,7 +1512,7 @@ resource "aws_ssm_association" "test" { `, rName, assocName, compSeverity) } -func testAccAssociationRateControlConfig(rName, rate string) string { +func testAccAssociationConfig_rateControl(rName, rate string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -1553,7 +1553,7 @@ resource "aws_ssm_association" "test" { `, rName, rate) } -func testAccAssociationWithOutputLocationAndWaitForSuccessConfig(rName string) string { +func testAccAssociationConfig_outputLocationAndWaitForSuccess(rName string) string { return acctest.ConfigCompose( testAccAssociationWithOutputLocationS3RegionConfigBase(rName), ` diff --git a/internal/service/ssm/document.go b/internal/service/ssm/document.go index 33f186ef3ac..b5c6f14cd98 100644 --- a/internal/service/ssm/document.go +++ b/internal/service/ssm/document.go @@ -267,14 +267,14 @@ func resourceDocumentRead(d *schema.ResourceData, meta interface{}) error { describeDocumentOutput, err := conn.DescribeDocument(describeDocumentInput) - if tfawserr.ErrCodeEquals(err, ssm.ErrCodeInvalidDocument) { - log.Printf("[WARN] SSM Document not found so removing from state") + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, ssm.ErrCodeInvalidDocument) { + log.Printf("[WARN] SSM Document (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("error describing SSM Document (%s): %s", d.Id(), err) + return fmt.Errorf("error describing SSM Document (%s): %w", d.Id(), err) } if describeDocumentOutput == nil || describeDocumentOutput.Document == nil { @@ -288,13 +288,19 @@ func resourceDocumentRead(d *schema.ResourceData, meta interface{}) error { } getDocumentOutput, err := conn.GetDocument(getDocumentInput) - + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, ssm.ErrCodeInvalidDocument, ssm.ErrCodeInvalidDocumentVersion) { + log.Printf("[WARN] SSM Document (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } if err != nil { - return fmt.Errorf("error getting SSM Document (%s): %s", d.Id(), err) + return fmt.Errorf("error getting SSM Document (%s): %w", d.Id(), err) } - if getDocumentOutput == nil { - return fmt.Errorf("error getting SSM Document (%s): empty result", d.Id()) + if !d.IsNewResource() && getDocumentOutput == nil { + log.Printf("[WARN] SSM Document (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } doc := describeDocumentOutput.Document diff --git a/internal/service/ssm/document_data_source_test.go b/internal/service/ssm/document_data_source_test.go index d7d7fa2eef3..d0bda91f1a7 100644 --- a/internal/service/ssm/document_data_source_test.go +++ b/internal/service/ssm/document_data_source_test.go @@ -20,7 +20,7 @@ func TestAccSSMDocumentDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckDocumentDataSourceConfig(name, "JSON"), + Config: testAccDocumentDataSourceConfig_basic(name, "JSON"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_ssm_document.test", "arn"), resource.TestCheckResourceAttrPair(resourceName, "name", "aws_ssm_document.test", "name"), @@ -31,7 +31,7 @@ func TestAccSSMDocumentDataSource_basic(t *testing.T) { ), }, { - Config: testAccCheckDocumentDataSourceConfig(name, "YAML"), + Config: testAccDocumentDataSourceConfig_basic(name, "YAML"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_ssm_document.test", "arn"), resource.TestCheckResourceAttrPair(resourceName, "name", "aws_ssm_document.test", "name"), @@ -64,7 +64,7 @@ func TestAccSSMDocumentDataSource_managed(t *testing.T) { }) } -func testAccCheckDocumentDataSourceConfig(name, documentFormat string) string { +func testAccDocumentDataSourceConfig_basic(name, documentFormat string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "%s" diff --git a/internal/service/ssm/document_test.go b/internal/service/ssm/document_test.go index 192cdfc45c3..30bb11abc0f 100644 --- a/internal/service/ssm/document_test.go +++ b/internal/service/ssm/document_test.go @@ -25,7 +25,7 @@ func TestAccSSMDocument_basic(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentBasicConfig(name), + Config: testAccDocumentConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "document_format", "JSON"), @@ -57,7 +57,7 @@ func TestAccSSMDocument_name(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentBasicConfig(rName1), + Config: testAccDocumentConfig_basic(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName1), @@ -69,7 +69,7 @@ func TestAccSSMDocument_name(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentBasicConfig(rName2), + Config: testAccDocumentConfig_basic(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName2), @@ -89,7 +89,7 @@ func TestAccSSMDocument_Target_type(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentBasicTargetTypeConfig(name, "/"), + Config: testAccDocumentConfig_basicTargetType(name, "/"), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_type", "/"), @@ -101,7 +101,7 @@ func TestAccSSMDocument_Target_type(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentBasicTargetTypeConfig(name, "/AWS::EC2::Instance"), + Config: testAccDocumentConfig_basicTargetType(name, "/AWS::EC2::Instance"), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_type", "/AWS::EC2::Instance"), @@ -121,7 +121,7 @@ func TestAccSSMDocument_versionName(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentBasicVersionNameConfig(name, "release-1.0.0"), + Config: testAccDocumentConfig_basicVersionName(name, "release-1.0.0"), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "version_name", "release-1.0.0"), @@ -133,7 +133,7 @@ func TestAccSSMDocument_versionName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentBasicVersionNameConfig(name, "release-1.0.1"), + Config: testAccDocumentConfig_basicVersionName(name, "release-1.0.1"), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "version_name", "release-1.0.1"), @@ -153,7 +153,7 @@ func TestAccSSMDocument_update(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocument20Config(name), + Config: testAccDocumentConfig_20(name), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "schema_version", "2.0"), @@ -167,7 +167,7 @@ func TestAccSSMDocument_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocument20UpdatedConfig(name), + Config: testAccDocumentConfig_20Updated(name), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "latest_version", "2"), @@ -188,7 +188,7 @@ func TestAccSSMDocument_Permission_public(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentPublicPermissionConfig(name), + Config: testAccDocumentConfig_publicPermission(name), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "permissions.type", "Share"), @@ -215,7 +215,7 @@ func TestAccSSMDocument_Permission_private(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentPrivatePermissionConfig(name, ids), + Config: testAccDocumentConfig_privatePermission(name, ids), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "permissions.type", "Share"), @@ -241,7 +241,7 @@ func TestAccSSMDocument_Permission_batching(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentPrivatePermissionConfig(name, ids), + Config: testAccDocumentConfig_privatePermission(name, ids), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "permissions.type", "Share"), @@ -269,7 +269,7 @@ func TestAccSSMDocument_Permission_change(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentPrivatePermissionConfig(name, idsInitial), + Config: testAccDocumentConfig_privatePermission(name, idsInitial), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "permissions.type", "Share"), @@ -282,7 +282,7 @@ func TestAccSSMDocument_Permission_change(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentPrivatePermissionConfig(name, idsRemove), + Config: testAccDocumentConfig_privatePermission(name, idsRemove), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "permissions.type", "Share"), @@ -290,7 +290,7 @@ func TestAccSSMDocument_Permission_change(t *testing.T) { ), }, { - Config: testAccDocumentPrivatePermissionConfig(name, idsAdd), + Config: testAccDocumentConfig_privatePermission(name, idsAdd), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "permissions.type", "Share"), @@ -311,7 +311,7 @@ func TestAccSSMDocument_params(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentParamConfig(name), + Config: testAccDocumentConfig_param(name), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "parameter.0.name", "commands"), @@ -341,7 +341,7 @@ func TestAccSSMDocument_automation(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentTypeAutomationConfig(name), + Config: testAccDocumentConfig_typeAutomation(name), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "document_type", "Automation"), @@ -369,7 +369,7 @@ func TestAccSSMDocument_package(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentTypePackageConfig(name, rInt), + Config: testAccDocumentConfig_typePackage(name, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "document_type", "Package"), @@ -382,7 +382,7 @@ func TestAccSSMDocument_package(t *testing.T) { ImportStateVerifyIgnore: []string{"attachments_source"}, // This doesn't work because the API doesn't provide attachments info directly }, { - Config: testAccDocumentTypePackageConfig(name, rInt2), + Config: testAccDocumentConfig_typePackage(name, rInt2), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "document_type", "Package"), @@ -403,7 +403,7 @@ func TestAccSSMDocument_SchemaVersion_1(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentSchemaVersion1Config(rName), + Config: testAccDocumentConfig_schemaVersion1(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "schema_version", "1.0"), @@ -415,7 +415,7 @@ func TestAccSSMDocument_SchemaVersion_1(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentSchemaVersion1UpdateConfig(rName), + Config: testAccDocumentConfig_schemaVersion1Update(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "schema_version", "1.0"), @@ -435,7 +435,7 @@ func TestAccSSMDocument_session(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentTypeSessionConfig(name), + Config: testAccDocumentConfig_typeSession(name), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "document_type", "Session"), @@ -482,7 +482,7 @@ mainSteps: CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentConfig_DocumentFormat_YAML(name, content1), + Config: testAccDocumentConfig_formatYAML(name, content1), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "content", content1+"\n"), @@ -495,7 +495,7 @@ mainSteps: ImportStateVerify: true, }, { - Config: testAccDocumentConfig_DocumentFormat_YAML(name, content2), + Config: testAccDocumentConfig_formatYAML(name, content2), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "content", content2+"\n"), @@ -517,7 +517,7 @@ func TestAccSSMDocument_tags(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentConfig_Tags_Single(rName, "key1", "value1"), + Config: testAccDocumentConfig_tagsSingle(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -530,7 +530,7 @@ func TestAccSSMDocument_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDocumentConfig_Tags_Multiple(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDocumentConfig_tagsMultiple(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -539,7 +539,7 @@ func TestAccSSMDocument_tags(t *testing.T) { ), }, { - Config: testAccDocumentConfig_Tags_Single(rName, "key2", "value2updated"), + Config: testAccDocumentConfig_tagsSingle(rName, "key2", "value2updated"), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -560,7 +560,7 @@ func TestAccSSMDocument_disappears(t *testing.T) { CheckDestroy: testAccCheckDocumentDestroy, Steps: []resource.TestStep{ { - Config: testAccDocumentBasicConfig(name), + Config: testAccDocumentConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckDocumentExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfssm.ResourceDocument(), resourceName), @@ -666,7 +666,7 @@ func testAccCheckDocumentDestroy(s *terraform.State) error { Based on examples from here: https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/create-ssm-doc.html */ -func testAccDocumentBasicConfig(rName string) string { +func testAccDocumentConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "%s" @@ -696,7 +696,7 @@ DOC `, rName) } -func testAccDocumentBasicTargetTypeConfig(rName, typ string) string { +func testAccDocumentConfig_basicTargetType(rName, typ string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "%s" @@ -726,7 +726,7 @@ DOC `, rName, typ) } -func testAccDocumentBasicVersionNameConfig(rName, version string) string { +func testAccDocumentConfig_basicVersionName(rName, version string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %[1]q @@ -757,7 +757,7 @@ DOC `, rName, version) } -func testAccDocument20Config(rName string) string { +func testAccDocumentConfig_20(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "test_document-%s" @@ -786,7 +786,7 @@ DOC `, rName) } -func testAccDocument20UpdatedConfig(rName string) string { +func testAccDocumentConfig_20Updated(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "test_document-%s" @@ -815,7 +815,7 @@ DOC `, rName) } -func testAccDocumentPublicPermissionConfig(rName string) string { +func testAccDocumentConfig_publicPermission(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "test_document-%s" @@ -850,7 +850,7 @@ DOC `, rName) } -func testAccDocumentPrivatePermissionConfig(rName string, rIds string) string { +func testAccDocumentConfig_privatePermission(rName string, rIds string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "test_document-%s" @@ -885,7 +885,7 @@ DOC `, rName, rIds) } -func testAccDocumentParamConfig(rName string) string { +func testAccDocumentConfig_param(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "test_document-%s" @@ -934,8 +934,8 @@ DOC `, rName) } -func testAccDocumentTypeAutomationConfig(rName string) string { - return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), fmt.Sprintf(` +func testAccDocumentConfig_typeAutomation(rName string) string { + return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_iam_instance_profile" "ssm_profile" { name = "ssm_profile-%[1]s" role = aws_iam_role.ssm_role.name @@ -1021,7 +1021,7 @@ DOC `, rName)) } -func testAccDocumentTypePackageConfig(rName string, rInt int) string { +func testAccDocumentConfig_typePackage(rName string, rInt int) string { return fmt.Sprintf(` resource "aws_iam_instance_profile" "test" { name = "ssm_profile-%[1]s" @@ -1131,7 +1131,7 @@ DOC `, rName, rInt) } -func testAccDocumentTypeSessionConfig(rName string) string { +func testAccDocumentConfig_typeSession(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = "test_document-%s" @@ -1156,7 +1156,7 @@ DOC `, rName) } -func testAccDocumentConfig_DocumentFormat_YAML(rName, content string) string { +func testAccDocumentConfig_formatYAML(rName, content string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { document_format = "YAML" @@ -1171,7 +1171,7 @@ DOC `, rName, content) } -func testAccDocumentSchemaVersion1Config(rName string) string { +func testAccDocumentConfig_schemaVersion1(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %q @@ -1196,7 +1196,7 @@ DOC `, rName) } -func testAccDocumentSchemaVersion1UpdateConfig(rName string) string { +func testAccDocumentConfig_schemaVersion1Update(rName string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { name = %q @@ -1221,7 +1221,7 @@ DOC `, rName) } -func testAccDocumentConfig_Tags_Single(rName, key1, value1 string) string { +func testAccDocumentConfig_tagsSingle(rName, key1, value1 string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { document_type = "Command" @@ -1254,7 +1254,7 @@ DOC `, rName, key1, value1) } -func testAccDocumentConfig_Tags_Multiple(rName, key1, value1, key2, value2 string) string { +func testAccDocumentConfig_tagsMultiple(rName, key1, value1, key2, value2 string) string { return fmt.Sprintf(` resource "aws_ssm_document" "test" { document_type = "Command" diff --git a/internal/service/ssm/instances_data_source_test.go b/internal/service/ssm/instances_data_source_test.go index bff7b802434..c28c673bb0d 100644 --- a/internal/service/ssm/instances_data_source_test.go +++ b/internal/service/ssm/instances_data_source_test.go @@ -32,10 +32,10 @@ func TestAccSSMInstancesDataSource_filter(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckInstancesDataSourceConfig_filter_instance(rName), + Config: testAccInstancesDataSourceConfig_filterInstance(rName), }, { - Config: testAccCheckInstancesDataSourceConfig_filter_dataSource(rName), + Config: testAccInstancesDataSourceConfig_filter(rName), Check: resource.ComposeAggregateTestCheckFunc( registrationSleep(), resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), @@ -46,7 +46,7 @@ func TestAccSSMInstancesDataSource_filter(t *testing.T) { }) } -func testAccCheckInstancesDataSourceConfig_filter_instance(rName string) string { +func testAccInstancesDataSourceConfig_filterInstance(rName string) string { return acctest.ConfigCompose( acctest.ConfigAvailableAZsNoOptInDefaultExclude(), acctest.AvailableEC2InstanceTypeForRegion("t2.micro", "t3.micro"), @@ -159,9 +159,9 @@ resource "aws_instance" "test" { `, rName)) } -func testAccCheckInstancesDataSourceConfig_filter_dataSource(rName string) string { +func testAccInstancesDataSourceConfig_filter(rName string) string { return acctest.ConfigCompose( - testAccCheckInstancesDataSourceConfig_filter_instance(rName), + testAccInstancesDataSourceConfig_filterInstance(rName), ` data "aws_ssm_instances" "test" { filter { diff --git a/internal/service/ssm/maintenance_window.go b/internal/service/ssm/maintenance_window.go index a605b444439..86e6f70a272 100644 --- a/internal/service/ssm/maintenance_window.go +++ b/internal/service/ssm/maintenance_window.go @@ -187,19 +187,14 @@ func resourceMaintenanceWindowUpdate(d *schema.ResourceData, meta interface{}) e _, err := conn.UpdateMaintenanceWindow(params) if err != nil { - if tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { - log.Printf("[WARN] Maintenance Window %s not found, removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("error updating SSM Maintenance Window (%s): %s", d.Id(), err) + return fmt.Errorf("error updating SSM Maintenance Window (%s): %w", d.Id(), err) } if d.HasChange("tags_all") { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), ssm.ResourceTypeForTaggingMaintenanceWindow, o, n); err != nil { - return fmt.Errorf("error updating SSM Maintenance Window (%s) tags: %s", d.Id(), err) + return fmt.Errorf("error updating SSM Maintenance Window (%s) tags: %w", d.Id(), err) } } @@ -217,12 +212,12 @@ func resourceMaintenanceWindowRead(d *schema.ResourceData, meta interface{}) err resp, err := conn.GetMaintenanceWindow(params) if err != nil { - if tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { log.Printf("[WARN] Maintenance Window %s not found, removing from state", d.Id()) d.SetId("") return nil } - return fmt.Errorf("error reading SSM Maintenance Window (%s): %s", d.Id(), err) + return fmt.Errorf("error reading SSM Maintenance Window (%s): %w", d.Id(), err) } d.Set("allow_unassociated_targets", resp.AllowUnassociatedTargets) diff --git a/internal/service/ssm/maintenance_window_target.go b/internal/service/ssm/maintenance_window_target.go index 05673f075ec..3fde04446fe 100644 --- a/internal/service/ssm/maintenance_window_target.go +++ b/internal/service/ssm/maintenance_window_target.go @@ -141,7 +141,7 @@ func resourceMaintenanceWindowTargetRead(d *schema.ResourceData, meta interface{ } resp, err := conn.DescribeMaintenanceWindowTargets(params) - if tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { log.Printf("[WARN] Maintenance Window (%s) Target (%s) not found, removing from state", windowID, d.Id()) d.SetId("") return nil @@ -164,10 +164,12 @@ func resourceMaintenanceWindowTargetRead(d *schema.ResourceData, meta interface{ if err := d.Set("targets", flattenTargets(t.Targets)); err != nil { return fmt.Errorf("Error setting targets: %w", err) } + + break } } - if !found { + if !d.IsNewResource() && !found { log.Printf("[INFO] Maintenance Window Target not found. Removing from state") d.SetId("") return nil diff --git a/internal/service/ssm/maintenance_window_target_test.go b/internal/service/ssm/maintenance_window_target_test.go index 266a6f9838e..e1aa2f540b4 100644 --- a/internal/service/ssm/maintenance_window_target_test.go +++ b/internal/service/ssm/maintenance_window_target_test.go @@ -27,7 +27,7 @@ func TestAccSSMMaintenanceWindowTarget_basic(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTargetBasicConfig(rName), + Config: testAccMaintenanceWindowTargetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTargetExists(resourceName, &maint), resource.TestCheckResourceAttr(resourceName, "targets.0.key", "tag:Name"), @@ -63,7 +63,7 @@ func TestAccSSMMaintenanceWindowTarget_noNameOrDescription(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTargetNoNameOrDescriptionConfig(rName), + Config: testAccMaintenanceWindowTargetConfig_noNameOrDescription(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTargetExists(resourceName, &maint), resource.TestCheckResourceAttr(resourceName, "targets.0.key", "tag:Name"), @@ -94,15 +94,15 @@ func TestAccSSMMaintenanceWindowTarget_validation(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTargetBasicWithTargetConfig(name, "Bäd Name!@#$%^", "good description"), + Config: testAccMaintenanceWindowTargetConfig_basic2(name, "Bäd Name!@#$%^", "good description"), ExpectError: regexp.MustCompile(`Only alphanumeric characters, hyphens, dots & underscores allowed`), }, { - Config: testAccMaintenanceWindowTargetBasicWithTargetConfig(name, "goodname", "bd"), + Config: testAccMaintenanceWindowTargetConfig_basic2(name, "goodname", "bd"), ExpectError: regexp.MustCompile(`expected length of [\w]+ to be in the range \(3 - 128\), got [\w]+`), }, { - Config: testAccMaintenanceWindowTargetBasicWithTargetConfig(name, "goodname", "This description is tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo long"), + Config: testAccMaintenanceWindowTargetConfig_basic2(name, "goodname", "This description is tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo long"), ExpectError: regexp.MustCompile(`expected length of [\w]+ to be in the range \(3 - 128\), got [\w]+`), }, }, @@ -120,7 +120,7 @@ func TestAccSSMMaintenanceWindowTarget_update(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTargetBasicConfig(rName), + Config: testAccMaintenanceWindowTargetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTargetExists(resourceName, &maint), resource.TestCheckResourceAttr(resourceName, "targets.0.key", "tag:Name"), @@ -141,7 +141,7 @@ func TestAccSSMMaintenanceWindowTarget_update(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowTargetBasicUpdatedConfig(rName), + Config: testAccMaintenanceWindowTargetConfig_basicUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTargetExists(resourceName, &maint), resource.TestCheckResourceAttr(resourceName, "owner_information", "something"), @@ -176,7 +176,7 @@ func TestAccSSMMaintenanceWindowTarget_resourceGroup(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTargetBasicResourceGroupConfig(rName), + Config: testAccMaintenanceWindowTargetConfig_basicResourceGroup(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTargetExists(resourceName, &maint), resource.TestCheckResourceAttr(resourceName, "targets.0.key", "resource-groups:ResourceTypeFilters"), @@ -211,7 +211,7 @@ func TestAccSSMMaintenanceWindowTarget_disappears(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTargetBasicConfig(rName), + Config: testAccMaintenanceWindowTargetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTargetExists(resourceName, &maint), acctest.CheckResourceDisappears(acctest.Provider, tfssm.ResourceMaintenanceWindowTarget(), resourceName), @@ -233,7 +233,7 @@ func TestAccSSMMaintenanceWindowTarget_Disappears_window(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTargetDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTargetBasicConfig(rName), + Config: testAccMaintenanceWindowTargetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTargetExists(resourceName, &maint), acctest.CheckResourceDisappears(acctest.Provider, tfssm.ResourceMaintenanceWindow(), "aws_ssm_maintenance_window.test"), @@ -317,7 +317,7 @@ func testAccCheckMaintenanceWindowTargetDestroy(s *terraform.State) error { return nil } -func testAccMaintenanceWindowTargetBasicConfig(rName string) string { +func testAccMaintenanceWindowTargetConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { name = %[1]q @@ -345,7 +345,7 @@ resource "aws_ssm_maintenance_window_target" "test" { `, rName) } -func testAccMaintenanceWindowTargetBasicResourceGroupConfig(rName string) string { +func testAccMaintenanceWindowTargetConfig_basicResourceGroup(rName string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { name = %[1]q @@ -373,7 +373,7 @@ resource "aws_ssm_maintenance_window_target" "test" { `, rName) } -func testAccMaintenanceWindowTargetNoNameOrDescriptionConfig(rName string) string { +func testAccMaintenanceWindowTargetConfig_noNameOrDescription(rName string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { name = %[1]q @@ -399,7 +399,7 @@ resource "aws_ssm_maintenance_window_target" "test" { `, rName) } -func testAccMaintenanceWindowTargetBasicUpdatedConfig(rName string) string { +func testAccMaintenanceWindowTargetConfig_basicUpdated(rName string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { name = %[1]q @@ -428,7 +428,7 @@ resource "aws_ssm_maintenance_window_target" "test" { `, rName) } -func testAccMaintenanceWindowTargetBasicWithTargetConfig(rName, tName, tDesc string) string { +func testAccMaintenanceWindowTargetConfig_basic2(rName, tName, tDesc string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { name = %[1]q diff --git a/internal/service/ssm/maintenance_window_task.go b/internal/service/ssm/maintenance_window_task.go index 1d19f064f09..8a8b54ef8e7 100644 --- a/internal/service/ssm/maintenance_window_task.go +++ b/internal/service/ssm/maintenance_window_task.go @@ -733,7 +733,7 @@ func resourceMaintenanceWindowTaskRead(d *schema.ResourceData, meta interface{}) WindowTaskId: aws.String(d.Id()), } resp, err := conn.GetMaintenanceWindowTask(params) - if tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { log.Printf("[WARN] Maintenance Window (%s) Task (%s) not found, removing from state", windowID, d.Id()) d.SetId("") return nil @@ -825,14 +825,8 @@ func resourceMaintenanceWindowTaskUpdate(d *schema.ResourceData, meta interface{ } _, err := conn.UpdateMaintenanceWindowTask(params) - if tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { - log.Printf("[WARN] Maintenance Window (%s) Task (%s) not found, removing from state", windowID, d.Id()) - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error updating Maintenance Window (%s) Task (%s): %s", windowID, d.Id(), err) + return fmt.Errorf("error updating Maintenance Window (%s) Task (%s): %w", windowID, d.Id(), err) } return resourceMaintenanceWindowTaskRead(d, meta) @@ -853,7 +847,7 @@ func resourceMaintenanceWindowTaskDelete(d *schema.ResourceData, meta interface{ return nil } if err != nil { - return fmt.Errorf("error deregistering SSM Maintenance Window Task (%s): %s", d.Id(), err) + return fmt.Errorf("error deregistering SSM Maintenance Window Task (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/ssm/maintenance_window_task_test.go b/internal/service/ssm/maintenance_window_task_test.go index b97cac70b9a..c7554cf616b 100644 --- a/internal/service/ssm/maintenance_window_task_test.go +++ b/internal/service/ssm/maintenance_window_task_test.go @@ -28,7 +28,7 @@ func TestAccSSMMaintenanceWindowTask_basic(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskBasicConfig(rName), + Config: testAccMaintenanceWindowTaskConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &before), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ssm", regexp.MustCompile(`windowtask/.+`)), @@ -38,7 +38,7 @@ func TestAccSSMMaintenanceWindowTask_basic(t *testing.T) { ), }, { - Config: testAccMaintenanceWindowTaskBasicUpdateConfig(rName, "test description", "RUN_COMMAND", "AWS-InstallPowerShellModule", 3, 3, 2), + Config: testAccMaintenanceWindowTaskConfig_basicUpdate(rName, "test description", "RUN_COMMAND", "AWS-InstallPowerShellModule", 3, 3, 2), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("maintenance-window-task-%s", rName)), @@ -73,7 +73,7 @@ func TestAccSSMMaintenanceWindowTask_noTarget(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskNoTargetConfig(rName), + Config: testAccMaintenanceWindowTaskConfig_noTarget(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "targets.#", "0"), @@ -101,7 +101,7 @@ func TestAccSSMMaintenanceWindowTask_cutoff(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskCutoffConfig(rName, "CANCEL_TASK"), + Config: testAccMaintenanceWindowTaskConfig_cutoff(rName, "CANCEL_TASK"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "cutoff_behavior", "CANCEL_TASK"), @@ -114,7 +114,7 @@ func TestAccSSMMaintenanceWindowTask_cutoff(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowTaskCutoffConfig(rName, "CONTINUE_TASK"), + Config: testAccMaintenanceWindowTaskConfig_cutoff(rName, "CONTINUE_TASK"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "cutoff_behavior", "CONTINUE_TASK"), @@ -136,7 +136,7 @@ func TestAccSSMMaintenanceWindowTask_noRole(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskNoRoleConfig(rName), + Config: testAccMaintenanceWindowTaskConfig_noRole(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), ), @@ -157,13 +157,13 @@ func TestAccSSMMaintenanceWindowTask_updateForcesNewResource(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskBasicConfig(rName), + Config: testAccMaintenanceWindowTaskConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &before), ), }, { - Config: testAccMaintenanceWindowTaskBasicUpdatedConfig(rName), + Config: testAccMaintenanceWindowTaskConfig_basicUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", "TestMaintenanceWindowTask"), @@ -193,7 +193,7 @@ func TestAccSSMMaintenanceWindowTask_description(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskDescriptionConfig(rName, "description1"), + Config: testAccMaintenanceWindowTaskConfig_description(rName, "description1"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task1), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -206,7 +206,7 @@ func TestAccSSMMaintenanceWindowTask_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowTaskDescriptionConfig(rName, "description2"), + Config: testAccMaintenanceWindowTaskConfig_description(rName, "description2"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task2), resource.TestCheckResourceAttr(resourceName, "description", "description2"), @@ -229,14 +229,14 @@ func TestAccSSMMaintenanceWindowTask_taskInvocationAutomationParameters(t *testi CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskAutomationConfig(rName, "$DEFAULT"), + Config: testAccMaintenanceWindowTaskConfig_automation(rName, "$DEFAULT"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), resource.TestCheckResourceAttr(resourceName, "task_invocation_parameters.0.automation_parameters.0.document_version", "$DEFAULT"), ), }, { - Config: testAccMaintenanceWindowTaskAutomationUpdateConfig(rName, "$LATEST"), + Config: testAccMaintenanceWindowTaskConfig_automationUpdate(rName, "$LATEST"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), resource.TestCheckResourceAttr(resourceName, "task_invocation_parameters.0.automation_parameters.0.document_version", "$LATEST"), @@ -270,7 +270,7 @@ func TestAccSSMMaintenanceWindowTask_taskInvocationLambdaParameters(t *testing.T CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskLambdaConfig(funcName, policyName, roleName, sgName, rString, rInt), + Config: testAccMaintenanceWindowTaskConfig_lambda(funcName, policyName, roleName, sgName, rString, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), ), @@ -299,7 +299,7 @@ func TestAccSSMMaintenanceWindowTask_taskInvocationRunCommandParameters(t *testi CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskRunCommandConfig(rName, "test comment", 30), + Config: testAccMaintenanceWindowTaskConfig_runCommand(rName, "test comment", 30), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), resource.TestCheckResourceAttrPair(resourceName, "service_role_arn", serviceRoleResourceName, "arn"), @@ -309,7 +309,7 @@ func TestAccSSMMaintenanceWindowTask_taskInvocationRunCommandParameters(t *testi ), }, { - Config: testAccMaintenanceWindowTaskRunCommandUpdateConfig(rName, "test comment update", 60), + Config: testAccMaintenanceWindowTaskConfig_runCommandUpdate(rName, "test comment update", 60), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), resource.TestCheckResourceAttr(resourceName, "task_invocation_parameters.0.run_command_parameters.0.comment", "test comment update"), @@ -341,7 +341,7 @@ func TestAccSSMMaintenanceWindowTask_taskInvocationRunCommandParametersCloudWatc CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskRunCommandCloudWatchConfig(name, true), + Config: testAccMaintenanceWindowTaskConfig_runCommandCloudWatch(name, true), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), resource.TestCheckResourceAttrPair(resourceName, "service_role_arn", serviceRoleResourceName, "arn"), @@ -357,7 +357,7 @@ func TestAccSSMMaintenanceWindowTask_taskInvocationRunCommandParametersCloudWatc ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowTaskRunCommandCloudWatchConfig(name, false), + Config: testAccMaintenanceWindowTaskConfig_runCommandCloudWatch(name, false), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), resource.TestCheckResourceAttrPair(resourceName, "service_role_arn", serviceRoleResourceName, "arn"), @@ -366,7 +366,7 @@ func TestAccSSMMaintenanceWindowTask_taskInvocationRunCommandParametersCloudWatc ), }, { - Config: testAccMaintenanceWindowTaskRunCommandCloudWatchConfig(name, true), + Config: testAccMaintenanceWindowTaskConfig_runCommandCloudWatch(name, true), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), resource.TestCheckResourceAttrPair(resourceName, "service_role_arn", serviceRoleResourceName, "arn"), @@ -391,7 +391,7 @@ func TestAccSSMMaintenanceWindowTask_taskInvocationStepFunctionParameters(t *tes CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskStepFunctionConfig(rString), + Config: testAccMaintenanceWindowTaskConfig_stepFunction(rString), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), ), @@ -418,7 +418,7 @@ func TestAccSSMMaintenanceWindowTask_emptyNotification(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskEmptyNotifcationConfig(rName), + Config: testAccMaintenanceWindowTaskConfig_emptyNotifcation(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &task), ), @@ -440,7 +440,7 @@ func TestAccSSMMaintenanceWindowTask_disappears(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowTaskDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTaskBasicConfig(name), + Config: testAccMaintenanceWindowTaskConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowTaskExists(resourceName, &before), acctest.CheckResourceDisappears(acctest.Provider, tfssm.ResourceMaintenanceWindowTask(), resourceName), @@ -601,7 +601,7 @@ POLICY `, rName) } -func testAccMaintenanceWindowTaskBasicConfig(rName string) string { +func testAccMaintenanceWindowTaskConfig_basic(rName string) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName) + ` resource "aws_ssm_maintenance_window_task" "test" { @@ -630,7 +630,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `) } -func testAccMaintenanceWindowTaskNoTargetConfig(rName string) string { +func testAccMaintenanceWindowTaskConfig_noTarget(rName string) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName) + ` resource "aws_ssm_maintenance_window_task" "test" { @@ -643,7 +643,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `) } -func testAccMaintenanceWindowTaskCutoffConfig(rName, cutoff string) string { +func testAccMaintenanceWindowTaskConfig_cutoff(rName, cutoff string) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName)+` resource "aws_ssm_maintenance_window_task" "test" { @@ -657,7 +657,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `, cutoff) } -func testAccMaintenanceWindowTaskBasicUpdateConfig(rName, description, taskType, taskArn string, priority, maxConcurrency, maxErrors int) string { +func testAccMaintenanceWindowTaskConfig_basicUpdate(rName, description, taskType, taskArn string, priority, maxConcurrency, maxErrors int) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName)+` resource "aws_ssm_maintenance_window_task" "test" { @@ -724,7 +724,7 @@ EOF `, rName, taskType, taskArn, description, priority, maxConcurrency, maxErrors) } -func testAccMaintenanceWindowTaskBasicUpdatedConfig(rName string) string { +func testAccMaintenanceWindowTaskConfig_basicUpdated(rName string) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName) + ` resource "aws_ssm_maintenance_window_task" "test" { @@ -755,7 +755,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `) } -func testAccMaintenanceWindowTaskDescriptionConfig(rName string, description string) string { +func testAccMaintenanceWindowTaskConfig_description(rName string, description string) string { return acctest.ConfigCompose( testAccMaintenanceWindowTaskBaseConfig(rName), fmt.Sprintf(` @@ -784,7 +784,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `, description)) } -func testAccMaintenanceWindowTaskEmptyNotifcationConfig(rName string) string { +func testAccMaintenanceWindowTaskConfig_emptyNotifcation(rName string) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName) + ` resource "aws_ssm_maintenance_window_task" "test" { @@ -817,7 +817,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `) } -func testAccMaintenanceWindowTaskNoRoleConfig(rName string) string { +func testAccMaintenanceWindowTaskConfig_noRole(rName string) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName) + ` resource "aws_ssm_maintenance_window_task" "test" { description = "This resource is for test purpose only" @@ -846,7 +846,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `) } -func testAccMaintenanceWindowTaskAutomationConfig(rName, version string) string { +func testAccMaintenanceWindowTaskConfig_automation(rName, version string) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName)+` resource "aws_ssm_maintenance_window_task" "test" { @@ -882,7 +882,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `, rName, version) } -func testAccMaintenanceWindowTaskAutomationUpdateConfig(rName, version string) string { +func testAccMaintenanceWindowTaskConfig_automationUpdate(rName, version string) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName)+` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -927,7 +927,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `, rName, version) } -func testAccMaintenanceWindowTaskLambdaConfig(funcName, policyName, roleName, sgName, rName string, rInt int) string { +func testAccMaintenanceWindowTaskConfig_lambda(funcName, policyName, roleName, sgName, rName string, rInt int) string { return fmt.Sprintf(testAccLambdaBasicConfig(funcName, policyName, roleName, sgName)+ testAccMaintenanceWindowTaskBaseConfig(rName)+` @@ -961,7 +961,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `, rName, rInt) } -func testAccMaintenanceWindowTaskRunCommandConfig(rName, comment string, timeoutSeconds int) string { +func testAccMaintenanceWindowTaskConfig_runCommand(rName, comment string, timeoutSeconds int) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName)+` resource "aws_ssm_maintenance_window_task" "test" { @@ -996,7 +996,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `, rName, comment, timeoutSeconds) } -func testAccMaintenanceWindowTaskRunCommandUpdateConfig(rName, comment string, timeoutSeconds int) string { +func testAccMaintenanceWindowTaskConfig_runCommandUpdate(rName, comment string, timeoutSeconds int) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName)+` resource "aws_s3_bucket" "test" { bucket = %[1]q @@ -1042,7 +1042,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `, rName, comment, timeoutSeconds) } -func testAccMaintenanceWindowTaskRunCommandCloudWatchConfig(rName string, enabled bool) string { +func testAccMaintenanceWindowTaskConfig_runCommandCloudWatch(rName string, enabled bool) string { return fmt.Sprintf(testAccMaintenanceWindowTaskBaseConfig(rName)+` resource "aws_cloudwatch_log_group" "test" { name = %[1]q @@ -1083,7 +1083,7 @@ resource "aws_ssm_maintenance_window_task" "test" { `, rName, enabled) } -func testAccMaintenanceWindowTaskStepFunctionConfig(rName string) string { +func testAccMaintenanceWindowTaskConfig_stepFunction(rName string) string { return testAccMaintenanceWindowTaskBaseConfig(rName) + fmt.Sprintf(` resource "aws_sfn_activity" "test" { name = %[1]q diff --git a/internal/service/ssm/maintenance_window_test.go b/internal/service/ssm/maintenance_window_test.go index db329b8ff16..0258f9855aa 100644 --- a/internal/service/ssm/maintenance_window_test.go +++ b/internal/service/ssm/maintenance_window_test.go @@ -27,7 +27,7 @@ func TestAccSSMMaintenanceWindow_basic(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowConfig(rName), + Config: testAccMaintenanceWindowConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &winId), resource.TestCheckResourceAttr(resourceName, "cutoff", "1"), @@ -63,7 +63,7 @@ func TestAccSSMMaintenanceWindow_description(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowDescriptionConfig(rName, "foo"), + Config: testAccMaintenanceWindowConfig_description(rName, "foo"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &winId), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -76,7 +76,7 @@ func TestAccSSMMaintenanceWindow_description(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowDescriptionConfig(rName, "bar"), + Config: testAccMaintenanceWindowConfig_description(rName, "bar"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &winId), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -99,7 +99,7 @@ func TestAccSSMMaintenanceWindow_tags(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowTags1Config(rName, "key1", "value1"), + Config: testAccMaintenanceWindowConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &winId), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -112,7 +112,7 @@ func TestAccSSMMaintenanceWindow_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccMaintenanceWindowConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &winId), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -121,7 +121,7 @@ func TestAccSSMMaintenanceWindow_tags(t *testing.T) { ), }, { - Config: testAccMaintenanceWindowTags1Config(rName, "key2", "value2"), + Config: testAccMaintenanceWindowConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &winId), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -144,7 +144,7 @@ func TestAccSSMMaintenanceWindow_disappears(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowConfig(rName), + Config: testAccMaintenanceWindowConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &winId), testAccCheckMaintenanceWindowDisappears(&winId), @@ -168,7 +168,7 @@ func TestAccSSMMaintenanceWindow_multipleUpdates(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowConfig(rName1), + Config: testAccMaintenanceWindowConfig_basic(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow1), resource.TestCheckResourceAttr(resourceName, "cutoff", "1"), @@ -179,7 +179,7 @@ func TestAccSSMMaintenanceWindow_multipleUpdates(t *testing.T) { ), }, { - Config: testAccMaintenanceWindowMultipleUpdatesConfig(rName2), + Config: testAccMaintenanceWindowConfig_multipleUpdates(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow2), resource.TestCheckResourceAttr(resourceName, "cutoff", "8"), @@ -205,7 +205,7 @@ func TestAccSSMMaintenanceWindow_cutoff(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowCutoffConfig(rName, 1), + Config: testAccMaintenanceWindowConfig_cutoff(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow1), resource.TestCheckResourceAttr(resourceName, "cutoff", "1"), @@ -217,7 +217,7 @@ func TestAccSSMMaintenanceWindow_cutoff(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowCutoffConfig(rName, 2), + Config: testAccMaintenanceWindowConfig_cutoff(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow2), resource.TestCheckResourceAttr(resourceName, "cutoff", "2"), @@ -239,7 +239,7 @@ func TestAccSSMMaintenanceWindow_duration(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowDurationConfig(rName, 3), + Config: testAccMaintenanceWindowConfig_duration(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow1), resource.TestCheckResourceAttr(resourceName, "duration", "3"), @@ -251,7 +251,7 @@ func TestAccSSMMaintenanceWindow_duration(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowDurationConfig(rName, 10), + Config: testAccMaintenanceWindowConfig_duration(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow2), resource.TestCheckResourceAttr(resourceName, "duration", "10"), @@ -273,7 +273,7 @@ func TestAccSSMMaintenanceWindow_enabled(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowEnabledConfig(rName, false), + Config: testAccMaintenanceWindowConfig_enabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow1), resource.TestCheckResourceAttr(resourceName, "enabled", "false"), @@ -285,7 +285,7 @@ func TestAccSSMMaintenanceWindow_enabled(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowEnabledConfig(rName, true), + Config: testAccMaintenanceWindowConfig_enabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow2), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), @@ -309,7 +309,7 @@ func TestAccSSMMaintenanceWindow_endDate(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowEndDateConfig(rName, endDate1), + Config: testAccMaintenanceWindowConfig_endDate(rName, endDate1), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow1), resource.TestCheckResourceAttr(resourceName, "end_date", endDate1), @@ -321,14 +321,14 @@ func TestAccSSMMaintenanceWindow_endDate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowEndDateConfig(rName, endDate2), + Config: testAccMaintenanceWindowConfig_endDate(rName, endDate2), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow2), resource.TestCheckResourceAttr(resourceName, "end_date", endDate2), ), }, { - Config: testAccMaintenanceWindowConfig(rName), + Config: testAccMaintenanceWindowConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow3), resource.TestCheckResourceAttr(resourceName, "end_date", ""), @@ -350,7 +350,7 @@ func TestAccSSMMaintenanceWindow_schedule(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowScheduleConfig(rName, "cron(0 16 ? * TUE *)"), + Config: testAccMaintenanceWindowConfig_schedule(rName, "cron(0 16 ? * TUE *)"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow1), resource.TestCheckResourceAttr(resourceName, "schedule", "cron(0 16 ? * TUE *)"), @@ -362,7 +362,7 @@ func TestAccSSMMaintenanceWindow_schedule(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowScheduleConfig(rName, "cron(0 16 ? * WED *)"), + Config: testAccMaintenanceWindowConfig_schedule(rName, "cron(0 16 ? * WED *)"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow2), resource.TestCheckResourceAttr(resourceName, "schedule", "cron(0 16 ? * WED *)"), @@ -384,7 +384,7 @@ func TestAccSSMMaintenanceWindow_scheduleTimezone(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowScheduleTimezoneConfig(rName, "America/Los_Angeles"), + Config: testAccMaintenanceWindowConfig_scheduleTimezone(rName, "America/Los_Angeles"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow1), resource.TestCheckResourceAttr(resourceName, "schedule_timezone", "America/Los_Angeles"), @@ -396,14 +396,14 @@ func TestAccSSMMaintenanceWindow_scheduleTimezone(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowScheduleTimezoneConfig(rName, "America/New_York"), + Config: testAccMaintenanceWindowConfig_scheduleTimezone(rName, "America/New_York"), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow2), resource.TestCheckResourceAttr(resourceName, "schedule_timezone", "America/New_York"), ), }, { - Config: testAccMaintenanceWindowConfig(rName), + Config: testAccMaintenanceWindowConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow3), resource.TestCheckResourceAttr(resourceName, "schedule_timezone", ""), @@ -425,7 +425,7 @@ func TestAccSSMMaintenanceWindow_scheduleOffset(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowScheduleOffsetConfig(rName, 2), + Config: testAccMaintenanceWindowConfig_scheduleOffset(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow1), resource.TestCheckResourceAttr(resourceName, "schedule_offset", "2"), @@ -437,7 +437,7 @@ func TestAccSSMMaintenanceWindow_scheduleOffset(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowScheduleOffsetConfig(rName, 5), + Config: testAccMaintenanceWindowConfig_scheduleOffset(rName, 5), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow2), resource.TestCheckResourceAttr(resourceName, "schedule_offset", "5"), @@ -461,7 +461,7 @@ func TestAccSSMMaintenanceWindow_startDate(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccMaintenanceWindowStartDateConfig(rName, startDate1), + Config: testAccMaintenanceWindowConfig_startDate(rName, startDate1), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow1), resource.TestCheckResourceAttr(resourceName, "start_date", startDate1), @@ -473,14 +473,14 @@ func TestAccSSMMaintenanceWindow_startDate(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccMaintenanceWindowStartDateConfig(rName, startDate2), + Config: testAccMaintenanceWindowConfig_startDate(rName, startDate2), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow2), resource.TestCheckResourceAttr(resourceName, "start_date", startDate2), ), }, { - Config: testAccMaintenanceWindowConfig(rName), + Config: testAccMaintenanceWindowConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckMaintenanceWindowExists(resourceName, &maintenanceWindow3), resource.TestCheckResourceAttr(resourceName, "start_date", ""), @@ -570,7 +570,7 @@ func testAccCheckMaintenanceWindowDestroy(s *terraform.State) error { return nil } -func testAccMaintenanceWindowConfig(rName string) string { +func testAccMaintenanceWindowConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -581,7 +581,7 @@ resource "aws_ssm_maintenance_window" "test" { `, rName) } -func testAccMaintenanceWindowDescriptionConfig(rName, desc string) string { +func testAccMaintenanceWindowConfig_description(rName, desc string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -593,7 +593,7 @@ resource "aws_ssm_maintenance_window" "test" { `, rName, desc) } -func testAccMaintenanceWindowTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccMaintenanceWindowConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -608,7 +608,7 @@ resource "aws_ssm_maintenance_window" "test" { `, rName, tagKey1, tagValue1) } -func testAccMaintenanceWindowTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccMaintenanceWindowConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -624,7 +624,7 @@ resource "aws_ssm_maintenance_window" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccMaintenanceWindowCutoffConfig(rName string, cutoff int) string { +func testAccMaintenanceWindowConfig_cutoff(rName string, cutoff int) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = %d @@ -635,7 +635,7 @@ resource "aws_ssm_maintenance_window" "test" { `, cutoff, rName) } -func testAccMaintenanceWindowDurationConfig(rName string, duration int) string { +func testAccMaintenanceWindowConfig_duration(rName string, duration int) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -646,7 +646,7 @@ resource "aws_ssm_maintenance_window" "test" { `, duration, rName) } -func testAccMaintenanceWindowEnabledConfig(rName string, enabled bool) string { +func testAccMaintenanceWindowConfig_enabled(rName string, enabled bool) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -658,7 +658,7 @@ resource "aws_ssm_maintenance_window" "test" { `, enabled, rName) } -func testAccMaintenanceWindowEndDateConfig(rName, endDate string) string { +func testAccMaintenanceWindowConfig_endDate(rName, endDate string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -670,7 +670,7 @@ resource "aws_ssm_maintenance_window" "test" { `, endDate, rName) } -func testAccMaintenanceWindowMultipleUpdatesConfig(rName string) string { +func testAccMaintenanceWindowConfig_multipleUpdates(rName string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 8 @@ -682,7 +682,7 @@ resource "aws_ssm_maintenance_window" "test" { `, rName) } -func testAccMaintenanceWindowScheduleConfig(rName, schedule string) string { +func testAccMaintenanceWindowConfig_schedule(rName, schedule string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -693,7 +693,7 @@ resource "aws_ssm_maintenance_window" "test" { `, rName, schedule) } -func testAccMaintenanceWindowScheduleTimezoneConfig(rName, scheduleTimezone string) string { +func testAccMaintenanceWindowConfig_scheduleTimezone(rName, scheduleTimezone string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -705,7 +705,7 @@ resource "aws_ssm_maintenance_window" "test" { `, rName, scheduleTimezone) } -func testAccMaintenanceWindowScheduleOffsetConfig(rName string, scheduleOffset int) string { +func testAccMaintenanceWindowConfig_scheduleOffset(rName string, scheduleOffset int) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 @@ -717,7 +717,7 @@ resource "aws_ssm_maintenance_window" "test" { `, rName, scheduleOffset) } -func testAccMaintenanceWindowStartDateConfig(rName, startDate string) string { +func testAccMaintenanceWindowConfig_startDate(rName, startDate string) string { return fmt.Sprintf(` resource "aws_ssm_maintenance_window" "test" { cutoff = 1 diff --git a/internal/service/ssm/maintenance_windows_data_source_test.go b/internal/service/ssm/maintenance_windows_data_source_test.go index d0a6563d0c7..84a1e3639fc 100644 --- a/internal/service/ssm/maintenance_windows_data_source_test.go +++ b/internal/service/ssm/maintenance_windows_data_source_test.go @@ -23,14 +23,14 @@ func TestAccSSMMaintenanceWindowsDataSource_filter(t *testing.T) { CheckDestroy: testAccCheckMaintenanceWindowDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckMaintenanceWindowsDataSourceConfig_filter_name(rName1, rName2, rName3), + Config: testAccMaintenanceWindowsDataSourceConfig_filterName(rName1, rName2, rName3), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), resource.TestCheckResourceAttrPair(dataSourceName, "ids.0", "aws_ssm_maintenance_window.test2", "id"), ), }, { - Config: testAccCheckMaintenanceWindowsDataSourceConfig_filter_enabled(rName1, rName2, rName3), + Config: testAccMaintenanceWindowsDataSourceConfig_filterEnabled(rName1, rName2, rName3), Check: resource.ComposeAggregateTestCheckFunc( acctest.CheckResourceAttrGreaterThanValue(dataSourceName, "ids.#", "1"), ), @@ -66,7 +66,7 @@ resource "aws_ssm_maintenance_window" "test3" { `, rName1, rName2, rName3) } -func testAccCheckMaintenanceWindowsDataSourceConfig_filter_name(rName1, rName2, rName3 string) string { +func testAccMaintenanceWindowsDataSourceConfig_filterName(rName1, rName2, rName3 string) string { return acctest.ConfigCompose( testAccCheckMaintenanceWindowsDataSourceConfig(rName1, rName2, rName3), fmt.Sprintf(` @@ -85,7 +85,7 @@ data "aws_ssm_maintenance_windows" "test" { `, rName2)) } -func testAccCheckMaintenanceWindowsDataSourceConfig_filter_enabled(rName1, rName2, rName3 string) string { +func testAccMaintenanceWindowsDataSourceConfig_filterEnabled(rName1, rName2, rName3 string) string { return acctest.ConfigCompose( testAccCheckMaintenanceWindowsDataSourceConfig(rName1, rName2, rName3), ` diff --git a/internal/service/ssm/parameter.go b/internal/service/ssm/parameter.go index f6e3a725e6b..4590449d829 100644 --- a/internal/service/ssm/parameter.go +++ b/internal/service/ssm/parameter.go @@ -49,10 +49,13 @@ func ResourceParameter() *schema.Resource { "tier": { Type: schema.TypeString, Optional: true, - Default: ssm.ParameterTierStandard, + Computed: true, ValidateFunc: validation.StringInSlice(ssm.ParameterTier_Values(), false), DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { - return d.Get("tier").(string) == ssm.ParameterTierIntelligentTiering + if old != "" { + return new == ssm.ParameterTierIntelligentTiering + } + return false }, }, "type": { @@ -104,10 +107,8 @@ func ResourceParameter() *schema.Resource { CustomizeDiff: customdiff.Sequence( // Prevent the following error during tier update from Advanced to Standard: // ValidationException: This parameter uses the advanced-parameter tier. You can't downgrade a parameter from the advanced-parameter tier to the standard-parameter tier. If necessary, you can delete the advanced parameter and recreate it as a standard parameter. - // In the case of Advanced to Intelligent-Tiering, a ValidationException is not thrown - // but rather no change occurs without resource re-creation customdiff.ForceNewIfChange("tier", func(_ context.Context, old, new, meta interface{}) bool { - return old.(string) == ssm.ParameterTierAdvanced && (new.(string) == ssm.ParameterTierStandard || new.(string) == ssm.ParameterTierIntelligentTiering) + return old.(string) == ssm.ParameterTierAdvanced && new.(string) == ssm.ParameterTierStandard }), customdiff.ComputedIf("version", func(_ context.Context, diff *schema.ResourceDiff, meta interface{}) bool { return diff.HasChange("value") @@ -127,12 +128,14 @@ func resourceParameterCreate(d *schema.ResourceData, meta interface{}) error { paramInput := &ssm.PutParameterInput{ Name: aws.String(name), Type: aws.String(d.Get("type").(string)), - Tier: aws.String(d.Get("tier").(string)), Value: aws.String(d.Get("value").(string)), - Overwrite: aws.Bool(ShouldUpdateParameter(d)), AllowedPattern: aws.String(d.Get("allowed_pattern").(string)), } + if v, ok := d.GetOk("tier"); ok { + paramInput.Tier = aws.String(v.(string)) + } + if v, ok := d.GetOk("data_type"); ok { paramInput.DataType = aws.String(v.(string)) } @@ -145,33 +148,20 @@ func resourceParameterCreate(d *schema.ResourceData, meta interface{}) error { paramInput.SetKeyId(keyID.(string)) } - // AWS SSM Service only supports PutParameter requests with Tags - // iff Overwrite is not provided or is false; in this resource's case, - // the Overwrite value is always set in the paramInput so we check for the value - if len(tags) > 0 && !aws.BoolValue(paramInput.Overwrite) { + if len(tags) > 0 { paramInput.Tags = Tags(tags.IgnoreAWS()) } _, err := conn.PutParameter(paramInput) if tfawserr.ErrMessageContains(err, "ValidationException", "Tier is not supported") { + log.Printf("[WARN] Creating SSM Parameter (%s): tier %q not supported, using default", name, d.Get("tier").(string)) paramInput.Tier = nil _, err = conn.PutParameter(paramInput) } if err != nil { - return fmt.Errorf("error creating SSM parameter (%s): %w", name, err) - } - - // Since the AWS SSM Service does not support PutParameter requests with - // Tags and Overwrite set to true, we make an additional API call - // to Update the resource's tags if necessary - if d.HasChange("tags_all") && paramInput.Tags == nil { - o, n := d.GetChange("tags_all") - - if err := UpdateTags(conn, name, ssm.ResourceTypeForTaggingParameter, o, n); err != nil { - return fmt.Errorf("error updating SSM Parameter (%s) tags: %w", name, err) - } + return fmt.Errorf("error creating SSM Parameter (%s): %w", name, err) } d.SetId(name) @@ -240,7 +230,7 @@ func resourceParameterRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error describing SSM parameter (%s): %w", d.Id(), err) } - if describeResp == nil || len(describeResp.Parameters) == 0 || describeResp.Parameters[0] == nil { + if !d.IsNewResource() && (describeResp == nil || len(describeResp.Parameters) == 0 || describeResp.Parameters[0] == nil) { log.Printf("[WARN] SSM Parameter %q not found, removing from state", d.Id()) d.SetId("") return nil @@ -249,10 +239,7 @@ func resourceParameterRead(d *schema.ResourceData, meta interface{}) error { detail := describeResp.Parameters[0] d.Set("key_id", detail.KeyId) d.Set("description", detail.Description) - d.Set("tier", ssm.ParameterTierStandard) - if detail.Tier != nil { - d.Set("tier", detail.Tier) - } + d.Set("tier", detail.Tier) d.Set("allowed_pattern", detail.AllowedPattern) d.Set("data_type", detail.DataType) @@ -291,6 +278,12 @@ func resourceParameterUpdate(d *schema.ResourceData, meta interface{}) error { AllowedPattern: aws.String(d.Get("allowed_pattern").(string)), } + // Retrieve the value set in the config directly to counteract the DiffSuppressFunc above + tier := d.GetRawConfig().GetAttr("tier") + if tier.IsKnown() && !tier.IsNull() { + paramInput.Tier = aws.String(tier.AsString()) + } + if d.HasChange("data_type") { paramInput.DataType = aws.String(d.Get("data_type").(string)) } @@ -306,12 +299,13 @@ func resourceParameterUpdate(d *schema.ResourceData, meta interface{}) error { _, err := conn.PutParameter(paramInput) if tfawserr.ErrMessageContains(err, "ValidationException", "Tier is not supported") { + log.Printf("[WARN] Updating SSM Parameter (%s): tier %q not supported, using default", d.Get("name").(string), d.Get("tier").(string)) paramInput.Tier = nil _, err = conn.PutParameter(paramInput) } if err != nil { - return fmt.Errorf("error updating SSM parameter (%s): %w", d.Id(), err) + return fmt.Errorf("error updating SSM Parameter (%s): %w", d.Id(), err) } } diff --git a/internal/service/ssm/parameter_data_source_test.go b/internal/service/ssm/parameter_data_source_test.go index 260fa7249b3..a8ce064da1d 100644 --- a/internal/service/ssm/parameter_data_source_test.go +++ b/internal/service/ssm/parameter_data_source_test.go @@ -20,7 +20,7 @@ func TestAccSSMParameterDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckParameterDataSourceConfig(name, "false"), + Config: testAccParameterDataSourceConfig_basic(name, "false"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_ssm_parameter.test", "arn"), resource.TestCheckResourceAttr(resourceName, "name", name), @@ -31,7 +31,7 @@ func TestAccSSMParameterDataSource_basic(t *testing.T) { ), }, { - Config: testAccCheckParameterDataSourceConfig(name, "true"), + Config: testAccParameterDataSourceConfig_basic(name, "true"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_ssm_parameter.test", "arn"), resource.TestCheckResourceAttr(resourceName, "name", name), @@ -54,7 +54,7 @@ func TestAccSSMParameterDataSource_fullPath(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckParameterDataSourceConfig(name, "false"), + Config: testAccParameterDataSourceConfig_basic(name, "false"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", "aws_ssm_parameter.test", "arn"), resource.TestCheckResourceAttr(resourceName, "name", name), @@ -67,7 +67,7 @@ func TestAccSSMParameterDataSource_fullPath(t *testing.T) { }) } -func testAccCheckParameterDataSourceConfig(name string, withDecryption string) string { +func testAccParameterDataSourceConfig_basic(name string, withDecryption string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test" { name = "%s" diff --git a/internal/service/ssm/parameter_test.go b/internal/service/ssm/parameter_test.go index b745d08a013..bd502560c4e 100644 --- a/internal/service/ssm/parameter_test.go +++ b/internal/service/ssm/parameter_test.go @@ -27,13 +27,13 @@ func TestAccSSMParameter_basic(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicConfig(name, "String", "test2"), + Config: testAccParameterConfig_basic(name, "String", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ssm", fmt.Sprintf("parameter/%s", name)), resource.TestCheckResourceAttr(resourceName, "value", "test2"), resource.TestCheckResourceAttr(resourceName, "type", "String"), - resource.TestCheckResourceAttr(resourceName, "tier", "Standard"), + resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierStandard), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), resource.TestCheckResourceAttrSet(resourceName, "version"), resource.TestCheckResourceAttr(resourceName, "data_type", "text"), @@ -61,7 +61,7 @@ func TestAccSSMParameter_tier(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterTierConfig(rName, ssm.ParameterTierAdvanced), + Config: testAccParameterConfig_tier(rName, ssm.ParameterTierAdvanced), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶meter1), resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierAdvanced), @@ -74,14 +74,14 @@ func TestAccSSMParameter_tier(t *testing.T) { ImportStateVerifyIgnore: []string{"overwrite"}, }, { - Config: testAccParameterTierConfig(rName, ssm.ParameterTierStandard), + Config: testAccParameterConfig_tier(rName, ssm.ParameterTierStandard), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶meter2), resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierStandard), ), }, { - Config: testAccParameterTierConfig(rName, ssm.ParameterTierAdvanced), + Config: testAccParameterConfig_tier(rName, ssm.ParameterTierAdvanced), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶meter3), resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierAdvanced), @@ -103,7 +103,7 @@ func TestAccSSMParameter_Tier_intelligentTieringToStandard(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterTierConfig(rName, ssm.ParameterTierIntelligentTiering), + Config: testAccParameterConfig_tier(rName, ssm.ParameterTierIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶meter), resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierStandard), @@ -116,14 +116,14 @@ func TestAccSSMParameter_Tier_intelligentTieringToStandard(t *testing.T) { ImportStateVerifyIgnore: []string{"overwrite"}, }, { - Config: testAccParameterTierConfig(rName, ssm.ParameterTierStandard), + Config: testAccParameterConfig_tier(rName, ssm.ParameterTierStandard), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶meter), resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierStandard), ), }, { - Config: testAccParameterTierConfig(rName, ssm.ParameterTierIntelligentTiering), + Config: testAccParameterConfig_tier(rName, ssm.ParameterTierIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶meter), resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierStandard), @@ -151,7 +151,7 @@ func TestAccSSMParameter_Tier_intelligentTieringToAdvanced(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterTierConfig(rName, ssm.ParameterTierIntelligentTiering), + Config: testAccParameterConfig_tier(rName, ssm.ParameterTierIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶meter1), resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierStandard), @@ -164,17 +164,18 @@ func TestAccSSMParameter_Tier_intelligentTieringToAdvanced(t *testing.T) { ImportStateVerifyIgnore: []string{"overwrite"}, }, { - Config: testAccParameterTierConfig(rName, ssm.ParameterTierAdvanced), + Config: testAccParameterConfig_tier(rName, ssm.ParameterTierAdvanced), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶meter1), resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierAdvanced), ), }, { - Config: testAccParameterTierConfig(rName, ssm.ParameterTierIntelligentTiering), + // Intelligent-Tiering will not downgrade an existing parameter to Standard + Config: testAccParameterConfig_tier(rName, ssm.ParameterTierIntelligentTiering), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶meter2), - resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierStandard), + resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierAdvanced), ), }, { @@ -187,6 +188,68 @@ func TestAccSSMParameter_Tier_intelligentTieringToAdvanced(t *testing.T) { }) } +func TestAccSSMParameter_Tier_intelligentTieringOnCreation(t *testing.T) { + var parameter ssm.Parameter + rName := fmt.Sprintf("%s_%s", t.Name(), sdkacctest.RandString(10)) + resourceName := "aws_ssm_parameter.test" + + value := sdkacctest.RandString(5000) // Maximum size for Standard tier is 4 KB + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ssm.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckParameterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccParameterConfig_tierWithValue(rName, ssm.ParameterTierIntelligentTiering, value), + Check: resource.ComposeTestCheckFunc( + testAccCheckParameterExists(resourceName, ¶meter), + resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierAdvanced), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"overwrite"}, + }, + }, + }) +} + +func TestAccSSMParameter_Tier_intelligentTieringOnUpdate(t *testing.T) { + var parameter ssm.Parameter + rName := fmt.Sprintf("%s_%s", t.Name(), sdkacctest.RandString(10)) + resourceName := "aws_ssm_parameter.test" + + standardSizedValue := sdkacctest.RandString(10) + advancedSizedValue := sdkacctest.RandString(5000) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ssm.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckParameterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccParameterConfig_tierWithValue(rName, ssm.ParameterTierIntelligentTiering, standardSizedValue), + Check: resource.ComposeTestCheckFunc( + testAccCheckParameterExists(resourceName, ¶meter), + resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierStandard), + ), + }, + { + Config: testAccParameterConfig_tierWithValue(rName, ssm.ParameterTierIntelligentTiering, advancedSizedValue), + Check: resource.ComposeTestCheckFunc( + testAccCheckParameterExists(resourceName, ¶meter), + resource.TestCheckResourceAttr(resourceName, "tier", ssm.ParameterTierAdvanced), + ), + }, + }, + }) +} + func TestAccSSMParameter_disappears(t *testing.T) { var param ssm.Parameter name := fmt.Sprintf("%s_%s", t.Name(), sdkacctest.RandString(10)) @@ -199,7 +262,7 @@ func TestAccSSMParameter_disappears(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicConfig(name, "String", "test2"), + Config: testAccParameterConfig_basic(name, "String", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), acctest.CheckResourceDisappears(acctest.Provider, tfssm.ResourceParameter(), resourceName), @@ -222,7 +285,7 @@ func TestAccSSMParameter_overwrite(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicOverwriteConfig(name, "String", "test2"), + Config: testAccParameterConfig_basicOverwrite(name, "String", "test2"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "version", "1"), ), @@ -234,7 +297,7 @@ func TestAccSSMParameter_overwrite(t *testing.T) { ImportStateVerifyIgnore: []string{"overwrite"}, }, { - Config: testAccParameterBasicOverwriteConfig(name, "String", "test3"), + Config: testAccParameterConfig_basicOverwrite(name, "String", "test3"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "value", "test3"), @@ -257,13 +320,13 @@ func TestAccSSMParameter_overwriteCascade(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterCascadeOverwriteConfig(name, "test1"), + Config: testAccParameterConfig_cascadeOverwrite(name, "test1"), }, { - Config: testAccParameterCascadeOverwriteConfig(name, "test2"), + Config: testAccParameterConfig_cascadeOverwrite(name, "test2"), }, { - Config: testAccParameterCascadeOverwriteConfig(name, "test2"), + Config: testAccParameterConfig_cascadeOverwrite(name, "test2"), PlanOnly: true, ExpectNonEmptyPlan: false, }, @@ -284,7 +347,7 @@ func TestAccSSMParameter_overwriteWithTags(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterOverwriteWithTags1Config(rName, true, "key1", "value1"), + Config: testAccParameterConfig_overwriteTags1(rName, true, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -314,7 +377,7 @@ func TestAccSSMParameter_noOverwriteWithTags(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterOverwriteWithTags1Config(rName, false, "key1", "value1"), + Config: testAccParameterConfig_overwriteTags1(rName, false, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -344,7 +407,7 @@ func TestAccSSMParameter_updateToOverwriteWithTags(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicTags1Config(rName, "key1", "value1"), + Config: testAccParameterConfig_basicTags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -357,7 +420,7 @@ func TestAccSSMParameter_updateToOverwriteWithTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccParameterOverwriteWithTags1Config(rName, true, "key1", "value2"), + Config: testAccParameterConfig_overwriteTags1(rName, true, "key1", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -380,7 +443,7 @@ func TestAccSSMParameter_tags(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicTags1Config(rName, "key1", "value1"), + Config: testAccParameterConfig_basicTags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -394,7 +457,7 @@ func TestAccSSMParameter_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"overwrite"}, }, { - Config: testAccParameterBasicTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccParameterConfig_basicTags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -403,7 +466,7 @@ func TestAccSSMParameter_tags(t *testing.T) { ), }, { - Config: testAccParameterBasicTags1Config(rName, "key2", "value2"), + Config: testAccParameterConfig_basicTags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -426,7 +489,7 @@ func TestAccSSMParameter_updateType(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicConfig(name, "SecureString", "test2"), + Config: testAccParameterConfig_basic(name, "SecureString", "test2"), }, { ResourceName: resourceName, @@ -435,7 +498,7 @@ func TestAccSSMParameter_updateType(t *testing.T) { ImportStateVerifyIgnore: []string{"overwrite"}, }, { - Config: testAccParameterBasicConfig(name, "String", "test2"), + Config: testAccParameterConfig_basic(name, "String", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "type", "String"), @@ -457,7 +520,7 @@ func TestAccSSMParameter_updateDescription(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicOverwriteConfig(name, "String", "test2"), + Config: testAccParameterConfig_basicOverwrite(name, "String", "test2"), }, { ResourceName: resourceName, @@ -466,7 +529,7 @@ func TestAccSSMParameter_updateDescription(t *testing.T) { ImportStateVerifyIgnore: []string{"overwrite"}, }, { - Config: testAccParameterBasicOverwriteWithoutDescriptionConfig(name, "String", "test2"), + Config: testAccParameterConfig_basicOverwriteNoDescription(name, "String", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -489,7 +552,7 @@ func TestAccSSMParameter_changeNameForcesNew(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicConfig(before, "String", "test2"), + Config: testAccParameterConfig_basic(before, "String", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, &beforeParam), ), @@ -501,7 +564,7 @@ func TestAccSSMParameter_changeNameForcesNew(t *testing.T) { ImportStateVerifyIgnore: []string{"overwrite"}, }, { - Config: testAccParameterBasicConfig(after, "String", "test2"), + Config: testAccParameterConfig_basic(after, "String", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, &afterParam), testAccCheckParameterRecreated(t, &beforeParam, &afterParam), @@ -523,7 +586,7 @@ func TestAccSSMParameter_fullPath(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicConfig(name, "String", "test2"), + Config: testAccParameterConfig_basic(name, "String", "test2"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ssm", fmt.Sprintf("parameter%s", name)), @@ -553,7 +616,7 @@ func TestAccSSMParameter_secure(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterBasicConfig(name, "SecureString", "secret"), + Config: testAccParameterConfig_basic(name, "SecureString", "secret"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "value", "secret"), @@ -583,7 +646,7 @@ func TestAccSSMParameter_DataType_ec2Image(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterDataTypeEC2ImageConfig(rName), + Config: testAccParameterConfig_dataTypeEC2Image(rName), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "data_type", "aws:ec2:image"), @@ -612,7 +675,7 @@ func TestAccSSMParameter_secureWithKey(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterSecureWithKeyConfig(name, "secret", randString), + Config: testAccParameterConfig_secureKey(name, "secret", randString), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "value", "secret"), @@ -643,7 +706,7 @@ func TestAccSSMParameter_Secure_keyUpdate(t *testing.T) { CheckDestroy: testAccCheckParameterDestroy, Steps: []resource.TestStep{ { - Config: testAccParameterSecureConfig(name, "secret"), + Config: testAccParameterConfig_secure(name, "secret"), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "value", "secret"), @@ -658,7 +721,7 @@ func TestAccSSMParameter_Secure_keyUpdate(t *testing.T) { ImportStateVerifyIgnore: []string{"overwrite"}, }, { - Config: testAccParameterSecureWithKeyConfig(name, "secret", randString), + Config: testAccParameterConfig_secureKey(name, "secret", randString), Check: resource.ComposeTestCheckFunc( testAccCheckParameterExists(resourceName, ¶m), resource.TestCheckResourceAttr(resourceName, "value", "secret"), @@ -749,7 +812,7 @@ func testAccCheckParameterDestroy(s *terraform.State) error { return nil } -func testAccParameterBasicConfig(rName, pType, value string) string { +func testAccParameterConfig_basic(rName, pType, value string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test" { name = %[1]q @@ -759,7 +822,7 @@ resource "aws_ssm_parameter" "test" { `, rName, pType, value) } -func testAccParameterTierConfig(rName, tier string) string { +func testAccParameterConfig_tier(rName, tier string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test" { name = %[1]q @@ -770,9 +833,20 @@ resource "aws_ssm_parameter" "test" { `, rName, tier) } -func testAccParameterDataTypeEC2ImageConfig(rName string) string { +func testAccParameterConfig_tierWithValue(rName, tier, value string) string { + return fmt.Sprintf(` +resource "aws_ssm_parameter" "test" { + name = %[1]q + tier = %[2]q + type = "String" + value = %[3]q +} +`, rName, tier, value) +} + +func testAccParameterConfig_dataTypeEC2Image(rName string) string { return acctest.ConfigCompose( - acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + acctest.ConfigLatestAmazonLinuxHVMEBSAMI(), fmt.Sprintf(` resource "aws_ssm_parameter" "test" { name = %[1]q @@ -783,7 +857,7 @@ resource "aws_ssm_parameter" "test" { `, rName)) } -func testAccParameterBasicTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccParameterConfig_basicTags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test" { name = %[1]q @@ -797,7 +871,7 @@ resource "aws_ssm_parameter" "test" { `, rName, tagKey1, tagValue1) } -func testAccParameterBasicTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccParameterConfig_basicTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test" { name = %[1]q @@ -812,7 +886,7 @@ resource "aws_ssm_parameter" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccParameterBasicOverwriteConfig(rName, pType, value string) string { +func testAccParameterConfig_basicOverwrite(rName, pType, value string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test" { name = "test_parameter-%[1]s" @@ -824,7 +898,7 @@ resource "aws_ssm_parameter" "test" { `, rName, pType, value) } -func testAccParameterBasicOverwriteWithoutDescriptionConfig(rName, pType, value string) string { +func testAccParameterConfig_basicOverwriteNoDescription(rName, pType, value string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test" { name = "test_parameter-%[1]s" @@ -835,7 +909,7 @@ resource "aws_ssm_parameter" "test" { `, rName, pType, value) } -func testAccParameterOverwriteWithTags1Config(rName string, overwrite bool, tagKey1, tagValue1 string) string { +func testAccParameterConfig_overwriteTags1(rName string, overwrite bool, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test" { name = %[1]q @@ -849,7 +923,7 @@ resource "aws_ssm_parameter" "test" { `, rName, overwrite, tagKey1, tagValue1) } -func testAccParameterCascadeOverwriteConfig(rName, value string) string { +func testAccParameterConfig_cascadeOverwrite(rName, value string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test_upstream" { name = "test_parameter_upstream-%[1]s" @@ -867,7 +941,7 @@ resource "aws_ssm_parameter" "test_downstream" { `, rName, value) } -func testAccParameterSecureConfig(rName string, value string) string { +func testAccParameterConfig_secure(rName string, value string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "secret_test" { name = "test_secure_parameter-%[1]s" @@ -878,7 +952,7 @@ resource "aws_ssm_parameter" "secret_test" { `, rName, value) } -func testAccParameterSecureWithKeyConfig(rName string, value string, keyAlias string) string { +func testAccParameterConfig_secureKey(rName string, value string, keyAlias string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "secret_test" { name = "test_secure_parameter-%[1]s" diff --git a/internal/service/ssm/parameters_by_path_data_source_test.go b/internal/service/ssm/parameters_by_path_data_source_test.go index a34617aefb3..d6dddbf6523 100644 --- a/internal/service/ssm/parameters_by_path_data_source_test.go +++ b/internal/service/ssm/parameters_by_path_data_source_test.go @@ -21,7 +21,7 @@ func TestAccSSMParametersByPathDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckParametersByPathDataSourceConfig(rName1, rName2, false), + Config: testAccParametersByPathDataSourceConfig_basic(rName1, rName2, false), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "arns.#", "2"), resource.TestCheckResourceAttr(resourceName, "names.#", "2"), @@ -35,7 +35,7 @@ func TestAccSSMParametersByPathDataSource_basic(t *testing.T) { }) } -func testAccCheckParametersByPathDataSourceConfig(rName1, rName2 string, withDecryption bool) string { +func testAccParametersByPathDataSourceConfig_basic(rName1, rName2 string, withDecryption bool) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "test1" { name = "/%[1]s/param-a" @@ -78,7 +78,7 @@ func TestAccSSMParametersByPathDataSource_withRecursion(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckParametersByPathDataSourceConfigWithRecursion(pathPrefix), + Config: testAccParametersByPathDataSourceConfig_recursion(pathPrefix), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "arns.#", "2"), resource.TestCheckResourceAttr(resourceName, "names.#", "2"), @@ -91,7 +91,7 @@ func TestAccSSMParametersByPathDataSource_withRecursion(t *testing.T) { }) } -func testAccCheckParametersByPathDataSourceConfigWithRecursion(pathPrefix string) string { +func testAccParametersByPathDataSourceConfig_recursion(pathPrefix string) string { return fmt.Sprintf(` resource "aws_ssm_parameter" "top_level" { name = "/%[1]s/top_param" diff --git a/internal/service/ssm/patch_baseline.go b/internal/service/ssm/patch_baseline.go index dfdd520b281..a471b204e5d 100644 --- a/internal/service/ssm/patch_baseline.go +++ b/internal/service/ssm/patch_baseline.go @@ -350,8 +350,8 @@ func resourcePatchBaselineRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetPatchBaseline(params) if err != nil { - if tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { - log.Printf("[WARN] Patch Baseline %s not found, removing from state", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, ssm.ErrCodeDoesNotExistException) { + log.Printf("[WARN] SSM Patch Baseline (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/ssm/patch_baseline_data_source_test.go b/internal/service/ssm/patch_baseline_data_source_test.go index 6dc15f3b491..935ca15f619 100644 --- a/internal/service/ssm/patch_baseline_data_source_test.go +++ b/internal/service/ssm/patch_baseline_data_source_test.go @@ -19,7 +19,7 @@ func TestAccSSMPatchBaselineDataSource_existingBaseline(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccCheckPatchBaselineDataSourceConfig_existingBaseline(), + Config: testAccPatchBaselineDataSourceConfig_existing(), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "approved_patches.#", "0"), resource.TestCheckResourceAttr(dataSourceName, "approved_patches_compliance_level", "UNSPECIFIED"), @@ -50,7 +50,7 @@ func TestAccSSMPatchBaselineDataSource_newBaseline(t *testing.T) { CheckDestroy: testAccCheckPatchBaselineDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckPatchBaselineDataSourceConfig_newBaseline(rName), + Config: testAccPatchBaselineDataSourceConfig_new(rName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "approved_patches", resourceName, "approved_patches"), resource.TestCheckResourceAttrPair(dataSourceName, "approved_patches_compliance_level", resourceName, "approved_patches_compliance_level"), @@ -70,7 +70,7 @@ func TestAccSSMPatchBaselineDataSource_newBaseline(t *testing.T) { } // Test against one of the default baselines created by AWS -func testAccCheckPatchBaselineDataSourceConfig_existingBaseline() string { +func testAccPatchBaselineDataSourceConfig_existing() string { return ` data "aws_ssm_patch_baseline" "test" { owner = "AWS" @@ -81,7 +81,7 @@ data "aws_ssm_patch_baseline" "test" { } // Create a new baseline and pull it back -func testAccCheckPatchBaselineDataSourceConfig_newBaseline(name string) string { +func testAccPatchBaselineDataSourceConfig_new(name string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = "%s" diff --git a/internal/service/ssm/patch_baseline_test.go b/internal/service/ssm/patch_baseline_test.go index 241d0e6cac1..7a450f0721f 100644 --- a/internal/service/ssm/patch_baseline_test.go +++ b/internal/service/ssm/patch_baseline_test.go @@ -26,7 +26,7 @@ func TestAccSSMPatchBaseline_basic(t *testing.T) { CheckDestroy: testAccCheckPatchBaselineDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchBaselineBasicConfig(name), + Config: testAccPatchBaselineConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &before), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ssm", regexp.MustCompile(`patchbaseline/pb-.+`)), @@ -45,7 +45,7 @@ func TestAccSSMPatchBaseline_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPatchBaselineBasicUpdatedConfig(name), + Config: testAccPatchBaselineConfig_basicUpdated(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &after), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ssm", regexp.MustCompile(`patchbaseline/pb-.+`)), @@ -79,7 +79,7 @@ func TestAccSSMPatchBaseline_tags(t *testing.T) { CheckDestroy: testAccCheckPatchBaselineDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchBaselineBasicTags1Config(name, "key1", "value1"), + Config: testAccPatchBaselineConfig_basicTags1(name, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &patch), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -92,7 +92,7 @@ func TestAccSSMPatchBaseline_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPatchBaselineBasicTags2Config(name, "key1", "value1updated", "key2", "value2"), + Config: testAccPatchBaselineConfig_basicTags2(name, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &patch), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -101,7 +101,7 @@ func TestAccSSMPatchBaseline_tags(t *testing.T) { ), }, { - Config: testAccPatchBaselineBasicTags1Config(name, "key2", "value2"), + Config: testAccPatchBaselineConfig_basicTags1(name, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &patch), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -124,7 +124,7 @@ func TestAccSSMPatchBaseline_disappears(t *testing.T) { CheckDestroy: testAccCheckPatchBaselineDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchBaselineBasicConfig(name), + Config: testAccPatchBaselineConfig_basic(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &identity), acctest.CheckResourceDisappears(acctest.Provider, tfssm.ResourcePatchBaseline(), resourceName), @@ -146,7 +146,7 @@ func TestAccSSMPatchBaseline_operatingSystem(t *testing.T) { CheckDestroy: testAccCheckPatchBaselineDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchBaselineWithOperatingSystemConfig(name), + Config: testAccPatchBaselineConfig_operatingSystem(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "approval_rule.#", "1"), @@ -163,7 +163,7 @@ func TestAccSSMPatchBaseline_operatingSystem(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPatchBaselineWithOperatingSystemUpdatedConfig(name), + Config: testAccPatchBaselineConfig_operatingSystemUpdated(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "approval_rule.#", "1"), @@ -190,7 +190,7 @@ func TestAccSSMPatchBaseline_approveUntilDateParam(t *testing.T) { CheckDestroy: testAccCheckPatchBaselineDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchBaselineWithApproveUntilDateConfig(name), + Config: testAccPatchBaselineConfig_approveUntilDate(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "approval_rule.#", "1"), @@ -207,7 +207,7 @@ func TestAccSSMPatchBaseline_approveUntilDateParam(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPatchBaselineWithApproveUntilDateUpdatedConfig(name), + Config: testAccPatchBaselineConfig_approveUntilDateUpdated(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "approval_rule.#", "1"), @@ -239,7 +239,7 @@ func TestAccSSMPatchBaseline_sources(t *testing.T) { CheckDestroy: testAccCheckPatchBaselineDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchBaselineWithSourceConfig(name), + Config: testAccPatchBaselineConfig_source(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "source.#", "1"), @@ -255,7 +255,7 @@ func TestAccSSMPatchBaseline_sources(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPatchBaselineWithSourceUpdatedConfig(name), + Config: testAccPatchBaselineConfig_sourceUpdated(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "source.#", "2"), @@ -291,7 +291,7 @@ func TestAccSSMPatchBaseline_approvedPatchesNonSec(t *testing.T) { CheckDestroy: testAccCheckPatchBaselineDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchBaselineBasicApprovedPatchesNonSecConfig(name), + Config: testAccPatchBaselineConfig_basicApprovedPatchesNonSec(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &ssmPatch), resource.TestCheckResourceAttr(resourceName, "approved_patches_enable_non_security", "true"), @@ -318,7 +318,7 @@ func TestAccSSMPatchBaseline_rejectPatchesAction(t *testing.T) { CheckDestroy: testAccCheckPatchBaselineDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchBaselineBasicRejectPatchesActionConfig(name), + Config: testAccPatchBaselineConfig_basicRejectPatchesAction(name), Check: resource.ComposeTestCheckFunc( testAccCheckPatchBaselineExists(resourceName, &ssmPatch), resource.TestCheckResourceAttr(resourceName, "rejected_patches_action", "ALLOW_AS_DEPENDENCY"), @@ -410,7 +410,7 @@ func testAccCheckPatchBaselineDestroy(s *terraform.State) error { return nil } -func testAccPatchBaselineBasicConfig(rName string) string { +func testAccPatchBaselineConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = "patch-baseline-%s" @@ -421,7 +421,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName) } -func testAccPatchBaselineBasicTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccPatchBaselineConfig_basicTags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = %[1]q @@ -436,7 +436,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName, tagKey1, tagValue1) } -func testAccPatchBaselineBasicTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccPatchBaselineConfig_basicTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = %[1]q @@ -452,7 +452,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccPatchBaselineBasicUpdatedConfig(rName string) string { +func testAccPatchBaselineConfig_basicUpdated(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = "updated-patch-baseline-%s" @@ -463,7 +463,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName) } -func testAccPatchBaselineWithOperatingSystemConfig(rName string) string { +func testAccPatchBaselineConfig_operatingSystem(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = "patch-baseline-%s" @@ -493,7 +493,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName) } -func testAccPatchBaselineWithOperatingSystemUpdatedConfig(rName string) string { +func testAccPatchBaselineConfig_operatingSystemUpdated(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = "patch-baseline-%s" @@ -522,7 +522,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName) } -func testAccPatchBaselineWithApproveUntilDateConfig(rName string) string { +func testAccPatchBaselineConfig_approveUntilDate(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = %[1]q @@ -552,7 +552,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName) } -func testAccPatchBaselineWithApproveUntilDateUpdatedConfig(rName string) string { +func testAccPatchBaselineConfig_approveUntilDateUpdated(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = %[1]q @@ -582,7 +582,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName) } -func testAccPatchBaselineWithSourceConfig(rName string) string { +func testAccPatchBaselineConfig_source(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = %[1]q @@ -600,7 +600,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName) } -func testAccPatchBaselineWithSourceUpdatedConfig(rName string) string { +func testAccPatchBaselineConfig_sourceUpdated(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = %[1]q @@ -624,7 +624,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName) } -func testAccPatchBaselineBasicApprovedPatchesNonSecConfig(rName string) string { +func testAccPatchBaselineConfig_basicApprovedPatchesNonSec(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = %q @@ -637,7 +637,7 @@ resource "aws_ssm_patch_baseline" "test" { `, rName) } -func testAccPatchBaselineBasicRejectPatchesActionConfig(rName string) string { +func testAccPatchBaselineConfig_basicRejectPatchesAction(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test" { name = "patch-baseline-%s" diff --git a/internal/service/ssm/patch_group_test.go b/internal/service/ssm/patch_group_test.go index 7f1824006b9..a9fa66c05ce 100644 --- a/internal/service/ssm/patch_group_test.go +++ b/internal/service/ssm/patch_group_test.go @@ -24,7 +24,7 @@ func TestAccSSMPatchGroup_basic(t *testing.T) { CheckDestroy: testAccCheckPatchGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchGroupBasicConfig(rName), + Config: testAccPatchGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPatchGroupExists(resourceName), ), @@ -44,7 +44,7 @@ func TestAccSSMPatchGroup_disappears(t *testing.T) { CheckDestroy: nil, Steps: []resource.TestStep{ { - Config: testAccPatchGroupBasicConfig(rName), + Config: testAccPatchGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPatchGroupExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfssm.ResourcePatchGroup(), resourceName), @@ -68,7 +68,7 @@ func TestAccSSMPatchGroup_multipleBaselines(t *testing.T) { CheckDestroy: testAccCheckPatchGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccPatchGroupMultipleBaselinesConfig(rName), + Config: testAccPatchGroupConfig_multipleBaselines(rName), Check: resource.ComposeTestCheckFunc( testAccCheckPatchGroupExists(resourceName1), testAccCheckPatchGroupExists(resourceName2), @@ -138,7 +138,7 @@ func testAccCheckPatchGroupExists(n string) resource.TestCheckFunc { } } -func testAccPatchGroupBasicConfig(rName string) string { +func testAccPatchGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "foo" { name = %[1]q @@ -152,7 +152,7 @@ resource "aws_ssm_patch_group" "patchgroup" { `, rName) } -func testAccPatchGroupMultipleBaselinesConfig(rName string) string { +func testAccPatchGroupConfig_multipleBaselines(rName string) string { return fmt.Sprintf(` resource "aws_ssm_patch_baseline" "test1" { approved_patches = ["KB123456"] diff --git a/internal/service/ssm/resource_data_sync.go b/internal/service/ssm/resource_data_sync.go index 14230668d1a..6814cb6a713 100644 --- a/internal/service/ssm/resource_data_sync.go +++ b/internal/service/ssm/resource_data_sync.go @@ -134,7 +134,6 @@ func resourceResourceDataSyncDelete(d *schema.ResourceData, meta interface{}) er if tfawserr.ErrCodeEquals(err, ssm.ErrCodeResourceDataSyncNotFoundException) { return nil } - if err != nil { return fmt.Errorf("error deleting SSM Resource Data Sync (%s): %w", d.Id(), err) } @@ -163,11 +162,9 @@ func FindResourceDataSyncItem(conn *ssm.SSM, name string) (*ssm.ResourceDataSync if err != nil { return nil, err } - if result == nil { - return nil, tfresource.NewEmptyResultError(input) + return nil, &resource.NotFoundError{} } - return result, nil } diff --git a/internal/service/ssoadmin/account_assignment_test.go b/internal/service/ssoadmin/account_assignment_test.go index 8a9a98ba609..ede3b98bea2 100644 --- a/internal/service/ssoadmin/account_assignment_test.go +++ b/internal/service/ssoadmin/account_assignment_test.go @@ -32,7 +32,7 @@ func TestAccSSOAdminAccountAssignment_Basic_group(t *testing.T) { CheckDestroy: testAccCheckAccountAssignmentDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountAssignmentBasicGroupConfig(groupName, rName), + Config: testAccAccountAssignmentConfig_basicGroup(groupName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccountAssignmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_type", "AWS_ACCOUNT"), @@ -65,7 +65,7 @@ func TestAccSSOAdminAccountAssignment_Basic_user(t *testing.T) { CheckDestroy: testAccCheckAccountAssignmentDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountAssignmentBasicUserConfig(userName, rName), + Config: testAccAccountAssignmentConfig_basicUser(userName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccountAssignmentExists(resourceName), resource.TestCheckResourceAttr(resourceName, "target_type", "AWS_ACCOUNT"), @@ -98,7 +98,7 @@ func TestAccSSOAdminAccountAssignment_disappears(t *testing.T) { CheckDestroy: testAccCheckAccountAssignmentDestroy, Steps: []resource.TestStep{ { - Config: testAccAccountAssignmentBasicGroupConfig(groupName, rName), + Config: testAccAccountAssignmentConfig_basicGroup(groupName, rName), Check: resource.ComposeTestCheckFunc( testAccCheckAccountAssignmentExists(resourceName), acctest.CheckResourceDisappears(acctest.Provider, tfssoadmin.ResourceAccountAssignment(), resourceName), @@ -199,7 +199,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName) } -func testAccAccountAssignmentBasicGroupConfig(groupName, rName string) string { +func testAccAccountAssignmentConfig_basicGroup(groupName, rName string) string { return acctest.ConfigCompose( testAccAccountAssignmentBaseConfig(rName), fmt.Sprintf(` @@ -222,7 +222,7 @@ resource "aws_ssoadmin_account_assignment" "test" { `, groupName)) } -func testAccAccountAssignmentBasicUserConfig(userName, rName string) string { +func testAccAccountAssignmentConfig_basicUser(userName, rName string) string { return acctest.ConfigCompose( testAccAccountAssignmentBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/ssoadmin/instances_data_source_test.go b/internal/service/ssoadmin/instances_data_source_test.go index 566ec2ca901..32c5446c01a 100644 --- a/internal/service/ssoadmin/instances_data_source_test.go +++ b/internal/service/ssoadmin/instances_data_source_test.go @@ -46,7 +46,7 @@ func TestAccSSOAdminInstancesDataSource_basic(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccInstancesBasicDataSourceConfig, + Config: testAccInstancesDataSourceConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dataSourceName, "arns.#", "1"), resource.TestCheckResourceAttr(dataSourceName, "identity_store_ids.#", "1"), @@ -58,4 +58,4 @@ func TestAccSSOAdminInstancesDataSource_basic(t *testing.T) { }) } -const testAccInstancesBasicDataSourceConfig = `data "aws_ssoadmin_instances" "test" {}` +const testAccInstancesDataSourceConfig_basic = `data "aws_ssoadmin_instances" "test" {}` diff --git a/internal/service/ssoadmin/permission_set_data_source_test.go b/internal/service/ssoadmin/permission_set_data_source_test.go index 2fd1a7319a6..0b0593d62fc 100644 --- a/internal/service/ssoadmin/permission_set_data_source_test.go +++ b/internal/service/ssoadmin/permission_set_data_source_test.go @@ -22,7 +22,7 @@ func TestAccSSOAdminPermissionSetDataSource_arn(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSSOPermissionSetByARNDataSourceConfig(rName), + Config: testAccPermissionSetDataSourceConfig_ssoByARN(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "name"), @@ -47,7 +47,7 @@ func TestAccSSOAdminPermissionSetDataSource_name(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSSOPermissionSetByNameDataSourceConfig(rName), + Config: testAccPermissionSetDataSourceConfig_ssoByName(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "name"), @@ -69,7 +69,7 @@ func TestAccSSOAdminPermissionSetDataSource_nonExistent(t *testing.T) { ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccSSOPermissionSetByNameDataSourceConfig_nonExistent, + Config: testAccPermissionSetDataSourceConfig_ssoByNameNonExistent, ExpectError: regexp.MustCompile(`not found`), }, }, @@ -95,7 +95,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName) } -func testAccSSOPermissionSetByARNDataSourceConfig(rName string) string { +func testAccPermissionSetDataSourceConfig_ssoByARN(rName string) string { return acctest.ConfigCompose( testAccSSOPermissionSetBaseDataSourceConfig(rName), ` @@ -106,7 +106,7 @@ data "aws_ssoadmin_permission_set" "test" { `) } -func testAccSSOPermissionSetByNameDataSourceConfig(rName string) string { +func testAccPermissionSetDataSourceConfig_ssoByName(rName string) string { return acctest.ConfigCompose( testAccSSOPermissionSetBaseDataSourceConfig(rName), ` @@ -117,7 +117,7 @@ data "aws_ssoadmin_permission_set" "test" { `) } -const testAccSSOPermissionSetByNameDataSourceConfig_nonExistent = ` +const testAccPermissionSetDataSourceConfig_ssoByNameNonExistent = ` data "aws_ssoadmin_instances" "test" {} data "aws_ssoadmin_permission_set" "test" { diff --git a/internal/service/ssoadmin/permission_set_test.go b/internal/service/ssoadmin/permission_set_test.go index be07b5fc2da..ce629242066 100644 --- a/internal/service/ssoadmin/permission_set_test.go +++ b/internal/service/ssoadmin/permission_set_test.go @@ -26,7 +26,7 @@ func TestAccSSOAdminPermissionSet_basic(t *testing.T) { CheckDestroy: testAccCheckPermissionSetDestroy, Steps: []resource.TestStep{ { - Config: testAccPermissionSetBasicConfig(rName), + Config: testAccPermissionSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -53,7 +53,7 @@ func TestAccSSOAdminPermissionSet_tags(t *testing.T) { CheckDestroy: testAccCheckPermissionSetDestroy, Steps: []resource.TestStep{ { - Config: testAccPermissionSetTagsSingleConfig(rName, "key1", "value1"), + Config: testAccPermissionSetConfig_tagsSingle(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -66,7 +66,7 @@ func TestAccSSOAdminPermissionSet_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPermissionSetTagsMultipleConfig(rName, "key1", "updatedvalue1", "key2", "value2"), + Config: testAccPermissionSetConfig_tagsMultiple(rName, "key1", "updatedvalue1", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -80,7 +80,7 @@ func TestAccSSOAdminPermissionSet_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccPermissionSetTagsSingleConfig(rName, "key2", "value2"), + Config: testAccPermissionSetConfig_tagsSingle(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -107,14 +107,14 @@ func TestAccSSOAdminPermissionSet_updateDescription(t *testing.T) { CheckDestroy: testAccCheckPermissionSetDestroy, Steps: []resource.TestStep{ { - Config: testAccPermissionSetBasicConfig(rName), + Config: testAccPermissionSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", ""), ), }, { - Config: testAccPermissionSetUpdateDescriptionConfig(rName), + Config: testAccPermissionSetConfig_updateDescription(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -140,14 +140,14 @@ func TestAccSSOAdminPermissionSet_updateRelayState(t *testing.T) { CheckDestroy: testAccCheckPermissionSetDestroy, Steps: []resource.TestStep{ { - Config: testAccPermissionSetBasicConfig(rName), + Config: testAccPermissionSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "relay_state", ""), ), }, { - Config: testAccPermissionSetUpdateRelayStateConfig(rName), + Config: testAccPermissionSetConfig_updateRelayState(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "relay_state", "https://example.com"), @@ -173,13 +173,13 @@ func TestAccSSOAdminPermissionSet_updateSessionDuration(t *testing.T) { CheckDestroy: testAccCheckPermissionSetDestroy, Steps: []resource.TestStep{ { - Config: testAccPermissionSetBasicConfig(rName), + Config: testAccPermissionSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), ), }, { - Config: testAccPermissionSetUpdateSessionDurationConfig(rName), + Config: testAccPermissionSetConfig_updateSessionDuration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "session_duration", "PT2H"), @@ -208,7 +208,7 @@ func TestAccSSOAdminPermissionSet_RelayState_updateSessionDuration(t *testing.T) CheckDestroy: testAccCheckPermissionSetDestroy, Steps: []resource.TestStep{ { - Config: testAccPermissionSetRelayStateConfig(rName), + Config: testAccPermissionSetConfig_relayState(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -218,7 +218,7 @@ func TestAccSSOAdminPermissionSet_RelayState_updateSessionDuration(t *testing.T) ), }, { - Config: testAccPermissionSetRelayStateConfig_updateSessionDuration(rName), + Config: testAccPermissionSetConfig_relayStateUpdateSessionDuration(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", rName), @@ -247,13 +247,13 @@ func TestAccSSOAdminPermissionSet_mixedPolicyAttachments(t *testing.T) { CheckDestroy: testAccCheckPermissionSetDestroy, Steps: []resource.TestStep{ { - Config: testAccPermissionSetBasicConfig(rName), + Config: testAccPermissionSetConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), ), }, { - Config: testAccPermissionSetMixedPolicyAttachmentsConfig(rName), + Config: testAccPermissionSetConfig_mixedPolicyAttachments(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSOAdminPermissionSetExists(resourceName), ), @@ -334,7 +334,7 @@ func testAccCheckSOAdminPermissionSetExists(resourceName string) resource.TestCh } } -func testAccPermissionSetBasicConfig(rName string) string { +func testAccPermissionSetConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_ssoadmin_instances" "test" {} @@ -345,7 +345,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName) } -func testAccPermissionSetUpdateDescriptionConfig(rName string) string { +func testAccPermissionSetConfig_updateDescription(rName string) string { return fmt.Sprintf(` data "aws_ssoadmin_instances" "test" {} @@ -357,7 +357,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName) } -func testAccPermissionSetUpdateRelayStateConfig(rName string) string { +func testAccPermissionSetConfig_updateRelayState(rName string) string { return fmt.Sprintf(` data "aws_ssoadmin_instances" "test" {} @@ -369,7 +369,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName) } -func testAccPermissionSetUpdateSessionDurationConfig(rName string) string { +func testAccPermissionSetConfig_updateSessionDuration(rName string) string { return fmt.Sprintf(` data "aws_ssoadmin_instances" "test" {} @@ -381,7 +381,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName) } -func testAccPermissionSetRelayStateConfig(rName string) string { +func testAccPermissionSetConfig_relayState(rName string) string { return fmt.Sprintf(` data "aws_ssoadmin_instances" "test" {} @@ -395,7 +395,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName) } -func testAccPermissionSetRelayStateConfig_updateSessionDuration(rName string) string { +func testAccPermissionSetConfig_relayStateUpdateSessionDuration(rName string) string { return fmt.Sprintf(` data "aws_ssoadmin_instances" "test" {} @@ -409,7 +409,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName) } -func testAccPermissionSetTagsSingleConfig(rName, tagKey1, tagValue1 string) string { +func testAccPermissionSetConfig_tagsSingle(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_ssoadmin_instances" "test" {} @@ -424,7 +424,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName, tagKey1, tagValue1) } -func testAccPermissionSetTagsMultipleConfig(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccPermissionSetConfig_tagsMultiple(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_ssoadmin_instances" "test" {} @@ -440,7 +440,7 @@ resource "aws_ssoadmin_permission_set" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccPermissionSetMixedPolicyAttachmentsConfig(rName string) string { +func testAccPermissionSetConfig_mixedPolicyAttachments(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} diff --git a/internal/service/storagegateway/cache_test.go b/internal/service/storagegateway/cache_test.go index 1bd7ae7c264..fc8379e5346 100644 --- a/internal/service/storagegateway/cache_test.go +++ b/internal/service/storagegateway/cache_test.go @@ -84,7 +84,7 @@ func TestAccStorageGatewayCache_fileGateway(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCacheConfig_FileGateway(rName), + Config: testAccCacheConfig_fileGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCacheExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "disk_id"), @@ -114,7 +114,7 @@ func TestAccStorageGatewayCache_tapeAndVolumeGateway(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCacheConfig_TapeAndVolumeGateway(rName), + Config: testAccCacheConfig_tapeAndVolumeGateway(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCacheExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "disk_id"), @@ -168,8 +168,8 @@ func testAccCheckCacheExists(resourceName string) resource.TestCheckFunc { } } -func testAccCacheConfig_FileGateway(rName string) string { - return testAccGatewayConfig_GatewayType_FileS3(rName) + fmt.Sprintf(` +func testAccCacheConfig_fileGateway(rName string) string { + return testAccGatewayConfig_typeFileS3(rName) + fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" @@ -209,8 +209,8 @@ resource "aws_storagegateway_cache" "test" { `, rName) } -func testAccCacheConfig_TapeAndVolumeGateway(rName string) string { - return testAccGatewayConfig_GatewayType_Cached(rName) + fmt.Sprintf(` +func testAccCacheConfig_tapeAndVolumeGateway(rName string) string { + return testAccGatewayConfig_typeCached(rName) + fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" diff --git a/internal/service/storagegateway/cached_iscsi_volume_test.go b/internal/service/storagegateway/cached_iscsi_volume_test.go index 0a65eeb36db..d886b109502 100644 --- a/internal/service/storagegateway/cached_iscsi_volume_test.go +++ b/internal/service/storagegateway/cached_iscsi_volume_test.go @@ -84,7 +84,7 @@ func TestAccStorageGatewayCachediSCSIVolume_basic(t *testing.T) { CheckDestroy: testAccCheckCachediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccCachediSCSIVolumeConfig_Basic(rName), + Config: testAccCachediSCSIVolumeConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachediSCSIVolumeExists(resourceName, &cachedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -124,7 +124,7 @@ func TestAccStorageGatewayCachediSCSIVolume_kms(t *testing.T) { CheckDestroy: testAccCheckCachediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccCachediSCSIVolumeKMSEncryptedConfig(rName), + Config: testAccCachediSCSIVolumeConfig_kmsEncrypted(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachediSCSIVolumeExists(resourceName, &cachedIscsiVolume), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "true"), @@ -152,7 +152,7 @@ func TestAccStorageGatewayCachediSCSIVolume_tags(t *testing.T) { CheckDestroy: testAccCheckCachediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccCachediSCSIVolumeTags1Config(rName, "key1", "value1"), + Config: testAccCachediSCSIVolumeConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckCachediSCSIVolumeExists(resourceName, &cachedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -166,7 +166,7 @@ func TestAccStorageGatewayCachediSCSIVolume_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCachediSCSIVolumeTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccCachediSCSIVolumeConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCachediSCSIVolumeExists(resourceName, &cachedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -176,7 +176,7 @@ func TestAccStorageGatewayCachediSCSIVolume_tags(t *testing.T) { ), }, { - Config: testAccCachediSCSIVolumeTags1Config(rName, "key2", "value2"), + Config: testAccCachediSCSIVolumeConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckCachediSCSIVolumeExists(resourceName, &cachedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -200,7 +200,7 @@ func TestAccStorageGatewayCachediSCSIVolume_snapshotID(t *testing.T) { CheckDestroy: testAccCheckCachediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccCachediSCSIVolumeConfig_SnapshotID(rName), + Config: testAccCachediSCSIVolumeConfig_snapshotID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachediSCSIVolumeExists(resourceName, &cachedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -239,7 +239,7 @@ func TestAccStorageGatewayCachediSCSIVolume_sourceVolumeARN(t *testing.T) { CheckDestroy: testAccCheckCachediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccCachediSCSIVolumeConfig_SourceVolumeARN(rName), + Config: testAccCachediSCSIVolumeConfig_sourceARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachediSCSIVolumeExists(resourceName, &cachedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -277,7 +277,7 @@ func TestAccStorageGatewayCachediSCSIVolume_disappears(t *testing.T) { CheckDestroy: testAccCheckCachediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccCachediSCSIVolumeConfig_Basic(rName), + Config: testAccCachediSCSIVolumeConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckCachediSCSIVolumeExists(resourceName, &storedIscsiVolume), acctest.CheckResourceDisappears(acctest.Provider, tfstoragegateway.ResourceCachediSCSIVolume(), resourceName), @@ -354,7 +354,7 @@ func testAccCheckCachediSCSIVolumeDestroy(s *terraform.State) error { func testAccCachediSCSIVolumeBaseConfig(rName string) string { return acctest.ConfigCompose( - testAccGatewayConfig_GatewayType_Cached(rName), + testAccGatewayConfig_typeCached(rName), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone @@ -395,7 +395,7 @@ resource "aws_storagegateway_cache" "test" { `, rName)) } -func testAccCachediSCSIVolumeConfig_Basic(rName string) string { +func testAccCachediSCSIVolumeConfig_basic(rName string) string { return acctest.ConfigCompose( testAccCachediSCSIVolumeBaseConfig(rName), fmt.Sprintf(` @@ -408,7 +408,7 @@ resource "aws_storagegateway_cached_iscsi_volume" "test" { `, rName)) } -func testAccCachediSCSIVolumeKMSEncryptedConfig(rName string) string { +func testAccCachediSCSIVolumeConfig_kmsEncrypted(rName string) string { return testAccCachediSCSIVolumeBaseConfig(rName) + fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Terraform acc test %[1]s" @@ -442,7 +442,7 @@ resource "aws_storagegateway_cached_iscsi_volume" "test" { `, rName) } -func testAccCachediSCSIVolumeTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccCachediSCSIVolumeConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose( testAccCachediSCSIVolumeBaseConfig(rName), fmt.Sprintf(` @@ -459,7 +459,7 @@ resource "aws_storagegateway_cached_iscsi_volume" "test" { `, rName, tagKey1, tagValue1)) } -func testAccCachediSCSIVolumeTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccCachediSCSIVolumeConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose( testAccCachediSCSIVolumeBaseConfig(rName), fmt.Sprintf(` @@ -477,7 +477,7 @@ resource "aws_storagegateway_cached_iscsi_volume" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccCachediSCSIVolumeConfig_SnapshotID(rName string) string { +func testAccCachediSCSIVolumeConfig_snapshotID(rName string) string { return acctest.ConfigCompose( testAccCachediSCSIVolumeBaseConfig(rName), fmt.Sprintf(` @@ -509,7 +509,7 @@ resource "aws_storagegateway_cached_iscsi_volume" "test" { `, rName)) } -func testAccCachediSCSIVolumeConfig_SourceVolumeARN(rName string) string { +func testAccCachediSCSIVolumeConfig_sourceARN(rName string) string { return acctest.ConfigCompose( testAccCachediSCSIVolumeBaseConfig(rName), fmt.Sprintf(` diff --git a/internal/service/storagegateway/file_system_association_test.go b/internal/service/storagegateway/file_system_association_test.go index dd96a634733..fee39141a4a 100644 --- a/internal/service/storagegateway/file_system_association_test.go +++ b/internal/service/storagegateway/file_system_association_test.go @@ -32,7 +32,7 @@ func TestAccStorageGatewayFileSystemAssociation_basic(t *testing.T) { CheckDestroy: testAccCheckFileSystemAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemAssociationConfig_Required(rName, domainName, username), + Config: testAccFileSystemAssociationConfig_required(rName, domainName, username), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`fs-association/fsa-.+`)), @@ -67,7 +67,7 @@ func TestAccStorageGatewayFileSystemAssociation_tags(t *testing.T) { CheckDestroy: testAccCheckFileSystemAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemAssociationTags1Config(rName, domainName, username, "key1", "value1"), + Config: testAccFileSystemAssociationConfig_tags1(rName, domainName, username, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`fs-association/fsa-.+`)), @@ -82,7 +82,7 @@ func TestAccStorageGatewayFileSystemAssociation_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"username", "password"}, }, { - Config: testAccFileSystemAssociationTags2Config(rName, domainName, username, "key1", "value1updated", "key2", "value2"), + Config: testAccFileSystemAssociationConfig_tags2(rName, domainName, username, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`fs-association/fsa-.+`)), @@ -92,7 +92,7 @@ func TestAccStorageGatewayFileSystemAssociation_tags(t *testing.T) { ), }, { - Config: testAccFileSystemAssociationTags1Config(rName, domainName, username, "key2", "value2"), + Config: testAccFileSystemAssociationConfig_tags1(rName, domainName, username, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`fs-association/fsa-.+`)), @@ -118,7 +118,7 @@ func TestAccStorageGatewayFileSystemAssociation_cacheAttributes(t *testing.T) { CheckDestroy: testAccCheckFileSystemAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemAssociationConfig_Cache(rName, domainName, username, 400), + Config: testAccFileSystemAssociationConfig_cache(rName, domainName, username, 400), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), resource.TestCheckResourceAttr(resourceName, "cache_attributes.#", "1"), @@ -132,7 +132,7 @@ func TestAccStorageGatewayFileSystemAssociation_cacheAttributes(t *testing.T) { ImportStateVerifyIgnore: []string{"username", "password"}, }, { - Config: testAccFileSystemAssociationConfig_Cache(rName, domainName, username, 0), + Config: testAccFileSystemAssociationConfig_cache(rName, domainName, username, 0), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), resource.TestCheckResourceAttr(resourceName, "cache_attributes.#", "1"), @@ -157,7 +157,7 @@ func TestAccStorageGatewayFileSystemAssociation_auditDestination(t *testing.T) { CheckDestroy: testAccCheckFileSystemAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemAssociationConfig_Audit(rName, domainName, username, "aws_cloudwatch_log_group.test.arn"), + Config: testAccFileSystemAssociationConfig_audit(rName, domainName, username, "aws_cloudwatch_log_group.test.arn"), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), resource.TestCheckResourceAttrPair(resourceName, "audit_destination_arn", "aws_cloudwatch_log_group.test", "arn"), @@ -169,14 +169,14 @@ func TestAccStorageGatewayFileSystemAssociation_auditDestination(t *testing.T) { ImportStateVerifyIgnore: []string{"username", "password"}, }, { - Config: testAccFileSystemAssociationConfig_AuditDisabled(rName, domainName, username), + Config: testAccFileSystemAssociationConfig_auditDisabled(rName, domainName, username), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), resource.TestCheckResourceAttr(resourceName, "audit_destination_arn", ""), ), }, { - Config: testAccFileSystemAssociationConfig_Audit(rName, domainName, username, "aws_cloudwatch_log_group.test2.arn"), + Config: testAccFileSystemAssociationConfig_audit(rName, domainName, username, "aws_cloudwatch_log_group.test2.arn"), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), resource.TestCheckResourceAttrPair(resourceName, "audit_destination_arn", "aws_cloudwatch_log_group.test2", "arn"), @@ -200,7 +200,7 @@ func TestAccStorageGatewayFileSystemAssociation_disappears(t *testing.T) { CheckDestroy: testAccCheckFileSystemAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemAssociationConfig_Required(rName, domainName, username), + Config: testAccFileSystemAssociationConfig_required(rName, domainName, username), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), acctest.CheckResourceDisappears(acctest.Provider, tfstoragegateway.ResourceFileSystemAssociation(), resourceName), @@ -225,7 +225,7 @@ func TestAccStorageGatewayFileSystemAssociation_Disappears_storageGateway(t *tes CheckDestroy: testAccCheckFileSystemAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemAssociationConfig_Required(rName, domainName, username), + Config: testAccFileSystemAssociationConfig_required(rName, domainName, username), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), acctest.CheckResourceDisappears(acctest.Provider, tfstoragegateway.ResourceGateway(), "aws_storagegateway_gateway.test"), @@ -253,7 +253,7 @@ func TestAccStorageGatewayFileSystemAssociation_Disappears_fsxFileSystem(t *test CheckDestroy: testAccCheckFileSystemAssociationDestroy, Steps: []resource.TestStep{ { - Config: testAccFileSystemAssociationConfig_Required(rName, domainName, username), + Config: testAccFileSystemAssociationConfig_required(rName, domainName, username), Check: resource.ComposeTestCheckFunc( testAccCheckFileSystemAssociationExists(resourceName, &fileSystemAssociation), acctest.CheckResourceDisappears(acctest.Provider, tffsx.ResourceWindowsFileSystem(), "aws_fsx_windows_file_system.test"), @@ -348,7 +348,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, username)) } -func testAccFileSystemAssociationConfig_Required(rName, domainName, username string) string { +func testAccFileSystemAssociationConfig_required(rName, domainName, username string) string { return testAccFileSystemAssociationBase(rName, domainName, username) + fmt.Sprintf(` resource "aws_storagegateway_file_system_association" "test" { gateway_arn = aws_storagegateway_gateway.test.arn @@ -359,7 +359,7 @@ resource "aws_storagegateway_file_system_association" "test" { `, username) } -func testAccFileSystemAssociationTags1Config(rName, domainName, username, tagKey1, tagValue1 string) string { +func testAccFileSystemAssociationConfig_tags1(rName, domainName, username, tagKey1, tagValue1 string) string { return testAccFileSystemAssociationBase(rName, domainName, username) + fmt.Sprintf(` resource "aws_storagegateway_file_system_association" "test" { gateway_arn = aws_storagegateway_gateway.test.arn @@ -374,7 +374,7 @@ resource "aws_storagegateway_file_system_association" "test" { `, username, tagKey1, tagValue1) } -func testAccFileSystemAssociationTags2Config(rName, domainName, username, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccFileSystemAssociationConfig_tags2(rName, domainName, username, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccFileSystemAssociationBase(rName, domainName, username) + fmt.Sprintf(` resource "aws_storagegateway_file_system_association" "test" { gateway_arn = aws_storagegateway_gateway.test.arn @@ -390,7 +390,7 @@ resource "aws_storagegateway_file_system_association" "test" { `, username, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccFileSystemAssociationConfig_Audit(rName, domainName, username string, loggingDestination string) string { +func testAccFileSystemAssociationConfig_audit(rName, domainName, username string, loggingDestination string) string { return testAccFileSystemAssociationBase(rName, domainName, username) + fmt.Sprintf(` resource "aws_storagegateway_file_system_association" "test" { gateway_arn = aws_storagegateway_gateway.test.arn @@ -404,7 +404,7 @@ resource "aws_cloudwatch_log_group" "test" {} resource "aws_cloudwatch_log_group" "test2" {} `, username, loggingDestination) } -func testAccFileSystemAssociationConfig_AuditDisabled(rName, domainName, username string) string { +func testAccFileSystemAssociationConfig_auditDisabled(rName, domainName, username string) string { return testAccFileSystemAssociationBase(rName, domainName, username) + fmt.Sprintf(` resource "aws_storagegateway_file_system_association" "test" { gateway_arn = aws_storagegateway_gateway.test.arn @@ -419,7 +419,7 @@ resource "aws_cloudwatch_log_group" "test2" {} `, username) } -func testAccFileSystemAssociationConfig_Cache(rName, domainName, username string, cache int) string { +func testAccFileSystemAssociationConfig_cache(rName, domainName, username string, cache int) string { return testAccFileSystemAssociationBase(rName, domainName, username) + fmt.Sprintf(` resource "aws_storagegateway_file_system_association" "test" { gateway_arn = aws_storagegateway_gateway.test.arn diff --git a/internal/service/storagegateway/gateway_test.go b/internal/service/storagegateway/gateway_test.go index e93b7930b56..477f035b196 100644 --- a/internal/service/storagegateway/gateway_test.go +++ b/internal/service/storagegateway/gateway_test.go @@ -28,7 +28,7 @@ func TestAccStorageGatewayGateway_GatewayType_cached(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_GatewayType_Cached(rName), + Config: testAccGatewayConfig_typeCached(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+`)), @@ -71,7 +71,7 @@ func TestAccStorageGatewayGateway_GatewayType_fileFSxSMB(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_GatewayType_FileFSxSMB(rName), + Config: testAccGatewayConfig_typeFileFSxSMB(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+`)), @@ -113,7 +113,7 @@ func TestAccStorageGatewayGateway_GatewayType_fileS3(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_GatewayType_FileS3(rName), + Config: testAccGatewayConfig_typeFileS3(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+`)), @@ -155,7 +155,7 @@ func TestAccStorageGatewayGateway_GatewayType_stored(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_GatewayType_Stored(rName), + Config: testAccGatewayConfig_typeStored(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+`)), @@ -197,7 +197,7 @@ func TestAccStorageGatewayGateway_GatewayType_vtl(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_GatewayType_Vtl(rName), + Config: testAccGatewayConfig_typeVtl(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+`)), @@ -237,7 +237,7 @@ func TestAccStorageGatewayGateway_tags(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayTags1Config(rName, "key1", "value1"), + Config: testAccGatewayConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+`)), @@ -252,7 +252,7 @@ func TestAccStorageGatewayGateway_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"activation_key", "gateway_ip_address"}, }, { - Config: testAccGatewayTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccGatewayConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -261,7 +261,7 @@ func TestAccStorageGatewayGateway_tags(t *testing.T) { ), }, { - Config: testAccGatewayTags1Config(rName, "key2", "value2"), + Config: testAccGatewayConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -285,14 +285,14 @@ func TestAccStorageGatewayGateway_gatewayName(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_GatewayType_FileS3(rName1), + Config: testAccGatewayConfig_typeFileS3(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "gateway_name", rName1), ), }, { - Config: testAccGatewayConfig_GatewayType_FileS3(rName2), + Config: testAccGatewayConfig_typeFileS3(rName2), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "gateway_name", rName2), @@ -321,7 +321,7 @@ func TestAccStorageGatewayGateway_cloudWatchLogs(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_Log_Group(rName1), + Config: testAccGatewayConfig_logGroup(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttrPair(resourceName, "cloudwatch_log_group_arn", resourceName2, "arn"), @@ -349,14 +349,14 @@ func TestAccStorageGatewayGateway_gatewayTimezone(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_GatewayTimezone(rName, "GMT-1:00"), + Config: testAccGatewayConfig_timezone(rName, "GMT-1:00"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "gateway_timezone", "GMT-1:00"), ), }, { - Config: testAccGatewayConfig_GatewayTimezone(rName, "GMT-2:00"), + Config: testAccGatewayConfig_timezone(rName, "GMT-2:00"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "gateway_timezone", "GMT-2:00"), @@ -385,7 +385,7 @@ func TestAccStorageGatewayGateway_gatewayVPCEndpoint(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_GatewayVPCEndpoint(rName), + Config: testAccGatewayConfig_vpcEndpoint(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttrPair(resourceName, "gateway_vpc_endpoint", vpcEndpointResourceName, "dns_entry.0.dns_name"), @@ -414,7 +414,7 @@ func TestAccStorageGatewayGateway_smbActiveDirectorySettings(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_SMBActiveDirectorySettings(rName, domainName), + Config: testAccGatewayConfig_smbActiveDirectorySettings(rName, domainName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_active_directory_settings.#", "1"), @@ -446,7 +446,7 @@ func TestAccStorageGatewayGateway_SMBActiveDirectorySettings_timeout(t *testing. CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_SMBActiveDirectorySettingsTimeout(rName, domainName, 50), + Config: testAccGatewayConfig_smbActiveDirectorySettingsTimeout(rName, domainName, 50), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_active_directory_settings.#", "1"), @@ -478,7 +478,7 @@ func TestAccStorageGatewayGateway_smbMicrosoftActiveDirectorySettings(t *testing CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_SMBMicrosoftActiveDirectorySettings(rName, domainName), + Config: testAccGatewayConfig_smbMicrosoftActiveDirectorySettings(rName, domainName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_active_directory_settings.#", "1"), @@ -510,7 +510,7 @@ func TestAccStorageGatewayGateway_SMBMicrosoftActiveDirectorySettings_timeout(t CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_SMBMicrosoftActiveDirectorySettingsTimeout(rName, domainName, 50), + Config: testAccGatewayConfig_smbMicrosoftActiveDirectorySettingsTimeout(rName, domainName, 50), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_active_directory_settings.#", "1"), @@ -540,14 +540,14 @@ func TestAccStorageGatewayGateway_smbGuestPassword(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_SMBGuestPassword(rName, "myguestpassword1"), + Config: testAccGatewayConfig_smbGuestPassword(rName, "myguestpassword1"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_guest_password", "myguestpassword1"), ), }, { - Config: testAccGatewayConfig_SMBGuestPassword(rName, "myguestpassword2"), + Config: testAccGatewayConfig_smbGuestPassword(rName, "myguestpassword2"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_guest_password", "myguestpassword2"), @@ -575,7 +575,7 @@ func TestAccStorageGatewayGateway_smbSecurityStrategy(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewaySMBSecurityStrategyConfig(rName, "ClientSpecified"), + Config: testAccGatewayConfig_smbSecurityStrategy(rName, "ClientSpecified"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_security_strategy", "ClientSpecified"), @@ -589,7 +589,7 @@ func TestAccStorageGatewayGateway_smbSecurityStrategy(t *testing.T) { ImportStateVerifyIgnore: []string{"activation_key", "gateway_ip_address"}, }, { - Config: testAccGatewaySMBSecurityStrategyConfig(rName, "MandatorySigning"), + Config: testAccGatewayConfig_smbSecurityStrategy(rName, "MandatorySigning"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_security_strategy", "MandatorySigning"), @@ -611,7 +611,7 @@ func TestAccStorageGatewayGateway_smbVisibility(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewaySMBVisibilityConfig(rName, true), + Config: testAccGatewayConfig_smbVisibility(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_file_share_visibility", "true"), @@ -624,14 +624,14 @@ func TestAccStorageGatewayGateway_smbVisibility(t *testing.T) { ImportStateVerifyIgnore: []string{"activation_key", "gateway_ip_address"}, }, { - Config: testAccGatewaySMBVisibilityConfig(rName, false), + Config: testAccGatewayConfig_smbVisibility(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_file_share_visibility", "false"), ), }, { - Config: testAccGatewaySMBVisibilityConfig(rName, true), + Config: testAccGatewayConfig_smbVisibility(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "smb_file_share_visibility", "true"), @@ -653,7 +653,7 @@ func TestAccStorageGatewayGateway_disappears(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayConfig_GatewayType_Cached(rName), + Config: testAccGatewayConfig_typeCached(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), acctest.CheckResourceDisappears(acctest.Provider, tfstoragegateway.ResourceGateway(), resourceName), @@ -676,7 +676,7 @@ func TestAccStorageGatewayGateway_bandwidthUpload(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayBandwidthUploadConfig(rName, 102400), + Config: testAccGatewayConfig_bandwidthUpload(rName, 102400), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "average_upload_rate_limit_in_bits_per_sec", "102400"), @@ -689,14 +689,14 @@ func TestAccStorageGatewayGateway_bandwidthUpload(t *testing.T) { ImportStateVerifyIgnore: []string{"activation_key", "gateway_ip_address"}, }, { - Config: testAccGatewayBandwidthUploadConfig(rName, 2*102400), + Config: testAccGatewayConfig_bandwidthUpload(rName, 2*102400), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "average_upload_rate_limit_in_bits_per_sec", "204800"), ), }, { - Config: testAccGatewayConfig_GatewayType_Cached(rName), + Config: testAccGatewayConfig_typeCached(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "average_upload_rate_limit_in_bits_per_sec", "0"), @@ -718,7 +718,7 @@ func TestAccStorageGatewayGateway_bandwidthDownload(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayBandwidthDownloadConfig(rName, 102400), + Config: testAccGatewayConfig_bandwidthDownload(rName, 102400), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "average_download_rate_limit_in_bits_per_sec", "102400"), @@ -731,14 +731,14 @@ func TestAccStorageGatewayGateway_bandwidthDownload(t *testing.T) { ImportStateVerifyIgnore: []string{"activation_key", "gateway_ip_address"}, }, { - Config: testAccGatewayBandwidthDownloadConfig(rName, 2*102400), + Config: testAccGatewayConfig_bandwidthDownload(rName, 2*102400), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "average_download_rate_limit_in_bits_per_sec", "204800"), ), }, { - Config: testAccGatewayConfig_GatewayType_Cached(rName), + Config: testAccGatewayConfig_typeCached(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "average_upload_rate_limit_in_bits_per_sec", "0"), @@ -760,7 +760,7 @@ func TestAccStorageGatewayGateway_bandwidthAll(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayBandwidthAllConfig(rName, 102400), + Config: testAccGatewayConfig_bandwidthAll(rName, 102400), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "average_upload_rate_limit_in_bits_per_sec", "102400"), @@ -774,7 +774,7 @@ func TestAccStorageGatewayGateway_bandwidthAll(t *testing.T) { ImportStateVerifyIgnore: []string{"activation_key", "gateway_ip_address"}, }, { - Config: testAccGatewayBandwidthAllConfig(rName, 2*102400), + Config: testAccGatewayConfig_bandwidthAll(rName, 2*102400), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "average_upload_rate_limit_in_bits_per_sec", "204800"), @@ -782,7 +782,7 @@ func TestAccStorageGatewayGateway_bandwidthAll(t *testing.T) { ), }, { - Config: testAccGatewayConfig_GatewayType_Cached(rName), + Config: testAccGatewayConfig_typeCached(rName), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "average_upload_rate_limit_in_bits_per_sec", "0"), @@ -805,7 +805,7 @@ func TestAccStorageGatewayGateway_maintenanceStartTime(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccGatewayMaintenanceStartTimeConfig(rName, 22, 0, "3", ""), + Config: testAccGatewayConfig_maintenanceStartTime(rName, 22, 0, "3", ""), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "maintenance_start_time.#", "1"), @@ -822,7 +822,7 @@ func TestAccStorageGatewayGateway_maintenanceStartTime(t *testing.T) { ImportStateVerifyIgnore: []string{"activation_key", "gateway_ip_address"}, }, { - Config: testAccGatewayMaintenanceStartTimeConfig(rName, 21, 10, "", "12"), + Config: testAccGatewayConfig_maintenanceStartTime(rName, 21, 10, "", "12"), Check: resource.ComposeTestCheckFunc( testAccCheckGatewayExists(resourceName, &gateway), resource.TestCheckResourceAttr(resourceName, "maintenance_start_time.0.hour_of_day", "21"), @@ -997,7 +997,7 @@ resource "aws_instance" "test" { `, rName)) } -func testAccGatewayConfig_GatewayType_Cached(rName string) string { +func testAccGatewayConfig_typeCached(rName string) string { return acctest.ConfigCompose(testAcc_TapeAndVolumeGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1008,7 +1008,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName)) } -func testAccGatewayConfig_GatewayType_FileFSxSMB(rName string) string { +func testAccGatewayConfig_typeFileFSxSMB(rName string) string { return acctest.ConfigCompose(testAcc_FileGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1019,7 +1019,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName)) } -func testAccGatewayConfig_GatewayType_FileS3(rName string) string { +func testAccGatewayConfig_typeFileS3(rName string) string { return acctest.ConfigCompose(testAcc_FileGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1030,7 +1030,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName)) } -func testAccGatewayConfig_Log_Group(rName string) string { +func testAccGatewayConfig_logGroup(rName string) string { return acctest.ConfigCompose(testAcc_FileGatewayBase(rName), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = %[1]q @@ -1046,7 +1046,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName)) } -func testAccGatewayConfig_GatewayType_Stored(rName string) string { +func testAccGatewayConfig_typeStored(rName string) string { return acctest.ConfigCompose(testAcc_TapeAndVolumeGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1057,7 +1057,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName)) } -func testAccGatewayConfig_GatewayType_Vtl(rName string) string { +func testAccGatewayConfig_typeVtl(rName string) string { return acctest.ConfigCompose(testAcc_TapeAndVolumeGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1068,7 +1068,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName)) } -func testAccGatewayConfig_GatewayTimezone(rName, gatewayTimezone string) string { +func testAccGatewayConfig_timezone(rName, gatewayTimezone string) string { return acctest.ConfigCompose(testAcc_FileGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1079,7 +1079,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, gatewayTimezone)) } -func testAccGatewayConfig_GatewayVPCEndpoint(rName string) string { +func testAccGatewayConfig_vpcEndpoint(rName string) string { return acctest.ConfigCompose(testAcc_TapeAndVolumeGatewayBase(rName), fmt.Sprintf(` data "aws_vpc_endpoint_service" "storagegateway" { service = "storagegateway" @@ -1247,7 +1247,7 @@ resource "aws_instance" "test" { `, rName)) } -func testAccGatewayConfig_SMBActiveDirectorySettings(rName, domainName string) string { +func testAccGatewayConfig_smbActiveDirectorySettings(rName, domainName string) string { return acctest.ConfigCompose( testAccGatewaySMBActiveDirectorySettingsBaseConfig(rName), testAccGatewayConfig_DirectoryServiceSimpleDirectory(rName, domainName), @@ -1267,7 +1267,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName)) } -func testAccGatewayConfig_SMBActiveDirectorySettingsTimeout(rName, domainName string, timeout int) string { +func testAccGatewayConfig_smbActiveDirectorySettingsTimeout(rName, domainName string, timeout int) string { return acctest.ConfigCompose( testAccGatewaySMBActiveDirectorySettingsBaseConfig(rName), testAccGatewayConfig_DirectoryServiceSimpleDirectory(rName, domainName), @@ -1288,7 +1288,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, timeout)) } -func testAccGatewayConfig_SMBMicrosoftActiveDirectorySettings(rName, domainName string) string { +func testAccGatewayConfig_smbMicrosoftActiveDirectorySettings(rName, domainName string) string { return acctest.ConfigCompose( testAccGatewaySMBActiveDirectorySettingsBaseConfig(rName), testAccGatewayConfig_DirectoryServiceMicrosoftAD(rName, domainName), @@ -1308,7 +1308,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName)) } -func testAccGatewayConfig_SMBMicrosoftActiveDirectorySettingsTimeout(rName, domainName string, timeout int) string { +func testAccGatewayConfig_smbMicrosoftActiveDirectorySettingsTimeout(rName, domainName string, timeout int) string { return acctest.ConfigCompose( testAccGatewaySMBActiveDirectorySettingsBaseConfig(rName), testAccGatewayConfig_DirectoryServiceMicrosoftAD(rName, domainName), @@ -1329,7 +1329,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, timeout)) } -func testAccGatewayConfig_SMBGuestPassword(rName, smbGuestPassword string) string { +func testAccGatewayConfig_smbGuestPassword(rName, smbGuestPassword string) string { return acctest.ConfigCompose(testAcc_FileGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1341,7 +1341,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, smbGuestPassword)) } -func testAccGatewaySMBSecurityStrategyConfig(rName, strategy string) string { +func testAccGatewayConfig_smbSecurityStrategy(rName, strategy string) string { return acctest.ConfigCompose(testAcc_FileGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1353,7 +1353,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, strategy)) } -func testAccGatewaySMBVisibilityConfig(rName string, visible bool) string { +func testAccGatewayConfig_smbVisibility(rName string, visible bool) string { return acctest.ConfigCompose(testAcc_FileGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1365,7 +1365,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, visible)) } -func testAccGatewayTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccGatewayConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAcc_TapeAndVolumeGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1380,7 +1380,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, tagKey1, tagValue1)) } -func testAccGatewayTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccGatewayConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAcc_TapeAndVolumeGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1396,7 +1396,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccGatewayBandwidthUploadConfig(rName string, rate int) string { +func testAccGatewayConfig_bandwidthUpload(rName string, rate int) string { return acctest.ConfigCompose(testAcc_TapeAndVolumeGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1408,7 +1408,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, rate)) } -func testAccGatewayBandwidthDownloadConfig(rName string, rate int) string { +func testAccGatewayConfig_bandwidthDownload(rName string, rate int) string { return acctest.ConfigCompose(testAcc_TapeAndVolumeGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1420,7 +1420,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, rate)) } -func testAccGatewayBandwidthAllConfig(rName string, rate int) string { +func testAccGatewayConfig_bandwidthAll(rName string, rate int) string { return acctest.ConfigCompose(testAcc_TapeAndVolumeGatewayBase(rName), fmt.Sprintf(` resource "aws_storagegateway_gateway" "test" { gateway_ip_address = aws_instance.test.public_ip @@ -1433,7 +1433,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName, rate)) } -func testAccGatewayMaintenanceStartTimeConfig(rName string, hourOfDay, minuteOfHour int, dayOfWeek, dayOfMonth string) string { +func testAccGatewayConfig_maintenanceStartTime(rName string, hourOfDay, minuteOfHour int, dayOfWeek, dayOfMonth string) string { if dayOfWeek == "" { dayOfWeek = strconv.Quote(dayOfWeek) } diff --git a/internal/service/storagegateway/local_disk_data_source_test.go b/internal/service/storagegateway/local_disk_data_source_test.go index 690b893c0ee..98ded00d0eb 100644 --- a/internal/service/storagegateway/local_disk_data_source_test.go +++ b/internal/service/storagegateway/local_disk_data_source_test.go @@ -23,11 +23,11 @@ func TestAccStorageGatewayLocalDiskDataSource_diskNode(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccLocalDiskDataSourceConfig_DiskNode_NonExistent(rName), + Config: testAccLocalDiskDataSourceConfig_nodeNonExistent(rName), ExpectError: regexp.MustCompile(`no results found`), }, { - Config: testAccLocalDiskDataSourceConfig_DiskNode(rName), + Config: testAccLocalDiskDataSourceConfig_node(rName), Check: resource.ComposeTestCheckFunc( testAccLocalDiskExistsDataSource(dataSourceName), resource.TestMatchResourceAttr(dataSourceName, "disk_id", regexp.MustCompile(`.+`)), @@ -50,11 +50,11 @@ func TestAccStorageGatewayLocalDiskDataSource_diskPath(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccLocalDiskDataSourceConfig_DiskPath_NonExistent(rName), + Config: testAccLocalDiskDataSourceConfig_pathNonExistent(rName), ExpectError: regexp.MustCompile(`no results found`), }, { - Config: testAccLocalDiskDataSourceConfig_DiskPath(rName), + Config: testAccLocalDiskDataSourceConfig_path(rName), Check: resource.ComposeTestCheckFunc( testAccLocalDiskExistsDataSource(dataSourceName), resource.TestMatchResourceAttr(dataSourceName, "disk_id", regexp.MustCompile(`.+`)), @@ -79,7 +79,7 @@ func testAccLocalDiskExistsDataSource(dataSourceName string) resource.TestCheckF func testAccLocalDiskBaseDataSourceConfig(rName string) string { return acctest.ConfigCompose( - testAccGatewayConfig_GatewayType_FileS3(rName), + testAccGatewayConfig_typeFileS3(rName), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone @@ -100,7 +100,7 @@ resource "aws_volume_attachment" "test" { `, rName)) } -func testAccLocalDiskDataSourceConfig_DiskNode(rName string) string { +func testAccLocalDiskDataSourceConfig_node(rName string) string { return acctest.ConfigCompose( testAccLocalDiskBaseDataSourceConfig(rName), ` @@ -111,7 +111,7 @@ data "aws_storagegateway_local_disk" "test" { `) } -func testAccLocalDiskDataSourceConfig_DiskNode_NonExistent(rName string) string { +func testAccLocalDiskDataSourceConfig_nodeNonExistent(rName string) string { return acctest.ConfigCompose( testAccLocalDiskBaseDataSourceConfig(rName), ` @@ -122,7 +122,7 @@ data "aws_storagegateway_local_disk" "test" { `) } -func testAccLocalDiskDataSourceConfig_DiskPath(rName string) string { +func testAccLocalDiskDataSourceConfig_path(rName string) string { return acctest.ConfigCompose( testAccLocalDiskBaseDataSourceConfig(rName), ` @@ -133,7 +133,7 @@ data "aws_storagegateway_local_disk" "test" { `) } -func testAccLocalDiskDataSourceConfig_DiskPath_NonExistent(rName string) string { +func testAccLocalDiskDataSourceConfig_pathNonExistent(rName string) string { return acctest.ConfigCompose( testAccLocalDiskBaseDataSourceConfig(rName), ` diff --git a/internal/service/storagegateway/nfs_file_share_test.go b/internal/service/storagegateway/nfs_file_share_test.go index e9fe6dc399a..1c5851690da 100644 --- a/internal/service/storagegateway/nfs_file_share_test.go +++ b/internal/service/storagegateway/nfs_file_share_test.go @@ -30,7 +30,7 @@ func TestAccStorageGatewayNFSFileShare_basic(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_Required(rName), + Config: testAccNFSFileShareConfig_required(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`share/share-.+`)), @@ -81,7 +81,7 @@ func TestAccStorageGatewayNFSFileShare_audit(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareAuditConfig(rName), + Config: testAccNFSFileShareConfig_audit(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttrPair(resourceName, "audit_destination_arn", logResourceName, "arn"), @@ -93,7 +93,7 @@ func TestAccStorageGatewayNFSFileShare_audit(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNFSFileShareAuditUpdatedConfig(rName), + Config: testAccNFSFileShareConfig_auditUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttrPair(resourceName, "audit_destination_arn", logResourceNameSecond, "arn"), @@ -115,7 +115,7 @@ func TestAccStorageGatewayNFSFileShare_tags(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareTags1Config(rName, "key1", "value1"), + Config: testAccNFSFileShareConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`share/share-.+`)), @@ -129,7 +129,7 @@ func TestAccStorageGatewayNFSFileShare_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNFSFileShareTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccNFSFileShareConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`share/share-.+`)), @@ -139,7 +139,7 @@ func TestAccStorageGatewayNFSFileShare_tags(t *testing.T) { ), }, { - Config: testAccNFSFileShareTags1Config(rName, "key2", "value2"), + Config: testAccNFSFileShareConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`share/share-.+`)), @@ -163,7 +163,7 @@ func TestAccStorageGatewayNFSFileShare_fileShareName(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareFileShareNameConfig(rName, "test_1"), + Config: testAccNFSFileShareConfig_name(rName, "test_1"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "file_share_name", "test_1"), @@ -175,7 +175,7 @@ func TestAccStorageGatewayNFSFileShare_fileShareName(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNFSFileShareFileShareNameConfig(rName, "test_2"), + Config: testAccNFSFileShareConfig_name(rName, "test_2"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "file_share_name", "test_2"), @@ -197,7 +197,7 @@ func TestAccStorageGatewayNFSFileShare_clientList(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_ClientList_Single(rName, "1.1.1.1/32"), + Config: testAccNFSFileShareConfig_clientListSingle(rName, "1.1.1.1/32"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "client_list.#", "1"), @@ -205,7 +205,7 @@ func TestAccStorageGatewayNFSFileShare_clientList(t *testing.T) { ), }, { - Config: testAccNFSFileShareConfig_ClientList_Multiple(rName, "2.2.2.2/32", "3.3.3.3/32"), + Config: testAccNFSFileShareConfig_clientListMultiple(rName, "2.2.2.2/32", "3.3.3.3/32"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "client_list.#", "2"), @@ -214,7 +214,7 @@ func TestAccStorageGatewayNFSFileShare_clientList(t *testing.T) { ), }, { - Config: testAccNFSFileShareConfig_ClientList_Single(rName, "4.4.4.4"), + Config: testAccNFSFileShareConfig_clientListSingle(rName, "4.4.4.4"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "client_list.#", "1"), @@ -242,14 +242,14 @@ func TestAccStorageGatewayNFSFileShare_defaultStorageClass(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_DefaultStorageClass(rName, "S3_STANDARD_IA"), + Config: testAccNFSFileShareConfig_defaultStorageClass(rName, "S3_STANDARD_IA"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "default_storage_class", "S3_STANDARD_IA"), ), }, { - Config: testAccNFSFileShareConfig_DefaultStorageClass(rName, "S3_ONEZONE_IA"), + Config: testAccNFSFileShareConfig_defaultStorageClass(rName, "S3_ONEZONE_IA"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "default_storage_class", "S3_ONEZONE_IA"), @@ -276,14 +276,14 @@ func TestAccStorageGatewayNFSFileShare_guessMIMETypeEnabled(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_GuessMIMETypeEnabled(rName, false), + Config: testAccNFSFileShareConfig_guessMIMETypeEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "guess_mime_type_enabled", "false"), ), }, { - Config: testAccNFSFileShareConfig_GuessMIMETypeEnabled(rName, true), + Config: testAccNFSFileShareConfig_guessMIMETypeEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "guess_mime_type_enabled", "true"), @@ -310,11 +310,11 @@ func TestAccStorageGatewayNFSFileShare_kmsEncrypted(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_KMSEncrypted(rName, true), + Config: testAccNFSFileShareConfig_kmsEncrypted(rName, true), ExpectError: regexp.MustCompile(`KMSKey is missing`), }, { - Config: testAccNFSFileShareConfig_KMSEncrypted(rName, false), + Config: testAccNFSFileShareConfig_kmsEncrypted(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "false"), @@ -343,7 +343,7 @@ func TestAccStorageGatewayNFSFileShare_kmsKeyARN(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_KMSKeyARN(rName), + Config: testAccNFSFileShareConfig_kmsKeyARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "true"), @@ -351,7 +351,7 @@ func TestAccStorageGatewayNFSFileShare_kmsKeyARN(t *testing.T) { ), }, { - Config: testAccNFSFileShareConfig_KMSKeyARN_Update(rName), + Config: testAccNFSFileShareConfig_kmsKeyARNUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "true"), @@ -364,7 +364,7 @@ func TestAccStorageGatewayNFSFileShare_kmsKeyARN(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNFSFileShareConfig_KMSEncrypted(rName, false), + Config: testAccNFSFileShareConfig_kmsEncrypted(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "false"), @@ -386,7 +386,7 @@ func TestAccStorageGatewayNFSFileShare_nFSFileShareDefaults(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_NFSFileShareDefaults(rName, "0700", "0600", 1, 2), + Config: testAccNFSFileShareConfig_defaults(rName, "0700", "0600", 1, 2), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "nfs_file_share_defaults.#", "1"), @@ -397,7 +397,7 @@ func TestAccStorageGatewayNFSFileShare_nFSFileShareDefaults(t *testing.T) { ), }, { - Config: testAccNFSFileShareConfig_NFSFileShareDefaults(rName, "0770", "0660", 3, 4), + Config: testAccNFSFileShareConfig_defaults(rName, "0770", "0660", 3, 4), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "nfs_file_share_defaults.#", "1"), @@ -428,14 +428,14 @@ func TestAccStorageGatewayNFSFileShare_objectACL(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_ObjectACL(rName, storagegateway.ObjectACLPublicRead), + Config: testAccNFSFileShareConfig_objectACL(rName, storagegateway.ObjectACLPublicRead), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPublicRead), ), }, { - Config: testAccNFSFileShareConfig_ObjectACL(rName, storagegateway.ObjectACLPublicReadWrite), + Config: testAccNFSFileShareConfig_objectACL(rName, storagegateway.ObjectACLPublicReadWrite), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPublicReadWrite), @@ -462,14 +462,14 @@ func TestAccStorageGatewayNFSFileShare_readOnly(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_ReadOnly(rName, false), + Config: testAccNFSFileShareConfig_readOnly(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "read_only", "false"), ), }, { - Config: testAccNFSFileShareConfig_ReadOnly(rName, true), + Config: testAccNFSFileShareConfig_readOnly(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "read_only", "true"), @@ -496,14 +496,14 @@ func TestAccStorageGatewayNFSFileShare_requesterPays(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_RequesterPays(rName, false), + Config: testAccNFSFileShareConfig_requesterPays(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "requester_pays", "false"), ), }, { - Config: testAccNFSFileShareConfig_RequesterPays(rName, true), + Config: testAccNFSFileShareConfig_requesterPays(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "requester_pays", "true"), @@ -530,14 +530,14 @@ func TestAccStorageGatewayNFSFileShare_squash(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_Squash(rName, "NoSquash"), + Config: testAccNFSFileShareConfig_squash(rName, "NoSquash"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "squash", "NoSquash"), ), }, { - Config: testAccNFSFileShareConfig_Squash(rName, "AllSquash"), + Config: testAccNFSFileShareConfig_squash(rName, "AllSquash"), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "squash", "AllSquash"), @@ -564,7 +564,7 @@ func TestAccStorageGatewayNFSFileShare_notificationPolicy(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareNotificationPolicyConfig(rName), + Config: testAccNFSFileShareConfig_notificationPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "notification_policy", "{\"Upload\": {\"SettlingTimeInSeconds\": 60}}"), @@ -576,14 +576,14 @@ func TestAccStorageGatewayNFSFileShare_notificationPolicy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNFSFileShareConfig_Required(rName), + Config: testAccNFSFileShareConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "notification_policy", "{}"), ), }, { - Config: testAccNFSFileShareNotificationPolicyConfig(rName), + Config: testAccNFSFileShareConfig_notificationPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "notification_policy", "{\"Upload\": {\"SettlingTimeInSeconds\": 60}}"), @@ -605,7 +605,7 @@ func TestAccStorageGatewayNFSFileShare_cacheAttributes(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareCacheAttributesConfig(rName, 300), + Config: testAccNFSFileShareConfig_cacheAttributes(rName, 300), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "cache_attributes.#", "1"), @@ -618,7 +618,7 @@ func TestAccStorageGatewayNFSFileShare_cacheAttributes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccNFSFileShareCacheAttributesConfig(rName, 500), + Config: testAccNFSFileShareConfig_cacheAttributes(rName, 500), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "cache_attributes.#", "1"), @@ -626,7 +626,7 @@ func TestAccStorageGatewayNFSFileShare_cacheAttributes(t *testing.T) { ), }, { - Config: testAccNFSFileShareCacheAttributesConfig(rName, 300), + Config: testAccNFSFileShareConfig_cacheAttributes(rName, 300), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), resource.TestCheckResourceAttr(resourceName, "cache_attributes.#", "1"), @@ -649,7 +649,7 @@ func TestAccStorageGatewayNFSFileShare_disappears(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_Required(rName), + Config: testAccNFSFileShareConfig_required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(resourceName, &nfsFileShare), acctest.CheckResourceDisappears(acctest.Provider, tfstoragegateway.ResourceNFSFileShare(), resourceName), @@ -776,7 +776,7 @@ resource "aws_storagegateway_gateway" "test" { `, rName) } -func testAccNFSFileShareConfig_Required(rName string) string { +func testAccNFSFileShareConfig_required(rName string) string { return testAcc_S3FileShareBase(rName) + ` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -787,7 +787,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { ` } -func testAccNFSFileShareFileShareNameConfig(rName, fsName string) string { +func testAccNFSFileShareConfig_name(rName, fsName string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -799,7 +799,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, fsName) } -func testAccNFSFileShareTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccNFSFileShareConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -814,7 +814,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, tagKey1, tagValue1) } -func testAccNFSFileShareTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccNFSFileShareConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -830,7 +830,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccNFSFileShareConfig_ClientList_Single(rName, clientList1 string) string { +func testAccNFSFileShareConfig_clientListSingle(rName, clientList1 string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = [%q] @@ -841,7 +841,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, clientList1) } -func testAccNFSFileShareConfig_ClientList_Multiple(rName, clientList1, clientList2 string) string { +func testAccNFSFileShareConfig_clientListMultiple(rName, clientList1, clientList2 string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = [%q, %q] @@ -852,7 +852,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, clientList1, clientList2) } -func testAccNFSFileShareConfig_DefaultStorageClass(rName, defaultStorageClass string) string { +func testAccNFSFileShareConfig_defaultStorageClass(rName, defaultStorageClass string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -864,7 +864,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, defaultStorageClass) } -func testAccNFSFileShareConfig_GuessMIMETypeEnabled(rName string, guessMimeTypeEnabled bool) string { +func testAccNFSFileShareConfig_guessMIMETypeEnabled(rName string, guessMimeTypeEnabled bool) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -876,7 +876,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, guessMimeTypeEnabled) } -func testAccNFSFileShareConfig_KMSEncrypted(rName string, kmsEncrypted bool) string { +func testAccNFSFileShareConfig_kmsEncrypted(rName string, kmsEncrypted bool) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -888,7 +888,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, kmsEncrypted) } -func testAccNFSFileShareConfig_KMSKeyARN(rName string) string { +func testAccNFSFileShareConfig_kmsKeyARN(rName string) string { return testAcc_S3FileShareBase(rName) + ` resource "aws_kms_key" "test" { count = 2 @@ -908,7 +908,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { ` } -func testAccNFSFileShareConfig_KMSKeyARN_Update(rName string) string { +func testAccNFSFileShareConfig_kmsKeyARNUpdate(rName string) string { return testAcc_S3FileShareBase(rName) + ` resource "aws_kms_key" "test" { count = 2 @@ -928,7 +928,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { ` } -func testAccNFSFileShareConfig_NFSFileShareDefaults(rName, directoryMode, fileMode string, groupID, ownerID int) string { +func testAccNFSFileShareConfig_defaults(rName, directoryMode, fileMode string, groupID, ownerID int) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -946,7 +946,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, directoryMode, fileMode, groupID, ownerID) } -func testAccNFSFileShareConfig_ObjectACL(rName, objectACL string) string { +func testAccNFSFileShareConfig_objectACL(rName, objectACL string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -958,7 +958,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, objectACL) } -func testAccNFSFileShareConfig_ReadOnly(rName string, readOnly bool) string { +func testAccNFSFileShareConfig_readOnly(rName string, readOnly bool) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -970,7 +970,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, readOnly) } -func testAccNFSFileShareConfig_RequesterPays(rName string, requesterPays bool) string { +func testAccNFSFileShareConfig_requesterPays(rName string, requesterPays bool) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -982,7 +982,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, requesterPays) } -func testAccNFSFileShareConfig_Squash(rName, squash string) string { +func testAccNFSFileShareConfig_squash(rName, squash string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -994,7 +994,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, squash) } -func testAccNFSFileShareCacheAttributesConfig(rName string, timeout int) string { +func testAccNFSFileShareConfig_cacheAttributes(rName string, timeout int) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -1009,7 +1009,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, timeout) } -func testAccNFSFileShareNotificationPolicyConfig(rName string) string { +func testAccNFSFileShareConfig_notificationPolicy(rName string) string { return testAcc_S3FileShareBase(rName) + ` resource "aws_storagegateway_nfs_file_share" "test" { client_list = ["0.0.0.0/0"] @@ -1021,7 +1021,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { ` } -func testAccNFSFileShareAuditConfig(rName string) string { +func testAccNFSFileShareConfig_audit(rName string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = %[1]q @@ -1037,7 +1037,7 @@ resource "aws_storagegateway_nfs_file_share" "test" { `, rName) } -func testAccNFSFileShareAuditUpdatedConfig(rName string) string { +func testAccNFSFileShareConfig_auditUpdated(rName string) string { return testAcc_S3FileShareBase(rName) + fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = %[1]q diff --git a/internal/service/storagegateway/smb_file_share_test.go b/internal/service/storagegateway/smb_file_share_test.go index 0efe86c41a1..c58581a2adf 100644 --- a/internal/service/storagegateway/smb_file_share_test.go +++ b/internal/service/storagegateway/smb_file_share_test.go @@ -31,7 +31,7 @@ func TestAccStorageGatewaySMBFileShare_Authentication_activeDirectory(t *testing CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_Authentication_ActiveDirectory(rName, domainName), + Config: testAccSMBFileShareConfig_authenticationActiveDirectory(rName, domainName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`share/share-.+`)), @@ -80,7 +80,7 @@ func TestAccStorageGatewaySMBFileShare_Authentication_guestAccess(t *testing.T) CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_Authentication_GuestAccess(rName), + Config: testAccSMBFileShareConfig_authenticationGuestAccess(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "admin_user_list.#", "0"), @@ -127,7 +127,7 @@ func TestAccStorageGatewaySMBFileShare_accessBasedEnumeration(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareAccessBasedEnumerationConfig(rName, true), + Config: testAccSMBFileShareConfig_accessBasedEnumeration(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "access_based_enumeration", "true"), @@ -139,14 +139,14 @@ func TestAccStorageGatewaySMBFileShare_accessBasedEnumeration(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSMBFileShareAccessBasedEnumerationConfig(rName, false), + Config: testAccSMBFileShareConfig_accessBasedEnumeration(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "access_based_enumeration", "false"), ), }, { - Config: testAccSMBFileShareAccessBasedEnumerationConfig(rName, true), + Config: testAccSMBFileShareConfig_accessBasedEnumeration(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "access_based_enumeration", "true"), @@ -168,7 +168,7 @@ func TestAccStorageGatewaySMBFileShare_notificationPolicy(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareNotificationPolicyConfig(rName), + Config: testAccSMBFileShareConfig_notificationPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "notification_policy", "{\"Upload\": {\"SettlingTimeInSeconds\": 60}}"), @@ -180,14 +180,14 @@ func TestAccStorageGatewaySMBFileShare_notificationPolicy(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSMBFileShareConfig_Authentication_GuestAccess(rName), + Config: testAccSMBFileShareConfig_authenticationGuestAccess(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "notification_policy", "{}"), ), }, { - Config: testAccSMBFileShareNotificationPolicyConfig(rName), + Config: testAccSMBFileShareConfig_notificationPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "notification_policy", "{\"Upload\": {\"SettlingTimeInSeconds\": 60}}"), @@ -209,14 +209,14 @@ func TestAccStorageGatewaySMBFileShare_defaultStorageClass(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_DefaultStorageClass(rName, "S3_STANDARD_IA"), + Config: testAccSMBFileShareConfig_defaultStorageClass(rName, "S3_STANDARD_IA"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "default_storage_class", "S3_STANDARD_IA"), ), }, { - Config: testAccSMBFileShareConfig_DefaultStorageClass(rName, "S3_ONEZONE_IA"), + Config: testAccSMBFileShareConfig_defaultStorageClass(rName, "S3_ONEZONE_IA"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "default_storage_class", "S3_ONEZONE_IA"), @@ -243,14 +243,14 @@ func TestAccStorageGatewaySMBFileShare_fileShareName(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_FileShareName(rName, "foo_share"), + Config: testAccSMBFileShareConfig_name(rName, "foo_share"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "file_share_name", "foo_share"), ), }, { - Config: testAccSMBFileShareConfig_FileShareName(rName, "bar_share"), + Config: testAccSMBFileShareConfig_name(rName, "bar_share"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "file_share_name", "bar_share"), @@ -277,7 +277,7 @@ func TestAccStorageGatewaySMBFileShare_tags(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareTags1Config(rName, "key1", "value1"), + Config: testAccSMBFileShareConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -290,7 +290,7 @@ func TestAccStorageGatewaySMBFileShare_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSMBFileShareTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccSMBFileShareConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -299,7 +299,7 @@ func TestAccStorageGatewaySMBFileShare_tags(t *testing.T) { ), }, { - Config: testAccSMBFileShareTags1Config(rName, "key2", "value2"), + Config: testAccSMBFileShareConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -322,14 +322,14 @@ func TestAccStorageGatewaySMBFileShare_guessMIMETypeEnabled(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_GuessMIMETypeEnabled(rName, false), + Config: testAccSMBFileShareConfig_guessMIMETypeEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "guess_mime_type_enabled", "false"), ), }, { - Config: testAccSMBFileShareConfig_GuessMIMETypeEnabled(rName, true), + Config: testAccSMBFileShareConfig_guessMIMETypeEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "guess_mime_type_enabled", "true"), @@ -374,14 +374,14 @@ func TestAccStorageGatewaySMBFileShare_opLocksEnabled(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_OpLocksEnabled(rName, false), + Config: testAccSMBFileShareConfig_opLocksEnabled(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "oplocks_enabled", "false"), ), }, { - Config: testAccSMBFileShareConfig_OpLocksEnabled(rName, true), + Config: testAccSMBFileShareConfig_opLocksEnabled(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "oplocks_enabled", "true"), @@ -410,21 +410,21 @@ func TestAccStorageGatewaySMBFileShare_invalidUserList(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_InvalidUserList_Single(rName, domainName, "invaliduser1"), + Config: testAccSMBFileShareConfig_invalidUserListSingle(rName, domainName, "invaliduser1"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "invalid_user_list.#", "1"), ), }, { - Config: testAccSMBFileShareConfig_InvalidUserList_Multiple(rName, domainName, "invaliduser2", "invaliduser3"), + Config: testAccSMBFileShareConfig_invalidUserListMultiple(rName, domainName, "invaliduser2", "invaliduser3"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "invalid_user_list.#", "2"), ), }, { - Config: testAccSMBFileShareConfig_InvalidUserList_Single(rName, domainName, "invaliduser4"), + Config: testAccSMBFileShareConfig_invalidUserListSingle(rName, domainName, "invaliduser4"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "invalid_user_list.#", "1"), @@ -451,11 +451,11 @@ func TestAccStorageGatewaySMBFileShare_kmsEncrypted(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_KMSEncrypted(rName, true), + Config: testAccSMBFileShareConfig_kmsEncrypted(rName, true), ExpectError: regexp.MustCompile(`KMSKey is missing`), }, { - Config: testAccSMBFileShareConfig_KMSEncrypted(rName, false), + Config: testAccSMBFileShareConfig_kmsEncrypted(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "false"), @@ -484,7 +484,7 @@ func TestAccStorageGatewaySMBFileShare_kmsKeyARN(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_KMSKeyARN(rName), + Config: testAccSMBFileShareConfig_kmsKeyARN(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "true"), @@ -492,7 +492,7 @@ func TestAccStorageGatewaySMBFileShare_kmsKeyARN(t *testing.T) { ), }, { - Config: testAccSMBFileShareConfig_KMSKeyARN_Update(rName), + Config: testAccSMBFileShareConfig_kmsKeyARNUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "true"), @@ -505,7 +505,7 @@ func TestAccStorageGatewaySMBFileShare_kmsKeyARN(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSMBFileShareConfig_KMSEncrypted(rName, false), + Config: testAccSMBFileShareConfig_kmsEncrypted(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "false"), @@ -527,14 +527,14 @@ func TestAccStorageGatewaySMBFileShare_objectACL(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_ObjectACL(rName, storagegateway.ObjectACLPublicRead), + Config: testAccSMBFileShareConfig_objectACL(rName, storagegateway.ObjectACLPublicRead), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPublicRead), ), }, { - Config: testAccSMBFileShareConfig_ObjectACL(rName, storagegateway.ObjectACLPublicReadWrite), + Config: testAccSMBFileShareConfig_objectACL(rName, storagegateway.ObjectACLPublicReadWrite), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPublicReadWrite), @@ -561,14 +561,14 @@ func TestAccStorageGatewaySMBFileShare_readOnly(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_ReadOnly(rName, false), + Config: testAccSMBFileShareConfig_readOnly(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "read_only", "false"), ), }, { - Config: testAccSMBFileShareConfig_ReadOnly(rName, true), + Config: testAccSMBFileShareConfig_readOnly(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "read_only", "true"), @@ -595,14 +595,14 @@ func TestAccStorageGatewaySMBFileShare_requesterPays(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_RequesterPays(rName, false), + Config: testAccSMBFileShareConfig_requesterPays(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "requester_pays", "false"), ), }, { - Config: testAccSMBFileShareConfig_RequesterPays(rName, true), + Config: testAccSMBFileShareConfig_requesterPays(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "requester_pays", "true"), @@ -630,21 +630,21 @@ func TestAccStorageGatewaySMBFileShare_validUserList(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_ValidUserList_Single(rName, domainName, "validuser1"), + Config: testAccSMBFileShareConfig_validUserListSingle(rName, domainName, "validuser1"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "valid_user_list.#", "1"), ), }, { - Config: testAccSMBFileShareConfig_ValidUserList_Multiple(rName, domainName, "validuser2", "validuser3"), + Config: testAccSMBFileShareConfig_validUserListMultiple(rName, domainName, "validuser2", "validuser3"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "valid_user_list.#", "2"), ), }, { - Config: testAccSMBFileShareConfig_ValidUserList_Single(rName, domainName, "validuser4"), + Config: testAccSMBFileShareConfig_validUserListSingle(rName, domainName, "validuser4"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "valid_user_list.#", "1"), @@ -672,7 +672,7 @@ func TestAccStorageGatewaySMBFileShare_SMB_acl(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareSMBACLConfig(rName, domainName, true), + Config: testAccSMBFileShareConfig_acl(rName, domainName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "smb_acl_enabled", "true"), @@ -684,14 +684,14 @@ func TestAccStorageGatewaySMBFileShare_SMB_acl(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSMBFileShareSMBACLConfig(rName, domainName, false), + Config: testAccSMBFileShareConfig_acl(rName, domainName, false), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "smb_acl_enabled", "false"), ), }, { - Config: testAccSMBFileShareSMBACLConfig(rName, domainName, true), + Config: testAccSMBFileShareConfig_acl(rName, domainName, true), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "smb_acl_enabled", "true"), @@ -715,7 +715,7 @@ func TestAccStorageGatewaySMBFileShare_audit(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareAuditDestinationConfig(rName), + Config: testAccSMBFileShareConfig_auditDestination(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttrPair(resourceName, "audit_destination_arn", logResourceName, "arn"), @@ -727,7 +727,7 @@ func TestAccStorageGatewaySMBFileShare_audit(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSMBFileShareAuditDestinationUpdatedConfig(rName), + Config: testAccSMBFileShareConfig_auditDestinationUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttrPair(resourceName, "audit_destination_arn", logResourceNameSecond, "arn"), @@ -749,7 +749,7 @@ func TestAccStorageGatewaySMBFileShare_cacheAttributes(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareCacheAttributesConfig(rName, 300), + Config: testAccSMBFileShareConfig_cacheAttributes(rName, 300), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "cache_attributes.#", "1"), @@ -762,7 +762,7 @@ func TestAccStorageGatewaySMBFileShare_cacheAttributes(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSMBFileShareCacheAttributesConfig(rName, 500), + Config: testAccSMBFileShareConfig_cacheAttributes(rName, 500), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "cache_attributes.#", "1"), @@ -770,7 +770,7 @@ func TestAccStorageGatewaySMBFileShare_cacheAttributes(t *testing.T) { ), }, { - Config: testAccSMBFileShareCacheAttributesConfig(rName, 300), + Config: testAccSMBFileShareConfig_cacheAttributes(rName, 300), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "cache_attributes.#", "1"), @@ -793,7 +793,7 @@ func TestAccStorageGatewaySMBFileShare_caseSensitivity(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareCaseSensitivityConfig(rName, "CaseSensitive"), + Config: testAccSMBFileShareConfig_caseSensitivity(rName, "CaseSensitive"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "case_sensitivity", "CaseSensitive"), @@ -805,14 +805,14 @@ func TestAccStorageGatewaySMBFileShare_caseSensitivity(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccSMBFileShareCaseSensitivityConfig(rName, "ClientSpecified"), + Config: testAccSMBFileShareConfig_caseSensitivity(rName, "ClientSpecified"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "case_sensitivity", "ClientSpecified"), ), }, { - Config: testAccSMBFileShareCaseSensitivityConfig(rName, "CaseSensitive"), + Config: testAccSMBFileShareConfig_caseSensitivity(rName, "CaseSensitive"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "case_sensitivity", "CaseSensitive"), @@ -834,7 +834,7 @@ func TestAccStorageGatewaySMBFileShare_disappears(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_Authentication_GuestAccess(rName), + Config: testAccSMBFileShareConfig_authenticationGuestAccess(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), acctest.CheckResourceDisappears(acctest.Provider, tfstoragegateway.ResourceSMBFileShare(), resourceName), @@ -858,21 +858,21 @@ func TestAccStorageGatewaySMBFileShare_adminUserList(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy, Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_AdminUserList_Single(rName, domainName, "adminuser1"), + Config: testAccSMBFileShareConfig_adminUserListSingle(rName, domainName, "adminuser1"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "admin_user_list.#", "1"), ), }, { - Config: testAccSMBFileShareConfig_AdminUserList_Multiple(rName, domainName, "adminuser2", "adminuser3"), + Config: testAccSMBFileShareConfig_adminUserListMultiple(rName, domainName, "adminuser2", "adminuser3"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "admin_user_list.#", "2"), ), }, { - Config: testAccSMBFileShareConfig_AdminUserList_Single(rName, domainName, "adminuser4"), + Config: testAccSMBFileShareConfig_adminUserListSingle(rName, domainName, "adminuser4"), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(resourceName, &smbFileShare), resource.TestCheckResourceAttr(resourceName, "admin_user_list.#", "1"), @@ -934,7 +934,7 @@ func testAccCheckSMBFileShareExists(resourceName string, smbFileShare *storagega } func testAcc_SMBFileShare_ActiveDirectoryBase(rName, domainName string) string { - return acctest.ConfigCompose(testAccGatewayConfig_SMBActiveDirectorySettings(rName, domainName), fmt.Sprintf(` + return acctest.ConfigCompose(testAccGatewayConfig_smbActiveDirectorySettings(rName, domainName), fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -985,7 +985,7 @@ resource "aws_s3_bucket" "test" { } func testAcc_SMBFileShare_GuestAccessBase(rName string) string { - return acctest.ConfigCompose(testAccGatewayConfig_SMBGuestPassword(rName, "smbguestpassword"), fmt.Sprintf(` + return acctest.ConfigCompose(testAccGatewayConfig_smbGuestPassword(rName, "smbguestpassword"), fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -1035,7 +1035,7 @@ resource "aws_s3_bucket" "test" { `, rName)) } -func testAccSMBFileShareConfig_Authentication_ActiveDirectory(rName, domainName string) string { +func testAccSMBFileShareConfig_authenticationActiveDirectory(rName, domainName string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_ActiveDirectoryBase(rName, domainName), ` resource "aws_storagegateway_smb_file_share" "test" { authentication = "ActiveDirectory" @@ -1046,7 +1046,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `) } -func testAccSMBFileShareConfig_Authentication_GuestAccess(rName string) string { +func testAccSMBFileShareConfig_authenticationGuestAccess(rName string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), ` resource "aws_storagegateway_smb_file_share" "test" { authentication = "GuestAccess" @@ -1057,7 +1057,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `) } -func testAccSMBFileShareAccessBasedEnumerationConfig(rName string, enabled bool) string { +func testAccSMBFileShareConfig_accessBasedEnumeration(rName string, enabled bool) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { authentication = "GuestAccess" @@ -1069,7 +1069,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, enabled)) } -func testAccSMBFileShareNotificationPolicyConfig(rName string) string { +func testAccSMBFileShareConfig_notificationPolicy(rName string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), ` resource "aws_storagegateway_smb_file_share" "test" { authentication = "GuestAccess" @@ -1081,7 +1081,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `) } -func testAccSMBFileShareConfig_DefaultStorageClass(rName, defaultStorageClass string) string { +func testAccSMBFileShareConfig_defaultStorageClass(rName, defaultStorageClass string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1094,7 +1094,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, defaultStorageClass)) } -func testAccSMBFileShareConfig_FileShareName(rName, fileShareName string) string { +func testAccSMBFileShareConfig_name(rName, fileShareName string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1107,7 +1107,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, fileShareName)) } -func testAccSMBFileShareConfig_GuessMIMETypeEnabled(rName string, guessMimeTypeEnabled bool) string { +func testAccSMBFileShareConfig_guessMIMETypeEnabled(rName string, guessMimeTypeEnabled bool) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1121,7 +1121,7 @@ resource "aws_storagegateway_smb_file_share" "test" { } /* -func testAccSMBFileShareConfig_OpLocksEnabled(rName string, opLocksEnabled bool) string { +func testAccSMBFileShareConfig_opLocksEnabled(rName string, opLocksEnabled bool) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1135,7 +1135,7 @@ resource "aws_storagegateway_smb_file_share" "test" { } */ -func testAccSMBFileShareConfig_InvalidUserList_Single(rName, domainName, invalidUser1 string) string { +func testAccSMBFileShareConfig_invalidUserListSingle(rName, domainName, invalidUser1 string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_ActiveDirectoryBase(rName, domainName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Must be ActiveDirectory @@ -1148,7 +1148,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, invalidUser1)) } -func testAccSMBFileShareConfig_InvalidUserList_Multiple(rName, domainName, invalidUser1, invalidUser2 string) string { +func testAccSMBFileShareConfig_invalidUserListMultiple(rName, domainName, invalidUser1, invalidUser2 string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_ActiveDirectoryBase(rName, domainName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Must be ActiveDirectory @@ -1161,7 +1161,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, invalidUser1, invalidUser2)) } -func testAccSMBFileShareConfig_KMSEncrypted(rName string, kmsEncrypted bool) string { +func testAccSMBFileShareConfig_kmsEncrypted(rName string, kmsEncrypted bool) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1174,7 +1174,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, kmsEncrypted)) } -func testAccSMBFileShareConfig_KMSKeyARN(rName string) string { +func testAccSMBFileShareConfig_kmsKeyARN(rName string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), ` resource "aws_kms_key" "test" { count = 2 @@ -1195,7 +1195,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `) } -func testAccSMBFileShareConfig_KMSKeyARN_Update(rName string) string { +func testAccSMBFileShareConfig_kmsKeyARNUpdate(rName string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), ` resource "aws_kms_key" "test" { count = 2 @@ -1216,7 +1216,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `) } -func testAccSMBFileShareConfig_ObjectACL(rName, objectACL string) string { +func testAccSMBFileShareConfig_objectACL(rName, objectACL string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1229,7 +1229,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, objectACL)) } -func testAccSMBFileShareConfig_ReadOnly(rName string, readOnly bool) string { +func testAccSMBFileShareConfig_readOnly(rName string, readOnly bool) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1242,7 +1242,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, readOnly)) } -func testAccSMBFileShareConfig_RequesterPays(rName string, requesterPays bool) string { +func testAccSMBFileShareConfig_requesterPays(rName string, requesterPays bool) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1255,7 +1255,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, requesterPays)) } -func testAccSMBFileShareConfig_ValidUserList_Single(rName, domainName, validUser1 string) string { +func testAccSMBFileShareConfig_validUserListSingle(rName, domainName, validUser1 string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_ActiveDirectoryBase(rName, domainName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Must be ActiveDirectory @@ -1268,7 +1268,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, validUser1)) } -func testAccSMBFileShareConfig_ValidUserList_Multiple(rName, domainName, validUser1, validUser2 string) string { +func testAccSMBFileShareConfig_validUserListMultiple(rName, domainName, validUser1, validUser2 string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_ActiveDirectoryBase(rName, domainName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Must be ActiveDirectory @@ -1281,7 +1281,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, validUser1, validUser2)) } -func testAccSMBFileShareConfig_AdminUserList_Single(rName, domainName, adminUser1 string) string { +func testAccSMBFileShareConfig_adminUserListSingle(rName, domainName, adminUser1 string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_ActiveDirectoryBase(rName, domainName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Must be ActiveDirectory @@ -1294,7 +1294,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, adminUser1)) } -func testAccSMBFileShareConfig_AdminUserList_Multiple(rName, domainName, adminUser1, adminUser2 string) string { +func testAccSMBFileShareConfig_adminUserListMultiple(rName, domainName, adminUser1, adminUser2 string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_ActiveDirectoryBase(rName, domainName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Must be ActiveDirectory @@ -1307,7 +1307,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, adminUser1, adminUser2)) } -func testAccSMBFileShareTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccSMBFileShareConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1323,7 +1323,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, tagKey1, tagValue1)) } -func testAccSMBFileShareTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccSMBFileShareConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1340,7 +1340,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, tagKey1, tagValue1, tagKey2, tagValue2)) } -func testAccSMBFileShareSMBACLConfig(rName, domainName string, enabled bool) string { +func testAccSMBFileShareConfig_acl(rName, domainName string, enabled bool) string { return acctest.ConfigCompose(testAcc_SMBFileShare_ActiveDirectoryBase(rName, domainName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { authentication = "ActiveDirectory" @@ -1352,7 +1352,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, enabled)) } -func testAccSMBFileShareAuditDestinationConfig(rName string) string { +func testAccSMBFileShareConfig_auditDestination(rName string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = %[1]q @@ -1369,7 +1369,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, rName)) } -func testAccSMBFileShareAuditDestinationUpdatedConfig(rName string) string { +func testAccSMBFileShareConfig_auditDestinationUpdated(rName string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_cloudwatch_log_group" "test" { name = %[1]q @@ -1390,7 +1390,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, rName)) } -func testAccSMBFileShareCacheAttributesConfig(rName string, timeout int) string { +func testAccSMBFileShareConfig_cacheAttributes(rName string, timeout int) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing @@ -1406,7 +1406,7 @@ resource "aws_storagegateway_smb_file_share" "test" { `, timeout)) } -func testAccSMBFileShareCaseSensitivityConfig(rName, option string) string { +func testAccSMBFileShareConfig_caseSensitivity(rName, option string) string { return acctest.ConfigCompose(testAcc_SMBFileShare_GuestAccessBase(rName), fmt.Sprintf(` resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing diff --git a/internal/service/storagegateway/stored_iscsi_volume_test.go b/internal/service/storagegateway/stored_iscsi_volume_test.go index e50c2ac2f0f..4237d4be759 100644 --- a/internal/service/storagegateway/stored_iscsi_volume_test.go +++ b/internal/service/storagegateway/stored_iscsi_volume_test.go @@ -28,7 +28,7 @@ func TestAccStorageGatewayStorediSCSIVolume_basic(t *testing.T) { CheckDestroy: testAccCheckStorediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccStorediSCSIVolumeBasicConfig(rName), + Config: testAccStorediSCSIVolumeConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStorediSCSIVolumeExists(resourceName, &storedIscsiVolume), resource.TestCheckResourceAttr(resourceName, "preserve_existing_data", "false"), @@ -70,7 +70,7 @@ func TestAccStorageGatewayStorediSCSIVolume_kms(t *testing.T) { CheckDestroy: testAccCheckStorediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccStorediSCSIVolumeKMSEncryptedConfig(rName), + Config: testAccStorediSCSIVolumeConfig_kmsEncrypted(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStorediSCSIVolumeExists(resourceName, &storedIscsiVolume), resource.TestCheckResourceAttr(resourceName, "kms_encrypted", "true"), @@ -98,7 +98,7 @@ func TestAccStorageGatewayStorediSCSIVolume_tags(t *testing.T) { CheckDestroy: testAccCheckStorediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccStorediSCSIVolumeTags1Config(rName, "key1", "value1"), + Config: testAccStorediSCSIVolumeConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckStorediSCSIVolumeExists(resourceName, &storedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -112,7 +112,7 @@ func TestAccStorageGatewayStorediSCSIVolume_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccStorediSCSIVolumeTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccStorediSCSIVolumeConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStorediSCSIVolumeExists(resourceName, &storedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -122,7 +122,7 @@ func TestAccStorageGatewayStorediSCSIVolume_tags(t *testing.T) { ), }, { - Config: testAccStorediSCSIVolumeTags1Config(rName, "key2", "value2"), + Config: testAccStorediSCSIVolumeConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckStorediSCSIVolumeExists(resourceName, &storedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -146,7 +146,7 @@ func TestAccStorageGatewayStorediSCSIVolume_snapshotID(t *testing.T) { CheckDestroy: testAccCheckStorediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccStorediSCSIVolumeSnapshotIDConfig(rName), + Config: testAccStorediSCSIVolumeConfig_snapshotID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStorediSCSIVolumeExists(resourceName, &storedIscsiVolume), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`gateway/sgw-.+/volume/vol-.+`)), @@ -183,7 +183,7 @@ func TestAccStorageGatewayStorediSCSIVolume_disappears(t *testing.T) { CheckDestroy: testAccCheckStorediSCSIVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccStorediSCSIVolumeBasicConfig(rName), + Config: testAccStorediSCSIVolumeConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckStorediSCSIVolumeExists(resourceName, &storedIscsiVolume), acctest.CheckResourceDisappears(acctest.Provider, tfstoragegateway.ResourceStorediSCSIVolume(), resourceName), @@ -259,7 +259,7 @@ func testAccCheckStorediSCSIVolumeDestroy(s *terraform.State) error { } func testAccStorediSCSIVolumeBaseConfig(rName string) string { - return testAccGatewayConfig_GatewayType_Stored(rName) + fmt.Sprintf(` + return testAccGatewayConfig_typeStored(rName) + fmt.Sprintf(` resource "aws_ebs_volume" "buffer" { availability_zone = aws_instance.test.availability_zone size = 10 @@ -311,7 +311,7 @@ data "aws_storagegateway_local_disk" "test" { `, rName) } -func testAccStorediSCSIVolumeBasicConfig(rName string) string { +func testAccStorediSCSIVolumeConfig_basic(rName string) string { return testAccStorediSCSIVolumeBaseConfig(rName) + fmt.Sprintf(` resource "aws_storagegateway_stored_iscsi_volume" "test" { gateway_arn = data.aws_storagegateway_local_disk.test.gateway_arn @@ -325,7 +325,7 @@ resource "aws_storagegateway_stored_iscsi_volume" "test" { `, rName) } -func testAccStorediSCSIVolumeKMSEncryptedConfig(rName string) string { +func testAccStorediSCSIVolumeConfig_kmsEncrypted(rName string) string { return testAccStorediSCSIVolumeBaseConfig(rName) + fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Terraform acc test %[1]s" @@ -362,7 +362,7 @@ resource "aws_storagegateway_stored_iscsi_volume" "test" { `, rName) } -func testAccStorediSCSIVolumeTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccStorediSCSIVolumeConfig_tags1(rName, tagKey1, tagValue1 string) string { return testAccStorediSCSIVolumeBaseConfig(rName) + fmt.Sprintf(` resource "aws_storagegateway_stored_iscsi_volume" "test" { gateway_arn = data.aws_storagegateway_local_disk.test.gateway_arn @@ -380,7 +380,7 @@ resource "aws_storagegateway_stored_iscsi_volume" "test" { `, rName, tagKey1, tagValue1) } -func testAccStorediSCSIVolumeTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccStorediSCSIVolumeConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccStorediSCSIVolumeBaseConfig(rName) + fmt.Sprintf(` resource "aws_storagegateway_stored_iscsi_volume" "test" { gateway_arn = data.aws_storagegateway_local_disk.test.gateway_arn @@ -399,7 +399,7 @@ resource "aws_storagegateway_stored_iscsi_volume" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccStorediSCSIVolumeSnapshotIDConfig(rName string) string { +func testAccStorediSCSIVolumeConfig_snapshotID(rName string) string { return testAccStorediSCSIVolumeBaseConfig(rName) + fmt.Sprintf(` resource "aws_ebs_volume" "snapvolume" { availability_zone = aws_instance.test.availability_zone diff --git a/internal/service/storagegateway/tape_pool_test.go b/internal/service/storagegateway/tape_pool_test.go index fef4efde29e..6f5edc37e86 100644 --- a/internal/service/storagegateway/tape_pool_test.go +++ b/internal/service/storagegateway/tape_pool_test.go @@ -27,7 +27,7 @@ func TestAccStorageGatewayTapePool_basic(t *testing.T) { CheckDestroy: testAccCheckTapePoolDestroy, Steps: []resource.TestStep{ { - Config: testAccTapePoolBasicConfig(rName), + Config: testAccTapePoolConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTapePoolExists(resourceName, &TapePool), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`tapepool/pool-.+`)), @@ -58,7 +58,7 @@ func TestAccStorageGatewayTapePool_retention(t *testing.T) { CheckDestroy: testAccCheckTapePoolDestroy, Steps: []resource.TestStep{ { - Config: testAccTapePoolRetentionConfig(rName), + Config: testAccTapePoolConfig_retention(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTapePoolExists(resourceName, &TapePool), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "storagegateway", regexp.MustCompile(`tapepool/pool-.+`)), @@ -89,7 +89,7 @@ func TestAccStorageGatewayTapePool_tags(t *testing.T) { CheckDestroy: testAccCheckTapePoolDestroy, Steps: []resource.TestStep{ { - Config: testAccTapePoolTags1Config(rName, "key1", "value1"), + Config: testAccTapePoolConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckTapePoolExists(resourceName, &TapePool), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -102,7 +102,7 @@ func TestAccStorageGatewayTapePool_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccTapePoolTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccTapePoolConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTapePoolExists(resourceName, &TapePool), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -111,7 +111,7 @@ func TestAccStorageGatewayTapePool_tags(t *testing.T) { ), }, { - Config: testAccTapePoolTags1Config(rName, "key2", "value2"), + Config: testAccTapePoolConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckTapePoolExists(resourceName, &TapePool), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -134,7 +134,7 @@ func TestAccStorageGatewayTapePool_disappears(t *testing.T) { CheckDestroy: testAccCheckTapePoolDestroy, Steps: []resource.TestStep{ { - Config: testAccTapePoolBasicConfig(rName), + Config: testAccTapePoolConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckTapePoolExists(resourceName, &storedIscsiVolume), acctest.CheckResourceDisappears(acctest.Provider, tfstoragegateway.ResourceTapePool(), resourceName), @@ -200,7 +200,7 @@ func testAccCheckTapePoolDestroy(s *terraform.State) error { return nil } -func testAccTapePoolBasicConfig(rName string) string { +func testAccTapePoolConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_storagegateway_tape_pool" "test" { pool_name = %[1]q @@ -209,7 +209,7 @@ resource "aws_storagegateway_tape_pool" "test" { `, rName) } -func testAccTapePoolRetentionConfig(rName string) string { +func testAccTapePoolConfig_retention(rName string) string { return fmt.Sprintf(` resource "aws_storagegateway_tape_pool" "test" { pool_name = %[1]q @@ -220,7 +220,7 @@ resource "aws_storagegateway_tape_pool" "test" { `, rName) } -func testAccTapePoolTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccTapePoolConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_storagegateway_tape_pool" "test" { pool_name = %[1]q @@ -233,7 +233,7 @@ resource "aws_storagegateway_tape_pool" "test" { `, rName, tagKey1, tagValue1) } -func testAccTapePoolTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccTapePoolConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_storagegateway_tape_pool" "test" { pool_name = %[1]q diff --git a/internal/service/storagegateway/upload_buffer_test.go b/internal/service/storagegateway/upload_buffer_test.go index 79093b22e01..850566fb6a9 100644 --- a/internal/service/storagegateway/upload_buffer_test.go +++ b/internal/service/storagegateway/upload_buffer_test.go @@ -85,7 +85,7 @@ func TestAccStorageGatewayUploadBuffer_basic(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccUploadBufferDiskIDConfig(rName), + Config: testAccUploadBufferConfig_diskID(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUploadBufferExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "disk_id", localDiskDataSourceName, "id"), @@ -118,7 +118,7 @@ func TestAccStorageGatewayUploadBuffer_diskPath(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccUploadBufferDiskPathConfig(rName), + Config: testAccUploadBufferConfig_diskPath(rName), Check: resource.ComposeTestCheckFunc( testAccCheckUploadBufferExists(resourceName), resource.TestMatchResourceAttr(resourceName, "disk_id", regexp.MustCompile(`.+`)), @@ -163,8 +163,8 @@ func testAccCheckUploadBufferExists(resourceName string) resource.TestCheckFunc } } -func testAccUploadBufferDiskIDConfig(rName string) string { - return testAccGatewayConfig_GatewayType_Stored(rName) + fmt.Sprintf(` +func testAccUploadBufferConfig_diskID(rName string) string { + return testAccGatewayConfig_typeStored(rName) + fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" @@ -194,8 +194,8 @@ resource "aws_storagegateway_upload_buffer" "test" { `, rName) } -func testAccUploadBufferDiskPathConfig(rName string) string { - return testAccGatewayConfig_GatewayType_Cached(rName) + fmt.Sprintf(` +func testAccUploadBufferConfig_diskPath(rName string) string { + return testAccGatewayConfig_typeCached(rName) + fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" diff --git a/internal/service/storagegateway/working_storage_test.go b/internal/service/storagegateway/working_storage_test.go index d5fc69d3048..39d92a0ea52 100644 --- a/internal/service/storagegateway/working_storage_test.go +++ b/internal/service/storagegateway/working_storage_test.go @@ -85,7 +85,7 @@ func TestAccStorageGatewayWorkingStorage_basic(t *testing.T) { CheckDestroy: testAccCheckGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccWorkingStorageConfig_Basic(rName), + Config: testAccWorkingStorageConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckWorkingStorageExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "disk_id", localDiskDataSourceName, "id"), @@ -139,8 +139,8 @@ func testAccCheckWorkingStorageExists(resourceName string) resource.TestCheckFun } } -func testAccWorkingStorageConfig_Basic(rName string) string { - return testAccGatewayConfig_GatewayType_Stored(rName) + fmt.Sprintf(` +func testAccWorkingStorageConfig_basic(rName string) string { + return testAccGatewayConfig_typeStored(rName) + fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" diff --git a/internal/service/swf/domain_test.go b/internal/service/swf/domain_test.go index 57493617aea..ee419e3a8c1 100644 --- a/internal/service/swf/domain_test.go +++ b/internal/service/swf/domain_test.go @@ -38,7 +38,7 @@ func TestAccSWFDomain_basic(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_Name(rName), + Config: testAccDomainConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDomainExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "swf", regexp.MustCompile(`/domain/.+`)), @@ -69,7 +69,7 @@ func TestAccSWFDomain_tags(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainTags1Config(rName, "key1", "value1"), + Config: testAccDomainConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDomainExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -82,7 +82,7 @@ func TestAccSWFDomain_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccDomainTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccDomainConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDomainExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -91,7 +91,7 @@ func TestAccSWFDomain_tags(t *testing.T) { ), }, { - Config: testAccDomainTags1Config(rName, "key2", "value2"), + Config: testAccDomainConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDomainExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -115,7 +115,7 @@ func TestAccSWFDomain_namePrefix(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_NamePrefix, + Config: testAccDomainConfig_namePrefix, Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDomainExists(resourceName), resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile(`^tf-acc-test`)), @@ -144,7 +144,7 @@ func TestAccSWFDomain_generatedName(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_GeneratedName, + Config: testAccDomainConfig_generatedName, Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDomainExists(resourceName), ), @@ -172,7 +172,7 @@ func TestAccSWFDomain_description(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy, Steps: []resource.TestStep{ { - Config: testAccDomainConfig_Description(rName, "description1"), + Config: testAccDomainConfig_description(rName, "description1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckDomainExists(resourceName), resource.TestCheckResourceAttr(resourceName, "description", "description1"), @@ -243,7 +243,7 @@ func testAccCheckDomainExists(n string) resource.TestCheckFunc { } } -func testAccDomainConfig_Description(rName, description string) string { +func testAccDomainConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_swf_domain" "test" { description = %q @@ -253,13 +253,13 @@ resource "aws_swf_domain" "test" { `, description, rName) } -const testAccDomainConfig_GeneratedName = ` +const testAccDomainConfig_generatedName = ` resource "aws_swf_domain" "test" { workflow_execution_retention_period_in_days = 1 } ` -func testAccDomainConfig_Name(rName string) string { +func testAccDomainConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_swf_domain" "test" { name = %q @@ -268,7 +268,7 @@ resource "aws_swf_domain" "test" { `, rName) } -func testAccDomainTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccDomainConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_swf_domain" "test" { name = %[1]q @@ -281,7 +281,7 @@ resource "aws_swf_domain" "test" { `, rName, tagKey1, tagValue1) } -func testAccDomainTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccDomainConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_swf_domain" "test" { name = %[1]q @@ -295,7 +295,7 @@ resource "aws_swf_domain" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -const testAccDomainConfig_NamePrefix = ` +const testAccDomainConfig_namePrefix = ` resource "aws_swf_domain" "test" { name_prefix = "tf-acc-test" workflow_execution_retention_period_in_days = 1 diff --git a/internal/service/synthetics/canary.go b/internal/service/synthetics/canary.go index 7fbba770ce9..d8675f6c407 100644 --- a/internal/service/synthetics/canary.go +++ b/internal/service/synthetics/canary.go @@ -74,6 +74,11 @@ func ResourceCanary() *schema.Resource { return strings.TrimPrefix(new, "s3://") == old }, }, + "delete_lambda": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, "engine_arn": { Type: schema.TypeString, Computed: true, @@ -549,7 +554,8 @@ func resourceCanaryDelete(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Deleting Synthetics Canary: (%s)", d.Id()) _, err := conn.DeleteCanary(&synthetics.DeleteCanaryInput{ - Name: aws.String(d.Id()), + Name: aws.String(d.Id()), + DeleteLambda: aws.Bool(d.Get("delete_lambda").(bool)), }) if tfawserr.ErrCodeEquals(err, synthetics.ErrCodeResourceNotFoundException) { diff --git a/internal/service/synthetics/canary_test.go b/internal/service/synthetics/canary_test.go index eee08e11a81..420fc6a82ab 100644 --- a/internal/service/synthetics/canary_test.go +++ b/internal/service/synthetics/canary_test.go @@ -3,12 +3,8 @@ package synthetics_test import ( "fmt" "regexp" - "strings" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/lambda" "github.com/aws/aws-sdk-go/service/synthetics" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -31,7 +27,7 @@ func TestAccSyntheticsCanary_basic(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryBasicConfig(rName), + Config: testAccCanaryConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf1), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", synthetics.ServiceName, regexp.MustCompile(`canary:.+`)), @@ -60,10 +56,10 @@ func TestAccSyntheticsCanary_basic(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda"}, }, { - Config: testAccCanaryZipUpdatedConfig(rName), + Config: testAccCanaryConfig_zipUpdated(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf2), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", synthetics.ServiceName, regexp.MustCompile(`canary:.+`)), @@ -105,7 +101,7 @@ func TestAccSyntheticsCanary_artifactEncryption(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryArtifactEncryptionConfig(rName), + Config: testAccCanaryConfig_artifactEncryption(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "artifact_config.#", "1"), @@ -117,10 +113,10 @@ func TestAccSyntheticsCanary_artifactEncryption(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda"}, }, { - Config: testAccCanaryArtifactEncryptionKMSConfig(rName), + Config: testAccCanaryConfig_artifactEncryptionKMS(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "artifact_config.#", "1"), @@ -145,7 +141,7 @@ func TestAccSyntheticsCanary_runtimeVersion(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryRuntimeVersionConfig(rName, "syn-nodejs-puppeteer-3.1"), + Config: testAccCanaryConfig_runtimeVersion(rName, "syn-nodejs-puppeteer-3.1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf1), resource.TestCheckResourceAttr(resourceName, "runtime_version", "syn-nodejs-puppeteer-3.1"), @@ -155,10 +151,10 @@ func TestAccSyntheticsCanary_runtimeVersion(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda"}, }, { - Config: testAccCanaryRuntimeVersionConfig(rName, "syn-nodejs-puppeteer-3.2"), + Config: testAccCanaryConfig_runtimeVersion(rName, "syn-nodejs-puppeteer-3.2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf1), resource.TestCheckResourceAttr(resourceName, "runtime_version", "syn-nodejs-puppeteer-3.2"), @@ -180,7 +176,7 @@ func TestAccSyntheticsCanary_startCanary(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryStartCanaryConfig(rName, true), + Config: testAccCanaryConfig_start(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf1), resource.TestCheckResourceAttr(resourceName, "timeline.#", "1"), @@ -191,10 +187,10 @@ func TestAccSyntheticsCanary_startCanary(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda"}, }, { - Config: testAccCanaryStartCanaryConfig(rName, false), + Config: testAccCanaryConfig_start(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf2), resource.TestCheckResourceAttr(resourceName, "timeline.#", "1"), @@ -203,7 +199,7 @@ func TestAccSyntheticsCanary_startCanary(t *testing.T) { ), }, { - Config: testAccCanaryStartCanaryConfig(rName, true), + Config: testAccCanaryConfig_start(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf3), resource.TestCheckResourceAttr(resourceName, "timeline.#", "1"), @@ -228,7 +224,7 @@ func TestAccSyntheticsCanary_StartCanary_codeChanges(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryStartCanaryConfig(rName, true), + Config: testAccCanaryConfig_start(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf1), resource.TestCheckResourceAttr(resourceName, "status", "RUNNING"), @@ -240,10 +236,10 @@ func TestAccSyntheticsCanary_StartCanary_codeChanges(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda"}, }, { - Config: testAccCanaryStartCanaryZipUpdatedConfig(rName, true), + Config: testAccCanaryConfig_startZipUpdated(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf2), resource.TestCheckResourceAttr(resourceName, "status", "RUNNING"), @@ -269,7 +265,7 @@ func TestAccSyntheticsCanary_s3(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryBasicS3CodeConfig(rName), + Config: testAccCanaryConfig_basicS3Code(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", synthetics.ServiceName, regexp.MustCompile(`canary:.+`)), @@ -295,7 +291,7 @@ func TestAccSyntheticsCanary_s3(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"s3_bucket", "s3_key", "s3_version", "start_canary"}, + ImportStateVerifyIgnore: []string{"s3_bucket", "s3_key", "s3_version", "start_canary", "delete_lambda"}, }, }, }) @@ -313,7 +309,7 @@ func TestAccSyntheticsCanary_run(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryRun1Config(rName), + Config: testAccCanaryConfig_run1(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -325,10 +321,10 @@ func TestAccSyntheticsCanary_run(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda"}, }, { - Config: testAccCanaryRun2Config(rName), + Config: testAccCanaryConfig_run2(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "run_config.0.memory_in_mb", "960"), @@ -336,7 +332,7 @@ func TestAccSyntheticsCanary_run(t *testing.T) { ), }, { - Config: testAccCanaryRun1Config(rName), + Config: testAccCanaryConfig_run1(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "run_config.0.memory_in_mb", "960"), @@ -359,7 +355,7 @@ func TestAccSyntheticsCanary_runTracing(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryRunTracingConfig(rName, true), + Config: testAccCanaryConfig_runTracing(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "run_config.0.active_tracing", "true"), @@ -369,17 +365,17 @@ func TestAccSyntheticsCanary_runTracing(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda"}, }, { - Config: testAccCanaryRunTracingConfig(rName, false), + Config: testAccCanaryConfig_runTracing(rName, false), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "run_config.0.active_tracing", "false"), ), }, { - Config: testAccCanaryRunTracingConfig(rName, true), + Config: testAccCanaryConfig_runTracing(rName, true), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "run_config.0.active_tracing", "true"), @@ -401,9 +397,10 @@ func TestAccSyntheticsCanary_runEnvironmentVariables(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryRunEnvVariables1Config(rName), + Config: testAccCanaryConfig_runEnvVariables1(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "run_config.0.environment_variables.%", "1"), resource.TestCheckResourceAttr(resourceName, "run_config.0.environment_variables.test1", "result1"), ), }, @@ -411,23 +408,17 @@ func TestAccSyntheticsCanary_runEnvironmentVariables(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "run_config.0.environment_variables"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda", "run_config.0.environment_variables"}, }, { - Config: testAccCanaryRunEnvVariables2Config(rName), + Config: testAccCanaryConfig_runEnvVariables2(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "run_config.0.environment_variables.%", "2"), resource.TestCheckResourceAttr(resourceName, "run_config.0.environment_variables.test1", "result1"), resource.TestCheckResourceAttr(resourceName, "run_config.0.environment_variables.test2", "result2"), ), }, - { - Config: testAccCanaryBasicConfig(rName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckCanaryExists(resourceName, &conf), - resource.TestCheckNoResourceAttr(resourceName, "run_config.0.environment_variables"), - ), - }, }, }) } @@ -448,7 +439,7 @@ func TestAccSyntheticsCanary_vpc(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryVPC1Config(rName), + Config: testAccCanaryConfig_vpc1(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "vpc_config.0.subnet_ids.#", "1"), @@ -460,10 +451,10 @@ func TestAccSyntheticsCanary_vpc(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda"}, }, { - Config: testAccCanaryVPC2Config(rName), + Config: testAccCanaryConfig_vpc2(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "vpc_config.0.subnet_ids.#", "2"), @@ -472,13 +463,12 @@ func TestAccSyntheticsCanary_vpc(t *testing.T) { ), }, { - Config: testAccCanaryVPC3Config(rName), + Config: testAccCanaryConfig_vpc3(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "vpc_config.0.subnet_ids.#", "1"), resource.TestCheckResourceAttr(resourceName, "vpc_config.0.security_group_ids.#", "1"), resource.TestCheckResourceAttrPair(resourceName, "vpc_config.0.vpc_id", "aws_vpc.test", "id"), - testAccCheckCanaryDeleteImplicitResources(resourceName), ), }, }, @@ -497,7 +487,7 @@ func TestAccSyntheticsCanary_tags(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryTags1Config(rName, "key1", "value1"), + Config: testAccCanaryConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -508,10 +498,10 @@ func TestAccSyntheticsCanary_tags(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"zip_file", "start_canary"}, + ImportStateVerifyIgnore: []string{"zip_file", "start_canary", "delete_lambda"}, }, { - Config: testAccCanaryTags2Config(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccCanaryConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -520,7 +510,7 @@ func TestAccSyntheticsCanary_tags(t *testing.T) { ), }, { - Config: testAccCanaryTags1Config(rName, "key2", "value2"), + Config: testAccCanaryConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -543,7 +533,7 @@ func TestAccSyntheticsCanary_disappears(t *testing.T) { CheckDestroy: testAccCheckCanaryDestroy, Steps: []resource.TestStep{ { - Config: testAccCanaryBasicConfig(rName), + Config: testAccCanaryConfig_basic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckCanaryExists(resourceName, &conf), acctest.CheckResourceDisappears(acctest.Provider, tfsynthetics.ResourceCanary(), resourceName), @@ -604,57 +594,6 @@ func testAccCheckCanaryExists(n string, canary *synthetics.Canary) resource.Test } } -func testAccCheckCanaryDeleteImplicitResources(n string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("synthetics Canary not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("synthetics Canary name not set") - } - - lambdaConn := acctest.Provider.Meta().(*conns.AWSClient).LambdaConn - - layerArn := rs.Primary.Attributes["source_location_arn"] - layerArnObj, err := arn.Parse(layerArn) - if err != nil { - return fmt.Errorf("synthetics Canary Lambda Layer %s incorrect arn format: %w", layerArn, err) - } - - layerName := strings.Split(layerArnObj.Resource, ":") - - deleteLayerVersionInput := &lambda.DeleteLayerVersionInput{ - LayerName: aws.String(layerName[1]), - VersionNumber: aws.Int64(1), - } - - _, err = lambdaConn.DeleteLayerVersion(deleteLayerVersionInput) - if err != nil { - return fmt.Errorf("synthetics Canary Lambda Layer %s could not be deleted: %w", layerArn, err) - } - - lambdaArn := rs.Primary.Attributes["engine_arn"] - lambdaArnObj, err := arn.Parse(layerArn) - if err != nil { - return fmt.Errorf("synthetics Canary Lambda %s incorrect arn format: %w", lambdaArn, err) - } - lambdaArnParts := strings.Split(lambdaArnObj.Resource, ":") - - deleteLambdaInput := &lambda.DeleteFunctionInput{ - FunctionName: aws.String(lambdaArnParts[1]), - } - - _, err = lambdaConn.DeleteFunction(deleteLambdaInput) - if err != nil { - return fmt.Errorf("synthetics Canary Lambda %s could not be deleted: %w", lambdaArn, err) - } - - return nil - } -} - func testAccCheckCanaryIsUpdated(first, second *synthetics.Canary) resource.TestCheckFunc { return func(s *terraform.State) error { if !second.Timeline.LastModified.After(*first.Timeline.LastModified) { @@ -789,7 +728,7 @@ EOF `, rName) } -func testAccCanaryRun1Config(rName string) string { +func testAccCanaryConfig_run1(rName string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -798,6 +737,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -812,7 +752,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryRun2Config(rName string) string { +func testAccCanaryConfig_run2(rName string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -821,6 +761,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -836,7 +777,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryRunTracingConfig(rName string, tracing bool) string { +func testAccCanaryConfig_runTracing(rName string, tracing bool) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -845,6 +786,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -860,7 +802,7 @@ resource "aws_synthetics_canary" "test" { `, rName, tracing)) } -func testAccCanaryRunEnvVariables1Config(rName string) string { +func testAccCanaryConfig_runEnvVariables1(rName string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -869,6 +811,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -885,7 +828,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryRunEnvVariables2Config(rName string) string { +func testAccCanaryConfig_runEnvVariables2(rName string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -894,6 +837,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -911,7 +855,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryBasicConfig(rName string) string { +func testAccCanaryConfig_basic(rName string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { # Must have bucket versioning enabled first @@ -923,6 +867,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -931,7 +876,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryArtifactEncryptionConfig(rName string) string { +func testAccCanaryConfig_artifactEncryption(rName string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -940,6 +885,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.3" + delete_lambda = true artifact_config { s3_encryption { @@ -956,7 +902,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryArtifactEncryptionKMSConfig(rName string) string { +func testAccCanaryConfig_artifactEncryptionKMS(rName string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_kms_key" "test" { description = %[1]q @@ -970,6 +916,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.3" + delete_lambda = true artifact_config { s3_encryption { @@ -987,7 +934,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryRuntimeVersionConfig(rName, version string) string { +func testAccCanaryConfig_runtimeVersion(rName, version string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -996,6 +943,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = %[2]q + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -1006,7 +954,7 @@ resource "aws_synthetics_canary" "test" { `, rName, version)) } -func testAccCanaryZipUpdatedConfig(rName string) string { +func testAccCanaryConfig_zipUpdated(rName string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -1015,6 +963,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest_modified.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -1025,7 +974,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryStartCanaryConfig(rName string, state bool) string { +func testAccCanaryConfig_start(rName string, state bool) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -1035,6 +984,7 @@ resource "aws_synthetics_canary" "test" { zip_file = "test-fixtures/lambdatest.zip" start_canary = %[2]t runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -1045,7 +995,7 @@ resource "aws_synthetics_canary" "test" { `, rName, state)) } -func testAccCanaryStartCanaryZipUpdatedConfig(rName string, state bool) string { +func testAccCanaryConfig_startZipUpdated(rName string, state bool) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -1055,6 +1005,7 @@ resource "aws_synthetics_canary" "test" { zip_file = "test-fixtures/lambdatest_modified.zip" start_canary = %[2]t runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -1065,7 +1016,7 @@ resource "aws_synthetics_canary" "test" { `, rName, state)) } -func testAccCanaryBasicS3CodeConfig(rName string) string { +func testAccCanaryConfig_basicS3Code(rName string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -1076,6 +1027,7 @@ resource "aws_synthetics_canary" "test" { s3_key = aws_s3_object.test.key s3_version = aws_s3_object.test.version_id runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -1150,7 +1102,7 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName)) } -func testAccCanaryVPC1Config(rName string) string { +func testAccCanaryConfig_vpc1(rName string) string { return acctest.ConfigCompose( testAccCanaryBaseConfig(rName), testAccCanaryVPCBaseConfig(rName), @@ -1162,6 +1114,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -1177,7 +1130,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryVPC2Config(rName string) string { +func testAccCanaryConfig_vpc2(rName string) string { return acctest.ConfigCompose( testAccCanaryBaseConfig(rName), testAccCanaryVPCBaseConfig(rName), @@ -1189,6 +1142,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -1204,7 +1158,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryVPC3Config(rName string) string { +func testAccCanaryConfig_vpc3(rName string) string { return acctest.ConfigCompose( testAccCanaryBaseConfig(rName), testAccCanaryVPCBaseConfig(rName), @@ -1216,6 +1170,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -1231,7 +1186,7 @@ resource "aws_synthetics_canary" "test" { `, rName)) } -func testAccCanaryTags1Config(rName, tagKey1, tagValue1 string) string { +func testAccCanaryConfig_tags1(rName, tagKey1, tagValue1 string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -1240,6 +1195,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" @@ -1252,7 +1208,7 @@ resource "aws_synthetics_canary" "test" { `, rName, tagKey1, tagValue1)) } -func testAccCanaryTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccCanaryConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return acctest.ConfigCompose(testAccCanaryBaseConfig(rName), fmt.Sprintf(` resource "aws_synthetics_canary" "test" { name = %[1]q @@ -1261,6 +1217,7 @@ resource "aws_synthetics_canary" "test" { handler = "exports.handler" zip_file = "test-fixtures/lambdatest.zip" runtime_version = "syn-nodejs-puppeteer-3.2" + delete_lambda = true schedule { expression = "rate(0 minute)" diff --git a/internal/service/transfer/enum.go b/internal/service/transfer/enum.go index 880b435fa83..f1a115345d0 100644 --- a/internal/service/transfer/enum.go +++ b/internal/service/transfer/enum.go @@ -4,6 +4,7 @@ const ( SecurityPolicyName2018_11 = "TransferSecurityPolicy-2018-11" SecurityPolicyName2020_06 = "TransferSecurityPolicy-2020-06" SecurityPolicyNameFIPS_2020_06 = "TransferSecurityPolicy-FIPS-2020-06" + SecurityPolicyName2022_03 = "TransferSecurityPolicy-2022-03" ) func SecurityPolicyName_Values() []string { @@ -11,5 +12,6 @@ func SecurityPolicyName_Values() []string { SecurityPolicyName2018_11, SecurityPolicyName2020_06, SecurityPolicyNameFIPS_2020_06, + SecurityPolicyName2022_03, } } diff --git a/internal/service/transfer/server_test.go b/internal/service/transfer/server_test.go index c306e3e7a55..066d91661c5 100644 --- a/internal/service/transfer/server_test.go +++ b/internal/service/transfer/server_test.go @@ -180,6 +180,13 @@ func testAccServer_securityPolicy(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "security_policy_name", "TransferSecurityPolicy-2018-11"), ), }, + { + Config: testAccServerConfig_securityPolicy("TransferSecurityPolicy-2022-03"), + Check: resource.ComposeTestCheckFunc( + testAccCheckServerExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "security_policy_name", "TransferSecurityPolicy-2022-03"), + ), + }, }, }) } diff --git a/internal/service/waf/ipset_test.go b/internal/service/waf/ipset_test.go index 407fb4ad082..57d96b21c18 100644 --- a/internal/service/waf/ipset_test.go +++ b/internal/service/waf/ipset_test.go @@ -220,7 +220,7 @@ func TestAccWAFIPSet_IPSetDescriptors_1000UpdateLimit(t *testing.T) { CheckDestroy: testAccCheckIPSetDestroy, Steps: []resource.TestStep{ { - Config: testAccIPSetConfig_IPSetDescriptors(rName, strings.Join(ipSetDescriptors, "\n")), + Config: testAccIPSetConfig_ipSetDescriptors(rName, strings.Join(ipSetDescriptors, "\n")), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckIPSetExists(resourceName, &ipset), resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.#", "2048"), @@ -505,7 +505,7 @@ resource "aws_waf_ipset" "test" { `, name) } -func testAccIPSetConfig_IPSetDescriptors(name, ipSetDescriptors string) string { +func testAccIPSetConfig_ipSetDescriptors(name, ipSetDescriptors string) string { return fmt.Sprintf(` resource "aws_waf_ipset" "test" { name = %[1]q diff --git a/internal/service/wafregional/byte_match_set.go b/internal/service/wafregional/byte_match_set.go index a2dbe3a4ff1..184001425e3 100644 --- a/internal/service/wafregional/byte_match_set.go +++ b/internal/service/wafregional/byte_match_set.go @@ -106,7 +106,7 @@ func resourceByteMatchSetRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetByteMatchSet(params) - if tfawserr.ErrCodeEquals(err, waf.ErrCodeNonexistentItemException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, waf.ErrCodeNonexistentItemException) { log.Printf("[WARN] WAF Regional Byte Set Match (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -116,7 +116,7 @@ func resourceByteMatchSetRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error getting WAF Regional Byte Match Set (%s): %s", d.Id(), err) } - if resp == nil || resp.ByteMatchSet == nil { + if !d.IsNewResource() && (resp == nil || resp.ByteMatchSet == nil) { log.Printf("[WARN] WAF Regional Byte Set Match (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/internal/service/wafregional/geo_match_set.go b/internal/service/wafregional/geo_match_set.go index da2ed50b396..1bd9207edfa 100644 --- a/internal/service/wafregional/geo_match_set.go +++ b/internal/service/wafregional/geo_match_set.go @@ -53,8 +53,6 @@ func resourceGeoMatchSetCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).WAFRegionalConn region := meta.(*conns.AWSClient).Region - log.Printf("[INFO] Creating WAF Regional Geo Match Set: %s", d.Get("name").(string)) - wr := NewRetryer(conn, region) out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { params := &waf.CreateGeoMatchSetInput{ @@ -65,7 +63,7 @@ func resourceGeoMatchSetCreate(d *schema.ResourceData, meta interface{}) error { return conn.CreateGeoMatchSet(params) }) if err != nil { - return fmt.Errorf("Failed creating WAF Regional Geo Match Set: %s", err) + return fmt.Errorf("Failed creating WAF Regional Geo Match Set: %w", err) } resp := out.(*waf.CreateGeoMatchSetOutput) @@ -76,20 +74,19 @@ func resourceGeoMatchSetCreate(d *schema.ResourceData, meta interface{}) error { func resourceGeoMatchSetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).WAFRegionalConn - log.Printf("[INFO] Reading WAF Regional Geo Match Set: %s", d.Get("name").(string)) + params := &waf.GetGeoMatchSetInput{ GeoMatchSetId: aws.String(d.Id()), } - resp, err := conn.GetGeoMatchSet(params) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { log.Printf("[WARN] WAF WAF Regional Geo Match Set (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("Error getting WAF Regional Geo Match Set (%s): %s", d.Id(), err) + return fmt.Errorf("error getting WAF Regional Geo Match Set (%s): %w", d.Id(), err) } d.Set("name", resp.GeoMatchSet.Name) @@ -107,13 +104,8 @@ func resourceGeoMatchSetUpdate(d *schema.ResourceData, meta interface{}) error { oldConstraints, newConstraints := o.(*schema.Set).List(), n.(*schema.Set).List() err := updateGeoMatchSetResourceWR(d.Id(), oldConstraints, newConstraints, conn, region) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] WAF WAF Regional Geo Match Set (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } if err != nil { - return fmt.Errorf("Failed updating WAF Regional Geo Match Set(%s): %s", d.Id(), err) + return fmt.Errorf("failed updating WAF Regional Geo Match Set (%s): %w", d.Id(), err) } } @@ -129,7 +121,7 @@ func resourceGeoMatchSetDelete(d *schema.ResourceData, meta interface{}) error { noConstraints := []interface{}{} err := updateGeoMatchSetResourceWR(d.Id(), oldConstraints, noConstraints, conn, region) if err != nil { - return fmt.Errorf("Error updating WAF Regional Geo Match Constraint: %s", err) + return fmt.Errorf("error updating WAF Regional Geo Match Constraint (%s): %w", d.Id(), err) } } @@ -146,7 +138,7 @@ func resourceGeoMatchSetDelete(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("Failed deleting WAF Regional Geo Match Set(%s): %s", d.Id(), err) + return fmt.Errorf("failed deleting WAF Regional Geo Match Set (%s): %w", d.Id(), err) } return nil @@ -161,11 +153,10 @@ func updateGeoMatchSetResourceWR(id string, oldConstraints, newConstraints []int Updates: tfwaf.DiffGeoMatchSetConstraints(oldConstraints, newConstraints), } - log.Printf("[INFO] Updating WAF Regional Geo Match Set constraints: %s", req) return conn.UpdateGeoMatchSet(req) }) if err != nil { - return fmt.Errorf("Failed updating WAF Regional Geo Match Set: %s", err) + return fmt.Errorf("failed updating WAF Regional Geo Match Set (%s): %w", id, err) } return nil diff --git a/internal/service/wafregional/ipset.go b/internal/service/wafregional/ipset.go index 7d8f5196048..fd44161eb09 100644 --- a/internal/service/wafregional/ipset.go +++ b/internal/service/wafregional/ipset.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -85,7 +85,7 @@ func resourceIPSetRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetIPSet(params) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "WAFNonexistentItemException" { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { log.Printf("[WARN] WAF IPSet (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/internal/service/wafregional/ipset_test.go b/internal/service/wafregional/ipset_test.go index a306ea5e270..d54f32eafe6 100644 --- a/internal/service/wafregional/ipset_test.go +++ b/internal/service/wafregional/ipset_test.go @@ -192,7 +192,7 @@ func TestAccWAFRegionalIPSet_IPSetDescriptors_1000UpdateLimit(t *testing.T) { CheckDestroy: testAccCheckIPSetDestroy, Steps: []resource.TestStep{ { - Config: testAccIPSetConfig_IPSetDescriptors(ipsetName, strings.Join(ipSetDescriptors, "\n")), + Config: testAccIPSetConfig_ipSetDescriptors(ipsetName, strings.Join(ipSetDescriptors, "\n")), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckIPSetExists(resourceName, &ipset), resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.#", "2048"), @@ -479,7 +479,7 @@ resource "aws_wafregional_ipset" "ipset" { `, name) } -func testAccIPSetConfig_IPSetDescriptors(name, ipSetDescriptors string) string { +func testAccIPSetConfig_ipSetDescriptors(name, ipSetDescriptors string) string { return fmt.Sprintf(` resource "aws_wafregional_ipset" "ipset" { name = "%s" diff --git a/internal/service/wafregional/rate_based_rule.go b/internal/service/wafregional/rate_based_rule.go index 4f3917cfa5a..396e32225b4 100644 --- a/internal/service/wafregional/rate_based_rule.go +++ b/internal/service/wafregional/rate_based_rule.go @@ -105,7 +105,7 @@ func resourceRateBasedRuleCreate(d *schema.ResourceData, meta interface{}) error return conn.CreateRateBasedRule(params) }) if err != nil { - return fmt.Errorf("Error creating WAF Regional Rate Based Rule (%s): %s", d.Id(), err) + return fmt.Errorf("error creating WAF Regional Rate Based Rule (%s): %w", d.Get("name").(string), err) } resp := out.(*waf.CreateRateBasedRuleOutput) d.SetId(aws.StringValue(resp.Rule.RuleId)) @@ -115,7 +115,7 @@ func resourceRateBasedRuleCreate(d *schema.ResourceData, meta interface{}) error noPredicates := []interface{}{} err := updateRateBasedRuleResourceWR(d.Id(), noPredicates, newPredicates, d.Get("rate_limit"), conn, region) if err != nil { - return fmt.Errorf("Error Updating WAF Rate Based Rule: %s", err) + return fmt.Errorf("error updating WAF Regional Rate Based Rule (%s): %w", d.Get("name").(string), err) } } @@ -132,13 +132,13 @@ func resourceRateBasedRuleRead(d *schema.ResourceData, meta interface{}) error { } resp, err := conn.GetRateBasedRule(params) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] WAF Regional Rate Based Rule (%s) not found, removing from state", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + log.Printf("[WARN] WAF Regional Rate Based Rule (%s) not found, removing from state", d.Get("name").(string)) d.SetId("") return nil } if err != nil { - return fmt.Errorf("Error getting WAF Regional Rate Based Rule (%s): %s", d.Id(), err) + return fmt.Errorf("error getting WAF Regional Rate Based Rule (%s): %w", d.Get("name").(string), err) } var predicates []map[string]interface{} @@ -162,7 +162,7 @@ func resourceRateBasedRuleRead(d *schema.ResourceData, meta interface{}) error { tagList, err := ListTags(conn, arn) if err != nil { - return fmt.Errorf("Failed to get WAF Regional Rated Based Rule parameter tags for %s: %s", d.Get("name"), err) + return fmt.Errorf("failed to get WAF Regional Rated Based Rule parameter tags for %s: %w", d.Get("name"), err) } tags := tagList.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -195,13 +195,8 @@ func resourceRateBasedRuleUpdate(d *schema.ResourceData, meta interface{}) error rateLimit := d.Get("rate_limit") err := updateRateBasedRuleResourceWR(d.Id(), oldP, newP, rateLimit, conn, region) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] WAF Regional Rate Based Rule (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } if err != nil { - return fmt.Errorf("Error updating WAF Regional Rate Based Rule Predicates (%s): %s", d.Id(), err) + return fmt.Errorf("error updating WAF Regional Rate Based Rule Predicates (%s): %w", d.Get("name").(string), err) } } @@ -209,7 +204,7 @@ func resourceRateBasedRuleUpdate(d *schema.ResourceData, meta interface{}) error o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating tags: %s", err) + return fmt.Errorf("error updating tags: %w", err) } } @@ -230,7 +225,7 @@ func resourceRateBasedRuleDelete(d *schema.ResourceData, meta interface{}) error return nil } if err != nil { - return fmt.Errorf("Error updating WAF Regional Rate Based Rule Predicates (%s): %s", d.Id(), err) + return fmt.Errorf("error updating WAF Regional Rate Based Rule Predicates (%s): %w", d.Get("name").(string), err) } } @@ -247,7 +242,7 @@ func resourceRateBasedRuleDelete(d *schema.ResourceData, meta interface{}) error return nil } if err != nil { - return fmt.Errorf("Error deleting WAF Regional Rate Based Rule (%s): %s", d.Id(), err) + return fmt.Errorf("error deleting WAF Regional Rate Based Rule (%s): %w", d.Get("name").(string), err) } return nil diff --git a/internal/service/wafregional/regex_match_set.go b/internal/service/wafregional/regex_match_set.go index 5d9d4df08fb..b30b5e3bc4e 100644 --- a/internal/service/wafregional/regex_match_set.go +++ b/internal/service/wafregional/regex_match_set.go @@ -86,7 +86,7 @@ func resourceRegexMatchSetCreate(d *schema.ResourceData, meta interface{}) error return conn.CreateRegexMatchSet(params) }) if err != nil { - return fmt.Errorf("Failed creating WAF Regional Regex Match Set: %s", err) + return fmt.Errorf("Failed creating WAF Regional Regex Match Set: %w", err) } resp := out.(*waf.CreateRegexMatchSetOutput) @@ -98,15 +98,14 @@ func resourceRegexMatchSetCreate(d *schema.ResourceData, meta interface{}) error func resourceRegexMatchSetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).WAFRegionalConn - log.Printf("[INFO] Reading WAF Regional Regex Match Set: %s", d.Get("name").(string)) set, err := FindRegexMatchSetByID(conn, d.Id()) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { log.Printf("[WARN] WAF Regional Regex Match Set (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("Error getting WAF Regional Regex Match Set (%s): %s", d.Id(), err) + return fmt.Errorf("error getting WAF Regional Regex Match Set (%s): %w", d.Id(), err) } d.Set("name", set.Name) @@ -119,19 +118,12 @@ func resourceRegexMatchSetUpdate(d *schema.ResourceData, meta interface{}) error conn := meta.(*conns.AWSClient).WAFRegionalConn region := meta.(*conns.AWSClient).Region - log.Printf("[INFO] Updating WAF Regional Regex Match Set: %s", d.Get("name").(string)) - if d.HasChange("regex_match_tuple") { o, n := d.GetChange("regex_match_tuple") oldT, newT := o.(*schema.Set).List(), n.(*schema.Set).List() err := updateRegexMatchSetResourceWR(d.Id(), oldT, newT, conn, region) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] WAF Regional Rate Based Rule (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } if err != nil { - return fmt.Errorf("Failed updating WAF Regional Regex Match Set(%s): %s", d.Id(), err) + return fmt.Errorf("failed updating WAF Regional Regex Match Set (%s): %w", d.Id(), err) } } diff --git a/internal/service/wafregional/regex_pattern_set.go b/internal/service/wafregional/regex_pattern_set.go index 38d758336a9..d75f44fafbf 100644 --- a/internal/service/wafregional/regex_pattern_set.go +++ b/internal/service/wafregional/regex_pattern_set.go @@ -53,7 +53,7 @@ func resourceRegexPatternSetCreate(d *schema.ResourceData, meta interface{}) err return conn.CreateRegexPatternSet(params) }) if err != nil { - return fmt.Errorf("Failed creating WAF Regional Regex Pattern Set: %s", err) + return fmt.Errorf("failed creating WAF Regional Regex Pattern Set: %w", err) } resp := out.(*waf.CreateRegexPatternSetOutput) @@ -72,13 +72,13 @@ func resourceRegexPatternSetRead(d *schema.ResourceData, meta interface{}) error resp, err := conn.GetRegexPatternSet(params) if err != nil { - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { log.Printf("[WARN] WAF Regional Regex Pattern Set (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return fmt.Errorf("Error getting WAF Regional Regex Pattern Set (%s): %s", d.Id(), err) + return fmt.Errorf("error getting WAF Regional Regex Pattern Set (%s): %w", d.Id(), err) } d.Set("name", resp.RegexPatternSet.Name) @@ -97,11 +97,6 @@ func resourceRegexPatternSetUpdate(d *schema.ResourceData, meta interface{}) err o, n := d.GetChange("regex_pattern_strings") oldPatterns, newPatterns := o.(*schema.Set).List(), n.(*schema.Set).List() err := updateRegexPatternSetPatternStringsWR(d.Id(), oldPatterns, newPatterns, conn, region) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] WAF Regional Rate Based Rule (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } if err != nil { return fmt.Errorf("Failed updating WAF Regional Regex Pattern Set(%s): %s", d.Id(), err) } @@ -122,7 +117,7 @@ func resourceRegexPatternSetDelete(d *schema.ResourceData, meta interface{}) err return nil } if err != nil { - return fmt.Errorf("Failed updating WAF Regional Regex Pattern Set(%s): %s", d.Id(), err) + return fmt.Errorf("failed updating WAF Regional Regex Pattern Set (%s): %w", d.Id(), err) } } @@ -132,11 +127,10 @@ func resourceRegexPatternSetDelete(d *schema.ResourceData, meta interface{}) err ChangeToken: token, RegexPatternSetId: aws.String(d.Id()), } - log.Printf("[INFO] Deleting WAF Regional Regex Pattern Set: %s", req) return conn.DeleteRegexPatternSet(req) }) if err != nil { - return fmt.Errorf("Failed deleting WAF Regional Regex Pattern Set: %s", err) + return fmt.Errorf("failed deleting WAF Regional Regex Pattern Set (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/wafregional/rule.go b/internal/service/wafregional/rule.go index 592b37f2505..ea4ea5e724d 100644 --- a/internal/service/wafregional/rule.go +++ b/internal/service/wafregional/rule.go @@ -120,8 +120,8 @@ func resourceRuleRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetRule(params) if err != nil { - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] WAF Rule (%s) not found, error code (404)", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + log.Printf("[WARN] WAF Rule (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/wafregional/rule_group.go b/internal/service/wafregional/rule_group.go index 9392fa4b9ab..7ecc908e9df 100644 --- a/internal/service/wafregional/rule_group.go +++ b/internal/service/wafregional/rule_group.go @@ -134,7 +134,7 @@ func resourceRuleGroupRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetRuleGroup(params) if err != nil { - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { log.Printf("[WARN] WAF Regional Rule Group (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/internal/service/wafregional/size_constraint_set.go b/internal/service/wafregional/size_constraint_set.go index 90ad78a50cc..9018a782b4e 100644 --- a/internal/service/wafregional/size_constraint_set.go +++ b/internal/service/wafregional/size_constraint_set.go @@ -45,7 +45,7 @@ func resourceSizeConstraintSetCreate(d *schema.ResourceData, meta interface{}) e return conn.CreateSizeConstraintSet(params) }) if err != nil { - return fmt.Errorf("Error creating WAF Regional SizeConstraintSet: %s", err) + return fmt.Errorf("error creating WAF Regional SizeConstraintSet: %w", err) } resp := out.(*waf.CreateSizeConstraintSetOutput) @@ -63,13 +63,13 @@ func resourceSizeConstraintSetRead(d *schema.ResourceData, meta interface{}) err } resp, err := conn.GetSizeConstraintSet(params) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { log.Printf("[WARN] WAF Regional SizeConstraintSet (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("Error getting WAF Regional Size Constraint Set (%s): %s", d.Id(), err) + return fmt.Errorf("error getting WAF Regional Size Constraint Set (%s): %w", d.Id(), err) } d.Set("name", resp.SizeConstraintSet.Name) @@ -86,13 +86,8 @@ func resourceSizeConstraintSetUpdate(d *schema.ResourceData, meta interface{}) e oldConstraints, newConstraints := o.(*schema.Set).List(), n.(*schema.Set).List() err := updateRegionalSizeConstraintSetResource(d.Id(), oldConstraints, newConstraints, client.WAFRegionalConn, client.Region) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] WAF Regional SizeConstraintSet (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } if err != nil { - return fmt.Errorf("Error updating WAF Regional SizeConstraintSet(%s): %s", d.Id(), err) + return fmt.Errorf("error updating WAF Regional SizeConstraintSet(%s): %w", d.Id(), err) } } @@ -112,7 +107,7 @@ func resourceSizeConstraintSetDelete(d *schema.ResourceData, meta interface{}) e return nil } if err != nil { - return fmt.Errorf("Error deleting WAF Regional SizeConstraintSet(%s): %s", d.Id(), err) + return fmt.Errorf("error deleting WAF Regional SizeConstraintSet(%s): %w", d.Id(), err) } } @@ -128,7 +123,7 @@ func resourceSizeConstraintSetDelete(d *schema.ResourceData, meta interface{}) e return nil } if err != nil { - return fmt.Errorf("Error deleting WAF Regional SizeConstraintSet: %s", err) + return fmt.Errorf("error deleting WAF Regional SizeConstraintSet: %w", err) } return nil diff --git a/internal/service/wafregional/sql_injection_match_set.go b/internal/service/wafregional/sql_injection_match_set.go index 43cf70e61e3..98fd6636a0a 100644 --- a/internal/service/wafregional/sql_injection_match_set.go +++ b/internal/service/wafregional/sql_injection_match_set.go @@ -86,7 +86,7 @@ func resourceSQLInjectionMatchSetCreate(d *schema.ResourceData, meta interface{} return conn.CreateSqlInjectionMatchSet(params) }) if err != nil { - return fmt.Errorf("Failed creating Regional WAF SQL Injection Match Set: %s", err) + return fmt.Errorf("failed creating Regional WAF SQL Injection Match Set: %w", err) } resp := out.(*waf.CreateSqlInjectionMatchSetOutput) d.SetId(aws.StringValue(resp.SqlInjectionMatchSet.SqlInjectionMatchSetId)) @@ -102,13 +102,13 @@ func resourceSQLInjectionMatchSetRead(d *schema.ResourceData, meta interface{}) } resp, err := conn.GetSqlInjectionMatchSet(params) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] Regional WAF SQL Injection Match Set (%s) not found, error code (404)", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + log.Printf("[WARN] Regional WAF SQL Injection Match Set (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("Error getting Regional WAF SQL Injection Match Set (%s):%s", d.Id(), err) + return fmt.Errorf("error getting Regional WAF SQL Injection Match Set (%s): %w", d.Id(), err) } d.Set("name", resp.SqlInjectionMatchSet.Name) @@ -126,13 +126,9 @@ func resourceSQLInjectionMatchSetUpdate(d *schema.ResourceData, meta interface{} oldT, newT := o.(*schema.Set).List(), n.(*schema.Set).List() err := updateSQLInjectionMatchSetResourceWR(d.Id(), oldT, newT, conn, region) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] Regional WAF SQL Injection Match Set (%s) not found, error code (404)", d.Id()) - d.SetId("") - return nil - } + if err != nil { - return fmt.Errorf("Error updating Regional WAF SQL Injection Match Set (%s): %s", d.Id(), err) + return fmt.Errorf("error updating Regional WAF SQL Injection Match Set (%s): %w", d.Id(), err) } } @@ -148,11 +144,13 @@ func resourceSQLInjectionMatchSetDelete(d *schema.ResourceData, meta interface{} if len(oldTuples) > 0 { noTuples := []interface{}{} err := updateSQLInjectionMatchSetResourceWR(d.Id(), oldTuples, noTuples, conn, region) + if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { return nil } + if err != nil { - return fmt.Errorf("Error updating Regional WAF SQL Injection Match Set (%s): %s", d.Id(), err) + return fmt.Errorf("error updating Regional WAF SQL Injection Match Set (%s): %w", d.Id(), err) } } @@ -169,7 +167,7 @@ func resourceSQLInjectionMatchSetDelete(d *schema.ResourceData, meta interface{} return nil } if err != nil { - return fmt.Errorf("Failed deleting Regional WAF SQL Injection Match Set (%s): %s", d.Id(), err) + return fmt.Errorf("failed deleting Regional WAF SQL Injection Match Set (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/wafregional/web_acl.go b/internal/service/wafregional/web_acl.go index 5d0ca356d2d..b78e32e8f41 100644 --- a/internal/service/wafregional/web_acl.go +++ b/internal/service/wafregional/web_acl.go @@ -252,16 +252,16 @@ func resourceWebACLRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetWebACL(params) if err != nil { - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { log.Printf("[WARN] WAF Regional ACL (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("unable to read WAF Regional ACL (%s): %w", d.Id(), err) } - if resp == nil || resp.WebACL == nil { + if !d.IsNewResource() && (resp == nil || resp.WebACL == nil) { log.Printf("[WARN] WAF Regional ACL (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/internal/service/wafregional/web_acl_association.go b/internal/service/wafregional/web_acl_association.go index 472f4a9c2ab..4f3d8dfe611 100644 --- a/internal/service/wafregional/web_acl_association.go +++ b/internal/service/wafregional/web_acl_association.go @@ -89,7 +89,7 @@ func resourceWebACLAssociationRead(d *schema.ResourceData, meta interface{}) err output, err := conn.GetWebACLForResource(input) - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { log.Printf("[WARN] WAF Regional Web ACL for resource (%s) not found, removing from state", resourceArn) d.SetId("") return nil @@ -99,7 +99,7 @@ func resourceWebACLAssociationRead(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("error getting WAF Regional Web ACL for resource (%s): %s", resourceArn, err) } - if output == nil || output.WebACLSummary == nil { + if !d.IsNewResource() && (output == nil || output.WebACLSummary == nil) { log.Printf("[WARN] WAF Regional Web ACL for resource (%s) not found, removing from state", resourceArn) d.SetId("") return nil diff --git a/internal/service/wafregional/xss_match_set.go b/internal/service/wafregional/xss_match_set.go index 310172b314b..a50abcf8958 100644 --- a/internal/service/wafregional/xss_match_set.go +++ b/internal/service/wafregional/xss_match_set.go @@ -106,8 +106,8 @@ func resourceXSSMatchSetRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetXssMatchSet(params) if err != nil { - if tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] Regional WAF XSS Match Set (%s) not found, error code (404)", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { + log.Printf("[WARN] Regional WAF XSS Match Set (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/worklink/fleet.go b/internal/service/worklink/fleet.go index 204e6f33654..687964ece24 100644 --- a/internal/service/worklink/fleet.go +++ b/internal/service/worklink/fleet.go @@ -141,7 +141,7 @@ func resourceFleetCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateFleet(input) if err != nil { - return fmt.Errorf("Error creating Worklink Fleet: %s", err) + return fmt.Errorf("Error creating WorkLink Fleet: %w", err) } d.SetId(aws.StringValue(resp.FleetArn)) @@ -172,12 +172,12 @@ func resourceFleetRead(d *schema.ResourceData, meta interface{}) error { FleetArn: aws.String(d.Id()), }) if err != nil { - if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] Worklink Fleet (%s) not found, removing from state", d.Id()) + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { + log.Printf("[WARN] WorkLink Fleet (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return fmt.Errorf("Error describe worklink fleet: %s", err) + return fmt.Errorf("error describing WorkLink Fleet (%s): %w", d.Id(), err) } d.Set("arn", d.Id()) @@ -193,7 +193,7 @@ func resourceFleetRead(d *schema.ResourceData, meta interface{}) error { FleetArn: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("Error describe worklink audit stream configuration: %s", err) + return fmt.Errorf("error describing WorkLink Fleet (%s) audit stream configuration: %w", d.Id(), err) } d.Set("audit_stream_arn", auditStreamConfigurationResp.AuditStreamArn) @@ -201,28 +201,27 @@ func resourceFleetRead(d *schema.ResourceData, meta interface{}) error { FleetArn: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("Error describe worklink company network configuration: %s", err) + return fmt.Errorf("error describing WorkLink Fleet (%s) company network configuration: %w", d.Id(), err) } if err := d.Set("network", flattenNetworkConfigResponse(companyNetworkConfigurationResp)); err != nil { - return fmt.Errorf("Error setting network: %s", err) + return fmt.Errorf("error setting network: %w", err) } identityProviderConfigurationResp, err := conn.DescribeIdentityProviderConfiguration(&worklink.DescribeIdentityProviderConfigurationInput{ FleetArn: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("Error describe worklink company network configuration: %s", err) + return fmt.Errorf("error describing WorkLink Fleet (%s) identity provider configuration: %w", d.Id(), err) } - if err := d.Set("identity_provider", flattenIdentityProviderConfigResponse(identityProviderConfigurationResp)); err != nil { - return fmt.Errorf("Error setting identity_provider: %s", err) + return fmt.Errorf("error setting identity_provider: %w", err) } devicePolicyConfigurationResp, err := conn.DescribeDevicePolicyConfiguration(&worklink.DescribeDevicePolicyConfigurationInput{ FleetArn: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("Error describe worklink device policy configuration: %s", err) + return fmt.Errorf("error describing WorkLink Fleet (%s) device policy configuration: %w", d.Id(), err) } d.Set("device_ca_certificate", strings.TrimSpace(aws.StringValue(devicePolicyConfigurationResp.DeviceCaCertificate))) @@ -244,12 +243,7 @@ func resourceFleetUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChanges("display_name", "optimize_for_end_user_location") { _, err := conn.UpdateFleetMetadata(input) if err != nil { - if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] Worklink Fleet (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error updating worklink fleet: %s", err) + return fmt.Errorf("error updating WorkLink Fleet (%s): %w", d.Id(), err) } } @@ -291,7 +285,7 @@ func resourceFleetDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { return nil } - return fmt.Errorf("Error deleting Worklink Fleet resource share %s: %s", d.Id(), err) + return fmt.Errorf("error deleting WorkLink Fleet resource share (%s): %w", d.Id(), err) } stateConf := &resource.StateChangeConf{ @@ -305,9 +299,7 @@ func resourceFleetDelete(d *schema.ResourceData, meta interface{}) error { _, err := stateConf.WaitForState() if err != nil { - return fmt.Errorf( - "Error waiting for Worklink Fleet (%s) to become deleted: %s", - d.Id(), err) + return fmt.Errorf("error waiting for WorkLink Fleet (%s) to become deleted: %w", d.Id(), err) } return nil @@ -340,14 +332,8 @@ func updateAuditStreamConfiguration(conn *worklink.WorkLink, d *schema.ResourceD return nil } - log.Printf("[DEBUG] Update audit stream configuration option: %#v", input) if _, err := conn.UpdateAuditStreamConfiguration(input); err != nil { - if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] Worklink Fleet (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error Updating Worklink Audit Stream Configuration: %s", err) + return fmt.Errorf("error updating WorkLink Fleet (%s) Audit Stream Configuration: %w", d.Id(), err) } return nil @@ -368,14 +354,8 @@ func updateCompanyNetworkConfiguration(conn *worklink.WorkLink, d *schema.Resour SubnetIds: flex.ExpandStringSet(config["subnet_ids"].(*schema.Set)), VpcId: aws.String(config["vpc_id"].(string)), } - log.Printf("[DEBUG] Update company network configuration option: %#v", input) if _, err := conn.UpdateCompanyNetworkConfiguration(input); err != nil { - if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] Worklink Fleet (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error Updating Worklink Network Configuration: %s", err) + return fmt.Errorf("error updating WorkLink Fleet (%s) Company Network Configuration: %w", d.Id(), err) } } return nil @@ -391,14 +371,8 @@ func updateDevicePolicyConfiguration(conn *worklink.WorkLink, d *schema.Resource return nil } - log.Printf("[DEBUG] Update device policy configuration option: %#v", input) if _, err := conn.UpdateDevicePolicyConfiguration(input); err != nil { - if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] Worklink Fleet (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error Updating Worklink Device Policy Configuration: %s", err) + return fmt.Errorf("error updating WorkLink Fleet (%s) Device Policy Configuration: %w", d.Id(), err) } return nil } @@ -418,14 +392,8 @@ func updateIdentityProviderConfiguration(conn *worklink.WorkLink, d *schema.Reso IdentityProviderType: aws.String(config["type"].(string)), IdentityProviderSamlMetadata: aws.String(config["saml_metadata"].(string)), } - log.Printf("[DEBUG] Update identity provider configuration option: %#v", input) if _, err := conn.UpdateIdentityProviderConfiguration(input); err != nil { - if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] Worklink Fleet (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error Updating Identity Provider Configuration: %s", err) + return fmt.Errorf("error updating WorkLink Fleet (%s) Identity Provider Configuration: %w", d.Id(), err) } } diff --git a/internal/service/worklink/website_certificate_authority_association.go b/internal/service/worklink/website_certificate_authority_association.go index f5103f63975..399bf8b0514 100644 --- a/internal/service/worklink/website_certificate_authority_association.go +++ b/internal/service/worklink/website_certificate_authority_association.go @@ -86,7 +86,7 @@ func resourceWebsiteCertificateAuthorityAssociationRead(d *schema.ResourceData, resp, err := conn.DescribeWebsiteCertificateAuthority(input) if err != nil { - if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { log.Printf("[WARN] WorkLink Website Certificate Authority Association (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/internal/sweep/sweep.go b/internal/sweep/sweep.go index 0bb5d3737a2..c72946b33a2 100644 --- a/internal/sweep/sweep.go +++ b/internal/sweep/sweep.go @@ -45,7 +45,7 @@ func SharedRegionalSweepClientWithContext(ctx context.Context, region string) (i return client, nil } - _, _, err := conns.RequireOneOfEnvVar([]string{conns.EnvVarProfile, conns.EnvVarAccessKeyId, conns.EnvVarContainerCredentialsFullUri}, "credentials for running sweepers") + _, _, err := conns.RequireOneOfEnvVar([]string{conns.EnvVarProfile, conns.EnvVarAccessKeyId, conns.EnvVarContainerCredentialsFullURI}, "credentials for running sweepers") if err != nil { return nil, err } diff --git a/internal/sweep/sweep_test.go b/internal/sweep/sweep_test.go index 7b020ecb148..90dd0369d2d 100644 --- a/internal/sweep/sweep_test.go +++ b/internal/sweep/sweep_test.go @@ -16,6 +16,7 @@ import ( _ "github.com/hashicorp/terraform-provider-aws/internal/service/apigateway" _ "github.com/hashicorp/terraform-provider-aws/internal/service/apigatewayv2" _ "github.com/hashicorp/terraform-provider-aws/internal/service/appconfig" + _ "github.com/hashicorp/terraform-provider-aws/internal/service/applicationinsights" _ "github.com/hashicorp/terraform-provider-aws/internal/service/appmesh" _ "github.com/hashicorp/terraform-provider-aws/internal/service/apprunner" _ "github.com/hashicorp/terraform-provider-aws/internal/service/appstream" @@ -65,6 +66,7 @@ import ( _ "github.com/hashicorp/terraform-provider-aws/internal/service/elbv2" _ "github.com/hashicorp/terraform-provider-aws/internal/service/emr" _ "github.com/hashicorp/terraform-provider-aws/internal/service/emrcontainers" + _ "github.com/hashicorp/terraform-provider-aws/internal/service/emrserverless" _ "github.com/hashicorp/terraform-provider-aws/internal/service/events" _ "github.com/hashicorp/terraform-provider-aws/internal/service/firehose" _ "github.com/hashicorp/terraform-provider-aws/internal/service/fsx" @@ -87,6 +89,7 @@ import ( _ "github.com/hashicorp/terraform-provider-aws/internal/service/lexmodels" _ "github.com/hashicorp/terraform-provider-aws/internal/service/licensemanager" _ "github.com/hashicorp/terraform-provider-aws/internal/service/lightsail" + _ "github.com/hashicorp/terraform-provider-aws/internal/service/location" _ "github.com/hashicorp/terraform-provider-aws/internal/service/logs" _ "github.com/hashicorp/terraform-provider-aws/internal/service/memorydb" _ "github.com/hashicorp/terraform-provider-aws/internal/service/mq" @@ -104,6 +107,7 @@ import ( _ "github.com/hashicorp/terraform-provider-aws/internal/service/route53" _ "github.com/hashicorp/terraform-provider-aws/internal/service/route53recoverycontrolconfig" _ "github.com/hashicorp/terraform-provider-aws/internal/service/route53resolver" + _ "github.com/hashicorp/terraform-provider-aws/internal/service/rum" _ "github.com/hashicorp/terraform-provider-aws/internal/service/s3" _ "github.com/hashicorp/terraform-provider-aws/internal/service/s3control" _ "github.com/hashicorp/terraform-provider-aws/internal/service/sagemaker" diff --git a/internal/verify/validate.go b/internal/verify/validate.go index 5adfe2f2f49..a6705480a9a 100644 --- a/internal/verify/validate.go +++ b/internal/verify/validate.go @@ -350,6 +350,18 @@ var ValidStringDateOrPositiveInt = validation.Any( validation.StringMatch(regexp.MustCompile(`^\d+$`), "must be a positive integer value"), ) +func ValidDuration(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + duration, err := time.ParseDuration(value) + if err != nil { + errors = append(errors, fmt.Errorf("%q cannot be parsed as a duration: %s", k, err)) + } + if duration < 0 { + errors = append(errors, fmt.Errorf("%q must be greater than zero", k)) + } + return +} + // FloatGreaterThan returns a SchemaValidateFunc which tests if the provided value // is of type float and is greater than threshold. func FloatGreaterThan(threshold float64) schema.SchemaValidateFunc { diff --git a/internal/verify/verify.go b/internal/verify/verify.go index 875eb77e983..f3e21ee0196 100644 --- a/internal/verify/verify.go +++ b/internal/verify/verify.go @@ -1,6 +1,7 @@ package verify import ( + "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "gopkg.in/yaml.v2" ) @@ -52,7 +53,11 @@ const ( ErrCodeValidationException = "ValidationException" ) -func CheckISOErrorTagsUnsupported(err error) bool { +func CheckISOErrorTagsUnsupported(partition string, err error) bool { + if partition == endpoints.AwsPartitionID { + return false + } + if tfawserr.ErrCodeContains(err, ErrCodeAccessDenied) { return true } diff --git a/names/caps.csv b/names/caps.csv new file mode 100644 index 00000000000..3737a463e85 --- /dev/null +++ b/names/caps.csv @@ -0,0 +1,125 @@ +Wrong,Right +Acl,ACL +Acm,ACM +Acmpca,ACMPCA +AcmPca,ACMPCA +Ami,AMI +Api,API +ApiGateway,APIGateway +Appconfig,AppConfig +Appmesh,AppMesh +Appsync,AppSync +Arn,ARN +Asg,ASG +Asn,ASN +Autoscaling,AutoScaling +Bgp,BGP +Byoip,BYOIP +Cidr,CIDR +Cloudformation,CloudFormation +Cloudfront,CloudFront +Cloudwatch,CloudWatch +Cmk,CMK +Cname,CNAME +Coip,CoIP +Cpu,CPU +Css,CSS +Csv,CSV +Dax,DAX +Db,DB +Dhcp,DHCP +Dkim,DKIM +Dlm,DLM +Dms,DMS +Dns,DNS +Dnssec,DNSSEC +DocDb,DocDB +Docdb,DocDB +Dynamodb,DynamoDB +DynamoDb,DynamoDB +Ebs,EBS +Ec2,EC2 +Ecmp,ECMP +Ecr,ECR +Ecs,ECS +Efs,EFS +Eip,EIP +Eks,EKS +Elasticache,ElastiCache +ElasticSearch,Elasticsearch +Elb,ELB +Emr,EMR +Fifo,FIFO +Fms,FMS +Fqdns,FQDNS +Fsx,FSx +FSX,FSx +Gamelift,GameLift +Gcm,GCM +Gp2,GP2 +Gp3,GP3 +Graphql,GraphQL +Grpc,GRPC +Guardduty,GuardDuty +Haproxy,HAProxy +Hsm,HSM +Http,HTTP +Https,HTTPS +Hvm,HVM +Iam,IAM +Iot,IoT +Ip,IP +Ipam,IPAM +Ipset,IPSet +Iscsi,iSCSI +Jdbc,JDBC +Json,JSON +Kms,KMS +Mfa,MFA +Msk,MSK +Mwaa,MWAA +Mysql,MySQL +Nfs,NFS +Oauth,OAuth +Oidc,OIDC +Opsworks,OpsWorks +Php,PHP +Pitr,PITR +Posix,POSIX +Precheck,PreCheck +Qldb,QLDB +Rabbitmq,RabbitMQ +Rds,RDS +Rfc,RFC +Sagemaker,SageMaker +Sasl,SASL +Sfn,SFN +Smb,SMB +Sms,SMS +Smtp,SMTP +Sns,SNS +Sql,SQL +Sqs,SQS +Ssh,SSH +Ssl,SSL +Ssm,SSM +Sso,SSO +Sts,STS +Swf,SWF +Tcp,TCP +Tls,TLS +Ttl,TTL +Uri,URI +Url,URL +Vgw,VGW +Voip,VoIP +Vpc,VPC +Vpn,VPN +Waf,WAF +Wafv2,WAFV2 +Workgroup,WorkGroup +Worklink,WorkLink +Workspaces,WorkSpaces +Xray,XRay +Xss,XSS +Yaml,YAML \ No newline at end of file diff --git a/names/caps.md b/names/caps.md new file mode 100644 index 00000000000..484a11b6f89 --- /dev/null +++ b/names/caps.md @@ -0,0 +1,152 @@ +# Caps List + + +In Terraform AWS Provider code, we have two guiding principles for capitalization in function, constant, and variable names: + +1. We use [Go-idiomatic MixedCaps](https://go.dev/doc/effective_go#mixed-caps), with [idiomatic treatment of initialisms](https://github.com/golang/go/wiki/CodeReviewComments#initialisms). +2. We follow AWS's preferred capitalization for service names (_e.g._, ["SageMaker"](https://aws.amazon.com/sagemaker/) rather than "Sagemaker"). + +For _principle 1_, the [golang/go Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments#initialisms) are instructive: + +> Words in names that are initialisms or acronyms (e.g. "URL" or "NATO") have a consistent case. For example, "URL" should appear as "URL" or "url" (as in "urlPony", or "URLPony"), never as "Url". As an example: ServeHTTP not ServeHttp. For identifiers with multiple initialized "words", use for example "xmlHTTPRequest" or "XMLHTTPRequest". + +> This rule also applies to "ID" when it is short for "identifier" (which is pretty much all cases when it's not the "id" as in "ego", "superego"), so write "appID" instead of "appId". + +For _principle 2_, take a look at the AWS website for a service to see the capitalization that AWS prefers. For example, [GameLift](https://aws.amazon.com/gamelift/) rather than "Gamelift". + +To help enforce these principles, we are using [semgrep](https://semgrep.dev/) rules. Below, you will find a list of the specific caps cases we look for currently. This list is generated from the [same source](caps.csv) as the semgrep rules. + +**NOTE:** Please do NOT add "Id" to the list. Use "ID" or "id", never "Id", but we have found linter enforcement of this initialism to be too error prone because of the number of false positives for "Id" (_e.g._, "Identifier"). + +**NOTE:** Capitalization rules are all found in the ".semgrep-service-name0.yml" configuration file are named `-in-func-name`, `-in-var-name`, or `-in-const-name`, where `Test#` comes from the table below. + +**NOTE:** The `Test#` order is _wonky_ because we need to match on longer names first. In the future, with an option to automatically correct problems, fixing the longest possible initialism first is important (_e.g._, `HTTPS` needs to be fixed before `HTTP` to avoid something like `HTTPs`). + +The caps enforced are as follows: + +| Wrong | Right | Test# | +| --- | --- | --- | +| Acl | ACL | caps1 | +| Acm | ACM | caps1 | +| AcmPca | ACMPCA | caps0 | +| Acmpca | ACMPCA | caps0 | +| Ami | AMI | caps1 | +| Api | API | caps1 | +| ApiGateway | APIGateway | caps0 | +| Appconfig | AppConfig | caps0 | +| Appmesh | AppMesh | caps0 | +| Appsync | AppSync | caps0 | +| Arn | ARN | caps2 | +| Asg | ASG | caps2 | +| Asn | ASN | caps2 | +| Autoscaling | AutoScaling | caps0 | +| Bgp | BGP | caps2 | +| Byoip | BYOIP | caps0 | +| Cidr | CIDR | caps1 | +| Cloudformation | CloudFormation | caps0 | +| Cloudfront | CloudFront | caps0 | +| Cloudwatch | CloudWatch | caps0 | +| Cmk | CMK | caps2 | +| Cname | CNAME | caps0 | +| Coip | CoIP | caps1 | +| Cpu | CPU | caps2 | +| Css | CSS | caps2 | +| Csv | CSV | caps2 | +| Dax | DAX | caps2 | +| Db | DB | caps3 | +| Dhcp | DHCP | caps1 | +| Dkim | DKIM | caps1 | +| Dlm | DLM | caps2 | +| Dms | DMS | caps2 | +| Dns | DNS | caps2 | +| Dnssec | DNSSEC | caps0 | +| DocDb | DocDB | caps0 | +| Docdb | DocDB | caps0 | +| DynamoDb | DynamoDB | caps0 | +| Dynamodb | DynamoDB | caps0 | +| Ebs | EBS | caps2 | +| Ec2 | EC2 | caps2 | +| Ecmp | ECMP | caps1 | +| Ecr | ECR | caps2 | +| Ecs | ECS | caps2 | +| Efs | EFS | caps2 | +| Eip | EIP | caps2 | +| Eks | EKS | caps2 | +| Elasticache | ElastiCache | caps0 | +| ElasticSearch | Elasticsearch | caps0 | +| Elb | ELB | caps2 | +| Emr | EMR | caps2 | +| Fifo | FIFO | caps1 | +| Fms | FMS | caps2 | +| Fqdns | FQDNS | caps0 | +| FSX | FSx | caps2 | +| Fsx | FSx | caps2 | +| Gamelift | GameLift | caps0 | +| Gcm | GCM | caps2 | +| Gp2 | GP2 | caps2 | +| Gp3 | GP3 | caps2 | +| Graphql | GraphQL | caps0 | +| Grpc | GRPC | caps1 | +| Guardduty | GuardDuty | caps0 | +| Haproxy | HAProxy | caps0 | +| Hsm | HSM | caps2 | +| Http | HTTP | caps1 | +| Https | HTTPS | caps1 | +| Hvm | HVM | caps2 | +| Iam | IAM | caps2 | +| Iot | IoT | caps2 | +| Ip | IP | caps3 | +| Ipam | IPAM | caps1 | +| Ipset | IPSet | caps1 | +| Iscsi | iSCSI | caps1 | +| Jdbc | JDBC | caps1 | +| Json | JSON | caps1 | +| Kms | KMS | caps3 | +| Mfa | MFA | caps3 | +| Msk | MSK | caps3 | +| Mwaa | MWAA | caps1 | +| Mysql | MySQL | caps1 | +| Nfs | NFS | caps3 | +| Oauth | OAuth | caps1 | +| Oidc | OIDC | caps1 | +| Opsworks | OpsWorks | caps0 | +| Php | PHP | caps3 | +| Pitr | PITR | caps1 | +| Posix | POSIX | caps1 | +| Precheck | PreCheck | caps0 | +| Qldb | QLDB | caps1 | +| Rabbitmq | RabbitMQ | caps0 | +| Rds | RDS | caps3 | +| Rfc | RFC | caps3 | +| Sagemaker | SageMaker | caps0 | +| Sasl | SASL | caps1 | +| Sfn | SFN | caps3 | +| Smb | SMB | caps3 | +| Sms | SMS | caps3 | +| Smtp | SMTP | caps1 | +| Sns | SNS | caps3 | +| Sql | SQL | caps3 | +| Sqs | SQS | caps3 | +| Ssh | SSH | caps3 | +| Ssl | SSL | caps3 | +| Ssm | SSM | caps3 | +| Sso | SSO | caps3 | +| Sts | STS | caps3 | +| Swf | SWF | caps3 | +| Tcp | TCP | caps3 | +| Tls | TLS | caps3 | +| Ttl | TTL | caps3 | +| Uri | URI | caps3 | +| Url | URL | caps3 | +| Vgw | VGW | caps3 | +| Voip | VoIP | caps1 | +| Vpc | VPC | caps3 | +| Vpn | VPN | caps3 | +| Waf | WAF | caps3 | +| Wafv2 | WAFV2 | caps1 | +| Workgroup | WorkGroup | caps0 | +| Worklink | WorkLink | caps0 | +| Workspaces | WorkSpaces | caps0 | +| Xray | XRay | caps1 | +| Xss | XSS | caps3 | +| Yaml | YAML | caps1 | diff --git a/names/consts_gen.go b/names/consts_gen.go index 220a71ea6f5..a93087e5346 100644 --- a/names/consts_gen.go +++ b/names/consts_gen.go @@ -101,6 +101,7 @@ const ( ELBV2 = "elbv2" EMR = "emr" EMRContainers = "emrcontainers" + EMRServerless = "emrserverless" ElastiCache = "elasticache" ElasticBeanstalk = "elasticbeanstalk" ElasticInference = "elasticinference" diff --git a/names/names.go b/names/names.go index 93d721a4ccb..54daa453c36 100644 --- a/names/names.go +++ b/names/names.go @@ -23,6 +23,7 @@ import ( // This "should" be defined by the AWS Go SDK v2, but currently isn't. const ( + KendraEndpointID = "kendra" Route53DomainsEndpointID = "route53domains" ) diff --git a/names/names_data.csv b/names/names_data.csv index 40b8b20fb34..7b939310dc0 100644 --- a/names/names_data.csv +++ b/names/names_data.csv @@ -64,7 +64,7 @@ cloudtrail,cloudtrail,cloudtrail,cloudtrail,,cloudtrail,,,CloudTrail,CloudTrail, cloudwatch,cloudwatch,cloudwatch,cloudwatch,,cloudwatch,,,CloudWatch,CloudWatch,,1,aws_cloudwatch_(?!(event_|log_|query_)),aws_cloudwatch_,,cloudwatch_dashboard;cloudwatch_metric_;cloudwatch_composite_,CloudWatch,Amazon,,,,, application-insights,applicationinsights,applicationinsights,applicationinsights,,applicationinsights,,,ApplicationInsights,ApplicationInsights,,1,,aws_applicationinsights_,,applicationinsights_,CloudWatch Application Insights,Amazon,,,,, evidently,evidently,cloudwatchevidently,evidently,,evidently,,cloudwatchevidently,Evidently,CloudWatchEvidently,,1,,aws_evidently_,,evidently_,CloudWatch Evidently,Amazon,,,,, -logs,logs,cloudwatchlogs,cloudwatchlogs,,logs,,cloudwatchlogs,Logs,CloudWatchLogs,,1,aws_cloudwatch_(log_|query_),aws_logs_,,cloudwatch_log_;cloudwatch_query_,CloudWatch Logs,Amazon,,,,, +logs,logs,cloudwatchlogs,cloudwatchlogs,,logs,,cloudwatchlog;cloudwatchlogs,Logs,CloudWatchLogs,,1,aws_cloudwatch_(log_|query_),aws_logs_,,cloudwatch_log_;cloudwatch_query_,CloudWatch Logs,Amazon,,,,, rum,rum,cloudwatchrum,rum,,rum,,cloudwatchrum,RUM,CloudWatchRUM,,1,,aws_rum_,,rum_,CloudWatch RUM,Amazon,,,,, synthetics,synthetics,synthetics,synthetics,,synthetics,,,Synthetics,Synthetics,,1,,aws_synthetics_,,synthetics_,CloudWatch Synthetics,Amazon,,,,, codeartifact,codeartifact,codeartifact,codeartifact,,codeartifact,,,CodeArtifact,CodeArtifact,,1,,aws_codeartifact_,,codeartifact_,CodeArtifact,AWS,,,,, @@ -78,7 +78,7 @@ codestar,codestar,codestar,codestar,,codestar,,,CodeStar,CodeStar,,1,,aws_codest codestar-connections,codestarconnections,codestarconnections,codestarconnections,,codestarconnections,,,CodeStarConnections,CodeStarConnections,,1,,aws_codestarconnections_,,codestarconnections_,CodeStar Connections,AWS,,,,, codestar-notifications,codestarnotifications,codestarnotifications,codestarnotifications,,codestarnotifications,,,CodeStarNotifications,CodeStarNotifications,,1,,aws_codestarnotifications_,,codestarnotifications_,CodeStar Notifications,AWS,,,,, cognito-identity,cognitoidentity,cognitoidentity,cognitoidentity,,cognitoidentity,,,CognitoIdentity,CognitoIdentity,,1,aws_cognito_identity_(?!provider),aws_cognitoidentity_,,cognito_identity_pool,Cognito Identity,Amazon,,,,, -cognito-idp,cognitoidp,cognitoidentityprovider,cognitoidentityprovider,,cognitoidp,,cognitoidentityprovider,CognitoIDP,CognitoIdentityProvider,,1,aws_cognito_(identity_provider|resource|user),aws_cognitoidp_,,cognito_identity_provider;cognito_resource_;cognito_user,Cognito IDP (Identity Provider),Amazon,,,,, +cognito-idp,cognitoidp,cognitoidentityprovider,cognitoidentityprovider,,cognitoidp,,cognitoidentityprovider,CognitoIDP,CognitoIdentityProvider,,1,aws_cognito_(identity_provider|resource|user|risk),aws_cognitoidp_,,cognito_identity_provider;cognito_resource_;cognito_user;cognito_risk,Cognito IDP (Identity Provider),Amazon,,,,, cognito-sync,cognitosync,cognitosync,cognitosync,,cognitosync,,,CognitoSync,CognitoSync,,1,,aws_cognitosync_,,cognitosync_,Cognito Sync,Amazon,,,,, comprehend,comprehend,comprehend,comprehend,,comprehend,,,Comprehend,Comprehend,,1,,aws_comprehend_,,comprehend_,Comprehend,Amazon,,,,, comprehendmedical,comprehendmedical,comprehendmedical,comprehendmedical,,comprehendmedical,,,ComprehendMedical,ComprehendMedical,,1,,aws_comprehendmedical_,,comprehendmedical_,Comprehend Medical,Amazon,,,,, @@ -115,7 +115,7 @@ ds,ds,directoryservice,directoryservice,,ds,,directoryservice,DS,DirectoryServic dynamodb,dynamodb,dynamodb,dynamodb,,dynamodb,,,DynamoDB,DynamoDB,,1,,aws_dynamodb_,,dynamodb_,DynamoDB,Amazon,,,AWS_DYNAMODB_ENDPOINT,TF_AWS_DYNAMODB_ENDPOINT, dax,dax,dax,dax,,dax,,,DAX,DAX,,1,,aws_dax_,,dax_,DynamoDB Accelerator (DAX),Amazon,,,,, dynamodbstreams,dynamodbstreams,dynamodbstreams,dynamodbstreams,,dynamodbstreams,,,DynamoDBStreams,DynamoDBStreams,,1,,aws_dynamodbstreams_,,dynamodbstreams_,DynamoDB Streams,Amazon,,,,, -,,,,,ec2ebs,ec2,,,,,,aws_(ebs_|volume_attach|snapshot_create),aws_ec2ebs_,ebs_,ebs_;volume_attachment;snapshot_,EBS (EC2),Amazon,x,x,,,Part of EC2 +,,,,,ec2ebs,ec2,,EC2EBS,,,,aws_(ebs_|volume_attach|snapshot_create),aws_ec2ebs_,ebs_,ebs_;volume_attachment;snapshot_,EBS (EC2),Amazon,x,x,,,Part of EC2 ebs,ebs,ebs,ebs,,ebs,,,EBS,EBS,,1,,aws_ebs_,,changewhenimplemented,EBS (Elastic Block Store),Amazon,,,,, ec2,ec2,ec2,ec2,,ec2,ec2,,EC2,EC2,,1,aws_(ami|availability_zone|ec2_(availability|capacity|fleet|host|instance|serial|spot|tag)|eip|instance|key_pair|launch_template|placement_group|spot),aws_ec2_,ec2_,ami;availability_zone;ec2_availability_;ec2_capacity_;ec2_fleet;ec2_host;ec2_instance_;ec2_serial_;ec2_spot_;ec2_tag;eip;instance;key_pair;launch_template;placement_group;spot_,EC2 (Elastic Compute Cloud),Amazon,,,,, imagebuilder,imagebuilder,imagebuilder,imagebuilder,,imagebuilder,,,ImageBuilder,Imagebuilder,,1,,aws_imagebuilder_,,imagebuilder_,EC2 Image Builder,Amazon,,,,, @@ -125,7 +125,7 @@ ecr-public,ecrpublic,ecrpublic,ecrpublic,,ecrpublic,,,ECRPublic,ECRPublic,,1,,aw ecs,ecs,ecs,ecs,,ecs,,,ECS,ECS,,1,,aws_ecs_,,ecs_,ECS (Elastic Container),Amazon,,,,, efs,efs,efs,efs,,efs,,,EFS,EFS,,1,,aws_efs_,,efs_,EFS (Elastic File System),Amazon,,,,, eks,eks,eks,eks,,eks,,,EKS,EKS,,1,,aws_eks_,,eks_,EKS (Elastic Kubernetes),Amazon,,,,, -elasticbeanstalk,elasticbeanstalk,elasticbeanstalk,elasticbeanstalk,,elasticbeanstalk,,,ElasticBeanstalk,ElasticBeanstalk,,1,aws_elastic_beanstalk_,aws_elasticbeanstalk_,,elastic_beanstalk_,Elastic Beanstalk,AWS,,,,, +elasticbeanstalk,elasticbeanstalk,elasticbeanstalk,elasticbeanstalk,,elasticbeanstalk,,beanstalk,ElasticBeanstalk,ElasticBeanstalk,,1,aws_elastic_beanstalk_,aws_elasticbeanstalk_,,elastic_beanstalk_,Elastic Beanstalk,AWS,,,,, elastic-inference,elasticinference,elasticinference,elasticinference,,elasticinference,,,ElasticInference,ElasticInference,,1,,aws_elasticinference_,,elasticinference_,Elastic Inference,Amazon,,,,, elastictranscoder,elastictranscoder,elastictranscoder,elastictranscoder,,elastictranscoder,,,ElasticTranscoder,ElasticTranscoder,,1,,aws_elastictranscoder_,,elastictranscoder_,Elastic Transcoder,Amazon,,,,, elasticache,elasticache,elasticache,elasticache,,elasticache,,,ElastiCache,ElastiCache,,1,,aws_elasticache_,,elasticache_,ElastiCache,Amazon,,,,, @@ -143,6 +143,7 @@ mediatailor,mediatailor,mediatailor,mediatailor,,mediatailor,,,MediaTailor,Media ,,,,,,,,,,,,,,,,Elemental On-Premises,AWS,x,,,,No SDK support emr,emr,emr,emr,,emr,,,EMR,EMR,,1,,aws_emr_,,emr_,EMR,Amazon,,,,, emr-containers,emrcontainers,emrcontainers,emrcontainers,,emrcontainers,,,EMRContainers,EMRContainers,,1,,aws_emrcontainers_,,emrcontainers_,EMR Containers,Amazon,,,,, +emr-serverless,emrserverless,emrserverless,emrserverless,,emrserverless,,,EMRServerless,EMRServerless,,1,,aws_emrserverless_,,emrserverless_,EMR Serverless,Amazon,,,,, ,,,,,,,,,,,,,,,,End-of-Support Migration Program (EMP) for Windows Server,AWS,x,,,,No SDK support events,events,eventbridge,eventbridge,,events,,eventbridge;cloudwatchevents,Events,EventBridge,,1,aws_cloudwatch_event_,aws_events_,,cloudwatch_event_,EventBridge,Amazon,,,,, schemas,schemas,schemas,schemas,,schemas,,,Schemas,Schemas,,1,,aws_schemas_,,schemas_,EventBridge Schemas,Amazon,,,,, @@ -191,7 +192,7 @@ iottwinmaker,iottwinmaker,iottwinmaker,iottwinmaker,,iottwinmaker,,,IoTTwinMaker iotwireless,iotwireless,iotwireless,iotwireless,,iotwireless,,,IoTWireless,IoTWireless,,1,,aws_iotwireless_,,iotwireless_,IoT Wireless,AWS,,,,, ,,,,,,,,,,,,,,,,IQ,AWS,x,,,,No SDK support ivs,ivs,ivs,ivs,,ivs,,,IVS,IVS,,1,,aws_ivs_,,ivs_,IVS (Interactive Video),Amazon,,,,, -kendra,kendra,kendra,kendra,,kendra,,,Kendra,Kendra,,1,,aws_kendra_,,kendra_,Kendra,Amazon,,,,, +kendra,kendra,kendra,kendra,,kendra,,,Kendra,Kendra,x,2,,aws_kendra_,,kendra_,Kendra,Amazon,,,,, keyspaces,keyspaces,keyspaces,,,keyspaces,,,Keyspaces,Keyspaces,,1,,aws_keyspaces_,,keyspaces_,Keyspaces (for Apache Cassandra),Amazon,,,,, kinesis,kinesis,kinesis,kinesis,,kinesis,,,Kinesis,Kinesis,,1,aws_kinesis_stream,aws_kinesis_,,kinesis_stream,Kinesis,Amazon,,,,, kinesisanalytics,kinesisanalytics,kinesisanalytics,kinesisanalytics,,kinesisanalytics,,,KinesisAnalytics,KinesisAnalytics,,1,aws_kinesis_analytics_,aws_kinesisanalytics_,,kinesis_analytics_,Kinesis Analytics,Amazon,,,,, @@ -205,7 +206,7 @@ kms,kms,kms,kms,,kms,,,KMS,KMS,,1,,aws_kms_,,kms_,KMS (Key Management),AWS,,,,, lakeformation,lakeformation,lakeformation,lakeformation,,lakeformation,,,LakeFormation,LakeFormation,,1,,aws_lakeformation_,,lakeformation_,Lake Formation,AWS,,,,, lambda,lambda,lambda,lambda,,lambda,,,Lambda,Lambda,,1,,aws_lambda_,,lambda_,Lambda,AWS,,,,, ,,,,,,,,,,,,,,,,Launch Wizard,AWS,x,,,,No SDK support -lex-models,lexmodels,lexmodelbuildingservice,lexmodelbuildingservice,,lexmodels,,lexmodelbuilding;lexmodelbuildingservice,LexModels,LexModelBuildingService,,1,aws_lex_,aws_lexmodels_,,lex_,Lex Model Building,Amazon,,,,, +lex-models,lexmodels,lexmodelbuildingservice,lexmodelbuildingservice,,lexmodels,,lexmodelbuilding;lexmodelbuildingservice;lex,LexModels,LexModelBuildingService,,1,aws_lex_,aws_lexmodels_,,lex_,Lex Model Building,Amazon,,,,, lexv2-models,lexv2models,lexmodelsv2,lexmodelsv2,,lexmodelsv2,,lexv2models,LexModelsV2,LexModelsV2,,1,,aws_lexmodelsv2_,,lexmodelsv2_,Lex Models V2,Amazon,,,,, lex-runtime,lexruntime,lexruntimeservice,lexruntimeservice,,lexruntime,,lexruntimeservice,LexRuntime,LexRuntimeService,,1,,aws_lexruntime_,,lexruntime_,Lex Runtime,Amazon,,,,, lexv2-runtime,lexv2runtime,lexruntimev2,lexruntimev2,,lexruntimev2,,lexv2runtime,LexRuntimeV2,LexRuntimeV2,,1,,aws_lexruntimev2_,,lexruntimev2_,Lex Runtime V2,Amazon,,,,, @@ -222,7 +223,7 @@ macie,macie,macie,macie,,macie,,,Macie,Macie,,1,,aws_macie_,,macie_,Macie Classi ,,,,,,,,,,,,,,,,Mainframe Modernization,AWS,x,,,,No SDK support managedblockchain,managedblockchain,managedblockchain,managedblockchain,,managedblockchain,,,ManagedBlockchain,ManagedBlockchain,,1,,aws_managedblockchain_,,managedblockchain_,Managed Blockchain,Amazon,,,,, grafana,grafana,managedgrafana,grafana,,grafana,,managedgrafana;amg,Grafana,ManagedGrafana,,1,,aws_grafana_,,grafana_,Managed Grafana,Amazon,,,,, -kafka,kafka,kafka,kafka,,kafka,,,Kafka,Kafka,,1,aws_msk_,aws_kafka_,,msk_,Managed Streaming for Kafka,Amazon,,,,, +kafka,kafka,kafka,kafka,,kafka,,msk,Kafka,Kafka,,1,aws_msk_,aws_kafka_,,msk_,Managed Streaming for Kafka,Amazon,,,,, kafkaconnect,kafkaconnect,kafkaconnect,kafkaconnect,,kafkaconnect,,,KafkaConnect,KafkaConnect,,1,aws_mskconnect_,aws_kafkaconnect_,,mskconnect_,Managed Streaming for Kafka Connect,Amazon,,,,, ,,,,,,,,,,,,,,,,Management Console,AWS,x,,,,No SDK support marketplace-catalog,marketplacecatalog,marketplacecatalog,marketplacecatalog,,marketplacecatalog,,,MarketplaceCatalog,MarketplaceCatalog,,1,,aws_marketplacecatalog_,,marketplace_catalog_,Marketplace Catalog,AWS,,,,, @@ -230,7 +231,7 @@ marketplacecommerceanalytics,marketplacecommerceanalytics,marketplacecommerceana marketplace-entitlement,marketplaceentitlement,marketplaceentitlementservice,marketplaceentitlementservice,,marketplaceentitlement,,marketplaceentitlementservice,MarketplaceEntitlement,MarketplaceEntitlementService,,1,,aws_marketplaceentitlement_,,marketplaceentitlement_,Marketplace Entitlement,AWS,,,,, meteringmarketplace,meteringmarketplace,marketplacemetering,marketplacemetering,,marketplacemetering,,meteringmarketplace,MarketplaceMetering,MarketplaceMetering,,1,,aws_marketplacemetering_,,marketplacemetering_,Marketplace Metering,AWS,,,,, memorydb,memorydb,memorydb,memorydb,,memorydb,,,MemoryDB,MemoryDB,,1,,aws_memorydb_,,memorydb_,MemoryDB for Redis,Amazon,,,,, -,,,,,meta,,,,,,,aws_(arn|billing_service_account|default_tags|ip_ranges|partition|regions?|service)$,aws_meta_,,arn;ip_ranges;billing_service_account;default_tags;partition;region;service\.,Meta Data Sources,,x,x,,,Not an AWS service (metadata) +,,,,,meta,,,Meta,,,,aws_(arn|billing_service_account|default_tags|ip_ranges|partition|regions?|service)$,aws_meta_,,arn;ip_ranges;billing_service_account;default_tags;partition;region;service\.,Meta Data Sources,,x,x,,,Not an AWS service (metadata) mgh,mgh,migrationhub,migrationhub,,mgh,,migrationhub,MgH,MigrationHub,,1,,aws_mgh_,,mgh_,MgH (Migration Hub),AWS,,,,, ,,,,,,,,,,,,,,,,Microservice Extractor for .NET,AWS,x,,,,No SDK support migrationhub-config,migrationhubconfig,migrationhubconfig,migrationhubconfig,,migrationhubconfig,,,MigrationHubConfig,MigrationHubConfig,,1,,aws_migrationhubconfig_,,migrationhubconfig_,Migration Hub Config,AWS,,,,, @@ -254,7 +255,7 @@ opsworks,opsworks,opsworks,opsworks,,opsworks,,,OpsWorks,OpsWorks,,1,,aws_opswor opsworks-cm,opsworkscm,opsworkscm,opsworkscm,,opsworkscm,,,OpsWorksCM,OpsWorksCM,,1,,aws_opsworkscm_,,opsworkscm_,OpsWorks CM,AWS,,,,, organizations,organizations,organizations,organizations,,organizations,,,Organizations,Organizations,,1,,aws_organizations_,,organizations_,Organizations,AWS,,,,, outposts,outposts,outposts,outposts,,outposts,,,Outposts,Outposts,,1,,aws_outposts_,,outposts_,Outposts,AWS,,,,, -,,,,,ec2outposts,ec2,,,,,,aws_ec2_(coip_pool|local_gateway),aws_ec2outposts_,outposts_,ec2_coip_pool;ec2_local_gateway,Outposts (EC2),AWS,x,x,,,Part of EC2 +,,,,,ec2outposts,ec2,,EC2Outposts,,,,aws_ec2_(coip_pool|local_gateway),aws_ec2outposts_,outposts_,ec2_coip_pool;ec2_local_gateway,Outposts (EC2),AWS,x,x,,,Part of EC2 panorama,panorama,panorama,panorama,,panorama,,,Panorama,Panorama,,1,,aws_panorama_,,panorama_,Panorama,AWS,,,,, ,,,,,,,,,,,,,,,,ParallelCluster,AWS,x,,,,No SDK support personalize,personalize,personalize,personalize,,personalize,,,Personalize,Personalize,,1,,aws_personalize_,,personalize_,Personalize,Amazon,,,,, @@ -339,18 +340,18 @@ timestream-write,timestreamwrite,timestreamwrite,timestreamwrite,,timestreamwrit transcribe,transcribe,transcribeservice,transcribe,,transcribe,,transcribeservice,Transcribe,TranscribeService,,1,,aws_transcribe_,,transcribe_,Transcribe,Amazon,,,,, ,,transcribestreamingservice,transcribestreaming,,transcribestreaming,,transcribestreamingservice,TranscribeStreaming,TranscribeStreamingService,,1,,aws_transcribestreaming_,,transcribestreaming_,Transcribe Streaming,Amazon,,,,, transfer,transfer,transfer,transfer,,transfer,,,Transfer,Transfer,,1,,aws_transfer_,,transfer_,Transfer Family,AWS,,,,, -,,,,,transitgateway,ec2,,,,,,aws_ec2_transit_gateway,aws_transitgateway_,transitgateway_,ec2_transit_gateway,Transit Gateway,AWS,x,x,,,Part of EC2 +,,,,,transitgateway,ec2,,TransitGateway,,,,aws_ec2_transit_gateway,aws_transitgateway_,transitgateway_,ec2_transit_gateway,Transit Gateway,AWS,x,x,,,Part of EC2 translate,translate,translate,translate,,translate,,,Translate,Translate,,1,,aws_translate_,,translate_,Translate,Amazon,,,,, ,,,,,,,,,,,,,,,,Trusted Advisor,AWS,x,,,,Part of Support -,,,,,vpc,ec2,,,,,,aws_((default_)?(network_acl|route_table|security_group|subnet|vpc(?!_ipam))|ec2_(managed|network|subnet|traffic)|egress_only_internet|flow_log|internet_gateway|main_route_table_association|nat_gateway|network_interface|prefix_list|route\b),aws_vpc_,vpc_,default_network_;default_route_;default_security_;default_subnet;default_vpc;ec2_managed_;ec2_network_;ec2_subnet_;ec2_traffic_;egress_only_;flow_log;internet_gateway;main_route_;nat_;network_;prefix_list;route_;route\.;security_group;subnet;vpc_dhcp_;vpc_endpoint;vpc_ipv;vpc_peering_;vpc\.;vpcs\.,VPC (Virtual Private Cloud),Amazon,x,x,,,Part of EC2 -,,,,,ipam,ec2,,,,,,aws_vpc_ipam,aws_ipam_,ipam_,vpc_ipam,VPC IPAM (IP Address Manager),Amazon,x,x,,,Part of EC2 -,,,,,vpnclient,ec2,,,,,,aws_ec2_client_vpn,aws_vpnclient_,vpnclient_,ec2_client_vpn_,VPN (Client),AWS,x,x,,,Part of EC2 -,,,,,vpnsite,ec2,,,,,,aws_(customer_gateway|vpn_),aws_vpnsite_,vpnsite_,customer_gateway;vpn_,VPN (Site-to-Site),AWS,x,x,,,Part of EC2 +,,,,,vpc,ec2,,VPC,,,,aws_((default_)?(network_acl|route_table|security_group|subnet|vpc(?!_ipam))|ec2_(managed|network|subnet|traffic)|egress_only_internet|flow_log|internet_gateway|main_route_table_association|nat_gateway|network_interface|prefix_list|route\b),aws_vpc_,vpc_,default_network_;default_route_;default_security_;default_subnet;default_vpc;ec2_managed_;ec2_network_;ec2_subnet_;ec2_traffic_;egress_only_;flow_log;internet_gateway;main_route_;nat_;network_;prefix_list;route_;route\.;security_group;subnet;vpc_dhcp_;vpc_endpoint;vpc_ipv;vpc_peering_;vpc\.;vpcs\.,VPC (Virtual Private Cloud),Amazon,x,x,,,Part of EC2 +,,,,,ipam,ec2,,IPAM,,,,aws_vpc_ipam,aws_ipam_,ipam_,vpc_ipam,VPC IPAM (IP Address Manager),Amazon,x,x,,,Part of EC2 +,,,,,vpnclient,ec2,,ClientVPN,,,,aws_ec2_client_vpn,aws_vpnclient_,vpnclient_,ec2_client_vpn_,VPN (Client),AWS,x,x,,,Part of EC2 +,,,,,vpnsite,ec2,,SiteVPN,,,,aws_(customer_gateway|vpn_),aws_vpnsite_,vpnsite_,customer_gateway;vpn_,VPN (Site-to-Site),AWS,x,x,,,Part of EC2 wafv2,wafv2,wafv2,wafv2,,wafv2,,,WAFV2,WAFV2,,1,,aws_wafv2_,,wafv2_,WAF,AWS,,,,, waf,waf,waf,waf,,waf,,,WAF,WAF,,1,,aws_waf_,,waf_,WAF Classic,AWS,,,,, waf-regional,wafregional,wafregional,wafregional,,wafregional,,,WAFRegional,WAFRegional,,1,,aws_wafregional_,,wafregional_,WAF Classic Regional,AWS,,,,, ,,,,,,,,,,,,,,,,WAM (WorkSpaces Application Manager),Amazon,x,,,,No SDK support -,,,,,wavelength,ec2,,,,,,aws_ec2_carrier_gateway,aws_wavelength_,wavelength_,ec2_carrier_,Wavelength,AWS,x,x,,,Part of EC2 +,,,,,wavelength,ec2,,Wavelength,,,,aws_ec2_carrier_gateway,aws_wavelength_,wavelength_,ec2_carrier_,Wavelength,AWS,x,x,,,Part of EC2 budgets,budgets,budgets,budgets,,budgets,,,Budgets,Budgets,,1,,aws_budgets_,,budgets_,Web Services Budgets,Amazon,,,,, wellarchitected,wellarchitected,wellarchitected,wellarchitected,,wellarchitected,,,WellArchitected,WellArchitected,,1,,aws_wellarchitected_,,wellarchitected_,Well-Architected Tool,AWS,,,,, workdocs,workdocs,workdocs,workdocs,,workdocs,,,WorkDocs,WorkDocs,,1,,aws_workdocs_,,workdocs_,WorkDocs,Amazon,,,,, diff --git a/providerlint/go.mod b/providerlint/go.mod index 4e9d88f09bc..d798a48c14f 100644 --- a/providerlint/go.mod +++ b/providerlint/go.mod @@ -3,8 +3,8 @@ module github.com/hashicorp/terraform-provider-aws/providerlint go 1.16 require ( - github.com/aws/aws-sdk-go v1.44.15 + github.com/aws/aws-sdk-go v1.44.39 github.com/bflad/tfproviderlint v0.28.1 - github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0 + github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 golang.org/x/tools v0.0.0-20201028111035-eafbe7b904eb ) diff --git a/providerlint/go.sum b/providerlint/go.sum index e37d36f02cf..afac8c15794 100644 --- a/providerlint/go.sum +++ b/providerlint/go.sum @@ -65,8 +65,8 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkY github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM= github.com/aws/aws-sdk-go v1.25.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go v1.37.0/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= -github.com/aws/aws-sdk-go v1.44.15 h1:z02BVeV6k7hZMfWEQmKh3X23s3F9PBHFCcIVfNlut7A= -github.com/aws/aws-sdk-go v1.44.15/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= +github.com/aws/aws-sdk-go v1.44.39 h1:pMxYLqnuDidT0ZTDAhYC66fb3W3Yc+oShmfzEL4fTDI= +github.com/aws/aws-sdk-go v1.44.39/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= github.com/bflad/gopaniccheck v0.1.0 h1:tJftp+bv42ouERmUMWLoUn/5bi/iQZjHPznM00cP/bU= github.com/bflad/gopaniccheck v0.1.0/go.mod h1:ZCj2vSr7EqVeDaqVsWN4n2MwdROx1YL+LFo47TSWtsA= github.com/bflad/tfproviderlint v0.28.1 h1:7f54/ynV6/lK5/1EyG7tHtc4sMdjJSEFGjZNRJKwBs8= @@ -83,8 +83,8 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= -github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -96,7 +96,7 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -203,8 +203,8 @@ github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+l github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-plugin v1.3.0/go.mod h1:F9eH4LrE/ZsRdbwhfjs9k9HoDUwAHnYtXdgmf1AVNs0= github.com/hashicorp/go-plugin v1.4.0/go.mod h1:5fGEH17QVwTTcR0zV7yhDPLLmFX9YSZ38b18Udy6vYQ= -github.com/hashicorp/go-plugin v1.4.3 h1:DXmvivbWD5qdiBts9TpBC7BYL1Aia5sxbRgQB+v6UZM= -github.com/hashicorp/go-plugin v1.4.3/go.mod h1:5fGEH17QVwTTcR0zV7yhDPLLmFX9YSZ38b18Udy6vYQ= +github.com/hashicorp/go-plugin v1.4.4 h1:NVdrSdFRt3SkZtNckJ6tog7gbpRrcbOjQi/rgF7JYWQ= +github.com/hashicorp/go-plugin v1.4.4/go.mod h1:viDMjcLJuDui6pXb8U4HVfb8AamCWhHGUjr2IrTF67s= github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= @@ -214,8 +214,9 @@ github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09 github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.4.0 h1:aAQzgqIrRKRa7w75CKpbBxYsmUoPjzVm1W59ca1L0J4= github.com/hashicorp/go-version v1.4.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.5.0 h1:O293SZ2Eg+AAYijkVK3jR786Am1bhDEh2GHT0tIVE5E= +github.com/hashicorp/go-version v1.5.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hc-install v0.3.1/go.mod h1:3LCdWcCDS1gaHC9mhHCGbkYfoY6vdsKohGjugbZdZak= @@ -237,19 +238,19 @@ github.com/hashicorp/terraform-exec v0.16.1 h1:NAwZFJW2L2SaCBVZoVaH8LPImLOGbPLkS github.com/hashicorp/terraform-exec v0.16.1/go.mod h1:aj0lVshy8l+MHhFNoijNHtqTJQI3Xlowv5EOsEaGO7M= github.com/hashicorp/terraform-json v0.5.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= github.com/hashicorp/terraform-json v0.8.0/go.mod h1:3defM4kkMfttwiE7VakJDwCd4R+umhSQnvJwORXbprE= -github.com/hashicorp/terraform-json v0.13.0 h1:Li9L+lKD1FO5RVFRM1mMMIBDoUHslOniyEi5CM+FWGY= github.com/hashicorp/terraform-json v0.13.0/go.mod h1:y5OdLBCT+rxbwnpxZs9kGL7R9ExU76+cpdY8zHwoazk= +github.com/hashicorp/terraform-json v0.14.0 h1:sh9iZ1Y8IFJLx+xQiKHGud6/TSUCM0N8e17dKDpqV7s= +github.com/hashicorp/terraform-json v0.14.0/go.mod h1:5A9HIWPkk4e5aeeXIBbkcOvaZbIYnAIkEyqP2pNSckM= github.com/hashicorp/terraform-plugin-go v0.2.1/go.mod h1:10V6F3taeDWVAoLlkmArKttR3IULlRWFAGtQIQTIDr4= -github.com/hashicorp/terraform-plugin-go v0.9.0 h1:FvLY/3z4SNVatPZdoFcyrlNbCar+WyyOTv5X4Tp+WZc= -github.com/hashicorp/terraform-plugin-go v0.9.0/go.mod h1:EawBkgjBWNf7jiKnVoyDyF39OSV+u6KUX+Y73EPj3oM= -github.com/hashicorp/terraform-plugin-log v0.3.0/go.mod h1:EjueSP/HjlyFAsDqt+okpCPjkT4NDynAe32AeDC4vps= +github.com/hashicorp/terraform-plugin-go v0.9.1 h1:vXdHaQ6aqL+OF076nMSBV+JKPdmXlzG5mzVDD04WyPs= +github.com/hashicorp/terraform-plugin-go v0.9.1/go.mod h1:ItjVSlQs70otlzcCwlPcU8FRXLdO973oYFRZwAOxy8M= github.com/hashicorp/terraform-plugin-log v0.4.0 h1:F3eVnm8r2EfQCe2k9blPIiF/r2TT01SHijXnS7bujvc= github.com/hashicorp/terraform-plugin-log v0.4.0/go.mod h1:9KclxdunFownr4pIm1jdmwKRmE4d6HVG2c9XDq47rpg= github.com/hashicorp/terraform-plugin-sdk v1.16.1 h1:G2iK7MBT4LuNcVASPXWS1ciBUuIm8oIY0zRfCmi3xy4= github.com/hashicorp/terraform-plugin-sdk v1.16.1/go.mod h1:KSsGcuZ1JRqnmYzz+sWIiUwNvJkzXbGRIdefwFfOdyY= github.com/hashicorp/terraform-plugin-sdk/v2 v2.5.0/go.mod h1:z+cMZ0iswzZOahBJ3XmNWgWkVnAd2bl8g+FhyyuPDH4= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0 h1:9fjPgCenJqnbjo95SDcbJ+YdLyEC1N35cwKWcRWhJTQ= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0/go.mod h1:hLa0sTiySU/AWEgV2GxJh0/pQIqcCmm30IPja9N9lTg= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 h1:Qr5fWNg1SPSfCRMtou67Y6Kcy9UnMYRNlIJTKRuUvXU= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0/go.mod h1:b+LFg8WpYgFgvEBP/6Htk5H9/pJp1V1E8NJAekfH2Ws= github.com/hashicorp/terraform-plugin-test/v2 v2.1.3/go.mod h1:pmaUHiUtDL/8Mz3FuyZ/vRDb0LpaOWQjVRW9ORF7FHs= github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896 h1:1FGtlkJw87UsTMg5s8jrekrHmUPUJaMcu6ELiVhQrNw= github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896/go.mod h1:bzBPnUIkI0RxauU8Dqo+2KrZZ28Cf48s8V6IHt3p4co= @@ -522,6 +523,7 @@ golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210502180810-71e4cd670f79/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -666,8 +668,8 @@ google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.45.0 h1:NEpgUqV3Z+ZjkqMsxMg11IaDrXY4RY6CQukSGK0uI1M= -google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.46.0 h1:oCjezcn6g6A75TGoKYBPgKmVBLexhYLM6MebdrPApP8= +google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0/go.mod h1:DNq5QpG7LJqD2AamLZ7zvKE0DEpVl2BSEVjFycAAjRY= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= diff --git a/providerlint/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/providerlint/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go index 11bd2009808..4a1a0f9ef8c 100644 --- a/providerlint/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ b/providerlint/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go @@ -1937,9 +1937,15 @@ var awsPartition = partition{ }, "app-integrations": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -3046,6 +3052,73 @@ var awsPartition = partition{ }: endpoint{}, }, }, + "backup-gateway": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "batch": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{}, @@ -3080,6 +3153,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -3225,6 +3301,13 @@ var awsPartition = partition{ }, }, }, + "catalog.marketplace": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + }, + }, "ce": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, @@ -5313,6 +5396,22 @@ var awsPartition = partition{ }: endpoint{}, }, }, + "connect-campaigns": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "contact-lens": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -6395,30 +6494,66 @@ var awsPartition = partition{ }, "drs": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -7492,6 +7627,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -8314,24 +8452,96 @@ var awsPartition = partition{ }, "email": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "email-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "email-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "email-fips.us-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "email-fips.us-west-2.amazonaws.com", + }, }, }, "emr-containers": service{ @@ -8461,6 +8671,52 @@ var awsPartition = partition{ }, }, }, + "emr-serverless": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "emr-serverless-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "emr-serverless-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "emr-serverless-fips.us-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "emr-serverless-fips.us-west-2.amazonaws.com", + }, + }, + }, "entitlement.marketplace": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -11019,6 +11275,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -11081,6 +11340,14 @@ var awsPartition = partition{ Region: "ap-southeast-2", }, }, + endpointKey{ + Region: "ca-central-1", + }: endpoint{ + Hostname: "data.iotevents.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, endpointKey{ Region: "eu-central-1", }: endpoint{ @@ -11290,11 +11557,29 @@ var awsPartition = partition{ Region: "ap-southeast-2", }: endpoint{}, endpointKey{ - Region: "eu-central-1", + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "iotsitewise-fips.ca-central-1.amazonaws.com", + }, + endpointKey{ + Region: "eu-central-1", }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "iotsitewise-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -11304,6 +11589,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "iotsitewise-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-west-2", }: endpoint{ @@ -11322,6 +11616,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "iotsitewise-fips.us-east-1.amazonaws.com", }, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "iotsitewise-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -13065,6 +13368,31 @@ var awsPartition = partition{ }: endpoint{}, }, }, + "m2": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "machinelearning": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -13762,6 +14090,66 @@ var awsPartition = partition{ }, }, }, + "memory-db": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "fips", + }: endpoint{ + Hostname: "memory-db-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "messaging-chime": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -14720,6 +15108,14 @@ var awsPartition = partition{ Region: "ap-northeast-2", }, }, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{ + Hostname: "oidc.ap-northeast-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-3", + }, + }, endpointKey{ Region: "ap-south-1", }: endpoint{ @@ -15413,6 +15809,14 @@ var awsPartition = partition{ Region: "ap-northeast-2", }, }, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{ + Hostname: "portal.sso.ap-northeast-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-3", + }, + }, endpointKey{ Region: "ap-south-1", }: endpoint{ @@ -15461,6 +15865,14 @@ var awsPartition = partition{ Region: "eu-north-1", }, }, + endpointKey{ + Region: "eu-south-1", + }: endpoint{ + Hostname: "portal.sso.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + }, endpointKey{ Region: "eu-west-1", }: endpoint{ @@ -15578,6 +15990,25 @@ var awsPartition = partition{ }: endpoint{}, }, }, + "proton": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "qldb": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -16361,6 +16792,43 @@ var awsPartition = partition{ }, }, }, + "redshift-serverless": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "rekognition": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -16614,6 +17082,70 @@ var awsPartition = partition{ }, }, }, + "resiliencehub": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "resource-groups": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -18453,6 +18985,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -18680,7 +19215,10 @@ var awsPartition = partition{ Region: "ap-southeast-2", }: endpoint{}, endpointKey{ - Region: "ca-central-1", + Region: "ap-southeast-3", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", @@ -22096,7 +22634,583 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ap-east-1", }: endpoint{ - Hostname: "waf-regional-fips.ap-east-1.amazonaws.com", + Hostname: "waf-regional-fips.ap-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ap-northeast-1", + }: endpoint{ + Hostname: "waf-regional-fips.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ap-northeast-2", + }: endpoint{ + Hostname: "waf-regional-fips.ap-northeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ap-northeast-3", + }: endpoint{ + Hostname: "waf-regional-fips.ap-northeast-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-3", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ap-south-1", + }: endpoint{ + Hostname: "waf-regional-fips.ap-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-south-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ap-southeast-1", + }: endpoint{ + Hostname: "waf-regional-fips.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ap-southeast-2", + }: endpoint{ + Hostname: "waf-regional-fips.ap-southeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ap-southeast-3", + }: endpoint{ + Hostname: "waf-regional-fips.ap-southeast-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-3", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "waf-regional-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-eu-central-1", + }: endpoint{ + Hostname: "waf-regional-fips.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-eu-north-1", + }: endpoint{ + Hostname: "waf-regional-fips.eu-north-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-north-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-eu-south-1", + }: endpoint{ + Hostname: "waf-regional-fips.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-eu-west-1", + }: endpoint{ + Hostname: "waf-regional-fips.eu-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-eu-west-2", + }: endpoint{ + Hostname: "waf-regional-fips.eu-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-eu-west-3", + }: endpoint{ + Hostname: "waf-regional-fips.eu-west-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-3", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-me-south-1", + }: endpoint{ + Hostname: "waf-regional-fips.me-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "me-south-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-sa-east-1", + }: endpoint{ + Hostname: "waf-regional-fips.sa-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "sa-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "waf-regional-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "waf-regional-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "waf-regional-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "waf-regional-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "me-south-1", + }: endpoint{ + Hostname: "waf-regional.me-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "me-south-1", + }, + }, + endpointKey{ + Region: "me-south-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "waf-regional-fips.me-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "me-south-1", + }, + }, + endpointKey{ + Region: "sa-east-1", + }: endpoint{ + Hostname: "waf-regional.sa-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "sa-east-1", + }, + }, + endpointKey{ + Region: "sa-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "waf-regional-fips.sa-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "sa-east-1", + }, + }, + endpointKey{ + Region: "us-east-1", + }: endpoint{ + Hostname: "waf-regional.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "waf-regional-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "us-east-2", + }: endpoint{ + Hostname: "waf-regional.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "waf-regional-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + endpointKey{ + Region: "us-west-1", + }: endpoint{ + Hostname: "waf-regional.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "waf-regional-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + endpointKey{ + Region: "us-west-2", + }: endpoint{ + Hostname: "waf-regional.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "waf-regional-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + }, + }, + "wafv2": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{ + Hostname: "wafv2.af-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "af-south-1", + }, + }, + endpointKey{ + Region: "af-south-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.af-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "af-south-1", + }, + }, + endpointKey{ + Region: "ap-east-1", + }: endpoint{ + Hostname: "wafv2.ap-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-east-1", + }, + }, + endpointKey{ + Region: "ap-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.ap-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-east-1", + }, + }, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{ + Hostname: "wafv2.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + endpointKey{ + Region: "ap-northeast-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{ + Hostname: "wafv2.ap-northeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-2", + }, + }, + endpointKey{ + Region: "ap-northeast-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.ap-northeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-2", + }, + }, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{ + Hostname: "wafv2.ap-northeast-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-3", + }, + }, + endpointKey{ + Region: "ap-northeast-3", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.ap-northeast-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-3", + }, + }, + endpointKey{ + Region: "ap-south-1", + }: endpoint{ + Hostname: "wafv2.ap-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-south-1", + }, + }, + endpointKey{ + Region: "ap-south-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.ap-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-south-1", + }, + }, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{ + Hostname: "wafv2.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + endpointKey{ + Region: "ap-southeast-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{ + Hostname: "wafv2.ap-southeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-2", + }, + }, + endpointKey{ + Region: "ap-southeast-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.ap-southeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-2", + }, + }, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{ + Hostname: "wafv2.ap-southeast-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-3", + }, + }, + endpointKey{ + Region: "ap-southeast-3", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.ap-southeast-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-3", + }, + }, + endpointKey{ + Region: "ca-central-1", + }: endpoint{ + Hostname: "wafv2.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + endpointKey{ + Region: "eu-central-1", + }: endpoint{ + Hostname: "wafv2.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + endpointKey{ + Region: "eu-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + endpointKey{ + Region: "eu-north-1", + }: endpoint{ + Hostname: "wafv2.eu-north-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-north-1", + }, + }, + endpointKey{ + Region: "eu-north-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.eu-north-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-north-1", + }, + }, + endpointKey{ + Region: "eu-south-1", + }: endpoint{ + Hostname: "wafv2.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + }, + endpointKey{ + Region: "eu-south-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + }, + endpointKey{ + Region: "eu-west-1", + }: endpoint{ + Hostname: "wafv2.eu-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + }, + endpointKey{ + Region: "eu-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.eu-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + }, + endpointKey{ + Region: "eu-west-2", + }: endpoint{ + Hostname: "wafv2.eu-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-2", + }, + }, + endpointKey{ + Region: "eu-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.eu-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-2", + }, + }, + endpointKey{ + Region: "eu-west-3", + }: endpoint{ + Hostname: "wafv2.eu-west-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-3", + }, + }, + endpointKey{ + Region: "eu-west-3", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.eu-west-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-3", + }, + }, + endpointKey{ + Region: "fips-af-south-1", + }: endpoint{ + Hostname: "wafv2-fips.af-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "af-south-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ap-east-1", + }: endpoint{ + Hostname: "wafv2-fips.ap-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "ap-east-1", }, @@ -22105,7 +23219,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ap-northeast-1", }: endpoint{ - Hostname: "waf-regional-fips.ap-northeast-1.amazonaws.com", + Hostname: "wafv2-fips.ap-northeast-1.amazonaws.com", CredentialScope: credentialScope{ Region: "ap-northeast-1", }, @@ -22114,7 +23228,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ap-northeast-2", }: endpoint{ - Hostname: "waf-regional-fips.ap-northeast-2.amazonaws.com", + Hostname: "wafv2-fips.ap-northeast-2.amazonaws.com", CredentialScope: credentialScope{ Region: "ap-northeast-2", }, @@ -22123,7 +23237,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ap-northeast-3", }: endpoint{ - Hostname: "waf-regional-fips.ap-northeast-3.amazonaws.com", + Hostname: "wafv2-fips.ap-northeast-3.amazonaws.com", CredentialScope: credentialScope{ Region: "ap-northeast-3", }, @@ -22132,7 +23246,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ap-south-1", }: endpoint{ - Hostname: "waf-regional-fips.ap-south-1.amazonaws.com", + Hostname: "wafv2-fips.ap-south-1.amazonaws.com", CredentialScope: credentialScope{ Region: "ap-south-1", }, @@ -22141,7 +23255,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ap-southeast-1", }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-1.amazonaws.com", + Hostname: "wafv2-fips.ap-southeast-1.amazonaws.com", CredentialScope: credentialScope{ Region: "ap-southeast-1", }, @@ -22150,7 +23264,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ap-southeast-2", }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-2.amazonaws.com", + Hostname: "wafv2-fips.ap-southeast-2.amazonaws.com", CredentialScope: credentialScope{ Region: "ap-southeast-2", }, @@ -22159,7 +23273,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ap-southeast-3", }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-3.amazonaws.com", + Hostname: "wafv2-fips.ap-southeast-3.amazonaws.com", CredentialScope: credentialScope{ Region: "ap-southeast-3", }, @@ -22168,7 +23282,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ca-central-1", }: endpoint{ - Hostname: "waf-regional-fips.ca-central-1.amazonaws.com", + Hostname: "wafv2-fips.ca-central-1.amazonaws.com", CredentialScope: credentialScope{ Region: "ca-central-1", }, @@ -22177,7 +23291,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-eu-central-1", }: endpoint{ - Hostname: "waf-regional-fips.eu-central-1.amazonaws.com", + Hostname: "wafv2-fips.eu-central-1.amazonaws.com", CredentialScope: credentialScope{ Region: "eu-central-1", }, @@ -22186,7 +23300,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-eu-north-1", }: endpoint{ - Hostname: "waf-regional-fips.eu-north-1.amazonaws.com", + Hostname: "wafv2-fips.eu-north-1.amazonaws.com", CredentialScope: credentialScope{ Region: "eu-north-1", }, @@ -22195,7 +23309,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-eu-south-1", }: endpoint{ - Hostname: "waf-regional-fips.eu-south-1.amazonaws.com", + Hostname: "wafv2-fips.eu-south-1.amazonaws.com", CredentialScope: credentialScope{ Region: "eu-south-1", }, @@ -22204,7 +23318,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-eu-west-1", }: endpoint{ - Hostname: "waf-regional-fips.eu-west-1.amazonaws.com", + Hostname: "wafv2-fips.eu-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "eu-west-1", }, @@ -22213,7 +23327,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-eu-west-2", }: endpoint{ - Hostname: "waf-regional-fips.eu-west-2.amazonaws.com", + Hostname: "wafv2-fips.eu-west-2.amazonaws.com", CredentialScope: credentialScope{ Region: "eu-west-2", }, @@ -22222,7 +23336,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-eu-west-3", }: endpoint{ - Hostname: "waf-regional-fips.eu-west-3.amazonaws.com", + Hostname: "wafv2-fips.eu-west-3.amazonaws.com", CredentialScope: credentialScope{ Region: "eu-west-3", }, @@ -22231,7 +23345,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-me-south-1", }: endpoint{ - Hostname: "waf-regional-fips.me-south-1.amazonaws.com", + Hostname: "wafv2-fips.me-south-1.amazonaws.com", CredentialScope: credentialScope{ Region: "me-south-1", }, @@ -22240,7 +23354,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-sa-east-1", }: endpoint{ - Hostname: "waf-regional-fips.sa-east-1.amazonaws.com", + Hostname: "wafv2-fips.sa-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "sa-east-1", }, @@ -22249,7 +23363,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-east-1", }: endpoint{ - Hostname: "waf-regional-fips.us-east-1.amazonaws.com", + Hostname: "wafv2-fips.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, @@ -22258,7 +23372,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-east-2", }: endpoint{ - Hostname: "waf-regional-fips.us-east-2.amazonaws.com", + Hostname: "wafv2-fips.us-east-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-2", }, @@ -22267,7 +23381,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-west-1", }: endpoint{ - Hostname: "waf-regional-fips.us-west-1.amazonaws.com", + Hostname: "wafv2-fips.us-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-1", }, @@ -22276,7 +23390,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-west-2", }: endpoint{ - Hostname: "waf-regional-fips.us-west-2.amazonaws.com", + Hostname: "wafv2-fips.us-west-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-2", }, @@ -22285,7 +23399,7 @@ var awsPartition = partition{ endpointKey{ Region: "me-south-1", }: endpoint{ - Hostname: "waf-regional.me-south-1.amazonaws.com", + Hostname: "wafv2.me-south-1.amazonaws.com", CredentialScope: credentialScope{ Region: "me-south-1", }, @@ -22294,7 +23408,7 @@ var awsPartition = partition{ Region: "me-south-1", Variant: fipsVariant, }: endpoint{ - Hostname: "waf-regional-fips.me-south-1.amazonaws.com", + Hostname: "wafv2-fips.me-south-1.amazonaws.com", CredentialScope: credentialScope{ Region: "me-south-1", }, @@ -22302,7 +23416,7 @@ var awsPartition = partition{ endpointKey{ Region: "sa-east-1", }: endpoint{ - Hostname: "waf-regional.sa-east-1.amazonaws.com", + Hostname: "wafv2.sa-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "sa-east-1", }, @@ -22311,7 +23425,7 @@ var awsPartition = partition{ Region: "sa-east-1", Variant: fipsVariant, }: endpoint{ - Hostname: "waf-regional-fips.sa-east-1.amazonaws.com", + Hostname: "wafv2-fips.sa-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "sa-east-1", }, @@ -22319,7 +23433,7 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-1", }: endpoint{ - Hostname: "waf-regional.us-east-1.amazonaws.com", + Hostname: "wafv2.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, @@ -22328,7 +23442,7 @@ var awsPartition = partition{ Region: "us-east-1", Variant: fipsVariant, }: endpoint{ - Hostname: "waf-regional-fips.us-east-1.amazonaws.com", + Hostname: "wafv2-fips.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, @@ -22336,7 +23450,7 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-2", }: endpoint{ - Hostname: "waf-regional.us-east-2.amazonaws.com", + Hostname: "wafv2.us-east-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-2", }, @@ -22345,7 +23459,7 @@ var awsPartition = partition{ Region: "us-east-2", Variant: fipsVariant, }: endpoint{ - Hostname: "waf-regional-fips.us-east-2.amazonaws.com", + Hostname: "wafv2-fips.us-east-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-2", }, @@ -22353,7 +23467,7 @@ var awsPartition = partition{ endpointKey{ Region: "us-west-1", }: endpoint{ - Hostname: "waf-regional.us-west-1.amazonaws.com", + Hostname: "wafv2.us-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-1", }, @@ -22362,7 +23476,7 @@ var awsPartition = partition{ Region: "us-west-1", Variant: fipsVariant, }: endpoint{ - Hostname: "waf-regional-fips.us-west-1.amazonaws.com", + Hostname: "wafv2-fips.us-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-1", }, @@ -22370,7 +23484,7 @@ var awsPartition = partition{ endpointKey{ Region: "us-west-2", }: endpoint{ - Hostname: "waf-regional.us-west-2.amazonaws.com", + Hostname: "wafv2.us-west-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-2", }, @@ -22379,13 +23493,71 @@ var awsPartition = partition{ Region: "us-west-2", Variant: fipsVariant, }: endpoint{ - Hostname: "waf-regional-fips.us-west-2.amazonaws.com", + Hostname: "wafv2-fips.us-west-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-2", }, }, }, }, + "wellarchitected": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "wisdom": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -23679,6 +24851,16 @@ var awscnPartition = partition{ }, }, }, + "memory-db": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "monitoring": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -24275,6 +25457,62 @@ var awscnPartition = partition{ }, }, }, + "wafv2": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{ + Hostname: "wafv2.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + endpointKey{ + Region: "cn-north-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{ + Hostname: "wafv2.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + endpointKey{ + Region: "cn-northwest-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + endpointKey{ + Region: "fips-cn-north-1", + }: endpoint{ + Hostname: "wafv2-fips.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-cn-northwest-1", + }: endpoint{ + Hostname: "wafv2-fips.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + Deprecated: boxedTrue, + }, + }, + }, "workspaces": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -24910,6 +26148,16 @@ var awsusgovPartition = partition{ }: endpoint{}, }, }, + "backup-gateway": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + }, + }, "batch": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{}, @@ -28221,42 +29469,12 @@ var awsusgovPartition = partition{ }, }, Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "servicecatalog-appregistry.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "servicecatalog-appregistry.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, endpointKey{ Region: "us-gov-east-1", }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-appregistry.us-gov-east-1.amazonaws.com", - }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-appregistry.us-gov-west-1.amazonaws.com", - }, }, }, "servicediscovery": service{ @@ -28978,6 +30196,16 @@ var awsusgovPartition = partition{ }, }, }, + "transcribestreaming": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + }, + }, "transfer": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -29101,6 +30329,62 @@ var awsusgovPartition = partition{ }, }, }, + "wafv2": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "wafv2-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "wafv2-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{ + Hostname: "wafv2.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{ + Hostname: "wafv2.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + }, + }, "workspaces": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -29239,6 +30523,13 @@ var awsisoPartition = partition{ }: endpoint{}, }, }, + "appconfigdata": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, + }, + }, "application-autoscaling": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -30452,5 +31743,12 @@ var awsisobPartition = partition{ }: endpoint{}, }, }, + "workspaces": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-isob-east-1", + }: endpoint{}, + }, + }, }, } diff --git a/providerlint/vendor/github.com/golang/protobuf/jsonpb/decode.go b/providerlint/vendor/github.com/golang/protobuf/jsonpb/decode.go new file mode 100644 index 00000000000..60e82caa9a2 --- /dev/null +++ b/providerlint/vendor/github.com/golang/protobuf/jsonpb/decode.go @@ -0,0 +1,524 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsonpb + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "math" + "reflect" + "strconv" + "strings" + "time" + + "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/encoding/protojson" + protoV2 "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +const wrapJSONUnmarshalV2 = false + +// UnmarshalNext unmarshals the next JSON object from d into m. +func UnmarshalNext(d *json.Decoder, m proto.Message) error { + return new(Unmarshaler).UnmarshalNext(d, m) +} + +// Unmarshal unmarshals a JSON object from r into m. +func Unmarshal(r io.Reader, m proto.Message) error { + return new(Unmarshaler).Unmarshal(r, m) +} + +// UnmarshalString unmarshals a JSON object from s into m. +func UnmarshalString(s string, m proto.Message) error { + return new(Unmarshaler).Unmarshal(strings.NewReader(s), m) +} + +// Unmarshaler is a configurable object for converting from a JSON +// representation to a protocol buffer object. +type Unmarshaler struct { + // AllowUnknownFields specifies whether to allow messages to contain + // unknown JSON fields, as opposed to failing to unmarshal. + AllowUnknownFields bool + + // AnyResolver is used to resolve the google.protobuf.Any well-known type. + // If unset, the global registry is used by default. + AnyResolver AnyResolver +} + +// JSONPBUnmarshaler is implemented by protobuf messages that customize the way +// they are unmarshaled from JSON. Messages that implement this should also +// implement JSONPBMarshaler so that the custom format can be produced. +// +// The JSON unmarshaling must follow the JSON to proto specification: +// https://developers.google.com/protocol-buffers/docs/proto3#json +// +// Deprecated: Custom types should implement protobuf reflection instead. +type JSONPBUnmarshaler interface { + UnmarshalJSONPB(*Unmarshaler, []byte) error +} + +// Unmarshal unmarshals a JSON object from r into m. +func (u *Unmarshaler) Unmarshal(r io.Reader, m proto.Message) error { + return u.UnmarshalNext(json.NewDecoder(r), m) +} + +// UnmarshalNext unmarshals the next JSON object from d into m. +func (u *Unmarshaler) UnmarshalNext(d *json.Decoder, m proto.Message) error { + if m == nil { + return errors.New("invalid nil message") + } + + // Parse the next JSON object from the stream. + raw := json.RawMessage{} + if err := d.Decode(&raw); err != nil { + return err + } + + // Check for custom unmarshalers first since they may not properly + // implement protobuf reflection that the logic below relies on. + if jsu, ok := m.(JSONPBUnmarshaler); ok { + return jsu.UnmarshalJSONPB(u, raw) + } + + mr := proto.MessageReflect(m) + + // NOTE: For historical reasons, a top-level null is treated as a noop. + // This is incorrect, but kept for compatibility. + if string(raw) == "null" && mr.Descriptor().FullName() != "google.protobuf.Value" { + return nil + } + + if wrapJSONUnmarshalV2 { + // NOTE: If input message is non-empty, we need to preserve merge semantics + // of the old jsonpb implementation. These semantics are not supported by + // the protobuf JSON specification. + isEmpty := true + mr.Range(func(protoreflect.FieldDescriptor, protoreflect.Value) bool { + isEmpty = false // at least one iteration implies non-empty + return false + }) + if !isEmpty { + // Perform unmarshaling into a newly allocated, empty message. + mr = mr.New() + + // Use a defer to copy all unmarshaled fields into the original message. + dst := proto.MessageReflect(m) + defer mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + dst.Set(fd, v) + return true + }) + } + + // Unmarshal using the v2 JSON unmarshaler. + opts := protojson.UnmarshalOptions{ + DiscardUnknown: u.AllowUnknownFields, + } + if u.AnyResolver != nil { + opts.Resolver = anyResolver{u.AnyResolver} + } + return opts.Unmarshal(raw, mr.Interface()) + } else { + if err := u.unmarshalMessage(mr, raw); err != nil { + return err + } + return protoV2.CheckInitialized(mr.Interface()) + } +} + +func (u *Unmarshaler) unmarshalMessage(m protoreflect.Message, in []byte) error { + md := m.Descriptor() + fds := md.Fields() + + if jsu, ok := proto.MessageV1(m.Interface()).(JSONPBUnmarshaler); ok { + return jsu.UnmarshalJSONPB(u, in) + } + + if string(in) == "null" && md.FullName() != "google.protobuf.Value" { + return nil + } + + switch wellKnownType(md.FullName()) { + case "Any": + var jsonObject map[string]json.RawMessage + if err := json.Unmarshal(in, &jsonObject); err != nil { + return err + } + + rawTypeURL, ok := jsonObject["@type"] + if !ok { + return errors.New("Any JSON doesn't have '@type'") + } + typeURL, err := unquoteString(string(rawTypeURL)) + if err != nil { + return fmt.Errorf("can't unmarshal Any's '@type': %q", rawTypeURL) + } + m.Set(fds.ByNumber(1), protoreflect.ValueOfString(typeURL)) + + var m2 protoreflect.Message + if u.AnyResolver != nil { + mi, err := u.AnyResolver.Resolve(typeURL) + if err != nil { + return err + } + m2 = proto.MessageReflect(mi) + } else { + mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL) + if err != nil { + if err == protoregistry.NotFound { + return fmt.Errorf("could not resolve Any message type: %v", typeURL) + } + return err + } + m2 = mt.New() + } + + if wellKnownType(m2.Descriptor().FullName()) != "" { + rawValue, ok := jsonObject["value"] + if !ok { + return errors.New("Any JSON doesn't have 'value'") + } + if err := u.unmarshalMessage(m2, rawValue); err != nil { + return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err) + } + } else { + delete(jsonObject, "@type") + rawJSON, err := json.Marshal(jsonObject) + if err != nil { + return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err) + } + if err = u.unmarshalMessage(m2, rawJSON); err != nil { + return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err) + } + } + + rawWire, err := protoV2.Marshal(m2.Interface()) + if err != nil { + return fmt.Errorf("can't marshal proto %v into Any.Value: %v", typeURL, err) + } + m.Set(fds.ByNumber(2), protoreflect.ValueOfBytes(rawWire)) + return nil + case "BoolValue", "BytesValue", "StringValue", + "Int32Value", "UInt32Value", "FloatValue", + "Int64Value", "UInt64Value", "DoubleValue": + fd := fds.ByNumber(1) + v, err := u.unmarshalValue(m.NewField(fd), in, fd) + if err != nil { + return err + } + m.Set(fd, v) + return nil + case "Duration": + v, err := unquoteString(string(in)) + if err != nil { + return err + } + d, err := time.ParseDuration(v) + if err != nil { + return fmt.Errorf("bad Duration: %v", err) + } + + sec := d.Nanoseconds() / 1e9 + nsec := d.Nanoseconds() % 1e9 + m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec))) + m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec))) + return nil + case "Timestamp": + v, err := unquoteString(string(in)) + if err != nil { + return err + } + t, err := time.Parse(time.RFC3339Nano, v) + if err != nil { + return fmt.Errorf("bad Timestamp: %v", err) + } + + sec := t.Unix() + nsec := t.Nanosecond() + m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec))) + m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec))) + return nil + case "Value": + switch { + case string(in) == "null": + m.Set(fds.ByNumber(1), protoreflect.ValueOfEnum(0)) + case string(in) == "true": + m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(true)) + case string(in) == "false": + m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(false)) + case hasPrefixAndSuffix('"', in, '"'): + s, err := unquoteString(string(in)) + if err != nil { + return fmt.Errorf("unrecognized type for Value %q", in) + } + m.Set(fds.ByNumber(3), protoreflect.ValueOfString(s)) + case hasPrefixAndSuffix('[', in, ']'): + v := m.Mutable(fds.ByNumber(6)) + return u.unmarshalMessage(v.Message(), in) + case hasPrefixAndSuffix('{', in, '}'): + v := m.Mutable(fds.ByNumber(5)) + return u.unmarshalMessage(v.Message(), in) + default: + f, err := strconv.ParseFloat(string(in), 0) + if err != nil { + return fmt.Errorf("unrecognized type for Value %q", in) + } + m.Set(fds.ByNumber(2), protoreflect.ValueOfFloat64(f)) + } + return nil + case "ListValue": + var jsonArray []json.RawMessage + if err := json.Unmarshal(in, &jsonArray); err != nil { + return fmt.Errorf("bad ListValue: %v", err) + } + + lv := m.Mutable(fds.ByNumber(1)).List() + for _, raw := range jsonArray { + ve := lv.NewElement() + if err := u.unmarshalMessage(ve.Message(), raw); err != nil { + return err + } + lv.Append(ve) + } + return nil + case "Struct": + var jsonObject map[string]json.RawMessage + if err := json.Unmarshal(in, &jsonObject); err != nil { + return fmt.Errorf("bad StructValue: %v", err) + } + + mv := m.Mutable(fds.ByNumber(1)).Map() + for key, raw := range jsonObject { + kv := protoreflect.ValueOf(key).MapKey() + vv := mv.NewValue() + if err := u.unmarshalMessage(vv.Message(), raw); err != nil { + return fmt.Errorf("bad value in StructValue for key %q: %v", key, err) + } + mv.Set(kv, vv) + } + return nil + } + + var jsonObject map[string]json.RawMessage + if err := json.Unmarshal(in, &jsonObject); err != nil { + return err + } + + // Handle known fields. + for i := 0; i < fds.Len(); i++ { + fd := fds.Get(i) + if fd.IsWeak() && fd.Message().IsPlaceholder() { + continue // weak reference is not linked in + } + + // Search for any raw JSON value associated with this field. + var raw json.RawMessage + name := string(fd.Name()) + if fd.Kind() == protoreflect.GroupKind { + name = string(fd.Message().Name()) + } + if v, ok := jsonObject[name]; ok { + delete(jsonObject, name) + raw = v + } + name = string(fd.JSONName()) + if v, ok := jsonObject[name]; ok { + delete(jsonObject, name) + raw = v + } + + field := m.NewField(fd) + // Unmarshal the field value. + if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd) && !isSingularJSONPBUnmarshaler(field, fd)) { + continue + } + v, err := u.unmarshalValue(field, raw, fd) + if err != nil { + return err + } + m.Set(fd, v) + } + + // Handle extension fields. + for name, raw := range jsonObject { + if !strings.HasPrefix(name, "[") || !strings.HasSuffix(name, "]") { + continue + } + + // Resolve the extension field by name. + xname := protoreflect.FullName(name[len("[") : len(name)-len("]")]) + xt, _ := protoregistry.GlobalTypes.FindExtensionByName(xname) + if xt == nil && isMessageSet(md) { + xt, _ = protoregistry.GlobalTypes.FindExtensionByName(xname.Append("message_set_extension")) + } + if xt == nil { + continue + } + delete(jsonObject, name) + fd := xt.TypeDescriptor() + if fd.ContainingMessage().FullName() != m.Descriptor().FullName() { + return fmt.Errorf("extension field %q does not extend message %q", xname, m.Descriptor().FullName()) + } + + field := m.NewField(fd) + // Unmarshal the field value. + if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd) && !isSingularJSONPBUnmarshaler(field, fd)) { + continue + } + v, err := u.unmarshalValue(field, raw, fd) + if err != nil { + return err + } + m.Set(fd, v) + } + + if !u.AllowUnknownFields && len(jsonObject) > 0 { + for name := range jsonObject { + return fmt.Errorf("unknown field %q in %v", name, md.FullName()) + } + } + return nil +} + +func isSingularWellKnownValue(fd protoreflect.FieldDescriptor) bool { + if md := fd.Message(); md != nil { + return md.FullName() == "google.protobuf.Value" && fd.Cardinality() != protoreflect.Repeated + } + return false +} + +func isSingularJSONPBUnmarshaler(v protoreflect.Value, fd protoreflect.FieldDescriptor) bool { + if fd.Message() != nil && fd.Cardinality() != protoreflect.Repeated { + _, ok := proto.MessageV1(v.Interface()).(JSONPBUnmarshaler) + return ok + } + return false +} + +func (u *Unmarshaler) unmarshalValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { + switch { + case fd.IsList(): + var jsonArray []json.RawMessage + if err := json.Unmarshal(in, &jsonArray); err != nil { + return v, err + } + lv := v.List() + for _, raw := range jsonArray { + ve, err := u.unmarshalSingularValue(lv.NewElement(), raw, fd) + if err != nil { + return v, err + } + lv.Append(ve) + } + return v, nil + case fd.IsMap(): + var jsonObject map[string]json.RawMessage + if err := json.Unmarshal(in, &jsonObject); err != nil { + return v, err + } + kfd := fd.MapKey() + vfd := fd.MapValue() + mv := v.Map() + for key, raw := range jsonObject { + var kv protoreflect.MapKey + if kfd.Kind() == protoreflect.StringKind { + kv = protoreflect.ValueOf(key).MapKey() + } else { + v, err := u.unmarshalSingularValue(kfd.Default(), []byte(key), kfd) + if err != nil { + return v, err + } + kv = v.MapKey() + } + + vv, err := u.unmarshalSingularValue(mv.NewValue(), raw, vfd) + if err != nil { + return v, err + } + mv.Set(kv, vv) + } + return v, nil + default: + return u.unmarshalSingularValue(v, in, fd) + } +} + +var nonFinite = map[string]float64{ + `"NaN"`: math.NaN(), + `"Infinity"`: math.Inf(+1), + `"-Infinity"`: math.Inf(-1), +} + +func (u *Unmarshaler) unmarshalSingularValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { + switch fd.Kind() { + case protoreflect.BoolKind: + return unmarshalValue(in, new(bool)) + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: + return unmarshalValue(trimQuote(in), new(int32)) + case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + return unmarshalValue(trimQuote(in), new(int64)) + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: + return unmarshalValue(trimQuote(in), new(uint32)) + case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + return unmarshalValue(trimQuote(in), new(uint64)) + case protoreflect.FloatKind: + if f, ok := nonFinite[string(in)]; ok { + return protoreflect.ValueOfFloat32(float32(f)), nil + } + return unmarshalValue(trimQuote(in), new(float32)) + case protoreflect.DoubleKind: + if f, ok := nonFinite[string(in)]; ok { + return protoreflect.ValueOfFloat64(float64(f)), nil + } + return unmarshalValue(trimQuote(in), new(float64)) + case protoreflect.StringKind: + return unmarshalValue(in, new(string)) + case protoreflect.BytesKind: + return unmarshalValue(in, new([]byte)) + case protoreflect.EnumKind: + if hasPrefixAndSuffix('"', in, '"') { + vd := fd.Enum().Values().ByName(protoreflect.Name(trimQuote(in))) + if vd == nil { + return v, fmt.Errorf("unknown value %q for enum %s", in, fd.Enum().FullName()) + } + return protoreflect.ValueOfEnum(vd.Number()), nil + } + return unmarshalValue(in, new(protoreflect.EnumNumber)) + case protoreflect.MessageKind, protoreflect.GroupKind: + err := u.unmarshalMessage(v.Message(), in) + return v, err + default: + panic(fmt.Sprintf("invalid kind %v", fd.Kind())) + } +} + +func unmarshalValue(in []byte, v interface{}) (protoreflect.Value, error) { + err := json.Unmarshal(in, v) + return protoreflect.ValueOf(reflect.ValueOf(v).Elem().Interface()), err +} + +func unquoteString(in string) (out string, err error) { + err = json.Unmarshal([]byte(in), &out) + return out, err +} + +func hasPrefixAndSuffix(prefix byte, in []byte, suffix byte) bool { + if len(in) >= 2 && in[0] == prefix && in[len(in)-1] == suffix { + return true + } + return false +} + +// trimQuote is like unquoteString but simply strips surrounding quotes. +// This is incorrect, but is behavior done by the legacy implementation. +func trimQuote(in []byte) []byte { + if len(in) >= 2 && in[0] == '"' && in[len(in)-1] == '"' { + in = in[1 : len(in)-1] + } + return in +} diff --git a/providerlint/vendor/github.com/golang/protobuf/jsonpb/encode.go b/providerlint/vendor/github.com/golang/protobuf/jsonpb/encode.go new file mode 100644 index 00000000000..685c80a62bc --- /dev/null +++ b/providerlint/vendor/github.com/golang/protobuf/jsonpb/encode.go @@ -0,0 +1,559 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsonpb + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "math" + "reflect" + "sort" + "strconv" + "strings" + "time" + + "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/encoding/protojson" + protoV2 "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +const wrapJSONMarshalV2 = false + +// Marshaler is a configurable object for marshaling protocol buffer messages +// to the specified JSON representation. +type Marshaler struct { + // OrigName specifies whether to use the original protobuf name for fields. + OrigName bool + + // EnumsAsInts specifies whether to render enum values as integers, + // as opposed to string values. + EnumsAsInts bool + + // EmitDefaults specifies whether to render fields with zero values. + EmitDefaults bool + + // Indent controls whether the output is compact or not. + // If empty, the output is compact JSON. Otherwise, every JSON object + // entry and JSON array value will be on its own line. + // Each line will be preceded by repeated copies of Indent, where the + // number of copies is the current indentation depth. + Indent string + + // AnyResolver is used to resolve the google.protobuf.Any well-known type. + // If unset, the global registry is used by default. + AnyResolver AnyResolver +} + +// JSONPBMarshaler is implemented by protobuf messages that customize the +// way they are marshaled to JSON. Messages that implement this should also +// implement JSONPBUnmarshaler so that the custom format can be parsed. +// +// The JSON marshaling must follow the proto to JSON specification: +// https://developers.google.com/protocol-buffers/docs/proto3#json +// +// Deprecated: Custom types should implement protobuf reflection instead. +type JSONPBMarshaler interface { + MarshalJSONPB(*Marshaler) ([]byte, error) +} + +// Marshal serializes a protobuf message as JSON into w. +func (jm *Marshaler) Marshal(w io.Writer, m proto.Message) error { + b, err := jm.marshal(m) + if len(b) > 0 { + if _, err := w.Write(b); err != nil { + return err + } + } + return err +} + +// MarshalToString serializes a protobuf message as JSON in string form. +func (jm *Marshaler) MarshalToString(m proto.Message) (string, error) { + b, err := jm.marshal(m) + if err != nil { + return "", err + } + return string(b), nil +} + +func (jm *Marshaler) marshal(m proto.Message) ([]byte, error) { + v := reflect.ValueOf(m) + if m == nil || (v.Kind() == reflect.Ptr && v.IsNil()) { + return nil, errors.New("Marshal called with nil") + } + + // Check for custom marshalers first since they may not properly + // implement protobuf reflection that the logic below relies on. + if jsm, ok := m.(JSONPBMarshaler); ok { + return jsm.MarshalJSONPB(jm) + } + + if wrapJSONMarshalV2 { + opts := protojson.MarshalOptions{ + UseProtoNames: jm.OrigName, + UseEnumNumbers: jm.EnumsAsInts, + EmitUnpopulated: jm.EmitDefaults, + Indent: jm.Indent, + } + if jm.AnyResolver != nil { + opts.Resolver = anyResolver{jm.AnyResolver} + } + return opts.Marshal(proto.MessageReflect(m).Interface()) + } else { + // Check for unpopulated required fields first. + m2 := proto.MessageReflect(m) + if err := protoV2.CheckInitialized(m2.Interface()); err != nil { + return nil, err + } + + w := jsonWriter{Marshaler: jm} + err := w.marshalMessage(m2, "", "") + return w.buf, err + } +} + +type jsonWriter struct { + *Marshaler + buf []byte +} + +func (w *jsonWriter) write(s string) { + w.buf = append(w.buf, s...) +} + +func (w *jsonWriter) marshalMessage(m protoreflect.Message, indent, typeURL string) error { + if jsm, ok := proto.MessageV1(m.Interface()).(JSONPBMarshaler); ok { + b, err := jsm.MarshalJSONPB(w.Marshaler) + if err != nil { + return err + } + if typeURL != "" { + // we are marshaling this object to an Any type + var js map[string]*json.RawMessage + if err = json.Unmarshal(b, &js); err != nil { + return fmt.Errorf("type %T produced invalid JSON: %v", m.Interface(), err) + } + turl, err := json.Marshal(typeURL) + if err != nil { + return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err) + } + js["@type"] = (*json.RawMessage)(&turl) + if b, err = json.Marshal(js); err != nil { + return err + } + } + w.write(string(b)) + return nil + } + + md := m.Descriptor() + fds := md.Fields() + + // Handle well-known types. + const secondInNanos = int64(time.Second / time.Nanosecond) + switch wellKnownType(md.FullName()) { + case "Any": + return w.marshalAny(m, indent) + case "BoolValue", "BytesValue", "StringValue", + "Int32Value", "UInt32Value", "FloatValue", + "Int64Value", "UInt64Value", "DoubleValue": + fd := fds.ByNumber(1) + return w.marshalValue(fd, m.Get(fd), indent) + case "Duration": + const maxSecondsInDuration = 315576000000 + // "Generated output always contains 0, 3, 6, or 9 fractional digits, + // depending on required precision." + s := m.Get(fds.ByNumber(1)).Int() + ns := m.Get(fds.ByNumber(2)).Int() + if s < -maxSecondsInDuration || s > maxSecondsInDuration { + return fmt.Errorf("seconds out of range %v", s) + } + if ns <= -secondInNanos || ns >= secondInNanos { + return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos) + } + if (s > 0 && ns < 0) || (s < 0 && ns > 0) { + return errors.New("signs of seconds and nanos do not match") + } + var sign string + if s < 0 || ns < 0 { + sign, s, ns = "-", -1*s, -1*ns + } + x := fmt.Sprintf("%s%d.%09d", sign, s, ns) + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + w.write(fmt.Sprintf(`"%vs"`, x)) + return nil + case "Timestamp": + // "RFC 3339, where generated output will always be Z-normalized + // and uses 0, 3, 6 or 9 fractional digits." + s := m.Get(fds.ByNumber(1)).Int() + ns := m.Get(fds.ByNumber(2)).Int() + if ns < 0 || ns >= secondInNanos { + return fmt.Errorf("ns out of range [0, %v)", secondInNanos) + } + t := time.Unix(s, ns).UTC() + // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits). + x := t.Format("2006-01-02T15:04:05.000000000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + w.write(fmt.Sprintf(`"%vZ"`, x)) + return nil + case "Value": + // JSON value; which is a null, number, string, bool, object, or array. + od := md.Oneofs().Get(0) + fd := m.WhichOneof(od) + if fd == nil { + return errors.New("nil Value") + } + return w.marshalValue(fd, m.Get(fd), indent) + case "Struct", "ListValue": + // JSON object or array. + fd := fds.ByNumber(1) + return w.marshalValue(fd, m.Get(fd), indent) + } + + w.write("{") + if w.Indent != "" { + w.write("\n") + } + + firstField := true + if typeURL != "" { + if err := w.marshalTypeURL(indent, typeURL); err != nil { + return err + } + firstField = false + } + + for i := 0; i < fds.Len(); { + fd := fds.Get(i) + if od := fd.ContainingOneof(); od != nil { + fd = m.WhichOneof(od) + i += od.Fields().Len() + if fd == nil { + continue + } + } else { + i++ + } + + v := m.Get(fd) + + if !m.Has(fd) { + if !w.EmitDefaults || fd.ContainingOneof() != nil { + continue + } + if fd.Cardinality() != protoreflect.Repeated && (fd.Message() != nil || fd.Syntax() == protoreflect.Proto2) { + v = protoreflect.Value{} // use "null" for singular messages or proto2 scalars + } + } + + if !firstField { + w.writeComma() + } + if err := w.marshalField(fd, v, indent); err != nil { + return err + } + firstField = false + } + + // Handle proto2 extensions. + if md.ExtensionRanges().Len() > 0 { + // Collect a sorted list of all extension descriptor and values. + type ext struct { + desc protoreflect.FieldDescriptor + val protoreflect.Value + } + var exts []ext + m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + if fd.IsExtension() { + exts = append(exts, ext{fd, v}) + } + return true + }) + sort.Slice(exts, func(i, j int) bool { + return exts[i].desc.Number() < exts[j].desc.Number() + }) + + for _, ext := range exts { + if !firstField { + w.writeComma() + } + if err := w.marshalField(ext.desc, ext.val, indent); err != nil { + return err + } + firstField = false + } + } + + if w.Indent != "" { + w.write("\n") + w.write(indent) + } + w.write("}") + return nil +} + +func (w *jsonWriter) writeComma() { + if w.Indent != "" { + w.write(",\n") + } else { + w.write(",") + } +} + +func (w *jsonWriter) marshalAny(m protoreflect.Message, indent string) error { + // "If the Any contains a value that has a special JSON mapping, + // it will be converted as follows: {"@type": xxx, "value": yyy}. + // Otherwise, the value will be converted into a JSON object, + // and the "@type" field will be inserted to indicate the actual data type." + md := m.Descriptor() + typeURL := m.Get(md.Fields().ByNumber(1)).String() + rawVal := m.Get(md.Fields().ByNumber(2)).Bytes() + + var m2 protoreflect.Message + if w.AnyResolver != nil { + mi, err := w.AnyResolver.Resolve(typeURL) + if err != nil { + return err + } + m2 = proto.MessageReflect(mi) + } else { + mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL) + if err != nil { + return err + } + m2 = mt.New() + } + + if err := protoV2.Unmarshal(rawVal, m2.Interface()); err != nil { + return err + } + + if wellKnownType(m2.Descriptor().FullName()) == "" { + return w.marshalMessage(m2, indent, typeURL) + } + + w.write("{") + if w.Indent != "" { + w.write("\n") + } + if err := w.marshalTypeURL(indent, typeURL); err != nil { + return err + } + w.writeComma() + if w.Indent != "" { + w.write(indent) + w.write(w.Indent) + w.write(`"value": `) + } else { + w.write(`"value":`) + } + if err := w.marshalMessage(m2, indent+w.Indent, ""); err != nil { + return err + } + if w.Indent != "" { + w.write("\n") + w.write(indent) + } + w.write("}") + return nil +} + +func (w *jsonWriter) marshalTypeURL(indent, typeURL string) error { + if w.Indent != "" { + w.write(indent) + w.write(w.Indent) + } + w.write(`"@type":`) + if w.Indent != "" { + w.write(" ") + } + b, err := json.Marshal(typeURL) + if err != nil { + return err + } + w.write(string(b)) + return nil +} + +// marshalField writes field description and value to the Writer. +func (w *jsonWriter) marshalField(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error { + if w.Indent != "" { + w.write(indent) + w.write(w.Indent) + } + w.write(`"`) + switch { + case fd.IsExtension(): + // For message set, use the fname of the message as the extension name. + name := string(fd.FullName()) + if isMessageSet(fd.ContainingMessage()) { + name = strings.TrimSuffix(name, ".message_set_extension") + } + + w.write("[" + name + "]") + case w.OrigName: + name := string(fd.Name()) + if fd.Kind() == protoreflect.GroupKind { + name = string(fd.Message().Name()) + } + w.write(name) + default: + w.write(string(fd.JSONName())) + } + w.write(`":`) + if w.Indent != "" { + w.write(" ") + } + return w.marshalValue(fd, v, indent) +} + +func (w *jsonWriter) marshalValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error { + switch { + case fd.IsList(): + w.write("[") + comma := "" + lv := v.List() + for i := 0; i < lv.Len(); i++ { + w.write(comma) + if w.Indent != "" { + w.write("\n") + w.write(indent) + w.write(w.Indent) + w.write(w.Indent) + } + if err := w.marshalSingularValue(fd, lv.Get(i), indent+w.Indent); err != nil { + return err + } + comma = "," + } + if w.Indent != "" { + w.write("\n") + w.write(indent) + w.write(w.Indent) + } + w.write("]") + return nil + case fd.IsMap(): + kfd := fd.MapKey() + vfd := fd.MapValue() + mv := v.Map() + + // Collect a sorted list of all map keys and values. + type entry struct{ key, val protoreflect.Value } + var entries []entry + mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { + entries = append(entries, entry{k.Value(), v}) + return true + }) + sort.Slice(entries, func(i, j int) bool { + switch kfd.Kind() { + case protoreflect.BoolKind: + return !entries[i].key.Bool() && entries[j].key.Bool() + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + return entries[i].key.Int() < entries[j].key.Int() + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + return entries[i].key.Uint() < entries[j].key.Uint() + case protoreflect.StringKind: + return entries[i].key.String() < entries[j].key.String() + default: + panic("invalid kind") + } + }) + + w.write(`{`) + comma := "" + for _, entry := range entries { + w.write(comma) + if w.Indent != "" { + w.write("\n") + w.write(indent) + w.write(w.Indent) + w.write(w.Indent) + } + + s := fmt.Sprint(entry.key.Interface()) + b, err := json.Marshal(s) + if err != nil { + return err + } + w.write(string(b)) + + w.write(`:`) + if w.Indent != "" { + w.write(` `) + } + + if err := w.marshalSingularValue(vfd, entry.val, indent+w.Indent); err != nil { + return err + } + comma = "," + } + if w.Indent != "" { + w.write("\n") + w.write(indent) + w.write(w.Indent) + } + w.write(`}`) + return nil + default: + return w.marshalSingularValue(fd, v, indent) + } +} + +func (w *jsonWriter) marshalSingularValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error { + switch { + case !v.IsValid(): + w.write("null") + return nil + case fd.Message() != nil: + return w.marshalMessage(v.Message(), indent+w.Indent, "") + case fd.Enum() != nil: + if fd.Enum().FullName() == "google.protobuf.NullValue" { + w.write("null") + return nil + } + + vd := fd.Enum().Values().ByNumber(v.Enum()) + if vd == nil || w.EnumsAsInts { + w.write(strconv.Itoa(int(v.Enum()))) + } else { + w.write(`"` + string(vd.Name()) + `"`) + } + return nil + default: + switch v.Interface().(type) { + case float32, float64: + switch { + case math.IsInf(v.Float(), +1): + w.write(`"Infinity"`) + return nil + case math.IsInf(v.Float(), -1): + w.write(`"-Infinity"`) + return nil + case math.IsNaN(v.Float()): + w.write(`"NaN"`) + return nil + } + case int64, uint64: + w.write(fmt.Sprintf(`"%d"`, v.Interface())) + return nil + } + + b, err := json.Marshal(v.Interface()) + if err != nil { + return err + } + w.write(string(b)) + return nil + } +} diff --git a/providerlint/vendor/github.com/golang/protobuf/jsonpb/json.go b/providerlint/vendor/github.com/golang/protobuf/jsonpb/json.go new file mode 100644 index 00000000000..480e2448de6 --- /dev/null +++ b/providerlint/vendor/github.com/golang/protobuf/jsonpb/json.go @@ -0,0 +1,69 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package jsonpb provides functionality to marshal and unmarshal between a +// protocol buffer message and JSON. It follows the specification at +// https://developers.google.com/protocol-buffers/docs/proto3#json. +// +// Do not rely on the default behavior of the standard encoding/json package +// when called on generated message types as it does not operate correctly. +// +// Deprecated: Use the "google.golang.org/protobuf/encoding/protojson" +// package instead. +package jsonpb + +import ( + "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/runtime/protoimpl" +) + +// AnyResolver takes a type URL, present in an Any message, +// and resolves it into an instance of the associated message. +type AnyResolver interface { + Resolve(typeURL string) (proto.Message, error) +} + +type anyResolver struct{ AnyResolver } + +func (r anyResolver) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) { + return r.FindMessageByURL(string(message)) +} + +func (r anyResolver) FindMessageByURL(url string) (protoreflect.MessageType, error) { + m, err := r.Resolve(url) + if err != nil { + return nil, err + } + return protoimpl.X.MessageTypeOf(m), nil +} + +func (r anyResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { + return protoregistry.GlobalTypes.FindExtensionByName(field) +} + +func (r anyResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { + return protoregistry.GlobalTypes.FindExtensionByNumber(message, field) +} + +func wellKnownType(s protoreflect.FullName) string { + if s.Parent() == "google.protobuf" { + switch s.Name() { + case "Empty", "Any", + "BoolValue", "BytesValue", "StringValue", + "Int32Value", "UInt32Value", "FloatValue", + "Int64Value", "UInt64Value", "DoubleValue", + "Duration", "Timestamp", + "NullValue", "Struct", "Value", "ListValue": + return string(s.Name()) + } + } + return "" +} + +func isMessageSet(md protoreflect.MessageDescriptor) bool { + ms, ok := md.(interface{ IsMessageSet() bool }) + return ok && ms.IsMessageSet() +} diff --git a/providerlint/vendor/github.com/hashicorp/go-plugin/README.md b/providerlint/vendor/github.com/hashicorp/go-plugin/README.md index 46ee09fc0ca..39391f24fe4 100644 --- a/providerlint/vendor/github.com/hashicorp/go-plugin/README.md +++ b/providerlint/vendor/github.com/hashicorp/go-plugin/README.md @@ -3,8 +3,9 @@ `go-plugin` is a Go (golang) plugin system over RPC. It is the plugin system that has been in use by HashiCorp tooling for over 4 years. While initially created for [Packer](https://www.packer.io), it is additionally in use by -[Terraform](https://www.terraform.io), [Nomad](https://www.nomadproject.io), and -[Vault](https://www.vaultproject.io). +[Terraform](https://www.terraform.io), [Nomad](https://www.nomadproject.io), +[Vault](https://www.vaultproject.io), and +[Boundary](https://www.boundaryproject.io). While the plugin system is over RPC, it is currently only designed to work over a local [reliable] network. Plugins over a real network are not supported diff --git a/providerlint/vendor/github.com/hashicorp/go-plugin/client.go b/providerlint/vendor/github.com/hashicorp/go-plugin/client.go index 67dca883576..e0bee88a1d4 100644 --- a/providerlint/vendor/github.com/hashicorp/go-plugin/client.go +++ b/providerlint/vendor/github.com/hashicorp/go-plugin/client.go @@ -574,6 +574,8 @@ func (c *Client) Start() (addr net.Addr, err error) { c.config.TLSConfig = &tls.Config{ Certificates: []tls.Certificate{cert}, + ClientAuth: tls.RequireAndVerifyClientCert, + MinVersion: tls.VersionTLS12, ServerName: "localhost", } } @@ -629,17 +631,19 @@ func (c *Client) Start() (addr net.Addr, err error) { // Wait for the command to end. err := cmd.Wait() - debugMsgArgs := []interface{}{ + msgArgs := []interface{}{ "path", path, "pid", pid, } if err != nil { - debugMsgArgs = append(debugMsgArgs, + msgArgs = append(msgArgs, []interface{}{"error", err.Error()}...) + c.logger.Error("plugin process exited", msgArgs...) + } else { + // Log and make sure to flush the logs right away + c.logger.Info("plugin process exited", msgArgs...) } - // Log and make sure to flush the logs write away - c.logger.Debug("plugin process exited", debugMsgArgs...) os.Stderr.Sync() // Set that we exited, which takes a lock @@ -774,7 +778,7 @@ func (c *Client) Start() (addr net.Addr, err error) { } // loadServerCert is used by AutoMTLS to read an x.509 cert returned by the -// server, and load it as the RootCA for the client TLSConfig. +// server, and load it as the RootCA and ClientCA for the client TLSConfig. func (c *Client) loadServerCert(cert string) error { certPool := x509.NewCertPool() @@ -791,6 +795,7 @@ func (c *Client) loadServerCert(cert string) error { certPool.AddCert(x509Cert) c.config.TLSConfig.RootCAs = certPool + c.config.TLSConfig.ClientCAs = certPool return nil } diff --git a/providerlint/vendor/github.com/hashicorp/go-plugin/go.mod b/providerlint/vendor/github.com/hashicorp/go-plugin/go.mod index 4e182e6258f..f2885221524 100644 --- a/providerlint/vendor/github.com/hashicorp/go-plugin/go.mod +++ b/providerlint/vendor/github.com/hashicorp/go-plugin/go.mod @@ -1,6 +1,6 @@ module github.com/hashicorp/go-plugin -go 1.13 +go 1.17 require ( github.com/golang/protobuf v1.3.4 @@ -9,7 +9,16 @@ require ( github.com/jhump/protoreflect v1.6.0 github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77 github.com/oklog/run v1.0.0 - github.com/stretchr/testify v1.3.0 // indirect golang.org/x/net v0.0.0-20190311183353-d8887717615a google.golang.org/grpc v1.27.1 ) + +require ( + github.com/fatih/color v1.7.0 // indirect + github.com/mattn/go-colorable v0.1.4 // indirect + github.com/mattn/go-isatty v0.0.10 // indirect + github.com/stretchr/testify v1.3.0 // indirect + golang.org/x/sys v0.0.0-20191008105621-543471e840be // indirect + golang.org/x/text v0.3.0 // indirect + google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 // indirect +) diff --git a/providerlint/vendor/github.com/hashicorp/go-plugin/go.sum b/providerlint/vendor/github.com/hashicorp/go-plugin/go.sum index 56062044ee4..93d2905cdc3 100644 --- a/providerlint/vendor/github.com/hashicorp/go-plugin/go.sum +++ b/providerlint/vendor/github.com/hashicorp/go-plugin/go.sum @@ -2,7 +2,6 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -13,7 +12,6 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -50,7 +48,6 @@ golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvx golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/net v0.0.0-20180530234432-1e491301e022/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= @@ -60,7 +57,6 @@ golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20191008105621-543471e840be h1:QAcqgptGM8IQBC9K/RC4o+O9YmqEm0diQn9QmZw/0mU= @@ -74,7 +70,6 @@ golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBn google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20170818010345-ee236bd376b0/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= diff --git a/providerlint/vendor/github.com/hashicorp/go-plugin/process_posix.go b/providerlint/vendor/github.com/hashicorp/go-plugin/process_posix.go index 70ba546bf6d..185957f8d11 100644 --- a/providerlint/vendor/github.com/hashicorp/go-plugin/process_posix.go +++ b/providerlint/vendor/github.com/hashicorp/go-plugin/process_posix.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package plugin diff --git a/providerlint/vendor/github.com/hashicorp/go-plugin/rpc_server.go b/providerlint/vendor/github.com/hashicorp/go-plugin/rpc_server.go index 5bb18dd5db1..449ba6cc1ee 100644 --- a/providerlint/vendor/github.com/hashicorp/go-plugin/rpc_server.go +++ b/providerlint/vendor/github.com/hashicorp/go-plugin/rpc_server.go @@ -45,7 +45,11 @@ func (s *RPCServer) Serve(lis net.Listener) { for { conn, err := lis.Accept() if err != nil { - log.Printf("[ERR] plugin: plugin server: %s", err) + severity := "ERR" + if errors.Is(err, net.ErrClosed) { + severity = "DEBUG" + } + log.Printf("[%s] plugin: plugin server: %s", severity, err) return } diff --git a/providerlint/vendor/github.com/hashicorp/go-plugin/server.go b/providerlint/vendor/github.com/hashicorp/go-plugin/server.go index 7a58cc39197..e134999103f 100644 --- a/providerlint/vendor/github.com/hashicorp/go-plugin/server.go +++ b/providerlint/vendor/github.com/hashicorp/go-plugin/server.go @@ -304,13 +304,13 @@ func Serve(opts *ServeConfig) { certPEM, keyPEM, err := generateCert() if err != nil { - logger.Error("failed to generate client certificate", "error", err) + logger.Error("failed to generate server certificate", "error", err) panic(err) } cert, err := tls.X509KeyPair(certPEM, keyPEM) if err != nil { - logger.Error("failed to parse client certificate", "error", err) + logger.Error("failed to parse server certificate", "error", err) panic(err) } @@ -319,6 +319,8 @@ func Serve(opts *ServeConfig) { ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: clientCertPool, MinVersion: tls.VersionTLS12, + RootCAs: clientCertPool, + ServerName: "localhost", } // We send back the raw leaf cert data for the client rather than the diff --git a/providerlint/vendor/github.com/hashicorp/go-version/CHANGELOG.md b/providerlint/vendor/github.com/hashicorp/go-version/CHANGELOG.md index 2020c472743..094550020e9 100644 --- a/providerlint/vendor/github.com/hashicorp/go-version/CHANGELOG.md +++ b/providerlint/vendor/github.com/hashicorp/go-version/CHANGELOG.md @@ -1,4 +1,4 @@ -# 1.4.0 (January 5, 2021) +# 1.4.0 (January 5, 2022) FEATURES: diff --git a/providerlint/vendor/github.com/hashicorp/go-version/README.md b/providerlint/vendor/github.com/hashicorp/go-version/README.md index 851a337beb4..4d250509033 100644 --- a/providerlint/vendor/github.com/hashicorp/go-version/README.md +++ b/providerlint/vendor/github.com/hashicorp/go-version/README.md @@ -1,5 +1,5 @@ # Versioning Library for Go -[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/master.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/master) +[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/main.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/main) [![GoDoc](https://godoc.org/github.com/hashicorp/go-version?status.svg)](https://godoc.org/github.com/hashicorp/go-version) go-version is a library for parsing versions and version constraints, diff --git a/providerlint/vendor/github.com/hashicorp/go-version/version.go b/providerlint/vendor/github.com/hashicorp/go-version/version.go index 116a74466db..e87df69906d 100644 --- a/providerlint/vendor/github.com/hashicorp/go-version/version.go +++ b/providerlint/vendor/github.com/hashicorp/go-version/version.go @@ -388,3 +388,20 @@ func (v *Version) String() string { func (v *Version) Original() string { return v.original } + +// UnmarshalText implements encoding.TextUnmarshaler interface. +func (v *Version) UnmarshalText(b []byte) error { + temp, err := NewVersion(string(b)) + if err != nil { + return err + } + + *v = *temp + + return nil +} + +// MarshalText implements encoding.TextMarshaler interface. +func (v *Version) MarshalText() ([]byte, error) { + return []byte(v.String()), nil +} diff --git a/providerlint/vendor/github.com/hashicorp/terraform-json/config.go b/providerlint/vendor/github.com/hashicorp/terraform-json/config.go index e093cfa8bff..5ebe4bc840c 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-json/config.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-json/config.go @@ -48,6 +48,9 @@ type ProviderConfig struct { // The name of the provider, ie: "aws". Name string `json:"name,omitempty"` + // The fully-specified name of the provider, ie: "registry.terraform.io/hashicorp/aws". + FullName string `json:"full_name,omitempty"` + // The alias of the provider, ie: "us-east-1". Alias string `json:"alias,omitempty"` diff --git a/providerlint/vendor/github.com/hashicorp/terraform-json/go.mod b/providerlint/vendor/github.com/hashicorp/terraform-json/go.mod index a04aeeac97a..76514d4741c 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-json/go.mod +++ b/providerlint/vendor/github.com/hashicorp/terraform-json/go.mod @@ -4,9 +4,10 @@ go 1.13 require ( github.com/davecgh/go-spew v1.1.1 - github.com/google/go-cmp v0.5.6 - github.com/hashicorp/go-version v1.3.0 + github.com/google/go-cmp v0.5.8 + github.com/hashicorp/go-version v1.5.0 github.com/mitchellh/copystructure v1.2.0 github.com/sebdah/goldie v1.0.0 - github.com/zclconf/go-cty v1.9.1 + github.com/zclconf/go-cty v1.10.0 + github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b ) diff --git a/providerlint/vendor/github.com/hashicorp/terraform-json/go.sum b/providerlint/vendor/github.com/hashicorp/terraform-json/go.sum index 51d9bd15286..cf933f2408b 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-json/go.sum +++ b/providerlint/vendor/github.com/hashicorp/terraform-json/go.sum @@ -1,17 +1,20 @@ +github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= -github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/hashicorp/go-version v1.3.0 h1:McDWVJIU/y+u1BRV06dPaLfLCaT7fUTJLp5r04x7iNw= -github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/hashicorp/go-version v1.5.0 h1:O293SZ2Eg+AAYijkVK3jR786Am1bhDEh2GHT0tIVE5E= +github.com/hashicorp/go-version v1.5.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= @@ -23,20 +26,25 @@ github.com/sebdah/goldie v1.0.0/go.mod h1:jXP4hmWywNEwZzhMuv2ccnqTSFpuq8iyQhtQdk github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= -github.com/zclconf/go-cty v1.9.1 h1:viqrgQwFl5UpSxc046qblj78wZXVDFnSOufaOTER+cc= -github.com/zclconf/go-cty v1.9.1/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= +github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= +github.com/zclconf/go-cty v1.10.0 h1:mp9ZXQeIcN8kAwuqorjH+Q+njbJKjLrvB2yIh4q7U+0= +github.com/zclconf/go-cty v1.10.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= +github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b h1:FosyBZYxY34Wul7O/MSKey3txpPYyCqVO5ZyceuQJEI= +github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b/go.mod h1:ZRKQfBXbGkpdV6QMzT3rU1kSTAnfu1dO8dPKjYprgj8= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/providerlint/vendor/github.com/hashicorp/terraform-json/plan.go b/providerlint/vendor/github.com/hashicorp/terraform-json/plan.go index 1de5bc82a09..274006a0180 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-json/plan.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-json/plan.go @@ -55,6 +55,19 @@ type Plan struct { // The Terraform configuration used to make the plan. Config *Config `json:"configuration,omitempty"` + + // RelevantAttributes represents any resource instances and their + // attributes which may have contributed to the planned changes + RelevantAttributes []ResourceAttribute `json:"relevant_attributes,omitempty"` +} + +// ResourceAttribute describes a full path to a resource attribute +type ResourceAttribute struct { + // Resource describes resource instance address (e.g. null_resource.foo) + Resource string `json:"resource"` + // Attribute describes the attribute path using a lossy representation + // of cty.Path. (e.g. ["id"] or ["objects", 0, "val"]). + Attribute []json.RawMessage `json:"attribute"` } // Validate checks to ensure that the plan is present, and the diff --git a/providerlint/vendor/github.com/hashicorp/terraform-json/schemas.go b/providerlint/vendor/github.com/hashicorp/terraform-json/schemas.go index 2360231d00f..027224b620a 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-json/schemas.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-json/schemas.go @@ -223,6 +223,13 @@ type SchemaAttribute struct { Sensitive bool `json:"sensitive,omitempty"` } +// jsonSchemaAttribute describes an attribute within a schema block +// in a middle-step internal representation before marshalled into +// a more useful SchemaAttribute with cty.Type. +// +// This avoid panic on marshalling cty.NilType (from cty upstream) +// which the default Go marshaller cannot ignore because it's a +// not nil-able struct. type jsonSchemaAttribute struct { AttributeType json.RawMessage `json:"type,omitempty"` AttributeNestedType *SchemaNestedAttributeType `json:"nested_type,omitempty"` diff --git a/providerlint/vendor/github.com/hashicorp/terraform-json/state.go b/providerlint/vendor/github.com/hashicorp/terraform-json/state.go index bece5c22021..3c3f6a4b0aa 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-json/state.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-json/state.go @@ -7,6 +7,7 @@ import ( "fmt" "github.com/hashicorp/go-version" + "github.com/zclconf/go-cty/cty" ) // StateFormatVersionConstraints defines the versions of the JSON state format @@ -175,4 +176,31 @@ type StateOutput struct { // The value of the output. Value interface{} `json:"value,omitempty"` + + // The type of the output. + Type cty.Type `json:"type,omitempty"` +} + +// jsonStateOutput describes an output value in a middle-step internal +// representation before marshalled into a more useful StateOutput with cty.Type. +// +// This avoid panic on marshalling cty.NilType (from cty upstream) +// which the default Go marshaller cannot ignore because it's a +// not nil-able struct. +type jsonStateOutput struct { + Sensitive bool `json:"sensitive"` + Value interface{} `json:"value,omitempty"` + Type json.RawMessage `json:"type,omitempty"` +} + +func (so *StateOutput) MarshalJSON() ([]byte, error) { + jsonSa := &jsonStateOutput{ + Sensitive: so.Sensitive, + Value: so.Value, + } + if so.Type != cty.NilType { + outputType, _ := so.Type.MarshalJSON() + jsonSa.Type = outputType + } + return json.Marshal(jsonSa) } diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value.go index c2c26feb5e6..4d7b749894e 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value.go @@ -440,7 +440,7 @@ func (val Value) As(dst interface{}) error { if !ok { return fmt.Errorf("can't unmarshal %s into %T, expected *big.Float", val.Type(), dst) } - target.Set(v) + target.Copy(v) return nil case **big.Float: if val.IsNull() { diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_msgpack.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_msgpack.go index 40857da7547..c4047aeab2b 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_msgpack.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_msgpack.go @@ -74,7 +74,7 @@ func msgpackUnmarshal(dec *msgpack.Decoder, typ Type, path *AttributePath) (Valu if err != nil { return Value{}, path.NewErrorf("couldn't decode number as int64: %w", err) } - return NewValue(Number, big.NewFloat(float64(rv))), nil + return NewValue(Number, new(big.Float).SetInt64(rv)), nil } switch peek { case msgpackCodes.Int8, msgpackCodes.Int16, msgpackCodes.Int32, msgpackCodes.Int64: @@ -82,13 +82,13 @@ func msgpackUnmarshal(dec *msgpack.Decoder, typ Type, path *AttributePath) (Valu if err != nil { return Value{}, path.NewErrorf("couldn't decode number as int64: %w", err) } - return NewValue(Number, big.NewFloat(float64(rv))), nil + return NewValue(Number, new(big.Float).SetInt64(rv)), nil case msgpackCodes.Uint8, msgpackCodes.Uint16, msgpackCodes.Uint32, msgpackCodes.Uint64: rv, err := dec.DecodeUint64() if err != nil { return Value{}, path.NewErrorf("couldn't decode number as uint64: %w", err) } - return NewValue(Number, big.NewFloat(float64(rv))), nil + return NewValue(Number, new(big.Float).SetUint64(rv)), nil case msgpackCodes.Float, msgpackCodes.Double: rv, err := dec.DecodeFloat64() if err != nil { diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go index d9bc172ea9a..9e52348d69d 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go @@ -19,17 +19,108 @@ import ( testing "github.com/mitchellh/go-testing-interface" ) +// protov5ProviderFactory is a function which is called to start a protocol +// version 5 provider server. +type protov5ProviderFactory func() (tfprotov5.ProviderServer, error) + +// protov5ProviderFactories is a mapping of provider addresses to provider +// factory for protocol version 5 provider servers. +type protov5ProviderFactories map[string]func() (tfprotov5.ProviderServer, error) + +// merge combines provider factories. +// +// In case of an overlapping entry, the later entry will overwrite the previous +// value. +func (pf protov5ProviderFactories) merge(otherPfs ...protov5ProviderFactories) protov5ProviderFactories { + result := make(protov5ProviderFactories) + + for name, providerFactory := range pf { + result[name] = providerFactory + } + + for _, otherPf := range otherPfs { + for name, providerFactory := range otherPf { + result[name] = providerFactory + } + } + + return result +} + +// protov6ProviderFactory is a function which is called to start a protocol +// version 6 provider server. +type protov6ProviderFactory func() (tfprotov6.ProviderServer, error) + +// protov6ProviderFactories is a mapping of provider addresses to provider +// factory for protocol version 6 provider servers. +type protov6ProviderFactories map[string]func() (tfprotov6.ProviderServer, error) + +// merge combines provider factories. +// +// In case of an overlapping entry, the later entry will overwrite the previous +// value. +func (pf protov6ProviderFactories) merge(otherPfs ...protov6ProviderFactories) protov6ProviderFactories { + result := make(protov6ProviderFactories) + + for name, providerFactory := range pf { + result[name] = providerFactory + } + + for _, otherPf := range otherPfs { + for name, providerFactory := range otherPf { + result[name] = providerFactory + } + } + + return result +} + +// sdkProviderFactory is a function which is called to start a SDK provider +// server. +type sdkProviderFactory func() (*schema.Provider, error) + +// protov6ProviderFactories is a mapping of provider addresses to provider +// factory for protocol version 6 provider servers. +type sdkProviderFactories map[string]func() (*schema.Provider, error) + +// merge combines provider factories. +// +// In case of an overlapping entry, the later entry will overwrite the previous +// value. +func (pf sdkProviderFactories) merge(otherPfs ...sdkProviderFactories) sdkProviderFactories { + result := make(sdkProviderFactories) + + for name, providerFactory := range pf { + result[name] = providerFactory + } + + for _, otherPf := range otherPfs { + for name, providerFactory := range otherPf { + result[name] = providerFactory + } + } + + return result +} + type providerFactories struct { - legacy map[string]func() (*schema.Provider, error) - protov5 map[string]func() (tfprotov5.ProviderServer, error) - protov6 map[string]func() (tfprotov6.ProviderServer, error) + legacy sdkProviderFactories + protov5 protov5ProviderFactories + protov6 protov6ProviderFactories } -func runProviderCommand(ctx context.Context, t testing.T, f func() error, wd *plugintest.WorkingDir, factories providerFactories) error { +func runProviderCommand(ctx context.Context, t testing.T, f func() error, wd *plugintest.WorkingDir, factories *providerFactories) error { // don't point to this as a test failure location // point to whatever called it t.Helper() + // This should not happen, but prevent panics just in case. + if factories == nil { + err := fmt.Errorf("Provider factories are missing to run Terraform command. Please report this bug in the testing framework.") + logging.HelperResourceError(ctx, err.Error()) + return err + } + // Run the providers in the same process as the test runner using the // reattach behavior in Terraform. This ensures we get test coverage // and enables the use of delve as a debugger. diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_providers.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_providers.go new file mode 100644 index 00000000000..c09e4657cc2 --- /dev/null +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_providers.go @@ -0,0 +1,56 @@ +package resource + +import ( + "context" + "fmt" + "strings" +) + +// providerConfig takes the list of providers in a TestCase and returns a +// config with only empty provider blocks. This is useful for Import, where no +// config is provided, but the providers must be defined. +func (c TestCase) providerConfig(_ context.Context) string { + var providerBlocks, requiredProviderBlocks strings.Builder + + // [BF] The Providers field handling predates the logic being moved to this + // method. It's not entirely clear to me at this time why this field + // is being used and not the others, but leaving it here just in case + // it does have a special purpose that wasn't being unit tested prior. + for name := range c.Providers { + providerBlocks.WriteString(fmt.Sprintf("provider %q {}\n", name)) + } + + for name, externalProvider := range c.ExternalProviders { + providerBlocks.WriteString(fmt.Sprintf("provider %q {}\n", name)) + + if externalProvider.Source == "" && externalProvider.VersionConstraint == "" { + continue + } + + requiredProviderBlocks.WriteString(fmt.Sprintf(" %s = {\n", name)) + + if externalProvider.Source != "" { + requiredProviderBlocks.WriteString(fmt.Sprintf(" source = %q\n", externalProvider.Source)) + } + + if externalProvider.VersionConstraint != "" { + requiredProviderBlocks.WriteString(fmt.Sprintf(" version = %q\n", externalProvider.VersionConstraint)) + } + + requiredProviderBlocks.WriteString(" }\n") + } + + if requiredProviderBlocks.Len() > 0 { + return fmt.Sprintf(` +terraform { + required_providers { +%[1]s + } +} + +%[2]s +`, strings.TrimSuffix(requiredProviderBlocks.String(), "\n"), providerBlocks.String()) + } + + return providerBlocks.String() +} diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_validate.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_validate.go new file mode 100644 index 00000000000..39e5da46c9c --- /dev/null +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_validate.go @@ -0,0 +1,85 @@ +package resource + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" +) + +// hasProviders returns true if the TestCase has set any of the +// ExternalProviders, ProtoV5ProviderFactories, ProtoV6ProviderFactories, +// ProviderFactories, or Providers fields. +func (c TestCase) hasProviders(_ context.Context) bool { + if len(c.ExternalProviders) > 0 { + return true + } + + if len(c.ProtoV5ProviderFactories) > 0 { + return true + } + + if len(c.ProtoV6ProviderFactories) > 0 { + return true + } + + if len(c.ProviderFactories) > 0 { + return true + } + + if len(c.Providers) > 0 { + return true + } + + return false +} + +// validate ensures the TestCase is valid based on the following criteria: +// +// - No overlapping ExternalProviders and Providers entries +// - No overlapping ExternalProviders and ProviderFactories entries +// - TestStep validations performed by the (TestStep).validate() method. +// +func (c TestCase) validate(ctx context.Context) error { + logging.HelperResourceTrace(ctx, "Validating TestCase") + + if len(c.Steps) == 0 { + err := fmt.Errorf("TestCase missing Steps") + logging.HelperResourceError(ctx, "TestCase validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + for name := range c.ExternalProviders { + if _, ok := c.Providers[name]; ok { + err := fmt.Errorf("TestCase provider %q set in both ExternalProviders and Providers", name) + logging.HelperResourceError(ctx, "TestCase validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + if _, ok := c.ProviderFactories[name]; ok { + err := fmt.Errorf("TestCase provider %q set in both ExternalProviders and ProviderFactories", name) + logging.HelperResourceError(ctx, "TestCase validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + } + + testCaseHasProviders := c.hasProviders(ctx) + + for stepIndex, step := range c.Steps { + stepNumber := stepIndex + 1 // Use 1-based index for humans + stepValidateReq := testStepValidateRequest{ + StepNumber: stepNumber, + TestCaseHasProviders: testCaseHasProviders, + } + + err := step.validate(ctx, stepValidateReq) + + if err != nil { + err := fmt.Errorf("TestStep %d/%d validation error: %w", stepNumber, len(c.Steps), err) + logging.HelperResourceError(ctx, "TestCase validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + } + + return nil +} diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go index 45180d2c779..8047a2cdc85 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go @@ -318,6 +318,11 @@ type TestCase struct { // ProviderFactories can be specified for the providers that are valid. // + // This can also be specified at the TestStep level to enable per-step + // differences in providers, however all provider specifications must + // be done either at the TestCase level or TestStep level, otherwise the + // testing framework will raise an error and fail the test. + // // These are the providers that can be referenced within the test. Each key // is an individually addressable provider. Typically you will only pass a // single value here for the provider you are testing. Aliases are not @@ -339,6 +344,11 @@ type TestCase struct { // ProtoV5ProviderFactories serves the same purpose as ProviderFactories, // but for protocol v5 providers defined using the terraform-plugin-go // ProviderServer interface. + // + // This can also be specified at the TestStep level to enable per-step + // differences in providers, however all provider specifications must + // be done either at the TestCase level or TestStep level, otherwise the + // testing framework will raise an error and fail the test. ProtoV5ProviderFactories map[string]func() (tfprotov5.ProviderServer, error) // ProtoV6ProviderFactories serves the same purpose as ProviderFactories, @@ -346,6 +356,11 @@ type TestCase struct { // ProviderServer interface. // The version of Terraform used in acceptance testing must be greater // than or equal to v0.15.4 to use ProtoV6ProviderFactories. + // + // This can also be specified at the TestStep level to enable per-step + // differences in providers, however all provider specifications must + // be done either at the TestCase level or TestStep level, otherwise the + // testing framework will raise an error and fail the test. ProtoV6ProviderFactories map[string]func() (tfprotov6.ProviderServer, error) // Providers is the ResourceProvider that will be under test. @@ -354,11 +369,18 @@ type TestCase struct { Providers map[string]*schema.Provider // ExternalProviders are providers the TestCase relies on that should - // be downloaded from the registry during init. This is only really - // necessary to set if you're using import, as providers in your config - // will be automatically retrieved during init. Import doesn't use a - // config, however, so we allow manually specifying them here to be - // downloaded for import tests. + // be downloaded from the registry during init. + // + // This can also be specified at the TestStep level to enable per-step + // differences in providers, however all provider specifications must + // be done either at the TestCase level or TestStep level, otherwise the + // testing framework will raise an error and fail the test. + // + // This is generally unnecessary to set at the TestCase level, however + // it has existing in the testing framework prior to the introduction of + // TestStep level specification and was only necessary for performing + // import testing where the configuration contained a provider outside the + // one under test. ExternalProviders map[string]ExternalProvider // PreventPostDestroyRefresh can be set to true for cases where data sources @@ -540,6 +562,74 @@ type TestStep struct { // fields that can't be refreshed and don't matter. ImportStateVerify bool ImportStateVerifyIgnore []string + + // ProviderFactories can be specified for the providers that are valid for + // this TestStep. When providers are specified at the TestStep level, all + // TestStep within a TestCase must declare providers. + // + // This can also be specified at the TestCase level for all TestStep, + // however all provider specifications must be done either at the TestCase + // level or TestStep level, otherwise the testing framework will raise an + // error and fail the test. + // + // These are the providers that can be referenced within the test. Each key + // is an individually addressable provider. Typically you will only pass a + // single value here for the provider you are testing. Aliases are not + // supported by the test framework, so to use multiple provider instances, + // you should add additional copies to this map with unique names. To set + // their configuration, you would reference them similar to the following: + // + // provider "my_factory_key" { + // # ... + // } + // + // resource "my_resource" "mr" { + // provider = my_factory_key + // + // # ... + // } + ProviderFactories map[string]func() (*schema.Provider, error) + + // ProtoV5ProviderFactories serves the same purpose as ProviderFactories, + // but for protocol v5 providers defined using the terraform-plugin-go + // ProviderServer interface. When providers are specified at the TestStep + // level, all TestStep within a TestCase must declare providers. + // + // This can also be specified at the TestCase level for all TestStep, + // however all provider specifications must be done either at the TestCase + // level or TestStep level, otherwise the testing framework will raise an + // error and fail the test. + ProtoV5ProviderFactories map[string]func() (tfprotov5.ProviderServer, error) + + // ProtoV6ProviderFactories serves the same purpose as ProviderFactories, + // but for protocol v6 providers defined using the terraform-plugin-go + // ProviderServer interface. + // The version of Terraform used in acceptance testing must be greater + // than or equal to v0.15.4 to use ProtoV6ProviderFactories. When providers + // are specified at the TestStep level, all TestStep within a TestCase must + // declare providers. + // + // This can also be specified at the TestCase level for all TestStep, + // however all provider specifications must be done either at the TestCase + // level or TestStep level, otherwise the testing framework will raise an + // error and fail the test. + ProtoV6ProviderFactories map[string]func() (tfprotov6.ProviderServer, error) + + // ExternalProviders are providers the TestStep relies on that should + // be downloaded from the registry during init. When providers are + // specified at the TestStep level, all TestStep within a TestCase must + // declare providers. + // + // This can also be specified at the TestCase level for all TestStep, + // however all provider specifications must be done either at the TestCase + // level or TestStep level, otherwise the testing framework will raise an + // error and fail the test. + // + // Outside specifying an earlier version of the provider under test, + // typically for state upgrader testing, this is generally only necessary + // for performing import testing where the prior TestStep configuration + // contained a provider outside the one under test. + ExternalProviders map[string]ExternalProvider } // ParallelTest performs an acceptance test on a resource, allowing concurrency @@ -593,6 +683,16 @@ func Test(t testing.T, c TestCase) { ctx := context.Background() ctx = logging.InitTestContext(ctx, t) + err := c.validate(ctx) + + if err != nil { + logging.HelperResourceError(ctx, + "Test validation error", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("Test validation error: %s", err) + } + // We only run acceptance tests if an env var is set because they're // slow and generally require some outside configuration. You can opt out // of this with OverrideEnvVar on individual TestCases. @@ -608,9 +708,6 @@ func Test(t testing.T, c TestCase) { c.ProviderFactories = map[string]func() (*schema.Provider, error){} for name, p := range c.Providers { - if _, ok := c.ProviderFactories[name]; ok { - t.Fatalf("ProviderFactory for %q already exists, cannot overwrite with Provider", name) - } prov := p c.ProviderFactories[name] = func() (*schema.Provider, error) { //nolint:unparam // required signature return prov, nil @@ -648,43 +745,6 @@ func Test(t testing.T, c TestCase) { logging.HelperResourceDebug(ctx, "Finished TestCase") } -// testProviderConfig takes the list of Providers in a TestCase and returns a -// config with only empty provider blocks. This is useful for Import, where no -// config is provided, but the providers must be defined. -func testProviderConfig(c TestCase) (string, error) { - var lines []string - var requiredProviders []string - for p := range c.Providers { - lines = append(lines, fmt.Sprintf("provider %q {}\n", p)) - } - for p, v := range c.ExternalProviders { - if _, ok := c.Providers[p]; ok { - return "", fmt.Errorf("Provider %q set in both Providers and ExternalProviders for TestCase. Must be set in only one.", p) - } - if _, ok := c.ProviderFactories[p]; ok { - return "", fmt.Errorf("Provider %q set in both ProviderFactories and ExternalProviders for TestCase. Must be set in only one.", p) - } - lines = append(lines, fmt.Sprintf("provider %q {}\n", p)) - var providerBlock string - if v.VersionConstraint != "" { - providerBlock = fmt.Sprintf("%s\nversion = %q", providerBlock, v.VersionConstraint) - } - if v.Source != "" { - providerBlock = fmt.Sprintf("%s\nsource = %q", providerBlock, v.Source) - } - if providerBlock != "" { - providerBlock = fmt.Sprintf("%s = {%s\n}\n", p, providerBlock) - } - requiredProviders = append(requiredProviders, providerBlock) - } - - if len(requiredProviders) > 0 { - lines = append([]string{fmt.Sprintf("terraform {\nrequired_providers {\n%s}\n}\n\n", strings.Join(requiredProviders, ""))}, lines...) - } - - return strings.Join(lines, ""), nil -} - // UnitTest is a helper to force the acceptance testing harness to run in the // normal unit test suite. This should only be used for resource that don't // have any external dependencies. @@ -698,10 +758,6 @@ func UnitTest(t testing.T, c TestCase) { } func testResource(c TestStep, state *terraform.State) (*terraform.ResourceState, error) { - if c.ResourceName == "" { - return nil, fmt.Errorf("ResourceName must be set in TestStep") - } - for _, m := range state.Modules { if len(m.Resources) > 0 { if v, ok := m.Resources[c.ResourceName]; ok { diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go index 163bd3d668f..f1e607f8342 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go @@ -10,23 +10,17 @@ import ( tfjson "github.com/hashicorp/terraform-json" testing "github.com/mitchellh/go-testing-interface" - "github.com/hashicorp/terraform-plugin-go/tfprotov5" - "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func runPostTestDestroy(ctx context.Context, t testing.T, c TestCase, wd *plugintest.WorkingDir, factories map[string]func() (*schema.Provider, error), v5factories map[string]func() (tfprotov5.ProviderServer, error), v6factories map[string]func() (tfprotov6.ProviderServer, error), statePreDestroy *terraform.State) error { +func runPostTestDestroy(ctx context.Context, t testing.T, c TestCase, wd *plugintest.WorkingDir, providers *providerFactories, statePreDestroy *terraform.State) error { t.Helper() err := runProviderCommand(ctx, t, func() error { return wd.Destroy(ctx) - }, wd, providerFactories{ - legacy: factories, - protov5: v5factories, - protov6: v6factories}) + }, wd, providers) if err != nil { return err } @@ -55,6 +49,12 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest ctx = logging.TestTerraformPathContext(ctx, wd.GetHelper().TerraformExecPath()) ctx = logging.TestWorkingDirectoryContext(ctx, wd.GetHelper().WorkingDirectory()) + providers := &providerFactories{ + legacy: c.ProviderFactories, + protov5: c.ProtoV5ProviderFactories, + protov6: c.ProtoV6ProviderFactories, + } + defer func() { var statePreDestroy *terraform.State var err error @@ -64,10 +64,7 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { logging.HelperResourceError(ctx, "Error retrieving state, there may be dangling resources", @@ -78,7 +75,7 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest } if !stateIsEmpty(statePreDestroy) { - err := runPostTestDestroy(ctx, t, c, wd, c.ProviderFactories, c.ProtoV5ProviderFactories, c.ProtoV6ProviderFactories, statePreDestroy) + err := runPostTestDestroy(ctx, t, c, wd, providers, statePreDestroy) if err != nil { logging.HelperResourceError(ctx, "Error running post-test destroy, there may be dangling resources", @@ -91,36 +88,28 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest wd.Close() }() - providerCfg, err := testProviderConfig(c) - if err != nil { - logging.HelperResourceError(ctx, - "Error creating test provider configuration", - map[string]interface{}{logging.KeyError: err}, - ) - t.Fatalf("Error creating test provider configuration: %s", err.Error()) - } + if c.hasProviders(ctx) { + err := wd.SetConfig(ctx, c.providerConfig(ctx)) - err = wd.SetConfig(ctx, providerCfg) - if err != nil { - logging.HelperResourceError(ctx, - "Error setting test provider configuration", - map[string]interface{}{logging.KeyError: err}, - ) - t.Fatalf("Error setting test provider configuration: %s", err) - } - err = runProviderCommand(ctx, t, func() error { - return wd.Init(ctx) - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) - if err != nil { - logging.HelperResourceError(ctx, - "Error running init", - map[string]interface{}{logging.KeyError: err}, - ) - t.Fatalf("Error running init: %s", err.Error()) - return + if err != nil { + logging.HelperResourceError(ctx, + "TestCase error setting provider configuration", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestCase error setting provider configuration: %s", err) + } + + err = runProviderCommand(ctx, t, func() error { + return wd.Init(ctx) + }, wd, providers) + + if err != nil { + logging.HelperResourceError(ctx, + "TestCase error running init", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestCase error running init: %s", err.Error()) + } } logging.HelperResourceDebug(ctx, "Starting TestSteps") @@ -129,8 +118,9 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest // acts as default for import tests var appliedCfg string - for i, step := range c.Steps { - ctx = logging.TestStepNumberContext(ctx, i+1) + for stepIndex, step := range c.Steps { + stepNumber := stepIndex + 1 // 1-based indexing for humans + ctx = logging.TestStepNumberContext(ctx, stepNumber) logging.HelperResourceDebug(ctx, "Starting TestStep") @@ -155,30 +145,103 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest logging.HelperResourceDebug(ctx, "Called TestStep SkipFunc") if skip { - t.Logf("Skipping step %d/%d due to SkipFunc", i+1, len(c.Steps)) + t.Logf("Skipping step %d/%d due to SkipFunc", stepNumber, len(c.Steps)) logging.HelperResourceWarn(ctx, "Skipping TestStep due to SkipFunc") continue } } + if step.Config != "" && !step.Destroy && len(step.Taint) > 0 { + var state *terraform.State + + err := runProviderCommand(ctx, t, func() error { + var err error + + state, err = getState(ctx, t, wd) + + if err != nil { + return err + } + + return nil + }, wd, providers) + + if err != nil { + logging.HelperResourceError(ctx, + "TestStep error reading prior state before tainting resources", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestStep %d/%d error reading prior state before tainting resources: %s", stepNumber, len(c.Steps), err) + } + + err = testStepTaint(ctx, state, step) + + if err != nil { + logging.HelperResourceError(ctx, + "TestStep error tainting resources", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestStep %d/%d error tainting resources: %s", stepNumber, len(c.Steps), err) + } + } + + if step.hasProviders(ctx) { + providers = &providerFactories{ + legacy: sdkProviderFactories(c.ProviderFactories).merge(step.ProviderFactories), + protov5: protov5ProviderFactories(c.ProtoV5ProviderFactories).merge(step.ProtoV5ProviderFactories), + protov6: protov6ProviderFactories(c.ProtoV6ProviderFactories).merge(step.ProtoV6ProviderFactories), + } + + providerCfg := step.providerConfig(ctx) + + err := wd.SetConfig(ctx, providerCfg) + + if err != nil { + logging.HelperResourceError(ctx, + "TestStep error setting provider configuration", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestStep %d/%d error setting test provider configuration: %s", stepNumber, len(c.Steps), err) + } + + err = runProviderCommand( + ctx, + t, + func() error { + return wd.Init(ctx) + }, + wd, + providers, + ) + + if err != nil { + logging.HelperResourceError(ctx, + "TestStep error running init", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestStep %d/%d running init: %s", stepNumber, len(c.Steps), err.Error()) + return + } + } + if step.ImportState { logging.HelperResourceTrace(ctx, "TestStep is ImportState mode") - err := testStepNewImportState(ctx, t, c, helper, wd, step, appliedCfg) + err := testStepNewImportState(ctx, t, helper, wd, step, appliedCfg, providers) if step.ExpectError != nil { logging.HelperResourceDebug(ctx, "Checking TestStep ExpectError") if err == nil { logging.HelperResourceError(ctx, "Error running import: expected an error but got none", ) - t.Fatalf("Step %d/%d error running import: expected an error but got none", i+1, len(c.Steps)) + t.Fatalf("Step %d/%d error running import: expected an error but got none", stepNumber, len(c.Steps)) } if !step.ExpectError.MatchString(err.Error()) { logging.HelperResourceError(ctx, fmt.Sprintf("Error running import: expected an error with pattern (%s)", step.ExpectError.String()), map[string]interface{}{logging.KeyError: err}, ) - t.Fatalf("Step %d/%d error running import, expected an error with pattern (%s), no match on: %s", i+1, len(c.Steps), step.ExpectError.String(), err) + t.Fatalf("Step %d/%d error running import, expected an error with pattern (%s), no match on: %s", stepNumber, len(c.Steps), step.ExpectError.String(), err) } } else { if err != nil && c.ErrorCheck != nil { @@ -191,7 +254,7 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest "Error running import", map[string]interface{}{logging.KeyError: err}, ) - t.Fatalf("Step %d/%d error running import: %s", i+1, len(c.Steps), err) + t.Fatalf("Step %d/%d error running import: %s", stepNumber, len(c.Steps), err) } } @@ -203,7 +266,7 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest if step.Config != "" { logging.HelperResourceTrace(ctx, "TestStep is Config mode") - err := testStepNewConfig(ctx, t, c, wd, step) + err := testStepNewConfig(ctx, t, c, wd, step, providers) if step.ExpectError != nil { logging.HelperResourceDebug(ctx, "Checking TestStep ExpectError") @@ -211,14 +274,14 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest logging.HelperResourceError(ctx, "Expected an error but got none", ) - t.Fatalf("Step %d/%d, expected an error but got none", i+1, len(c.Steps)) + t.Fatalf("Step %d/%d, expected an error but got none", stepNumber, len(c.Steps)) } if !step.ExpectError.MatchString(err.Error()) { logging.HelperResourceError(ctx, fmt.Sprintf("Expected an error with pattern (%s)", step.ExpectError.String()), map[string]interface{}{logging.KeyError: err}, ) - t.Fatalf("Step %d/%d, expected an error with pattern, no match on: %s", i+1, len(c.Steps), err) + t.Fatalf("Step %d/%d, expected an error with pattern, no match on: %s", stepNumber, len(c.Steps), err) } } else { if err != nil && c.ErrorCheck != nil { @@ -233,7 +296,7 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest "Unexpected error", map[string]interface{}{logging.KeyError: err}, ) - t.Fatalf("Step %d/%d error: %s", i+1, len(c.Steps), err) + t.Fatalf("Step %d/%d error: %s", stepNumber, len(c.Steps), err) } } @@ -244,7 +307,7 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest continue } - t.Fatalf("Step %d/%d, unsupported test mode", i+1, len(c.Steps)) + t.Fatalf("Step %d/%d, unsupported test mode", stepNumber, len(c.Steps)) } } @@ -277,7 +340,7 @@ func planIsEmpty(plan *tfjson.Plan) bool { return true } -func testIDRefresh(ctx context.Context, t testing.T, c TestCase, wd *plugintest.WorkingDir, step TestStep, r *terraform.ResourceState) error { +func testIDRefresh(ctx context.Context, t testing.T, c TestCase, wd *plugintest.WorkingDir, step TestStep, r *terraform.ResourceState, providers *providerFactories) error { t.Helper() spewConf := spew.NewDefaultConfig() @@ -291,11 +354,7 @@ func testIDRefresh(ctx context.Context, t testing.T, c TestCase, wd *plugintest. // Temporarily set the config to a minimal provider config for the refresh // test. After the refresh we can reset it. - cfg, err := testProviderConfig(c) - if err != nil { - return err - } - err = wd.SetConfig(ctx, cfg) + err := wd.SetConfig(ctx, c.providerConfig(ctx)) if err != nil { t.Fatalf("Error setting import test config: %s", err) } @@ -317,10 +376,7 @@ func testIDRefresh(ctx context.Context, t testing.T, c TestCase, wd *plugintest. return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return err } diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go index 5a9df2bf5f1..09d18c36452 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go @@ -13,30 +13,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugintest.WorkingDir, step TestStep) error { +func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugintest.WorkingDir, step TestStep, providers *providerFactories) error { t.Helper() - if !step.Destroy { - var state *terraform.State - var err error - err = runProviderCommand(ctx, t, func() error { - state, err = getState(ctx, t, wd) - if err != nil { - return err - } - return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) - if err != nil { - return err - } - if err := testStepTaint(ctx, state, step); err != nil { - return fmt.Errorf("Error when tainting resources: %s", err) - } - } - err := wd.SetConfig(ctx, step.Config) if err != nil { return fmt.Errorf("Error setting config: %w", err) @@ -46,10 +25,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint // failing to do this will result in data sources not being updated err = runProviderCommand(ctx, t, func() error { return wd.Refresh(ctx) - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error running pre-apply refresh: %w", err) } @@ -66,10 +42,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint return wd.CreateDestroyPlan(ctx) } return wd.CreatePlan(ctx) - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error running pre-apply plan: %w", err) } @@ -84,10 +57,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving pre-apply state: %w", err) } @@ -95,10 +65,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint // Apply the diff, creating real resources err = runProviderCommand(ctx, t, func() error { return wd.Apply(ctx) - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { if step.Destroy { return fmt.Errorf("Error running destroy: %w", err) @@ -114,10 +81,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving state after apply: %w", err) } @@ -148,10 +112,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint return wd.CreateDestroyPlan(ctx) } return wd.CreatePlan(ctx) - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error running post-apply plan: %w", err) } @@ -161,10 +122,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint var err error plan, err = wd.SavedPlan(ctx) return err - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving post-apply plan: %w", err) } @@ -175,10 +133,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint var err error stdout, err = wd.SavedPlanRawStdout(ctx) return err - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving formatted plan output: %w", err) } @@ -189,10 +144,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint if !step.Destroy || (step.Destroy && !step.PreventPostDestroyRefresh) { err := runProviderCommand(ctx, t, func() error { return wd.Refresh(ctx) - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error running post-apply refresh: %w", err) } @@ -204,10 +156,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint return wd.CreateDestroyPlan(ctx) } return wd.CreatePlan(ctx) - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error running second post-apply plan: %w", err) } @@ -216,10 +165,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint var err error plan, err = wd.SavedPlan(ctx) return err - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving second post-apply plan: %w", err) } @@ -231,10 +177,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint var err error stdout, err = wd.SavedPlanRawStdout(ctx) return err - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving formatted second plan output: %w", err) } @@ -257,10 +200,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return err @@ -290,7 +230,7 @@ func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugint // this fails. If refresh isn't read-only, then this will have // caught a different bug. if idRefreshCheck != nil { - if err := testIDRefresh(ctx, t, c, wd, step, idRefreshCheck); err != nil { + if err := testIDRefresh(ctx, t, c, wd, step, idRefreshCheck, providers); err != nil { return fmt.Errorf( "[ERROR] Test: ID-only test failed: %s", err) } diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go index 1dc98143a64..ec61b055f3a 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go @@ -14,7 +14,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func testStepNewImportState(ctx context.Context, t testing.T, c TestCase, helper *plugintest.Helper, wd *plugintest.WorkingDir, step TestStep, cfg string) error { +func testStepNewImportState(ctx context.Context, t testing.T, helper *plugintest.Helper, wd *plugintest.WorkingDir, step TestStep, cfg string, providers *providerFactories) error { t.Helper() spewConf := spew.NewDefaultConfig() @@ -33,10 +33,7 @@ func testStepNewImportState(ctx context.Context, t testing.T, c TestCase, helper return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { t.Fatalf("Error getting state: %s", err) } @@ -100,20 +97,14 @@ func testStepNewImportState(ctx context.Context, t testing.T, c TestCase, helper err = runProviderCommand(ctx, t, func() error { return importWd.Init(ctx) - }, importWd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, importWd, providers) if err != nil { t.Fatalf("Error running init: %s", err) } err = runProviderCommand(ctx, t, func() error { return importWd.Import(ctx, step.ResourceName, importId) - }, importWd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, importWd, providers) if err != nil { return err } @@ -125,10 +116,7 @@ func testStepNewImportState(ctx context.Context, t testing.T, c TestCase, helper return err } return nil - }, importWd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, importWd, providers) if err != nil { t.Fatalf("Error getting state: %s", err) } diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_providers.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_providers.go new file mode 100644 index 00000000000..35d4a9bf57f --- /dev/null +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_providers.go @@ -0,0 +1,48 @@ +package resource + +import ( + "context" + "fmt" + "strings" +) + +// providerConfig takes the list of providers in a TestStep and returns a +// config with only empty provider blocks. This is useful for Import, where no +// config is provided, but the providers must be defined. +func (s TestStep) providerConfig(_ context.Context) string { + var providerBlocks, requiredProviderBlocks strings.Builder + + for name, externalProvider := range s.ExternalProviders { + providerBlocks.WriteString(fmt.Sprintf("provider %q {}\n", name)) + + if externalProvider.Source == "" && externalProvider.VersionConstraint == "" { + continue + } + + requiredProviderBlocks.WriteString(fmt.Sprintf(" %s = {\n", name)) + + if externalProvider.Source != "" { + requiredProviderBlocks.WriteString(fmt.Sprintf(" source = %q\n", externalProvider.Source)) + } + + if externalProvider.VersionConstraint != "" { + requiredProviderBlocks.WriteString(fmt.Sprintf(" version = %q\n", externalProvider.VersionConstraint)) + } + + requiredProviderBlocks.WriteString(" }\n") + } + + if requiredProviderBlocks.Len() > 0 { + return fmt.Sprintf(` +terraform { + required_providers { +%[1]s + } +} + +%[2]s +`, strings.TrimSuffix(requiredProviderBlocks.String(), "\n"), providerBlocks.String()) + } + + return providerBlocks.String() +} diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_validate.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_validate.go new file mode 100644 index 00000000000..e9239328c69 --- /dev/null +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_validate.go @@ -0,0 +1,99 @@ +package resource + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" +) + +// testStepValidateRequest contains data for the (TestStep).validate() method. +type testStepValidateRequest struct { + // StepNumber is the index of the TestStep in the TestCase.Steps. + StepNumber int + + // TestCaseHasProviders is enabled if the TestCase has set any of + // ExternalProviders, ProtoV5ProviderFactories, ProtoV6ProviderFactories, + // or ProviderFactories. + TestCaseHasProviders bool +} + +// hasProviders returns true if the TestStep has set any of the +// ExternalProviders, ProtoV5ProviderFactories, ProtoV6ProviderFactories, or +// ProviderFactories fields. +func (s TestStep) hasProviders(_ context.Context) bool { + if len(s.ExternalProviders) > 0 { + return true + } + + if len(s.ProtoV5ProviderFactories) > 0 { + return true + } + + if len(s.ProtoV6ProviderFactories) > 0 { + return true + } + + if len(s.ProviderFactories) > 0 { + return true + } + + return false +} + +// validate ensures the TestStep is valid based on the following criteria: +// +// - Config or ImportState is set. +// - Providers are not specified (ExternalProviders, +// ProtoV5ProviderFactories, ProtoV6ProviderFactories, ProviderFactories) +// if specified at the TestCase level. +// - Providers are specified (ExternalProviders, ProtoV5ProviderFactories, +// ProtoV6ProviderFactories, ProviderFactories) if not specified at the +// TestCase level. +// - No overlapping ExternalProviders and ProviderFactories entries +// - ResourceName is not empty when ImportState is true, ImportStateIdFunc +// is not set, and ImportStateId is not set. +// +func (s TestStep) validate(ctx context.Context, req testStepValidateRequest) error { + ctx = logging.TestStepNumberContext(ctx, req.StepNumber) + + logging.HelperResourceTrace(ctx, "Validating TestStep") + + if s.Config == "" && !s.ImportState { + err := fmt.Errorf("TestStep missing Config or ImportState") + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + for name := range s.ExternalProviders { + if _, ok := s.ProviderFactories[name]; ok { + err := fmt.Errorf("TestStep provider %q set in both ExternalProviders and ProviderFactories", name) + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + } + + hasProviders := s.hasProviders(ctx) + + if req.TestCaseHasProviders && hasProviders { + err := fmt.Errorf("Providers must only be specified either at the TestCase or TestStep level") + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + if !req.TestCaseHasProviders && !hasProviders { + err := fmt.Errorf("Providers must be specified at the TestCase level or in all TestStep") + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + if s.ImportState { + if s.ImportStateId == "" && s.ImportStateIdFunc == nil && s.ResourceName == "" { + err := fmt.Errorf("TestStep ImportState must be specified with ImportStateId, ImportStateIdFunc, or ResourceName") + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + } + + return nil +} diff --git a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/working_dir.go b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/working_dir.go index 5309fcfb0a0..1c15e6f5c19 100644 --- a/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/working_dir.go +++ b/providerlint/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/working_dir.go @@ -155,7 +155,9 @@ func (wd *WorkingDir) Init(ctx context.Context) error { logging.HelperResourceTrace(ctx, "Calling Terraform CLI init command") - err := wd.tf.Init(context.Background(), tfexec.Reattach(wd.reattachInfo)) + // -upgrade=true is required for per-TestStep provider version changes + // e.g. TestTest_TestStep_ExternalProviders_DifferentVersions + err := wd.tf.Init(context.Background(), tfexec.Reattach(wd.reattachInfo), tfexec.Upgrade(true)) logging.HelperResourceTrace(ctx, "Called Terraform CLI init command") diff --git a/providerlint/vendor/google.golang.org/grpc/balancer/balancer.go b/providerlint/vendor/google.golang.org/grpc/balancer/balancer.go index bcc6f5451c9..f7a7697cad0 100644 --- a/providerlint/vendor/google.golang.org/grpc/balancer/balancer.go +++ b/providerlint/vendor/google.golang.org/grpc/balancer/balancer.go @@ -27,6 +27,7 @@ import ( "net" "strings" + "google.golang.org/grpc/channelz" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal" @@ -192,7 +193,7 @@ type BuildOptions struct { // server can ignore this field. Authority string // ChannelzParentID is the parent ClientConn's channelz ID. - ChannelzParentID int64 + ChannelzParentID *channelz.Identifier // CustomUserAgent is the custom user agent set on the parent ClientConn. // The balancer should set the same custom user agent if it creates a // ClientConn. diff --git a/providerlint/vendor/google.golang.org/grpc/balancer_conn_wrappers.go b/providerlint/vendor/google.golang.org/grpc/balancer_conn_wrappers.go index f4ea6174682..b1c23eaae0d 100644 --- a/providerlint/vendor/google.golang.org/grpc/balancer_conn_wrappers.go +++ b/providerlint/vendor/google.golang.org/grpc/balancer_conn_wrappers.go @@ -20,130 +20,178 @@ package grpc import ( "fmt" + "strings" "sync" "google.golang.org/grpc/balancer" "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/internal/balancer/gracefulswitch" "google.golang.org/grpc/internal/buffer" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/resolver" ) -// scStateUpdate contains the subConn and the new state it changed to. -type scStateUpdate struct { - sc balancer.SubConn - state connectivity.State - err error -} +// ccBalancerWrapper sits between the ClientConn and the Balancer. +// +// ccBalancerWrapper implements methods corresponding to the ones on the +// balancer.Balancer interface. The ClientConn is free to call these methods +// concurrently and the ccBalancerWrapper ensures that calls from the ClientConn +// to the Balancer happen synchronously and in order. +// +// ccBalancerWrapper also implements the balancer.ClientConn interface and is +// passed to the Balancer implementations. It invokes unexported methods on the +// ClientConn to handle these calls from the Balancer. +// +// It uses the gracefulswitch.Balancer internally to ensure that balancer +// switches happen in a graceful manner. +type ccBalancerWrapper struct { + cc *ClientConn -// exitIdle contains no data and is just a signal sent on the updateCh in -// ccBalancerWrapper to instruct the balancer to exit idle. -type exitIdle struct{} + // Since these fields are accessed only from handleXxx() methods which are + // synchronized by the watcher goroutine, we do not need a mutex to protect + // these fields. + balancer *gracefulswitch.Balancer + curBalancerName string -// ccBalancerWrapper is a wrapper on top of cc for balancers. -// It implements balancer.ClientConn interface. -type ccBalancerWrapper struct { - cc *ClientConn - balancerMu sync.Mutex // synchronizes calls to the balancer - balancer balancer.Balancer - hasExitIdle bool - updateCh *buffer.Unbounded - closed *grpcsync.Event - done *grpcsync.Event - - mu sync.Mutex - subConns map[*acBalancerWrapper]struct{} + updateCh *buffer.Unbounded // Updates written on this channel are processed by watcher(). + resultCh *buffer.Unbounded // Results of calls to UpdateClientConnState() are pushed here. + closed *grpcsync.Event // Indicates if close has been called. + done *grpcsync.Event // Indicates if close has completed its work. } -func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.BuildOptions) *ccBalancerWrapper { +// newCCBalancerWrapper creates a new balancer wrapper. The underlying balancer +// is not created until the switchTo() method is invoked. +func newCCBalancerWrapper(cc *ClientConn, bopts balancer.BuildOptions) *ccBalancerWrapper { ccb := &ccBalancerWrapper{ cc: cc, updateCh: buffer.NewUnbounded(), + resultCh: buffer.NewUnbounded(), closed: grpcsync.NewEvent(), done: grpcsync.NewEvent(), - subConns: make(map[*acBalancerWrapper]struct{}), } go ccb.watcher() - ccb.balancer = b.Build(ccb, bopts) - _, ccb.hasExitIdle = ccb.balancer.(balancer.ExitIdler) + ccb.balancer = gracefulswitch.NewBalancer(ccb, bopts) return ccb } -// watcher balancer functions sequentially, so the balancer can be implemented -// lock-free. +// The following xxxUpdate structs wrap the arguments received as part of the +// corresponding update. The watcher goroutine uses the 'type' of the update to +// invoke the appropriate handler routine to handle the update. + +type ccStateUpdate struct { + ccs *balancer.ClientConnState +} + +type scStateUpdate struct { + sc balancer.SubConn + state connectivity.State + err error +} + +type exitIdleUpdate struct{} + +type resolverErrorUpdate struct { + err error +} + +type switchToUpdate struct { + name string +} + +type subConnUpdate struct { + acbw *acBalancerWrapper +} + +// watcher is a long-running goroutine which reads updates from a channel and +// invokes corresponding methods on the underlying balancer. It ensures that +// these methods are invoked in a synchronous fashion. It also ensures that +// these methods are invoked in the order in which the updates were received. func (ccb *ccBalancerWrapper) watcher() { for { select { - case t := <-ccb.updateCh.Get(): + case u := <-ccb.updateCh.Get(): ccb.updateCh.Load() if ccb.closed.HasFired() { break } - switch u := t.(type) { + switch update := u.(type) { + case *ccStateUpdate: + ccb.handleClientConnStateChange(update.ccs) case *scStateUpdate: - ccb.balancerMu.Lock() - ccb.balancer.UpdateSubConnState(u.sc, balancer.SubConnState{ConnectivityState: u.state, ConnectionError: u.err}) - ccb.balancerMu.Unlock() - case *acBalancerWrapper: - ccb.mu.Lock() - if ccb.subConns != nil { - delete(ccb.subConns, u) - ccb.cc.removeAddrConn(u.getAddrConn(), errConnDrain) - } - ccb.mu.Unlock() - case exitIdle: - if ccb.cc.GetState() == connectivity.Idle { - if ei, ok := ccb.balancer.(balancer.ExitIdler); ok { - // We already checked that the balancer implements - // ExitIdle before pushing the event to updateCh, but - // check conditionally again as defensive programming. - ccb.balancerMu.Lock() - ei.ExitIdle() - ccb.balancerMu.Unlock() - } - } + ccb.handleSubConnStateChange(update) + case *exitIdleUpdate: + ccb.handleExitIdle() + case *resolverErrorUpdate: + ccb.handleResolverError(update.err) + case *switchToUpdate: + ccb.handleSwitchTo(update.name) + case *subConnUpdate: + ccb.handleRemoveSubConn(update.acbw) default: - logger.Errorf("ccBalancerWrapper.watcher: unknown update %+v, type %T", t, t) + logger.Errorf("ccBalancerWrapper.watcher: unknown update %+v, type %T", update, update) } case <-ccb.closed.Done(): } if ccb.closed.HasFired() { - ccb.balancerMu.Lock() - ccb.balancer.Close() - ccb.balancerMu.Unlock() - ccb.mu.Lock() - scs := ccb.subConns - ccb.subConns = nil - ccb.mu.Unlock() - ccb.UpdateState(balancer.State{ConnectivityState: connectivity.Connecting, Picker: nil}) - ccb.done.Fire() - // Fire done before removing the addr conns. We can safely unblock - // ccb.close and allow the removeAddrConns to happen - // asynchronously. - for acbw := range scs { - ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) - } + ccb.handleClose() return } } } -func (ccb *ccBalancerWrapper) close() { - ccb.closed.Fire() - <-ccb.done.Done() +// updateClientConnState is invoked by grpc to push a ClientConnState update to +// the underlying balancer. +// +// Unlike other methods invoked by grpc to push updates to the underlying +// balancer, this method cannot simply push the update onto the update channel +// and return. It needs to return the error returned by the underlying balancer +// back to grpc which propagates that to the resolver. +func (ccb *ccBalancerWrapper) updateClientConnState(ccs *balancer.ClientConnState) error { + ccb.updateCh.Put(&ccStateUpdate{ccs: ccs}) + + var res interface{} + select { + case res = <-ccb.resultCh.Get(): + ccb.resultCh.Load() + case <-ccb.closed.Done(): + // Return early if the balancer wrapper is closed while we are waiting for + // the underlying balancer to process a ClientConnState update. + return nil + } + // If the returned error is nil, attempting to type assert to error leads to + // panic. So, this needs to handled separately. + if res == nil { + return nil + } + return res.(error) } -func (ccb *ccBalancerWrapper) exitIdle() bool { - if !ccb.hasExitIdle { - return false +// handleClientConnStateChange handles a ClientConnState update from the update +// channel and invokes the appropriate method on the underlying balancer. +// +// If the addresses specified in the update contain addresses of type "grpclb" +// and the selected LB policy is not "grpclb", these addresses will be filtered +// out and ccs will be modified with the updated address list. +func (ccb *ccBalancerWrapper) handleClientConnStateChange(ccs *balancer.ClientConnState) { + if ccb.curBalancerName != grpclbName { + // Filter any grpclb addresses since we don't have the grpclb balancer. + var addrs []resolver.Address + for _, addr := range ccs.ResolverState.Addresses { + if addr.Type == resolver.GRPCLB { + continue + } + addrs = append(addrs, addr) + } + ccs.ResolverState.Addresses = addrs } - ccb.updateCh.Put(exitIdle{}) - return true + ccb.resultCh.Put(ccb.balancer.UpdateClientConnState(*ccs)) } -func (ccb *ccBalancerWrapper) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State, err error) { +// updateSubConnState is invoked by grpc to push a subConn state update to the +// underlying balancer. +func (ccb *ccBalancerWrapper) updateSubConnState(sc balancer.SubConn, s connectivity.State, err error) { // When updating addresses for a SubConn, if the address in use is not in // the new addresses, the old ac will be tearDown() and a new ac will be // created. tearDown() generates a state change with Shutdown state, we @@ -161,44 +209,125 @@ func (ccb *ccBalancerWrapper) handleSubConnStateChange(sc balancer.SubConn, s co }) } -func (ccb *ccBalancerWrapper) updateClientConnState(ccs *balancer.ClientConnState) error { - ccb.balancerMu.Lock() - defer ccb.balancerMu.Unlock() - return ccb.balancer.UpdateClientConnState(*ccs) +// handleSubConnStateChange handles a SubConnState update from the update +// channel and invokes the appropriate method on the underlying balancer. +func (ccb *ccBalancerWrapper) handleSubConnStateChange(update *scStateUpdate) { + ccb.balancer.UpdateSubConnState(update.sc, balancer.SubConnState{ConnectivityState: update.state, ConnectionError: update.err}) +} + +func (ccb *ccBalancerWrapper) exitIdle() { + ccb.updateCh.Put(&exitIdleUpdate{}) +} + +func (ccb *ccBalancerWrapper) handleExitIdle() { + if ccb.cc.GetState() != connectivity.Idle { + return + } + ccb.balancer.ExitIdle() } func (ccb *ccBalancerWrapper) resolverError(err error) { - ccb.balancerMu.Lock() - defer ccb.balancerMu.Unlock() + ccb.updateCh.Put(&resolverErrorUpdate{err: err}) +} + +func (ccb *ccBalancerWrapper) handleResolverError(err error) { ccb.balancer.ResolverError(err) } +// switchTo is invoked by grpc to instruct the balancer wrapper to switch to the +// LB policy identified by name. +// +// ClientConn calls newCCBalancerWrapper() at creation time. Upon receipt of the +// first good update from the name resolver, it determines the LB policy to use +// and invokes the switchTo() method. Upon receipt of every subsequent update +// from the name resolver, it invokes this method. +// +// the ccBalancerWrapper keeps track of the current LB policy name, and skips +// the graceful balancer switching process if the name does not change. +func (ccb *ccBalancerWrapper) switchTo(name string) { + ccb.updateCh.Put(&switchToUpdate{name: name}) +} + +// handleSwitchTo handles a balancer switch update from the update channel. It +// calls the SwitchTo() method on the gracefulswitch.Balancer with a +// balancer.Builder corresponding to name. If no balancer.Builder is registered +// for the given name, it uses the default LB policy which is "pick_first". +func (ccb *ccBalancerWrapper) handleSwitchTo(name string) { + // TODO: Other languages use case-insensitive balancer registries. We should + // switch as well. See: https://github.com/grpc/grpc-go/issues/5288. + if strings.EqualFold(ccb.curBalancerName, name) { + return + } + + // TODO: Ensure that name is a registered LB policy when we get here. + // We currently only validate the `loadBalancingConfig` field. We need to do + // the same for the `loadBalancingPolicy` field and reject the service config + // if the specified policy is not registered. + builder := balancer.Get(name) + if builder == nil { + channelz.Warningf(logger, ccb.cc.channelzID, "Channel switches to new LB policy %q, since the specified LB policy %q was not registered", PickFirstBalancerName, name) + builder = newPickfirstBuilder() + } else { + channelz.Infof(logger, ccb.cc.channelzID, "Channel switches to new LB policy %q", name) + } + + if err := ccb.balancer.SwitchTo(builder); err != nil { + channelz.Errorf(logger, ccb.cc.channelzID, "Channel failed to build new LB policy %q: %v", name, err) + return + } + ccb.curBalancerName = builder.Name() +} + +// handleRemoveSucConn handles a request from the underlying balancer to remove +// a subConn. +// +// See comments in RemoveSubConn() for more details. +func (ccb *ccBalancerWrapper) handleRemoveSubConn(acbw *acBalancerWrapper) { + ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) +} + +func (ccb *ccBalancerWrapper) close() { + ccb.closed.Fire() + <-ccb.done.Done() +} + +func (ccb *ccBalancerWrapper) handleClose() { + ccb.balancer.Close() + ccb.done.Fire() +} + func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { if len(addrs) <= 0 { return nil, fmt.Errorf("grpc: cannot create SubConn with empty address list") } - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return nil, fmt.Errorf("grpc: ClientConn balancer wrapper was closed") - } ac, err := ccb.cc.newAddrConn(addrs, opts) if err != nil { + channelz.Warningf(logger, ccb.cc.channelzID, "acBalancerWrapper: NewSubConn: failed to newAddrConn: %v", err) return nil, err } acbw := &acBalancerWrapper{ac: ac} acbw.ac.mu.Lock() ac.acbw = acbw acbw.ac.mu.Unlock() - ccb.subConns[acbw] = struct{}{} return acbw, nil } func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) { - // The RemoveSubConn() is handled in the run() goroutine, to avoid deadlock - // during switchBalancer() if the old balancer calls RemoveSubConn() in its - // Close(). - ccb.updateCh.Put(sc) + // Before we switched the ccBalancerWrapper to use gracefulswitch.Balancer, it + // was required to handle the RemoveSubConn() method asynchronously by pushing + // the update onto the update channel. This was done to avoid a deadlock as + // switchBalancer() was holding cc.mu when calling Close() on the old + // balancer, which would in turn call RemoveSubConn(). + // + // With the use of gracefulswitch.Balancer in ccBalancerWrapper, handling this + // asynchronously is probably not required anymore since the switchTo() method + // handles the balancer switch by pushing the update onto the channel. + // TODO(easwars): Handle this inline. + acbw, ok := sc.(*acBalancerWrapper) + if !ok { + return + } + ccb.updateCh.Put(&subConnUpdate{acbw: acbw}) } func (ccb *ccBalancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) { @@ -210,11 +339,6 @@ func (ccb *ccBalancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resol } func (ccb *ccBalancerWrapper) UpdateState(s balancer.State) { - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return - } // Update picker before updating state. Even though the ordering here does // not matter, it can lead to multiple calls of Pick in the common start-up // case where we wait for ready and then perform an RPC. If the picker is diff --git a/providerlint/vendor/google.golang.org/grpc/channelz/channelz.go b/providerlint/vendor/google.golang.org/grpc/channelz/channelz.go new file mode 100644 index 00000000000..a220c47c59a --- /dev/null +++ b/providerlint/vendor/google.golang.org/grpc/channelz/channelz.go @@ -0,0 +1,36 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package channelz exports internals of the channelz implementation as required +// by other gRPC packages. +// +// The implementation of the channelz spec as defined in +// https://github.com/grpc/proposal/blob/master/A14-channelz.md, is provided by +// the `internal/channelz` package. +// +// Experimental +// +// Notice: All APIs in this package are experimental and may be removed in a +// later release. +package channelz + +import "google.golang.org/grpc/internal/channelz" + +// Identifier is an opaque identifier which uniquely identifies an entity in the +// channelz database. +type Identifier = channelz.Identifier diff --git a/providerlint/vendor/google.golang.org/grpc/clientconn.go b/providerlint/vendor/google.golang.org/grpc/clientconn.go index f9af7891371..3ed6eb8e75e 100644 --- a/providerlint/vendor/google.golang.org/grpc/clientconn.go +++ b/providerlint/vendor/google.golang.org/grpc/clientconn.go @@ -159,23 +159,20 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * } }() - if channelz.IsOn() { - if cc.dopts.channelzParentID != 0 { - cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, cc.dopts.channelzParentID, target) - channelz.AddTraceEvent(logger, cc.channelzID, 0, &channelz.TraceEventDesc{ - Desc: "Channel Created", - Severity: channelz.CtInfo, - Parent: &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Nested Channel(id:%d) created", cc.channelzID), - Severity: channelz.CtInfo, - }, - }) - } else { - cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, 0, target) - channelz.Info(logger, cc.channelzID, "Channel Created") + pid := cc.dopts.channelzParentID + cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, pid, target) + ted := &channelz.TraceEventDesc{ + Desc: "Channel created", + Severity: channelz.CtInfo, + } + if cc.dopts.channelzParentID != nil { + ted.Parent = &channelz.TraceEventDesc{ + Desc: fmt.Sprintf("Nested Channel(id:%d) created", cc.channelzID.Int()), + Severity: channelz.CtInfo, } - cc.csMgr.channelzID = cc.channelzID } + channelz.AddTraceEvent(logger, cc.channelzID, 1, ted) + cc.csMgr.channelzID = cc.channelzID if cc.dopts.copts.TransportCredentials == nil && cc.dopts.copts.CredsBundle == nil { return nil, errNoTransportSecurity @@ -281,7 +278,7 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * if creds := cc.dopts.copts.TransportCredentials; creds != nil { credsClone = creds.Clone() } - cc.balancerBuildOpts = balancer.BuildOptions{ + cc.balancerWrapper = newCCBalancerWrapper(cc, balancer.BuildOptions{ DialCreds: credsClone, CredsBundle: cc.dopts.copts.CredsBundle, Dialer: cc.dopts.copts.Dialer, @@ -289,7 +286,7 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * CustomUserAgent: cc.dopts.copts.UserAgent, ChannelzParentID: cc.channelzID, Target: cc.parsedTarget, - } + }) // Build the resolver. rWrapper, err := newCCResolverWrapper(cc, resolverBuilder) @@ -398,7 +395,7 @@ type connectivityStateManager struct { mu sync.Mutex state connectivity.State notifyChan chan struct{} - channelzID int64 + channelzID *channelz.Identifier } // updateState updates the connectivity.State of ClientConn. @@ -464,34 +461,36 @@ var _ ClientConnInterface = (*ClientConn)(nil) // handshakes. It also handles errors on established connections by // re-resolving the name and reconnecting. type ClientConn struct { - ctx context.Context - cancel context.CancelFunc - - target string - parsedTarget resolver.Target - authority string - dopts dialOptions - csMgr *connectivityStateManager - - balancerBuildOpts balancer.BuildOptions - blockingpicker *pickerWrapper - + ctx context.Context // Initialized using the background context at dial time. + cancel context.CancelFunc // Cancelled on close. + + // The following are initialized at dial time, and are read-only after that. + target string // User's dial target. + parsedTarget resolver.Target // See parseTargetAndFindResolver(). + authority string // See determineAuthority(). + dopts dialOptions // Default and user specified dial options. + channelzID *channelz.Identifier // Channelz identifier for the channel. + balancerWrapper *ccBalancerWrapper // Uses gracefulswitch.balancer underneath. + + // The following provide their own synchronization, and therefore don't + // require cc.mu to be held to access them. + csMgr *connectivityStateManager + blockingpicker *pickerWrapper safeConfigSelector iresolver.SafeConfigSelector + czData *channelzData + retryThrottler atomic.Value // Updated from service config. - mu sync.RWMutex - resolverWrapper *ccResolverWrapper - sc *ServiceConfig - conns map[*addrConn]struct{} - // Keepalive parameter can be updated if a GoAway is received. - mkp keepalive.ClientParameters - curBalancerName string - balancerWrapper *ccBalancerWrapper - retryThrottler atomic.Value - + // firstResolveEvent is used to track whether the name resolver sent us at + // least one update. RPCs block on this event. firstResolveEvent *grpcsync.Event - channelzID int64 // channelz unique identification number - czData *channelzData + // mu protects the following fields. + // TODO: split mu so the same mutex isn't used for everything. + mu sync.RWMutex + resolverWrapper *ccResolverWrapper // Initialized in Dial; cleared in Close. + sc *ServiceConfig // Latest service config received from the resolver. + conns map[*addrConn]struct{} // Set to nil on close. + mkp keepalive.ClientParameters // May be updated upon receipt of a GoAway. lceMu sync.Mutex // protects lastConnectionError lastConnectionError error @@ -536,14 +535,7 @@ func (cc *ClientConn) GetState() connectivity.State { // Notice: This API is EXPERIMENTAL and may be changed or removed in a later // release. func (cc *ClientConn) Connect() { - cc.mu.Lock() - defer cc.mu.Unlock() - if cc.balancerWrapper != nil && cc.balancerWrapper.exitIdle() { - return - } - for ac := range cc.conns { - go ac.connect() - } + cc.balancerWrapper.exitIdle() } func (cc *ClientConn) scWatcher() { @@ -623,9 +615,7 @@ func (cc *ClientConn) updateResolverState(s resolver.State, err error) error { // with the new addresses. cc.maybeApplyDefaultServiceConfig(nil) - if cc.balancerWrapper != nil { - cc.balancerWrapper.resolverError(err) - } + cc.balancerWrapper.resolverError(err) // No addresses are valid with err set; return early. cc.mu.Unlock() @@ -653,16 +643,10 @@ func (cc *ClientConn) updateResolverState(s resolver.State, err error) error { cc.applyServiceConfigAndBalancer(sc, configSelector, s.Addresses) } else { ret = balancer.ErrBadResolverState - if cc.balancerWrapper == nil { - var err error - if s.ServiceConfig.Err != nil { - err = status.Errorf(codes.Unavailable, "error parsing service config: %v", s.ServiceConfig.Err) - } else { - err = status.Errorf(codes.Unavailable, "illegal service config type: %T", s.ServiceConfig.Config) - } - cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{cc.sc}) - cc.blockingpicker.updatePicker(base.NewErrPicker(err)) - cc.csMgr.updateState(connectivity.TransientFailure) + if cc.sc == nil { + // Apply the failing LB only if we haven't received valid service config + // from the name resolver in the past. + cc.applyFailingLB(s.ServiceConfig) cc.mu.Unlock() return ret } @@ -670,24 +654,12 @@ func (cc *ClientConn) updateResolverState(s resolver.State, err error) error { } var balCfg serviceconfig.LoadBalancingConfig - if cc.dopts.balancerBuilder == nil && cc.sc != nil && cc.sc.lbConfig != nil { + if cc.sc != nil && cc.sc.lbConfig != nil { balCfg = cc.sc.lbConfig.cfg } - - cbn := cc.curBalancerName bw := cc.balancerWrapper cc.mu.Unlock() - if cbn != grpclbName { - // Filter any grpclb addresses since we don't have the grpclb balancer. - for i := 0; i < len(s.Addresses); { - if s.Addresses[i].Type == resolver.GRPCLB { - copy(s.Addresses[i:], s.Addresses[i+1:]) - s.Addresses = s.Addresses[:len(s.Addresses)-1] - continue - } - i++ - } - } + uccsErr := bw.updateClientConnState(&balancer.ClientConnState{ResolverState: s, BalancerConfig: balCfg}) if ret == nil { ret = uccsErr // prefer ErrBadResolver state since any other error is @@ -696,56 +668,28 @@ func (cc *ClientConn) updateResolverState(s resolver.State, err error) error { return ret } -// switchBalancer starts the switching from current balancer to the balancer -// with the given name. -// -// It will NOT send the current address list to the new balancer. If needed, -// caller of this function should send address list to the new balancer after -// this function returns. +// applyFailingLB is akin to configuring an LB policy on the channel which +// always fails RPCs. Here, an actual LB policy is not configured, but an always +// erroring picker is configured, which returns errors with information about +// what was invalid in the received service config. A config selector with no +// service config is configured, and the connectivity state of the channel is +// set to TransientFailure. // // Caller must hold cc.mu. -func (cc *ClientConn) switchBalancer(name string) { - if strings.EqualFold(cc.curBalancerName, name) { - return - } - - channelz.Infof(logger, cc.channelzID, "ClientConn switching balancer to %q", name) - if cc.dopts.balancerBuilder != nil { - channelz.Info(logger, cc.channelzID, "ignoring balancer switching: Balancer DialOption used instead") - return - } - if cc.balancerWrapper != nil { - // Don't hold cc.mu while closing the balancers. The balancers may call - // methods that require cc.mu (e.g. cc.NewSubConn()). Holding the mutex - // would cause a deadlock in that case. - cc.mu.Unlock() - cc.balancerWrapper.close() - cc.mu.Lock() - } - - builder := balancer.Get(name) - if builder == nil { - channelz.Warningf(logger, cc.channelzID, "Channel switches to new LB policy %q due to fallback from invalid balancer name", PickFirstBalancerName) - channelz.Infof(logger, cc.channelzID, "failed to get balancer builder for: %v, using pick_first instead", name) - builder = newPickfirstBuilder() +func (cc *ClientConn) applyFailingLB(sc *serviceconfig.ParseResult) { + var err error + if sc.Err != nil { + err = status.Errorf(codes.Unavailable, "error parsing service config: %v", sc.Err) } else { - channelz.Infof(logger, cc.channelzID, "Channel switches to new LB policy %q", name) + err = status.Errorf(codes.Unavailable, "illegal service config type: %T", sc.Config) } - - cc.curBalancerName = builder.Name() - cc.balancerWrapper = newCCBalancerWrapper(cc, builder, cc.balancerBuildOpts) + cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{nil}) + cc.blockingpicker.updatePicker(base.NewErrPicker(err)) + cc.csMgr.updateState(connectivity.TransientFailure) } func (cc *ClientConn) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State, err error) { - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return - } - // TODO(bar switching) send updates to all balancer wrappers when balancer - // gracefully switching is supported. - cc.balancerWrapper.handleSubConnStateChange(sc, s, err) - cc.mu.Unlock() + cc.balancerWrapper.updateSubConnState(sc, s, err) } // newAddrConn creates an addrConn for addrs and adds it to cc.conns. @@ -768,17 +712,21 @@ func (cc *ClientConn) newAddrConn(addrs []resolver.Address, opts balancer.NewSub cc.mu.Unlock() return nil, ErrClientConnClosing } - if channelz.IsOn() { - ac.channelzID = channelz.RegisterSubChannel(ac, cc.channelzID, "") - channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{ - Desc: "Subchannel Created", - Severity: channelz.CtInfo, - Parent: &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Subchannel(id:%d) created", ac.channelzID), - Severity: channelz.CtInfo, - }, - }) + + var err error + ac.channelzID, err = channelz.RegisterSubChannel(ac, cc.channelzID, "") + if err != nil { + return nil, err } + channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{ + Desc: "Subchannel created", + Severity: channelz.CtInfo, + Parent: &channelz.TraceEventDesc{ + Desc: fmt.Sprintf("Subchannel(id:%d) created", ac.channelzID.Int()), + Severity: channelz.CtInfo, + }, + }) + cc.conns[ac] = struct{}{} cc.mu.Unlock() return ac, nil @@ -991,35 +939,26 @@ func (cc *ClientConn) applyServiceConfigAndBalancer(sc *ServiceConfig, configSel cc.retryThrottler.Store((*retryThrottler)(nil)) } - if cc.dopts.balancerBuilder == nil { - // Only look at balancer types and switch balancer if balancer dial - // option is not set. - var newBalancerName string - if cc.sc != nil && cc.sc.lbConfig != nil { - newBalancerName = cc.sc.lbConfig.name - } else { - var isGRPCLB bool - for _, a := range addrs { - if a.Type == resolver.GRPCLB { - isGRPCLB = true - break - } - } - if isGRPCLB { - newBalancerName = grpclbName - } else if cc.sc != nil && cc.sc.LB != nil { - newBalancerName = *cc.sc.LB - } else { - newBalancerName = PickFirstBalancerName + var newBalancerName string + if cc.sc != nil && cc.sc.lbConfig != nil { + newBalancerName = cc.sc.lbConfig.name + } else { + var isGRPCLB bool + for _, a := range addrs { + if a.Type == resolver.GRPCLB { + isGRPCLB = true + break } } - cc.switchBalancer(newBalancerName) - } else if cc.balancerWrapper == nil { - // Balancer dial option was set, and this is the first time handling - // resolved addresses. Build a balancer with dopts.balancerBuilder. - cc.curBalancerName = cc.dopts.balancerBuilder.Name() - cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, cc.balancerBuildOpts) + if isGRPCLB { + newBalancerName = grpclbName + } else if cc.sc != nil && cc.sc.LB != nil { + newBalancerName = *cc.sc.LB + } else { + newBalancerName = PickFirstBalancerName + } } + cc.balancerWrapper.switchTo(newBalancerName) } func (cc *ClientConn) resolveNow(o resolver.ResolveNowOptions) { @@ -1070,11 +1009,11 @@ func (cc *ClientConn) Close() error { rWrapper := cc.resolverWrapper cc.resolverWrapper = nil bWrapper := cc.balancerWrapper - cc.balancerWrapper = nil cc.mu.Unlock() + // The order of closing matters here since the balancer wrapper assumes the + // picker is closed before it is closed. cc.blockingpicker.close() - if bWrapper != nil { bWrapper.close() } @@ -1085,22 +1024,22 @@ func (cc *ClientConn) Close() error { for ac := range conns { ac.tearDown(ErrClientConnClosing) } - if channelz.IsOn() { - ted := &channelz.TraceEventDesc{ - Desc: "Channel Deleted", + ted := &channelz.TraceEventDesc{ + Desc: "Channel deleted", + Severity: channelz.CtInfo, + } + if cc.dopts.channelzParentID != nil { + ted.Parent = &channelz.TraceEventDesc{ + Desc: fmt.Sprintf("Nested channel(id:%d) deleted", cc.channelzID.Int()), Severity: channelz.CtInfo, } - if cc.dopts.channelzParentID != 0 { - ted.Parent = &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Nested channel(id:%d) deleted", cc.channelzID), - Severity: channelz.CtInfo, - } - } - channelz.AddTraceEvent(logger, cc.channelzID, 0, ted) - // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add trace reference to - // the entity being deleted, and thus prevent it from being deleted right away. - channelz.RemoveEntry(cc.channelzID) } + channelz.AddTraceEvent(logger, cc.channelzID, 0, ted) + // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add + // trace reference to the entity being deleted, and thus prevent it from being + // deleted right away. + channelz.RemoveEntry(cc.channelzID) + return nil } @@ -1130,7 +1069,7 @@ type addrConn struct { backoffIdx int // Needs to be stateful for resetConnectBackoff. resetBackoff chan struct{} - channelzID int64 // channelz unique identification number. + channelzID *channelz.Identifier czData *channelzData } @@ -1312,14 +1251,12 @@ func (ac *addrConn) createTransport(addr resolver.Address, copts transport.Conne connectCtx, cancel := context.WithDeadline(ac.ctx, connectDeadline) defer cancel() - if channelz.IsOn() { - copts.ChannelzParentID = ac.channelzID - } + copts.ChannelzParentID = ac.channelzID newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, addr, copts, func() { prefaceReceived.Fire() }, onGoAway, onClose) if err != nil { // newTr is either nil, or closed. - channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %v. Err: %v", addr, err) + channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %s. Err: %v", addr, err) return err } @@ -1332,7 +1269,7 @@ func (ac *addrConn) createTransport(addr resolver.Address, copts transport.Conne newTr.Close(transport.ErrConnClosing) if connectCtx.Err() == context.DeadlineExceeded { err := errors.New("failed to receive server preface within timeout") - channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %v: %v", addr, err) + channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %s: %v", addr, err) return err } return nil @@ -1497,19 +1434,18 @@ func (ac *addrConn) tearDown(err error) { curTr.GracefulClose() ac.mu.Lock() } - if channelz.IsOn() { - channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{ - Desc: "Subchannel Deleted", + channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{ + Desc: "Subchannel deleted", + Severity: channelz.CtInfo, + Parent: &channelz.TraceEventDesc{ + Desc: fmt.Sprintf("Subchannel(id:%d) deleted", ac.channelzID.Int()), Severity: channelz.CtInfo, - Parent: &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Subchanel(id:%d) deleted", ac.channelzID), - Severity: channelz.CtInfo, - }, - }) - // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add trace reference to - // the entity being deleted, and thus prevent it from being deleted right away. - channelz.RemoveEntry(ac.channelzID) - } + }, + }) + // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add + // trace reference to the entity being deleted, and thus prevent it from + // being deleted right away. + channelz.RemoveEntry(ac.channelzID) ac.mu.Unlock() } diff --git a/providerlint/vendor/google.golang.org/grpc/dialoptions.go b/providerlint/vendor/google.golang.org/grpc/dialoptions.go index c4bf09f9e94..f2f605a17c4 100644 --- a/providerlint/vendor/google.golang.org/grpc/dialoptions.go +++ b/providerlint/vendor/google.golang.org/grpc/dialoptions.go @@ -20,12 +20,11 @@ package grpc import ( "context" - "fmt" "net" "time" "google.golang.org/grpc/backoff" - "google.golang.org/grpc/balancer" + "google.golang.org/grpc/channelz" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/internal" @@ -45,19 +44,17 @@ type dialOptions struct { chainUnaryInts []UnaryClientInterceptor chainStreamInts []StreamClientInterceptor - cp Compressor - dc Decompressor - bs internalbackoff.Strategy - block bool - returnLastError bool - timeout time.Duration - scChan <-chan ServiceConfig - authority string - copts transport.ConnectOptions - callOptions []CallOption - // This is used by WithBalancerName dial option. - balancerBuilder balancer.Builder - channelzParentID int64 + cp Compressor + dc Decompressor + bs internalbackoff.Strategy + block bool + returnLastError bool + timeout time.Duration + scChan <-chan ServiceConfig + authority string + copts transport.ConnectOptions + callOptions []CallOption + channelzParentID *channelz.Identifier disableServiceConfig bool disableRetry bool disableHealthCheck bool @@ -195,25 +192,6 @@ func WithDecompressor(dc Decompressor) DialOption { }) } -// WithBalancerName sets the balancer that the ClientConn will be initialized -// with. Balancer registered with balancerName will be used. This function -// panics if no balancer was registered by balancerName. -// -// The balancer cannot be overridden by balancer option specified by service -// config. -// -// Deprecated: use WithDefaultServiceConfig and WithDisableServiceConfig -// instead. Will be removed in a future 1.x release. -func WithBalancerName(balancerName string) DialOption { - builder := balancer.Get(balancerName) - if builder == nil { - panic(fmt.Sprintf("grpc.WithBalancerName: no balancer is registered for name %v", balancerName)) - } - return newFuncDialOption(func(o *dialOptions) { - o.balancerBuilder = builder - }) -} - // WithServiceConfig returns a DialOption which has a channel to read the // service configuration. // @@ -304,8 +282,8 @@ func WithReturnConnectionError() DialOption { // WithCredentialsBundle or WithPerRPCCredentials) which require transport // security is incompatible and will cause grpc.Dial() to fail. // -// Deprecated: use WithTransportCredentials and insecure.NewCredentials() instead. -// Will be supported throughout 1.x. +// Deprecated: use WithTransportCredentials and insecure.NewCredentials() +// instead. Will be supported throughout 1.x. func WithInsecure() DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.TransportCredentials = insecure.NewCredentials() @@ -498,7 +476,7 @@ func WithAuthority(a string) DialOption { // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. -func WithChannelzParentID(id int64) DialOption { +func WithChannelzParentID(id *channelz.Identifier) DialOption { return newFuncDialOption(func(o *dialOptions) { o.channelzParentID = id }) diff --git a/providerlint/vendor/google.golang.org/grpc/go.mod b/providerlint/vendor/google.golang.org/grpc/go.mod index 0e7dc351ae1..6a760ed7435 100644 --- a/providerlint/vendor/google.golang.org/grpc/go.mod +++ b/providerlint/vendor/google.golang.org/grpc/go.mod @@ -6,14 +6,14 @@ require ( github.com/cespare/xxhash/v2 v2.1.1 github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4 github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1 - github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021 + github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1 github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b github.com/golang/protobuf v1.5.2 - github.com/google/go-cmp v0.5.5 + github.com/google/go-cmp v0.5.6 github.com/google/uuid v1.1.2 - golang.org/x/net v0.0.0-20200822124328-c89045814202 + golang.org/x/net v0.0.0-20201021035429-f5854403a974 golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d - golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd + golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 - google.golang.org/protobuf v1.26.0 + google.golang.org/protobuf v1.27.1 ) diff --git a/providerlint/vendor/google.golang.org/grpc/go.sum b/providerlint/vendor/google.golang.org/grpc/go.sum index 03be9ef71ec..5f418dba1b4 100644 --- a/providerlint/vendor/google.golang.org/grpc/go.sum +++ b/providerlint/vendor/google.golang.org/grpc/go.sum @@ -12,8 +12,8 @@ github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGX github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4 h1:hzAQntlaYRkVSFEfj9OTWlVV1H155FMD8BTKktLv0QI= github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= -github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1 h1:zH8ljVhhq7yC0MIeUL/IviMtY8hx2mK8cN9wEYb8ggw= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= @@ -22,8 +22,8 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021 h1:fP+fF0up6oPY49OrjPrhIJ8yQfdIM85NXMLkMg1EXVs= -github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1 h1:xvqufLtNVwAhN8NMyWklVgxnWohi+wtMGQMhtxexlm0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0 h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= @@ -49,8 +49,9 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= @@ -75,8 +76,9 @@ golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20200822124328-c89045814202 h1:VvcQYSHwXgi7W+TpUR6A9g6Up98WAHf3f/ulnJ62IyA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -87,10 +89,14 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 h1:myAQVi0cGEoqQVR5POX+8RR2mrocKqNN1hmeMqhX27k= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= @@ -122,8 +128,9 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2 google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/providerlint/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go b/providerlint/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go new file mode 100644 index 00000000000..7ba8f4d1831 --- /dev/null +++ b/providerlint/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go @@ -0,0 +1,382 @@ +/* + * + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package gracefulswitch implements a graceful switch load balancer. +package gracefulswitch + +import ( + "errors" + "fmt" + "sync" + + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/balancer/base" + "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/resolver" +) + +var errBalancerClosed = errors.New("gracefulSwitchBalancer is closed") +var _ balancer.Balancer = (*Balancer)(nil) + +// NewBalancer returns a graceful switch Balancer. +func NewBalancer(cc balancer.ClientConn, opts balancer.BuildOptions) *Balancer { + return &Balancer{ + cc: cc, + bOpts: opts, + } +} + +// Balancer is a utility to gracefully switch from one balancer to +// a new balancer. It implements the balancer.Balancer interface. +type Balancer struct { + bOpts balancer.BuildOptions + cc balancer.ClientConn + + // mu protects the following fields and all fields within balancerCurrent + // and balancerPending. mu does not need to be held when calling into the + // child balancers, as all calls into these children happen only as a direct + // result of a call into the gracefulSwitchBalancer, which are also + // guaranteed to be synchronous. There is one exception: an UpdateState call + // from a child balancer when current and pending are populated can lead to + // calling Close() on the current. To prevent that racing with an + // UpdateSubConnState from the channel, we hold currentMu during Close and + // UpdateSubConnState calls. + mu sync.Mutex + balancerCurrent *balancerWrapper + balancerPending *balancerWrapper + closed bool // set to true when this balancer is closed + + // currentMu must be locked before mu. This mutex guards against this + // sequence of events: UpdateSubConnState() called, finds the + // balancerCurrent, gives up lock, updateState comes in, causes Close() on + // balancerCurrent before the UpdateSubConnState is called on the + // balancerCurrent. + currentMu sync.Mutex +} + +// swap swaps out the current lb with the pending lb and updates the ClientConn. +// The caller must hold gsb.mu. +func (gsb *Balancer) swap() { + gsb.cc.UpdateState(gsb.balancerPending.lastState) + cur := gsb.balancerCurrent + gsb.balancerCurrent = gsb.balancerPending + gsb.balancerPending = nil + go func() { + gsb.currentMu.Lock() + defer gsb.currentMu.Unlock() + cur.Close() + }() +} + +// Helper function that checks if the balancer passed in is current or pending. +// The caller must hold gsb.mu. +func (gsb *Balancer) balancerCurrentOrPending(bw *balancerWrapper) bool { + return bw == gsb.balancerCurrent || bw == gsb.balancerPending +} + +// SwitchTo initializes the graceful switch process, which completes based on +// connectivity state changes on the current/pending balancer. Thus, the switch +// process is not complete when this method returns. This method must be called +// synchronously alongside the rest of the balancer.Balancer methods this +// Graceful Switch Balancer implements. +func (gsb *Balancer) SwitchTo(builder balancer.Builder) error { + gsb.mu.Lock() + if gsb.closed { + gsb.mu.Unlock() + return errBalancerClosed + } + bw := &balancerWrapper{ + gsb: gsb, + lastState: balancer.State{ + ConnectivityState: connectivity.Connecting, + Picker: base.NewErrPicker(balancer.ErrNoSubConnAvailable), + }, + subconns: make(map[balancer.SubConn]bool), + } + balToClose := gsb.balancerPending // nil if there is no pending balancer + if gsb.balancerCurrent == nil { + gsb.balancerCurrent = bw + } else { + gsb.balancerPending = bw + } + gsb.mu.Unlock() + balToClose.Close() + // This function takes a builder instead of a balancer because builder.Build + // can call back inline, and this utility needs to handle the callbacks. + newBalancer := builder.Build(bw, gsb.bOpts) + if newBalancer == nil { + // This is illegal and should never happen; we clear the balancerWrapper + // we were constructing if it happens to avoid a potential panic. + gsb.mu.Lock() + if gsb.balancerPending != nil { + gsb.balancerPending = nil + } else { + gsb.balancerCurrent = nil + } + gsb.mu.Unlock() + return balancer.ErrBadResolverState + } + + // This write doesn't need to take gsb.mu because this field never gets read + // or written to on any calls from the current or pending. Calls from grpc + // to this balancer are guaranteed to be called synchronously, so this + // bw.Balancer field will never be forwarded to until this SwitchTo() + // function returns. + bw.Balancer = newBalancer + return nil +} + +// Returns nil if the graceful switch balancer is closed. +func (gsb *Balancer) latestBalancer() *balancerWrapper { + gsb.mu.Lock() + defer gsb.mu.Unlock() + if gsb.balancerPending != nil { + return gsb.balancerPending + } + return gsb.balancerCurrent +} + +// UpdateClientConnState forwards the update to the latest balancer created. +func (gsb *Balancer) UpdateClientConnState(state balancer.ClientConnState) error { + // The resolver data is only relevant to the most recent LB Policy. + balToUpdate := gsb.latestBalancer() + if balToUpdate == nil { + return errBalancerClosed + } + // Perform this call without gsb.mu to prevent deadlocks if the child calls + // back into the channel. The latest balancer can never be closed during a + // call from the channel, even without gsb.mu held. + return balToUpdate.UpdateClientConnState(state) +} + +// ResolverError forwards the error to the latest balancer created. +func (gsb *Balancer) ResolverError(err error) { + // The resolver data is only relevant to the most recent LB Policy. + balToUpdate := gsb.latestBalancer() + if balToUpdate == nil { + return + } + // Perform this call without gsb.mu to prevent deadlocks if the child calls + // back into the channel. The latest balancer can never be closed during a + // call from the channel, even without gsb.mu held. + balToUpdate.ResolverError(err) +} + +// ExitIdle forwards the call to the latest balancer created. +// +// If the latest balancer does not support ExitIdle, the subConns are +// re-connected to manually. +func (gsb *Balancer) ExitIdle() { + balToUpdate := gsb.latestBalancer() + if balToUpdate == nil { + return + } + // There is no need to protect this read with a mutex, as the write to the + // Balancer field happens in SwitchTo, which completes before this can be + // called. + if ei, ok := balToUpdate.Balancer.(balancer.ExitIdler); ok { + ei.ExitIdle() + return + } + for sc := range balToUpdate.subconns { + sc.Connect() + } +} + +// UpdateSubConnState forwards the update to the appropriate child. +func (gsb *Balancer) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) { + gsb.currentMu.Lock() + defer gsb.currentMu.Unlock() + gsb.mu.Lock() + // Forward update to the appropriate child. Even if there is a pending + // balancer, the current balancer should continue to get SubConn updates to + // maintain the proper state while the pending is still connecting. + var balToUpdate *balancerWrapper + if gsb.balancerCurrent != nil && gsb.balancerCurrent.subconns[sc] { + balToUpdate = gsb.balancerCurrent + } else if gsb.balancerPending != nil && gsb.balancerPending.subconns[sc] { + balToUpdate = gsb.balancerPending + } + gsb.mu.Unlock() + if balToUpdate == nil { + // SubConn belonged to a stale lb policy that has not yet fully closed, + // or the balancer was already closed. + return + } + balToUpdate.UpdateSubConnState(sc, state) +} + +// Close closes any active child balancers. +func (gsb *Balancer) Close() { + gsb.mu.Lock() + gsb.closed = true + currentBalancerToClose := gsb.balancerCurrent + gsb.balancerCurrent = nil + pendingBalancerToClose := gsb.balancerPending + gsb.balancerPending = nil + gsb.mu.Unlock() + + currentBalancerToClose.Close() + pendingBalancerToClose.Close() +} + +// balancerWrapper wraps a balancer.Balancer, and overrides some Balancer +// methods to help cleanup SubConns created by the wrapped balancer. +// +// It implements the balancer.ClientConn interface and is passed down in that +// capacity to the wrapped balancer. It maintains a set of subConns created by +// the wrapped balancer and calls from the latter to create/update/remove +// SubConns update this set before being forwarded to the parent ClientConn. +// State updates from the wrapped balancer can result in invocation of the +// graceful switch logic. +type balancerWrapper struct { + balancer.Balancer + gsb *Balancer + + lastState balancer.State + subconns map[balancer.SubConn]bool // subconns created by this balancer +} + +func (bw *balancerWrapper) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) { + if state.ConnectivityState == connectivity.Shutdown { + bw.gsb.mu.Lock() + delete(bw.subconns, sc) + bw.gsb.mu.Unlock() + } + // There is no need to protect this read with a mutex, as the write to the + // Balancer field happens in SwitchTo, which completes before this can be + // called. + bw.Balancer.UpdateSubConnState(sc, state) +} + +// Close closes the underlying LB policy and removes the subconns it created. bw +// must not be referenced via balancerCurrent or balancerPending in gsb when +// called. gsb.mu must not be held. Does not panic with a nil receiver. +func (bw *balancerWrapper) Close() { + // before Close is called. + if bw == nil { + return + } + // There is no need to protect this read with a mutex, as Close() is + // impossible to be called concurrently with the write in SwitchTo(). The + // callsites of Close() for this balancer in Graceful Switch Balancer will + // never be called until SwitchTo() returns. + bw.Balancer.Close() + bw.gsb.mu.Lock() + for sc := range bw.subconns { + bw.gsb.cc.RemoveSubConn(sc) + } + bw.gsb.mu.Unlock() +} + +func (bw *balancerWrapper) UpdateState(state balancer.State) { + // Hold the mutex for this entire call to ensure it cannot occur + // concurrently with other updateState() calls. This causes updates to + // lastState and calls to cc.UpdateState to happen atomically. + bw.gsb.mu.Lock() + defer bw.gsb.mu.Unlock() + bw.lastState = state + + if !bw.gsb.balancerCurrentOrPending(bw) { + return + } + + if bw == bw.gsb.balancerCurrent { + // In the case that the current balancer exits READY, and there is a pending + // balancer, you can forward the pending balancer's cached State up to + // ClientConn and swap the pending into the current. This is because there + // is no reason to gracefully switch from and keep using the old policy as + // the ClientConn is not connected to any backends. + if state.ConnectivityState != connectivity.Ready && bw.gsb.balancerPending != nil { + bw.gsb.swap() + return + } + // Even if there is a pending balancer waiting to be gracefully switched to, + // continue to forward current balancer updates to the Client Conn. Ignoring + // state + picker from the current would cause undefined behavior/cause the + // system to behave incorrectly from the current LB policies perspective. + // Also, the current LB is still being used by grpc to choose SubConns per + // RPC, and thus should use the most updated form of the current balancer. + bw.gsb.cc.UpdateState(state) + return + } + // This method is now dealing with a state update from the pending balancer. + // If the current balancer is currently in a state other than READY, the new + // policy can be swapped into place immediately. This is because there is no + // reason to gracefully switch from and keep using the old policy as the + // ClientConn is not connected to any backends. + if state.ConnectivityState != connectivity.Connecting || bw.gsb.balancerCurrent.lastState.ConnectivityState != connectivity.Ready { + bw.gsb.swap() + } +} + +func (bw *balancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { + bw.gsb.mu.Lock() + if !bw.gsb.balancerCurrentOrPending(bw) { + bw.gsb.mu.Unlock() + return nil, fmt.Errorf("%T at address %p that called NewSubConn is deleted", bw, bw) + } + bw.gsb.mu.Unlock() + + sc, err := bw.gsb.cc.NewSubConn(addrs, opts) + if err != nil { + return nil, err + } + bw.gsb.mu.Lock() + if !bw.gsb.balancerCurrentOrPending(bw) { // balancer was closed during this call + bw.gsb.cc.RemoveSubConn(sc) + bw.gsb.mu.Unlock() + return nil, fmt.Errorf("%T at address %p that called NewSubConn is deleted", bw, bw) + } + bw.subconns[sc] = true + bw.gsb.mu.Unlock() + return sc, nil +} + +func (bw *balancerWrapper) ResolveNow(opts resolver.ResolveNowOptions) { + // Ignore ResolveNow requests from anything other than the most recent + // balancer, because older balancers were already removed from the config. + if bw != bw.gsb.latestBalancer() { + return + } + bw.gsb.cc.ResolveNow(opts) +} + +func (bw *balancerWrapper) RemoveSubConn(sc balancer.SubConn) { + bw.gsb.mu.Lock() + if !bw.gsb.balancerCurrentOrPending(bw) { + bw.gsb.mu.Unlock() + return + } + bw.gsb.mu.Unlock() + bw.gsb.cc.RemoveSubConn(sc) +} + +func (bw *balancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) { + bw.gsb.mu.Lock() + if !bw.gsb.balancerCurrentOrPending(bw) { + bw.gsb.mu.Unlock() + return + } + bw.gsb.mu.Unlock() + bw.gsb.cc.UpdateAddresses(sc, addrs) +} + +func (bw *balancerWrapper) Target() string { + return bw.gsb.cc.Target() +} diff --git a/providerlint/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go b/providerlint/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go index 5cc3aeddb21..0a25ce43f3f 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go @@ -31,7 +31,7 @@ import ( // Logger is the global binary logger. It can be used to get binary logger for // each method. type Logger interface { - getMethodLogger(methodName string) *MethodLogger + GetMethodLogger(methodName string) MethodLogger } // binLogger is the global binary logger for the binary. One of this should be @@ -49,17 +49,24 @@ func SetLogger(l Logger) { binLogger = l } +// GetLogger gets the binarg logger. +// +// Only call this at init time. +func GetLogger() Logger { + return binLogger +} + // GetMethodLogger returns the methodLogger for the given methodName. // // methodName should be in the format of "/service/method". // // Each methodLogger returned by this method is a new instance. This is to // generate sequence id within the call. -func GetMethodLogger(methodName string) *MethodLogger { +func GetMethodLogger(methodName string) MethodLogger { if binLogger == nil { return nil } - return binLogger.getMethodLogger(methodName) + return binLogger.GetMethodLogger(methodName) } func init() { @@ -68,17 +75,29 @@ func init() { binLogger = NewLoggerFromConfigString(configStr) } -type methodLoggerConfig struct { +// MethodLoggerConfig contains the setting for logging behavior of a method +// logger. Currently, it contains the max length of header and message. +type MethodLoggerConfig struct { // Max length of header and message. - hdr, msg uint64 + Header, Message uint64 +} + +// LoggerConfig contains the config for loggers to create method loggers. +type LoggerConfig struct { + All *MethodLoggerConfig + Services map[string]*MethodLoggerConfig + Methods map[string]*MethodLoggerConfig + + Blacklist map[string]struct{} } type logger struct { - all *methodLoggerConfig - services map[string]*methodLoggerConfig - methods map[string]*methodLoggerConfig + config LoggerConfig +} - blacklist map[string]struct{} +// NewLoggerFromConfig builds a logger with the given LoggerConfig. +func NewLoggerFromConfig(config LoggerConfig) Logger { + return &logger{config: config} } // newEmptyLogger creates an empty logger. The map fields need to be filled in @@ -88,57 +107,57 @@ func newEmptyLogger() *logger { } // Set method logger for "*". -func (l *logger) setDefaultMethodLogger(ml *methodLoggerConfig) error { - if l.all != nil { +func (l *logger) setDefaultMethodLogger(ml *MethodLoggerConfig) error { + if l.config.All != nil { return fmt.Errorf("conflicting global rules found") } - l.all = ml + l.config.All = ml return nil } // Set method logger for "service/*". // // New methodLogger with same service overrides the old one. -func (l *logger) setServiceMethodLogger(service string, ml *methodLoggerConfig) error { - if _, ok := l.services[service]; ok { +func (l *logger) setServiceMethodLogger(service string, ml *MethodLoggerConfig) error { + if _, ok := l.config.Services[service]; ok { return fmt.Errorf("conflicting service rules for service %v found", service) } - if l.services == nil { - l.services = make(map[string]*methodLoggerConfig) + if l.config.Services == nil { + l.config.Services = make(map[string]*MethodLoggerConfig) } - l.services[service] = ml + l.config.Services[service] = ml return nil } // Set method logger for "service/method". // // New methodLogger with same method overrides the old one. -func (l *logger) setMethodMethodLogger(method string, ml *methodLoggerConfig) error { - if _, ok := l.blacklist[method]; ok { +func (l *logger) setMethodMethodLogger(method string, ml *MethodLoggerConfig) error { + if _, ok := l.config.Blacklist[method]; ok { return fmt.Errorf("conflicting blacklist rules for method %v found", method) } - if _, ok := l.methods[method]; ok { + if _, ok := l.config.Methods[method]; ok { return fmt.Errorf("conflicting method rules for method %v found", method) } - if l.methods == nil { - l.methods = make(map[string]*methodLoggerConfig) + if l.config.Methods == nil { + l.config.Methods = make(map[string]*MethodLoggerConfig) } - l.methods[method] = ml + l.config.Methods[method] = ml return nil } // Set blacklist method for "-service/method". func (l *logger) setBlacklist(method string) error { - if _, ok := l.blacklist[method]; ok { + if _, ok := l.config.Blacklist[method]; ok { return fmt.Errorf("conflicting blacklist rules for method %v found", method) } - if _, ok := l.methods[method]; ok { + if _, ok := l.config.Methods[method]; ok { return fmt.Errorf("conflicting method rules for method %v found", method) } - if l.blacklist == nil { - l.blacklist = make(map[string]struct{}) + if l.config.Blacklist == nil { + l.config.Blacklist = make(map[string]struct{}) } - l.blacklist[method] = struct{}{} + l.config.Blacklist[method] = struct{}{} return nil } @@ -148,23 +167,23 @@ func (l *logger) setBlacklist(method string) error { // // Each methodLogger returned by this method is a new instance. This is to // generate sequence id within the call. -func (l *logger) getMethodLogger(methodName string) *MethodLogger { +func (l *logger) GetMethodLogger(methodName string) MethodLogger { s, m, err := grpcutil.ParseMethod(methodName) if err != nil { grpclogLogger.Infof("binarylogging: failed to parse %q: %v", methodName, err) return nil } - if ml, ok := l.methods[s+"/"+m]; ok { - return newMethodLogger(ml.hdr, ml.msg) + if ml, ok := l.config.Methods[s+"/"+m]; ok { + return newMethodLogger(ml.Header, ml.Message) } - if _, ok := l.blacklist[s+"/"+m]; ok { + if _, ok := l.config.Blacklist[s+"/"+m]; ok { return nil } - if ml, ok := l.services[s]; ok { - return newMethodLogger(ml.hdr, ml.msg) + if ml, ok := l.config.Services[s]; ok { + return newMethodLogger(ml.Header, ml.Message) } - if l.all == nil { + if l.config.All == nil { return nil } - return newMethodLogger(l.all.hdr, l.all.msg) + return newMethodLogger(l.config.All.Header, l.config.All.Message) } diff --git a/providerlint/vendor/google.golang.org/grpc/internal/binarylog/env_config.go b/providerlint/vendor/google.golang.org/grpc/internal/binarylog/env_config.go index d8f4e7602fd..ab589a76bf9 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/binarylog/env_config.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/binarylog/env_config.go @@ -89,7 +89,7 @@ func (l *logger) fillMethodLoggerWithConfigString(config string) error { if err != nil { return fmt.Errorf("invalid config: %q, %v", config, err) } - if err := l.setDefaultMethodLogger(&methodLoggerConfig{hdr: hdr, msg: msg}); err != nil { + if err := l.setDefaultMethodLogger(&MethodLoggerConfig{Header: hdr, Message: msg}); err != nil { return fmt.Errorf("invalid config: %v", err) } return nil @@ -104,11 +104,11 @@ func (l *logger) fillMethodLoggerWithConfigString(config string) error { return fmt.Errorf("invalid header/message length config: %q, %v", suffix, err) } if m == "*" { - if err := l.setServiceMethodLogger(s, &methodLoggerConfig{hdr: hdr, msg: msg}); err != nil { + if err := l.setServiceMethodLogger(s, &MethodLoggerConfig{Header: hdr, Message: msg}); err != nil { return fmt.Errorf("invalid config: %v", err) } } else { - if err := l.setMethodMethodLogger(s+"/"+m, &methodLoggerConfig{hdr: hdr, msg: msg}); err != nil { + if err := l.setMethodMethodLogger(s+"/"+m, &MethodLoggerConfig{Header: hdr, Message: msg}); err != nil { return fmt.Errorf("invalid config: %v", err) } } diff --git a/providerlint/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go b/providerlint/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go index 0cdb4183150..24df0a1a0c4 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go @@ -48,7 +48,11 @@ func (g *callIDGenerator) reset() { var idGen callIDGenerator // MethodLogger is the sub-logger for each method. -type MethodLogger struct { +type MethodLogger interface { + Log(LogEntryConfig) +} + +type methodLogger struct { headerMaxLen, messageMaxLen uint64 callID uint64 @@ -57,8 +61,8 @@ type MethodLogger struct { sink Sink // TODO(blog): make this plugable. } -func newMethodLogger(h, m uint64) *MethodLogger { - return &MethodLogger{ +func newMethodLogger(h, m uint64) *methodLogger { + return &methodLogger{ headerMaxLen: h, messageMaxLen: m, @@ -69,8 +73,10 @@ func newMethodLogger(h, m uint64) *MethodLogger { } } -// Log creates a proto binary log entry, and logs it to the sink. -func (ml *MethodLogger) Log(c LogEntryConfig) { +// Build is an internal only method for building the proto message out of the +// input event. It's made public to enable other library to reuse as much logic +// in methodLogger as possible. +func (ml *methodLogger) Build(c LogEntryConfig) *pb.GrpcLogEntry { m := c.toProto() timestamp, _ := ptypes.TimestampProto(time.Now()) m.Timestamp = timestamp @@ -85,11 +91,15 @@ func (ml *MethodLogger) Log(c LogEntryConfig) { case *pb.GrpcLogEntry_Message: m.PayloadTruncated = ml.truncateMessage(pay.Message) } + return m +} - ml.sink.Write(m) +// Log creates a proto binary log entry, and logs it to the sink. +func (ml *methodLogger) Log(c LogEntryConfig) { + ml.sink.Write(ml.Build(c)) } -func (ml *MethodLogger) truncateMetadata(mdPb *pb.Metadata) (truncated bool) { +func (ml *methodLogger) truncateMetadata(mdPb *pb.Metadata) (truncated bool) { if ml.headerMaxLen == maxUInt { return false } @@ -119,7 +129,7 @@ func (ml *MethodLogger) truncateMetadata(mdPb *pb.Metadata) (truncated bool) { return truncated } -func (ml *MethodLogger) truncateMessage(msgPb *pb.Message) (truncated bool) { +func (ml *methodLogger) truncateMessage(msgPb *pb.Message) (truncated bool) { if ml.messageMaxLen == maxUInt { return false } diff --git a/providerlint/vendor/google.golang.org/grpc/internal/channelz/funcs.go b/providerlint/vendor/google.golang.org/grpc/internal/channelz/funcs.go index ea660a147cf..777cbcd7921 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/channelz/funcs.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/channelz/funcs.go @@ -25,6 +25,7 @@ package channelz import ( "context" + "errors" "fmt" "sort" "sync" @@ -184,54 +185,77 @@ func GetServer(id int64) *ServerMetric { return db.get().GetServer(id) } -// RegisterChannel registers the given channel c in channelz database with ref -// as its reference name, and add it to the child list of its parent (identified -// by pid). pid = 0 means no parent. It returns the unique channelz tracking id -// assigned to this channel. -func RegisterChannel(c Channel, pid int64, ref string) int64 { +// RegisterChannel registers the given channel c in the channelz database with +// ref as its reference name, and adds it to the child list of its parent +// (identified by pid). pid == nil means no parent. +// +// Returns a unique channelz identifier assigned to this channel. +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterChannel(c Channel, pid *Identifier, ref string) *Identifier { id := idGen.genID() + var parent int64 + isTopChannel := true + if pid != nil { + isTopChannel = false + parent = pid.Int() + } + + if !IsOn() { + return newIdentifer(RefChannel, id, pid) + } + cn := &channel{ refName: ref, c: c, subChans: make(map[int64]string), nestedChans: make(map[int64]string), id: id, - pid: pid, + pid: parent, trace: &channelTrace{createdTime: time.Now(), events: make([]*TraceEvent, 0, getMaxTraceEntry())}, } - if pid == 0 { - db.get().addChannel(id, cn, true, pid) - } else { - db.get().addChannel(id, cn, false, pid) - } - return id + db.get().addChannel(id, cn, isTopChannel, parent) + return newIdentifer(RefChannel, id, pid) } -// RegisterSubChannel registers the given channel c in channelz database with ref -// as its reference name, and add it to the child list of its parent (identified -// by pid). It returns the unique channelz tracking id assigned to this subchannel. -func RegisterSubChannel(c Channel, pid int64, ref string) int64 { - if pid == 0 { - logger.Error("a SubChannel's parent id cannot be 0") - return 0 +// RegisterSubChannel registers the given subChannel c in the channelz database +// with ref as its reference name, and adds it to the child list of its parent +// (identified by pid). +// +// Returns a unique channelz identifier assigned to this subChannel. +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterSubChannel(c Channel, pid *Identifier, ref string) (*Identifier, error) { + if pid == nil { + return nil, errors.New("a SubChannel's parent id cannot be nil") } id := idGen.genID() + if !IsOn() { + return newIdentifer(RefSubChannel, id, pid), nil + } + sc := &subChannel{ refName: ref, c: c, sockets: make(map[int64]string), id: id, - pid: pid, + pid: pid.Int(), trace: &channelTrace{createdTime: time.Now(), events: make([]*TraceEvent, 0, getMaxTraceEntry())}, } - db.get().addSubChannel(id, sc, pid) - return id + db.get().addSubChannel(id, sc, pid.Int()) + return newIdentifer(RefSubChannel, id, pid), nil } // RegisterServer registers the given server s in channelz database. It returns // the unique channelz tracking id assigned to this server. -func RegisterServer(s Server, ref string) int64 { +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterServer(s Server, ref string) *Identifier { id := idGen.genID() + if !IsOn() { + return newIdentifer(RefServer, id, nil) + } + svr := &server{ refName: ref, s: s, @@ -240,71 +264,92 @@ func RegisterServer(s Server, ref string) int64 { id: id, } db.get().addServer(id, svr) - return id + return newIdentifer(RefServer, id, nil) } // RegisterListenSocket registers the given listen socket s in channelz database // with ref as its reference name, and add it to the child list of its parent // (identified by pid). It returns the unique channelz tracking id assigned to // this listen socket. -func RegisterListenSocket(s Socket, pid int64, ref string) int64 { - if pid == 0 { - logger.Error("a ListenSocket's parent id cannot be 0") - return 0 +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterListenSocket(s Socket, pid *Identifier, ref string) (*Identifier, error) { + if pid == nil { + return nil, errors.New("a ListenSocket's parent id cannot be 0") } id := idGen.genID() - ls := &listenSocket{refName: ref, s: s, id: id, pid: pid} - db.get().addListenSocket(id, ls, pid) - return id + if !IsOn() { + return newIdentifer(RefListenSocket, id, pid), nil + } + + ls := &listenSocket{refName: ref, s: s, id: id, pid: pid.Int()} + db.get().addListenSocket(id, ls, pid.Int()) + return newIdentifer(RefListenSocket, id, pid), nil } // RegisterNormalSocket registers the given normal socket s in channelz database -// with ref as its reference name, and add it to the child list of its parent +// with ref as its reference name, and adds it to the child list of its parent // (identified by pid). It returns the unique channelz tracking id assigned to // this normal socket. -func RegisterNormalSocket(s Socket, pid int64, ref string) int64 { - if pid == 0 { - logger.Error("a NormalSocket's parent id cannot be 0") - return 0 +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterNormalSocket(s Socket, pid *Identifier, ref string) (*Identifier, error) { + if pid == nil { + return nil, errors.New("a NormalSocket's parent id cannot be 0") } id := idGen.genID() - ns := &normalSocket{refName: ref, s: s, id: id, pid: pid} - db.get().addNormalSocket(id, ns, pid) - return id + if !IsOn() { + return newIdentifer(RefNormalSocket, id, pid), nil + } + + ns := &normalSocket{refName: ref, s: s, id: id, pid: pid.Int()} + db.get().addNormalSocket(id, ns, pid.Int()) + return newIdentifer(RefNormalSocket, id, pid), nil } // RemoveEntry removes an entry with unique channelz tracking id to be id from // channelz database. -func RemoveEntry(id int64) { - db.get().removeEntry(id) +// +// If channelz is not turned ON, this function is a no-op. +func RemoveEntry(id *Identifier) { + if !IsOn() { + return + } + db.get().removeEntry(id.Int()) } -// TraceEventDesc is what the caller of AddTraceEvent should provide to describe the event to be added -// to the channel trace. -// The Parent field is optional. It is used for event that will be recorded in the entity's parent -// trace also. +// TraceEventDesc is what the caller of AddTraceEvent should provide to describe +// the event to be added to the channel trace. +// +// The Parent field is optional. It is used for an event that will be recorded +// in the entity's parent trace. type TraceEventDesc struct { Desc string Severity Severity Parent *TraceEventDesc } -// AddTraceEvent adds trace related to the entity with specified id, using the provided TraceEventDesc. -func AddTraceEvent(l grpclog.DepthLoggerV2, id int64, depth int, desc *TraceEventDesc) { - for d := desc; d != nil; d = d.Parent { - switch d.Severity { - case CtUnknown, CtInfo: - l.InfoDepth(depth+1, d.Desc) - case CtWarning: - l.WarningDepth(depth+1, d.Desc) - case CtError: - l.ErrorDepth(depth+1, d.Desc) - } +// AddTraceEvent adds trace related to the entity with specified id, using the +// provided TraceEventDesc. +// +// If channelz is not turned ON, this will simply log the event descriptions. +func AddTraceEvent(l grpclog.DepthLoggerV2, id *Identifier, depth int, desc *TraceEventDesc) { + // Log only the trace description associated with the bottom most entity. + switch desc.Severity { + case CtUnknown, CtInfo: + l.InfoDepth(depth+1, withParens(id)+desc.Desc) + case CtWarning: + l.WarningDepth(depth+1, withParens(id)+desc.Desc) + case CtError: + l.ErrorDepth(depth+1, withParens(id)+desc.Desc) } + if getMaxTraceEntry() == 0 { return } - db.get().traceEvent(id, desc) + if IsOn() { + db.get().traceEvent(id.Int(), desc) + } } // channelMap is the storage data structure for channelz. diff --git a/providerlint/vendor/google.golang.org/grpc/internal/channelz/id.go b/providerlint/vendor/google.golang.org/grpc/internal/channelz/id.go new file mode 100644 index 00000000000..c9a27acd371 --- /dev/null +++ b/providerlint/vendor/google.golang.org/grpc/internal/channelz/id.go @@ -0,0 +1,75 @@ +/* + * + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package channelz + +import "fmt" + +// Identifier is an opaque identifier which uniquely identifies an entity in the +// channelz database. +type Identifier struct { + typ RefChannelType + id int64 + str string + pid *Identifier +} + +// Type returns the entity type corresponding to id. +func (id *Identifier) Type() RefChannelType { + return id.typ +} + +// Int returns the integer identifier corresponding to id. +func (id *Identifier) Int() int64 { + return id.id +} + +// String returns a string representation of the entity corresponding to id. +// +// This includes some information about the parent as well. Examples: +// Top-level channel: [Channel #channel-number] +// Nested channel: [Channel #parent-channel-number Channel #channel-number] +// Sub channel: [Channel #parent-channel SubChannel #subchannel-number] +func (id *Identifier) String() string { + return id.str +} + +// Equal returns true if other is the same as id. +func (id *Identifier) Equal(other *Identifier) bool { + if (id != nil) != (other != nil) { + return false + } + if id == nil && other == nil { + return true + } + return id.typ == other.typ && id.id == other.id && id.pid == other.pid +} + +// NewIdentifierForTesting returns a new opaque identifier to be used only for +// testing purposes. +func NewIdentifierForTesting(typ RefChannelType, id int64, pid *Identifier) *Identifier { + return newIdentifer(typ, id, pid) +} + +func newIdentifer(typ RefChannelType, id int64, pid *Identifier) *Identifier { + str := fmt.Sprintf("%s #%d", typ, id) + if pid != nil { + str = fmt.Sprintf("%s %s", pid, str) + } + return &Identifier{typ: typ, id: id, str: str, pid: pid} +} diff --git a/providerlint/vendor/google.golang.org/grpc/internal/channelz/logging.go b/providerlint/vendor/google.golang.org/grpc/internal/channelz/logging.go index b0013f9c886..8e13a3d2ce7 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/channelz/logging.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/channelz/logging.go @@ -26,77 +26,54 @@ import ( var logger = grpclog.Component("channelz") +func withParens(id *Identifier) string { + return "[" + id.String() + "] " +} + // Info logs and adds a trace event if channelz is on. -func Info(l grpclog.DepthLoggerV2, id int64, args ...interface{}) { - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: fmt.Sprint(args...), - Severity: CtInfo, - }) - } else { - l.InfoDepth(1, args...) - } +func Info(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprint(args...), + Severity: CtInfo, + }) } // Infof logs and adds a trace event if channelz is on. -func Infof(l grpclog.DepthLoggerV2, id int64, format string, args ...interface{}) { - msg := fmt.Sprintf(format, args...) - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: msg, - Severity: CtInfo, - }) - } else { - l.InfoDepth(1, msg) - } +func Infof(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprintf(format, args...), + Severity: CtInfo, + }) } // Warning logs and adds a trace event if channelz is on. -func Warning(l grpclog.DepthLoggerV2, id int64, args ...interface{}) { - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: fmt.Sprint(args...), - Severity: CtWarning, - }) - } else { - l.WarningDepth(1, args...) - } +func Warning(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprint(args...), + Severity: CtWarning, + }) } // Warningf logs and adds a trace event if channelz is on. -func Warningf(l grpclog.DepthLoggerV2, id int64, format string, args ...interface{}) { - msg := fmt.Sprintf(format, args...) - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: msg, - Severity: CtWarning, - }) - } else { - l.WarningDepth(1, msg) - } +func Warningf(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprintf(format, args...), + Severity: CtWarning, + }) } // Error logs and adds a trace event if channelz is on. -func Error(l grpclog.DepthLoggerV2, id int64, args ...interface{}) { - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: fmt.Sprint(args...), - Severity: CtError, - }) - } else { - l.ErrorDepth(1, args...) - } +func Error(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprint(args...), + Severity: CtError, + }) } // Errorf logs and adds a trace event if channelz is on. -func Errorf(l grpclog.DepthLoggerV2, id int64, format string, args ...interface{}) { - msg := fmt.Sprintf(format, args...) - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: msg, - Severity: CtError, - }) - } else { - l.ErrorDepth(1, msg) - } +func Errorf(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprintf(format, args...), + Severity: CtError, + }) } diff --git a/providerlint/vendor/google.golang.org/grpc/internal/channelz/types.go b/providerlint/vendor/google.golang.org/grpc/internal/channelz/types.go index 3c595d154bd..ad0ce4dabf0 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/channelz/types.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/channelz/types.go @@ -686,12 +686,33 @@ const ( type RefChannelType int const ( + // RefUnknown indicates an unknown entity type, the zero value for this type. + RefUnknown RefChannelType = iota // RefChannel indicates the referenced entity is a Channel. - RefChannel RefChannelType = iota + RefChannel // RefSubChannel indicates the referenced entity is a SubChannel. RefSubChannel + // RefServer indicates the referenced entity is a Server. + RefServer + // RefListenSocket indicates the referenced entity is a ListenSocket. + RefListenSocket + // RefNormalSocket indicates the referenced entity is a NormalSocket. + RefNormalSocket ) +var refChannelTypeToString = map[RefChannelType]string{ + RefUnknown: "Unknown", + RefChannel: "Channel", + RefSubChannel: "SubChannel", + RefServer: "Server", + RefListenSocket: "ListenSocket", + RefNormalSocket: "NormalSocket", +} + +func (r RefChannelType) String() string { + return refChannelTypeToString[r] +} + func (c *channelTrace) dumpData() *ChannelTrace { c.mu.Lock() ct := &ChannelTrace{EventNum: c.eventCount, CreationTime: c.createdTime} diff --git a/providerlint/vendor/google.golang.org/grpc/internal/internal.go b/providerlint/vendor/google.golang.org/grpc/internal/internal.go index 20fb880f344..6d355b0b013 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/internal.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/internal.go @@ -85,3 +85,9 @@ const ( // that supports backend returned by grpclb balancer. CredsBundleModeBackendFromBalancer = "backend-from-balancer" ) + +// RLSLoadBalancingPolicyName is the name of the RLS LB policy. +// +// It currently has an experimental suffix which would be removed once +// end-to-end testing of the policy is completed. +const RLSLoadBalancingPolicyName = "rls_experimental" diff --git a/providerlint/vendor/google.golang.org/grpc/internal/metadata/metadata.go b/providerlint/vendor/google.golang.org/grpc/internal/metadata/metadata.go index b8733dbf340..b2980f8ac44 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/metadata/metadata.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/metadata/metadata.go @@ -22,6 +22,9 @@ package metadata import ( + "fmt" + "strings" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/resolver" ) @@ -72,3 +75,46 @@ func Set(addr resolver.Address, md metadata.MD) resolver.Address { addr.Attributes = addr.Attributes.WithValue(mdKey, mdValue(md)) return addr } + +// Validate returns an error if the input md contains invalid keys or values. +// +// If the header is not a pseudo-header, the following items are checked: +// - header names must contain one or more characters from this set [0-9 a-z _ - .]. +// - if the header-name ends with a "-bin" suffix, no validation of the header value is performed. +// - otherwise, the header value must contain one or more characters from the set [%x20-%x7E]. +func Validate(md metadata.MD) error { + for k, vals := range md { + // pseudo-header will be ignored + if k[0] == ':' { + continue + } + // check key, for i that saving a conversion if not using for range + for i := 0; i < len(k); i++ { + r := k[i] + if !(r >= 'a' && r <= 'z') && !(r >= '0' && r <= '9') && r != '.' && r != '-' && r != '_' { + return fmt.Errorf("header key %q contains illegal characters not in [0-9a-z-_.]", k) + } + } + if strings.HasSuffix(k, "-bin") { + continue + } + // check value + for _, val := range vals { + if hasNotPrintable(val) { + return fmt.Errorf("header key %q contains value with non-printable ASCII characters", k) + } + } + } + return nil +} + +// hasNotPrintable return true if msg contains any characters which are not in %x20-%x7E +func hasNotPrintable(msg string) bool { + // for i that saving a conversion if not using for range + for i := 0; i < len(msg); i++ { + if msg[i] < 0x20 || msg[i] > 0x7E { + return true + } + } + return false +} diff --git a/providerlint/vendor/google.golang.org/grpc/internal/pretty/pretty.go b/providerlint/vendor/google.golang.org/grpc/internal/pretty/pretty.go new file mode 100644 index 00000000000..0177af4b511 --- /dev/null +++ b/providerlint/vendor/google.golang.org/grpc/internal/pretty/pretty.go @@ -0,0 +1,82 @@ +/* + * + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package pretty defines helper functions to pretty-print structs for logging. +package pretty + +import ( + "bytes" + "encoding/json" + "fmt" + + "github.com/golang/protobuf/jsonpb" + protov1 "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/encoding/protojson" + protov2 "google.golang.org/protobuf/proto" +) + +const jsonIndent = " " + +// ToJSON marshals the input into a json string. +// +// If marshal fails, it falls back to fmt.Sprintf("%+v"). +func ToJSON(e interface{}) string { + switch ee := e.(type) { + case protov1.Message: + mm := jsonpb.Marshaler{Indent: jsonIndent} + ret, err := mm.MarshalToString(ee) + if err != nil { + // This may fail for proto.Anys, e.g. for xDS v2, LDS, the v2 + // messages are not imported, and this will fail because the message + // is not found. + return fmt.Sprintf("%+v", ee) + } + return ret + case protov2.Message: + mm := protojson.MarshalOptions{ + Multiline: true, + Indent: jsonIndent, + } + ret, err := mm.Marshal(ee) + if err != nil { + // This may fail for proto.Anys, e.g. for xDS v2, LDS, the v2 + // messages are not imported, and this will fail because the message + // is not found. + return fmt.Sprintf("%+v", ee) + } + return string(ret) + default: + ret, err := json.MarshalIndent(ee, "", jsonIndent) + if err != nil { + return fmt.Sprintf("%+v", ee) + } + return string(ret) + } +} + +// FormatJSON formats the input json bytes with indentation. +// +// If Indent fails, it returns the unchanged input as string. +func FormatJSON(b []byte) string { + var out bytes.Buffer + err := json.Indent(&out, b, "", jsonIndent) + if err != nil { + return string(b) + } + return out.String() +} diff --git a/providerlint/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/providerlint/vendor/google.golang.org/grpc/internal/transport/http2_client.go index f0c72d33710..38ed3d566ff 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -132,7 +132,7 @@ type http2Client struct { kpDormant bool // Fields below are for channelz metric collection. - channelzID int64 // channelz unique identification number + channelzID *channelz.Identifier czData *channelzData onGoAway func(GoAwayReason) @@ -351,8 +351,9 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts } t.statsHandler.HandleConn(t.ctx, connBegin) } - if channelz.IsOn() { - t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, fmt.Sprintf("%s -> %s", t.localAddr, t.remoteAddr)) + t.channelzID, err = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, fmt.Sprintf("%s -> %s", t.localAddr, t.remoteAddr)) + if err != nil { + return nil, err } if t.keepaliveEnabled { t.kpDormancyCond = sync.NewCond(&t.mu) @@ -898,9 +899,7 @@ func (t *http2Client) Close(err error) { t.controlBuf.finish() t.cancel() t.conn.Close() - if channelz.IsOn() { - channelz.RemoveEntry(t.channelzID) - } + channelz.RemoveEntry(t.channelzID) // Append info about previous goaways if there were any, since this may be important // for understanding the root cause for this connection to be closed. _, goAwayDebugMessage := t.GetGoAwayReason() diff --git a/providerlint/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/providerlint/vendor/google.golang.org/grpc/internal/transport/http2_server.go index 2c6eaf0e59c..0956b500c18 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -36,6 +36,7 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" "google.golang.org/grpc/internal/grpcutil" + "google.golang.org/grpc/internal/syscall" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" @@ -117,7 +118,7 @@ type http2Server struct { idle time.Time // Fields below are for channelz metric collection. - channelzID int64 // channelz unique identification number + channelzID *channelz.Identifier czData *channelzData bufferPool *bufferPool @@ -231,6 +232,11 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, if kp.Timeout == 0 { kp.Timeout = defaultServerKeepaliveTimeout } + if kp.Time != infinity { + if err = syscall.SetTCPUserTimeout(conn, kp.Timeout); err != nil { + return nil, connectionErrorf(false, err, "transport: failed to set TCP_USER_TIMEOUT: %v", err) + } + } kep := config.KeepalivePolicy if kep.MinTime == 0 { kep.MinTime = defaultKeepalivePolicyMinTime @@ -275,12 +281,12 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, connBegin := &stats.ConnBegin{} t.stats.HandleConn(t.ctx, connBegin) } - if channelz.IsOn() { - t.channelzID = channelz.RegisterNormalSocket(t, config.ChannelzParentID, fmt.Sprintf("%s -> %s", t.remoteAddr, t.localAddr)) + t.channelzID, err = channelz.RegisterNormalSocket(t, config.ChannelzParentID, fmt.Sprintf("%s -> %s", t.remoteAddr, t.localAddr)) + if err != nil { + return nil, err } t.connectionID = atomic.AddUint64(&serverConnectionCounter, 1) - t.framer.writer.Flush() defer func() { @@ -1210,9 +1216,7 @@ func (t *http2Server) Close() { if err := t.conn.Close(); err != nil && logger.V(logLevel) { logger.Infof("transport: error closing conn during Close: %v", err) } - if channelz.IsOn() { - channelz.RemoveEntry(t.channelzID) - } + channelz.RemoveEntry(t.channelzID) // Cancel all active streams. for _, s := range streams { s.cancel() diff --git a/providerlint/vendor/google.golang.org/grpc/internal/transport/transport.go b/providerlint/vendor/google.golang.org/grpc/internal/transport/transport.go index 0c43efaa649..a9ce717f160 100644 --- a/providerlint/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/providerlint/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -34,6 +34,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/resolver" @@ -529,7 +530,7 @@ type ServerConfig struct { InitialConnWindowSize int32 WriteBufferSize int ReadBufferSize int - ChannelzParentID int64 + ChannelzParentID *channelz.Identifier MaxHeaderListSize *uint32 HeaderTableSize *uint32 } @@ -563,7 +564,7 @@ type ConnectOptions struct { // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall. ReadBufferSize int // ChannelzParentID sets the addrConn id which initiate the creation of this client transport. - ChannelzParentID int64 + ChannelzParentID *channelz.Identifier // MaxHeaderListSize sets the max (uncompressed) size of header list that is prepared to be received. MaxHeaderListSize *uint32 // UseProxy specifies if a proxy should be used. diff --git a/providerlint/vendor/google.golang.org/grpc/metadata/metadata.go b/providerlint/vendor/google.golang.org/grpc/metadata/metadata.go index 3604c7819fd..8e0f6abe89d 100644 --- a/providerlint/vendor/google.golang.org/grpc/metadata/metadata.go +++ b/providerlint/vendor/google.golang.org/grpc/metadata/metadata.go @@ -188,7 +188,9 @@ func FromIncomingContext(ctx context.Context) (MD, bool) { // map, and there's no guarantee that the MD attached to the context is // created using our helper functions. key := strings.ToLower(k) - out[key] = v + s := make([]string, len(v)) + copy(s, v) + out[key] = s } return out, true } @@ -226,7 +228,9 @@ func FromOutgoingContext(ctx context.Context) (MD, bool) { // map, and there's no guarantee that the MD attached to the context is // created using our helper functions. key := strings.ToLower(k) - out[key] = v + s := make([]string, len(v)) + copy(s, v) + out[key] = s } for _, added := range raw.added { if len(added)%2 == 1 { diff --git a/providerlint/vendor/google.golang.org/grpc/pickfirst.go b/providerlint/vendor/google.golang.org/grpc/pickfirst.go index 5168b62b078..fb7a99e0a27 100644 --- a/providerlint/vendor/google.golang.org/grpc/pickfirst.go +++ b/providerlint/vendor/google.golang.org/grpc/pickfirst.go @@ -44,79 +44,107 @@ func (*pickfirstBuilder) Name() string { } type pickfirstBalancer struct { - state connectivity.State - cc balancer.ClientConn - sc balancer.SubConn + state connectivity.State + cc balancer.ClientConn + subConn balancer.SubConn } func (b *pickfirstBalancer) ResolverError(err error) { - switch b.state { - case connectivity.TransientFailure, connectivity.Idle, connectivity.Connecting: - // Set a failing picker if we don't have a good picker. - b.cc.UpdateState(balancer.State{ConnectivityState: connectivity.TransientFailure, - Picker: &picker{err: fmt.Errorf("name resolver error: %v", err)}, - }) - } if logger.V(2) { logger.Infof("pickfirstBalancer: ResolverError called with error %v", err) } + if b.subConn == nil { + b.state = connectivity.TransientFailure + } + + if b.state != connectivity.TransientFailure { + // The picker will not change since the balancer does not currently + // report an error. + return + } + b.cc.UpdateState(balancer.State{ + ConnectivityState: connectivity.TransientFailure, + Picker: &picker{err: fmt.Errorf("name resolver error: %v", err)}, + }) } -func (b *pickfirstBalancer) UpdateClientConnState(cs balancer.ClientConnState) error { - if len(cs.ResolverState.Addresses) == 0 { +func (b *pickfirstBalancer) UpdateClientConnState(state balancer.ClientConnState) error { + if len(state.ResolverState.Addresses) == 0 { + // The resolver reported an empty address list. Treat it like an error by + // calling b.ResolverError. + if b.subConn != nil { + // Remove the old subConn. All addresses were removed, so it is no longer + // valid. + b.cc.RemoveSubConn(b.subConn) + b.subConn = nil + } b.ResolverError(errors.New("produced zero addresses")) return balancer.ErrBadResolverState } - if b.sc == nil { - var err error - b.sc, err = b.cc.NewSubConn(cs.ResolverState.Addresses, balancer.NewSubConnOptions{}) - if err != nil { - if logger.V(2) { - logger.Errorf("pickfirstBalancer: failed to NewSubConn: %v", err) - } - b.state = connectivity.TransientFailure - b.cc.UpdateState(balancer.State{ConnectivityState: connectivity.TransientFailure, - Picker: &picker{err: fmt.Errorf("error creating connection: %v", err)}, - }) - return balancer.ErrBadResolverState + + if b.subConn != nil { + b.cc.UpdateAddresses(b.subConn, state.ResolverState.Addresses) + return nil + } + + subConn, err := b.cc.NewSubConn(state.ResolverState.Addresses, balancer.NewSubConnOptions{}) + if err != nil { + if logger.V(2) { + logger.Errorf("pickfirstBalancer: failed to NewSubConn: %v", err) } - b.state = connectivity.Idle - b.cc.UpdateState(balancer.State{ConnectivityState: connectivity.Idle, Picker: &picker{result: balancer.PickResult{SubConn: b.sc}}}) - b.sc.Connect() - } else { - b.cc.UpdateAddresses(b.sc, cs.ResolverState.Addresses) - b.sc.Connect() + b.state = connectivity.TransientFailure + b.cc.UpdateState(balancer.State{ + ConnectivityState: connectivity.TransientFailure, + Picker: &picker{err: fmt.Errorf("error creating connection: %v", err)}, + }) + return balancer.ErrBadResolverState } + b.subConn = subConn + b.state = connectivity.Idle + b.cc.UpdateState(balancer.State{ + ConnectivityState: connectivity.Idle, + Picker: &picker{result: balancer.PickResult{SubConn: b.subConn}}, + }) + b.subConn.Connect() return nil } -func (b *pickfirstBalancer) UpdateSubConnState(sc balancer.SubConn, s balancer.SubConnState) { +func (b *pickfirstBalancer) UpdateSubConnState(subConn balancer.SubConn, state balancer.SubConnState) { if logger.V(2) { - logger.Infof("pickfirstBalancer: UpdateSubConnState: %p, %v", sc, s) + logger.Infof("pickfirstBalancer: UpdateSubConnState: %p, %v", subConn, state) } - if b.sc != sc { + if b.subConn != subConn { if logger.V(2) { - logger.Infof("pickfirstBalancer: ignored state change because sc is not recognized") + logger.Infof("pickfirstBalancer: ignored state change because subConn is not recognized") } return } - b.state = s.ConnectivityState - if s.ConnectivityState == connectivity.Shutdown { - b.sc = nil + b.state = state.ConnectivityState + if state.ConnectivityState == connectivity.Shutdown { + b.subConn = nil return } - switch s.ConnectivityState { + switch state.ConnectivityState { case connectivity.Ready: - b.cc.UpdateState(balancer.State{ConnectivityState: s.ConnectivityState, Picker: &picker{result: balancer.PickResult{SubConn: sc}}}) + b.cc.UpdateState(balancer.State{ + ConnectivityState: state.ConnectivityState, + Picker: &picker{result: balancer.PickResult{SubConn: subConn}}, + }) case connectivity.Connecting: - b.cc.UpdateState(balancer.State{ConnectivityState: s.ConnectivityState, Picker: &picker{err: balancer.ErrNoSubConnAvailable}}) + b.cc.UpdateState(balancer.State{ + ConnectivityState: state.ConnectivityState, + Picker: &picker{err: balancer.ErrNoSubConnAvailable}, + }) case connectivity.Idle: - b.cc.UpdateState(balancer.State{ConnectivityState: s.ConnectivityState, Picker: &idlePicker{sc: sc}}) + b.cc.UpdateState(balancer.State{ + ConnectivityState: state.ConnectivityState, + Picker: &idlePicker{subConn: subConn}, + }) case connectivity.TransientFailure: b.cc.UpdateState(balancer.State{ - ConnectivityState: s.ConnectivityState, - Picker: &picker{err: s.ConnectionError}, + ConnectivityState: state.ConnectivityState, + Picker: &picker{err: state.ConnectionError}, }) } } @@ -125,8 +153,8 @@ func (b *pickfirstBalancer) Close() { } func (b *pickfirstBalancer) ExitIdle() { - if b.sc != nil && b.state == connectivity.Idle { - b.sc.Connect() + if b.subConn != nil && b.state == connectivity.Idle { + b.subConn.Connect() } } @@ -135,18 +163,18 @@ type picker struct { err error } -func (p *picker) Pick(info balancer.PickInfo) (balancer.PickResult, error) { +func (p *picker) Pick(balancer.PickInfo) (balancer.PickResult, error) { return p.result, p.err } // idlePicker is used when the SubConn is IDLE and kicks the SubConn into // CONNECTING when Pick is called. type idlePicker struct { - sc balancer.SubConn + subConn balancer.SubConn } -func (i *idlePicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) { - i.sc.Connect() +func (i *idlePicker) Pick(balancer.PickInfo) (balancer.PickResult, error) { + i.subConn.Connect() return balancer.PickResult{}, balancer.ErrNoSubConnAvailable } diff --git a/providerlint/vendor/google.golang.org/grpc/resolver/resolver.go b/providerlint/vendor/google.golang.org/grpc/resolver/resolver.go index e28b6802606..ca2e35a3596 100644 --- a/providerlint/vendor/google.golang.org/grpc/resolver/resolver.go +++ b/providerlint/vendor/google.golang.org/grpc/resolver/resolver.go @@ -27,6 +27,7 @@ import ( "google.golang.org/grpc/attributes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/internal/pretty" "google.golang.org/grpc/serviceconfig" ) @@ -139,13 +140,18 @@ type Address struct { // Equal returns whether a and o are identical. Metadata is compared directly, // not with any recursive introspection. -func (a *Address) Equal(o Address) bool { +func (a Address) Equal(o Address) bool { return a.Addr == o.Addr && a.ServerName == o.ServerName && a.Attributes.Equal(o.Attributes) && a.BalancerAttributes.Equal(o.BalancerAttributes) && a.Type == o.Type && a.Metadata == o.Metadata } +// String returns JSON formatted string representation of the address. +func (a Address) String() string { + return pretty.ToJSON(a) +} + // BuildOptions includes additional information for the builder to create // the resolver. type BuildOptions struct { diff --git a/providerlint/vendor/google.golang.org/grpc/resolver_conn_wrapper.go b/providerlint/vendor/google.golang.org/grpc/resolver_conn_wrapper.go index 2c47cd54f07..05a9d4e0bac 100644 --- a/providerlint/vendor/google.golang.org/grpc/resolver_conn_wrapper.go +++ b/providerlint/vendor/google.golang.org/grpc/resolver_conn_wrapper.go @@ -19,7 +19,6 @@ package grpc import ( - "fmt" "strings" "sync" @@ -27,6 +26,7 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" + "google.golang.org/grpc/internal/pretty" "google.golang.org/grpc/resolver" "google.golang.org/grpc/serviceconfig" ) @@ -97,10 +97,7 @@ func (ccr *ccResolverWrapper) UpdateState(s resolver.State) error { if ccr.done.HasFired() { return nil } - channelz.Infof(logger, ccr.cc.channelzID, "ccResolverWrapper: sending update to cc: %v", s) - if channelz.IsOn() { - ccr.addChannelzTraceEvent(s) - } + ccr.addChannelzTraceEvent(s) ccr.curState = s if err := ccr.cc.updateResolverState(ccr.curState, nil); err == balancer.ErrBadResolverState { return balancer.ErrBadResolverState @@ -125,10 +122,7 @@ func (ccr *ccResolverWrapper) NewAddress(addrs []resolver.Address) { if ccr.done.HasFired() { return } - channelz.Infof(logger, ccr.cc.channelzID, "ccResolverWrapper: sending new addresses to cc: %v", addrs) - if channelz.IsOn() { - ccr.addChannelzTraceEvent(resolver.State{Addresses: addrs, ServiceConfig: ccr.curState.ServiceConfig}) - } + ccr.addChannelzTraceEvent(resolver.State{Addresses: addrs, ServiceConfig: ccr.curState.ServiceConfig}) ccr.curState.Addresses = addrs ccr.cc.updateResolverState(ccr.curState, nil) } @@ -141,7 +135,7 @@ func (ccr *ccResolverWrapper) NewServiceConfig(sc string) { if ccr.done.HasFired() { return } - channelz.Infof(logger, ccr.cc.channelzID, "ccResolverWrapper: got new service config: %v", sc) + channelz.Infof(logger, ccr.cc.channelzID, "ccResolverWrapper: got new service config: %s", sc) if ccr.cc.dopts.disableServiceConfig { channelz.Info(logger, ccr.cc.channelzID, "Service config lookups disabled; ignoring config") return @@ -151,9 +145,7 @@ func (ccr *ccResolverWrapper) NewServiceConfig(sc string) { channelz.Warningf(logger, ccr.cc.channelzID, "ccResolverWrapper: error parsing service config: %v", scpr.Err) return } - if channelz.IsOn() { - ccr.addChannelzTraceEvent(resolver.State{Addresses: ccr.curState.Addresses, ServiceConfig: scpr}) - } + ccr.addChannelzTraceEvent(resolver.State{Addresses: ccr.curState.Addresses, ServiceConfig: scpr}) ccr.curState.ServiceConfig = scpr ccr.cc.updateResolverState(ccr.curState, nil) } @@ -180,8 +172,5 @@ func (ccr *ccResolverWrapper) addChannelzTraceEvent(s resolver.State) { } else if len(ccr.curState.Addresses) == 0 && len(s.Addresses) > 0 { updates = append(updates, "resolver returned new addresses") } - channelz.AddTraceEvent(logger, ccr.cc.channelzID, 0, &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Resolver state updated: %+v (%v)", s, strings.Join(updates, "; ")), - Severity: channelz.CtInfo, - }) + channelz.Infof(logger, ccr.cc.channelzID, "Resolver state updated: %s (%v)", pretty.ToJSON(s), strings.Join(updates, "; ")) } diff --git a/providerlint/vendor/google.golang.org/grpc/server.go b/providerlint/vendor/google.golang.org/grpc/server.go index b24b6d53958..96431a058bf 100644 --- a/providerlint/vendor/google.golang.org/grpc/server.go +++ b/providerlint/vendor/google.golang.org/grpc/server.go @@ -134,7 +134,7 @@ type Server struct { channelzRemoveOnce sync.Once serveWG sync.WaitGroup // counts active Serve goroutines for GracefulStop - channelzID int64 // channelz unique identification number + channelzID *channelz.Identifier czData *channelzData serverWorkerChannels []chan *serverWorkerData @@ -584,9 +584,8 @@ func NewServer(opt ...ServerOption) *Server { s.initServerWorkers() } - if channelz.IsOn() { - s.channelzID = channelz.RegisterServer(&channelzServer{s}, "") - } + s.channelzID = channelz.RegisterServer(&channelzServer{s}, "") + channelz.Info(logger, s.channelzID, "Server created") return s } @@ -712,7 +711,7 @@ var ErrServerStopped = errors.New("grpc: the server has been stopped") type listenSocket struct { net.Listener - channelzID int64 + channelzID *channelz.Identifier } func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric { @@ -724,9 +723,8 @@ func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric { func (l *listenSocket) Close() error { err := l.Listener.Close() - if channelz.IsOn() { - channelz.RemoveEntry(l.channelzID) - } + channelz.RemoveEntry(l.channelzID) + channelz.Info(logger, l.channelzID, "ListenSocket deleted") return err } @@ -759,11 +757,6 @@ func (s *Server) Serve(lis net.Listener) error { ls := &listenSocket{Listener: lis} s.lis[ls] = true - if channelz.IsOn() { - ls.channelzID = channelz.RegisterListenSocket(ls, s.channelzID, lis.Addr().String()) - } - s.mu.Unlock() - defer func() { s.mu.Lock() if s.lis != nil && s.lis[ls] { @@ -773,8 +766,16 @@ func (s *Server) Serve(lis net.Listener) error { s.mu.Unlock() }() - var tempDelay time.Duration // how long to sleep on accept failure + var err error + ls.channelzID, err = channelz.RegisterListenSocket(ls, s.channelzID, lis.Addr().String()) + if err != nil { + s.mu.Unlock() + return err + } + s.mu.Unlock() + channelz.Info(logger, ls.channelzID, "ListenSocket created") + var tempDelay time.Duration // how long to sleep on accept failure for { rawConn, err := lis.Accept() if err != nil { @@ -1709,11 +1710,7 @@ func (s *Server) Stop() { s.done.Fire() }() - s.channelzRemoveOnce.Do(func() { - if channelz.IsOn() { - channelz.RemoveEntry(s.channelzID) - } - }) + s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) }) s.mu.Lock() listeners := s.lis @@ -1751,11 +1748,7 @@ func (s *Server) GracefulStop() { s.quit.Fire() defer s.done.Fire() - s.channelzRemoveOnce.Do(func() { - if channelz.IsOn() { - channelz.RemoveEntry(s.channelzID) - } - }) + s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) }) s.mu.Lock() if s.conns == nil { s.mu.Unlock() diff --git a/providerlint/vendor/google.golang.org/grpc/service_config.go b/providerlint/vendor/google.golang.org/grpc/service_config.go index 6926a06dc52..b01c548bb9a 100644 --- a/providerlint/vendor/google.golang.org/grpc/service_config.go +++ b/providerlint/vendor/google.golang.org/grpc/service_config.go @@ -381,6 +381,9 @@ func init() { // // If any of them is NOT *ServiceConfig, return false. func equalServiceConfig(a, b serviceconfig.Config) bool { + if a == nil && b == nil { + return true + } aa, ok := a.(*ServiceConfig) if !ok { return false diff --git a/providerlint/vendor/google.golang.org/grpc/stream.go b/providerlint/vendor/google.golang.org/grpc/stream.go index 8cdd652e037..e0b30b46fb1 100644 --- a/providerlint/vendor/google.golang.org/grpc/stream.go +++ b/providerlint/vendor/google.golang.org/grpc/stream.go @@ -36,6 +36,7 @@ import ( "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcrand" "google.golang.org/grpc/internal/grpcutil" + imetadata "google.golang.org/grpc/internal/metadata" iresolver "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/serviceconfig" "google.golang.org/grpc/internal/transport" @@ -166,6 +167,11 @@ func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth } func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { + if md, _, ok := metadata.FromOutgoingContextRaw(ctx); ok { + if err := imetadata.Validate(md); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + } if channelz.IsOn() { cc.incrCallsStarted() defer func() { @@ -456,7 +462,7 @@ type clientStream struct { retryThrottler *retryThrottler // The throttler active when the RPC began. - binlog *binarylog.MethodLogger // Binary logger, can be nil. + binlog binarylog.MethodLogger // Binary logger, can be nil. // serverHeaderBinlogged is a boolean for whether server header has been // logged. Server header will be logged when the first time one of those // happens: stream.Header(), stream.Recv(). @@ -1428,7 +1434,7 @@ type serverStream struct { statsHandler stats.Handler - binlog *binarylog.MethodLogger + binlog binarylog.MethodLogger // serverHeaderBinlogged indicates whether server header has been logged. It // will happen when one of the following two happens: stream.SendHeader(), // stream.Send(). @@ -1448,11 +1454,20 @@ func (ss *serverStream) SetHeader(md metadata.MD) error { if md.Len() == 0 { return nil } + err := imetadata.Validate(md) + if err != nil { + return status.Error(codes.Internal, err.Error()) + } return ss.s.SetHeader(md) } func (ss *serverStream) SendHeader(md metadata.MD) error { - err := ss.t.WriteHeader(ss.s, md) + err := imetadata.Validate(md) + if err != nil { + return status.Error(codes.Internal, err.Error()) + } + + err = ss.t.WriteHeader(ss.s, md) if ss.binlog != nil && !ss.serverHeaderBinlogged { h, _ := ss.s.Header() ss.binlog.Log(&binarylog.ServerHeader{ @@ -1467,6 +1482,9 @@ func (ss *serverStream) SetTrailer(md metadata.MD) { if md.Len() == 0 { return } + if err := imetadata.Validate(md); err != nil { + logger.Errorf("stream: failed to validate md when setting trailer, err: %v", err) + } ss.s.SetTrailer(md) } diff --git a/providerlint/vendor/google.golang.org/grpc/version.go b/providerlint/vendor/google.golang.org/grpc/version.go index 5bd4f534c1d..6af76dfe7bb 100644 --- a/providerlint/vendor/google.golang.org/grpc/version.go +++ b/providerlint/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.45.0" +const Version = "1.46.0" diff --git a/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/decode.go b/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/decode.go new file mode 100644 index 00000000000..07da5db3450 --- /dev/null +++ b/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/decode.go @@ -0,0 +1,665 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protojson + +import ( + "encoding/base64" + "fmt" + "math" + "strconv" + "strings" + + "google.golang.org/protobuf/internal/encoding/json" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/internal/set" + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +// Unmarshal reads the given []byte into the given proto.Message. +// The provided message must be mutable (e.g., a non-nil pointer to a message). +func Unmarshal(b []byte, m proto.Message) error { + return UnmarshalOptions{}.Unmarshal(b, m) +} + +// UnmarshalOptions is a configurable JSON format parser. +type UnmarshalOptions struct { + pragma.NoUnkeyedLiterals + + // If AllowPartial is set, input for messages that will result in missing + // required fields will not return an error. + AllowPartial bool + + // If DiscardUnknown is set, unknown fields are ignored. + DiscardUnknown bool + + // Resolver is used for looking up types when unmarshaling + // google.protobuf.Any messages or extension fields. + // If nil, this defaults to using protoregistry.GlobalTypes. + Resolver interface { + protoregistry.MessageTypeResolver + protoregistry.ExtensionTypeResolver + } +} + +// Unmarshal reads the given []byte and populates the given proto.Message +// using options in the UnmarshalOptions object. +// It will clear the message first before setting the fields. +// If it returns an error, the given message may be partially set. +// The provided message must be mutable (e.g., a non-nil pointer to a message). +func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error { + return o.unmarshal(b, m) +} + +// unmarshal is a centralized function that all unmarshal operations go through. +// For profiling purposes, avoid changing the name of this function or +// introducing other code paths for unmarshal that do not go through this. +func (o UnmarshalOptions) unmarshal(b []byte, m proto.Message) error { + proto.Reset(m) + + if o.Resolver == nil { + o.Resolver = protoregistry.GlobalTypes + } + + dec := decoder{json.NewDecoder(b), o} + if err := dec.unmarshalMessage(m.ProtoReflect(), false); err != nil { + return err + } + + // Check for EOF. + tok, err := dec.Read() + if err != nil { + return err + } + if tok.Kind() != json.EOF { + return dec.unexpectedTokenError(tok) + } + + if o.AllowPartial { + return nil + } + return proto.CheckInitialized(m) +} + +type decoder struct { + *json.Decoder + opts UnmarshalOptions +} + +// newError returns an error object with position info. +func (d decoder) newError(pos int, f string, x ...interface{}) error { + line, column := d.Position(pos) + head := fmt.Sprintf("(line %d:%d): ", line, column) + return errors.New(head+f, x...) +} + +// unexpectedTokenError returns a syntax error for the given unexpected token. +func (d decoder) unexpectedTokenError(tok json.Token) error { + return d.syntaxError(tok.Pos(), "unexpected token %s", tok.RawString()) +} + +// syntaxError returns a syntax error for given position. +func (d decoder) syntaxError(pos int, f string, x ...interface{}) error { + line, column := d.Position(pos) + head := fmt.Sprintf("syntax error (line %d:%d): ", line, column) + return errors.New(head+f, x...) +} + +// unmarshalMessage unmarshals a message into the given protoreflect.Message. +func (d decoder) unmarshalMessage(m pref.Message, skipTypeURL bool) error { + if unmarshal := wellKnownTypeUnmarshaler(m.Descriptor().FullName()); unmarshal != nil { + return unmarshal(d, m) + } + + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.ObjectOpen { + return d.unexpectedTokenError(tok) + } + + messageDesc := m.Descriptor() + if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { + return errors.New("no support for proto1 MessageSets") + } + + var seenNums set.Ints + var seenOneofs set.Ints + fieldDescs := messageDesc.Fields() + for { + // Read field name. + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + default: + return d.unexpectedTokenError(tok) + case json.ObjectClose: + return nil + case json.Name: + // Continue below. + } + + name := tok.Name() + // Unmarshaling a non-custom embedded message in Any will contain the + // JSON field "@type" which should be skipped because it is not a field + // of the embedded message, but simply an artifact of the Any format. + if skipTypeURL && name == "@type" { + d.Read() + continue + } + + // Get the FieldDescriptor. + var fd pref.FieldDescriptor + if strings.HasPrefix(name, "[") && strings.HasSuffix(name, "]") { + // Only extension names are in [name] format. + extName := pref.FullName(name[1 : len(name)-1]) + extType, err := d.opts.Resolver.FindExtensionByName(extName) + if err != nil && err != protoregistry.NotFound { + return d.newError(tok.Pos(), "unable to resolve %s: %v", tok.RawString(), err) + } + if extType != nil { + fd = extType.TypeDescriptor() + if !messageDesc.ExtensionRanges().Has(fd.Number()) || fd.ContainingMessage().FullName() != messageDesc.FullName() { + return d.newError(tok.Pos(), "message %v cannot be extended by %v", messageDesc.FullName(), fd.FullName()) + } + } + } else { + // The name can either be the JSON name or the proto field name. + fd = fieldDescs.ByJSONName(name) + if fd == nil { + fd = fieldDescs.ByTextName(name) + } + } + if flags.ProtoLegacy { + if fd != nil && fd.IsWeak() && fd.Message().IsPlaceholder() { + fd = nil // reset since the weak reference is not linked in + } + } + + if fd == nil { + // Field is unknown. + if d.opts.DiscardUnknown { + if err := d.skipJSONValue(); err != nil { + return err + } + continue + } + return d.newError(tok.Pos(), "unknown field %v", tok.RawString()) + } + + // Do not allow duplicate fields. + num := uint64(fd.Number()) + if seenNums.Has(num) { + return d.newError(tok.Pos(), "duplicate field %v", tok.RawString()) + } + seenNums.Set(num) + + // No need to set values for JSON null unless the field type is + // google.protobuf.Value or google.protobuf.NullValue. + if tok, _ := d.Peek(); tok.Kind() == json.Null && !isKnownValue(fd) && !isNullValue(fd) { + d.Read() + continue + } + + switch { + case fd.IsList(): + list := m.Mutable(fd).List() + if err := d.unmarshalList(list, fd); err != nil { + return err + } + case fd.IsMap(): + mmap := m.Mutable(fd).Map() + if err := d.unmarshalMap(mmap, fd); err != nil { + return err + } + default: + // If field is a oneof, check if it has already been set. + if od := fd.ContainingOneof(); od != nil { + idx := uint64(od.Index()) + if seenOneofs.Has(idx) { + return d.newError(tok.Pos(), "error parsing %s, oneof %v is already set", tok.RawString(), od.FullName()) + } + seenOneofs.Set(idx) + } + + // Required or optional fields. + if err := d.unmarshalSingular(m, fd); err != nil { + return err + } + } + } +} + +func isKnownValue(fd pref.FieldDescriptor) bool { + md := fd.Message() + return md != nil && md.FullName() == genid.Value_message_fullname +} + +func isNullValue(fd pref.FieldDescriptor) bool { + ed := fd.Enum() + return ed != nil && ed.FullName() == genid.NullValue_enum_fullname +} + +// unmarshalSingular unmarshals to the non-repeated field specified +// by the given FieldDescriptor. +func (d decoder) unmarshalSingular(m pref.Message, fd pref.FieldDescriptor) error { + var val pref.Value + var err error + switch fd.Kind() { + case pref.MessageKind, pref.GroupKind: + val = m.NewField(fd) + err = d.unmarshalMessage(val.Message(), false) + default: + val, err = d.unmarshalScalar(fd) + } + + if err != nil { + return err + } + m.Set(fd, val) + return nil +} + +// unmarshalScalar unmarshals to a scalar/enum protoreflect.Value specified by +// the given FieldDescriptor. +func (d decoder) unmarshalScalar(fd pref.FieldDescriptor) (pref.Value, error) { + const b32 int = 32 + const b64 int = 64 + + tok, err := d.Read() + if err != nil { + return pref.Value{}, err + } + + kind := fd.Kind() + switch kind { + case pref.BoolKind: + if tok.Kind() == json.Bool { + return pref.ValueOfBool(tok.Bool()), nil + } + + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + if v, ok := unmarshalInt(tok, b32); ok { + return v, nil + } + + case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind: + if v, ok := unmarshalInt(tok, b64); ok { + return v, nil + } + + case pref.Uint32Kind, pref.Fixed32Kind: + if v, ok := unmarshalUint(tok, b32); ok { + return v, nil + } + + case pref.Uint64Kind, pref.Fixed64Kind: + if v, ok := unmarshalUint(tok, b64); ok { + return v, nil + } + + case pref.FloatKind: + if v, ok := unmarshalFloat(tok, b32); ok { + return v, nil + } + + case pref.DoubleKind: + if v, ok := unmarshalFloat(tok, b64); ok { + return v, nil + } + + case pref.StringKind: + if tok.Kind() == json.String { + return pref.ValueOfString(tok.ParsedString()), nil + } + + case pref.BytesKind: + if v, ok := unmarshalBytes(tok); ok { + return v, nil + } + + case pref.EnumKind: + if v, ok := unmarshalEnum(tok, fd); ok { + return v, nil + } + + default: + panic(fmt.Sprintf("unmarshalScalar: invalid scalar kind %v", kind)) + } + + return pref.Value{}, d.newError(tok.Pos(), "invalid value for %v type: %v", kind, tok.RawString()) +} + +func unmarshalInt(tok json.Token, bitSize int) (pref.Value, bool) { + switch tok.Kind() { + case json.Number: + return getInt(tok, bitSize) + + case json.String: + // Decode number from string. + s := strings.TrimSpace(tok.ParsedString()) + if len(s) != len(tok.ParsedString()) { + return pref.Value{}, false + } + dec := json.NewDecoder([]byte(s)) + tok, err := dec.Read() + if err != nil { + return pref.Value{}, false + } + return getInt(tok, bitSize) + } + return pref.Value{}, false +} + +func getInt(tok json.Token, bitSize int) (pref.Value, bool) { + n, ok := tok.Int(bitSize) + if !ok { + return pref.Value{}, false + } + if bitSize == 32 { + return pref.ValueOfInt32(int32(n)), true + } + return pref.ValueOfInt64(n), true +} + +func unmarshalUint(tok json.Token, bitSize int) (pref.Value, bool) { + switch tok.Kind() { + case json.Number: + return getUint(tok, bitSize) + + case json.String: + // Decode number from string. + s := strings.TrimSpace(tok.ParsedString()) + if len(s) != len(tok.ParsedString()) { + return pref.Value{}, false + } + dec := json.NewDecoder([]byte(s)) + tok, err := dec.Read() + if err != nil { + return pref.Value{}, false + } + return getUint(tok, bitSize) + } + return pref.Value{}, false +} + +func getUint(tok json.Token, bitSize int) (pref.Value, bool) { + n, ok := tok.Uint(bitSize) + if !ok { + return pref.Value{}, false + } + if bitSize == 32 { + return pref.ValueOfUint32(uint32(n)), true + } + return pref.ValueOfUint64(n), true +} + +func unmarshalFloat(tok json.Token, bitSize int) (pref.Value, bool) { + switch tok.Kind() { + case json.Number: + return getFloat(tok, bitSize) + + case json.String: + s := tok.ParsedString() + switch s { + case "NaN": + if bitSize == 32 { + return pref.ValueOfFloat32(float32(math.NaN())), true + } + return pref.ValueOfFloat64(math.NaN()), true + case "Infinity": + if bitSize == 32 { + return pref.ValueOfFloat32(float32(math.Inf(+1))), true + } + return pref.ValueOfFloat64(math.Inf(+1)), true + case "-Infinity": + if bitSize == 32 { + return pref.ValueOfFloat32(float32(math.Inf(-1))), true + } + return pref.ValueOfFloat64(math.Inf(-1)), true + } + + // Decode number from string. + if len(s) != len(strings.TrimSpace(s)) { + return pref.Value{}, false + } + dec := json.NewDecoder([]byte(s)) + tok, err := dec.Read() + if err != nil { + return pref.Value{}, false + } + return getFloat(tok, bitSize) + } + return pref.Value{}, false +} + +func getFloat(tok json.Token, bitSize int) (pref.Value, bool) { + n, ok := tok.Float(bitSize) + if !ok { + return pref.Value{}, false + } + if bitSize == 32 { + return pref.ValueOfFloat32(float32(n)), true + } + return pref.ValueOfFloat64(n), true +} + +func unmarshalBytes(tok json.Token) (pref.Value, bool) { + if tok.Kind() != json.String { + return pref.Value{}, false + } + + s := tok.ParsedString() + enc := base64.StdEncoding + if strings.ContainsAny(s, "-_") { + enc = base64.URLEncoding + } + if len(s)%4 != 0 { + enc = enc.WithPadding(base64.NoPadding) + } + b, err := enc.DecodeString(s) + if err != nil { + return pref.Value{}, false + } + return pref.ValueOfBytes(b), true +} + +func unmarshalEnum(tok json.Token, fd pref.FieldDescriptor) (pref.Value, bool) { + switch tok.Kind() { + case json.String: + // Lookup EnumNumber based on name. + s := tok.ParsedString() + if enumVal := fd.Enum().Values().ByName(pref.Name(s)); enumVal != nil { + return pref.ValueOfEnum(enumVal.Number()), true + } + + case json.Number: + if n, ok := tok.Int(32); ok { + return pref.ValueOfEnum(pref.EnumNumber(n)), true + } + + case json.Null: + // This is only valid for google.protobuf.NullValue. + if isNullValue(fd) { + return pref.ValueOfEnum(0), true + } + } + + return pref.Value{}, false +} + +func (d decoder) unmarshalList(list pref.List, fd pref.FieldDescriptor) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.ArrayOpen { + return d.unexpectedTokenError(tok) + } + + switch fd.Kind() { + case pref.MessageKind, pref.GroupKind: + for { + tok, err := d.Peek() + if err != nil { + return err + } + + if tok.Kind() == json.ArrayClose { + d.Read() + return nil + } + + val := list.NewElement() + if err := d.unmarshalMessage(val.Message(), false); err != nil { + return err + } + list.Append(val) + } + default: + for { + tok, err := d.Peek() + if err != nil { + return err + } + + if tok.Kind() == json.ArrayClose { + d.Read() + return nil + } + + val, err := d.unmarshalScalar(fd) + if err != nil { + return err + } + list.Append(val) + } + } + + return nil +} + +func (d decoder) unmarshalMap(mmap pref.Map, fd pref.FieldDescriptor) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.ObjectOpen { + return d.unexpectedTokenError(tok) + } + + // Determine ahead whether map entry is a scalar type or a message type in + // order to call the appropriate unmarshalMapValue func inside the for loop + // below. + var unmarshalMapValue func() (pref.Value, error) + switch fd.MapValue().Kind() { + case pref.MessageKind, pref.GroupKind: + unmarshalMapValue = func() (pref.Value, error) { + val := mmap.NewValue() + if err := d.unmarshalMessage(val.Message(), false); err != nil { + return pref.Value{}, err + } + return val, nil + } + default: + unmarshalMapValue = func() (pref.Value, error) { + return d.unmarshalScalar(fd.MapValue()) + } + } + +Loop: + for { + // Read field name. + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + default: + return d.unexpectedTokenError(tok) + case json.ObjectClose: + break Loop + case json.Name: + // Continue. + } + + // Unmarshal field name. + pkey, err := d.unmarshalMapKey(tok, fd.MapKey()) + if err != nil { + return err + } + + // Check for duplicate field name. + if mmap.Has(pkey) { + return d.newError(tok.Pos(), "duplicate map key %v", tok.RawString()) + } + + // Read and unmarshal field value. + pval, err := unmarshalMapValue() + if err != nil { + return err + } + + mmap.Set(pkey, pval) + } + + return nil +} + +// unmarshalMapKey converts given token of Name kind into a protoreflect.MapKey. +// A map key type is any integral or string type. +func (d decoder) unmarshalMapKey(tok json.Token, fd pref.FieldDescriptor) (pref.MapKey, error) { + const b32 = 32 + const b64 = 64 + const base10 = 10 + + name := tok.Name() + kind := fd.Kind() + switch kind { + case pref.StringKind: + return pref.ValueOfString(name).MapKey(), nil + + case pref.BoolKind: + switch name { + case "true": + return pref.ValueOfBool(true).MapKey(), nil + case "false": + return pref.ValueOfBool(false).MapKey(), nil + } + + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + if n, err := strconv.ParseInt(name, base10, b32); err == nil { + return pref.ValueOfInt32(int32(n)).MapKey(), nil + } + + case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind: + if n, err := strconv.ParseInt(name, base10, b64); err == nil { + return pref.ValueOfInt64(int64(n)).MapKey(), nil + } + + case pref.Uint32Kind, pref.Fixed32Kind: + if n, err := strconv.ParseUint(name, base10, b32); err == nil { + return pref.ValueOfUint32(uint32(n)).MapKey(), nil + } + + case pref.Uint64Kind, pref.Fixed64Kind: + if n, err := strconv.ParseUint(name, base10, b64); err == nil { + return pref.ValueOfUint64(uint64(n)).MapKey(), nil + } + + default: + panic(fmt.Sprintf("invalid kind for map key: %v", kind)) + } + + return pref.MapKey{}, d.newError(tok.Pos(), "invalid value for %v key: %s", kind, tok.RawString()) +} diff --git a/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/doc.go b/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/doc.go new file mode 100644 index 00000000000..00ea2fecfb7 --- /dev/null +++ b/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/doc.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package protojson marshals and unmarshals protocol buffer messages as JSON +// format. It follows the guide at +// https://developers.google.com/protocol-buffers/docs/proto3#json. +// +// This package produces a different output than the standard "encoding/json" +// package, which does not operate correctly on protocol buffer messages. +package protojson diff --git a/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/encode.go b/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/encode.go new file mode 100644 index 00000000000..ba971f07810 --- /dev/null +++ b/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/encode.go @@ -0,0 +1,344 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protojson + +import ( + "encoding/base64" + "fmt" + + "google.golang.org/protobuf/internal/encoding/json" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/order" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + pref "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +const defaultIndent = " " + +// Format formats the message as a multiline string. +// This function is only intended for human consumption and ignores errors. +// Do not depend on the output being stable. It may change over time across +// different versions of the program. +func Format(m proto.Message) string { + return MarshalOptions{Multiline: true}.Format(m) +} + +// Marshal writes the given proto.Message in JSON format using default options. +// Do not depend on the output being stable. It may change over time across +// different versions of the program. +func Marshal(m proto.Message) ([]byte, error) { + return MarshalOptions{}.Marshal(m) +} + +// MarshalOptions is a configurable JSON format marshaler. +type MarshalOptions struct { + pragma.NoUnkeyedLiterals + + // Multiline specifies whether the marshaler should format the output in + // indented-form with every textual element on a new line. + // If Indent is an empty string, then an arbitrary indent is chosen. + Multiline bool + + // Indent specifies the set of indentation characters to use in a multiline + // formatted output such that every entry is preceded by Indent and + // terminated by a newline. If non-empty, then Multiline is treated as true. + // Indent can only be composed of space or tab characters. + Indent string + + // AllowPartial allows messages that have missing required fields to marshal + // without returning an error. If AllowPartial is false (the default), + // Marshal will return error if there are any missing required fields. + AllowPartial bool + + // UseProtoNames uses proto field name instead of lowerCamelCase name in JSON + // field names. + UseProtoNames bool + + // UseEnumNumbers emits enum values as numbers. + UseEnumNumbers bool + + // EmitUnpopulated specifies whether to emit unpopulated fields. It does not + // emit unpopulated oneof fields or unpopulated extension fields. + // The JSON value emitted for unpopulated fields are as follows: + // ╔═══════╤════════════════════════════╗ + // ║ JSON │ Protobuf field ║ + // ╠═══════╪════════════════════════════╣ + // ║ false │ proto3 boolean fields ║ + // ║ 0 │ proto3 numeric fields ║ + // ║ "" │ proto3 string/bytes fields ║ + // ║ null │ proto2 scalar fields ║ + // ║ null │ message fields ║ + // ║ [] │ list fields ║ + // ║ {} │ map fields ║ + // ╚═══════╧════════════════════════════╝ + EmitUnpopulated bool + + // Resolver is used for looking up types when expanding google.protobuf.Any + // messages. If nil, this defaults to using protoregistry.GlobalTypes. + Resolver interface { + protoregistry.ExtensionTypeResolver + protoregistry.MessageTypeResolver + } +} + +// Format formats the message as a string. +// This method is only intended for human consumption and ignores errors. +// Do not depend on the output being stable. It may change over time across +// different versions of the program. +func (o MarshalOptions) Format(m proto.Message) string { + if m == nil || !m.ProtoReflect().IsValid() { + return "" // invalid syntax, but okay since this is for debugging + } + o.AllowPartial = true + b, _ := o.Marshal(m) + return string(b) +} + +// Marshal marshals the given proto.Message in the JSON format using options in +// MarshalOptions. Do not depend on the output being stable. It may change over +// time across different versions of the program. +func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) { + return o.marshal(m) +} + +// marshal is a centralized function that all marshal operations go through. +// For profiling purposes, avoid changing the name of this function or +// introducing other code paths for marshal that do not go through this. +func (o MarshalOptions) marshal(m proto.Message) ([]byte, error) { + if o.Multiline && o.Indent == "" { + o.Indent = defaultIndent + } + if o.Resolver == nil { + o.Resolver = protoregistry.GlobalTypes + } + + internalEnc, err := json.NewEncoder(o.Indent) + if err != nil { + return nil, err + } + + // Treat nil message interface as an empty message, + // in which case the output in an empty JSON object. + if m == nil { + return []byte("{}"), nil + } + + enc := encoder{internalEnc, o} + if err := enc.marshalMessage(m.ProtoReflect(), ""); err != nil { + return nil, err + } + if o.AllowPartial { + return enc.Bytes(), nil + } + return enc.Bytes(), proto.CheckInitialized(m) +} + +type encoder struct { + *json.Encoder + opts MarshalOptions +} + +// typeFieldDesc is a synthetic field descriptor used for the "@type" field. +var typeFieldDesc = func() protoreflect.FieldDescriptor { + var fd filedesc.Field + fd.L0.FullName = "@type" + fd.L0.Index = -1 + fd.L1.Cardinality = protoreflect.Optional + fd.L1.Kind = protoreflect.StringKind + return &fd +}() + +// typeURLFieldRanger wraps a protoreflect.Message and modifies its Range method +// to additionally iterate over a synthetic field for the type URL. +type typeURLFieldRanger struct { + order.FieldRanger + typeURL string +} + +func (m typeURLFieldRanger) Range(f func(pref.FieldDescriptor, pref.Value) bool) { + if !f(typeFieldDesc, pref.ValueOfString(m.typeURL)) { + return + } + m.FieldRanger.Range(f) +} + +// unpopulatedFieldRanger wraps a protoreflect.Message and modifies its Range +// method to additionally iterate over unpopulated fields. +type unpopulatedFieldRanger struct{ pref.Message } + +func (m unpopulatedFieldRanger) Range(f func(pref.FieldDescriptor, pref.Value) bool) { + fds := m.Descriptor().Fields() + for i := 0; i < fds.Len(); i++ { + fd := fds.Get(i) + if m.Has(fd) || fd.ContainingOneof() != nil { + continue // ignore populated fields and fields within a oneofs + } + + v := m.Get(fd) + isProto2Scalar := fd.Syntax() == pref.Proto2 && fd.Default().IsValid() + isSingularMessage := fd.Cardinality() != pref.Repeated && fd.Message() != nil + if isProto2Scalar || isSingularMessage { + v = pref.Value{} // use invalid value to emit null + } + if !f(fd, v) { + return + } + } + m.Message.Range(f) +} + +// marshalMessage marshals the fields in the given protoreflect.Message. +// If the typeURL is non-empty, then a synthetic "@type" field is injected +// containing the URL as the value. +func (e encoder) marshalMessage(m pref.Message, typeURL string) error { + if !flags.ProtoLegacy && messageset.IsMessageSet(m.Descriptor()) { + return errors.New("no support for proto1 MessageSets") + } + + if marshal := wellKnownTypeMarshaler(m.Descriptor().FullName()); marshal != nil { + return marshal(e, m) + } + + e.StartObject() + defer e.EndObject() + + var fields order.FieldRanger = m + if e.opts.EmitUnpopulated { + fields = unpopulatedFieldRanger{m} + } + if typeURL != "" { + fields = typeURLFieldRanger{fields, typeURL} + } + + var err error + order.RangeFields(fields, order.IndexNameFieldOrder, func(fd pref.FieldDescriptor, v pref.Value) bool { + name := fd.JSONName() + if e.opts.UseProtoNames { + name = fd.TextName() + } + + if err = e.WriteName(name); err != nil { + return false + } + if err = e.marshalValue(v, fd); err != nil { + return false + } + return true + }) + return err +} + +// marshalValue marshals the given protoreflect.Value. +func (e encoder) marshalValue(val pref.Value, fd pref.FieldDescriptor) error { + switch { + case fd.IsList(): + return e.marshalList(val.List(), fd) + case fd.IsMap(): + return e.marshalMap(val.Map(), fd) + default: + return e.marshalSingular(val, fd) + } +} + +// marshalSingular marshals the given non-repeated field value. This includes +// all scalar types, enums, messages, and groups. +func (e encoder) marshalSingular(val pref.Value, fd pref.FieldDescriptor) error { + if !val.IsValid() { + e.WriteNull() + return nil + } + + switch kind := fd.Kind(); kind { + case pref.BoolKind: + e.WriteBool(val.Bool()) + + case pref.StringKind: + if e.WriteString(val.String()) != nil { + return errors.InvalidUTF8(string(fd.FullName())) + } + + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + e.WriteInt(val.Int()) + + case pref.Uint32Kind, pref.Fixed32Kind: + e.WriteUint(val.Uint()) + + case pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind, + pref.Sfixed64Kind, pref.Fixed64Kind: + // 64-bit integers are written out as JSON string. + e.WriteString(val.String()) + + case pref.FloatKind: + // Encoder.WriteFloat handles the special numbers NaN and infinites. + e.WriteFloat(val.Float(), 32) + + case pref.DoubleKind: + // Encoder.WriteFloat handles the special numbers NaN and infinites. + e.WriteFloat(val.Float(), 64) + + case pref.BytesKind: + e.WriteString(base64.StdEncoding.EncodeToString(val.Bytes())) + + case pref.EnumKind: + if fd.Enum().FullName() == genid.NullValue_enum_fullname { + e.WriteNull() + } else { + desc := fd.Enum().Values().ByNumber(val.Enum()) + if e.opts.UseEnumNumbers || desc == nil { + e.WriteInt(int64(val.Enum())) + } else { + e.WriteString(string(desc.Name())) + } + } + + case pref.MessageKind, pref.GroupKind: + if err := e.marshalMessage(val.Message(), ""); err != nil { + return err + } + + default: + panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind)) + } + return nil +} + +// marshalList marshals the given protoreflect.List. +func (e encoder) marshalList(list pref.List, fd pref.FieldDescriptor) error { + e.StartArray() + defer e.EndArray() + + for i := 0; i < list.Len(); i++ { + item := list.Get(i) + if err := e.marshalSingular(item, fd); err != nil { + return err + } + } + return nil +} + +// marshalMap marshals given protoreflect.Map. +func (e encoder) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) error { + e.StartObject() + defer e.EndObject() + + var err error + order.RangeEntries(mmap, order.GenericKeyOrder, func(k pref.MapKey, v pref.Value) bool { + if err = e.WriteName(k.String()); err != nil { + return false + } + if err = e.marshalSingular(v, fd.MapValue()); err != nil { + return false + } + return true + }) + return err +} diff --git a/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/well_known_types.go b/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/well_known_types.go new file mode 100644 index 00000000000..72924a9050c --- /dev/null +++ b/providerlint/vendor/google.golang.org/protobuf/encoding/protojson/well_known_types.go @@ -0,0 +1,889 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protojson + +import ( + "bytes" + "fmt" + "math" + "strconv" + "strings" + "time" + + "google.golang.org/protobuf/internal/encoding/json" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type marshalFunc func(encoder, pref.Message) error + +// wellKnownTypeMarshaler returns a marshal function if the message type +// has specialized serialization behavior. It returns nil otherwise. +func wellKnownTypeMarshaler(name pref.FullName) marshalFunc { + if name.Parent() == genid.GoogleProtobuf_package { + switch name.Name() { + case genid.Any_message_name: + return encoder.marshalAny + case genid.Timestamp_message_name: + return encoder.marshalTimestamp + case genid.Duration_message_name: + return encoder.marshalDuration + case genid.BoolValue_message_name, + genid.Int32Value_message_name, + genid.Int64Value_message_name, + genid.UInt32Value_message_name, + genid.UInt64Value_message_name, + genid.FloatValue_message_name, + genid.DoubleValue_message_name, + genid.StringValue_message_name, + genid.BytesValue_message_name: + return encoder.marshalWrapperType + case genid.Struct_message_name: + return encoder.marshalStruct + case genid.ListValue_message_name: + return encoder.marshalListValue + case genid.Value_message_name: + return encoder.marshalKnownValue + case genid.FieldMask_message_name: + return encoder.marshalFieldMask + case genid.Empty_message_name: + return encoder.marshalEmpty + } + } + return nil +} + +type unmarshalFunc func(decoder, pref.Message) error + +// wellKnownTypeUnmarshaler returns a unmarshal function if the message type +// has specialized serialization behavior. It returns nil otherwise. +func wellKnownTypeUnmarshaler(name pref.FullName) unmarshalFunc { + if name.Parent() == genid.GoogleProtobuf_package { + switch name.Name() { + case genid.Any_message_name: + return decoder.unmarshalAny + case genid.Timestamp_message_name: + return decoder.unmarshalTimestamp + case genid.Duration_message_name: + return decoder.unmarshalDuration + case genid.BoolValue_message_name, + genid.Int32Value_message_name, + genid.Int64Value_message_name, + genid.UInt32Value_message_name, + genid.UInt64Value_message_name, + genid.FloatValue_message_name, + genid.DoubleValue_message_name, + genid.StringValue_message_name, + genid.BytesValue_message_name: + return decoder.unmarshalWrapperType + case genid.Struct_message_name: + return decoder.unmarshalStruct + case genid.ListValue_message_name: + return decoder.unmarshalListValue + case genid.Value_message_name: + return decoder.unmarshalKnownValue + case genid.FieldMask_message_name: + return decoder.unmarshalFieldMask + case genid.Empty_message_name: + return decoder.unmarshalEmpty + } + } + return nil +} + +// The JSON representation of an Any message uses the regular representation of +// the deserialized, embedded message, with an additional field `@type` which +// contains the type URL. If the embedded message type is well-known and has a +// custom JSON representation, that representation will be embedded adding a +// field `value` which holds the custom JSON in addition to the `@type` field. + +func (e encoder) marshalAny(m pref.Message) error { + fds := m.Descriptor().Fields() + fdType := fds.ByNumber(genid.Any_TypeUrl_field_number) + fdValue := fds.ByNumber(genid.Any_Value_field_number) + + if !m.Has(fdType) { + if !m.Has(fdValue) { + // If message is empty, marshal out empty JSON object. + e.StartObject() + e.EndObject() + return nil + } else { + // Return error if type_url field is not set, but value is set. + return errors.New("%s: %v is not set", genid.Any_message_fullname, genid.Any_TypeUrl_field_name) + } + } + + typeVal := m.Get(fdType) + valueVal := m.Get(fdValue) + + // Resolve the type in order to unmarshal value field. + typeURL := typeVal.String() + emt, err := e.opts.Resolver.FindMessageByURL(typeURL) + if err != nil { + return errors.New("%s: unable to resolve %q: %v", genid.Any_message_fullname, typeURL, err) + } + + em := emt.New() + err = proto.UnmarshalOptions{ + AllowPartial: true, // never check required fields inside an Any + Resolver: e.opts.Resolver, + }.Unmarshal(valueVal.Bytes(), em.Interface()) + if err != nil { + return errors.New("%s: unable to unmarshal %q: %v", genid.Any_message_fullname, typeURL, err) + } + + // If type of value has custom JSON encoding, marshal out a field "value" + // with corresponding custom JSON encoding of the embedded message as a + // field. + if marshal := wellKnownTypeMarshaler(emt.Descriptor().FullName()); marshal != nil { + e.StartObject() + defer e.EndObject() + + // Marshal out @type field. + e.WriteName("@type") + if err := e.WriteString(typeURL); err != nil { + return err + } + + e.WriteName("value") + return marshal(e, em) + } + + // Else, marshal out the embedded message's fields in this Any object. + if err := e.marshalMessage(em, typeURL); err != nil { + return err + } + + return nil +} + +func (d decoder) unmarshalAny(m pref.Message) error { + // Peek to check for json.ObjectOpen to avoid advancing a read. + start, err := d.Peek() + if err != nil { + return err + } + if start.Kind() != json.ObjectOpen { + return d.unexpectedTokenError(start) + } + + // Use another decoder to parse the unread bytes for @type field. This + // avoids advancing a read from current decoder because the current JSON + // object may contain the fields of the embedded type. + dec := decoder{d.Clone(), UnmarshalOptions{}} + tok, err := findTypeURL(dec) + switch err { + case errEmptyObject: + // An empty JSON object translates to an empty Any message. + d.Read() // Read json.ObjectOpen. + d.Read() // Read json.ObjectClose. + return nil + + case errMissingType: + if d.opts.DiscardUnknown { + // Treat all fields as unknowns, similar to an empty object. + return d.skipJSONValue() + } + // Use start.Pos() for line position. + return d.newError(start.Pos(), err.Error()) + + default: + if err != nil { + return err + } + } + + typeURL := tok.ParsedString() + emt, err := d.opts.Resolver.FindMessageByURL(typeURL) + if err != nil { + return d.newError(tok.Pos(), "unable to resolve %v: %q", tok.RawString(), err) + } + + // Create new message for the embedded message type and unmarshal into it. + em := emt.New() + if unmarshal := wellKnownTypeUnmarshaler(emt.Descriptor().FullName()); unmarshal != nil { + // If embedded message is a custom type, + // unmarshal the JSON "value" field into it. + if err := d.unmarshalAnyValue(unmarshal, em); err != nil { + return err + } + } else { + // Else unmarshal the current JSON object into it. + if err := d.unmarshalMessage(em, true); err != nil { + return err + } + } + // Serialize the embedded message and assign the resulting bytes to the + // proto value field. + b, err := proto.MarshalOptions{ + AllowPartial: true, // No need to check required fields inside an Any. + Deterministic: true, + }.Marshal(em.Interface()) + if err != nil { + return d.newError(start.Pos(), "error in marshaling Any.value field: %v", err) + } + + fds := m.Descriptor().Fields() + fdType := fds.ByNumber(genid.Any_TypeUrl_field_number) + fdValue := fds.ByNumber(genid.Any_Value_field_number) + + m.Set(fdType, pref.ValueOfString(typeURL)) + m.Set(fdValue, pref.ValueOfBytes(b)) + return nil +} + +var errEmptyObject = fmt.Errorf(`empty object`) +var errMissingType = fmt.Errorf(`missing "@type" field`) + +// findTypeURL returns the token for the "@type" field value from the given +// JSON bytes. It is expected that the given bytes start with json.ObjectOpen. +// It returns errEmptyObject if the JSON object is empty or errMissingType if +// @type field does not exist. It returns other error if the @type field is not +// valid or other decoding issues. +func findTypeURL(d decoder) (json.Token, error) { + var typeURL string + var typeTok json.Token + numFields := 0 + // Skip start object. + d.Read() + +Loop: + for { + tok, err := d.Read() + if err != nil { + return json.Token{}, err + } + + switch tok.Kind() { + case json.ObjectClose: + if typeURL == "" { + // Did not find @type field. + if numFields > 0 { + return json.Token{}, errMissingType + } + return json.Token{}, errEmptyObject + } + break Loop + + case json.Name: + numFields++ + if tok.Name() != "@type" { + // Skip value. + if err := d.skipJSONValue(); err != nil { + return json.Token{}, err + } + continue + } + + // Return error if this was previously set already. + if typeURL != "" { + return json.Token{}, d.newError(tok.Pos(), `duplicate "@type" field`) + } + // Read field value. + tok, err := d.Read() + if err != nil { + return json.Token{}, err + } + if tok.Kind() != json.String { + return json.Token{}, d.newError(tok.Pos(), `@type field value is not a string: %v`, tok.RawString()) + } + typeURL = tok.ParsedString() + if typeURL == "" { + return json.Token{}, d.newError(tok.Pos(), `@type field contains empty value`) + } + typeTok = tok + } + } + + return typeTok, nil +} + +// skipJSONValue parses a JSON value (null, boolean, string, number, object and +// array) in order to advance the read to the next JSON value. It relies on +// the decoder returning an error if the types are not in valid sequence. +func (d decoder) skipJSONValue() error { + tok, err := d.Read() + if err != nil { + return err + } + // Only need to continue reading for objects and arrays. + switch tok.Kind() { + case json.ObjectOpen: + for { + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case json.ObjectClose: + return nil + case json.Name: + // Skip object field value. + if err := d.skipJSONValue(); err != nil { + return err + } + } + } + + case json.ArrayOpen: + for { + tok, err := d.Peek() + if err != nil { + return err + } + switch tok.Kind() { + case json.ArrayClose: + d.Read() + return nil + default: + // Skip array item. + if err := d.skipJSONValue(); err != nil { + return err + } + } + } + } + return nil +} + +// unmarshalAnyValue unmarshals the given custom-type message from the JSON +// object's "value" field. +func (d decoder) unmarshalAnyValue(unmarshal unmarshalFunc, m pref.Message) error { + // Skip ObjectOpen, and start reading the fields. + d.Read() + + var found bool // Used for detecting duplicate "value". + for { + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case json.ObjectClose: + if !found { + return d.newError(tok.Pos(), `missing "value" field`) + } + return nil + + case json.Name: + switch tok.Name() { + case "@type": + // Skip the value as this was previously parsed already. + d.Read() + + case "value": + if found { + return d.newError(tok.Pos(), `duplicate "value" field`) + } + // Unmarshal the field value into the given message. + if err := unmarshal(d, m); err != nil { + return err + } + found = true + + default: + if d.opts.DiscardUnknown { + if err := d.skipJSONValue(); err != nil { + return err + } + continue + } + return d.newError(tok.Pos(), "unknown field %v", tok.RawString()) + } + } + } +} + +// Wrapper types are encoded as JSON primitives like string, number or boolean. + +func (e encoder) marshalWrapperType(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.WrapperValue_Value_field_number) + val := m.Get(fd) + return e.marshalSingular(val, fd) +} + +func (d decoder) unmarshalWrapperType(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.WrapperValue_Value_field_number) + val, err := d.unmarshalScalar(fd) + if err != nil { + return err + } + m.Set(fd, val) + return nil +} + +// The JSON representation for Empty is an empty JSON object. + +func (e encoder) marshalEmpty(pref.Message) error { + e.StartObject() + e.EndObject() + return nil +} + +func (d decoder) unmarshalEmpty(pref.Message) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.ObjectOpen { + return d.unexpectedTokenError(tok) + } + + for { + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case json.ObjectClose: + return nil + + case json.Name: + if d.opts.DiscardUnknown { + if err := d.skipJSONValue(); err != nil { + return err + } + continue + } + return d.newError(tok.Pos(), "unknown field %v", tok.RawString()) + + default: + return d.unexpectedTokenError(tok) + } + } +} + +// The JSON representation for Struct is a JSON object that contains the encoded +// Struct.fields map and follows the serialization rules for a map. + +func (e encoder) marshalStruct(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.Struct_Fields_field_number) + return e.marshalMap(m.Get(fd).Map(), fd) +} + +func (d decoder) unmarshalStruct(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.Struct_Fields_field_number) + return d.unmarshalMap(m.Mutable(fd).Map(), fd) +} + +// The JSON representation for ListValue is JSON array that contains the encoded +// ListValue.values repeated field and follows the serialization rules for a +// repeated field. + +func (e encoder) marshalListValue(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.ListValue_Values_field_number) + return e.marshalList(m.Get(fd).List(), fd) +} + +func (d decoder) unmarshalListValue(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.ListValue_Values_field_number) + return d.unmarshalList(m.Mutable(fd).List(), fd) +} + +// The JSON representation for a Value is dependent on the oneof field that is +// set. Each of the field in the oneof has its own custom serialization rule. A +// Value message needs to be a oneof field set, else it is an error. + +func (e encoder) marshalKnownValue(m pref.Message) error { + od := m.Descriptor().Oneofs().ByName(genid.Value_Kind_oneof_name) + fd := m.WhichOneof(od) + if fd == nil { + return errors.New("%s: none of the oneof fields is set", genid.Value_message_fullname) + } + if fd.Number() == genid.Value_NumberValue_field_number { + if v := m.Get(fd).Float(); math.IsNaN(v) || math.IsInf(v, 0) { + return errors.New("%s: invalid %v value", genid.Value_NumberValue_field_fullname, v) + } + } + return e.marshalSingular(m.Get(fd), fd) +} + +func (d decoder) unmarshalKnownValue(m pref.Message) error { + tok, err := d.Peek() + if err != nil { + return err + } + + var fd pref.FieldDescriptor + var val pref.Value + switch tok.Kind() { + case json.Null: + d.Read() + fd = m.Descriptor().Fields().ByNumber(genid.Value_NullValue_field_number) + val = pref.ValueOfEnum(0) + + case json.Bool: + tok, err := d.Read() + if err != nil { + return err + } + fd = m.Descriptor().Fields().ByNumber(genid.Value_BoolValue_field_number) + val = pref.ValueOfBool(tok.Bool()) + + case json.Number: + tok, err := d.Read() + if err != nil { + return err + } + fd = m.Descriptor().Fields().ByNumber(genid.Value_NumberValue_field_number) + var ok bool + val, ok = unmarshalFloat(tok, 64) + if !ok { + return d.newError(tok.Pos(), "invalid %v: %v", genid.Value_message_fullname, tok.RawString()) + } + + case json.String: + // A JSON string may have been encoded from the number_value field, + // e.g. "NaN", "Infinity", etc. Parsing a proto double type also allows + // for it to be in JSON string form. Given this custom encoding spec, + // however, there is no way to identify that and hence a JSON string is + // always assigned to the string_value field, which means that certain + // encoding cannot be parsed back to the same field. + tok, err := d.Read() + if err != nil { + return err + } + fd = m.Descriptor().Fields().ByNumber(genid.Value_StringValue_field_number) + val = pref.ValueOfString(tok.ParsedString()) + + case json.ObjectOpen: + fd = m.Descriptor().Fields().ByNumber(genid.Value_StructValue_field_number) + val = m.NewField(fd) + if err := d.unmarshalStruct(val.Message()); err != nil { + return err + } + + case json.ArrayOpen: + fd = m.Descriptor().Fields().ByNumber(genid.Value_ListValue_field_number) + val = m.NewField(fd) + if err := d.unmarshalListValue(val.Message()); err != nil { + return err + } + + default: + return d.newError(tok.Pos(), "invalid %v: %v", genid.Value_message_fullname, tok.RawString()) + } + + m.Set(fd, val) + return nil +} + +// The JSON representation for a Duration is a JSON string that ends in the +// suffix "s" (indicating seconds) and is preceded by the number of seconds, +// with nanoseconds expressed as fractional seconds. +// +// Durations less than one second are represented with a 0 seconds field and a +// positive or negative nanos field. For durations of one second or more, a +// non-zero value for the nanos field must be of the same sign as the seconds +// field. +// +// Duration.seconds must be from -315,576,000,000 to +315,576,000,000 inclusive. +// Duration.nanos must be from -999,999,999 to +999,999,999 inclusive. + +const ( + secondsInNanos = 999999999 + maxSecondsInDuration = 315576000000 +) + +func (e encoder) marshalDuration(m pref.Message) error { + fds := m.Descriptor().Fields() + fdSeconds := fds.ByNumber(genid.Duration_Seconds_field_number) + fdNanos := fds.ByNumber(genid.Duration_Nanos_field_number) + + secsVal := m.Get(fdSeconds) + nanosVal := m.Get(fdNanos) + secs := secsVal.Int() + nanos := nanosVal.Int() + if secs < -maxSecondsInDuration || secs > maxSecondsInDuration { + return errors.New("%s: seconds out of range %v", genid.Duration_message_fullname, secs) + } + if nanos < -secondsInNanos || nanos > secondsInNanos { + return errors.New("%s: nanos out of range %v", genid.Duration_message_fullname, nanos) + } + if (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0) { + return errors.New("%s: signs of seconds and nanos do not match", genid.Duration_message_fullname) + } + // Generated output always contains 0, 3, 6, or 9 fractional digits, + // depending on required precision, followed by the suffix "s". + var sign string + if secs < 0 || nanos < 0 { + sign, secs, nanos = "-", -1*secs, -1*nanos + } + x := fmt.Sprintf("%s%d.%09d", sign, secs, nanos) + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + e.WriteString(x + "s") + return nil +} + +func (d decoder) unmarshalDuration(m pref.Message) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.String { + return d.unexpectedTokenError(tok) + } + + secs, nanos, ok := parseDuration(tok.ParsedString()) + if !ok { + return d.newError(tok.Pos(), "invalid %v value %v", genid.Duration_message_fullname, tok.RawString()) + } + // Validate seconds. No need to validate nanos because parseDuration would + // have covered that already. + if secs < -maxSecondsInDuration || secs > maxSecondsInDuration { + return d.newError(tok.Pos(), "%v value out of range: %v", genid.Duration_message_fullname, tok.RawString()) + } + + fds := m.Descriptor().Fields() + fdSeconds := fds.ByNumber(genid.Duration_Seconds_field_number) + fdNanos := fds.ByNumber(genid.Duration_Nanos_field_number) + + m.Set(fdSeconds, pref.ValueOfInt64(secs)) + m.Set(fdNanos, pref.ValueOfInt32(nanos)) + return nil +} + +// parseDuration parses the given input string for seconds and nanoseconds value +// for the Duration JSON format. The format is a decimal number with a suffix +// 's'. It can have optional plus/minus sign. There needs to be at least an +// integer or fractional part. Fractional part is limited to 9 digits only for +// nanoseconds precision, regardless of whether there are trailing zero digits. +// Example values are 1s, 0.1s, 1.s, .1s, +1s, -1s, -.1s. +func parseDuration(input string) (int64, int32, bool) { + b := []byte(input) + size := len(b) + if size < 2 { + return 0, 0, false + } + if b[size-1] != 's' { + return 0, 0, false + } + b = b[:size-1] + + // Read optional plus/minus symbol. + var neg bool + switch b[0] { + case '-': + neg = true + b = b[1:] + case '+': + b = b[1:] + } + if len(b) == 0 { + return 0, 0, false + } + + // Read the integer part. + var intp []byte + switch { + case b[0] == '0': + b = b[1:] + + case '1' <= b[0] && b[0] <= '9': + intp = b[0:] + b = b[1:] + n := 1 + for len(b) > 0 && '0' <= b[0] && b[0] <= '9' { + n++ + b = b[1:] + } + intp = intp[:n] + + case b[0] == '.': + // Continue below. + + default: + return 0, 0, false + } + + hasFrac := false + var frac [9]byte + if len(b) > 0 { + if b[0] != '.' { + return 0, 0, false + } + // Read the fractional part. + b = b[1:] + n := 0 + for len(b) > 0 && n < 9 && '0' <= b[0] && b[0] <= '9' { + frac[n] = b[0] + n++ + b = b[1:] + } + // It is not valid if there are more bytes left. + if len(b) > 0 { + return 0, 0, false + } + // Pad fractional part with 0s. + for i := n; i < 9; i++ { + frac[i] = '0' + } + hasFrac = true + } + + var secs int64 + if len(intp) > 0 { + var err error + secs, err = strconv.ParseInt(string(intp), 10, 64) + if err != nil { + return 0, 0, false + } + } + + var nanos int64 + if hasFrac { + nanob := bytes.TrimLeft(frac[:], "0") + if len(nanob) > 0 { + var err error + nanos, err = strconv.ParseInt(string(nanob), 10, 32) + if err != nil { + return 0, 0, false + } + } + } + + if neg { + if secs > 0 { + secs = -secs + } + if nanos > 0 { + nanos = -nanos + } + } + return secs, int32(nanos), true +} + +// The JSON representation for a Timestamp is a JSON string in the RFC 3339 +// format, i.e. "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" where +// {year} is always expressed using four digits while {month}, {day}, {hour}, +// {min}, and {sec} are zero-padded to two digits each. The fractional seconds, +// which can go up to 9 digits, up to 1 nanosecond resolution, is optional. The +// "Z" suffix indicates the timezone ("UTC"); the timezone is required. Encoding +// should always use UTC (as indicated by "Z") and a decoder should be able to +// accept both UTC and other timezones (as indicated by an offset). +// +// Timestamp.seconds must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z +// inclusive. +// Timestamp.nanos must be from 0 to 999,999,999 inclusive. + +const ( + maxTimestampSeconds = 253402300799 + minTimestampSeconds = -62135596800 +) + +func (e encoder) marshalTimestamp(m pref.Message) error { + fds := m.Descriptor().Fields() + fdSeconds := fds.ByNumber(genid.Timestamp_Seconds_field_number) + fdNanos := fds.ByNumber(genid.Timestamp_Nanos_field_number) + + secsVal := m.Get(fdSeconds) + nanosVal := m.Get(fdNanos) + secs := secsVal.Int() + nanos := nanosVal.Int() + if secs < minTimestampSeconds || secs > maxTimestampSeconds { + return errors.New("%s: seconds out of range %v", genid.Timestamp_message_fullname, secs) + } + if nanos < 0 || nanos > secondsInNanos { + return errors.New("%s: nanos out of range %v", genid.Timestamp_message_fullname, nanos) + } + // Uses RFC 3339, where generated output will be Z-normalized and uses 0, 3, + // 6 or 9 fractional digits. + t := time.Unix(secs, nanos).UTC() + x := t.Format("2006-01-02T15:04:05.000000000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + e.WriteString(x + "Z") + return nil +} + +func (d decoder) unmarshalTimestamp(m pref.Message) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.String { + return d.unexpectedTokenError(tok) + } + + t, err := time.Parse(time.RFC3339Nano, tok.ParsedString()) + if err != nil { + return d.newError(tok.Pos(), "invalid %v value %v", genid.Timestamp_message_fullname, tok.RawString()) + } + // Validate seconds. No need to validate nanos because time.Parse would have + // covered that already. + secs := t.Unix() + if secs < minTimestampSeconds || secs > maxTimestampSeconds { + return d.newError(tok.Pos(), "%v value out of range: %v", genid.Timestamp_message_fullname, tok.RawString()) + } + + fds := m.Descriptor().Fields() + fdSeconds := fds.ByNumber(genid.Timestamp_Seconds_field_number) + fdNanos := fds.ByNumber(genid.Timestamp_Nanos_field_number) + + m.Set(fdSeconds, pref.ValueOfInt64(secs)) + m.Set(fdNanos, pref.ValueOfInt32(int32(t.Nanosecond()))) + return nil +} + +// The JSON representation for a FieldMask is a JSON string where paths are +// separated by a comma. Fields name in each path are converted to/from +// lower-camel naming conventions. Encoding should fail if the path name would +// end up differently after a round-trip. + +func (e encoder) marshalFieldMask(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.FieldMask_Paths_field_number) + list := m.Get(fd).List() + paths := make([]string, 0, list.Len()) + + for i := 0; i < list.Len(); i++ { + s := list.Get(i).String() + if !pref.FullName(s).IsValid() { + return errors.New("%s contains invalid path: %q", genid.FieldMask_Paths_field_fullname, s) + } + // Return error if conversion to camelCase is not reversible. + cc := strs.JSONCamelCase(s) + if s != strs.JSONSnakeCase(cc) { + return errors.New("%s contains irreversible value %q", genid.FieldMask_Paths_field_fullname, s) + } + paths = append(paths, cc) + } + + e.WriteString(strings.Join(paths, ",")) + return nil +} + +func (d decoder) unmarshalFieldMask(m pref.Message) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.String { + return d.unexpectedTokenError(tok) + } + str := strings.TrimSpace(tok.ParsedString()) + if str == "" { + return nil + } + paths := strings.Split(str, ",") + + fd := m.Descriptor().Fields().ByNumber(genid.FieldMask_Paths_field_number) + list := m.Mutable(fd).List() + + for _, s0 := range paths { + s := strs.JSONSnakeCase(s0) + if strings.Contains(s0, "_") || !pref.FullName(s).IsValid() { + return d.newError(tok.Pos(), "%v contains invalid path: %q", genid.FieldMask_Paths_field_fullname, s0) + } + list.Append(pref.ValueOfString(s)) + } + return nil +} diff --git a/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode.go b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode.go new file mode 100644 index 00000000000..b13fd29e81e --- /dev/null +++ b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode.go @@ -0,0 +1,340 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "bytes" + "fmt" + "io" + "regexp" + "unicode/utf8" + + "google.golang.org/protobuf/internal/errors" +) + +// call specifies which Decoder method was invoked. +type call uint8 + +const ( + readCall call = iota + peekCall +) + +const unexpectedFmt = "unexpected token %s" + +// ErrUnexpectedEOF means that EOF was encountered in the middle of the input. +var ErrUnexpectedEOF = errors.New("%v", io.ErrUnexpectedEOF) + +// Decoder is a token-based JSON decoder. +type Decoder struct { + // lastCall is last method called, either readCall or peekCall. + // Initial value is readCall. + lastCall call + + // lastToken contains the last read token. + lastToken Token + + // lastErr contains the last read error. + lastErr error + + // openStack is a stack containing ObjectOpen and ArrayOpen values. The + // top of stack represents the object or the array the current value is + // directly located in. + openStack []Kind + + // orig is used in reporting line and column. + orig []byte + // in contains the unconsumed input. + in []byte +} + +// NewDecoder returns a Decoder to read the given []byte. +func NewDecoder(b []byte) *Decoder { + return &Decoder{orig: b, in: b} +} + +// Peek looks ahead and returns the next token kind without advancing a read. +func (d *Decoder) Peek() (Token, error) { + defer func() { d.lastCall = peekCall }() + if d.lastCall == readCall { + d.lastToken, d.lastErr = d.Read() + } + return d.lastToken, d.lastErr +} + +// Read returns the next JSON token. +// It will return an error if there is no valid token. +func (d *Decoder) Read() (Token, error) { + const scalar = Null | Bool | Number | String + + defer func() { d.lastCall = readCall }() + if d.lastCall == peekCall { + return d.lastToken, d.lastErr + } + + tok, err := d.parseNext() + if err != nil { + return Token{}, err + } + + switch tok.kind { + case EOF: + if len(d.openStack) != 0 || + d.lastToken.kind&scalar|ObjectClose|ArrayClose == 0 { + return Token{}, ErrUnexpectedEOF + } + + case Null: + if !d.isValueNext() { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + + case Bool, Number: + if !d.isValueNext() { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + + case String: + if d.isValueNext() { + break + } + // This string token should only be for a field name. + if d.lastToken.kind&(ObjectOpen|comma) == 0 { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + if len(d.in) == 0 { + return Token{}, ErrUnexpectedEOF + } + if c := d.in[0]; c != ':' { + return Token{}, d.newSyntaxError(d.currPos(), `unexpected character %s, missing ":" after field name`, string(c)) + } + tok.kind = Name + d.consume(1) + + case ObjectOpen, ArrayOpen: + if !d.isValueNext() { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + d.openStack = append(d.openStack, tok.kind) + + case ObjectClose: + if len(d.openStack) == 0 || + d.lastToken.kind == comma || + d.openStack[len(d.openStack)-1] != ObjectOpen { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + d.openStack = d.openStack[:len(d.openStack)-1] + + case ArrayClose: + if len(d.openStack) == 0 || + d.lastToken.kind == comma || + d.openStack[len(d.openStack)-1] != ArrayOpen { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + d.openStack = d.openStack[:len(d.openStack)-1] + + case comma: + if len(d.openStack) == 0 || + d.lastToken.kind&(scalar|ObjectClose|ArrayClose) == 0 { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + } + + // Update d.lastToken only after validating token to be in the right sequence. + d.lastToken = tok + + if d.lastToken.kind == comma { + return d.Read() + } + return tok, nil +} + +// Any sequence that looks like a non-delimiter (for error reporting). +var errRegexp = regexp.MustCompile(`^([-+._a-zA-Z0-9]{1,32}|.)`) + +// parseNext parses for the next JSON token. It returns a Token object for +// different types, except for Name. It does not handle whether the next token +// is in a valid sequence or not. +func (d *Decoder) parseNext() (Token, error) { + // Trim leading spaces. + d.consume(0) + + in := d.in + if len(in) == 0 { + return d.consumeToken(EOF, 0), nil + } + + switch in[0] { + case 'n': + if n := matchWithDelim("null", in); n != 0 { + return d.consumeToken(Null, n), nil + } + + case 't': + if n := matchWithDelim("true", in); n != 0 { + return d.consumeBoolToken(true, n), nil + } + + case 'f': + if n := matchWithDelim("false", in); n != 0 { + return d.consumeBoolToken(false, n), nil + } + + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + if n, ok := parseNumber(in); ok { + return d.consumeToken(Number, n), nil + } + + case '"': + s, n, err := d.parseString(in) + if err != nil { + return Token{}, err + } + return d.consumeStringToken(s, n), nil + + case '{': + return d.consumeToken(ObjectOpen, 1), nil + + case '}': + return d.consumeToken(ObjectClose, 1), nil + + case '[': + return d.consumeToken(ArrayOpen, 1), nil + + case ']': + return d.consumeToken(ArrayClose, 1), nil + + case ',': + return d.consumeToken(comma, 1), nil + } + return Token{}, d.newSyntaxError(d.currPos(), "invalid value %s", errRegexp.Find(in)) +} + +// newSyntaxError returns an error with line and column information useful for +// syntax errors. +func (d *Decoder) newSyntaxError(pos int, f string, x ...interface{}) error { + e := errors.New(f, x...) + line, column := d.Position(pos) + return errors.New("syntax error (line %d:%d): %v", line, column, e) +} + +// Position returns line and column number of given index of the original input. +// It will panic if index is out of range. +func (d *Decoder) Position(idx int) (line int, column int) { + b := d.orig[:idx] + line = bytes.Count(b, []byte("\n")) + 1 + if i := bytes.LastIndexByte(b, '\n'); i >= 0 { + b = b[i+1:] + } + column = utf8.RuneCount(b) + 1 // ignore multi-rune characters + return line, column +} + +// currPos returns the current index position of d.in from d.orig. +func (d *Decoder) currPos() int { + return len(d.orig) - len(d.in) +} + +// matchWithDelim matches s with the input b and verifies that the match +// terminates with a delimiter of some form (e.g., r"[^-+_.a-zA-Z0-9]"). +// As a special case, EOF is considered a delimiter. It returns the length of s +// if there is a match, else 0. +func matchWithDelim(s string, b []byte) int { + if !bytes.HasPrefix(b, []byte(s)) { + return 0 + } + + n := len(s) + if n < len(b) && isNotDelim(b[n]) { + return 0 + } + return n +} + +// isNotDelim returns true if given byte is a not delimiter character. +func isNotDelim(c byte) bool { + return (c == '-' || c == '+' || c == '.' || c == '_' || + ('a' <= c && c <= 'z') || + ('A' <= c && c <= 'Z') || + ('0' <= c && c <= '9')) +} + +// consume consumes n bytes of input and any subsequent whitespace. +func (d *Decoder) consume(n int) { + d.in = d.in[n:] + for len(d.in) > 0 { + switch d.in[0] { + case ' ', '\n', '\r', '\t': + d.in = d.in[1:] + default: + return + } + } +} + +// isValueNext returns true if next type should be a JSON value: Null, +// Number, String or Bool. +func (d *Decoder) isValueNext() bool { + if len(d.openStack) == 0 { + return d.lastToken.kind == 0 + } + + start := d.openStack[len(d.openStack)-1] + switch start { + case ObjectOpen: + return d.lastToken.kind&Name != 0 + case ArrayOpen: + return d.lastToken.kind&(ArrayOpen|comma) != 0 + } + panic(fmt.Sprintf( + "unreachable logic in Decoder.isValueNext, lastToken.kind: %v, openStack: %v", + d.lastToken.kind, start)) +} + +// consumeToken constructs a Token for given Kind with raw value derived from +// current d.in and given size, and consumes the given size-lenght of it. +func (d *Decoder) consumeToken(kind Kind, size int) Token { + tok := Token{ + kind: kind, + raw: d.in[:size], + pos: len(d.orig) - len(d.in), + } + d.consume(size) + return tok +} + +// consumeBoolToken constructs a Token for a Bool kind with raw value derived from +// current d.in and given size. +func (d *Decoder) consumeBoolToken(b bool, size int) Token { + tok := Token{ + kind: Bool, + raw: d.in[:size], + pos: len(d.orig) - len(d.in), + boo: b, + } + d.consume(size) + return tok +} + +// consumeStringToken constructs a Token for a String kind with raw value derived +// from current d.in and given size. +func (d *Decoder) consumeStringToken(s string, size int) Token { + tok := Token{ + kind: String, + raw: d.in[:size], + pos: len(d.orig) - len(d.in), + str: s, + } + d.consume(size) + return tok +} + +// Clone returns a copy of the Decoder for use in reading ahead the next JSON +// object, array or other values without affecting current Decoder. +func (d *Decoder) Clone() *Decoder { + ret := *d + ret.openStack = append([]Kind(nil), ret.openStack...) + return &ret +} diff --git a/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode_number.go b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode_number.go new file mode 100644 index 00000000000..2999d713320 --- /dev/null +++ b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode_number.go @@ -0,0 +1,254 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "bytes" + "strconv" +) + +// parseNumber reads the given []byte for a valid JSON number. If it is valid, +// it returns the number of bytes. Parsing logic follows the definition in +// https://tools.ietf.org/html/rfc7159#section-6, and is based off +// encoding/json.isValidNumber function. +func parseNumber(input []byte) (int, bool) { + var n int + + s := input + if len(s) == 0 { + return 0, false + } + + // Optional - + if s[0] == '-' { + s = s[1:] + n++ + if len(s) == 0 { + return 0, false + } + } + + // Digits + switch { + case s[0] == '0': + s = s[1:] + n++ + + case '1' <= s[0] && s[0] <= '9': + s = s[1:] + n++ + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + + default: + return 0, false + } + + // . followed by 1 or more digits. + if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { + s = s[2:] + n += 2 + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + } + + // e or E followed by an optional - or + and + // 1 or more digits. + if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { + s = s[1:] + n++ + if s[0] == '+' || s[0] == '-' { + s = s[1:] + n++ + if len(s) == 0 { + return 0, false + } + } + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + } + + // Check that next byte is a delimiter or it is at the end. + if n < len(input) && isNotDelim(input[n]) { + return 0, false + } + + return n, true +} + +// numberParts is the result of parsing out a valid JSON number. It contains +// the parts of a number. The parts are used for integer conversion. +type numberParts struct { + neg bool + intp []byte + frac []byte + exp []byte +} + +// parseNumber constructs numberParts from given []byte. The logic here is +// similar to consumeNumber above with the difference of having to construct +// numberParts. The slice fields in numberParts are subslices of the input. +func parseNumberParts(input []byte) (numberParts, bool) { + var neg bool + var intp []byte + var frac []byte + var exp []byte + + s := input + if len(s) == 0 { + return numberParts{}, false + } + + // Optional - + if s[0] == '-' { + neg = true + s = s[1:] + if len(s) == 0 { + return numberParts{}, false + } + } + + // Digits + switch { + case s[0] == '0': + // Skip first 0 and no need to store. + s = s[1:] + + case '1' <= s[0] && s[0] <= '9': + intp = s + n := 1 + s = s[1:] + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + intp = intp[:n] + + default: + return numberParts{}, false + } + + // . followed by 1 or more digits. + if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { + frac = s[1:] + n := 1 + s = s[2:] + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + frac = frac[:n] + } + + // e or E followed by an optional - or + and + // 1 or more digits. + if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { + s = s[1:] + exp = s + n := 0 + if s[0] == '+' || s[0] == '-' { + s = s[1:] + n++ + if len(s) == 0 { + return numberParts{}, false + } + } + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + exp = exp[:n] + } + + return numberParts{ + neg: neg, + intp: intp, + frac: bytes.TrimRight(frac, "0"), // Remove unnecessary 0s to the right. + exp: exp, + }, true +} + +// normalizeToIntString returns an integer string in normal form without the +// E-notation for given numberParts. It will return false if it is not an +// integer or if the exponent exceeds than max/min int value. +func normalizeToIntString(n numberParts) (string, bool) { + intpSize := len(n.intp) + fracSize := len(n.frac) + + if intpSize == 0 && fracSize == 0 { + return "0", true + } + + var exp int + if len(n.exp) > 0 { + i, err := strconv.ParseInt(string(n.exp), 10, 32) + if err != nil { + return "", false + } + exp = int(i) + } + + var num []byte + if exp >= 0 { + // For positive E, shift fraction digits into integer part and also pad + // with zeroes as needed. + + // If there are more digits in fraction than the E value, then the + // number is not an integer. + if fracSize > exp { + return "", false + } + + // Make sure resulting digits are within max value limit to avoid + // unnecessarily constructing a large byte slice that may simply fail + // later on. + const maxDigits = 20 // Max uint64 value has 20 decimal digits. + if intpSize+exp > maxDigits { + return "", false + } + + // Set cap to make a copy of integer part when appended. + num = n.intp[:len(n.intp):len(n.intp)] + num = append(num, n.frac...) + for i := 0; i < exp-fracSize; i++ { + num = append(num, '0') + } + } else { + // For negative E, shift digits in integer part out. + + // If there are fractions, then the number is not an integer. + if fracSize > 0 { + return "", false + } + + // index is where the decimal point will be after adjusting for negative + // exponent. + index := intpSize + exp + if index < 0 { + return "", false + } + + num = n.intp + // If any of the digits being shifted to the right of the decimal point + // is non-zero, then the number is not an integer. + for i := index; i < intpSize; i++ { + if num[i] != '0' { + return "", false + } + } + num = num[:index] + } + + if n.neg { + return "-" + string(num), true + } + return string(num), true +} diff --git a/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode_string.go b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode_string.go new file mode 100644 index 00000000000..f7fea7d8dd4 --- /dev/null +++ b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode_string.go @@ -0,0 +1,91 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "strconv" + "unicode" + "unicode/utf16" + "unicode/utf8" + + "google.golang.org/protobuf/internal/strs" +) + +func (d *Decoder) parseString(in []byte) (string, int, error) { + in0 := in + if len(in) == 0 { + return "", 0, ErrUnexpectedEOF + } + if in[0] != '"' { + return "", 0, d.newSyntaxError(d.currPos(), "invalid character %q at start of string", in[0]) + } + in = in[1:] + i := indexNeedEscapeInBytes(in) + in, out := in[i:], in[:i:i] // set cap to prevent mutations + for len(in) > 0 { + switch r, n := utf8.DecodeRune(in); { + case r == utf8.RuneError && n == 1: + return "", 0, d.newSyntaxError(d.currPos(), "invalid UTF-8 in string") + case r < ' ': + return "", 0, d.newSyntaxError(d.currPos(), "invalid character %q in string", r) + case r == '"': + in = in[1:] + n := len(in0) - len(in) + return string(out), n, nil + case r == '\\': + if len(in) < 2 { + return "", 0, ErrUnexpectedEOF + } + switch r := in[1]; r { + case '"', '\\', '/': + in, out = in[2:], append(out, r) + case 'b': + in, out = in[2:], append(out, '\b') + case 'f': + in, out = in[2:], append(out, '\f') + case 'n': + in, out = in[2:], append(out, '\n') + case 'r': + in, out = in[2:], append(out, '\r') + case 't': + in, out = in[2:], append(out, '\t') + case 'u': + if len(in) < 6 { + return "", 0, ErrUnexpectedEOF + } + v, err := strconv.ParseUint(string(in[2:6]), 16, 16) + if err != nil { + return "", 0, d.newSyntaxError(d.currPos(), "invalid escape code %q in string", in[:6]) + } + in = in[6:] + + r := rune(v) + if utf16.IsSurrogate(r) { + if len(in) < 6 { + return "", 0, ErrUnexpectedEOF + } + v, err := strconv.ParseUint(string(in[2:6]), 16, 16) + r = utf16.DecodeRune(r, rune(v)) + if in[0] != '\\' || in[1] != 'u' || + r == unicode.ReplacementChar || err != nil { + return "", 0, d.newSyntaxError(d.currPos(), "invalid escape code %q in string", in[:6]) + } + in = in[6:] + } + out = append(out, string(r)...) + default: + return "", 0, d.newSyntaxError(d.currPos(), "invalid escape code %q in string", in[:2]) + } + default: + i := indexNeedEscapeInBytes(in[n:]) + in, out = in[n+i:], append(out, in[:n+i]...) + } + } + return "", 0, ErrUnexpectedEOF +} + +// indexNeedEscapeInBytes returns the index of the character that needs +// escaping. If no characters need escaping, this returns the input length. +func indexNeedEscapeInBytes(b []byte) int { return indexNeedEscapeInString(strs.UnsafeString(b)) } diff --git a/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode_token.go b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode_token.go new file mode 100644 index 00000000000..50578d6593c --- /dev/null +++ b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/decode_token.go @@ -0,0 +1,192 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "bytes" + "fmt" + "strconv" +) + +// Kind represents a token kind expressible in the JSON format. +type Kind uint16 + +const ( + Invalid Kind = (1 << iota) / 2 + EOF + Null + Bool + Number + String + Name + ObjectOpen + ObjectClose + ArrayOpen + ArrayClose + + // comma is only for parsing in between tokens and + // does not need to be exported. + comma +) + +func (k Kind) String() string { + switch k { + case EOF: + return "eof" + case Null: + return "null" + case Bool: + return "bool" + case Number: + return "number" + case String: + return "string" + case ObjectOpen: + return "{" + case ObjectClose: + return "}" + case Name: + return "name" + case ArrayOpen: + return "[" + case ArrayClose: + return "]" + case comma: + return "," + } + return "" +} + +// Token provides a parsed token kind and value. +// +// Values are provided by the difference accessor methods. The accessor methods +// Name, Bool, and ParsedString will panic if called on the wrong kind. There +// are different accessor methods for the Number kind for converting to the +// appropriate Go numeric type and those methods have the ok return value. +type Token struct { + // Token kind. + kind Kind + // pos provides the position of the token in the original input. + pos int + // raw bytes of the serialized token. + // This is a subslice into the original input. + raw []byte + // boo is parsed boolean value. + boo bool + // str is parsed string value. + str string +} + +// Kind returns the token kind. +func (t Token) Kind() Kind { + return t.kind +} + +// RawString returns the read value in string. +func (t Token) RawString() string { + return string(t.raw) +} + +// Pos returns the token position from the input. +func (t Token) Pos() int { + return t.pos +} + +// Name returns the object name if token is Name, else it panics. +func (t Token) Name() string { + if t.kind == Name { + return t.str + } + panic(fmt.Sprintf("Token is not a Name: %v", t.RawString())) +} + +// Bool returns the bool value if token kind is Bool, else it panics. +func (t Token) Bool() bool { + if t.kind == Bool { + return t.boo + } + panic(fmt.Sprintf("Token is not a Bool: %v", t.RawString())) +} + +// ParsedString returns the string value for a JSON string token or the read +// value in string if token is not a string. +func (t Token) ParsedString() string { + if t.kind == String { + return t.str + } + panic(fmt.Sprintf("Token is not a String: %v", t.RawString())) +} + +// Float returns the floating-point number if token kind is Number. +// +// The floating-point precision is specified by the bitSize parameter: 32 for +// float32 or 64 for float64. If bitSize=32, the result still has type float64, +// but it will be convertible to float32 without changing its value. It will +// return false if the number exceeds the floating point limits for given +// bitSize. +func (t Token) Float(bitSize int) (float64, bool) { + if t.kind != Number { + return 0, false + } + f, err := strconv.ParseFloat(t.RawString(), bitSize) + if err != nil { + return 0, false + } + return f, true +} + +// Int returns the signed integer number if token is Number. +// +// The given bitSize specifies the integer type that the result must fit into. +// It returns false if the number is not an integer value or if the result +// exceeds the limits for given bitSize. +func (t Token) Int(bitSize int) (int64, bool) { + s, ok := t.getIntStr() + if !ok { + return 0, false + } + n, err := strconv.ParseInt(s, 10, bitSize) + if err != nil { + return 0, false + } + return n, true +} + +// Uint returns the signed integer number if token is Number. +// +// The given bitSize specifies the unsigned integer type that the result must +// fit into. It returns false if the number is not an unsigned integer value +// or if the result exceeds the limits for given bitSize. +func (t Token) Uint(bitSize int) (uint64, bool) { + s, ok := t.getIntStr() + if !ok { + return 0, false + } + n, err := strconv.ParseUint(s, 10, bitSize) + if err != nil { + return 0, false + } + return n, true +} + +func (t Token) getIntStr() (string, bool) { + if t.kind != Number { + return "", false + } + parts, ok := parseNumberParts(t.raw) + if !ok { + return "", false + } + return normalizeToIntString(parts) +} + +// TokenEquals returns true if given Tokens are equal, else false. +func TokenEquals(x, y Token) bool { + return x.kind == y.kind && + x.pos == y.pos && + bytes.Equal(x.raw, y.raw) && + x.boo == y.boo && + x.str == y.str +} diff --git a/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/encode.go b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/encode.go new file mode 100644 index 00000000000..fbdf3487342 --- /dev/null +++ b/providerlint/vendor/google.golang.org/protobuf/internal/encoding/json/encode.go @@ -0,0 +1,276 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "math" + "math/bits" + "strconv" + "strings" + "unicode/utf8" + + "google.golang.org/protobuf/internal/detrand" + "google.golang.org/protobuf/internal/errors" +) + +// kind represents an encoding type. +type kind uint8 + +const ( + _ kind = (1 << iota) / 2 + name + scalar + objectOpen + objectClose + arrayOpen + arrayClose +) + +// Encoder provides methods to write out JSON constructs and values. The user is +// responsible for producing valid sequences of JSON constructs and values. +type Encoder struct { + indent string + lastKind kind + indents []byte + out []byte +} + +// NewEncoder returns an Encoder. +// +// If indent is a non-empty string, it causes every entry for an Array or Object +// to be preceded by the indent and trailed by a newline. +func NewEncoder(indent string) (*Encoder, error) { + e := &Encoder{} + if len(indent) > 0 { + if strings.Trim(indent, " \t") != "" { + return nil, errors.New("indent may only be composed of space or tab characters") + } + e.indent = indent + } + return e, nil +} + +// Bytes returns the content of the written bytes. +func (e *Encoder) Bytes() []byte { + return e.out +} + +// WriteNull writes out the null value. +func (e *Encoder) WriteNull() { + e.prepareNext(scalar) + e.out = append(e.out, "null"...) +} + +// WriteBool writes out the given boolean value. +func (e *Encoder) WriteBool(b bool) { + e.prepareNext(scalar) + if b { + e.out = append(e.out, "true"...) + } else { + e.out = append(e.out, "false"...) + } +} + +// WriteString writes out the given string in JSON string value. Returns error +// if input string contains invalid UTF-8. +func (e *Encoder) WriteString(s string) error { + e.prepareNext(scalar) + var err error + if e.out, err = appendString(e.out, s); err != nil { + return err + } + return nil +} + +// Sentinel error used for indicating invalid UTF-8. +var errInvalidUTF8 = errors.New("invalid UTF-8") + +func appendString(out []byte, in string) ([]byte, error) { + out = append(out, '"') + i := indexNeedEscapeInString(in) + in, out = in[i:], append(out, in[:i]...) + for len(in) > 0 { + switch r, n := utf8.DecodeRuneInString(in); { + case r == utf8.RuneError && n == 1: + return out, errInvalidUTF8 + case r < ' ' || r == '"' || r == '\\': + out = append(out, '\\') + switch r { + case '"', '\\': + out = append(out, byte(r)) + case '\b': + out = append(out, 'b') + case '\f': + out = append(out, 'f') + case '\n': + out = append(out, 'n') + case '\r': + out = append(out, 'r') + case '\t': + out = append(out, 't') + default: + out = append(out, 'u') + out = append(out, "0000"[1+(bits.Len32(uint32(r))-1)/4:]...) + out = strconv.AppendUint(out, uint64(r), 16) + } + in = in[n:] + default: + i := indexNeedEscapeInString(in[n:]) + in, out = in[n+i:], append(out, in[:n+i]...) + } + } + out = append(out, '"') + return out, nil +} + +// indexNeedEscapeInString returns the index of the character that needs +// escaping. If no characters need escaping, this returns the input length. +func indexNeedEscapeInString(s string) int { + for i, r := range s { + if r < ' ' || r == '\\' || r == '"' || r == utf8.RuneError { + return i + } + } + return len(s) +} + +// WriteFloat writes out the given float and bitSize in JSON number value. +func (e *Encoder) WriteFloat(n float64, bitSize int) { + e.prepareNext(scalar) + e.out = appendFloat(e.out, n, bitSize) +} + +// appendFloat formats given float in bitSize, and appends to the given []byte. +func appendFloat(out []byte, n float64, bitSize int) []byte { + switch { + case math.IsNaN(n): + return append(out, `"NaN"`...) + case math.IsInf(n, +1): + return append(out, `"Infinity"`...) + case math.IsInf(n, -1): + return append(out, `"-Infinity"`...) + } + + // JSON number formatting logic based on encoding/json. + // See floatEncoder.encode for reference. + fmt := byte('f') + if abs := math.Abs(n); abs != 0 { + if bitSize == 64 && (abs < 1e-6 || abs >= 1e21) || + bitSize == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { + fmt = 'e' + } + } + out = strconv.AppendFloat(out, n, fmt, -1, bitSize) + if fmt == 'e' { + n := len(out) + if n >= 4 && out[n-4] == 'e' && out[n-3] == '-' && out[n-2] == '0' { + out[n-2] = out[n-1] + out = out[:n-1] + } + } + return out +} + +// WriteInt writes out the given signed integer in JSON number value. +func (e *Encoder) WriteInt(n int64) { + e.prepareNext(scalar) + e.out = append(e.out, strconv.FormatInt(n, 10)...) +} + +// WriteUint writes out the given unsigned integer in JSON number value. +func (e *Encoder) WriteUint(n uint64) { + e.prepareNext(scalar) + e.out = append(e.out, strconv.FormatUint(n, 10)...) +} + +// StartObject writes out the '{' symbol. +func (e *Encoder) StartObject() { + e.prepareNext(objectOpen) + e.out = append(e.out, '{') +} + +// EndObject writes out the '}' symbol. +func (e *Encoder) EndObject() { + e.prepareNext(objectClose) + e.out = append(e.out, '}') +} + +// WriteName writes out the given string in JSON string value and the name +// separator ':'. Returns error if input string contains invalid UTF-8, which +// should not be likely as protobuf field names should be valid. +func (e *Encoder) WriteName(s string) error { + e.prepareNext(name) + var err error + // Append to output regardless of error. + e.out, err = appendString(e.out, s) + e.out = append(e.out, ':') + return err +} + +// StartArray writes out the '[' symbol. +func (e *Encoder) StartArray() { + e.prepareNext(arrayOpen) + e.out = append(e.out, '[') +} + +// EndArray writes out the ']' symbol. +func (e *Encoder) EndArray() { + e.prepareNext(arrayClose) + e.out = append(e.out, ']') +} + +// prepareNext adds possible comma and indentation for the next value based +// on last type and indent option. It also updates lastKind to next. +func (e *Encoder) prepareNext(next kind) { + defer func() { + // Set lastKind to next. + e.lastKind = next + }() + + if len(e.indent) == 0 { + // Need to add comma on the following condition. + if e.lastKind&(scalar|objectClose|arrayClose) != 0 && + next&(name|scalar|objectOpen|arrayOpen) != 0 { + e.out = append(e.out, ',') + // For single-line output, add a random extra space after each + // comma to make output unstable. + if detrand.Bool() { + e.out = append(e.out, ' ') + } + } + return + } + + switch { + case e.lastKind&(objectOpen|arrayOpen) != 0: + // If next type is NOT closing, add indent and newline. + if next&(objectClose|arrayClose) == 0 { + e.indents = append(e.indents, e.indent...) + e.out = append(e.out, '\n') + e.out = append(e.out, e.indents...) + } + + case e.lastKind&(scalar|objectClose|arrayClose) != 0: + switch { + // If next type is either a value or name, add comma and newline. + case next&(name|scalar|objectOpen|arrayOpen) != 0: + e.out = append(e.out, ',', '\n') + + // If next type is a closing object or array, adjust indentation. + case next&(objectClose|arrayClose) != 0: + e.indents = e.indents[:len(e.indents)-len(e.indent)] + e.out = append(e.out, '\n') + } + e.out = append(e.out, e.indents...) + + case e.lastKind&name != 0: + e.out = append(e.out, ' ') + // For multi-line output, add a random extra space after key: to make + // output unstable. + if detrand.Bool() { + e.out = append(e.out, ' ') + } + } +} diff --git a/providerlint/vendor/modules.txt b/providerlint/vendor/modules.txt index f2c7d1ccb80..3d903e3bff6 100644 --- a/providerlint/vendor/modules.txt +++ b/providerlint/vendor/modules.txt @@ -2,7 +2,7 @@ github.com/agext/levenshtein # github.com/apparentlymart/go-textseg/v13 v13.0.0 github.com/apparentlymart/go-textseg/v13/textseg -# github.com/aws/aws-sdk-go v1.44.15 +# github.com/aws/aws-sdk-go v1.44.39 ## explicit github.com/aws/aws-sdk-go/aws/awserr github.com/aws/aws-sdk-go/aws/endpoints @@ -165,6 +165,7 @@ github.com/davecgh/go-spew/spew # github.com/fatih/color v1.7.0 github.com/fatih/color # github.com/golang/protobuf v1.5.2 +github.com/golang/protobuf/jsonpb github.com/golang/protobuf/proto github.com/golang/protobuf/ptypes github.com/golang/protobuf/ptypes/any @@ -194,12 +195,12 @@ github.com/hashicorp/go-cty/cty/set github.com/hashicorp/go-hclog # github.com/hashicorp/go-multierror v1.1.1 github.com/hashicorp/go-multierror -# github.com/hashicorp/go-plugin v1.4.3 +# github.com/hashicorp/go-plugin v1.4.4 github.com/hashicorp/go-plugin github.com/hashicorp/go-plugin/internal/plugin # github.com/hashicorp/go-uuid v1.0.3 github.com/hashicorp/go-uuid -# github.com/hashicorp/go-version v1.4.0 +# github.com/hashicorp/go-version v1.5.0 github.com/hashicorp/go-version # github.com/hashicorp/hc-install v0.3.2 github.com/hashicorp/hc-install @@ -225,9 +226,9 @@ github.com/hashicorp/logutils # github.com/hashicorp/terraform-exec v0.16.1 github.com/hashicorp/terraform-exec/internal/version github.com/hashicorp/terraform-exec/tfexec -# github.com/hashicorp/terraform-json v0.13.0 +# github.com/hashicorp/terraform-json v0.14.0 github.com/hashicorp/terraform-json -# github.com/hashicorp/terraform-plugin-go v0.9.0 +# github.com/hashicorp/terraform-plugin-go v0.9.1 github.com/hashicorp/terraform-plugin-go/internal/logging github.com/hashicorp/terraform-plugin-go/tfprotov5 github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/fromproto @@ -245,7 +246,7 @@ github.com/hashicorp/terraform-plugin-log/internal/hclogutils github.com/hashicorp/terraform-plugin-log/internal/logging github.com/hashicorp/terraform-plugin-log/tflog github.com/hashicorp/terraform-plugin-log/tfsdklog -# github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0 +# github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 ## explicit github.com/hashicorp/terraform-plugin-sdk/v2/diag github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging @@ -379,7 +380,7 @@ google.golang.org/appengine/internal/modules google.golang.org/appengine/internal/remote_api # google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d google.golang.org/genproto/googleapis/rpc/status -# google.golang.org/grpc v1.45.0 +# google.golang.org/grpc v1.46.0 google.golang.org/grpc google.golang.org/grpc/attributes google.golang.org/grpc/backoff @@ -388,6 +389,7 @@ google.golang.org/grpc/balancer/base google.golang.org/grpc/balancer/grpclb/state google.golang.org/grpc/balancer/roundrobin google.golang.org/grpc/binarylog/grpc_binarylog_v1 +google.golang.org/grpc/channelz google.golang.org/grpc/codes google.golang.org/grpc/connectivity google.golang.org/grpc/credentials @@ -399,6 +401,7 @@ google.golang.org/grpc/health google.golang.org/grpc/health/grpc_health_v1 google.golang.org/grpc/internal google.golang.org/grpc/internal/backoff +google.golang.org/grpc/internal/balancer/gracefulswitch google.golang.org/grpc/internal/balancerload google.golang.org/grpc/internal/binarylog google.golang.org/grpc/internal/buffer @@ -410,6 +413,7 @@ google.golang.org/grpc/internal/grpcrand google.golang.org/grpc/internal/grpcsync google.golang.org/grpc/internal/grpcutil google.golang.org/grpc/internal/metadata +google.golang.org/grpc/internal/pretty google.golang.org/grpc/internal/resolver google.golang.org/grpc/internal/resolver/dns google.golang.org/grpc/internal/resolver/passthrough @@ -430,12 +434,14 @@ google.golang.org/grpc/stats google.golang.org/grpc/status google.golang.org/grpc/tap # google.golang.org/protobuf v1.28.0 +google.golang.org/protobuf/encoding/protojson google.golang.org/protobuf/encoding/prototext google.golang.org/protobuf/encoding/protowire google.golang.org/protobuf/internal/descfmt google.golang.org/protobuf/internal/descopts google.golang.org/protobuf/internal/detrand google.golang.org/protobuf/internal/encoding/defval +google.golang.org/protobuf/internal/encoding/json google.golang.org/protobuf/internal/encoding/messageset google.golang.org/protobuf/internal/encoding/tag google.golang.org/protobuf/internal/encoding/text diff --git a/skaff/README.md b/skaff/README.md index 16debd47eae..da594b5f0c1 100644 --- a/skaff/README.md +++ b/skaff/README.md @@ -11,3 +11,70 @@ To use `skaff`, starting in the `terraform-provider-aws` directory: 3. Go to the service where your new resource will reside. _E.g._, `cd ../internal/service/mq`. 4. To get help, enter `skaff` without arguments. 5. Generate a resource with helpful comments. _E.g._, `skaff resource --name BrokerReboot` (or equivalently `skaff resource -n BrokerReboot`). + +## Usage + +### Help +``` +$ skaff --help +Usage: + skaff [command] + +Available Commands: + completion Generate the autocompletion script for the specified shell + datasource Create scaffolding for a data source + help Help about any command + resource Create scaffolding for a resource + +Flags: + -h, --help help for skaff +``` + +### Autocompletion +Generate the autocompletion script for skaff for the specified shell +``` +$ skaff completion --help +Usage: + skaff completion [command] + +Available Commands: + bash Generate the autocompletion script for bash + fish Generate the autocompletion script for fish + powershell Generate the autocompletion script for powershell + zsh Generate the autocompletion script for zsh + +Flags: + -h, --help help for completion + +Use "skaff completion [command] --help" for more information about a command +``` + +### Data Source +Create scaffolding for a data source +``` +$ skaff datasource --help +Usage: + skaff datasource [flags] + +Flags: + -c, --clear-comments Do not include instructional comments in source + -f, --force Force creation, overwriting existing files + -h, --help help for datasource + -n, --name string Name of the entity + -s, --snakename string If skaff doesn't get it right, explicitly give name in snake case (e.g., db_vpc_instance) +``` + +### Resource +Create scaffolding for a resource +``` +$ skaff resource --help +Usage: + skaff resource [flags] + +Flags: + -c, --clear-comments Do not include instructional comments in source + -f, --force Force creation, overwriting existing files + -h, --help help for resource + -n, --name string Name of the entity + -s, --snakename string If skaff doesn't get it right, explicitly give name in snake case (e.g., db_vpc_instance) +``` \ No newline at end of file diff --git a/skaff/cmd/datasource.go b/skaff/cmd/datasource.go new file mode 100644 index 00000000000..03874a25161 --- /dev/null +++ b/skaff/cmd/datasource.go @@ -0,0 +1,22 @@ +package cmd + +import ( + "github.com/hashicorp/terraform-provider-aws/skaff/datasource" + "github.com/spf13/cobra" +) + +var datasourceCmd = &cobra.Command{ + Use: "datasource", + Short: "Create scaffolding for a data source", + RunE: func(cmd *cobra.Command, args []string) error { + return datasource.Create(name, snakeName, !clearComments, force) + }, +} + +func init() { + rootCmd.AddCommand(datasourceCmd) + datasourceCmd.Flags().StringVarP(&snakeName, "snakename", "s", "", "If skaff doesn't get it right, explicitly give name in snake case (e.g., db_vpc_instance)") + datasourceCmd.Flags().BoolVarP(&clearComments, "clear-comments", "c", false, "Do not include instructional comments in source") + datasourceCmd.Flags().StringVarP(&name, "name", "n", "", "Name of the entity") + datasourceCmd.Flags().BoolVarP(&force, "force", "f", false, "Force creation, overwriting existing files") +} diff --git a/skaff/cmd/root.go b/skaff/cmd/root.go index 0179446664c..b7082283d2e 100644 --- a/skaff/cmd/root.go +++ b/skaff/cmd/root.go @@ -7,7 +7,7 @@ import ( ) var rootCmd = &cobra.Command{ - Use: "skaff [resource]", + Use: "skaff [resource|datasource]", Short: "Create scaffolding for the Terraform AWS Provider", } diff --git a/skaff/datasource/datasource.go b/skaff/datasource/datasource.go new file mode 100644 index 00000000000..e41aa2464ef --- /dev/null +++ b/skaff/datasource/datasource.go @@ -0,0 +1,143 @@ +package datasource + +import ( + "bytes" + _ "embed" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "text/template" + + "github.com/hashicorp/terraform-provider-aws/names" +) + +//go:embed datasource.tmpl +var datasourceTmpl string + +//go:embed datasourcetest.tmpl +var datasourceTestTmpl string + +//go:embed websitedoc.tmpl +var websiteTmpl string + +type TemplateData struct { + DataSource string + DataSourceLower string + IncludeComments bool + ServicePackage string + Service string + ServiceLower string + AWSServiceName string +} + +func toSnakeCase(upper string, snakeName string) string { + if snakeName != "" { + return snakeName + } + + re := regexp.MustCompile(`([a-z])([A-Z]{2,})`) + upper = re.ReplaceAllString(upper, `${1}_${2}`) + + re2 := regexp.MustCompile(`([A-Z][a-z])`) + return strings.TrimPrefix(strings.ToLower(re2.ReplaceAllString(upper, `_$1`)), "_") +} + +func Create(dsName, snakeName string, comments, force bool) error { + wd, err := os.Getwd() // os.Getenv("GOPACKAGE") not available since this is not run with go generate + if err != nil { + return fmt.Errorf("error reading working directory: %s", err) + } + + servicePackage := filepath.Base(wd) + + if dsName == "" { + return fmt.Errorf("error checking: no name given") + } + + if dsName == strings.ToLower(dsName) { + return fmt.Errorf("error checking: name should be properly capitalized (e.g., DBInstance)") + } + + if snakeName != "" && snakeName != strings.ToLower(snakeName) { + return fmt.Errorf("error checking: snake name should be all lower case with underscores, if needed (e.g., db_instance)") + } + + s, err := names.ProviderNameUpper(servicePackage) + if err != nil { + return fmt.Errorf("error getting service connection name: %w", err) + } + + sn, err := names.FullHumanFriendly(servicePackage) + if err != nil { + return fmt.Errorf("error getting AWS service name: %w", err) + } + + templateData := TemplateData{ + DataSource: dsName, + DataSourceLower: strings.ToLower(dsName), + IncludeComments: comments, + ServicePackage: servicePackage, + Service: s, + ServiceLower: strings.ToLower(s), + AWSServiceName: sn, + } + + f := fmt.Sprintf("%s_data_source.go", toSnakeCase(dsName, snakeName)) + if err = writeTemplate("newds", f, datasourceTmpl, force, templateData); err != nil { + return fmt.Errorf("writing datasource template: %w", err) + } + + tf := fmt.Sprintf("%s_data_source_test.go", toSnakeCase(dsName, snakeName)) + if err = writeTemplate("dstest", tf, datasourceTestTmpl, force, templateData); err != nil { + return fmt.Errorf("writing datasource test template: %w", err) + } + + wf := fmt.Sprintf("%s_%s.html.markdown", servicePackage, toSnakeCase(dsName, snakeName)) + wf = filepath.Join("..", "..", "..", "website", "docs", "d", wf) + if err = writeTemplate("webdoc", wf, websiteTmpl, force, templateData); err != nil { + return fmt.Errorf("writing datasource website doc template: %w", err) + } + + return nil +} + +func writeTemplate(templateName, filename, tmpl string, force bool, td TemplateData) error { + if _, err := os.Stat(filename); !os.IsNotExist(err) && !force { + return fmt.Errorf("file (%s) already exists and force is not set", filename) + } + + f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) + if err != nil { + return fmt.Errorf("error opening file (%s): %s", filename, err) + } + + tplate, err := template.New(templateName).Parse(tmpl) + if err != nil { + return fmt.Errorf("error parsing template: %s", err) + } + + var buffer bytes.Buffer + err = tplate.Execute(&buffer, td) + if err != nil { + return fmt.Errorf("error executing template: %s", err) + } + + //contents, err := format.Source(buffer.Bytes()) + //if err != nil { + // return fmt.Errorf("error formatting generated file: %s", err) + //} + + //if _, err := f.Write(contents); err != nil { + if _, err := f.Write(buffer.Bytes()); err != nil { + f.Close() // ignore error; Write error takes precedence + return fmt.Errorf("error writing to file (%s): %s", filename, err) + } + + if err := f.Close(); err != nil { + return fmt.Errorf("error closing file (%s): %s", filename, err) + } + + return nil +} diff --git a/skaff/datasource/datasource.tmpl b/skaff/datasource/datasource.tmpl new file mode 100644 index 00000000000..b66e3011ea5 --- /dev/null +++ b/skaff/datasource/datasource.tmpl @@ -0,0 +1,214 @@ +package {{ .ServicePackage }} + +{{- if .IncludeComments }} +// **PLEASE DELETE THIS AND ALL TIP COMMENTS BEFORE SUBMITTING A PR FOR REVIEW!** +// +// TIP: ==== INTRODUCTION ==== +// Thank you for trying the skaff tool! +// +// You have opted to include these helpful comments. They all include "TIP:" +// to help you find and remove them when you're done with them. +// +// While some aspects of this file are customized to your input, the +// scaffold tool does *not* look at the AWS API and ensure it has correct +// function, structure, and variable names. It makes guesses based on +// commonalities. You will need to make significant adjustments. +// +// In other words, as generated, this is a rough outline of the work you will +// need to do. If something doesn't make sense for your situation, get rid of +// it. +// +// Remember to register this new data source in the provider +// (internal/provider/provider.go) once you finish. Otherwise, Terraform won't +// know about it.{{- end }} + +import ( +{{- if .IncludeComments }} + // TIP: ==== IMPORTS ==== + // This is a common set of imports but not customized to your code since + // your code hasn't been written yet. Make sure you, your IDE, or + // goimports -w fixes these imports. +{{- end }} + "context" + "errors" + "fmt" + "log" + "reflect" + "regexp" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/{{ .ServicePackage }}" + "github.com/aws/aws-sdk-go-v2/service/{{ .ServicePackage }}/types" {{- if .IncludeComments }} // TIP: Some v2 packages use a separate package for types while some do not.{{- end }} + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/flex" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/verify" +) +{{ if .IncludeComments }} +// TIP: ==== FILE STRUCTURE ==== +// All data sources should follow this basic outline. Improve this data source's +// maintainability by sticking to it. +// +// 1. Package declaration +// 2. Imports +// 3. Main data source function with schema +// 4. Create, read, update, delete functions (in that order) +// 5. Other functions (flatteners, expanders, waiters, finders, etc.) +{{- end }} +func DataSource{{ .DataSource }}() *schema.Resource { + return &schema.Resource{ + {{- if .IncludeComments }} + // TIP: ==== ASSIGN CRUD FUNCTIONS ==== + // Data sources only have a read function. + {{- end }} + ReadWithoutTimeout: dataSource{{ .DataSource }}Read, + {{ if .IncludeComments }} + // TIP: ==== SCHEMA ==== + // In the schema, add each of the arguments and attributes in snake + // case (e.g., delete_automated_backups). + // * Alphabetize arguments to make them easier to find. + // * Do not add a blank line between arguments/attributes. + // + // Users can configure argument values while attribute values cannot be + // configured and are used as output. Arguments have either: + // Required: true, + // Optional: true, + // + // All attributes will be computed and some arguments. If users will + // want to read updated information or detect drift for an argument, + // it should be computed: + // Computed: true, + // + // You will typically find arguments in the input struct + // (e.g., CreateDBInstanceInput) for the create operation. Sometimes + // they are only in the input struct (e.g., ModifyDBInstanceInput) for + // the modify operation. + // + // For more about schema options, visit + // https://pkg.go.dev/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema#Schema + {{- end }} + Schema: map[string]*schema.Schema{ + "arn": { {{- if .IncludeComments }} // TIP: Many, but not all, data sources have an `arn` attribute.{{- end }} + Type: schema.TypeString, + Computed: true, + }, + "replace_with_arguments": { {{- if .IncludeComments }} // TIP: Add all your arguments and attributes.{{- end }} + Type: schema.TypeString, + Optional: true, + }, + "complex_argument": { {{- if .IncludeComments }} // TIP: See setting, getting, flattening, expanding examples below for this complex argument.{{- end }} + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "sub_field_one": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 2048), + }, + "sub_field_two": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "tags": tftags.TagsSchemaComputed(), {{- if .IncludeComments }} // TIP: Many, but not all, data sources have `tags` attributes.{{- end }} + }, + + CustomizeDiff: verify.SetTagsDiff, + } +} + +func dataSource{{ .DataSource }}Read(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + {{- if .IncludeComments }} + // TIP: ==== RESOURCE READ ==== + // Generally, the Read function should do the following things. Make + // sure there is a good reason if you don't do one of these. + // + // 1. Get a client connection to the relevant service + // 2. Get information about a resource from AWS + // 3. Set the arguments and attributes + // 4. Set the tags + // 5. Return nil + {{- end }} + {{- if .IncludeComments }} + + // TIP: -- 1. Get a client connection to the relevant service + {{- end }} + conn := meta.(*conns.AWSClient).{{ .Service }}Conn + {{ if .IncludeComments }} + // TIP: -- 2. Get information about a resource from AWS using an API Get, + // List, or Describe-type function, or, better yet, using a finder. + {{- end }} + out, err := find{{ .DataSource }}ByID(ctx, conn, d.Id()) + {{ if .IncludeComments }} + // TIP: -- 3. Set the arguments and attributes + // + // For simple data types (i.e., schema.TypeString, schema.TypeBool, + // schema.TypeInt, and schema.TypeFloat), a simple Set call (e.g., + // d.Set("arn", out.Arn) is sufficient. No error or nil checking is + // necessary. + // + // However, there are some situations where more handling is needed. + // a. Complex data types (e.g., schema.TypeList, schema.TypeSet) + // b. Where errorneous diffs occur. For example, a schema.TypeString may be + // a JSON. AWS may return the JSON in a slightly different order but it + // is equivalent to what is already set. In that case, you may check if + // it is equivalent before setting the different JSON. + {{- end }} + d.Set("arn", out.Arn) + d.Set("name", out.Name) + {{ if .IncludeComments }} + // TIP: Setting a complex type. + // For more information, see: + // https://github.com/hashicorp/terraform-provider-aws/blob/main/docs/contributing/data-handling-and-conversion.md + // https://github.com/hashicorp/terraform-provider-aws/blob/main/docs/contributing/data-handling-and-conversion.md#flatten-functions-for-blocks + // https://github.com/hashicorp/terraform-provider-aws/blob/main/docs/contributing/data-handling-and-conversion.md#root-typeset-of-resource-and-aws-list-of-structure + {{- end }} + if err := d.Set("complex_argument", flattenComplexArguments(out.ComplexArguments)); err != nil { + return diag.Errorf("setting complex argument: %s", err) + } + {{ if .IncludeComments }} + // TIP: Setting a JSON string to avoid errorneous diffs. + {{- end }} + p, err := verify.SecondJSONUnlessEquivalent(d.Get("policy").(string), aws.ToString(out.Policy)) + if err != nil { + return diag.Errorf("while setting policy (%s), encountered: %s", p, err) + } + + p, err = structure.NormalizeJsonString(p) + if err != nil { + return diag.Errorf("policy (%s) is invalid JSON: %s", p, err) + } + + d.Set("policy", p) + {{ if .IncludeComments }} + // TIP: -- 4. Set the tags + // + // TIP: Not all data sources support tags and tags don't always make sense. If + // your data source doesn't need tags, you can remove the tags lines here and + // below. Many data sources do include tags so this a reminder to include them + // where possible. + {{- end }} + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + + //lintignore:AWSR002 + if err := d.Set("tags", KeyValueTags(out.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return diag.Errorf("listing tags for {{ .Service }} {{ .DataSource }} (%s): %s", d.Id(), err) + } + {{ if .IncludeComments }} + // TIP: -- 5. Return nil + {{- end }} + return nil +} diff --git a/skaff/datasource/datasource_test.go b/skaff/datasource/datasource_test.go new file mode 100644 index 00000000000..3f33cf86424 --- /dev/null +++ b/skaff/datasource/datasource_test.go @@ -0,0 +1,54 @@ +package datasource + +import ( + "testing" +) + +func TestToSnakeName(t *testing.T) { + testCases := []struct { + TestName string + Input string + Expected string + }{ + { + TestName: "empty", + Input: "", + Expected: "", + }, + { + TestName: "simple", + Input: "Cheese", + Expected: "cheese", + }, + { + TestName: "two word", + Input: "CityLights", + Expected: "city_lights", + }, + { + TestName: "three word", + Input: "OpenEndResource", + Expected: "open_end_resource", + }, + { + TestName: "initialism", + Input: "DBInstance", + Expected: "db_instance", + }, + { + TestName: "initialisms", + Input: "DBInstanceVPCEndpoint", + Expected: "db_instance_vpc_endpoint", + }, + } + + for _, testCase := range testCases { + t.Run(testCase.TestName, func(t *testing.T) { + got := toSnakeCase(testCase.Input, "") + + if got != testCase.Expected { + t.Errorf("got %s, expected %s", got, testCase.Expected) + } + }) + } +} diff --git a/skaff/datasource/datasourcetest.tmpl b/skaff/datasource/datasourcetest.tmpl new file mode 100644 index 00000000000..26e5ae72476 --- /dev/null +++ b/skaff/datasource/datasourcetest.tmpl @@ -0,0 +1,208 @@ +package {{ .ServicePackage }}_test + +{{- if .IncludeComments }} +// **PLEASE DELETE THIS AND ALL TIP COMMENTS BEFORE SUBMITTING A PR FOR REVIEW!** +// +// TIP: ==== INTRODUCTION ==== +// Thank you for trying the skaff tool! +// +// You have opted to include these helpful comments. They all include "TIP:" +// to help you find and remove them when you're done with them. +// +// While some aspects of this file are customized to your input, the +// scaffold tool does *not* look at the AWS API and ensure it has correct +// function, structure, and variable names. It makes guesses based on +// commonalities. You will need to make significant adjustments. +// +// In other words, as generated, this is a rough outline of the work you will +// need to do. If something doesn't make sense for your situation, get rid of +// it. +// +// Remember to register this new data source in the provider +// (internal/provider/provider.go) once you finish. Otherwise, Terraform won't +// know about it.{{- end }} + +import ( +{{- if .IncludeComments }} + // TIP: ==== IMPORT ==== + // This is a common set of imports but not customized to your code + // since your code hasn't been written yet. Make sure you, your IDE, or + // goimports -w fixes these imports. +{{- end }} + "fmt" + "regexp" + "strings" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/{{ .ServicePackage }}" + "github.com/aws/aws-sdk-go-v2/service/{{ .ServicePackage }}/types" {{- if .IncludeComments }} // TIP: Some v2 packages use a separate package for types while some do not.{{- end }} + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" +{{- if .IncludeComments }} + + // TIP: You will often need to import the package that this test file lives + // in. Since it is in the "test" context, it must import the package to use + // any normal context constants, variables, or functions. +{{- end }} + tf{{ .ServicePackage }} "github.com/hashicorp/terraform-provider-aws/internal/service/{{ .ServicePackage }}" +) +{{ if .IncludeComments }} +// TIP: File Structure. The basic outline for all test files should be as +// follows. Improve this data source's maintainability by following this +// outline. +// +// 1. Package declaration (add "_test" since this is a test file) +// 2. Imports +// 3. Unit tests +// 4. Basic test +// 5. Disappears test +// 6. All the other tests +// 7. Helper functions (exists, destroy, check, etc.) +// 8. Functions that return Terraform configurations +{{- end }} +{{ if .IncludeComments }} + +// TIP: ==== UNIT TESTS ==== +// This is an example of a unit test. Its name is not prefixed with +// "TestAcc" like an acceptance test. +// +// Unlike acceptance tests, unit tests do not access AWS and are focused on a +// function (or method). Because of this, they are quick and cheap to run. +// +// In designing a data source's implementation, isolate complex bits from AWS bits +// so that they can be tested through a unit test. We encourage more unit tests +// in the provider. +// +// Cut and dry functions using well-used patterns, like typical flatteners and +// expanders, don't need unit testing. However, if they are complex or +// intricate, they should be unit tested. +{{- end }} +func Test{{ .DataSource }}ExampleUnitTest(t *testing.T) { + testCases := []struct { + TestName string + Input string + Expected string + Error bool + }{ + { + TestName: "empty", + Input: "", + Expected: "", + Error: true, + }, + { + TestName: "descriptive name", + Input: "some input", + Expected: "some output", + Error: false, + }, + { + TestName: "another descriptive name", + Input: "more input", + Expected: "more output", + Error: false, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.TestName, func(t *testing.T) { + got, err := tf{{ .ServicePackage }}.FunctionFromDataSource(testCase.Input) + + if err != nil && !testCase.Error { + t.Errorf("got error (%s), expected no error", err) + } + + if err == nil && testCase.Error { + t.Errorf("got (%s) and no error, expected error", got) + } + + if got != testCase.Expected { + t.Errorf("got %s, expected %s", got, testCase.Expected) + } + }) + } +} +{{ if .IncludeComments }} + +// TIP: ==== ACCEPTANCE TESTS ==== +// This is an example of a basic acceptance test. This should test as much of +// standard functionality of the data source as possible, and test importing, if +// applicable. We prefix its name with "TestAcc", the service, and the +// data source name. +// +// Acceptance test access AWS and cost money to run. +{{- end }} +func TestAcc{{ .Service }}{{ .DataSource }}DataSource_basic(t *testing.T) { + {{- if .IncludeComments }} + // TIP: This is a long-running test guard for tests that run longer than + // 300s (5 min) generally. + {{- end }} + if testing.Short() { + t.Skip("skipping long-running test in short mode") + } + + var {{ .DataSourceLower }} {{ .ServicePackage }}.Describe{{ .DataSource }}Response + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + dataSourceName := "aws_{{ .ServicePackage }}_{{ .DataSourceLower }}.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + acctest.PreCheck(t) + acctest.PreCheckPartitionHasService({{ .ServicePackage }}.EndpointsID, t) + testAccPreCheck(t) + }, + ErrorCheck: acctest.ErrorCheck(t, {{ .ServicePackage }}.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheck{{ .DataSource }}Destroy, + Steps: []resource.TestStep{ + { + Config: testAcc{{ .DataSource }}DataSourceConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheck{{ .DataSource }}Exists(dataSourceName, &{{ .DataSourceLower }}), + resource.TestCheckResourceAttr(dataSourceName, "auto_minor_version_upgrade", "false"), + resource.TestCheckResourceAttrSet(dataSourceName, "maintenance_window_start_time.0.day_of_week"), + resource.TestCheckTypeSetElemNestedAttrs(dataSourceName, "user.*", map[string]string{ + "console_access": "false", + "groups.#": "0", + "username": "Test", + "password": "TestTest1234", + }), + acctest.MatchResourceAttrRegionalARN(dataSourceName, "arn", "{{ .ServicePackage }}", regexp.MustCompile(`{{ .DataSourceLower }}:+.`)), + ), + }, + }, + }) +} + +func testAcc{{ .DataSource }}DataSourceConfig_basic(rName, version string) string { + return fmt.Sprintf(` +data "aws_security_group" "test" { + name = %[1]q +} + +data "aws_{{ .ServicePackage }}_{{ .DataSourceLower }}" "test" { + {{ .DataSourceLower }}_name = %[1]q + engine_type = "Active{{ .Service }}" + engine_version = %[2]q + host_instance_type = "{{ .ServicePackage }}.t2.micro" + security_groups = [aws_security_group.test.id] + authentication_strategy = "simple" + storage_type = "efs" + + logs { + general = true + } + + user { + username = "Test" + password = "TestTest1234" + } +} +`, rName, version) +} diff --git a/skaff/datasource/websitedoc.tmpl b/skaff/datasource/websitedoc.tmpl new file mode 100644 index 00000000000..a8883b61bb2 --- /dev/null +++ b/skaff/datasource/websitedoc.tmpl @@ -0,0 +1,37 @@ +--- +subcategory: "{{ .Service }}" +layout: "aws" +page_title: "AWS: aws_{{ .ServicePackage }}_{{ .DataSourceLower }}" +description: |- + Terraform data source for managing an AWS {{ .Service }} {{ .DataSource }}. +--- + +# Data Source: aws_{{ .ServicePackage }}_{{ .DataSourceLower }} + +Terraform data source for managing an AWS {{ .Service }} {{ .DataSource }}. + +## Example Usage + +### Basic Usage + +```terraform +data "aws_{{ .ServicePackage }}_{{ .DataSourceLower }}" "example" { +} +``` + +## Argument Reference + +The following arguments are required: + +* `example_arg` - (Required) Concise argument description. + +The following arguments are optional: + +* `optional_arg` - (Optional) Concise argument description. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - ARN of the {{ .DataSource }}. +* `example_attribute` - Concise description. diff --git a/skaff/go.mod b/skaff/go.mod index 2077f27e9e4..efb69890605 100644 --- a/skaff/go.mod +++ b/skaff/go.mod @@ -4,12 +4,12 @@ go 1.17 require ( github.com/hashicorp/terraform-provider-aws v1.60.1-0.20220322001452-8f7a597d0c24 - github.com/spf13/cobra v1.4.0 + github.com/spf13/cobra v1.5.0 ) require ( github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect - github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0 // indirect + github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/spf13/pflag v1.0.5 // indirect golang.org/x/text v0.3.7 // indirect diff --git a/skaff/go.sum b/skaff/go.sum index 09f1e41a613..019a17908b8 100644 --- a/skaff/go.sum +++ b/skaff/go.sum @@ -18,20 +18,26 @@ github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkE github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/aws/aws-sdk-go v1.42.18/go.mod h1:585smgzpB/KqRA+K3y/NL/oYRqQvpNJYvLm+LY1U59Q= github.com/aws/aws-sdk-go v1.42.52/go.mod h1:OGr6lGMAKGlG9CVrYnWYDKIyb829c6EVBRjxqjmPepc= -github.com/aws/aws-sdk-go v1.44.10/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= +github.com/aws/aws-sdk-go v1.44.34/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= github.com/aws/aws-sdk-go-v2 v1.16.3/go.mod h1:ytwTPBG6fXTZLxxeeCCWj2/EMYp/xDUgX+OET6TLNNU= +github.com/aws/aws-sdk-go-v2 v1.16.5/go.mod h1:Wh7MEsmEApyL5hrWzpDkba4gwAPc5/piwLVLFnCxp48= github.com/aws/aws-sdk-go-v2/config v1.15.4/go.mod h1:ZijHHh0xd/A+ZY53az0qzC5tT46kt4JVCePf2NX9Lk4= github.com/aws/aws-sdk-go-v2/credentials v1.12.0/go.mod h1:9YWk7VW+eyKsoIL6/CljkTrNVWBSK9pkqOPUuijid4A= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.4/go.mod h1:u/s5/Z+ohUQOPXl00m2yJVyioWDECsbpXTQlaqSlufc= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.6/go.mod h1:ClLMcuQA/wcHPmOIfNzNI4Y1Q0oDbmEkbYhMFOzHDh8= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.10/go.mod h1:F+EZtuIwjlv35kRJPyBGcsA4f7bnSoz15zOQ2lJq1Z4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.12/go.mod h1:Afj/U8svX6sJ77Q+FPWMzabJ9QjbwP32YlopgKALUpg= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.4/go.mod h1:8glyUqVIM4AmeenIsPo0oVh3+NUwnsQml2OFupfQW+0= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.6/go.mod h1:FwpAKI+FBPIELJIdmQzlLtRe8LQSOreMcM2wBsPMvvc= github.com/aws/aws-sdk-go-v2/internal/ini v1.3.11/go.mod h1:0MR+sS1b/yxsfAPvAESrw8NfwUoxMinDyw6EYR9BS2U= github.com/aws/aws-sdk-go-v2/service/iam v1.18.4/go.mod h1:FpNvAfCZyIQ3qeNJUOw4CShKvdizHblXqAvSk0qmyL4= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.4/go.mod h1:uKkN7qmSIsNJVyMtxNQoCEYMvFEXbOg9fwCJPdfp2u8= -github.com/aws/aws-sdk-go-v2/service/route53domains v1.12.4/go.mod h1:EfCWWmp+qWzwBON1SeWld+iFizfk+J1Y7YMvrPbxZP0= +github.com/aws/aws-sdk-go-v2/service/kendra v1.28.1/go.mod h1:X65PE/R8p6R3G8z+7kiw4VIuiXGXqpFLTgucSouVAwQ= +github.com/aws/aws-sdk-go-v2/service/route53domains v1.12.6/go.mod h1:3jGaTlaOTt2+qVc7mUwRhEWiZQ2al+Rga4lINIloO7g= github.com/aws/aws-sdk-go-v2/service/sso v1.11.4/go.mod h1:cPDwJwsP4Kff9mldCXAmddjJL6JGQqtA3Mzer2zyr88= github.com/aws/aws-sdk-go-v2/service/sts v1.16.4/go.mod h1:lfSYenAXtavyX2A1LsViglqlG9eEFYxNryTZS5rn3QE= github.com/aws/smithy-go v1.11.2/go.mod h1:3xHYmszWVx2c0kIwQeEVf9uSm4fYZt67FBJnwub1bgM= +github.com/aws/smithy-go v1.11.3/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A= github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -40,10 +46,10 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= -github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -52,7 +58,7 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -96,7 +102,7 @@ github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/hashicorp/aws-cloudformation-resource-schema-sdk-go v0.16.0/go.mod h1:C6GVuO9RWOrt6QCGTmLCOYuSHpkfQSBDuRqTteOlo0g= +github.com/hashicorp/aws-cloudformation-resource-schema-sdk-go v0.17.0/go.mod h1:C6GVuO9RWOrt6QCGTmLCOYuSHpkfQSBDuRqTteOlo0g= github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.16/go.mod h1:xySJRdcDB8hVSmboo3X+evGhZPzBYwPmZbQxLgfGfBw= github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2 v2.0.0-beta.17/go.mod h1:MS242y2IOhTXoT0nhbJt/Z1p/6hlisZunHwvrWAcJyY= github.com/hashicorp/awspolicyequivalence v1.5.0/go.mod h1:9IOaIHx+a7C0NfUNk1A93M7kHd5rJ19aoUx37LZGC14= @@ -111,23 +117,24 @@ github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320/go.mod h1:EiZBM github.com/hashicorp/go-hclog v0.14.1/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v1.2.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-plugin v1.4.3/go.mod h1:5fGEH17QVwTTcR0zV7yhDPLLmFX9YSZ38b18Udy6vYQ= +github.com/hashicorp/go-plugin v1.4.4/go.mod h1:viDMjcLJuDui6pXb8U4HVfb8AamCWhHGUjr2IrTF67s= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.4.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.5.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/hc-install v0.3.1/go.mod h1:3LCdWcCDS1gaHC9mhHCGbkYfoY6vdsKohGjugbZdZak= github.com/hashicorp/hc-install v0.3.2/go.mod h1:xMG6Tr8Fw1WFjlxH0A9v61cW15pFwgEGqEz0V4jisHs= github.com/hashicorp/hcl/v2 v2.12.0/go.mod h1:FwWsfWEjyV/CMj8s/gqAuiviY72rJ1/oayI9WftqcKg= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/terraform-exec v0.16.1/go.mod h1:aj0lVshy8l+MHhFNoijNHtqTJQI3Xlowv5EOsEaGO7M= github.com/hashicorp/terraform-json v0.13.0/go.mod h1:y5OdLBCT+rxbwnpxZs9kGL7R9ExU76+cpdY8zHwoazk= -github.com/hashicorp/terraform-plugin-go v0.9.0/go.mod h1:EawBkgjBWNf7jiKnVoyDyF39OSV+u6KUX+Y73EPj3oM= -github.com/hashicorp/terraform-plugin-log v0.3.0/go.mod h1:EjueSP/HjlyFAsDqt+okpCPjkT4NDynAe32AeDC4vps= +github.com/hashicorp/terraform-json v0.14.0/go.mod h1:5A9HIWPkk4e5aeeXIBbkcOvaZbIYnAIkEyqP2pNSckM= +github.com/hashicorp/terraform-plugin-go v0.9.1/go.mod h1:ItjVSlQs70otlzcCwlPcU8FRXLdO973oYFRZwAOxy8M= github.com/hashicorp/terraform-plugin-log v0.4.0/go.mod h1:9KclxdunFownr4pIm1jdmwKRmE4d6HVG2c9XDq47rpg= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0 h1:9fjPgCenJqnbjo95SDcbJ+YdLyEC1N35cwKWcRWhJTQ= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.16.0/go.mod h1:hLa0sTiySU/AWEgV2GxJh0/pQIqcCmm30IPja9N9lTg= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 h1:Qr5fWNg1SPSfCRMtou67Y6Kcy9UnMYRNlIJTKRuUvXU= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0/go.mod h1:b+LFg8WpYgFgvEBP/6Htk5H9/pJp1V1E8NJAekfH2Ws= github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896/go.mod h1:bzBPnUIkI0RxauU8Dqo+2KrZZ28Cf48s8V6IHt3p4co= github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734/go.mod h1:kNDNcF7sN4DocDLBkQYz73HGKwN1ANB1blq4lIYLYvg= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= @@ -183,8 +190,8 @@ github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNX github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q= -github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= +github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU= +github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM= github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= @@ -240,6 +247,7 @@ golang.org/x/net v0.0.0-20191009170851-d66e71096ffb/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210326060303-6b1517762897/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k= @@ -270,7 +278,9 @@ golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -317,7 +327,7 @@ google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8 google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0/go.mod h1:DNq5QpG7LJqD2AamLZ7zvKE0DEpVl2BSEVjFycAAjRY= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= diff --git a/skaff/resource/resource.tmpl b/skaff/resource/resource.tmpl index 8e386942810..3fc299b5ba0 100644 --- a/skaff/resource/resource.tmpl +++ b/skaff/resource/resource.tmpl @@ -393,7 +393,7 @@ func resource{{ .Resource }}Update(ctx context.Context, d *schema.ResourceData, } if d.HasChanges("an_argument") { - in.AnArgument = d.Get("an_argument").(string) + in.AnArgument = aws.String(d.Get("an_argument").(string)) update = true } @@ -408,7 +408,7 @@ func resource{{ .Resource }}Update(ctx context.Context, d *schema.ResourceData, // TIP: -- 3. Call the AWS modify/update function {{- end }} log.Printf("[DEBUG] Updating {{ .Service }} {{ .Resource }} (%s): %#v", d.Id(), in) - out, err := conn.Update{{ .Resource }}(ctx, in) + out, err := conn.Update{{ .Resource }}WithContext(ctx, in) if err != nil { return diag.Errorf("updating {{ .Service }} {{ .Resource }} (%s): %s", d.Id(), err) } @@ -585,7 +585,7 @@ func status{{ .Resource }}(ctx context.Context, conn *{{ .ServiceLower }}.{{ .Se return nil, "", err } - return out, out.Status, nil + return out, aws.ToString(out.Status), nil } } {{ if .IncludeComments }} diff --git a/skaff/resource/resourcetest.tmpl b/skaff/resource/resourcetest.tmpl index 6e47249cca9..c6d79864758 100644 --- a/skaff/resource/resourcetest.tmpl +++ b/skaff/resource/resourcetest.tmpl @@ -162,7 +162,7 @@ func TestAcc{{ .Service }}{{ .Resource }}_basic(t *testing.T) { CheckDestroy: testAccCheck{{ .Resource }}Destroy, Steps: []resource.TestStep{ { - Config: testAcc{{ .Resource }}Config(rName), + Config: testAcc{{ .Resource }}Config_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheck{{ .Resource }}Exists(resourceName, &{{ .ResourceLower }}), resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), @@ -206,7 +206,7 @@ func TestAcc{{ .Service }}{{ .Resource }}_disappears(t *testing.T) { CheckDestroy: testAccCheck{{ .Resource }}Destroy, Steps: []resource.TestStep{ { - Config: testAcc{{ .Resource }}Config(rName, testAcc{{ .Resource }}VersionNewer), + Config: testAcc{{ .Resource }}Config_basic(rName, testAcc{{ .Resource }}VersionNewer), Check: resource.ComposeTestCheckFunc( testAccCheck{{ .Resource }}Exists(resourceName, &{{ .ResourceLower }}), acctest.CheckResourceDisappears(acctest.Provider, tf{{ .ServicePackage }}.Resource{{ .Resource }}(), resourceName), @@ -295,7 +295,7 @@ func testAccCheck{{ .Resource }}NotRecreated(before, after *{{ .ServicePackage } } } -func testAcc{{ .Resource }}Config(rName, version string) string { +func testAcc{{ .Resource }}Config_basic(rName, version string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q diff --git a/tools/go.mod b/tools/go.mod index 3c27e3125d2..8b203f7fce4 100644 --- a/tools/go.mod +++ b/tools/go.mod @@ -5,12 +5,12 @@ go 1.17 require ( github.com/bflad/tfproviderdocs v0.9.1 github.com/client9/misspell v0.3.4 - github.com/golangci/golangci-lint v1.46.1 + github.com/golangci/golangci-lint v1.46.2 github.com/hashicorp/go-changelog v0.0.0-20201005170154-56335215ce3a github.com/katbyte/terrafmt v0.4.0 github.com/pavius/impi v0.0.3 - github.com/rhysd/actionlint v1.6.12 - github.com/terraform-linters/tflint v0.36.2 + github.com/rhysd/actionlint v1.6.13 + github.com/terraform-linters/tflint v0.38.1 ) require ( @@ -106,13 +106,13 @@ require ( github.com/gostaticanalysis/nilerr v0.1.1 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect - github.com/hashicorp/go-getter v1.5.11 // indirect + github.com/hashicorp/go-getter v1.6.1 // indirect github.com/hashicorp/go-hclog v1.2.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hashicorp/go-plugin v1.4.3 // indirect + github.com/hashicorp/go-plugin v1.4.4 // indirect github.com/hashicorp/go-safetemp v1.0.0 // indirect github.com/hashicorp/go-uuid v1.0.3 // indirect - github.com/hashicorp/go-version v1.4.0 // indirect + github.com/hashicorp/go-version v1.5.0 // indirect github.com/hashicorp/hc-install v0.3.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/hashicorp/hcl/v2 v2.12.0 // indirect @@ -143,7 +143,7 @@ require ( github.com/ldez/gomoddirectives v0.2.3 // indirect github.com/ldez/tagliatelle v0.3.1 // indirect github.com/leonklingele/grouper v1.1.0 // indirect - github.com/lufeee/execinquery v1.2.0 // indirect + github.com/lufeee/execinquery v1.2.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/maratori/testpackage v1.0.1 // indirect github.com/matoous/godox v0.0.0-20210227103229-6504466cf951 // indirect @@ -173,7 +173,7 @@ require ( github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/polyfloyd/go-errorlint v0.0.0-20211125173453-6d6d39c5bb8b // indirect + github.com/polyfloyd/go-errorlint v1.0.0 // indirect github.com/posener/complete v1.2.3 // indirect github.com/prometheus/client_golang v1.12.1 // indirect github.com/prometheus/client_model v0.2.0 // indirect @@ -238,8 +238,8 @@ require ( golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect golang.org/x/net v0.0.0-20220412020605-290c469a71a5 // indirect golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5 // indirect - golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect - golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 // indirect + golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 // indirect + golang.org/x/sys v0.0.0-20220517195934-5e4e11fc645e // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.11-0.20220316014157-77aa08bb151a // indirect golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect @@ -251,7 +251,7 @@ require ( gopkg.in/ini.v1 v1.66.4 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect + gopkg.in/yaml.v3 v3.0.0-20220512140231-539c8e751b99 // indirect honnef.co/go/tools v0.3.1 // indirect mvdan.cc/gofumpt v0.3.1 // indirect mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed // indirect diff --git a/tools/go.sum b/tools/go.sum index c88119b6e64..f44d91793d1 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -31,6 +31,7 @@ cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aD cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW4= cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= +cloud.google.com/go v0.98.0/go.mod h1:ua6Ush4NALrHk5QXDWnjvZHN93OuF0HfuEPq9I1X0cM= cloud.google.com/go v0.99.0/go.mod h1:w0Xx2nLzqWJPuozYQX+hFfCSI8WioryfRDzkoI/Y2ZA= cloud.google.com/go v0.100.2 h1:t9Iw5QH5v4XtlEQaCtUY7x6sCABps8sW0acw7e2WQ6Y= cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w99A= @@ -46,6 +47,7 @@ cloud.google.com/go/compute v1.5.0 h1:b1zWmYuuHz7gO9kDcM/EpHGr06UgsYNRpNJzI2kFiL cloud.google.com/go/compute v1.5.0/go.mod h1:9SMHyhJlzhlkJqrPAc839t2BZFTSk6Jdj6mkzQJeu0M= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= cloud.google.com/go/firestore v1.6.1/go.mod h1:asNXNOzBdyVQmEU+ggO8UPodTkEVFW5Qx+rwHnAz+EY= cloud.google.com/go/iam v0.3.0 h1:exkAomrVUuzx9kWFI1wm3KI0uoDeUFPB4kKGzx6x+Gc= cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp4bnY= @@ -69,6 +71,7 @@ github.com/Antonboom/errname v0.1.6/go.mod h1:7lz79JAnuoMNDAWE9MeeIr1/c/VpSUWatB github.com/Antonboom/nilnil v0.1.1 h1:PHhrh5ANKFWRBh7TdYmyyq2gyT2lotnvFvvFbylF81Q= github.com/Antonboom/nilnil v0.1.1/go.mod h1:L1jBqoWM7AOeTD+tSquifKSesRHs4ZdaxvZR+xdJEaI= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I= github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= @@ -110,6 +113,8 @@ github.com/alexkohler/prealloc v1.0.0 h1:Hbq0/3fJPQhNkN0dR95AVrr6R7tou91y0uHG5pO github.com/alexkohler/prealloc v1.0.0/go.mod h1:VetnK3dIgFBBKmg0YnD9F9x6Icjd+9cvfHR56wJVlKE= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= +github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= +github.com/andybalholm/brotli v1.0.3/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q= @@ -120,7 +125,9 @@ github.com/apparentlymart/go-cidr v1.1.0/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/Y github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0 h1:MzVXffFUye+ZcSR6opIgz9Co7WcDx6ZcY+RjfFHoA0I= github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= +github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= +github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= github.com/apparentlymart/go-versions v1.0.1 h1:ECIpSn0adcYNsBfSRwdDdz9fWlL+S/6EUd9+irwkBgU= @@ -154,6 +161,7 @@ github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1U github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= github.com/bkielbasa/cyclop v1.2.0 h1:7Jmnh0yL2DjKfw28p86YTd/B4lRGcNuu12sKE35sM7A= github.com/bkielbasa/cyclop v1.2.0/go.mod h1:qOI0yy6A7dYC4Zgsa72Ppm9kONl0RoIlPbzot9mhmeI= github.com/blizzy78/varnamelen v0.8.0 h1:oqSblyuQvFsW1hbBHh1zfwrKe3kcSj0rnXkKzsQ089M= @@ -172,6 +180,8 @@ github.com/breml/errchkjson v0.3.0/go.mod h1:9Cogkyv9gcT8HREpzi3TiqBxCqDzo8awa92 github.com/butuzov/ireturn v0.1.1 h1:QvrO2QF2+/Cx1WA/vETCIYBKtRjc30vesdoPUNo1EbY= github.com/butuzov/ireturn v0.1.1/go.mod h1:Wh6Zl3IMtTpaIKbmwzqi6olnM9ptYQxxVacMsOEFPoc= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= @@ -197,12 +207,16 @@ github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211130200136-a8f946100490/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= +github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190620071333-e64a0ec8b42a/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= @@ -222,6 +236,7 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/denis-tingaikin/go-header v0.4.3 h1:tEaZKAlqql6SKCY++utLmkPLd6K8IBM20Ha7UVm+mtU= github.com/denis-tingaikin/go-header v0.4.3/go.mod h1:0wOCWuN71D5qIgE2nz9KrKmuYBAC2Mra5RassOIQ2/c= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg= @@ -234,9 +249,11 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.m github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.1/go.mod h1:AY7fTTXNdv/aJ2O5jwpxAPOWUZ7hQAEvzN5Pf27BkQQ= github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.0.14/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/envoyproxy/protoc-gen-validate v0.6.2/go.mod h1:2t7qjJNvHPx8IjnBOzl9E9/baC+qXE/TeeyBRzgJDws= github.com/esimonov/ifshort v1.0.4 h1:6SID4yGWfRae/M7hkVDVVyppy8q/v9OuxNdmjLQStBA= github.com/esimonov/ifshort v1.0.4/go.mod h1:Pe8zjlRrJ80+q2CxHLfEOfTwxCZ4O+MuhcHcfgNWTk0= github.com/ettle/strcase v0.1.1 h1:htFueZyVeE1XNnMEfbqp5r67qAN/4r6ya1ysq8Q+Zcw= @@ -252,6 +269,7 @@ github.com/firefart/nonamedreturns v1.0.1 h1:fSvcq6ZpK/uBAgJEGMvzErlzyM4NELLqqdT github.com/firefart/nonamedreturns v1.0.1/go.mod h1:D3dpIBojGGNh5UfElmwPu73SwDCm+VKhHYqwlNOk2uQ= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/frankban/quicktest v1.14.2 h1:SPb1KFFmM+ybpEjPUhCCkZOM5xlovT5UbrMvWnXyBns= +github.com/frankban/quicktest v1.14.2/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= @@ -290,6 +308,7 @@ github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vb github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-redis/redis v6.15.8+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= @@ -329,6 +348,7 @@ github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXP github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -372,8 +392,8 @@ github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe h1:6RGUuS7EGotKx6 github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe/go.mod h1:gjqyPShc/m8pEMpk0a3SeagVb0kaqvhscv+i9jI5ZhQ= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a h1:iR3fYXUjHCR97qWS8ch1y9zPNsgXThGwjKPrYfqMPks= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= -github.com/golangci/golangci-lint v1.46.1 h1:sc3XD0pprdZuqZkl6snUfnmUT1XW4dTTyLeOBvxn+3M= -github.com/golangci/golangci-lint v1.46.1/go.mod h1:wX6nN6s18dtWgm5Hjmes0sZKOxi+32KCI+OLVQCyhtM= +github.com/golangci/golangci-lint v1.46.2 h1:o90t/Xa6dhJbvy8Bz2RpzUXqrkigp19DLStMolTZbyo= +github.com/golangci/golangci-lint v1.46.2/go.mod h1:3DkdHnxn9eoTTrpT2gB0TEv8KSziuoqe9FitgQLHvAY= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 h1:MfyDlzVjl1hoaPzPD4Gpb/QgoRfSBR0jdhwGyAWwMSA= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0/go.mod h1:66R6K6P6VWk9I95jvqGxkqJxVWGFy9XlDwLwVz1RCFg= github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca h1:kNY3/svz5T29MYHubXix4aDDuE3RWHkPvopM/EDv/MA= @@ -403,6 +423,7 @@ github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY= github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= github.com/google/go-github/v35 v35.3.0 h1:fU+WBzuukn0VssbayTT+Zo3/ESKX9JYWjbZTLOTEyho= github.com/google/go-github/v35 v35.3.0/go.mod h1:yWB7uCcVWaUbUP74Aq3whuMySRMatyRmq5U9FTNlbio= @@ -448,19 +469,25 @@ github.com/googleapis/gax-go/v2 v2.2.0/go.mod h1:as02EH8zWkzwUoLbBaFeQ+arQaj/Oth github.com/googleapis/gax-go/v2 v2.3.0 h1:nRJtk3y8Fm770D42QV6T90ZnvFZyk7agSo3Q+Z9p3WI= github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99EXz9pXxye9YM= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/gookit/color v1.2.6/go.mod h1:AhIE+pS6D4Ql0SQWbBeXPHw7gY0/sjHoA4s/n1KB7xg= github.com/gookit/color v1.5.0 h1:1Opow3+BWDwqor78DcJkJCIwnkviFi+rrOANki9BUFw= github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gordonklaus/ineffassign v0.0.0-20200309095847-7953dde2c7bf/go.mod h1:cuNKsD1zp2v6XfE/orVX2QE1LC+i254ceGcVeDT3pTU= github.com/gordonklaus/ineffassign v0.0.0-20210914165742-4cc7213b9bc8 h1:PVRE9d4AQKmbelZ7emNig1+NT27DUmKZn5qXxfio54U= github.com/gordonklaus/ineffassign v0.0.0-20210914165742-4cc7213b9bc8/go.mod h1:Qcp2HIAYhR7mNUVSIxZww3Guk4it82ghYcEXIAk+QT0= github.com/gorhill/cronexpr v0.0.0-20180427100037-88b0669f7d75/go.mod h1:g2644b03hfBX9Ov0ZBDgXXens4rxSxmqFBbhvKv2yVA= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gostaticanalysis/analysisutil v0.0.0-20190318220348-4088753ea4d3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE= github.com/gostaticanalysis/analysisutil v0.0.3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE= github.com/gostaticanalysis/analysisutil v0.1.0/go.mod h1:dMhHRU9KTiDcuLGdy87/2gTR8WruwYZrKdRq9m1O6uw= +github.com/gostaticanalysis/analysisutil v0.4.1/go.mod h1:18U/DLpRgIUd459wGxVHE0fRgmo1UgHDcbw7F5idXu0= github.com/gostaticanalysis/analysisutil v0.7.1 h1:ZMCjoue3DtDWQ5WyU16YbjbQEQ3VuzwxALrpYd+HeKk= github.com/gostaticanalysis/analysisutil v0.7.1/go.mod h1:v21E3hY37WKMGSnbsw2S/ojApNWb6C1//mXO48CXbVc= github.com/gostaticanalysis/comment v1.3.0/go.mod h1:xMicKDx7XRXYdVwY9f9wQpDJVnqWxw9wCauCMKp+IBI= @@ -473,14 +500,20 @@ github.com/gostaticanalysis/nilerr v0.1.1 h1:ThE+hJP0fEp4zWLkWHWcRyI2Od0p7DlgYG3 github.com/gostaticanalysis/nilerr v0.1.1/go.mod h1:wZYb6YI5YAxxq0i1+VJbY0s2YONW0HU0GPE3+5PWN4A= github.com/gostaticanalysis/testutil v0.3.1-0.20210208050101-bfb5c8eec0e4/go.mod h1:D+FIZ+7OahH3ePw/izIEeH5I06eKs1IKI4Xr64/Am3M= github.com/gostaticanalysis/testutil v0.4.0 h1:nhdCmubdmDF6VEatUNjgUZBJKWRqugoISdUv3PPQgHY= +github.com/gostaticanalysis/testutil v0.4.0/go.mod h1:bLIoPefWXrRi/ssLFWX1dx7Repi5x3CuviD3dgAZaBU= github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.12.1/go.mod h1:8XEsbTttt/W+VvjtQhLACqCisSPWTxCZ7sBRjU6iH9c= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= +github.com/hashicorp/consul/api v1.11.0/go.mod h1:XjsvQN+RJGWI2TWy1/kqaE16HrR2J/FWgkYjdZQsX9M= github.com/hashicorp/consul/api v1.12.0/go.mod h1:6pVBMo0ebnYdt2S3H87XhekM/HHrUoTD2XXb/VrZVy0= +github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/consul/sdk v0.8.0/go.mod h1:GBvyrGALthsZObzUGsfgHZQDXjg4lOjagTIwIR1vPms= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= @@ -490,11 +523,12 @@ github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtng github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= -github.com/hashicorp/go-getter v1.5.11 h1:wioTuNmaBU3IE9vdFtFMcmZWj0QzLc6DYaP6sNe5onY= -github.com/hashicorp/go-getter v1.5.11/go.mod h1:9i48BP6wpWweI/0/+FBjqLrp9S8XtwUGjiu0QkWHEaY= +github.com/hashicorp/go-getter v1.6.1 h1:NASsgP4q6tL94WH6nJxKWj8As2H/2kop/bB1d8JMyRY= +github.com/hashicorp/go-getter v1.6.1/go.mod h1:IZCrswsZPeWv9IkVnLElzRU/gz/QPi6pZHn4tv6vbwA= github.com/hashicorp/go-hclog v0.10.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v0.14.1/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= +github.com/hashicorp/go-hclog v1.0.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v1.2.0 h1:La19f8d7WIlm4ogzNHB0JGqs5AUDAZ2UfCY4sJXcJdM= github.com/hashicorp/go-hclog v1.2.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= @@ -504,9 +538,11 @@ github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHh github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-plugin v1.4.3 h1:DXmvivbWD5qdiBts9TpBC7BYL1Aia5sxbRgQB+v6UZM= github.com/hashicorp/go-plugin v1.4.3/go.mod h1:5fGEH17QVwTTcR0zV7yhDPLLmFX9YSZ38b18Udy6vYQ= +github.com/hashicorp/go-plugin v1.4.4 h1:NVdrSdFRt3SkZtNckJ6tog7gbpRrcbOjQi/rgF7JYWQ= +github.com/hashicorp/go-plugin v1.4.4/go.mod h1:viDMjcLJuDui6pXb8U4HVfb8AamCWhHGUjr2IrTF67s= github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= +github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= @@ -520,21 +556,31 @@ github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09 github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.4.0 h1:aAQzgqIrRKRa7w75CKpbBxYsmUoPjzVm1W59ca1L0J4= github.com/hashicorp/go-version v1.4.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.5.0 h1:O293SZ2Eg+AAYijkVK3jR786Am1bhDEh2GHT0tIVE5E= +github.com/hashicorp/go-version v1.5.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/hc-install v0.3.1/go.mod h1:3LCdWcCDS1gaHC9mhHCGbkYfoY6vdsKohGjugbZdZak= github.com/hashicorp/hc-install v0.3.2 h1:oiQdJZvXmkNcRcEOOfM5n+VTsvNjWQeOjfAoO6dKSH8= github.com/hashicorp/hc-install v0.3.2/go.mod h1:xMG6Tr8Fw1WFjlxH0A9v61cW15pFwgEGqEz0V4jisHs= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/hcl/v2 v2.6.0/go.mod h1:bQTN5mpo+jewjJgh8jr0JUguIi7qPHUF6yIfAEN3jqY= github.com/hashicorp/hcl/v2 v2.12.0 h1:PsYxySWpMD4KPaoJLnsHwtK5Qptvj/4Q6s0t4sUxZf4= github.com/hashicorp/hcl/v2 v2.12.0/go.mod h1:FwWsfWEjyV/CMj8s/gqAuiviY72rJ1/oayI9WftqcKg= github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= +github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY= github.com/hashicorp/mdns v1.0.4/go.mod h1:mtBihi+LeNXGtG8L9dX59gAEa12BDtBQSp4v/YAJqrc= +github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/hashicorp/memberlist v0.2.2/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= github.com/hashicorp/memberlist v0.3.0/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= +github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/hashicorp/serf v0.9.5/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk= github.com/hashicorp/serf v0.9.6/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= github.com/hashicorp/terraform-exec v0.16.1 h1:NAwZFJW2L2SaCBVZoVaH8LPImLOGbPLkSHy0IYbs2uE= @@ -554,6 +600,7 @@ github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbc github.com/huandu/xstrings v1.2.0/go.mod h1:DvyZB1rfVYsBIigL8HwpZgxHwXozlTgGqn63UyNX5k4= github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= @@ -587,6 +634,7 @@ github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfC github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jonboulle/clockwork v0.2.0/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= +github.com/josharian/txtarfs v0.0.0-20210218200122-0702f000015a/go.mod h1:izVPOvVRsHiKkeGCT6tYBNWyDVuzj9wAaBb5R9qamfw= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -598,6 +646,7 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1 github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jstemmer/go-junit-report v1.0.0 h1:8X1gzZpR+nVQLAht+L/foqOeX2l9DTZoaIPbEQHxsds= github.com/jstemmer/go-junit-report v1.0.0/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/juju/ratelimit v1.0.1/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= @@ -615,6 +664,7 @@ github.com/kisielk/errcheck v1.6.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.11.2/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.13.5 h1:9O69jUPDcsT9fEm74W92rZL9FQY7rCdaXVneq+yyzl4= github.com/klauspost/compress v1.13.5/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -626,6 +676,7 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -650,9 +701,13 @@ github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.9.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/lufeee/execinquery v1.2.0 h1:07LBuxOFCLoNXUuwnRxL1T+ef8rI0gYZRBe2yh9BflU= -github.com/lufeee/execinquery v1.2.0/go.mod h1:EC7DrEKView09ocscGHC+apXMIaorh4xqSxS/dy8SbM= +github.com/lufeee/execinquery v1.2.1 h1:hf0Ems4SHcUGBxpGN7Jz78z1ppVkP/837ZlETPCEtOM= +github.com/lufeee/execinquery v1.2.1/go.mod h1:EC7DrEKView09ocscGHC+apXMIaorh4xqSxS/dy8SbM= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= +github.com/lyft/protoc-gen-star v0.5.3/go.mod h1:V0xaHgaf5oCCqmcxYcWiDfTiKsZsRc87/1qhoTACD8w= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/maratori/testpackage v1.0.1 h1:QtJ5ZjqapShm0w5DosRjg0PRlSdAdlx+W6cCKoALdbQ= @@ -691,6 +746,7 @@ github.com/mbilski/exhaustivestruct v1.2.0/go.mod h1:OeTBVxQWoEmB2J2JCHmXWPJ0aks github.com/mgechev/dots v0.0.0-20210922191527-e955255bf517/go.mod h1:KQ7+USdGKfpPjXk4Ga+5XxQM4Lm4e3gAogrreFAYpOg= github.com/mgechev/revive v1.2.1 h1:GjFml7ZsoR0IrQ2E2YIvWFNS5GPDV7xNwvA5GM1HZC4= github.com/mgechev/revive v1.2.1/go.mod h1:+Ro3wqY4vakcYNtkBWdZC7dBg1xSB6sp054wWwmeFm0= +github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= github.com/miekg/dns v1.1.35/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM= github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= @@ -706,6 +762,7 @@ github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HK github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg= github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= @@ -713,8 +770,11 @@ github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4= github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= +github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= @@ -750,6 +810,7 @@ github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/olekukonko/tablewriter v0.0.2/go.mod h1:rSAaSIOAGT9odnlyGlUfAJaoc5w2fSBUmeGDbRWPxyQ= @@ -782,6 +843,7 @@ github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144T github.com/pavius/impi v0.0.3 h1:DND6MzU+BLABhOZXbELR3FU8b+zDgcq4dOCNLhiTYuI= github.com/pavius/impi v0.0.3/go.mod h1:x/hU0bfdWIhuOT1SKwiJg++yvkk6EuOtJk8WtDZqgr8= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.8.0/go.mod h1:D6yutnOGMveHEPV7VQOuvI/gXY61bv+9bAOTRnLElKs= github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= @@ -796,16 +858,19 @@ github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/polyfloyd/go-errorlint v0.0.0-20211125173453-6d6d39c5bb8b h1:/BDyEJWLnDUYKGWdlNx/82qSaVu2bUok/EvPUtIGuvw= -github.com/polyfloyd/go-errorlint v0.0.0-20211125173453-6d6d39c5bb8b/go.mod h1:wi9BfjxjF/bwiZ701TzmfKu6UKC357IOAtNr0Td0Lvw= +github.com/polyfloyd/go-errorlint v1.0.0 h1:pDrQG0lrh68e602Wfp68BlUTRFoHn8PZYAjLgt2LFsM= +github.com/polyfloyd/go-errorlint v1.0.0/go.mod h1:KZy4xxPJyy88/gldCe5OdW6OQRtNO3EZE7hXzmnebgA= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/posener/complete v1.2.3 h1:NP0eAhjcjImqslEwo/1hq7gpajME0fTLTezBKDqfXqo= github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= +github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= @@ -817,6 +882,8 @@ github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1: github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= @@ -824,12 +891,14 @@ github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9 github.com/prometheus/common v0.32.1 h1:hWIdL3N2HoUx3B8j3YN9mWor0qhY/NlEKZEaXxuIRh4= github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= +github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/pseudomuto/protoc-gen-doc v1.3.2/go.mod h1:y5+P6n3iGrbKG+9O04V5ld71in3v/bX88wUwgt+U8EA= github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= github.com/quasilyte/go-ruleguard v0.3.1-0.20210203134552-1b5a410e1cc8/go.mod h1:KsAh3x0e7Fkpgs+Q9pNLS5XpFSvYCEVl5gP9Pp1xp30= @@ -837,6 +906,7 @@ github.com/quasilyte/go-ruleguard v0.3.16-0.20220213074421-6aa060fab41a h1:sWFav github.com/quasilyte/go-ruleguard v0.3.16-0.20220213074421-6aa060fab41a/go.mod h1:VMX+OnnSw4LicdiEGtRSD/1X8kW7GuEscjYNr4cOIT4= github.com/quasilyte/go-ruleguard/dsl v0.3.0/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= github.com/quasilyte/go-ruleguard/dsl v0.3.16/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= +github.com/quasilyte/go-ruleguard/dsl v0.3.19/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= github.com/quasilyte/go-ruleguard/rules v0.0.0-20201231183845-9e62ed36efe1/go.mod h1:7JTjp89EGyU1d6XfBiXihJNG37wB2VRkd125Q1u7Plc= github.com/quasilyte/go-ruleguard/rules v0.0.0-20211022131956-028d6511ab71/go.mod h1:4cgAphtvu7Ftv7vOT2ZOYhC6CvBxZixcasr8qIOTA50= github.com/quasilyte/gogrep v0.0.0-20220120141003-628d8b3623b5 h1:PDWGei+Rf2bBiuZIbZmM20J2ftEy9IeUCHA8HbQqed8= @@ -845,8 +915,11 @@ github.com/quasilyte/regex/syntax v0.0.0-20200407221936-30656e2c4a95 h1:L8QM9bvf github.com/quasilyte/regex/syntax v0.0.0-20200407221936-30656e2c4a95/go.mod h1:rlzQ04UMyJXu/aOvhd8qT+hvDrFpiwqp8MRXDY9szc0= github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 h1:M8mH9eK4OUR4lu7Gd+PU1fV2/qnDNfzT635KRSObncs= github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567/go.mod h1:DWNGW8A4Y+GyBgPuaQJuWiy0XYftx4Xm/y5Jqk9I6VQ= -github.com/rhysd/actionlint v1.6.12 h1:Qoa69UsvF/7tNc0008v7s1hHDANHuqaq0qHhu4syf7w= -github.com/rhysd/actionlint v1.6.12/go.mod h1:M+vAgTIFE2yOdr91fpDF4CUsyZVsPmS+D/x2K7qhhP0= +github.com/remyoudompheng/go-dbus v0.0.0-20121104212943-b7232d34b1d5/go.mod h1:+u151txRmLpwxBmpYn9z3d1sdJdjRPQpsXuYeY9jNls= +github.com/remyoudompheng/go-liblzma v0.0.0-20190506200333-81bf2d431b96/go.mod h1:90HvCY7+oHHUKkbeMCiHt1WuFR2/hPJ9QrljDG+v6ls= +github.com/remyoudompheng/go-misc v0.0.0-20190427085024-2d6ac652a50e/go.mod h1:80FQABjoFzZ2M5uEa6FUaJYEmqU2UOKojlFVak1UAwI= +github.com/rhysd/actionlint v1.6.13 h1:HAS71S4jLn3AGY7jbeLmTLH4NzHgOZWrZHuG3CqpCko= +github.com/rhysd/actionlint v1.6.13/go.mod h1:VGCfWzByAtSwcq+1sppJCaTemrVJlDcFRhIwuazDFyo= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ= @@ -854,6 +927,7 @@ github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfm github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= @@ -865,6 +939,7 @@ github.com/ryancurrah/gomodguard v1.2.3/go.mod h1:rYbA/4Tg5c54mV1sv4sQTP5WOPBcoL github.com/ryanrolds/sqlclosecheck v0.3.0 h1:AZx+Bixh8zdUBxUA1NxbxVAS78vTPq4rCb8OUZI9xFw= github.com/ryanrolds/sqlclosecheck v0.3.0/go.mod h1:1gREqxyTGR3lVtpngyFo3hZAgk0KCtEdgEkHwDbigdA= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sagikazarmark/crypt v0.3.0/go.mod h1:uD/D+6UF4SrIR1uGEv7bBNkNqLGqUr43MRiaGWX1Nig= github.com/sagikazarmark/crypt v0.5.0/go.mod h1:l+nzl7KWh51rpzp2h7t4MZWyiEWdhNpOAnclKvg+mdA= github.com/sanposhiho/wastedassign/v2 v2.0.6 h1:+6/hQIHKNJAUixEj6EmOngGIisyeI+T3335lYTyxRoA= github.com/sanposhiho/wastedassign/v2 v2.0.6/go.mod h1:KyZ0MWTwxxBmfwn33zh3k1dmsbF2ud9pAAGfoLfjhtI= @@ -878,6 +953,7 @@ github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c h1:W65qqJCIOVP4jpqPQ0YvHYKwcMEMVWIzWC5iNQQfBTU= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c/go.mod h1:/PevMnwAxekIXwN8qQyfc5gl2NlkB3CQlkizAbOkeBs= +github.com/shirou/gopsutil/v3 v3.22.4/go.mod h1:D01hZJ4pVHPpCTZ3m3T2+wDF2YAGfd+H4ifUguaQzHM= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= @@ -892,6 +968,8 @@ github.com/sivchari/containedctx v1.0.2 h1:0hLQKpgC53OVF1VT7CeoFHk9YKstur1XOgfYI github.com/sivchari/containedctx v1.0.2/go.mod h1:PwZOeqm4/DLoJOqMSIJs3aKqXRX4YO+uXww087KZ7Bw= github.com/sivchari/tenv v1.5.0 h1:wxW0mFpKI6DIb3s6m1jCDYvkWXCskrimXMuGd0K/kSQ= github.com/sivchari/tenv v1.5.0/go.mod h1:64yStXKSOxDfX47NlhVwND4dHwfZDdbp2Lyl018Icvg= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/sonatard/noctx v0.0.1 h1:VC1Qhl6Oxx9vvWo3UDgrGXYCeKCe3Wbw7qAWL6FrmTY= github.com/sonatard/noctx v0.0.1/go.mod h1:9D2D/EoULe8Yy2joDHJj7bv3sZoq9AaSb8B4lqBjiZI= @@ -903,13 +981,19 @@ github.com/sourcegraph/jsonrpc2 v0.1.0 h1:ohJHjZ+PcaLxDUjqk2NC3tIGsVa5bXThe1ZheS github.com/sourcegraph/jsonrpc2 v0.1.0/go.mod h1:ZafdZgk/axhT1cvZAPOhw+95nz2I/Ra5qMlU4gTRwIo= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/afero v1.3.3/go.mod h1:5KUK8ByomD5Ti5Artl0RtHeI5pTF7MIDuXL3yY520V4= +github.com/spf13/afero v1.4.1/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= +github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/afero v1.8.2 h1:xehSyVa0YnHWsJ49JFljMpg1HX19V6NDZ1fkm1Xznbo= github.com/spf13/afero v1.8.2/go.mod h1:CtAatgMJh6bJEIs48Ay/FOnkljP3WeGUG0MC1RfAqwo= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.4.1 h1:s0hze+J0196ZfEMTs80N7UlFt0BDuQ7Q+JDnHiMWKdA= github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= +github.com/spf13/cobra v1.3.0/go.mod h1:BrRVncBjOJa/eUcVVm9CE+oC6as8k+VYr4NY7WCi9V4= github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q= github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= @@ -921,6 +1005,9 @@ github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= +github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= +github.com/spf13/viper v1.10.0/go.mod h1:SoyBPwAtKDzypXNDFKN5kzH7ppppbGZtls1UpIy5AsM= github.com/spf13/viper v1.11.0 h1:7OX/1FS6n7jHD1zGrZTM7WtY13ZELRyosK4k93oPr44= github.com/spf13/viper v1.11.0/go.mod h1:djo0X/bA5+tYVoCn+C7cAYJGcVn/qYLFTG8gdUsX7Zk= github.com/ssgreg/nlreturn/v2 v2.2.1 h1:X4XDI7jstt3ySqGU86YGAURbxw3oTDPK9sPEi6YEwQ0= @@ -950,14 +1037,16 @@ github.com/tenntenn/modver v1.0.1 h1:2klLppGhDgzJrScMpkj9Ujy3rXPUspSjAcev9tSEBgA github.com/tenntenn/modver v1.0.1/go.mod h1:bePIyQPb7UeioSRkw3Q0XeMhYZSMx9B8ePqg6SAMGH0= github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3 h1:f+jULpRQGxTSkNYKJ51yaw6ChIqO+Je8UqsTKN/cDag= github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3/go.mod h1:ON8b8w4BN/kE1EOhwT0o+d62W65a6aPw1nouo9LMgyY= -github.com/terraform-linters/tflint v0.36.2 h1:bdKI62dD2HDsedELoZGCDMFCF5p4SldKoqqgO+AzIXY= -github.com/terraform-linters/tflint v0.36.2/go.mod h1:2KyH5s10WVu21TYskb+dcqQ4hcE6KAeDwKFx4i3X4M0= +github.com/terraform-linters/tflint v0.38.1 h1:7znLG2IkxYkFltneiDnhQ+XCM26Lq/hYq4liXFILhJU= +github.com/terraform-linters/tflint v0.38.1/go.mod h1:EtWGfrfo6/iUGF6pFj44cQlp+cRq6TVFazTIf05T1Bc= github.com/terraform-linters/tflint-plugin-sdk v0.11.0 h1:SXgx5GVTLuPolMLbhH7/U8YDp26vIrF7bFpDalyYk8g= github.com/terraform-linters/tflint-plugin-sdk v0.11.0/go.mod h1:51sL8jOhqlNwCCzd5K2s88HiHRYjL4Rf+qPcZ/cApdc= github.com/tetafro/godot v1.4.11 h1:BVoBIqAf/2QdbFmSwAWnaIqDivZdOV0ZRwEm6jivLKw= github.com/tetafro/godot v1.4.11/go.mod h1:LR3CJpxDVGlYOWn3ZZg1PgNZdTUvzsZWu8xaEohUpn8= github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144 h1:kl4KhGNsJIbDHS9/4U9yQo1UcPQM0kOMJHn29EoH/Ro= github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= +github.com/tklauser/go-sysconf v0.3.10/go.mod h1:C8XykCvCb+Gn0oNCWPIlcb0RuglQTYaQ2hGm7jmxEFk= +github.com/tklauser/numcpus v0.4.0/go.mod h1:1+UI3pD8NW14VMwdgJNJ1ESk2UnwhAnz5hMwiKKqXCQ= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20200427203606-3cfed13b9966/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= @@ -965,6 +1054,7 @@ github.com/tomarrell/wrapcheck/v2 v2.6.1 h1:Cf4a/iwuMp9s7kKrh74GTgijRVim0wEpKjgA github.com/tomarrell/wrapcheck/v2 v2.6.1/go.mod h1:Eo+Opt6pyMW1b6cNllOcDSSoHO0aTJ+iF6BfCUbHltA= github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce/go.mod h1:o8v6yHRoik09Xen7gje4m9ERNah1d1PPsVq1VEx9vE4= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= +github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/ulikunitz/xz v0.5.8 h1:ERv8V6GKqVi23rgu5cj9pVfVzJbOqAY2Ntl88O6c2nQ= github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= @@ -976,7 +1066,12 @@ github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijb github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/uudashr/gocognit v1.0.5 h1:rrSex7oHr3/pPLQ0xoWq108XMU8s678FJcQ+aSfOHa4= github.com/uudashr/gocognit v1.0.5/go.mod h1:wgYz0mitoKOTysqxTDMOUXg+Jb5SvtihkfmugIZYpEA= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.30.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= +github.com/valyala/quicktemplate v1.7.0/go.mod h1:sqKJnoaOF88V07vkO+9FL8fb9uZg/VPSJnLYn+LmLk8= +github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/viki-org/dnscache v0.0.0-20130720023526-c70c1f23c5d8/go.mod h1:dniwbG03GafCjFohMDmz6Zc6oCuiqgH6tGNyXTkHzXE= +github.com/vmihailenco/msgpack v3.3.3+incompatible h1:wapg9xDUZDzGCNFlwc5SqI1rvcciqcxEHac4CYj89xI= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack/v4 v4.3.12 h1:07s4sz9IReOgdikxLTKNbBdqDMLsjPKXwvCazn8G65U= github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= @@ -986,8 +1081,11 @@ github.com/xanzy/ssh-agent v0.2.1/go.mod h1:mLlQY/MoOhWBj+gOGMQkOeiEvkx+8pJSI+0B github.com/xanzy/ssh-agent v0.3.0 h1:wUMzuKtKilRgBAD1sUb8gOwwRr2FGoBVumcjoOACClI= github.com/xanzy/ssh-agent v0.3.0/go.mod h1:3s9xbODqPuuhK9JV1R321M/FlMZSBvE5aY6eAcqrDh0= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8= github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= @@ -1010,6 +1108,7 @@ github.com/yuin/goldmark v1.4.1 h1:/vn0k+RBvwlxEmP5E7SZMqNxPhfMVFEJiykr15/0XKM= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark-meta v0.0.0-20191126180153-f0638e958b60 h1:gZucqLjL1eDzVWrXj4uiWeMbAopJlBR2mKQAsTGdPwo= github.com/yuin/goldmark-meta v0.0.0-20191126180153-f0638e958b60/go.mod h1:i9VhcIHN2PxXMbQrKqXNueok6QNONoPjNMoj9MygVL0= +github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= github.com/zclconf/go-cty v1.0.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.1.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= @@ -1023,11 +1122,15 @@ github.com/zclconf/go-cty-yaml v1.0.2 h1:dNyg4QLTrv2IfJpm7Wtxi55ed5gLGOlPrZ6kMd5 github.com/zclconf/go-cty-yaml v1.0.2/go.mod h1:IP3Ylp0wQpYm50IHK8OZWKMu6sPJIUgKa8XhiVHura0= gitlab.com/bosi/decorder v0.2.1 h1:ehqZe8hI4w7O4b1vgsDZw1YU1PE7iJXrQWFMsocbQ1w= gitlab.com/bosi/decorder v0.2.1/go.mod h1:6C/nhLSbF6qZbYD8bRmISBwc6vcWdNsiIBkRvjJFrH0= +go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= go.etcd.io/etcd v0.0.0-20200513171258-e048e166ab9c/go.mod h1:xCI7ZzBfRuGgBXyXO6yfWfDmlWd35khcWpUa4L0xI/k= +go.etcd.io/etcd/api/v3 v3.5.1/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/api/v3 v3.5.2/go.mod h1:5GB2vv4A4AOn3yk7MftYGHkUfGtDHnEraIjym4dYz5A= +go.etcd.io/etcd/client/pkg/v3 v3.5.1/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/pkg/v3 v3.5.2/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= +go.etcd.io/etcd/client/v2 v2.305.1/go.mod h1:pMEacxZW7o8pg4CrFE7pquyCJJzZvkvdD2RibOCCCGs= go.etcd.io/etcd/client/v2 v2.305.2/go.mod h1:2D7ZejHVMIfog1221iLSYlQRzrtECw3kz4I4VAQm3qI= go.mozilla.org/mozlog v0.0.0-20170222151521-4bb13139d403/go.mod h1:jHoPAGnDrCy6kaI2tAze5Prf0Nr0w/oNkROt2lw3n3o= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= @@ -1053,12 +1156,14 @@ go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= golang.org/x/crypto v0.0.0-20180501155221-613d6eafa307/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -1067,10 +1172,13 @@ golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220313003712-b769efc7c000/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA= golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -1083,6 +1191,7 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5 h1:FR+oGxGfbQu1d+jglI3rCkjAjUnhRSZcUxr+DqlDLNo= golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e h1:qyrTQ++p1afMkO4DPEeLGq/3oTsdlvdH4vqZUBWzUKM= golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= @@ -1112,6 +1221,7 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= @@ -1120,7 +1230,9 @@ golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1128,6 +1240,7 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -1166,8 +1279,10 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= @@ -1208,12 +1323,14 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 h1:w8s32wxx3sY+OjLlv9qltkLU5yvJzxjjgiHWLjdIcw4= +golang.org/x/sync v0.0.0-20220513210516-0976fa681c29/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -1264,6 +1381,7 @@ golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1289,6 +1407,7 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1296,6 +1415,7 @@ golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211105183446-c75c47738b0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1303,10 +1423,15 @@ golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220403020550-483a9cbc67c0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220406163625-3f8b81556e12/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 h1:xHms4gcpe1YE7A3yIllJXP16CMAGuqwO2lX1mTyyRRc= golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220513210249-45d2b4557a2a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220517195934-5e4e11fc645e h1:w36l2Uw3dRan1K3TyXriXvY+6T56GNmlKGcqiQUJDfM= +golang.org/x/sys v0.0.0-20220517195934-5e4e11fc645e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= @@ -1332,6 +1457,7 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190228203856-589c23e65e65/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190307163923-6a08e3108db3/go.mod h1:25r3+/G6/xytQM8iWZKq3Hn0kr0rgFKPUNVEL/dr3z4= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190311215038-5c2858a9cfe5/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= @@ -1339,6 +1465,7 @@ golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190321232350-e250d351ecad/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190322203728-c1a832b0ad89/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= @@ -1355,6 +1482,7 @@ golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= @@ -1395,6 +1523,7 @@ golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200812195022-5ae4c3c160a0/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200817023811-d00afeaade8f/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200820010801-b793a1359eac/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200831203904-5a2aa26beb65/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= @@ -1402,6 +1531,7 @@ golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82u golang.org/x/tools v0.0.0-20201001104356-43ebab892c4c/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201002184944-ecd9fd270d5d/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201023174141-c8cfbd0f21e6/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201028025901-8cd080b735b3/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -1463,6 +1593,7 @@ google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqiv google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdrMgI= google.golang.org/api v0.59.0/go.mod h1:sT2boj7M9YJxZzgeZqXogmhfmRWDtPzT31xkieUbuZU= google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I= +google.golang.org/api v0.62.0/go.mod h1:dKmwPCydfsad4qCH08MSdgWjfHOyfpd4VtDGgRFdavw= google.golang.org/api v0.63.0/go.mod h1:gs4ij2ffTRXwuzzgJl/56BdwJaA194ijkfn++9tDuPo= google.golang.org/api v0.67.0/go.mod h1:ShHKP8E60yPsKNw/w8w+VYaj9H6buA5UqDp8dhbQZ6g= google.golang.org/api v0.70.0/go.mod h1:Bs4ZM2HGifEvXwd50TtW70ovgJffJYw2oRCOFU/SkfA= @@ -1545,6 +1676,8 @@ google.golang.org/genproto v0.0.0-20210924002016-3dee208752a0/go.mod h1:5CzLGKJ6 google.golang.org/genproto v0.0.0-20211008145708-270636b82663/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211028162531-8db9c33dc351/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211129164237-f09f9a12af12/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211203200212-54befc351ae9/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211221195035-429b39de9b1c/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= @@ -1560,6 +1693,7 @@ google.golang.org/genproto v0.0.0-20220407144326-9054f6ed7bac/go.mod h1:8w6bsBMX google.golang.org/grpc v1.8.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= @@ -1587,6 +1721,7 @@ google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnD google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= google.golang.org/grpc v1.40.1/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc v1.42.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= google.golang.org/grpc v1.44.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= google.golang.org/grpc v1.46.0 h1:oCjezcn6g6A75TGoKYBPgKmVBLexhYLM6MebdrPApP8= @@ -1620,6 +1755,9 @@ gopkg.in/cheggaaa/pb.v1 v1.0.28/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qS gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= +gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.57.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.66.4 h1:SsAcf+mM7mRZo2nJNGt8mZCjG8ZRaNGMURJw7BsIST4= gopkg.in/ini.v1 v1.66.4/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= @@ -1639,8 +1777,9 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20220512140231-539c8e751b99 h1:dbuHpmKjkDzSOMKAWl10QNlgaZUd3V1q99xc81tt2Kc= +gopkg.in/yaml.v3 v3.0.0-20220512140231-539c8e751b99/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/website/allowed-subcategories.txt b/website/allowed-subcategories.txt index fb2b7c06beb..336ee6e5233 100644 --- a/website/allowed-subcategories.txt +++ b/website/allowed-subcategories.txt @@ -105,6 +105,7 @@ ELB (Elastic Load Balancing) ELB Classic EMR EMR Containers +EMR Serverless ElastiCache Elastic Beanstalk Elastic Inference diff --git a/website/docs/d/ami.html.markdown b/website/docs/d/ami.html.markdown index 9b97dce044e..92576cc822c 100644 --- a/website/docs/d/ami.html.markdown +++ b/website/docs/d/ami.html.markdown @@ -119,6 +119,7 @@ interpolation. * `tags` - Any tags assigned to the image. * `tags.#.key` - The key name of the tag. * `tags.#.value` - The value of the tag. +* `tpm_support` - If the image is configured for NitroTPM support, the value is `v2.0`. * `virtualization_type` - The type of virtualization of the AMI (ie: `hvm` or `paravirtual`). * `usage_operation` - The operation of the Amazon EC2 instance and the billing code that is associated with the AMI. diff --git a/website/docs/d/cloudfront_response_headers_policy.html.markdown b/website/docs/d/cloudfront_response_headers_policy.html.markdown index a58b02c5ede..feef36c874e 100644 --- a/website/docs/d/cloudfront_response_headers_policy.html.markdown +++ b/website/docs/d/cloudfront_response_headers_policy.html.markdown @@ -34,6 +34,7 @@ In addition to all arguments above, the following attributes are exported: * `cors_config` - A configuration for a set of HTTP response headers that are used for Cross-Origin Resource Sharing (CORS). See [Cors Config](#cors-config) for more information. * `custom_headers_config` - Object that contains an attribute `items` that contains a list of Custom Headers See [Custom Header](#custom-header) for more information. * `security_headers_config` - A configuration for a set of security-related HTTP response headers. See [Security Headers Config](#security-headers-config) for more information. +* `server_timing_headers_config` - (Optional) A configuration for enabling the Server-Timing header in HTTP responses sent from CloudFront. See [Server Timing Headers Config](#server-timing-headers-config) for more information. ### Cors Config @@ -91,3 +92,8 @@ In addition to all arguments above, the following attributes are exported: * `override` - A Boolean value that determines whether CloudFront overrides the X-XSS-Protection HTTP response header received from the origin with the one specified in this response headers policy. * `protection` - A Boolean value that determines the value of the X-XSS-Protection HTTP response header. When this setting is true, the value of the X-XSS-Protection header is 1. When this setting is false, the value of the X-XSS-Protection header is 0. * `report_uri` - A Boolean value that determines whether CloudFront sets a reporting URI in the X-XSS-Protection header. + +### Server Timing Headers Config + +* `enabled` - A Boolean that determines whether CloudFront adds the `Server-Timing` header to HTTP responses that it sends in response to requests that match a cache behavior that's associated with this response headers policy. +* `sampling_rate` - A number 0–100 (inclusive) that specifies the percentage of responses that you want CloudFront to add the Server-Timing header to. diff --git a/website/docs/d/cloudwatch_log_groups.html.markdown b/website/docs/d/cloudwatch_log_groups.html.markdown index ab22d50a4b9..9a9e58cd82a 100644 --- a/website/docs/d/cloudwatch_log_groups.html.markdown +++ b/website/docs/d/cloudwatch_log_groups.html.markdown @@ -22,7 +22,7 @@ data "aws_cloudwatch_log_groups" "example" { The following arguments are supported: -* `log_group_name_prefix` - (Required) The group prefix of the Cloudwatch log groups to list +* `log_group_name_prefix` - (Optional) The group prefix of the Cloudwatch log groups to list ## Attributes Reference diff --git a/website/docs/d/ec2_host.html.markdown b/website/docs/d/ec2_host.html.markdown index fcd06fe5dd4..80fade1142c 100644 --- a/website/docs/d/ec2_host.html.markdown +++ b/website/docs/d/ec2_host.html.markdown @@ -63,6 +63,7 @@ In addition to the attributes above, the following attributes are exported: * `host_recovery` - Indicates whether host recovery is enabled or disabled for the Dedicated Host. * `instance_family` - The instance family supported by the Dedicated Host. For example, "m5". * `instance_type` - The instance type supported by the Dedicated Host. For example, "m5.large". If the host supports multiple instance types, no instanceType is returned. +* `outpost_arn` - The Amazon Resource Name (ARN) of the AWS Outpost on which the Dedicated Host is allocated. * `owner_id` - The ID of the AWS account that owns the Dedicated Host. * `sockets` - The number of sockets on the Dedicated Host. * `total_vcpus` - The total number of vCPUs on the Dedicated Host. diff --git a/website/docs/d/elasticache_user.html.markdown b/website/docs/d/elasticache_user.html.markdown index 6656de7579e..002d7e54a3c 100644 --- a/website/docs/d/elasticache_user.html.markdown +++ b/website/docs/d/elasticache_user.html.markdown @@ -6,7 +6,7 @@ description: |- Get information on an ElastiCache User resource. --- -# Data Source: aws_elasticache_replication_group +# Data Source: aws_elasticache_user Use this data source to get information about an Elasticache User. diff --git a/website/docs/d/iam_policy.html.markdown b/website/docs/d/iam_policy.html.markdown index e662ab2b009..6faf7248295 100644 --- a/website/docs/d/iam_policy.html.markdown +++ b/website/docs/d/iam_policy.html.markdown @@ -32,8 +32,12 @@ data "aws_iam_policy" "example" { ## Argument Reference * `arn` - (Optional) The ARN of the IAM policy. + Conflicts with `name` and `path_prefix`. * `name` - (Optional) The name of the IAM policy. -* `path_prefix` - (Optional) The prefix of the path to the IAM policy. Defaults to a slash (`/`). + Conflicts with `arn`. +* `path_prefix` - (Optional) The prefix of the path to the IAM policy. + Defaults to a slash (`/`). + Conflicts with `arn`. ## Attributes Reference diff --git a/website/docs/d/iam_policy_document.html.markdown b/website/docs/d/iam_policy_document.html.markdown index c4c5d29bbd8..eb796aba4c8 100644 --- a/website/docs/d/iam_policy_document.html.markdown +++ b/website/docs/d/iam_policy_document.html.markdown @@ -75,6 +75,71 @@ resource "aws_iam_policy" "example" { } ``` +### Example Multiple Condition Keys and Values + +You can specify a [condition with multiple keys and values](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_multi-value-conditions.html) by supplying multiple `condition` blocks with the same `test` value, but differing `variable` and `values` values. + +```terraform +data "aws_iam_policy_document" "example_multiple_condition_keys_and_values" { + statement { + actions = [ + "kms:Decrypt", + "kms:GenerateDataKey" + ] + + resources = ["*"] + + condition { + test = "ForAnyValue:StringEquals" + variable = "kms:EncryptionContext:service" + values = ["pi"] + } + + condition { + test = "ForAnyValue:StringEquals" + variable = "kms:EncryptionContext:aws:pi:service" + values = ["rds"] + } + + condition { + test = "ForAnyValue:StringEquals" + variable = "kms:EncryptionContext:aws:rds:db-id" + values = ["db-AAAAABBBBBCCCCCDDDDDEEEEE", "db-EEEEEDDDDDCCCCCBBBBBAAAAA"] + } + + } +} +``` + +`data.aws_iam_policy_document.example_multiple_condition_keys_and_values.json` will evaluate to: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Action": [ + "kms:GenerateDataKey", + "kms:Decrypt" + ], + "Resource": "*", + "Condition": { + "ForAnyValue:StringEquals": { + "kms:EncryptionContext:aws:pi:service": "rds", + "kms:EncryptionContext:aws:rds:db-id": [ + "db-AAAAABBBBBCCCCCDDDDDEEEEE", + "db-EEEEEDDDDDCCCCCBBBBBAAAAA" + ], + "kms:EncryptionContext:service": "pi" + } + } + } + ] +} +``` + ### Example Assume-Role Policy with Multiple Principals You can specify multiple principal blocks with different types. You can also use this data source to generate an assume-role policy. diff --git a/website/docs/d/instance.html.markdown b/website/docs/d/instance.html.markdown index 461b379dfe8..d505588c160 100644 --- a/website/docs/d/instance.html.markdown +++ b/website/docs/d/instance.html.markdown @@ -62,6 +62,8 @@ interpolation. * `arn` - The ARN of the instance. * `associate_public_ip_address` - Whether or not the Instance is associated with a public IP address or not (Boolean). * `availability_zone` - The availability zone of the Instance. +* `disable_api_stop` - Whether or not EC2 Instance Stop Protection](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html#Using_StopProtection) is enabled (Boolean). +* `disable_api_termination` - Whether or not [EC2 Instance Termination Protection](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#Using_ChangingDisableAPITermination) is enabled (Boolean). * `ebs_block_device` - The EBS block device mappings of the Instance. * `delete_on_termination` - If the EBS volume will be deleted on termination. * `device_name` - The physical name of the device. @@ -93,6 +95,10 @@ interpolation. * `private_dns` - The private DNS name assigned to the Instance. Can only be used inside the Amazon EC2, and only available if you've enabled DNS hostnames for your VPC. +* `private_dns_name_options` - The options for the instance hostname. + * `enable_resource_name_dns_aaaa_record` - Indicates whether to respond to DNS queries for instance hostnames with DNS AAAA records. + * `enable_resource_name_dns_a_record` - Indicates whether to respond to DNS queries for instance hostnames with DNS A records. + * `hostname_type` - The type of hostname for EC2 instances. * `private_ip` - The private IP address assigned to the Instance. * `secondary_private_ips` - The secondary private IPv4 addresses assigned to the instance's primary network interface (eth0) in a VPC. * `public_dns` - The public DNS name assigned to the Instance. For EC2-VPC, this diff --git a/website/docs/d/kendra_faq.html.markdown b/website/docs/d/kendra_faq.html.markdown new file mode 100644 index 00000000000..4750c657a43 --- /dev/null +++ b/website/docs/d/kendra_faq.html.markdown @@ -0,0 +1,50 @@ +--- +subcategory: "Kendra" +layout: "aws" +page_title: "AWS: aws_kendra_faq" +description: |- + Provides details about a specific Amazon Kendra Faq. +--- + +# Data Source: aws_kendra_faq + +Provides details about a specific Amazon Kendra Faq. + +## Example Usage + +```hcl +data "aws_kendra_faq" "test" { + faq_id = "87654321-1234-4321-4321-321987654321" + index_id = "12345678-1234-1234-1234-123456789123" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `faq_id` - (Required) The identifier of the FAQ. +* `index_id` - (Required) The identifier of the index that contains the FAQ. + +## Attributes Reference + +In addition to all of the arguments above, the following attributes are exported: + +* `arn` - The Amazon Resource Name (ARN) of the FAQ. +* `created_at` - The Unix datetime that the faq was created. +* `description` - The description of the FAQ. +* `error_message` - When the `status` field value is `FAILED`, this contains a message that explains why. +* `file_format` - The file format used by the input files for the FAQ. Valid Values are `CSV`, `CSV_WITH_HEADER`, `JSON`. +* `id` - The unique identifiers of the FAQ and index separated by a slash (`/`). +* `language_code` - The code for a language. This shows a supported language for the FAQ document. For more information on supported languages, including their codes, see [Adding documents in languages other than English](https://docs.aws.amazon.com/kendra/latest/dg/in-adding-languages.html). +* `name` - Specifies the name of the FAQ. +* `role_arn` - The Amazon Resource Name (ARN) of a role with permission to access the S3 bucket that contains the FAQs. For more information, see [IAM Roles for Amazon Kendra](https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html). +* `s3_path` - The S3 location of the FAQ input data. Detailed below. +* `status` - The status of the FAQ. It is ready to use when the status is ACTIVE. +* `updated_at` - The date and time that the FAQ was last updated. +* `tags` - Metadata that helps organize the FAQs you create. + +The `s3_path` configuration block supports the following attributes: + +* `bucket` - The name of the S3 bucket that contains the file. +* `key` - The name of the file. diff --git a/website/docs/d/kendra_index.html.markdown b/website/docs/d/kendra_index.html.markdown new file mode 100644 index 00000000000..6547d6e4b1d --- /dev/null +++ b/website/docs/d/kendra_index.html.markdown @@ -0,0 +1,118 @@ +--- +subcategory: "Kendra" +layout: "aws" +page_title: "AWS: aws_kendra_index" +description: |- + Provides details about a specific Amazon Kendra Index. +--- + +# Data Source: aws_kendra_index + +Provides details about a specific Amazon Kendra Index. + +## Example Usage + +```hcl +data "aws_kendra_index" "example" { + id = "12345678-1234-1234-1234-123456789123" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `id` - (Required) Returns information on a specific Index by id. + +## Attributes Reference + +In addition to all of the arguments above, the following attributes are exported: + +* `arn` - The Amazon Resource Name (ARN) of the Index. +* `capacity_units` - A block that sets the number of additional document storage and query capacity units that should be used by the index. Documented below. +* `created_at` - The Unix datetime that the index was created. +* `description` - The description of the Index. +* `document_metadata_configuration_updates` - One or more blocks that specify the configuration settings for any metadata applied to the documents in the index. Documented below. +* `edition` - The Amazon Kendra edition for the index. +* `error_message` - When the Status field value is `FAILED`, this contains a message that explains why. +* `id` - The identifier of the Index. +* `index_statistics` - A block that provides information about the number of FAQ questions and answers and the number of text documents indexed. Documented below. +* `name` - Specifies the name of the Index. +* `role_arn` - An AWS Identity and Access Management (IAM) role that gives Amazon Kendra permissions to access your Amazon CloudWatch logs and metrics. This is also the role you use when you call the `BatchPutDocument` API to index documents from an Amazon S3 bucket. +* `server_side_encryption_configuration` - A block that specifies the identifier of the AWS KMS customer managed key (CMK) that's used to encrypt data indexed by Amazon Kendra. Amazon Kendra doesn't support asymmetric CMKs. Documented below. +* `status` - The current status of the index. When the value is `ACTIVE`, the index is ready for use. If the Status field value is `FAILED`, the `error_message` field contains a message that explains why. +* `updated_at` - The Unix datetime that the index was last updated. +* `user_context_policy` - The user context policy. Valid values are `ATTRIBUTE_FILTER` or `USER_TOKEN`. For more information, refer to [UserContextPolicy](https://docs.aws.amazon.com/kendra/latest/dg/API_CreateIndex. +html#Kendra-CreateIndex-request-UserContextPolicy). +* `user_group_resolution_configuration` - A block that enables fetching access levels of groups and users from an AWS Single Sign-On identity source. Documented below. +* `user_token_configurations` - A block that specifies the user token configuration. Documented below. +* `tags` - Metadata that helps organize the Indices you create. + +A `capacity_units` block supports the following attributes: + +* `query_capacity_units` - The amount of extra query capacity for an index and GetQuerySuggestions capacity. For more information, refer to [QueryCapacityUnits](https://docs.aws.amazon.com/kendra/latest/dg/API_CapacityUnitsConfiguration.html#Kendra-Type-CapacityUnitsConfiguration-QueryCapacityUnits). +* `storage_capacity_units` - The amount of extra storage capacity for an index. A single capacity unit provides 30 GB of storage space or 100,000 documents, whichever is reached first. Minimum value of 0. + +A `document_metadata_configuration_updates` block supports the following attributes: + +* `name` - The name of the index field. Minimum length of 1. Maximum length of 30. +* `relevance` - A block that provides manual tuning parameters to determine how the field affects the search results. Documented below. +* `search` - A block that provides information about how the field is used during a search. Documented below. +* `type` - The data type of the index field. Valid values are `STRING_VALUE`, `STRING_LIST_VALUE`, `LONG_VALUE`, `DATE_VALUE`. + +A `relevance` block supports the following attributes: + +* `duration` - Specifies the time period that the boost applies to. For more information, refer to [Duration](https://docs.aws.amazon.com/kendra/latest/dg/API_Relevance.html#Kendra-Type-Relevance-Duration). +* `freshness` - Indicates that this field determines how "fresh" a document is. For more information, refer to [Freshness](https://docs.aws.amazon.com/kendra/latest/dg/API_Relevance.html#Kendra-Type-Relevance-Freshness). +* `importance` - The relative importance of the field in the search. Larger numbers provide more of a boost than smaller numbers. Minimum value of 1. Maximum value of 10. +* `rank_order` - Determines how values should be interpreted. For more information, refer to [RankOrder](https://docs.aws.amazon.com/kendra/latest/dg/API_Relevance.html#Kendra-Type-Relevance-RankOrder). +* `values_importance_map` - A list of values that should be given a different boost when they appear in the result list. For more information, refer to [ValueImportanceMap](https://docs.aws.amazon.com/kendra/latest/dg/API_Relevance.html#Kendra-Type-Relevance-ValueImportanceMap). + +A `search` block supports the following attributes: + +* `displayable` - Determines whether the field is returned in the query response. The default is `true`. +* `facetable` - Indicates that the field can be used to create search facets, a count of results for each value in the field. The default is `false`. +* `searchable` - Determines whether the field is used in the search. If the Searchable field is true, you can use relevance tuning to manually tune how Amazon Kendra weights the field in the search. The default is `true` for `string` fields and `false` for `number` and `date` fields. +* `sortable` - Determines whether the field can be used to sort the results of a query. If you specify sorting on a field that does not have Sortable set to true, Amazon Kendra returns an exception. The default is `false`. + +A `index_statistics` block supports the following attributes: + +* `faq_statistics` - A block that specifies the number of question and answer topics in the index. Documented below. +* `text_document_statistics` - A block that specifies the number of text documents indexed. + +A `faq_statistics` block supports the following attributes: + +* `indexed_question_answers_count` - The total number of FAQ questions and answers contained in the index. + +A `text_document_statistics` block supports the following attributes: + +* `indexed_text_bytes` - The total size, in bytes, of the indexed documents. +* `indexed_text_documents_count` - The number of text documents indexed. + +A `server_side_encryption_configuration` block supports the following attributes: + +* `kms_key_id` - The identifier of the AWS KMScustomer master key (CMK). Amazon Kendra doesn't support asymmetric CMKs. + +A `user_group_resolution_configuration` block supports the following attributes: + +* `user_group_resolution_mode` - The identity store provider (mode) you want to use to fetch access levels of groups and users. AWS Single Sign-On is currently the only available mode. Your users and groups must exist in an AWS SSO identity source in order to use this mode. Valid Values are `AWS_SSO` or `NONE`. + +A `user_token_configurations` block supports the following attributes: + +* `json_token_type_configuration` - A block that specifies the information about the JSON token type configuration. +* `jwt_token_type_configuration` - A block that specifies the information about the JWT token type configuration. + +A `json_token_type_configuration` block supports the following attributes: + +* `group_attribute_field` - The group attribute field. +* `user_name_attribute_field` - The user name attribute field. + +A `jwt_token_type_configuration` block supports the following attributes: + +* `claim_regex` - The regular expression that identifies the claim. +* `group_attribute_field` - The group attribute field. +* `issuer` - The issuer of the token. +* `key_location` - The location of the key. Valid values are `URL` or `SECRET_MANAGER` +* `secrets_manager_arn` - The Amazon Resource Name (ARN) of the secret. +* `url` - The signing key URL. +* `user_name_attribute_field` - The user name attribute field. diff --git a/website/docs/d/lakeformation_permissions.html.markdown b/website/docs/d/lakeformation_permissions.html.markdown index 017c062039b..37d77fa47c5 100644 --- a/website/docs/d/lakeformation_permissions.html.markdown +++ b/website/docs/d/lakeformation_permissions.html.markdown @@ -8,7 +8,7 @@ description: |- # Data Source: aws_lakeformation_permissions -Get permissions for a principal to access metadata in the Data Catalog and data organized in underlying data storage such as Amazon S3. Permissions are granted to a principal, in a Data Catalog, relative to a Lake Formation resource, which includes the Data Catalog, databases, and tables. For more information, see [Security and Access Control to Metadata and Data in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/security-data-access.html). +Get permissions for a principal to access metadata in the Data Catalog and data organized in underlying data storage such as Amazon S3. Permissions are granted to a principal, in a Data Catalog, relative to a Lake Formation resource, which includes the Data Catalog, databases, tables, LF-tags, and LF-tag policies. For more information, see [Security and Access Control to Metadata and Data in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/security-data-access.html). ~> **NOTE:** This data source deals with explicitly granted permissions. Lake Formation grants implicit permissions to data lake administrators, database creators, and table creators. For more information, see [Implicit Lake Formation Permissions](https://docs.aws.amazon.com/lake-formation/latest/dg/implicit-permissions.html). @@ -39,6 +39,25 @@ data "aws_lakeformation_permissions" "test" { } ``` +### Permissions For Tag-Based Access Control + +```terraform +data "aws_lakeformation_permissions" "test" { + principal = aws_iam_role.workflow_role.arn + lf_tag_policy { + resource_type = "DATABASE" + expression { + key = "Team" + values = ["Sales"] + } + expression { + key = "Environment" + values = ["Dev", "Production"] + } + } +} +``` + ## Argument Reference The following arguments are required: @@ -50,6 +69,8 @@ One of the following is required: * `catalog_resource` - Whether the permissions are to be granted for the Data Catalog. Defaults to `false`. * `data_location` - Configuration block for a data location resource. Detailed below. * `database` - Configuration block for a database resource. Detailed below. +* `lf_tag` - (Optional) Configuration block for an LF-tag resource. Detailed below. +* `lf_tag_policy` - (Optional) Configuration block for an LF-tag policy resource. Detailed below. * `table` - Configuration block for a table resource. Detailed below. * `table_with_columns` - Configuration block for a table with columns resource. Detailed below. @@ -77,6 +98,33 @@ The following argument is optional: * `catalog_id` - (Optional) Identifier for the Data Catalog. By default, it is the account ID of the caller. +### lf_tag + +The following arguments are required: + +* `key` – (Required) The key-name for the tag. +* `values` - (Required) A list of possible values an attribute can take. + +The following argument is optional: + +* `catalog_id` - (Optional) Identifier for the Data Catalog. By default, it is the account ID of the caller. + +### lf_tag_policy + +The following arguments are required: + +* `resource_type` – (Required) The resource type for which the tag policy applies. Valid values are `DATABASE` and `TABLE`. +* `expression` - (Required) A list of tag conditions that apply to the resource's tag policy. Configuration block for tag conditions that apply to the policy. See [`expression`](#expression) below. + +The following argument is optional: + +* `catalog_id` - (Optional) Identifier for the Data Catalog. By default, it is the account ID of the caller. + +#### expression + +* `key` – (Required) The key-name of an LF-Tag. +* `values` - (Required) A list of possible values of an LF-Tag. + ### table The following argument is required: diff --git a/website/docs/d/location_place_index.html.markdown b/website/docs/d/location_place_index.html.markdown new file mode 100644 index 00000000000..f6011ae6f5c --- /dev/null +++ b/website/docs/d/location_place_index.html.markdown @@ -0,0 +1,33 @@ +--- +subcategory: "Location" +layout: "aws" +page_title: "AWS: aws_location_place_index" +description: |- + Retrieve information about a Location Service Place Index. +--- + +# Data Source: aws_location_place_index + +Retrieve information about a Location Service Place Index. + +## Example Usage + +```terraform +data "aws_location_place_index" "example" { + index_name = "example" +} +``` + +## Argument Reference + +* `index_name` - (Required) The name of the place index resource. + +## Attribute Reference + +* `create_time` - The timestamp for when the place index resource was created in ISO 8601 format. +* `data_source` - The data provider of geospatial data. +* `data_source_configuration` - List of configurations that specify data storage option for requesting Places. +* `description` - The optional description for the place index resource. +* `index_arn` - The Amazon Resource Name (ARN) for the place index resource. +* `tags` - Key-value map of resource tags for the map. +* `update_time` - The timestamp for when the place index resource was last update in ISO 8601. diff --git a/website/docs/d/outposts_asset.html.markdown b/website/docs/d/outposts_asset.html.markdown new file mode 100644 index 00000000000..0c0d2ae9b10 --- /dev/null +++ b/website/docs/d/outposts_asset.html.markdown @@ -0,0 +1,41 @@ +--- +subcategory: "Outposts" +layout: "aws" +page_title: "AWS: aws_outposts_asset" +description: |- + Information about hardware assets in an Outpost. +--- + +# Data Source: aws_outposts_asset + +Information about a specific hardware asset in an Outpost. + +## Example Usage + +```terraform +data "aws_outposts_assets" "example" { + arn = data.aws_outposts_outpost.example.arn +} + +data "aws_outposts_asset" "example" { + count = length(data.aws_outposts_assets.example.asset_ids) + arn = data.aws_outposts_outpost.example.arn + asset_id = element(data.aws_outposts_assets.this.asset_ids, count.index) +} + +``` + +## Argument Reference + +The following arguments are required: + +* `arn` - (Required) Outpost ARN. +* `asset_id` - (Required) The ID of the asset. + +## Attribute Reference + +In addition to all arguments above, the following attributes are exported: + +* `asset_type` - The type of the asset. +* `host_id` - The host ID of the Dedicated Hosts on the asset, if a Dedicated Host is provisioned. +* `rack_id` - The rack ID of the asset. diff --git a/website/docs/d/outposts_assets.html.markdown b/website/docs/d/outposts_assets.html.markdown new file mode 100644 index 00000000000..8b35f7809a0 --- /dev/null +++ b/website/docs/d/outposts_assets.html.markdown @@ -0,0 +1,32 @@ +--- +subcategory: "Outposts" +layout: "aws" +page_title: "AWS: aws_outposts_assets" +description: |- + Information about hardware assets in an Outpost. +--- + +# Data Source: aws_outposts_assets + +Information about hardware assets in an Outpost. + +## Example Usage + +```terraform +data "aws_outposts_assets" "example" { + arn = data.aws_outposts_outpost.example.arn +} + +``` + +## Argument Reference + +The following arguments are required: + +* `arn` - (Required) Outpost ARN. + +## Attribute Reference + +In addition to all arguments above, the following attributes are exported: + +* `asset_ids` - A list of all the subnet ids found. This data source will fail if none are found. diff --git a/website/docs/d/ram_resource_share.html.markdown b/website/docs/d/ram_resource_share.html.markdown index d33188aa755..f91e4a6850e 100644 --- a/website/docs/d/ram_resource_share.html.markdown +++ b/website/docs/d/ram_resource_share.html.markdown @@ -38,8 +38,9 @@ data "aws_ram_resource_share" "tag_filter" { The following Arguments are supported * `name` - (Required) The name of the resource share to retrieve. -* `resource_owner` (Required) The owner of the resource share. Valid values are SELF or OTHER-ACCOUNTS +* `resource_owner` (Required) The owner of the resource share. Valid values are `SELF` or `OTHER-ACCOUNTS`. +* `resource_share_status` (Optional) Specifies that you want to retrieve details of only those resource shares that have this status. Valid values are `PENDING`, `ACTIVE`, `FAILED`, `DELETING`, and `DELETED`. * `filter` - (Optional) A filter used to scope the list e.g., by tags. See [related docs] (https://docs.aws.amazon.com/ram/latest/APIReference/API_TagFilter.html). * `name` - (Required) The name of the tag key to filter on. * `values` - (Required) The value of the tag key. diff --git a/website/docs/d/redshift_cluster.html.markdown b/website/docs/d/redshift_cluster.html.markdown index ffd98b3de54..2fab74d4feb 100644 --- a/website/docs/d/redshift_cluster.html.markdown +++ b/website/docs/d/redshift_cluster.html.markdown @@ -51,12 +51,15 @@ The following arguments are supported: In addition to all arguments above, the following attributes are exported: +* `arn` - Amazon Resource Name (ARN) of cluster. * `allow_version_upgrade` - Whether major version upgrades can be applied during maintenance period * `automated_snapshot_retention_period` - The backup retention period +* `aqua_configuration_status` - The value represents how the cluster is configured to use AQUA. * `availability_zone` - The availability zone of the cluster * `availability_zone_relocation_enabled` - Indicates whether the cluster is able to be relocated to another availability zone. * `bucket_name` - The name of the S3 bucket where the log files are to be stored * `cluster_identifier` - The cluster identifier +* `cluster_nodes` - The nodes in the cluster. Cluster node blocks are documented below * `cluster_parameter_group_name` - The name of the parameter group to be associated with this cluster * `cluster_public_key` - The public key for the cluster * `cluster_revision_number` - The cluster revision number @@ -64,6 +67,7 @@ In addition to all arguments above, the following attributes are exported: * `cluster_subnet_group_name` - The name of a cluster subnet group to be associated with this cluster * `cluster_type` - The cluster type * `database_name` - The name of the default database in the cluster +* `default_iam_role_arn` - ∂The Amazon Resource Name (ARN) for the IAM role that was set as default for the cluster when the cluster was created. * `elastic_ip` - The Elastic IP of the cluster * `enable_logging` - Whether cluster logging is enabled * `encrypted` - Whether the cluster data is encrypted @@ -74,10 +78,20 @@ In addition to all arguments above, the following attributes are exported: * `master_username` - Username for the master DB user * `node_type` - The cluster node type * `number_of_nodes` - The number of nodes in the cluster +* `maintenance_track_name` - The name of the maintenance track for the restored cluster. +* `manual_snapshot_retention_period` - (Optional) The default number of days to retain a manual snapshot. * `port` - The port the cluster responds on * `preferred_maintenance_window` - The maintenance window * `publicly_accessible` - Whether the cluster is publicly accessible * `s3_key_prefix` - The folder inside the S3 bucket where the log files are stored +* `log_destination_type` - The log destination type. +* `log_exports` - The collection of exported log types. Log types include the connection log, user log and user activity log. * `tags` - The tags associated to the cluster * `vpc_id` - The VPC Id associated with the cluster * `vpc_security_group_ids` - The VPC security group Ids associated with the cluster + +Cluster nodes (for `cluster_nodes`) support the following attributes: + +* `node_role` - Whether the node is a leader node or a compute node +* `private_ip_address` - The private IP address of a node within a cluster +* `public_ip_address` - The public IP address of a node within a cluster diff --git a/website/docs/d/redshift_cluster_credentials.html.markdown b/website/docs/d/redshift_cluster_credentials.html.markdown new file mode 100644 index 00000000000..03c1dfc5eb7 --- /dev/null +++ b/website/docs/d/redshift_cluster_credentials.html.markdown @@ -0,0 +1,38 @@ +--- +subcategory: "Redshift" +layout: "aws" +page_title: "AWS: aws_redshift_cluster_credentials" +description: |- + Provides redshift cluster credentials +--- + +# Data Source: aws_redshift_cluster_credentials + +Provides redshift subnet group. + +## Example Usage + +```terraform +data "aws_redshift_cluster_credentials" "example" { + name = aws_redshift_cluster_credentials.example.name +} +``` + +## Argument Reference + +The following arguments are supported: + +* `auto_create` - (Optional) Create a database user with the name specified for the user named in `db_user` if one does not exist. +* `cluster_identifier` - (Required) The unique identifier of the cluster that contains the database for which your are requesting credentials. +* `db_name` - (Optional) The name of a database that DbUser is authorized to log on to. If `db_name` is not specified, `db_user` can log on to any existing database. +* `db_user` - (Required) The name of a database user. If a user name matching `db_user` exists in the database, the temporary user credentials have the same permissions as the existing user. If `db_user` doesn't exist in the database and `auto_create` is `True`, a new user is created using the value for `db_user` with `PUBLIC` permissions. If a database user matching the value for `db_user` doesn't exist and `not` is `False`, then the command succeeds but the connection attempt will fail because the user doesn't exist in the database. +* `db_groups` - (Optional) A list of the names of existing database groups that the user named in `db_user` will join for the current session, in addition to any group memberships for an existing user. If not specified, a new user is added only to `PUBLIC`. +* `duration_seconds` - (Optional) The number of seconds until the returned temporary password expires. Valid values are between `900` and `3600`. Default value is `900`. + + +## Attribute Reference + +In addition to all arguments above, the following attributes are exported: + +* `db_password` - A temporary password that authorizes the user name returned by `db_user` to log on to the database `db_name`. +* `expiration` - The date and time the password in `db_password` expires. diff --git a/website/docs/d/redshift_subnet_group.html.markdown b/website/docs/d/redshift_subnet_group.html.markdown new file mode 100644 index 00000000000..55e43874d93 --- /dev/null +++ b/website/docs/d/redshift_subnet_group.html.markdown @@ -0,0 +1,35 @@ +--- +subcategory: "Redshift" +layout: "aws" +page_title: "AWS: aws_redshift_subnet_group" +description: |- + Provides details about a specific redshift subnet_group +--- + +# Data Source: aws_redshift_subnet_group + +Provides details about a specific redshift subnet group. + +## Example Usage + +```terraform +data "aws_redshift_subnet_group" "example" { + name = aws_redshift_subnet_group.example.name +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the cluster subnet group for which information is requested. + +## Attribute Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - Amazon Resource Name (ARN) of the Redshift Subnet Group name. +* `description` - The description of the Redshift Subnet group. +* `id` - The Redshift Subnet group Name. +* `subnet_ids` - An array of VPC subnet IDs. +* `tags` - The tags associated to the Subnet Group diff --git a/website/docs/d/secretsmanager_secret_version.html.markdown b/website/docs/d/secretsmanager_secret_version.html.markdown index 7af1e35aa6f..093072722fe 100644 --- a/website/docs/d/secretsmanager_secret_version.html.markdown +++ b/website/docs/d/secretsmanager_secret_version.html.markdown @@ -52,5 +52,5 @@ output "example" { * `arn` - The ARN of the secret. * `id` - The unique identifier of this version of the secret. * `secret_string` - The decrypted part of the protected secret information that was originally provided as a string. -* `secret_binary` - The decrypted part of the protected secret information that was originally provided as a binary. Base64 encoded. +* `secret_binary` - The decrypted part of the protected secret information that was originally provided as a binary. * `version_id` - The unique identifier of this version of the secret. diff --git a/website/docs/d/vpc_endpoint_service.html.markdown b/website/docs/d/vpc_endpoint_service.html.markdown index c50811477c9..51fea7d274e 100644 --- a/website/docs/d/vpc_endpoint_service.html.markdown +++ b/website/docs/d/vpc_endpoint_service.html.markdown @@ -85,5 +85,6 @@ In addition to all arguments above, the following attributes are exported: * `owner` - The AWS account ID of the service owner or `amazon`. * `private_dns_name` - The private DNS name for the service. * `service_id` - The ID of the endpoint service. +* `supported_ip_address_types` - The supported IP address types. * `tags` - A map of tags assigned to the resource. * `vpc_endpoint_policy_supported` - Whether or not the service supports endpoint policies - `true` or `false`. diff --git a/website/docs/guides/custom-service-endpoints.html.md b/website/docs/guides/custom-service-endpoints.html.md index 5ac088ba1fb..b16a09b5309 100644 --- a/website/docs/guides/custom-service-endpoints.html.md +++ b/website/docs/guides/custom-service-endpoints.html.md @@ -166,7 +166,7 @@ provider "aws" {
  • efs
  • eks
  • elasticache
  • -
  • elasticbeanstalk
  • +
  • elasticbeanstalk (or beanstalk)
  • elasticinference
  • elasticsearch (or es or elasticsearchservice)
  • elastictranscoder
  • @@ -174,6 +174,7 @@ provider "aws" {
  • elbv2 (or elasticloadbalancingv2)
  • emr
  • emrcontainers
  • +
  • emrserverless
  • events (or eventbridge or cloudwatchevents)
  • evidently (or cloudwatchevidently)
  • finspace
  • @@ -218,7 +219,7 @@ provider "aws" {
  • iottwinmaker
  • iotwireless
  • ivs
  • -
  • kafka
  • +
  • kafka (or msk)
  • kafkaconnect
  • kendra
  • keyspaces
  • @@ -232,14 +233,14 @@ provider "aws" {
  • kms
  • lakeformation
  • lambda
  • -
  • lexmodels (or lexmodelbuilding or lexmodelbuildingservice)
  • +
  • lexmodels (or lexmodelbuilding or lexmodelbuildingservice or lex)
  • lexmodelsv2 (or lexv2models)
  • lexruntime (or lexruntimeservice)
  • lexruntimev2 (or lexv2runtime)
  • licensemanager
  • lightsail
  • location (or locationservice)
  • -
  • logs (or cloudwatchlogs)
  • +
  • logs (or cloudwatchlog or cloudwatchlogs)
  • lookoutequipment
  • lookoutmetrics
  • lookoutvision (or lookoutforvision)
  • diff --git a/website/docs/guides/using-aws-with-awscc-provider.html.md b/website/docs/guides/using-aws-with-awscc-provider.html.md index a6fd8e618b0..0f7570cf413 100644 --- a/website/docs/guides/using-aws-with-awscc-provider.html.md +++ b/website/docs/guides/using-aws-with-awscc-provider.html.md @@ -8,7 +8,7 @@ description: |- # Using AWS & AWSCC Provider Together -~> **NOTE**: The `awscc` provider is currently in technical preview. This means some aspects of its design and implementation are not yet considered stable for production use. We are actively looking for community feedback in order to identify needed improvements. +~> **NOTE:** The `awscc` provider is currently in technical preview. This means some aspects of its design and implementation are not yet considered stable for production use. We are actively looking for community feedback in order to identify needed improvements. The [HashiCorp Terraform AWS Cloud Control Provider](https://registry.terraform.io/providers/hashicorp/awscc/latest) aims to bring Amazon Web Services (AWS) resources to Terraform users faster. The new provider is automatically generated, which means new features and services on AWS can be supported right away. The AWS Cloud Control provider supports hundreds of AWS resources, with more support being added as AWS service teams adopt the Cloud Control API standard. @@ -39,7 +39,7 @@ Terraform can use many providers at once, as long as they are specified in your ```terraform terraform { - required_version = ">= 0.15.3" + required_version = ">= 1.0.7" required_providers { aws = { source = "hashicorp/aws" @@ -47,7 +47,7 @@ terraform { } awscc = { source = "hashicorp/awscc" - version = ">= 0.21.0" + version = ">= 0.25.0" } } } @@ -84,12 +84,13 @@ Above, we define a `awscc_networkmanager_global_network` with 2 tags and a descr Next we will create a [core network](https://docs.aws.amazon.com/vpc/latest/cloudwan/cloudwan-core-network-policy.html) using an AWSCC resource `awscc_networkmanager_core_network` and an AWS data source `data.aws_networkmanager_core_network_policy_document` which allows users to write HCL to generate the json policy used as the [core policy network](https://docs.aws.amazon.com/vpc/latest/cloudwan/cloudwan-policies-json.html). -``` +```terraform resource "awscc_networkmanager_core_network" "main" { description = "My Core Network" global_network_id = awscc_networkmanager_global_network.main.id - policy_document = data.aws_networkmanager_core_network_policy_document.main.json - tags = local.terraform_tag + # Compose jsonencode and jsondecode to produce a normalized JSON string. + policy_document = jsonencode(jsondecode(data.aws_networkmanager_core_network_policy_document.main.json)) + tags = local.terraform_tag } data "aws_networkmanager_core_network_policy_document" "main" { @@ -104,7 +105,7 @@ data "aws_networkmanager_core_network_policy_document" "main" { segments { name = "shared" - description = "Segment for shared services" + description = "SegmentForSharedServices" require_attachment_acceptance = true } diff --git a/website/docs/guides/version-4-upgrade.html.md b/website/docs/guides/version-4-upgrade.html.md index 28af8538833..1a2b9548b50 100644 --- a/website/docs/guides/version-4-upgrade.html.md +++ b/website/docs/guides/version-4-upgrade.html.md @@ -491,6 +491,8 @@ resource "aws_s3_bucket_cors_configuration" "example" { ### Migrating to `aws_s3_bucket_lifecycle_configuration` +~> **Note:** In version `3.x` of the provider, the `lifecycle_rule.id` argument was optional, while in version `4.x`, the `aws_s3_bucket_lifecycle_configuration.rule.id` argument required. Use the AWS CLI s3api [get-bucket-lifecycle-configuration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-lifecycle-configuration.html) to get the source bucket's lifecycle configuration to determine the ID. + #### For Lifecycle Rules with no `prefix` previously configured ~> **Note:** When configuring the `rule.filter` configuration block in the new `aws_s3_bucket_lifecycle_configuration` resource, use the AWS CLI s3api [get-bucket-lifecycle-configuration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-lifecycle-configuration.html) @@ -3295,7 +3297,7 @@ data "aws_iam_policy_document" "ad-log-policy" { ## Data Source: aws_subnet_ids -The `aws_subnet_ids` data source has been deprecated and will be removed removed in a future version. Use the `aws_subnets` data source instead. +The `aws_subnet_ids` data source has been deprecated and will be removed in a future version. Use the `aws_subnets` data source instead. For example, change a configuration such as diff --git a/website/docs/r/acm_certificate.html.markdown b/website/docs/r/acm_certificate.html.markdown index 1a532f9ec34..e5d384547fa 100644 --- a/website/docs/r/acm_certificate.html.markdown +++ b/website/docs/r/acm_certificate.html.markdown @@ -117,7 +117,7 @@ resource "aws_route53_record" "example" { The following arguments are supported: -* Creating an amazon issued certificate +* Creating an Amazon issued certificate * `domain_name` - (Required) A domain name for which the certificate should be issued * `subject_alternative_names` - (Optional) Set of domains that should be SANs in the issued certificate. To remove all elements of a previously configured list, set this value equal to an empty list (`[]`) or use the [`terraform taint` command](https://www.terraform.io/docs/commands/taint.html) to trigger recreation. * `validation_method` - (Required) Which method to use for validation. `DNS` or `EMAIL` are valid, `NONE` can be used for certificates that were imported into ACM and then into Terraform. diff --git a/website/docs/r/acmpca_policy.html.markdown b/website/docs/r/acmpca_policy.html.markdown new file mode 100644 index 00000000000..ec6c531ac2f --- /dev/null +++ b/website/docs/r/acmpca_policy.html.markdown @@ -0,0 +1,76 @@ +--- +subcategory: "ACM PCA (Certificate Manager Private Certificate Authority)" +layout: "aws" +page_title: "AWS: aws_acmpca_policy" +description: |- + Attaches a resource based policy to an AWS Certificate Manager Private Certificate Authority (ACM PCA) +--- + +# Resource: aws_acmpca_policy + +Attaches a resource based policy to a private CA. + +## Example Usage + +### Basic + +```terraform +resource "aws_acmpca_policy" "example" { + resource_arn = aws_acmpca_certificate_authority.example.arn + policy = < **NOTE**: Both `memory_mib.min` and `vcpu_count.min` must be specified. + +* `accelerator_count` - (Optional) Block describing the minimum and maximum number of accelerators (GPUs, FPGAs, or AWS Inferentia chips). Default is no minimum or maximum. + * `min` - (Optional) Minimum. + * `max` - (Optional) Maximum. Set to `0` to exclude instance types with accelerators. +* `accelerator_manufacturers` - (Optional) List of accelerator manufacturer names. Default is any manufacturer. + + ``` + Valid names: + * amazon-web-services + * amd + * nvidia + * xilinx + ``` + +* `accelerator_names` - (Optional) List of accelerator names. Default is any acclerator. + + ``` + Valid names: + * a100 - NVIDIA A100 GPUs + * v100 - NVIDIA V100 GPUs + * k80 - NVIDIA K80 GPUs + * t4 - NVIDIA T4 GPUs + * m60 - NVIDIA M60 GPUs + * radeon-pro-v520 - AMD Radeon Pro V520 GPUs + * vu9p - Xilinx VU9P FPGAs + ``` + +* `accelerator_total_memory_mib` - (Optional) Block describing the minimum and maximum total memory of the accelerators. Default is no minimum or maximum. + * `min` - (Optional) Minimum. + * `max` - (Optional) Maximum. +* `accelerator_types` - (Optional) List of accelerator types. Default is any accelerator type. + + ``` + Valid types: + * fpga + * gpu + * inference + ``` + +* `bare_metal` - (Optional) Indicate whether bare metal instace types should be `included`, `excluded`, or `required`. Default is `excluded`. +* `baseline_ebs_bandwidth_mbps` - (Optional) Block describing the minimum and maximum baseline EBS bandwidth, in Mbps. Default is no minimum or maximum. + * `min` - (Optional) Minimum. + * `max` - (Optional) Maximum. +* `burstable_performance` - (Optional) Indicate whether burstable performance instance types should be `included`, `excluded`, or `required`. Default is `excluded`. +* `cpu_manufacturers` (Optional) List of CPU manufacturer names. Default is any manufacturer. + + ~> **NOTE**: Don't confuse the CPU hardware manufacturer with the CPU hardware architecture. Instances will be launched with a compatible CPU architecture based on the Amazon Machine Image (AMI) that you specify in your launch template. + + ``` + Valid names: + * amazon-web-services + * amd + * intel + ``` + +* `excluded_instance_types` - (Optional) List of instance types to exclude. You can use strings with one or more wild cards, represented by an asterisk (\*). The following are examples: `c5*`, `m5a.*`, `r*`, `*3*`. For example, if you specify `c5*`, you are excluding the entire C5 instance family, which includes all C5a and C5n instance types. If you specify `m5a.*`, you are excluding all the M5a instance types, but not the M5n instance types. Maximum of 400 entries in the list; each entry is limited to 30 characters. Default is no excluded instance types. +* `instance_generations` - (Optional) List of instance generation names. Default is any generation. + + ``` + Valid names: + * current - Recommended for best performance. + * previous - For existing applications optimized for older instance types. + ``` + +* `local_storage` - (Optional) Indicate whether instance types with local storage volumes are `included`, `excluded`, or `required`. Default is `included`. +* `local_storage_types` - (Optional) List of local storage type names. Default any storage type. + + ``` + Value names: + * hdd - hard disk drive + * ssd - solid state drive + ``` + +* `memory_gib_per_vcpu` - (Optional) Block describing the minimum and maximum amount of memory (GiB) per vCPU. Default is no minimum or maximum. + * `min` - (Optional) Minimum. May be a decimal number, e.g. `0.5`. + * `max` - (Optional) Maximum. May be a decimal number, e.g. `0.5`. +* `memory_mib` - (Required) Block describing the minimum and maximum amount of memory (MiB). Default is no maximum. + * `min` - (Required) Minimum. + * `max` - (Optional) Maximum. +* `network_interface_count` - (Optional) Block describing the minimum and maximum number of network interfaces. Default is no minimum or maximum. + * `min` - (Optional) Minimum. + * `max` - (Optional) Maximum. +* `on_demand_max_price_percentage_over_lowest_price` - (Optional) The price protection threshold for On-Demand Instances. This is the maximum you’ll pay for an On-Demand Instance, expressed as a percentage higher than the cheapest M, C, or R instance type with your specified attributes. When Amazon EC2 Auto Scaling selects instance types with your attributes, we will exclude instance types whose price is higher than your threshold. The parameter accepts an integer, which Amazon EC2 Auto Scaling interprets as a percentage. To turn off price protection, specify a high value, such as 999999. Default is 20. + + If you set DesiredCapacityType to vcpu or memory-mib, the price protection threshold is applied based on the per vCPU or per memory price instead of the per instance price. +* `require_hibernate_support` - (Optional) Indicate whether instance types must support On-Demand Instance Hibernation, either `true` or `false`. Default is `false`. +* `spot_max_price_percentage_over_lowest_price` - (Optional) The price protection threshold for Spot Instances. This is the maximum you’ll pay for a Spot Instance, expressed as a percentage higher than the cheapest M, C, or R instance type with your specified attributes. When Amazon EC2 Auto Scaling selects instance types with your attributes, we will exclude instance types whose price is higher than your threshold. The parameter accepts an integer, which Amazon EC2 Auto Scaling interprets as a percentage. To turn off price protection, specify a high value, such as 999999. Default is 100. + + If you set DesiredCapacityType to vcpu or memory-mib, the price protection threshold is applied based on the per vCPU or per memory price instead of the per instance price. +* `total_local_storage_gb` - (Optional) Block describing the minimum and maximum total local storage (GB). Default is no minimum or maximum. + * `min` - (Optional) Minimum. May be a decimal number, e.g. `0.5`. + * `max` - (Optional) Maximum. May be a decimal number, e.g. `0.5`. +* `vcpu_count` - (Required) Block describing the minimum and maximum number of vCPUs. Default is no maximum. + * `min` - (Required) Minimum. + * `max` - (Optional) Maximum. + ### tag and tags The `tag` attribute accepts exactly one tag declaration with the following fields: diff --git a/website/docs/r/backup_selection.html.markdown b/website/docs/r/backup_selection.html.markdown index 67859a06851..e18f91ba686 100644 --- a/website/docs/r/backup_selection.html.markdown +++ b/website/docs/r/backup_selection.html.markdown @@ -72,6 +72,7 @@ resource "aws_backup_selection" "example" { iam_role_arn = aws_iam_role.example.arn name = "tf_example_backup_selection" plan_id = aws_backup_plan.example.id + resources = ["*"] condition { string_equals { diff --git a/website/docs/r/ce_anomaly_monitor.html.markdown b/website/docs/r/ce_anomaly_monitor.html.markdown new file mode 100644 index 00000000000..7176c4848ae --- /dev/null +++ b/website/docs/r/ce_anomaly_monitor.html.markdown @@ -0,0 +1,77 @@ +--- +subcategory: "CE (Cost Explorer)" +layout: "aws" +page_title: "AWS: aws_ce_anomaly_monitor" +description: |- + Provides a CE Cost Anomaly Monitor +--- + +# Resource: aws_ce_anomaly_monitor + +Provides a CE Anomaly Monitor. + +## Example Usage + +There are two main types of a Cost Anomaly Monitor: `DIMENSIONAL` and `CUSTOM`. + +### Dimensional Example + +```terraform +resource "aws_ce_anomaly_monitor" "service_monitor" { + name = "AWSServiceMonitor" + monitor_type = "DIMENSIONAL" + monitor_dimension = "SERVICE" +} +``` + +### Custom Example + +```terraform +resource "aws_ce_anomaly_monitor" "test" { + name = "AWSCustomAnomalyMonitor" + monitor_type = "CUSTOM" + + specification = < **Note:** In order to be able to have your AWS Lambda function or @@ -411,7 +473,7 @@ The following arguments are supported: ### ecs_target * `group` - (Optional) Specifies an ECS task group for the task. The maximum length is 255 characters. -* `launch_type` - (Optional) Specifies the launch type on which your task is running. The launch type that you specify here must match one of the launch type (compatibilities) of the target task. Valid values include: an empty string `""` (to specify no launch type), `EC2`, or `FARGATE`. +* `launch_type` - (Optional) Specifies the launch type on which your task is running. The launch type that you specify here must match one of the launch type (compatibilities) of the target task. Valid values include: `EC2`, `EXTERNAL`, or `FARGATE`. * `network_configuration` - (Optional) Use this if the ECS task uses the awsvpc network mode. This specifies the VPC subnets and security groups associated with the task, and whether a public IP address is to be used. Required if launch_type is FARGATE because the awsvpc mode is required for Fargate tasks. * `platform_version` - (Optional) Specifies the platform version for the task. Specify only the numeric portion of the platform version, such as 1.1.0. This is used only if LaunchType is FARGATE. For more information about valid platform versions, see [AWS Fargate Platform Versions](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html). * `task_count` - (Optional) The number of tasks to create based on the TaskDefinition. The default is 1. diff --git a/website/docs/r/cloudwatch_metric_stream.html.markdown b/website/docs/r/cloudwatch_metric_stream.html.markdown index 4546cd0483d..3047678115b 100644 --- a/website/docs/r/cloudwatch_metric_stream.html.markdown +++ b/website/docs/r/cloudwatch_metric_stream.html.markdown @@ -12,6 +12,8 @@ Provides a CloudWatch Metric Stream resource. ## Example Usage +### Filters + ```terraform resource "aws_cloudwatch_metric_stream" "main" { name = "my-metric-stream" @@ -137,6 +139,39 @@ resource "aws_kinesis_firehose_delivery_stream" "s3_stream" { } ``` +### Additional Statistics + +```terraform +resource "aws_cloudwatch_metric_stream" "main" { + name = "my-metric-stream" + role_arn = aws_iam_role.metric_stream_to_firehose.arn + firehose_arn = aws_kinesis_firehose_delivery_stream.s3_stream.arn + output_format = "json" + + statistics_configuration { + additional_statistics = [ + "p1", "tm99" + ] + + include_metric { + metric_name = "CPUUtilization" + namespace = "AWS/EC2" + } + } + + statistics_configuration { + additional_statistics = [ + "TS(50.5:)" + ] + + include_metric { + metric_name = "CPUUtilization" + namespace = "AWS/EC2" + } + } +} +``` + ## Argument Reference The following arguments are required: @@ -152,15 +187,28 @@ The following arguments are optional: * `name` - (Optional, Forces new resource) Friendly name of the metric stream. If omitted, Terraform will assign a random, unique name. Conflicts with `name_prefix`. * `name_prefix` - (Optional, Forces new resource) Creates a unique friendly name beginning with the specified prefix. Conflicts with `name`. * `tags` - (Optional) Map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. +* `statistics_configuration` - (Optional) For each entry in this array, you specify one or more metrics and the list of additional statistics to stream for those metrics. The additional statistics that you can stream depend on the stream's `output_format`. If the OutputFormat is `json`, you can stream any additional statistic that is supported by CloudWatch, listed in [CloudWatch statistics definitions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Statistics-definitions.html.html). If the OutputFormat is `opentelemetry0.7`, you can stream percentile statistics (p99 etc.). See details below. + +### Nested Fields -### `exclude_filter` +#### `exclude_filter` * `namespace` - (Required) Name of the metric namespace in the filter. -### `include_filter` +#### `include_filter` * `namespace` - (Required) Name of the metric namespace in the filter. +#### `statistics_configurations` + +* `additional_statistics` - (Required) The additional statistics to stream for the metrics listed in `include_metrics`. +* `include_metric` - (Required) An array that defines the metrics that are to have additional statistics streamed. See details below. + +#### `include_metrics` + +* `metric_name` - (Required) The name of the metric. +* `namespace` - (Required) The namespace of the metric. + ## Attributes Reference In addition to all arguments above, the following attributes are exported: diff --git a/website/docs/r/cognito_risk_configuration.html.markdown b/website/docs/r/cognito_risk_configuration.html.markdown new file mode 100644 index 00000000000..82ba6bd77fd --- /dev/null +++ b/website/docs/r/cognito_risk_configuration.html.markdown @@ -0,0 +1,96 @@ +--- +subcategory: "Cognito IDP (Identity Provider)" +layout: "aws" +page_title: "AWS: aws_cognito_risk_configuration" +description: |- + Provides a Cognito Risk Configuration resource. +--- + +# Resource: aws_cognito_risk_configuration + +Provides a Cognito Risk Configuration resource. + +## Example Usage + +```terraform +resource "aws_cognito_risk_configuration" "example" { + user_pool_id = aws_cognito_user_pool.example.id + + risk_exception_configuration { + blocked_ip_range_list = ["10.10.10.10/32"] + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `user_pool_id` - (Required) The user pool ID. +* `client_id` - (Optional) The app client ID. When the client ID is not provided, the same risk configuration is applied to all the clients in the User Pool. +* `account_takeover_risk_configuration` - (Optional) The account takeover risk configuration. See details below. +* `compromised_credentials_risk_configuration` - (Optional) The compromised credentials risk configuration. See details below. +* `risk_exception_configuration` - (Optional) The configuration to override the risk decision. See details below. + +### account_takeover_risk_configuration + +* `notify_configuration` - (Required) The notify configuration used to construct email notifications. See details below. +* `actions` - (Required) Account takeover risk configuration actions. See details below. + +#### notify_configuration + +* `block_email` - (Optional) Email template used when a detected risk event is blocked. See notify email type below. +* `mfa_email` - (Optional) The multi-factor authentication (MFA) email template used when MFA is challenged as part of a detected risk. See notify email type below. +* `no_action_email` - (Optional) The email template used when a detected risk event is allowed. See notify email type below. +* `from` - (Optional) The email address that is sending the email. The address must be either individually verified with Amazon Simple Email Service, or from a domain that has been verified with Amazon SES. +* `reply_to` - (Optional) The destination to which the receiver of an email should reply to. +* `source_arn` - (Required) The Amazon Resource Name (ARN) of the identity that is associated with the sending authorization policy. This identity permits Amazon Cognito to send for the email address specified in the From parameter. + +##### notify email type + +* `html_body` - (Required) The email HTML body. +* `block_email` - (Required) The email subject. +* `block_email` - (Required) The email text body. + +#### actions + +* `high_action` - (Optional) Action to take for a high risk. See action block below. +* `low_action` - (Optional) Action to take for a low risk. See action block below. +* `medium_action` - (Optional) Action to take for a medium risk. See action block below. + +##### action + +* `event_action` - (Required) The action to take in response to the account takeover action. Valid values are `BLOCK`, `MFA_IF_CONFIGURED`, `MFA_REQUIRED` and `NO_ACTION`. +* `notify` - (Required) Whether to send a notification. + +### compromised_credentials_risk_configuration + +* `event_filter` - (Optional) Perform the action for these events. The default is to perform all events if no event filter is specified. Valid values are `SIGN_IN`, `PASSWORD_CHANGE`, and `SIGN_UP`. +* `actions` - (Required) The compromised credentials risk configuration actions. See details below. + +#### actions + +* `event_action` - (Optional) The event action. Valid values are `BLOCK` or `NO_ACTION`. + +### risk_exception_configuration + +* `blocked_ip_range_list` - (Optional) Overrides the risk decision to always block the pre-authentication requests. The IP range is in CIDR notation, a compact representation of an IP address and its routing prefix. +* `skipped_ip_range_list` - (Optional) Risk detection isn't performed on the IP addresses in this range list. The IP range is in CIDR notation. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The user pool ID. or The user pool ID and Client Id separated by a `:` if the configuration is client specific. + +## Import + +Cognito Risk Configurations can be imported using the `id`, e.g., + +``` +$ terraform import aws_cognito_risk_configuration.main example +``` + +``` +$ terraform import aws_cognito_risk_configuration.main example:example +``` diff --git a/website/docs/r/cognito_user_pool_client.markdown b/website/docs/r/cognito_user_pool_client.markdown index 1823464932d..98b4847f032 100644 --- a/website/docs/r/cognito_user_pool_client.markdown +++ b/website/docs/r/cognito_user_pool_client.markdown @@ -145,6 +145,7 @@ The following arguments are optional: * `callback_urls` - (Optional) List of allowed callback URLs for the identity providers. * `default_redirect_uri` - (Optional) Default redirect URI. Must be in the list of callback URLs. * `enable_token_revocation` - (Optional) Enables or disables token revocation. +* `enable_propagate_additional_user_context_data` - (Optional) Activates the propagation of additional user context data. * `explicit_auth_flows` - (Optional) List of authentication flows (ADMIN_NO_SRP_AUTH, CUSTOM_AUTH_FLOW_ONLY, USER_PASSWORD_AUTH, ALLOW_ADMIN_USER_PASSWORD_AUTH, ALLOW_CUSTOM_AUTH, ALLOW_USER_PASSWORD_AUTH, ALLOW_USER_SRP_AUTH, ALLOW_REFRESH_TOKEN_AUTH). * `generate_secret` - (Optional) Should an application secret be generated. * `id_token_validity` - (Optional) Time limit, between 5 minutes and 1 day, after which the ID token is no longer valid and cannot be used. This value will be overridden if you have entered a value in `token_validity_units`. diff --git a/website/docs/r/connect_queue.html.markdown b/website/docs/r/connect_queue.html.markdown index 55a3bb9ace4..9be1f9f30a6 100644 --- a/website/docs/r/connect_queue.html.markdown +++ b/website/docs/r/connect_queue.html.markdown @@ -58,7 +58,7 @@ resource "aws_connect_queue" "test" { description = "Example Description" hours_of_operation_id = "12345678-1234-1234-1234-123456789012" - outbound_caller_config = { + outbound_caller_config { outbound_caller_id_name = "example" outbound_caller_id_number_id = "12345678-abcd-1234-abcd-123456789012" outbound_flow_id = "87654321-defg-1234-defg-987654321234" diff --git a/website/docs/r/customer_gateway.html.markdown b/website/docs/r/customer_gateway.html.markdown index e2a8441e2e3..8ffd4c377ae 100644 --- a/website/docs/r/customer_gateway.html.markdown +++ b/website/docs/r/customer_gateway.html.markdown @@ -33,7 +33,7 @@ The following arguments are supported: * `bgp_asn` - (Required) The gateway's Border Gateway Protocol (BGP) Autonomous System Number (ASN). * `certificate_arn` - (Optional) The Amazon Resource Name (ARN) for the customer gateway certificate. * `device_name` - (Optional) A name for the customer gateway device. -* `ip_address` - (Required) The IP address of the gateway's Internet-routable external interface. +* `ip_address` - (Required) The IPv4 address for the customer gateway device's outside interface. * `type` - (Required) The type of customer gateway. The only type AWS supports at this time is "ipsec.1". * `tags` - (Optional) Tags to apply to the gateway. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. diff --git a/website/docs/r/datasync_location_efs.html.markdown b/website/docs/r/datasync_location_efs.html.markdown index e2edf0954ad..894a9a77864 100644 --- a/website/docs/r/datasync_location_efs.html.markdown +++ b/website/docs/r/datasync_location_efs.html.markdown @@ -31,8 +31,11 @@ resource "aws_datasync_location_efs" "example" { The following arguments are supported: +* `access_point_arn` - (Optional) Specifies the Amazon Resource Name (ARN) of the access point that DataSync uses to access the Amazon EFS file system. * `ec2_config` - (Required) Configuration block containing EC2 configurations for connecting to the EFS File System. * `efs_file_system_arn` - (Required) Amazon Resource Name (ARN) of EFS File System. +* `file_system_access_role_arn` - (Optional) Specifies an Identity and Access Management (IAM) role that DataSync assumes when mounting the Amazon EFS file system. +* `in_transit_encryption` - (Optional) Specifies whether you want DataSync to use TLS encryption when transferring data to or from your Amazon EFS file system. Valid values are `NONE` and `TLS1_2`. * `subdirectory` - (Optional) Subdirectory to perform actions as source or destination. Default `/`. * `tags` - (Optional) Key-value pairs of resource tags to assign to the DataSync Location. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. diff --git a/website/docs/r/db_parameter_group.html.markdown b/website/docs/r/db_parameter_group.html.markdown index 78a94ee3297..3ca50cd49ff 100644 --- a/website/docs/r/db_parameter_group.html.markdown +++ b/website/docs/r/db_parameter_group.html.markdown @@ -18,6 +18,12 @@ Provides an RDS DB parameter group resource .Documentation of the available para > **Hands-on:** For an example of the `aws_db_parameter_group` in use, follow the [Manage AWS RDS Instances](https://learn.hashicorp.com/tutorials/terraform/aws-rds?in=terraform/aws&utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS) tutorial on HashiCorp Learn. +~> **NOTE:** After applying your changes, you may encounter a perpetual diff in your Terraform plan +output for a `parameter` whose `value` remains unchanged but whose `apply_method` is changing +(e.g. from `immediate` to `pending-reboot`, or `pending-reboot` to `immediate`). If only the +apply method of a parameter is changing, the AWS API will not register this change. To change +the `apply_method` of a parameter, its value must also change. + ## Example Usage ```terraform diff --git a/website/docs/r/dms_endpoint.html.markdown b/website/docs/r/dms_endpoint.html.markdown index bfecc65a022..ee385df17e0 100644 --- a/website/docs/r/dms_endpoint.html.markdown +++ b/website/docs/r/dms_endpoint.html.markdown @@ -44,7 +44,7 @@ The following arguments are required: * `endpoint_id` - (Required) Database endpoint identifier. Identifiers must contain from 1 to 255 alphanumeric characters or hyphens, begin with a letter, contain only ASCII letters, digits, and hyphens, not end with a hyphen, and not contain two consecutive hyphens. * `endpoint_type` - (Required) Type of endpoint. Valid values are `source`, `target`. -* `engine_name` - (Required) Type of engine for the endpoint. Valid values are `aurora`, `aurora-postgresql`, `azuredb`, `db2`, `docdb`, `dynamodb`, `elasticsearch`, `kafka`, `kinesis`, `mariadb`, `mongodb`, `mysql`, `opensearch`, `oracle`, `postgres`, `redshift`, `s3`, `sqlserver`, `sybase`. +* `engine_name` - (Required) Type of engine for the endpoint. Valid values are `aurora`, `aurora-postgresql`, `azuredb`, `db2`, `docdb`, `dynamodb`, `elasticsearch`, `kafka`, `kinesis`, `mariadb`, `mongodb`, `mysql`, `opensearch`, `oracle`, `postgres`, `redshift`, `s3`, `sqlserver`, `sybase`. Please note that some of engine names are available only for `target` endpoint type (e.g. `redshift`). * `kms_key_arn` - (Required when `engine_name` is `mongodb`, optional otherwise) ARN for the KMS key that will be used to encrypt the connection parameters. If you do not specify a value for `kms_key_arn`, then AWS DMS will use your default encryption key. AWS KMS creates the default encryption key for your AWS account. Your AWS account has a different default encryption key for each AWS region. The following arguments are optional: @@ -58,9 +58,10 @@ The following arguments are optional: * `mongodb_settings` - (Optional) Configuration block for MongoDB settings. See below. * `password` - (Optional) Password to be used to login to the endpoint database. * `port` - (Optional) Port used by the endpoint database. +* `redshift_settings` - (Optional) Configuration block for Redshift settings. See below. * `s3_settings` - (Optional) Configuration block for S3 settings. See below. * `secrets_manager_access_role_arn` - (Optional) ARN of the IAM role that specifies AWS DMS as the trusted entity and has the required permissions to access the value in SecretsManagerSecret. -* `secrets_manager_arn` - (Optional) Full ARN, partial ARN, or friendly name of the SecretsManagerSecret that contains the endpoint connection details. Supported only for `engine_name` as `oracle` and `postgres`. +* `secrets_manager_arn` - (Optional) Full ARN, partial ARN, or friendly name of the SecretsManagerSecret that contains the endpoint connection details. Supported only for `engine_name` as `aurora`, `aurora-postgresql`, `mariadb`, `mongodb`, `mysql`, `oracle`, `postgres`, `redshift` or `sqlserver`. * `server_name` - (Optional) Host name of the server. * `service_access_role` - (Optional) ARN used by the service access IAM role for dynamodb endpoints. * `ssl_mode` - (Optional, Default: none) SSL mode to use for the connection. Valid values are `none`, `require`, `verify-ca`, `verify-full` @@ -124,6 +125,16 @@ The following arguments are optional: * `extract_doc_id` - (Optional) Document ID. Use this setting when `nesting_level` is set to `none`. Default is `false`. * `nesting_level` - (Optional) Specifies either document or table mode. Default is `none`. Valid values are `one` (table mode) and `none` (document mode). +### redshift_settings + +-> Additional information can be found in the [Using Amazon Redshift as a Target for AWS Database Migration Service documentation](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Redshift.html). + +* `bucket_folder` - (Optional) Custom S3 Bucket Object prefix for intermediate storage. +* `bucket_name` - (Optional) Custom S3 Bucket name for intermediate storage. +* `encryption_mode` - (Optional) The server-side encryption mode that you want to encrypt your intermediate .csv object files copied to S3. Defaults to `SSE_S3`. Valid values are `SSE_S3` and `SSE_KMS`. +* `server_side_encryption_kms_key_id` - (Optional) If you set encryptionMode to `SSE_KMS`, set this parameter to the Amazon Resource Name (ARN) for the AWS KMS key. +* `service_access_role_arn` - (Optional) Amazon Resource Name (ARN) of the IAM Role with permissions to read from or write to the S3 Bucket for intermediate storage. + ### s3_settings -> Additional information can be found in the [Using Amazon S3 as a Source for AWS Database Migration Service documentation](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.S3.html) and [Using Amazon S3 as a Target for AWS Database Migration Service documentation](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.S3.html). diff --git a/website/docs/r/ebs_snapshot_copy.html.markdown b/website/docs/r/ebs_snapshot_copy.html.markdown index c939b9d24c6..51b13fada25 100644 --- a/website/docs/r/ebs_snapshot_copy.html.markdown +++ b/website/docs/r/ebs_snapshot_copy.html.markdown @@ -54,6 +54,14 @@ The following arguments are supported: * `temporary_restore_days` - (Optional) Specifies the number of days for which to temporarily restore an archived snapshot. Required for temporary restores only. The snapshot will be automatically re-archived after this period. * `tags` - A map of tags for the snapshot. If configured with a provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. +### Timeouts + +`aws_ebs_snapshot_copy` provides the following +[Timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) configuration options: + +- `create` - (Default `10 minutes`) Used for creating the ebs snapshot copy +- `delete` - (Default `10 minutes`) Used for deleting the ebs snapshot copy + ## Attributes Reference In addition to all arguments above, the following attributes are exported: diff --git a/website/docs/r/ebs_volume.html.markdown b/website/docs/r/ebs_volume.html.markdown index f363c50b15f..5b02df29b11 100644 --- a/website/docs/r/ebs_volume.html.markdown +++ b/website/docs/r/ebs_volume.html.markdown @@ -31,6 +31,7 @@ The following arguments are supported: * `availability_zone` - (Required) The AZ where the EBS volume will exist. * `encrypted` - (Optional) If true, the disk will be encrypted. +* `final_snapshot` - (Optional) If true, snapshot will be created before volume deletion. Any tags on the volume will be migrated to the snapshot. By default set to false * `iops` - (Optional) The amount of IOPS to provision for the disk. Only valid for `type` of `io1`, `io2` or `gp3`. * `multi_attach_enabled` - (Optional) Specifies whether to enable Amazon EBS Multi-Attach. Multi-Attach is supported on `io1` and `io2` volumes. * `size` - (Optional) The size of the drive in GiBs. diff --git a/website/docs/r/ec2_host.html.markdown b/website/docs/r/ec2_host.html.markdown index 2dbf030dbae..2792902127c 100644 --- a/website/docs/r/ec2_host.html.markdown +++ b/website/docs/r/ec2_host.html.markdown @@ -31,7 +31,8 @@ The following arguments are supported: * `availability_zone` - (Required) The Availability Zone in which to allocate the Dedicated Host. * `host_recovery` - (Optional) Indicates whether to enable or disable host recovery for the Dedicated Host. Valid values: `on`, `off`. Default: `off`. * `instance_family` - (Optional) Specifies the instance family to be supported by the Dedicated Hosts. If you specify an instance family, the Dedicated Hosts support multiple instance types within that instance family. Exactly one of `instance_family` or `instance_type` must be specified. -* `instance_type` - (Optional) Specifies the instance type to be supported by the Dedicated Hosts. If you specify an instance type, the Dedicated Hosts support instances of the specified instance type only. Exactly one of `instance_family` or `instance_type` must be specified. +* `instance_type` - (Optional) Specifies the instance type to be supported by the Dedicated Hosts. If you specify an instance type, the Dedicated Hosts support instances of the specified instance type only. Exactly one of `instance_family` or `instance_type` must be specified. +* `outpost_arn` - (Optional) The Amazon Resource Name (ARN) of the AWS Outpost on which to allocate the Dedicated Host. * `tags` - (Optional) Map of tags to assign to this resource. If configured with a provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. ## Attributes Reference diff --git a/website/docs/r/ecr_registry_scanning_configuration.html.markdown b/website/docs/r/ecr_registry_scanning_configuration.html.markdown index 0731bc5d677..46bf37d828d 100644 --- a/website/docs/r/ecr_registry_scanning_configuration.html.markdown +++ b/website/docs/r/ecr_registry_scanning_configuration.html.markdown @@ -75,5 +75,5 @@ In addition to all arguments above, the following attributes are exported: ECR Scanning Configurations can be imported using the `registry_id`, e.g., ``` -$ terraform import aws_ecr_registry_scanning_configuration 012345678901 +$ terraform import aws_ecr_registry_scanning_configuration.example 012345678901 ``` diff --git a/website/docs/r/ecs_cluster.html.markdown b/website/docs/r/ecs_cluster.html.markdown index 51512071fd8..822a6f12c8f 100644 --- a/website/docs/r/ecs_cluster.html.markdown +++ b/website/docs/r/ecs_cluster.html.markdown @@ -120,7 +120,7 @@ The following arguments are supported: ### `setting` * `name` - (Required) Name of the setting to manage. Valid values: `containerInsights`. -* `value` - (Required) The value to assign to the setting. Value values are `enabled` and `disabled`. +* `value` - (Required) The value to assign to the setting. Valid values are `enabled` and `disabled`. ## Attributes Reference diff --git a/website/docs/r/efs_replication_configuration.html.markdown b/website/docs/r/efs_replication_configuration.html.markdown new file mode 100644 index 00000000000..70a528795bf --- /dev/null +++ b/website/docs/r/efs_replication_configuration.html.markdown @@ -0,0 +1,84 @@ +--- +subcategory: "EFS (Elastic File System)" +layout: "aws" +page_title: "AWS: aws_efs_replication_configuration" +description: Provides an Elastic File System (EFS) Replication Configuration. +--- + +# Resource: aws_efs_replication_configuration + +Creates a replica of an existing EFS file system in the same or another region. Creating this resource causes the source EFS file system to be replicated to a new read-only destination EFS file system. Deleting this resource will cause the replication from source to destination to stop and the destination file system will no longer be read only. + +~> **NOTE:** Deleting this resource does **not** delete the destination file system that was created. + +## Example Usage + +Will create a replica using regional storage in us-west-2 that will be encrypted by the default EFS KMS key `/aws/elasticfilesystem`. + +```terraform +resource "aws_efs_file_system" "example" {} + +resource "aws_efs_replication_configuration" "example" { + source_file_system_id = aws_efs_file_system.example.id + + destination { + region = "us-west-2" + } +} +``` + +Replica will be created as One Zone storage in the us-west-2b Availability Zone and encrypted with the specified KMS key. + +```terraform +resource "aws_efs_file_system" "example" {} + +resource "aws_efs_replication_configuration" "example" { + source_file_system_id = aws_efs_file_system.example.id + + destination { + availability_zone_name = "us-west-2b" + kms_key_id = "1234abcd-12ab-34cd-56ef-1234567890ab" + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `source_file_system_id` - (Required) The ID of the file system that is to be replicated. +* `destination` - (Required) A destination configuration block (documented below). + +### Destination Arguments + +For **destination** the following attributes are supported: + +* `availability_zone_name` - (Optional) The availability zone in which the replica should be created. If specified, the replica will be created with One Zone storage. If omitted, regional storage will be used. +* `kms_key_id` - (Optional) The Key ID, ARN, alias, or alias ARN of the KMS key that should be used to encrypt the replica file system. If omitted, the default KMS key for EFS `/aws/elasticfilesystem` will be used. +* `region` - (Optional) The region in which the replica should be created. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `creation_time` - When the replication configuration was created. +* `original_source_file_system_arn` - The Amazon Resource Name (ARN) of the original source Amazon EFS file system in the replication configuration. +* `source_file_system_arn` - The Amazon Resource Name (ARN) of the current source file system in the replication configuration. +* `source_file_system_region` - The AWS Region in which the source Amazon EFS file system is located. +* `destination[0].file_system_id` - The fs ID of the replica. +* `destination[0].status` - The status of the replication. + +### Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) for certain actions: + +* `create` - (Default `10 minutes`) Used when creating the replication configuration. +* `delete` - (Default `20 minutes`) Used when deleting the replication configuration. + +## Import + +EFS Replication Configurations can be imported using the file system ID of either the source or destination file system. When importing, the `availability_zone_name` and `kms_key_id` attributes must **not** be set in the configuration. The AWS API does not return these values when querying the replication configuration and their presence will therefore show as a diff in a subsequent plan. + +``` +$ terraform import aws_efs_replication_configuration.example fs-id +``` diff --git a/website/docs/r/elasticache_global_replication_group.html.markdown b/website/docs/r/elasticache_global_replication_group.html.markdown index 659ae612279..afc09469de1 100644 --- a/website/docs/r/elasticache_global_replication_group.html.markdown +++ b/website/docs/r/elasticache_global_replication_group.html.markdown @@ -44,13 +44,76 @@ resource "aws_elasticache_replication_group" "secondary" { } ``` +### Managing Redis Engine Versions + +The initial Redis version is determined by the version set on the primary replication group. +However, once it is part of a Global Replication Group, +the Global Replication Group manages the version of all member replication groups. + +The member replication groups must have [`lifecycle.ignore_changes[engine_version]`](https://www.terraform.io/language/meta-arguments/lifecycle) set, +or Terraform will always return a diff. + +In this example, +the primary replication group will be created with Redis 6.0, +and then upgraded to Redis 6.2 once added to the Global Replication Group. +The secondary replication group will be created with Redis 6.2. + +```terraform +resource "aws_elasticache_global_replication_group" "example" { + global_replication_group_id_suffix = "example" + primary_replication_group_id = aws_elasticache_replication_group.primary.id + + engine_version = "6.2" +} + +resource "aws_elasticache_replication_group" "primary" { + replication_group_id = "example-primary" + replication_group_description = "primary replication group" + + engine = "redis" + engine_version = "6.0" + node_type = "cache.m5.large" + + number_cache_clusters = 1 + + lifecycle { + ignore_changes = [engine_version] + } +} + +resource "aws_elasticache_replication_group" "secondary" { + provider = aws.other_region + + replication_group_id = "example-secondary" + replication_group_description = "secondary replication group" + global_replication_group_id = aws_elasticache_global_replication_group.example.global_replication_group_id + + number_cache_clusters = 1 + + lifecycle { + ignore_changes = [engine_version] + } +} +``` + ## Argument Reference The following arguments are supported: +* `engine_version` - (Optional) Redis version to use for the Global Replication Group. + When creating, by default the Global Replication Group inherits the version of the primary replication group. + If a version is specified, the Global Replication Group and all member replication groups will be upgraded to this version. + Cannot be downgraded without replacing the Global Replication Group and all member replication groups. + If the version is 6 or higher, the major and minor version can be set, e.g., `6.2`, + or the minor version can be unspecified which will use the latest version at creation time, e.g., `6.x`. + The actual engine version used is returned in the attribute `engine_version_actual`, see [Attributes Reference](#attributes-reference) below. * `global_replication_group_id_suffix` – (Required) The suffix name of a Global Datastore. If `global_replication_group_id_suffix` is changed, creates a new resource. * `primary_replication_group_id` – (Required) The ID of the primary cluster that accepts writes and will replicate updates to the secondary cluster. If `primary_replication_group_id` is changed, creates a new resource. * `global_replication_group_description` – (Optional) A user-created description for the global replication group. +* `parameter_group_name` - (Optional) An ElastiCache Parameter Group to use for the Global Replication Group. + Required when upgrading a major engine version, but will be ignored if left configured after the upgrade is complete. + Specifying without a major version upgrade will fail. + Note that ElastiCache creates a copy of this parameter group for each member replication group. ## Attributes Reference diff --git a/website/docs/r/emr_instance_group.html.markdown b/website/docs/r/emr_instance_group.html.markdown index 7afbcf6d063..085b587809c 100644 --- a/website/docs/r/emr_instance_group.html.markdown +++ b/website/docs/r/emr_instance_group.html.markdown @@ -83,5 +83,5 @@ In addition to all arguments above, the following attributes are exported: EMR task instance group can be imported using their EMR Cluster id and Instance Group id separated by a forward-slash `/`, e.g., ``` -$ terraform import aws_emr_instance_group.task_greoup j-123456ABCDEF/ig-15EK4O09RZLNR +$ terraform import aws_emr_instance_group.task_group j-123456ABCDEF/ig-15EK4O09RZLNR ``` diff --git a/website/docs/r/emrserverless_application.markdown b/website/docs/r/emrserverless_application.markdown new file mode 100644 index 00000000000..367a1d760e1 --- /dev/null +++ b/website/docs/r/emrserverless_application.markdown @@ -0,0 +1,126 @@ +--- +subcategory: "EMR Serverless" +layout: "aws" +page_title: "AWS: aws_emrserverless_application" +description: |- + Manages an EMR Serverless Application +--- + +# Resource: aws_emrserverless_application + +Manages an EMR Serverless Application. + +## Example Usage + +### Basic Usage + +```terraform +resource "aws_emrserverless_application" "example" { + name = "example" + release_label = "emr-6.6.0" + type = "hive" +} +``` + +### Initial Capacity Usage + +```terraform +resource "aws_emrserverless_application" "example" { + name = "example" + release_label = "emr-6.6.0" + type = "hive" + + initial_capacity { + initial_capacity_type = "HiveDriver" + + initial_capacity_config { + worker_count = 1 + worker_configuration { + cpu = "2 vCPU" + memory = "10 GB" + } + } + } +} +``` + +### Maximum Capacity Usage + +```terraform +resource "aws_emrserverless_application" "example" { + name = "example" + release_label = "emr-6.6.0" + type = "hive" + + maximum_capacity { + cpu = "2 vCPU" + memory = "10 GB" + } +} +``` + +## Argument Reference + +The following arguments are required: + +* `auto_start_configuration` – (Optional) The configuration for an application to automatically start on job submission. +* `auto_stop_configuration` – (Optional) The configuration for an application to automatically stop after a certain amount of time being idle. +* `initial_capacity` – (Optional) The capacity to initialize when the application is created. +* `maximum_capacity` – (Optional) The maximum capacity to allocate when the application is created. This is cumulative across all workers at any given point in time, not just when an application is created. No new resources will be created once any one of the defined limits is hit. +* `name` – (Required) The name of the application. +* `network_configuration` – (Optional) The network configuration for customer VPC connectivity. +* `release_label` – (Required) The EMR release version associated with the application. +* `type` – (Required) The type of application you want to start, such as `spark` or `hive`. +* `tags` - (Optional) Key-value mapping of resource tags. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +### auto_start_configuration Arguments + +* `enabled` - (Optional) Enables the application to automatically start on job submission. Defaults to `true`. + +### auto_stop_configuration Arguments + +* `enabled` - (Optional) Enables the application to automatically stop after a certain amount of time being idle. Defaults to `true`. +* `idle_timeout_minutes` - (Optional) The amount of idle time in minutes after which your application will automatically stop. Defaults to `15` minutes. + +### initial_capacity Arguments + +* `initial_capacity_config` - (Optional) The initial capacity configuration per worker. +* `initial_capacity_type` - (Required) The worker type for an analytics framework. For Spark applications, the key can either be set to `Driver` or `Executor`. For Hive applications, it can be set to `HiveDriver` or `TezTask`. + +### maximum_capacity Arguments + +* `cpu` - (Required) The maximum allowed CPU for an application. +* `disk` - (Optional) The maximum allowed disk for an application. +* `memory` - (Required) The maximum allowed resources for an application. + +### network_configuration Arguments + +* `security_group_ids` - (Optional) The array of security group Ids for customer VPC connectivity. +* `subnet_ids` - (Optional) The array of subnet Ids for customer VPC connectivity. + +#### initial_capacity_config Arguments + +* `worker_configuration` - (Optional) The resource configuration of the initial capacity configuration. +* `worker_count` - (Required) The number of workers in the initial capacity configuration. + +##### worker_configuration Arguments + +* `cpu` - (Required) The CPU requirements for every worker instance of the worker type. +* `disk` - (Optional) The disk requirements for every worker instance of the worker type. +* `memory` - (Required) The memory requirements for every worker instance of the worker type. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - ARN of the cluster. +* `id` - The ID of the cluster. +* `tags_all` - Map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block). + +## Import + +EMR Severless applications can be imported using the `id`, e.g. + +``` +$ terraform import aws_emrserverless_application.example id +``` diff --git a/website/docs/r/glue_crawler.html.markdown b/website/docs/r/glue_crawler.html.markdown index 31ea8d4a6c3..05097fb606d 100644 --- a/website/docs/r/glue_crawler.html.markdown +++ b/website/docs/r/glue_crawler.html.markdown @@ -205,7 +205,7 @@ The following arguments are supported: ### Recrawl Policy -* `recrawl_behavior` - (Optional) Specifies whether to crawl the entire dataset again or to crawl only folders that were added since the last crawler run. Valid Values are: `CRAWL_EVERYTHING` and `CRAWL_NEW_FOLDERS_ONLY`. Default value is `CRAWL_EVERYTHING`. +* `recrawl_behavior` - (Optional) Specifies whether to crawl the entire dataset again, crawl only folders that were added since the last crawler run, or crawl what S3 notifies the crawler of via SQS. Valid Values are: `CRAWL_EVENT_MODE`, `CRAWL_EVERYTHING` and `CRAWL_NEW_FOLDERS_ONLY`. Default value is `CRAWL_EVERYTHING`. ## Attributes Reference diff --git a/website/docs/r/guardduty_detector.html.markdown b/website/docs/r/guardduty_detector.html.markdown index 846e6ddd03b..23b8e440471 100644 --- a/website/docs/r/guardduty_detector.html.markdown +++ b/website/docs/r/guardduty_detector.html.markdown @@ -22,6 +22,11 @@ resource "aws_guardduty_detector" "MyDetector" { s3_logs { enable = true } + kubernetes { + audit_logs { + enable = false + } + } } } ``` @@ -39,13 +44,31 @@ The following arguments are supported: The `datasources` block supports the following: -* `s3_logs` - (Optional) Describes whether S3 data event logs are enabled as a data source. See [S3 Logs](#s3-logs) below for more details. +* `s3_logs` - (Optional) Configures [S3 protection](https://docs.aws.amazon.com/guardduty/latest/ug/s3-protection.html). + See [S3 Logs](#s3-logs) below for more details. +* `kubernetes` - (Optional) Configures [Kubernetes protection](https://docs.aws.amazon.com/guardduty/latest/ug/kubernetes-protection.html). + See [Kubernetes](#kubernetes) and [Kubernetes Audit Logs](#kubernetes-audit-logs) below for more details. ### S3 Logs -This `s3_logs` block supports the following: +The `s3_logs` block supports the following: + +* `enable` - (Required) If true, enables [S3 protection](https://docs.aws.amazon.com/guardduty/latest/ug/s3-protection.html). + Defaults to `true`. + +### Kubernetes + +The `kubernetes` block supports the following: + +* `audit_logs` - (Required) Configures Kubernetes audit logs as a data source for [Kubernetes protection](https://docs.aws.amazon.com/guardduty/latest/ug/kubernetes-protection.html). + See [Kubernetes Audit Logs](#kubernetes-audit-logs) below for more details. + +### Kubernetes Audit Logs + +The `audit_logs` block supports the following: -* `enable` - (Required) If true, enables [S3 Protection](https://docs.aws.amazon.com/guardduty/latest/ug/s3_detection.html). Defaults to `true`. +* `enable` - (Required) If true, enables Kubernetes audit logs as a data source for [Kubernetes protection](https://docs.aws.amazon.com/guardduty/latest/ug/kubernetes-protection.html). + Defaults to `true`. ## Attributes Reference diff --git a/website/docs/r/imagebuilder_distribution_configuration.html.markdown b/website/docs/r/imagebuilder_distribution_configuration.html.markdown index 19a2eef861e..0a4c84dca9a 100644 --- a/website/docs/r/imagebuilder_distribution_configuration.html.markdown +++ b/website/docs/r/imagebuilder_distribution_configuration.html.markdown @@ -24,15 +24,15 @@ resource "aws_imagebuilder_distribution_configuration" "example" { name = "example-{{ imagebuilder:buildDate }}" - launch_template_configuration { - launch_template_id = "lt-0aaa1bcde2ff3456" - } - launch_permission { user_ids = ["123456789012"] } } + launch_template_configuration { + launch_template_id = "lt-0aaa1bcde2ff3456" + } + region = "us-east-1" } } diff --git a/website/docs/r/instance.html.markdown b/website/docs/r/instance.html.markdown index a5019c141cf..fe7c44763f9 100644 --- a/website/docs/r/instance.html.markdown +++ b/website/docs/r/instance.html.markdown @@ -101,6 +101,7 @@ The following arguments are supported: * `cpu_core_count` - (Optional) Sets the number of CPU cores for an instance. This option is only supported on creation of instance type that support CPU Options [CPU Cores and Threads Per CPU Core Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html#cpu-options-supported-instances-values) - specifying this option for unsupported instance types will return an error from the EC2 API. * `cpu_threads_per_core` - (Optional - has no effect unless `cpu_core_count` is also set) If set to to 1, hyperthreading is disabled on the launched instance. Defaults to 2 if not set. See [Optimizing CPU Options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) for more information. * `credit_specification` - (Optional) Configuration block for customizing the credit specification of the instance. See [Credit Specification](#credit-specification) below for more details. Terraform will only perform drift detection of its value when present in a configuration. Removing this configuration on existing instances will only stop managing it. It will not change the configuration back to the default for the instance type. +* `disable_api_stop` - (Optional) If true, enables [EC2 Instance Stop Protection](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html#Using_StopProtection). * `disable_api_termination` - (Optional) If true, enables [EC2 Instance Termination Protection](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#Using_ChangingDisableAPITermination). * `ebs_block_device` - (Optional) One or more configuration blocks with additional EBS block devices to attach to the instance. Block device configurations only apply on resource creation. See [Block Devices](#ebs-ephemeral-and-root-block-devices) below for details on attributes and drift detection. When accessing this as an attribute reference, it is a set of objects. * `ebs_optimized` - (Optional) If true, the launched EC2 instance will be EBS-optimized. Note that if this is not set on an instance type that is optimized by default then this will show as disabled but if the instance type is optimized by default then there is no need to set this and there is no effect to disabling it. See the [EBS Optimized section](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html) of the AWS User Guide for more information. @@ -123,6 +124,7 @@ The following arguments are supported: * `network_interface` - (Optional) Customize network interfaces to be attached at instance boot time. See [Network Interfaces](#network-interfaces) below for more details. * `placement_group` - (Optional) Placement Group to start the instance in. * `placement_partition_number` - (Optional) The number of the partition the instance is in. Valid only if [the `aws_placement_group` resource's](placement_group.html) `strategy` argument is set to `"partition"`. +* `private_dns_name_options` - (Optional) The options for the instance hostname. The default values are inherited from the subnet. See [Private DNS Name Options](#private-dns-name-options) below for more details. * `private_ip` - (Optional) Private IP address to associate with the instance in a VPC. * `root_block_device` - (Optional) Configuration block to customize details about the root block device of the instance. See [Block Devices](#ebs-ephemeral-and-root-block-devices) below for details. When accessing this as an attribute reference, it is a list containing one object. * `secondary_private_ips` - (Optional) A list of secondary private IPv4 addresses to assign to the instance's primary network interface (eth0) in a VPC. Can only be assigned to the primary network interface (eth0) attached at instance creation, not a pre-existing network interface i.e., referenced in a `network_interface` block. Refer to the [Elastic network interfaces documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) to see the maximum number of private IP addresses allowed per instance type. @@ -265,6 +267,14 @@ Each `network_interface` block supports the following: * `network_card_index` - (Optional) Integer index of the network card. Limited by instance type. The default index is `0`. * `network_interface_id` - (Required) ID of the network interface to attach. +### Private DNS Name Options + +The `private_dns_name_options` block supports the following: + +* `enable_resource_name_dns_aaaa_record` - Indicates whether to respond to DNS queries for instance hostnames with DNS AAAA records. +* `enable_resource_name_dns_a_record` - Indicates whether to respond to DNS queries for instance hostnames with DNS A records. +* `hostname_type` - The type of hostname for Amazon EC2 instances. For IPv4 only subnets, an instance DNS name must be based on the instance IPv4 address. For IPv6 native subnets, an instance DNS name must be based on the instance ID. For dual-stack subnets, you can specify whether DNS names use the instance IPv4 address or the instance ID. Valid values: `ip-name` and `resource-name`. + ### Launch Template Specification -> **Note:** Launch Template parameters will be used only once during instance creation. If you want to update existing instance you need to change parameters diff --git a/website/docs/r/kendra_experience.html.markdown b/website/docs/r/kendra_experience.html.markdown new file mode 100644 index 00000000000..4d952ed2e07 --- /dev/null +++ b/website/docs/r/kendra_experience.html.markdown @@ -0,0 +1,100 @@ +--- +subcategory: "Kendra" +layout: "aws" +page_title: "AWS: aws_kendra_experience" +description: |- + Terraform resource for managing an AWS Kendra Experience. +--- + +# Resource: aws_kendra_experience + +Terraform resource for managing an AWS Kendra Experience. + +## Example Usage + +### Basic Usage + +```terraform +resource "aws_kendra_experience" "example" { + index_id = aws_kendra_index.example.id + description = "My Kendra Experience" + name = "example" + role_arn = aws_iam_role.example.arn + + configuration { + content_source_configuration { + direct_put_content = true + faq_ids = [aws_kendra_faq.example.faq_id] + } + user_identity_configuration { + identity_attribute_name = "12345ec453-1546651e-79c4-4554-91fa-00b43ccfa245" + } + } +} +``` + +## Argument Reference + +~> **NOTE:** By default of the AWS Kendra API, updates to an existing `aws_kendra_experience` resource (e.g. updating the `name`) will also update the `configuration.content_source_configuration.direct_put_content` parameter to `false` if not already provided. + +The following arguments are required: + +* `index_id` - (Required, Forces new resource) The identifier of the index for your Amazon Kendra experience. +* `name` - (Required) A name for your Amazon Kendra experience. +* `role_arn` - (Required) The Amazon Resource Name (ARN) of a role with permission to access `Query API`, `QuerySuggestions API`, `SubmitFeedback API`, and `AWS SSO` that stores your user and group information. For more information, see [IAM roles for Amazon Kendra](https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html). + +The following arguments are optional: + +* `description` - (Optional, Forces new resource if removed) A description for your Amazon Kendra experience. +* `configuration` - (Optional) Configuration information for your Amazon Kendra experience. Terraform will only perform drift detection of its value when present in a configuration. [Detailed below](#configuration). + +### `configuration` + +~> **NOTE:** By default of the AWS Kendra API, the `content_source_configuration.direct_put_content` parameter will be set to `false` if not provided. + +The `configuration` configuration block supports the following arguments: + +* `content_source_configuration` - (Optional, Required if `user_identity_configuration` not provided) The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed via the `BatchPutDocument API`. Terraform will only perform drift detection of its value when present in a configuration. [Detailed below](#content_source_configuration). +* `user_identity_configuration` - (Optional, Required if `content_source_configuration` not provided) The AWS SSO field name that contains the identifiers of your users, such as their emails. [Detailed below](#user_identity_configuration). + +### `content_source_configuration` + +The `content_source_configuration` configuration block supports the following arguments: + +* `data_source_ids` - (Optional) The identifiers of the data sources you want to use for your Amazon Kendra experience. Maximum number of 100 items. +* `direct_put_content` - (Optional) Whether to use documents you indexed directly using the `BatchPutDocument API`. Defaults to `false`. +* `faq_ids` - (Optional) The identifier of the FAQs that you want to use for your Amazon Kendra experience. Maximum number of 100 items. + +### `user_identity_configuration` + +The `user_identity_configuration` configuration block supports the following argument: + +* `identity_attribute_name` - (Required) The AWS SSO field name that contains the identifiers of your users, such as their emails. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The unique identifiers of the experience and index separated by a slash (`/`). +* `arn` - ARN of the Experience. +* `endpoints` - Shows the endpoint URLs for your Amazon Kendra experiences. The URLs are unique and fully hosted by AWS. + * `endpoint` - The endpoint of your Amazon Kendra experience. + * `endpoint_type` - The type of endpoint for your Amazon Kendra experience. +* `experience_id` - The unique identifier of the experience. +* `status` - The current processing status of your Amazon Kendra experience. + +## Timeouts + +`aws_kendra_experience` provides the following [Timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) configuration options: + +* `create` - (Optional, Default: `30m`) +* `update` - (Optional, Default: `30m`) +* `delete` - (Optional, Default: `30m`) + +## Import + +Kendra Experience can be imported using the unique identifiers of the experience and index separated by a slash (`/`) e.g., + +``` +$ terraform import aws_kendra_experience.example 1045d08d-66ef-4882-b3ed-dfb7df183e90/b34dfdf7-1f2b-4704-9581-79e00296845f +``` diff --git a/website/docs/r/kendra_faq.html.markdown b/website/docs/r/kendra_faq.html.markdown new file mode 100644 index 00000000000..8807eb9b0e7 --- /dev/null +++ b/website/docs/r/kendra_faq.html.markdown @@ -0,0 +1,113 @@ +--- +subcategory: "Kendra" +layout: "aws" +page_title: "AWS: aws_kendra_faq" +description: |- + Terraform resource for managing an AWS Kendra FAQ. +--- + +# Resource: aws_kendra_faq + +Terraform resource for managing an AWS Kendra FAQ. + +## Example Usage + +### Basic + +```terraform +resource "aws_kendra_faq" "example" { + index_id = aws_kendra_index.example.id + name = "Example" + role_arn = aws_iam_role.example.arn + + source_s3_path { + bucket = aws_s3_bucket.example.id + key = aws_s3_object.example.key + } + + tags = { + Name = "Example Kendra Faq" + } +} +``` + +### With File Format + +```terraform +resource "aws_kendra_faq" "example" { + index_id = aws_kendra_index.example.id + name = "Example" + file_format = "CSV" + role_arn = aws_iam_role.example.arn + + source_s3_path { + bucket = aws_s3_bucket.example.id + key = aws_s3_object.example.key + } +} +``` + +### With Language Code + +```terraform +resource "aws_kendra_faq" "example" { + index_id = aws_kendra_index.example.id + name = "Example" + language_code = "en" + role_arn = aws_iam_role.example.arn + + source_s3_path { + bucket = aws_s3_bucket.example.id + key = aws_s3_object.example.key + } +} +``` + +## Argument Reference + +The following arguments are required: + +* `index_id`- (Required, Forces new resource) The identifier of the index for a FAQ. +* `name` - (Required, Forces new resource) The name that should be associated with the FAQ. +* `role_arn` - (Required, Forces new resource) The Amazon Resource Name (ARN) of a role with permission to access the S3 bucket that contains the FAQs. For more information, see [IAM Roles for Amazon Kendra](https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html). +* `s3_path` - (Required, Forces new resource) The S3 location of the FAQ input data. Detailed below. + +The `s3_path` configuration block supports the following arguments: + +* `bucket` - (Required, Forces new resource) The name of the S3 bucket that contains the file. +* `key` - (Required, Forces new resource) The name of the file. + +The following arguments are optional: + +* `description` - (Optional, Forces new resource) The description for a FAQ. +* `file_format` - (Optional, Forces new resource) The file format used by the input files for the FAQ. Valid Values are `CSV`, `CSV_WITH_HEADER`, `JSON`. +* `language_code` - (Optional, Forces new resource) The code for a language. This shows a supported language for the FAQ document. English is supported by default. For more information on supported languages, including their codes, see [Adding documents in languages other than English](https://docs.aws.amazon.com/kendra/latest/dg/in-adding-languages.html). +* `tags` - (Optional) Key-value map of resource tags. If configured with a provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - ARN of the FAQ. +* `created_at` - The Unix datetime that the FAQ was created. +* `error_message` - When the Status field value is `FAILED`, this contains a message that explains why. +* `faq_id` - The identifier of the FAQ. +* `id` - The unique identifiers of the FAQ and index separated by a slash (`/`) +* `status` - The status of the FAQ. It is ready to use when the status is ACTIVE. +* `updated_at` - The date and time that the FAQ was last updated. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block). + +## Timeouts + +`aws_kendra_faq` provides the following [Timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) configuration options: + +* `create` - (Optional, Default: `30m`) +* `delete` - (Optional, Default: `30m`) + +## Import + +`aws_kendra_faq` can be imported using the unique identifiers of the FAQ and index separated by a slash (`/`), e.g., + +``` +$ terraform import aws_kendra_faq.example faq-123456780/idx-8012925589 +``` diff --git a/website/docs/r/kendra_index.html.markdown b/website/docs/r/kendra_index.html.markdown new file mode 100644 index 00000000000..10e873c7c15 --- /dev/null +++ b/website/docs/r/kendra_index.html.markdown @@ -0,0 +1,187 @@ +--- +subcategory: "Kendra" +layout: "aws" +page_title: "AWS: aws_kendra_index" +description: |- + Provides an Amazon Kendra Index resource. +--- + +# Resource: aws_kendra_index + +Provides an Amazon Kendra Index resource. + +## Example Usage + +### Basic + +```terraform +resource "aws_kendra_index" "example" { + name = "example" + description = "example" + edition = "DEVELOPER_EDITION" + role_arn = aws_iam_role.this.arn + + tags = { + "Key1" = "Value1" + } +} +``` + +### With capacity units + +```terraform +resource "aws_kendra_index" "example" { + name = "example" + edition = "DEVELOPER_EDITION" + role_arn = aws_iam_role.this.arn + + capacity_units { + query_capacity_units = 2 + storage_capacity_units = 2 + } +} +``` + +### With server side encryption configuration + +```terraform +resource "aws_kendra_index" "example" { + name = "example" + role_arn = aws_iam_role.this.arn + + server_side_encryption_configuration { + kms_key_id = data.aws_kms_key.this.arn + } +} +``` + +### With JSON token type configuration + +```terraform +resource "aws_kendra_index" "example" { + name = "example" + role_arn = aws_iam_role.this.arn + + user_token_configurations { + json_token_type_configuration { + group_attribute_field = "groups" + user_name_attribute_field = "username" + } + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `capacity_units` - (Optional) A block that sets the number of additional document storage and query capacity units that should be used by the index. +* `description` - (Optional) The description of the Index. +* `edition` - (Optional) The Amazon Kendra edition to use for the index. Choose `DEVELOPER_EDITION` for indexes intended for development, testing, or proof of concept. Use `ENTERPRISE_EDITION` for your production databases. Once you set the edition for an index, it can't be changed. Defaults to `ENTERPRISE_EDITION` +* `name` - (Required) Specifies the name of the Index. +* `role_arn` - (Required) An AWS Identity and Access Management (IAM) role that gives Amazon Kendra permissions to access your Amazon CloudWatch logs and metrics. This is also the role you use when you call the `BatchPutDocument` API to index documents from an Amazon S3 bucket. +* `server_side_encryption_configuration` - (Optional) A block that specifies the identifier of the AWS KMS customer managed key (CMK) that's used to encrypt data indexed by Amazon Kendra. Amazon Kendra doesn't support asymmetric CMKs. Documented below. +* `user_context_policy` - (Optional) The user context policy. Valid values are `ATTRIBUTE_FILTER` or `USER_TOKEN`. For more information, refer to [UserContextPolicy](https://docs.aws.amazon.com/kendra/latest/dg/API_CreateIndex.html#Kendra-CreateIndex-request-UserContextPolicy). Defaults to `ATTRIBUTE_FILTER`. +* `user_group_resolution_configuration` - (Optional) A block that enables fetching access levels of groups and users from an AWS Single Sign-On identity source. To configure this, see [UserGroupResolutionConfiguration](https://docs.aws.amazon.com/kendra/latest/dg/API_UserGroupResolutionConfiguration.html). Documented below. +* `user_token_configurations` - (Optional) A block that specifies the user token configuration. Documented below. +* `tags` - (Optional) Tags to apply to the Index. If configured with a provider +[`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +A `capacity_units` block supports the following arguments: + +* `query_capacity_units` - (Required) The amount of extra query capacity for an index and GetQuerySuggestions capacity. For more information, refer to [QueryCapacityUnits](https://docs.aws.amazon.com/kendra/latest/dg/API_CapacityUnitsConfiguration.html#Kendra-Type-CapacityUnitsConfiguration-QueryCapacityUnits). +* `storage_capacity_units` - (Required) The amount of extra storage capacity for an index. A single capacity unit provides 30 GB of storage space or 100,000 documents, whichever is reached first. Minimum value of 0. + +A `server_side_encryption_configuration` block supports the following arguments: + +* `kms_key_id` - (Optional) The identifier of the AWS KMScustomer master key (CMK). Amazon Kendra doesn't support asymmetric CMKs. + +A `user_group_resolution_configuration` block supports the following arguments: + +* `user_group_resolution_mode` - (Required) The identity store provider (mode) you want to use to fetch access levels of groups and users. AWS Single Sign-On is currently the only available mode. Your users and groups must exist in an AWS SSO identity source in order to use this mode. Valid Values are `AWS_SSO` or `NONE`. + +A `user_token_configurations` block supports the following arguments: + +* `json_token_type_configuration` - (Optional) A block that specifies the information about the JSON token type configuration. +* `jwt_token_type_configuration` - (Optional) A block that specifies the information about the JWT token type configuration. + +A `json_token_type_configuration` block supports the following arguments: + +* `group_attribute_field` - (Required) The group attribute field. Minimum length of 1. Maximum length of 2048. +* `user_name_attribute_field` - (Required) The user name attribute field. Minimum length of 1. Maximum length of 2048. + +A `jwt_token_type_configuration` block supports the following arguments: + +* `claim_regex` - (Optional) The regular expression that identifies the claim. Minimum length of 1. Maximum length of 100. +* `group_attribute_field` - (Optional) The group attribute field. Minimum length of 1. Maximum length of 100. +* `issuer` - (Optional) The issuer of the token. Minimum length of 1. Maximum length of 65. +* `key_location` - (Required) The location of the key. Valid values are `URL` or `SECRET_MANAGER` +* `secrets_manager_arn` - (Optional) The Amazon Resource Name (ARN) of the secret. +* `url` - (Optional) The signing key URL. Valid pattern is `^(https?|ftp|file):\/\/([^\s]*)` +* `user_name_attribute_field` - (Optional) The user name attribute field. Minimum length of 1. Maximum length of 100. + +### Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) for certain actions: + +* `create` - (Defaults to 40 mins) Used when creating the index. +* `delete` - (Defaults to 40 mins) Used when deleting the index. +* `update` - (Defaults to 40 mins) Used when updating the index. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - The Amazon Resource Name (ARN) of the Index. +* `created_at` - The Unix datetime that the index was created. +* `document_metadata_configuration_updates` - One or more blocks that specify the configuration settings for any metadata applied to the documents in the index. Documented below. +* `error_message` - When the Status field value is `FAILED`, this contains a message that explains why. +* `id` - The identifier of the Index. +* `index_statistics` - A block that provides information about the number of FAQ questions and answers and the number of text documents indexed. Documented below. +* `status` - The current status of the index. When the value is `ACTIVE`, the index is ready for use. If the Status field value is `FAILED`, the `error_message` field contains a message that explains why. +* `updated_at` - The Unix datetime that the index was last updated. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block). + +A `document_metadata_configuration_updates` block supports the following attributes: + +* `name` - The name of the index field. Minimum length of 1. Maximum length of 30. +* `relevance` - A block that provides manual tuning parameters to determine how the field affects the search results. Documented below. +* `search` - A block that provides information about how the field is used during a search. Documented below. +* `type` - The data type of the index field. Valid values are `STRING_VALUE`, `STRING_LIST_VALUE`, `LONG_VALUE`, `DATE_VALUE`. + +A `relevance` block supports the following attributes: + +* `duration` - Specifies the time period that the boost applies to. For more information, refer to [Duration](https://docs.aws.amazon.com/kendra/latest/dg/API_Relevance.html#Kendra-Type-Relevance-Duration). +* `freshness` - Indicates that this field determines how "fresh" a document is. For more information, refer to [Freshness](https://docs.aws.amazon.com/kendra/latest/dg/API_Relevance.html#Kendra-Type-Relevance-Freshness). +* `importance` - The relative importance of the field in the search. Larger numbers provide more of a boost than smaller numbers. Minimum value of 1. Maximum value of 10. +* `rank_order` - Determines how values should be interpreted. For more information, refer to [RankOrder](https://docs.aws.amazon.com/kendra/latest/dg/API_Relevance.html#Kendra-Type-Relevance-RankOrder). +* `values_importance_map` - A list of values that should be given a different boost when they appear in the result list. For more information, refer to [ValueImportanceMap](https://docs.aws.amazon.com/kendra/latest/dg/API_Relevance.html#Kendra-Type-Relevance-ValueImportanceMap). + +A `search` block supports the following attributes: + +* `displayable` - Determines whether the field is returned in the query response. The default is `true`. +* `facetable` - Indicates that the field can be used to create search facets, a count of results for each value in the field. The default is `false`. +* `searchable` - Determines whether the field is used in the search. If the Searchable field is true, you can use relevance tuning to manually tune how Amazon Kendra weights the field in the search. The default is `true` for `string` fields and `false` for `number` and `date` fields. +* `sortable` - Determines whether the field can be used to sort the results of a query. If you specify sorting on a field that does not have Sortable set to true, Amazon Kendra returns an exception. The default is `false`. + +A `index_statistics` block supports the following attributes: + +* `faq_statistics` - A block that specifies the number of question and answer topics in the index. Documented below. +* `text_document_statistics` - A block that specifies the number of text documents indexed. + +A `faq_statistics` block supports the following attributes: + +* `indexed_question_answers_count` - The total number of FAQ questions and answers contained in the index. + +A `text_document_statistics` block supports the following attributes: + +* `indexed_text_bytes` - The total size, in bytes, of the indexed documents. +* `indexed_text_documents_count` - The number of text documents indexed. + +## Import + +Amazon Kendra Indexes can be imported using its `id`, e.g., + +``` +$ terraform import aws_kendra_index.example 12345678-1234-5678-9123-123456789123 +``` diff --git a/website/docs/r/kendra_query_suggestions_block_list.html.markdown b/website/docs/r/kendra_query_suggestions_block_list.html.markdown new file mode 100644 index 00000000000..db725558c9f --- /dev/null +++ b/website/docs/r/kendra_query_suggestions_block_list.html.markdown @@ -0,0 +1,75 @@ +--- +subcategory: "Kendra" +layout: "aws" +page_title: "AWS: aws_kendra_query_suggestions_block_list" +description: |- + Terraform resource for managing an AWS Kendra block list used for query suggestions for an index +--- + +# Resource: aws_kendra_query_suggestions_block_list + +Terraform resource for managing an AWS Kendra block list used for query suggestions for an index. + +## Example Usage + +### Basic Usage + +```terraform +resource "aws_kendra_query_suggestions_block_list" "example" { + index_id = aws_kendra_index.example.id + name = "Example" + role_arn = aws_iam_role.example.arn + + source_s3_path { + bucket = aws_s3_bucket.example.id + key = "example/suggestions.txt" + } + + tags = { + Name = "Example Kendra Index" + } +} +``` + +## Argument Reference + +The following arguments are required: + +* `index_id`- (Required, Forces new resource) The identifier of the index for a block list. +* `name` - (Required) The name for the block list. +* `role_arn` - (Required) The IAM (Identity and Access Management) role used to access the block list text file in S3. +* `source_s3_path` - (Required) The S3 path where your block list text file sits in S3. Detailed below. + +The `source_s3_path` configuration block supports the following arguments: + +* `bucket` - (Required) The name of the S3 bucket that contains the file. +* `key` - (Required) The name of the file. + +The following arguments are optional: + +* `description` - (Optional) The description for a block list. +* `tags` - (Optional) Key-value map of resource tags. If configured with a provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - ARN of the block list. +* `query_suggestions_block_list_id` - The unique indentifier of the block list. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block). + +## Timeouts + +`aws_kendra_query_suggestions_block_list` provides the following [Timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) configuration options: + +* `create` - (Optional, Default: `30m`) +* `update` - (Optional, Default: `30m`) +* `delete` - (Optional, Default: `30m`) + +## Import + +`aws_kendra_query_suggestions_block_list` can be imported using the unique identifiers of the block list and index separated by a slash (`/`), e.g., + +``` +$ terraform import aws_kendra_query_suggestions_block_list.example blocklist-123456780/idx-8012925589 +``` diff --git a/website/docs/r/kendra_thesaurus.html.markdown b/website/docs/r/kendra_thesaurus.html.markdown new file mode 100644 index 00000000000..116a7e3fed4 --- /dev/null +++ b/website/docs/r/kendra_thesaurus.html.markdown @@ -0,0 +1,74 @@ +--- +subcategory: "Kendra" +layout: "aws" +page_title: "AWS: aws_kendra_thesaurus" +description: |- + Terraform resource for managing an AWS Kendra Thesaurus. +--- + +# Resource: aws_kendra_thesaurus + +Terraform resource for managing an AWS Kendra Thesaurus. + +## Example Usage + +```terraform +resource "aws_kendra_thesaurus" "example" { + index_id = aws_kendra_index.example.id + name = "Example" + role_arn = aws_iam_role.example.arn + + source_s3_path { + bucket = aws_s3_bucket.example.id + key = aws_s3_object.example.key + } + + tags = { + Name = "Example Kendra Thesaurus" + } +} +``` + +## Argument Reference + +The following arguments are required: + +* `index_id`- (Required, Forces new resource) The identifier of the index for a thesaurus. +* `name` - (Required) The name for the thesaurus. +* `role_arn` - (Required) The IAM (Identity and Access Management) role used to access the thesaurus file in S3. +* `source_s3_path` - (Required) The S3 path where your thesaurus file sits in S3. Detailed below. + +The `source_s3_path` configuration block supports the following arguments: + +* `bucket` - (Required) The name of the S3 bucket that contains the file. +* `key` - (Required) The name of the file. + +The following arguments are optional: + +* `description` - (Optional) The description for a thesaurus. +* `tags` - (Optional) Key-value map of resource tags. If configured with a provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - ARN of the thesaurus. +* `id` - The unique identifiers of the thesaurus and index separated by a slash (`/`). +* `status` - The current status of the thesaurus. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block). + +## Timeouts + +`aws_kendra_thesaurus` provides the following [Timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) configuration options: + +* `create` - (Optional, Default: `30m`) +* `update` - (Optional, Default: `30m`) +* `delete` - (Optional, Default: `30m`) + +## Import + +`aws_kendra_thesaurus` can be imported using the unique identifiers of the thesaurus and index separated by a slash (`/`), e.g., + +``` +$ terraform import aws_kendra_thesaurus.example thesaurus-123456780/idx-8012925589 +``` diff --git a/website/docs/r/lakeformation_lf_tag.html.markdown b/website/docs/r/lakeformation_lf_tag.html.markdown new file mode 100644 index 00000000000..85d0ed7ee19 --- /dev/null +++ b/website/docs/r/lakeformation_lf_tag.html.markdown @@ -0,0 +1,42 @@ +--- +subcategory: "Lake Formation" +layout: "aws" +page_title: "AWS: aws_lakeformation_lf_tag" +description: |- + Creates a tag with the specified name and values. +--- + +# Resource: aws_lakeformation_lf_tag + +Creates an LF-Tag with the specified name and values. Each key must have at least one value. The maximum number of values permitted is 15. + +## Example Usage + +```terraform +resource "aws_lakeformation_lf_tag" "example" { + key = "module" + values = ["Orders", "Sales", "Customers"] +} +``` + +## Argument Reference + +The following arguments are supported: + +* `catalog_id` - (Optional) ID of the Data Catalog to create the tag in. If omitted, this defaults to the AWS Account ID. +* `key` - (Required) Key-name for the tag. +* `values` - (Required) List of possible values an attribute can take. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - Catalog ID and key-name of the tag + +## Import + +Lake Formation LF-Tags can be imported using the `catalog_id:key`. If you have not set a Catalog ID specify the AWS Account ID that the database is in, e.g. + +``` +$ terraform import aws_lakeformation_lf_tag.example 123456789012:some_key +``` diff --git a/website/docs/r/lakeformation_permissions.html.markdown b/website/docs/r/lakeformation_permissions.html.markdown index 18f7e326d19..d4c63e10526 100644 --- a/website/docs/r/lakeformation_permissions.html.markdown +++ b/website/docs/r/lakeformation_permissions.html.markdown @@ -8,7 +8,7 @@ description: |- # Resource: aws_lakeformation_permissions -Grants permissions to the principal to access metadata in the Data Catalog and data organized in underlying data storage such as Amazon S3. Permissions are granted to a principal, in a Data Catalog, relative to a Lake Formation resource, which includes the Data Catalog, databases, and tables. For more information, see [Security and Access Control to Metadata and Data in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/security-data-access.html). +Grants permissions to the principal to access metadata in the Data Catalog and data organized in underlying data storage such as Amazon S3. Permissions are granted to a principal, in a Data Catalog, relative to a Lake Formation resource, which includes the Data Catalog, databases, tables, LF-tags, and LF-tag policies. For more information, see [Security and Access Control to Metadata and Data in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/security-data-access.html). !> **WARNING:** Lake Formation permissions are not in effect by default within AWS. Using this resource will not secure your data and will result in errors if you do not change the security settings for existing resources and the default security settings for new resources. See [Default Behavior and `IAMAllowedPrincipals`](#default-behavior-and-iamallowedprincipals) for additional details. @@ -114,7 +114,7 @@ resource "aws_lakeformation_permissions" "example" { ```terraform resource "aws_lakeformation_permissions" "example" { - role = aws_iam_role.workflow_role.arn + principal = aws_iam_role.workflow_role.arn permissions = ["CREATE_TABLE", "ALTER", "DROP"] database { @@ -124,11 +124,31 @@ resource "aws_lakeformation_permissions" "example" { } ``` +### Grant Permissions Using Tag-Based Access Control + +```terraform +resource "aws_lakeformation_permissions" "test" { + role = aws_iam_role.sales_role.arn + permissions = ["CREATE_TABLE", "ALTER", "DROP"] + lf_tag_policy { + resource_type = "DATABASE" + expression { + key = "Team" + values = ["Sales"] + } + expression { + key = "Environment" + values = ["Dev", "Production"] + } + } +} +``` + ## Argument Reference The following arguments are required: -* `permissions` – (Required) List of permissions granted to the principal. Valid values may include `ALL`, `ALTER`, `CREATE_DATABASE`, `CREATE_TABLE`, `DATA_LOCATION_ACCESS`, `DELETE`, `DESCRIBE`, `DROP`, `INSERT`, and `SELECT`. For details on each permission, see [Lake Formation Permissions Reference](https://docs.aws.amazon.com/lake-formation/latest/dg/lf-permissions-reference.html). +* `permissions` – (Required) List of permissions granted to the principal. Valid values may include `ALL`, `ALTER`, `ASSOCIATE`, `CREATE_DATABASE`, `CREATE_TABLE`, `DATA_LOCATION_ACCESS`, `DELETE`, `DESCRIBE`, `DROP`, `INSERT`, and `SELECT`. For details on each permission, see [Lake Formation Permissions Reference](https://docs.aws.amazon.com/lake-formation/latest/dg/lf-permissions-reference.html). * `principal` – (Required) Principal to be granted the permissions on the resource. Supported principals include `IAM_ALLOWED_PRINCIPALS` (see [Default Behavior and `IAMAllowedPrincipals`](#default-behavior-and-iamallowedprincipals) above), IAM roles, users, groups, SAML groups and users, QuickSight groups, OUs, and organizations as well as AWS account IDs for cross-account permissions. For more information, see [Lake Formation Permissions Reference](https://docs.aws.amazon.com/lake-formation/latest/dg/lf-permissions-reference.html). ~> **NOTE:** We highly recommend that the `principal` _NOT_ be a Lake Formation administrator (granted using `aws_lakeformation_data_lake_settings`). The entity (e.g., IAM role) running Terraform will most likely need to be a Lake Formation administrator. As such, the entity will have implicit permissions and does not need permissions granted through this resource. @@ -138,6 +158,8 @@ One of the following is required: * `catalog_resource` - (Optional) Whether the permissions are to be granted for the Data Catalog. Defaults to `false`. * `data_location` - (Optional) Configuration block for a data location resource. Detailed below. * `database` - (Optional) Configuration block for a database resource. Detailed below. +* `lf_tag` - (Optional) Configuration block for an LF-tag resource. Detailed below. +* `lf_tag_policy` - (Optional) Configuration block for an LF-tag policy resource. Detailed below. * `table` - (Optional) Configuration block for a table resource. Detailed below. * `table_with_columns` - (Optional) Configuration block for a table with columns resource. Detailed below. @@ -166,6 +188,33 @@ The following argument is optional: * `catalog_id` - (Optional) Identifier for the Data Catalog. By default, it is the account ID of the caller. +### lf_tag + +The following arguments are required: + +* `key` – (Required) The key-name for the tag. +* `values` - (Required) A list of possible values an attribute can take. + +The following argument is optional: + +* `catalog_id` - (Optional) Identifier for the Data Catalog. By default, it is the account ID of the caller. + +### lf_tag_policy + +The following arguments are required: + +* `resource_type` – (Required) The resource type for which the tag policy applies. Valid values are `DATABASE` and `TABLE`. +* `expression` - (Required) A list of tag conditions that apply to the resource's tag policy. Configuration block for tag conditions that apply to the policy. See [`expression`](#expression) below. + +The following argument is optional: + +* `catalog_id` - (Optional) Identifier for the Data Catalog. By default, it is the account ID of the caller. + +#### expression + +* `key` – (Required) The key-name of an LF-Tag. +* `values` - (Required) A list of possible values of an LF-Tag. + ### table The following argument is required: diff --git a/website/docs/r/launch_template.html.markdown b/website/docs/r/launch_template.html.markdown index 361f9950f58..e1f27050f63 100644 --- a/website/docs/r/launch_template.html.markdown +++ b/website/docs/r/launch_template.html.markdown @@ -37,6 +37,7 @@ resource "aws_launch_template" "foo" { cpu_credits = "standard" } + disable_api_stop = true disable_api_termination = true ebs_optimized = true @@ -118,6 +119,7 @@ The following arguments are supported: Specification](#credit-specification) below for more details. * `default_version` - (Optional) Default Version of the launch template. * `description` - (Optional) Description of the launch template. +* `disable_api_stop` - (Optional) If true, enables [EC2 Instance Stop Protection](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html#Using_StopProtection). * `disable_api_termination` - (Optional) If `true`, enables [EC2 Instance Termination Protection](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#Using_ChangingDisableAPITermination) * `ebs_optimized` - (Optional) If `true`, the launched EC2 instance will be EBS-optimized. diff --git a/website/docs/r/lb_target_group.html.markdown b/website/docs/r/lb_target_group.html.markdown index 6546c6c8cb2..dc105a76f3d 100644 --- a/website/docs/r/lb_target_group.html.markdown +++ b/website/docs/r/lb_target_group.html.markdown @@ -57,8 +57,8 @@ resource "aws_lb_target_group" "lambda-example" { ### ALB Target Group ```terraform -resource "aws_lb_target_group" "lambda-example" { - name = "tf-example-lb-tg" +resource "aws_lb_target_group" "alb-example" { + name = "tf-example-lb-alb-tg" target_type = "alb" port = 80 protocol = "TCP" diff --git a/website/docs/r/lex_bot.html.markdown b/website/docs/r/lex_bot.html.markdown index 48f1ff33278..5a0ce9db0f5 100644 --- a/website/docs/r/lex_bot.html.markdown +++ b/website/docs/r/lex_bot.html.markdown @@ -62,7 +62,7 @@ The following arguments are supported: * `enable_model_improvements` - (Optional) Set to `true` to enable access to natural language understanding improvements. When you set the `enable_model_improvements` parameter to true you can use the `nlu_intent_confidence_threshold` parameter to configure confidence scores. For more information, see [Confidence Scores](https://docs.aws.amazon.com/lex/latest/dg/confidence-scores.html). You can only set the `enable_model_improvements` parameter in certain Regions. If you set the parameter to true, your bot has access to accuracy improvements. For more information see the [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-enableModelImprovements). * `idle_session_ttl_in_seconds` - (Optional) The maximum time in seconds that Amazon Lex retains the data gathered in a conversation. Default is `300`. Must be a number between 60 and 86400 (inclusive). * `locale` - (Optional) Specifies the target locale for the bot. Any intent used in the bot must be compatible with the locale of the bot. For available locales, see [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-locale). Default is `en-US`. -* `intent` - (Required) A set of Intent objects. Each intent represents a command that a user can express. Attributes are documented under [intent](#intent). Can have up to 100 Intent objects. +* `intent` - (Required) A set of Intent objects. Each intent represents a command that a user can express. Attributes are documented under [intent](#intent). Can have up to 250 Intent objects. * `name` - (Required) The name of the bot that you want to create, case sensitive. Must be between 2 and 50 characters in length. * `nlu_intent_confidence_threshold` - (Optional) Determines the threshold where Amazon Lex will insert the AMAZON.FallbackIntent, AMAZON.KendraSearchIntent, or both when returning alternative intents in a PostContent or PostText response. AMAZON.FallbackIntent and AMAZON.KendraSearchIntent are only inserted if they are configured for the bot. For more information see [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-nluIntentConfidenceThreshold) This value requires `enable_model_improvements` to be set to `true` and the default is `0`. Must be a float between 0 and 1. * `process_behavior` - (Optional) If you set the `process_behavior` element to `BUILD`, Amazon Lex builds the bot so that it can be run. If you set the element to `SAVE` Amazon Lex saves the bot, but doesn't build it. Default is `SAVE`. diff --git a/website/docs/r/lightsail_container_service.html.markdown b/website/docs/r/lightsail_container_service.html.markdown new file mode 100644 index 00000000000..4935bedbdd5 --- /dev/null +++ b/website/docs/r/lightsail_container_service.html.markdown @@ -0,0 +1,119 @@ +--- +subcategory: "Lightsail" +layout: "aws" +page_title: "AWS: aws_lightsail_container_service" +description: |- + Provides a resource to manage Lightsail container service +--- + +# Resource: aws_lightsail_container_service + +An Amazon Lightsail container service is a highly scalable compute and networking resource on which you can deploy, run, +and manage containers. For more information, see +[Container services in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-container-services). + +~> **Note:** For more information about the AWS Regions in which you can create Amazon Lightsail container services, +see ["Regions and Availability Zones in Amazon Lightsail"](https://lightsail.aws.amazon.com/ls/docs/overview/article/understanding-regions-and-availability-zones-in-amazon-lightsail). + +## Example Usage + +### Basic Usage + +```terraform +resource "aws_lightsail_container_service" "my_container_service" { + name = "container-service-1" + power = "nano" + scale = 1 + is_disabled = false + + tags = { + foo1 = "bar1" + foo2 = "" + } +} +``` + +### Public Domain Names + +```terraform +resource "aws_lightsail_container_service" "my_container_service" { + # ... other configuration ... + + public_domain_names { + certificate { + certificate_name = "example-certificate" + domain_names = [ + "www.example.com", + # maybe another domain name + ] + } + + # certificate { + # maybe another certificate + # } + } +} +``` + +## Argument Reference + +~> **NOTE:** You must create and validate an SSL/TLS certificate before you can use `public_domain_names` with your +container service. For more information, see +[Enabling and managing custom domains for your Amazon Lightsail container services](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-creating-container-services-certificates). + +The following arguments are supported: + +* `name` - (Required) The name for the container service. Names must be of length 1 to 63, and be + unique within each AWS Region in your Lightsail account. +* `power` - (Required) The power specification for the container service. The power specifies the amount of memory, + the number of vCPUs, and the monthly price of each node of the container service. + Possible values: `nano`, `micro`, `small`, `medium`, `large`, `xlarge`. +* `scale` - (Required) The scale specification for the container service. The scale specifies the allocated compute + nodes of the container service. +* `is_disabled` - (Optional) A Boolean value indicating whether the container service is disabled. Defaults to `false`. +* `public_domain_names` - (Optional) The public domain names to use with the container service, such as example.com + and www.example.com. You can specify up to four public domain names for a container service. The domain names that you + specify are used when you create a deployment with a container configured as the public endpoint of your container + service. If you don't specify public domain names, then you can use the default domain of the container service. + Defined below. +* `tags` - (Optional) Map of container service tags. To tag at launch, specify the tags in the Launch Template. If + configured with a provider + [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) + present, tags with matching keys will overwrite those defined at the provider-level. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - The Amazon Resource Name (ARN) of the container service. +* `availability_zone` - The Availability Zone. Follows the format us-east-2a (case-sensitive). +* `id` - Same as `name`. +* `power_id` - The ID of the power of the container service. +* `principal_arn`- The principal ARN of the container service. The principal ARN can be used to create a trust + relationship between your standard AWS account and your Lightsail container service. This allows you to give your + service permission to access resources in your standard AWS account. +* `private_domain_name` - The private domain name of the container service. The private domain name is accessible only + by other resources within the default virtual private cloud (VPC) of your Lightsail account. +* `region_name` - The AWS Region name. +* `resource_type` - The Lightsail resource type of the container service (i.e., ContainerService). +* `state` - The current state of the container service. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider + [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). +* `url` - The publicly accessible URL of the container service. If no public endpoint is specified in the + currentDeployment, this URL returns a 404 response. + +## Timeouts + +`aws_lightsail_container_service` provides the following [Timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) configuration options: + +* `create` - (Optional, Default: `30m`) +* `update` - (Optional, Default: `30m`) +* `delete` - (Optional, Default: `30m`) + +## Import + +Lightsail Container Service can be imported using the `name`, e.g., + +```shell +$ terraform import aws_lightsail_container_service.my_container_service container-service-1 +``` diff --git a/website/docs/r/lightsail_container_service_deployment_version.html.markdown b/website/docs/r/lightsail_container_service_deployment_version.html.markdown new file mode 100644 index 00000000000..cbedf8f2769 --- /dev/null +++ b/website/docs/r/lightsail_container_service_deployment_version.html.markdown @@ -0,0 +1,114 @@ +--- +subcategory: "Lightsail" +layout: "aws" +page_title: "AWS: aws_lightsail_container_service_deployment_version" +description: |- + Provides a resource to manage a deployment version for your Amazon Lightsail container service. +--- + +# Resource: aws_lightsail_container_service_deployment_version + +Provides a resource to manage a deployment version for your Amazon Lightsail container service. + +~> **NOTE:** The Amazon Lightsail container service must be enabled to create a deployment. + +~> **NOTE:** This resource allows you to manage an Amazon Lightsail container service deployment version but Terraform cannot destroy it. Removing this resource from your configuration will remove it from your statefile and Terraform management. + +## Example Usage + +### Basic Usage + +```terraform +resource "aws_lightsail_container_service_deployment_version" "example" { + container { + container_name = "hello-world" + image = "amazon/amazon-lightsail:hello-world" + + command = [] + + environment = { + MY_ENVIRONMENT_VARIABLE = "my_value" + } + + ports = { + 80 = "HTTP" + } + } + + public_endpoint { + container_name = "hello-world" + container_port = 80 + + health_check { + healthy_threshold = 2 + unhealthy_threshold = 2 + timeout_seconds = 2 + interval_seconds = 5 + path = "/" + success_codes = "200-499" + } + } + + service_name = aws_lightsail_container_service.example.name +} +``` + +## Argument Reference + +The following arguments are supported: + +* `service_name` - (Required) The name for the container service. +* `container` - (Required) A set of configuration blocks that describe the settings of the containers that will be launched on the container service. Maximum of 53. [Detailed below](#container). +* `public_endpoint` - (Optional) A configuration block that describes the settings of the public endpoint for the container service. [Detailed below](#public_endpoint). + +### `container` + +The `container` configuration block supports the following arguments: + +* `container_name` - (Required) The name for the container. +* `image` - (Required) The name of the image used for the container. Container images sourced from your Lightsail container service, that are registered and stored on your service, start with a colon (`:`). For example, `:container-service-1.mystaticwebsite.1`. Container images sourced from a public registry like Docker Hub don't start with a colon. For example, `nginx:latest` or `nginx`. +* `command` - (Optional) The launch command for the container. A list of string. +* `environment` - (Optional) A key-value map of the environment variables of the container. +* `ports` - (Optional) A key-value map of the open firewall ports of the container. Valid values: `HTTP`, `HTTPS`, `TCP`, `UDP`. + +### `public_endpoint` + +The `public_endpoint` configuration block supports the following arguments: + +* `container_name` - (Required) The name of the container for the endpoint. +* `container_port` - (Required) The port of the container to which traffic is forwarded to. +* `health_check` - (Required) A configuration block that describes the health check configuration of the container. [Detailed below](#health_check). + +### `health_check` + +The `health_check` configuration block supports the following arguments: + +* `healthy_threshold` - (Optional) The number of consecutive health checks successes required before moving the container to the Healthy state. Defaults to 2. +* `unhealthy_threshold` - (Optional) The number of consecutive health checks failures required before moving the container to the Unhealthy state. Defaults to 2. +* `timeout_seconds` - (Optional) The amount of time, in seconds, during which no response means a failed health check. You can specify between 2 and 60 seconds. Defaults to 2. +* `interval_seconds` - (Optional) The approximate interval, in seconds, between health checks of an individual container. You can specify between 5 and 300 seconds. Defaults to 5. +* `path` - (Optional) The path on the container on which to perform the health check. Defaults to "/". +* `success_codes` - (Optional) The HTTP codes to use when checking for a successful response from a container. You can specify values between 200 and 499. Defaults to "200-499". + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The `service_name` and `version` separation by a slash (`/`). +* `created_at` - The timestamp when the deployment was created. +* `state` - The current state of the container service. +* `version` - The version number of the deployment. + +## Timeouts + +`aws_lightsail_container_service_deployment_version` provides the following [Timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) configuration options: + +* `create` - (Optional, Default: `30m`) + +## Import + +Lightsail Container Service Deployment Version can be imported using the `service_name` and `version` separated by a slash (`/`), e.g., + +```shell +$ terraform import aws_lightsail_container_service_deployment_version.example container-service-1/1 +``` diff --git a/website/docs/r/location_place_index.html.markdown b/website/docs/r/location_place_index.html.markdown new file mode 100644 index 00000000000..d2df841349f --- /dev/null +++ b/website/docs/r/location_place_index.html.markdown @@ -0,0 +1,56 @@ +--- +subcategory: "Location" +layout: "aws" +page_title: "AWS: aws_location_place_index" +description: |- + Provides a Location Service Place Index. +--- + +# Resource: aws_location_place_index + +Provides a Location Service Place Index. + +## Example Usage + +```terraform +resource "aws_location_place_index" "example" { + data_source = "Here" + index_name = "example" +} +``` + +## Argument Reference + +The following arguments are required: + +* `data_source` - (Required) Specifies the geospatial data provider for the new place index. +* `index_name` - (Required) The name of the place index resource. + +The following arguments are optional: + +* `data_source_configuration` - (Optional) Configuration block with the data storage option chosen for requesting Places. Detailed below. +* `description` - (Optional) The optional description for the place index resource. +* `tags` - (Optional) Key-value tags for the place index. If configured with a provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +### data_source_configuration + +The following arguments are optional: + +* `intended_use` - (Optional) Specifies how the results of an operation will be stored by the caller. Valid values: `SingleUse`, `Storage`. Default: `SingleUse`. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `create_time` - The timestamp for when the place index resource was created in ISO 8601 format. +* `index_arn` - The Amazon Resource Name (ARN) for the place index resource. Used to specify a resource across AWS. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). +* `update_time` - The timestamp for when the place index resource was last update in ISO 8601. + +## Import + +`aws_location_place_index` resources can be imported using the place index name, e.g.: + +``` +$ terraform import aws_location_place_index.example example +``` diff --git a/website/docs/r/location_tracker.html.markdown b/website/docs/r/location_tracker.html.markdown new file mode 100644 index 00000000000..37b841c3367 --- /dev/null +++ b/website/docs/r/location_tracker.html.markdown @@ -0,0 +1,49 @@ +--- +subcategory: "Location" +layout: "aws" +page_title: "AWS: aws_location_tracker" +description: |- + Provides a Location Service Tracker. +--- + +# Resource: aws_location_tracker + +Provides a Location Service Tracker. + +## Example Usage + +```terraform +resource "aws_location_tracker" "example" { + tracker_name = "example" +} +``` + +## Argument Reference + +The following arguments are required: + +* `tracker_name` - (Required) The name of the tracker resource. + +The following arguments are optional: + +* `description` - (Optional) The optional description for the tracker resource. +* `kms_key_id` - (Optional) A key identifier for an AWS KMS customer managed key assigned to the Amazon Location resource. +* `position_filtering` - (Optional) The position filtering method of the tracker resource. Valid values: `TimeBased`, `DistanceBased`, `AccuracyBased`. Default: `TimeBased`. +* `tags` - (Optional) Key-value tags for the place index. If configured with a provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `create_time` - The timestamp for when the tracker resource was created in ISO 8601 format. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). +* `tracker_arn` - The Amazon Resource Name (ARN) for the tracker resource. Used when you need to specify a resource across all AWS. +* `update_time` - The timestamp for when the tracker resource was last update in ISO 8601 format. + +## Import + +`aws_location_tracker` resources can be imported using the tracker name, e.g.: + +``` +$ terraform import aws_location_tracker.example example +``` diff --git a/website/docs/r/msk_cluster.html.markdown b/website/docs/r/msk_cluster.html.markdown index 82adfd92b71..58465ae7f61 100644 --- a/website/docs/r/msk_cluster.html.markdown +++ b/website/docs/r/msk_cluster.html.markdown @@ -104,7 +104,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test_stream" { resource "aws_msk_cluster" "example" { cluster_name = "example" - kafka_version = "2.4.1" + kafka_version = "3.2.0" number_of_broker_nodes = 3 broker_node_group_info { diff --git a/website/docs/r/neptune_cluster.html.markdown b/website/docs/r/neptune_cluster.html.markdown index 463b43ff62f..d882abcf25e 100644 --- a/website/docs/r/neptune_cluster.html.markdown +++ b/website/docs/r/neptune_cluster.html.markdown @@ -39,6 +39,7 @@ See the AWS [Docs](https://docs.aws.amazon.com/neptune/latest/userguide/limits.h The following arguments are supported: +* `allow_major_version_upgrade` - (Optional) Specifies whether upgrades between different major versions are allowed. You must set it to `true` when providing an `engine_version` parameter that uses a different major version than the DB cluster's current version. Default is `false`. * `apply_immediately` - (Optional) Specifies whether any cluster modifications are applied immediately, or during the next maintenance window. Default is `false`. * `availability_zones` - (Optional) A list of EC2 Availability Zones that instances in the Neptune cluster can be created in. * `backup_retention_period` - (Optional) The days to retain backups for. Default `1` diff --git a/website/docs/r/network_interface.markdown b/website/docs/r/network_interface.markdown index 34f26788d37..051371f20b7 100644 --- a/website/docs/r/network_interface.markdown +++ b/website/docs/r/network_interface.markdown @@ -61,8 +61,8 @@ The following arguments are optional: * `ipv6_addresses` - (Optional) One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. Addresses are assigned without regard to order. You can't use this option if you're specifying `ipv6_address_count`. * `ipv6_prefix_count` - (Optional) Number of IPv6 prefixes that AWS automatically assigns to the network interface. * `ipv6_prefixes` - (Optional) One or more IPv6 prefixes assigned to the network interface. -* `private_ip_list` - (Optional) List of private IPs to assign to the ENI in sequential order. Requires setting `private_ip_list_enable` to `true`. -* `private_ip_list_enable` - (Optional) Whether `private_ip_list` is allowed and controls the IPs to assign to the ENI and `private_ips` and `private_ips_count` become read-only. Default false. +* `private_ip_list` - (Optional) List of private IPs to assign to the ENI in sequential order. Requires setting `private_ip_list_enabled` to `true`. +* `private_ip_list_enabled` - (Optional) Whether `private_ip_list` is allowed and controls the IPs to assign to the ENI and `private_ips` and `private_ips_count` become read-only. Default false. * `private_ips` - (Optional) List of private IPs to assign to the ENI without regard to order. * `private_ips_count` - (Optional) Number of secondary private IPs to assign to the ENI. The total number of private IPs will be 1 + `private_ips_count`, as a primary private IP will be assiged to an ENI by default. * `security_groups` - (Optional) List of security group IDs to assign to the ENI. diff --git a/website/docs/r/organizations_account.html.markdown b/website/docs/r/organizations_account.html.markdown index 0907b86cce9..05d0853873f 100644 --- a/website/docs/r/organizations_account.html.markdown +++ b/website/docs/r/organizations_account.html.markdown @@ -10,9 +10,9 @@ description: |- Provides a resource to create a member account in the current organization. -~> **Note:** Account management must be done from the organization's master account. +~> **Note:** Account management must be done from the organization's root account. -~> **Note:** By default, deleting this Terraform resource will only remove an AWS account from an organization. You must set the `close_on_deletion` flag to true to close the account. It is worth noting that quotas are enforced when using the `close_on_deletion` argument, which you can produce a [CLOSE_ACCOUNT_QUOTA_EXCEEDED](https://docs.aws.amazon.com/organizations/latest/APIReference/API_CloseAccount.html) error, and require you to close the account manually. +~> **Note:** By default, deleting this Terraform resource will only remove an AWS account from an organization. You must set the `close_on_deletion` flag to true to close the account. It is worth noting that quotas are enforced when using the `close_on_deletion` argument, which can produce a [CLOSE_ACCOUNT_QUOTA_EXCEEDED](https://docs.aws.amazon.com/organizations/latest/APIReference/API_CloseAccount.html) error, and require you to close the account manually. ## Example Usage @@ -34,9 +34,9 @@ The following arguments are optional: * `close_on_deletion` - (Optional) If true, a deletion event will close the account. Otherwise, it will only remove from the organization. This is not supported for GovCloud accounts. * `create_govcloud` - (Optional) Whether to also create a GovCloud account. The GovCloud account is tied to the main (commercial) account this resource creates. If `true`, the GovCloud account ID is available in the `govcloud_id` attribute. The only way to manage the GovCloud account with Terraform is to subsequently import the account using this resource. -* `iam_user_access_to_billing` - (Optional) If set to `ALLOW`, the new account enables IAM users to access account billing information if they have the required permissions. If set to `DENY`, then only the root user of the new account can access account billing information. +* `iam_user_access_to_billing` - (Optional) If set to `ALLOW`, the new account enables IAM users and roles to access account billing information if they have the required permissions. If set to `DENY`, then only the root user (and no roles) of the new account can access account billing information. If this is unset, the AWS API will default this to `ALLOW`. If the resource is created and this option is changed, it will try to recreate the account. * `parent_id` - (Optional) Parent Organizational Unit ID or Root ID for the account. Defaults to the Organization default Root ID. A configuration must be present for this argument to perform drift detection. -* `role_name` - (Optional) The name of an IAM role that Organizations automatically preconfigures in the new member account. This role trusts the master account, allowing users in the master account to assume the role, as permitted by the master account administrator. The role has administrator permissions in the new member account. The Organizations API provides no method for reading this information after account creation, so Terraform cannot perform drift detection on its value and will always show a difference for a configured value after import unless [`ignore_changes`](https://www.terraform.io/docs/configuration/meta-arguments/lifecycle.html#ignore_changes) is used. +* `role_name` - (Optional) The name of an IAM role that Organizations automatically preconfigures in the new member account. This role trusts the root account, allowing users in the root account to assume the role, as permitted by the root account administrator. The role has administrator permissions in the new member account. The Organizations API provides no method for reading this information after account creation, so Terraform cannot perform drift detection on its value and will always show a difference for a configured value after import unless [`ignore_changes`](https://www.terraform.io/docs/configuration/meta-arguments/lifecycle.html#ignore_changes) is used. * `tags` - (Optional) Key-value map of resource tags. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. ## Attributes Reference diff --git a/website/docs/r/ram_resource_share.markdown b/website/docs/r/ram_resource_share.markdown index 4e32c4e528a..1319eab4486 100644 --- a/website/docs/r/ram_resource_share.markdown +++ b/website/docs/r/ram_resource_share.markdown @@ -29,6 +29,7 @@ The following arguments are supported: * `name` - (Required) The name of the resource share. * `allow_external_principals` - (Optional) Indicates whether principals outside your organization can be associated with a resource share. +* `permission_arns` - (Optional) Specifies the Amazon Resource Names (ARNs) of the RAM permission to associate with the resource share. If you do not specify an ARN for the permission, RAM automatically attaches the default version of the permission for each resource type. You can associate only one permission with each resource type included in the resource share. * `tags` - (Optional) A map of tags to assign to the resource share. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. ## Attributes Reference diff --git a/website/docs/r/redshift_authentication_profile.html.markdown b/website/docs/r/redshift_authentication_profile.html.markdown new file mode 100644 index 00000000000..573542dc0b0 --- /dev/null +++ b/website/docs/r/redshift_authentication_profile.html.markdown @@ -0,0 +1,47 @@ +--- +subcategory: "Redshift" +layout: "aws" +page_title: "AWS: aws_redshift_authentication_profile" +description: |- + Creates a Redshift authentication profile +--- + +# Resource: aws_redshift_authentication_profile + +Creates a Redshift authentication profile + +## Example Usage + +```terraform +resource "aws_redshift_authentication_profile" "example" { + authentication_profile_name = "example" + authentication_profile_content = jsonencode( + { + AllowDBUserOverride = "1" + Client_ID = "ExampleClientID" + App_ID = "example" + } + ) +} +``` + +## Argument Reference + +The following arguments are supported: + +* `authentication_profile_name` - (Required, Forces new resource) The name of the authentication profile. +* `authentication_profile_content` - (Required) The content of the authentication profile in JSON format. The maximum length of the JSON string is determined by a quota for your account. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The name of the authentication profile. + +## Import + +Redshift Authentication Profiles support import by `authentication_profile_name`, e.g., + +```console +$ terraform import aws_redshift_authentication_profile.test example +``` diff --git a/website/docs/r/redshift_cluster.html.markdown b/website/docs/r/redshift_cluster.html.markdown index c0a1cabebc6..bce1621a6bf 100644 --- a/website/docs/r/redshift_cluster.html.markdown +++ b/website/docs/r/redshift_cluster.html.markdown @@ -13,6 +13,8 @@ Provides a Redshift Cluster Resource. ~> **Note:** All arguments including the username and password will be stored in the raw state as plain-text. [Read more about sensitive data in state](https://www.terraform.io/docs/state/sensitive-data.html). +~> **NOTE:** A Redshift cluster's default IAM role can be managed both by this resource's `default_iam_role_arn` argument and the [`aws_redshift_cluster_iam_roles`](redshift_cluster_iam_roles.html) resource's `default_iam_role_arn` argument. Do not configure different values for both arguments. Doing so will cause a conflict of default IAM roles. + ## Example Usage ```terraform @@ -36,6 +38,7 @@ The following arguments are supported: * `cluster_identifier` - (Required) The Cluster Identifier. Must be a lower case string. * `database_name` - (Optional) The name of the first database to be created when the cluster is created. If you do not provide a name, Amazon Redshift will create a default database called `dev`. +* `default_iam_role_arn` - (Optional) The Amazon Resource Name (ARN) for the IAM role that was set as default for the cluster when the cluster was created. * `node_type` - (Required) The node type to be provisioned for the cluster. * `cluster_type` - (Optional) The cluster type to use. Either `single-node` or `multi-node`. * `master_password` - (Required unless a `snapshot_identifier` is provided) Password for the master DB user. @@ -51,13 +54,15 @@ The following arguments are supported: Format: ddd:hh24:mi-ddd:hh24:mi * `cluster_parameter_group_name` - (Optional) The name of the parameter group to be associated with this cluster. * `automated_snapshot_retention_period` - (Optional) The number of days that automated snapshots are retained. If the value is 0, automated snapshots are disabled. Even if automated snapshots are disabled, you can still create manual snapshots when you want with create-cluster-snapshot. Default is 1. -* `port` - (Optional) The port number on which the cluster accepts incoming connections. +* `port` - (Optional) The port number on which the cluster accepts incoming connections. Valid values are between `1115` and `65535`. The cluster is accessible only via the JDBC and ODBC connection strings. Part of the connection string requires the port on which the cluster will listen for incoming connections. - Default port is 5439. + Default port is `5439`. * `cluster_version` - (Optional) The version of the Amazon Redshift engine software that you want to deploy on the cluster. The version selected runs on all the nodes in the cluster. -* `allow_version_upgrade` - (Optional) If true , major version upgrades can be applied during the maintenance window to the Amazon Redshift engine that is running on the cluster. Default is true +* `allow_version_upgrade` - (Optional) If true , major version upgrades can be applied during the maintenance window to the Amazon Redshift engine that is running on the cluster. Default is `true`. +* `apply_immediately` - (Optional) Specifies whether any cluster modifications are applied immediately, or during the next maintenance window. Default is `false`. +* `aqua_configuration_status` - (Optional) The value represents how the cluster is configured to use AQUA (Advanced Query Accelerator) after the cluster is restored. Possible values are `enabled`, `disabled`, and `auto`. Requires Cluster reboot. * `number_of_nodes` - (Optional) The number of compute nodes in the cluster. This parameter is required when the ClusterType parameter is specified as multi-node. Default is 1. * `publicly_accessible` - (Optional) If true, the cluster can be accessed from a public network. Default is `true`. * `encrypted` - (Optional) If true , the data in the cluster is encrypted at rest. @@ -71,6 +76,8 @@ The following arguments are supported: * `owner_account` - (Optional) The AWS customer account used to create or copy the snapshot. Required if you are restoring a snapshot you do not own, optional if you own the snapshot. * `iam_roles` - (Optional) A list of IAM Role ARNs to associate with the cluster. A Maximum of 10 can be associated to the cluster at any time. * `logging` - (Optional) Logging, documented below. +* `maintenance_track_name` - (Optional) The name of the maintenance track for the restored cluster. When you take a snapshot, the snapshot inherits the MaintenanceTrack value from the cluster. The snapshot might be on a different track than the cluster that was the source for the snapshot. For example, suppose that you take a snapshot of a cluster that is on the current track and then change the cluster to be on the trailing track. In this case, the snapshot and the source cluster are on different tracks. Default value is `current`. +* `manual_snapshot_retention_period` - (Optional) The default number of days to retain a manual snapshot. If the value is -1, the snapshot is retained indefinitely. This setting doesn't change the retention period of existing snapshots. Valid values are between `-1` and `3653`. Default value is `-1`. * `snapshot_copy` - (Optional) Configuration of automatic copy of snapshots from one region to another. Documented below. * `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. @@ -91,6 +98,8 @@ The following arguments are supported: * `bucket_name` - (Optional, required when `enable` is `true`) The name of an existing S3 bucket where the log files are to be stored. Must be in the same region as the cluster and the cluster must have read bucket and put object permissions. For more information on the permissions required for the bucket, please read the AWS [documentation](http://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html#db-auditing-enable-logging) * `s3_key_prefix` - (Optional) The prefix applied to the log file names. +* `log_destination_type` - (Optional) The log destination type. An enum with possible values of `s3` and `cloudwatch`. +* `log_exports` - (Optional) The collection of exported log types. Log types include the connection log, user log and user activity log. Required when `log_destination_type` is `cloudwatch`. #### `snapshot_copy` diff --git a/website/docs/r/redshift_cluster_iam_roles.html.markdown b/website/docs/r/redshift_cluster_iam_roles.html.markdown new file mode 100644 index 00000000000..f50a08ae953 --- /dev/null +++ b/website/docs/r/redshift_cluster_iam_roles.html.markdown @@ -0,0 +1,44 @@ +--- +subcategory: "Redshift" +layout: "aws" +page_title: "AWS: aws_redshift_cluster_iam_roles" +description: |- + Provides a Redshift Cluster IAM Roles resource. +--- + +# Resource: aws_redshift_cluster_iam_roles + +Provides a Redshift Cluster IAM Roles resource. + +~> **NOTE:** A Redshift cluster's default IAM role can be managed both by this resource's `default_iam_role_arn` argument and the [`aws_redshift_cluster`](redshift_cluster.html) resource's `default_iam_role_arn` argument. Do not configure different values for both arguments. Doing so will cause a conflict of default IAM roles. + +## Example Usage + +```terraform +resource "aws_redshift_cluster_iam_roles" "example" { + cluster_identifier = aws_redshift_cluster.example.cluster_identifier + iam_role_arns = [aws_iam_role.example.arn] +} +``` + +## Argument Reference + +The following arguments are supported: + +* `cluster_identifier` - (Required) The name of the Redshift Cluster IAM Roles. +* `iam_role_arns` - (Optional) A list of IAM Role ARNs to associate with the cluster. A Maximum of 10 can be associated to the cluster at any time. +* `default_iam_role_arn` - (Optional) The Amazon Resource Name (ARN) for the IAM role that was set as default for the cluster when the cluster was created. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The Redshift Cluster ID. + +## Import + +Redshift Cluster IAM Roless can be imported using the `cluster_identifier`, e.g., + +``` +$ terraform import aws_redshift_cluster_iam_roles.examplegroup1 example +``` diff --git a/website/docs/r/redshift_endpoint_access.html.markdown b/website/docs/r/redshift_endpoint_access.html.markdown new file mode 100644 index 00000000000..15937c9015e --- /dev/null +++ b/website/docs/r/redshift_endpoint_access.html.markdown @@ -0,0 +1,61 @@ +--- +subcategory: "Redshift" +layout: "aws" +page_title: "AWS: aws_redshift_endpoint_access" +description: |- + Provides a Redshift Endpoint Access resource. +--- + +# Resource: aws_redshift_endpoint_access + +Creates a new Amazon Redshift endpoint access. + +## Example Usage + +```terraform +resource "aws_redshift_endpoint_access" "example" { + endpoint_name = "example" + subnet_group_name = aws_redshift_subnet_group.example.id + cluster_identifier = aws_redshift_cluster.example.cluster_identifier +} +``` + +## Argument Reference + +The following arguments are supported: + +* `cluster_identifier` - (Required) The cluster identifier of the cluster to access. +* `endpoint_name` - (Required) The Redshift-managed VPC endpoint name. +* `resource_owner` - (Optional) The Amazon Web Services account ID of the owner of the cluster. This is only required if the cluster is in another Amazon Web Services account. +* `subnet_group_name` - (Required) The subnet group from which Amazon Redshift chooses the subnet to deploy the endpoint. +* `vpc_security_group_ids` - (Optional) The security group that defines the ports, protocols, and sources for inbound traffic that you are authorizing into your endpoint. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `address` - The DNS address of the endpoint. +* `id` - The Redshift-managed VPC endpoint name. +* `port` - The port number on which the cluster accepts incoming connections. +* `vpc_endpoint` - The connection endpoint for connecting to an Amazon Redshift cluster through the proxy. See details below. + +### VPC Endpoint + +* `network_interface` - One or more network interfaces of the endpoint. Also known as an interface endpoint. See details below. +* `vpc_endpoint_id` - The connection endpoint ID for connecting an Amazon Redshift cluster through the proxy. +* `vpc_id` - The VPC identifier that the endpoint is associated. + +### Network Interface + +* `availability_zone` - The Availability Zone. +* `network_interface_id` - The network interface identifier. +* `private_ip_address` - The IPv4 address of the network interface within the subnet. +* `subnet_id` - The subnet identifier. + +## Import + +Redshift endpoint access can be imported using the `name`, e.g., + +``` +$ terraform import aws_redshift_endpoint_access.example example +``` diff --git a/website/docs/r/redshift_event_subscription.html.markdown b/website/docs/r/redshift_event_subscription.html.markdown index 366d68bd11c..f79c9de0cc9 100644 --- a/website/docs/r/redshift_event_subscription.html.markdown +++ b/website/docs/r/redshift_event_subscription.html.markdown @@ -52,11 +52,11 @@ The following arguments are supported: * `name` - (Required) The name of the Redshift event subscription. * `sns_topic_arn` - (Required) The ARN of the SNS topic to send events to. -* `source_ids` - (Optional) A list of identifiers of the event sources for which events will be returned. If not specified, then all sources are included in the response. If specified, a source_type must also be specified. -* `source_type` - (Optional) The type of source that will be generating the events. Valid options are `cluster`, `cluster-parameter-group`, `cluster-security-group`, or `cluster-snapshot`. If not set, all sources will be subscribed to. -* `severity` - (Optional) The event severity to be published by the notification subscription. Valid options are `INFO` or `ERROR`. +* `source_ids` - (Optional) A list of identifiers of the event sources for which events will be returned. If not specified, then all sources are included in the response. If specified, a `source_type` must also be specified. +* `source_type` - (Optional) The type of source that will be generating the events. Valid options are `cluster`, `cluster-parameter-group`, `cluster-security-group`, `cluster-snapshot`, or `scheduled-action`. If not set, all sources will be subscribed to. +* `severity` - (Optional) The event severity to be published by the notification subscription. Valid options are `INFO` or `ERROR`. Default value of `INFO`. * `event_categories` - (Optional) A list of event categories for a SourceType that you want to subscribe to. See https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html or run `aws redshift describe-event-categories`. -* `enabled` - (Optional) A boolean flag to enable/disable the subscription. Defaults to true. +* `enabled` - (Optional) A boolean flag to enable/disable the subscription. Defaults to `true`. * `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. ## Attributes Reference diff --git a/website/docs/r/redshift_hsm_client_certificate.html.markdown b/website/docs/r/redshift_hsm_client_certificate.html.markdown new file mode 100644 index 00000000000..dc2a3bd203c --- /dev/null +++ b/website/docs/r/redshift_hsm_client_certificate.html.markdown @@ -0,0 +1,42 @@ +--- +subcategory: "Redshift" +layout: "aws" +page_title: "AWS: aws_redshift_hsm_client_certificate" +description: |- + Creates an HSM client certificate that an Amazon Redshift cluster will use to connect to the client's HSM in order to store and retrieve the keys used to encrypt the cluster databases. +--- + +# Resource: aws_redshift_hsm_client_certificate + +Creates an HSM client certificate that an Amazon Redshift cluster will use to connect to the client's HSM in order to store and retrieve the keys used to encrypt the cluster databases. + +## Example Usage + +```terraform +resource "aws_redshift_hsm_client_certificate" "example" { + hsm_client_certificate_identifier = "example" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `hsm_client_certificate_identifier` - (Required, Forces new resource) The identifier of the HSM client certificate. +* `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - Amazon Resource Name (ARN) of the Hsm Client Certificate. +* `hsm_client_certificate_public_key` - The public key that the Amazon Redshift cluster will use to connect to the HSM. You must register the public key in the HSM. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block). + +## Import + +Redshift Hsm Client Certificates support import by `hsm_client_certificate_identifier`, e.g., + +```console +$ terraform import aws_redshift_hsm_client_certificate.test example +``` diff --git a/website/docs/r/redshift_hsm_configuration.html.markdown b/website/docs/r/redshift_hsm_configuration.html.markdown new file mode 100644 index 00000000000..0695a6972ff --- /dev/null +++ b/website/docs/r/redshift_hsm_configuration.html.markdown @@ -0,0 +1,52 @@ +--- +subcategory: "Redshift" +layout: "aws" +page_title: "AWS: aws_redshift_hsm_configuration" +description: |- + Creates an HSM configuration that contains the information required by an Amazon Redshift cluster to store and use database encryption keys in a Hardware Security Module (HSM). +--- + +# Resource: aws_redshift_hsm_configuration + + Creates an HSM configuration that contains the information required by an Amazon Redshift cluster to store and use database encryption keys in a Hardware Security Module (HSM). + +## Example Usage + +```terraform +resource "aws_redshift_hsm_configuration" "example" { + description = "example" + hsm_configuration_identifier = "example" + hsm_ip_address = "10.0.0.1" + hsm_partition_name = "aws" + hsm_partition_password = "example" + hsm_server_public_certificate = "example" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `description` - (Required, Forces new resource) A text description of the HSM configuration to be created. +* `hsm_configuration_identifier` - (Required, Forces new resource) The identifier to be assigned to the new Amazon Redshift HSM configuration. +* `hsm_ip_address` - (Required, Forces new resource) The IP address that the Amazon Redshift cluster must use to access the HSM. +* `hsm_partition_name` - (Required, Forces new resource) The name of the partition in the HSM where the Amazon Redshift clusters will store their database encryption keys. +* `hsm_partition_password` - (Required, Forces new resource) The password required to access the HSM partition. +* `hsm_server_public_certificate` - (Required, Forces new resource) The HSMs public certificate file. When using Cloud HSM, the file name is server.pem. +* `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - Amazon Resource Name (ARN) of the Hsm Client Certificate. +* `hsm_configuration_public_key` - The public key that the Amazon Redshift cluster will use to connect to the HSM. You must register the public key in the HSM. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block). + +## Import + +Redshift Hsm Client Certificates support import by `hsm_configuration_identifier`, e.g., + +```console +$ terraform import aws_redshift_hsm_configuration.example example +``` diff --git a/website/docs/r/redshift_usage_limit.html.markdown b/website/docs/r/redshift_usage_limit.html.markdown new file mode 100644 index 00000000000..540a112fcd6 --- /dev/null +++ b/website/docs/r/redshift_usage_limit.html.markdown @@ -0,0 +1,50 @@ +--- +subcategory: "Redshift" +layout: "aws" +page_title: "AWS: aws_redshift_usage_limit" +description: |- + Provides a Redshift Usage Limit resource. +--- + +# Resource: aws_redshift_usage_limit + +Creates a new Amazon Redshift Usage Limit. + +## Example Usage + +```terraform +resource "aws_redshift_usage_limit" "example" { + cluster_identifier = aws_redshift_cluster.example.id + feature_type = "concurrency-scaling" + limit_type = "time" + amount = 60 +} +``` + +## Argument Reference + +The following arguments are supported: + +* `amount` - (Required) The limit amount. If time-based, this amount is in minutes. If data-based, this amount is in terabytes (TB). The value must be a positive number. +* `breach_action` - (Optional) The action that Amazon Redshift takes when the limit is reached. The default is `log`. Valid values are `log`, `emit-metric`, and `disable`. +* `cluster_identifier` - (Required) The identifier of the cluster that you want to limit usage. +* `feature_type` - (Required) The Amazon Redshift feature that you want to limit. Valid values are `spectrum`, `concurrency-scaling`, and `cross-region-datasharing`. +* `limit_type` - (Required) The type of limit. Depending on the feature type, this can be based on a time duration or data size. If FeatureType is `spectrum`, then LimitType must be `data-scanned`. If FeatureType is `concurrency-scaling`, then LimitType must be `time`. If FeatureType is `cross-region-datasharing`, then LimitType must be `data-scanned`. Valid values are `data-scanned`, and `time`. +* `period` - (Optional) The time period that the amount applies to. A weekly period begins on Sunday. The default is `monthly`. Valid values are `daily`, `weekly`, and `monthly`. +* `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - Amazon Resource Name (ARN) of the Redshift Usage Limit. +* `id` - The Redshift Usage Limit ID. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block). + +## Import + +Redshift usage limits can be imported using the `id`, e.g., + +``` +$ terraform import aws_redshift_usage_limit.example example-id +``` diff --git a/website/docs/r/redshiftdata_statement.html.markdown b/website/docs/r/redshiftdata_statement.html.markdown new file mode 100644 index 00000000000..b56fc7ffe9c --- /dev/null +++ b/website/docs/r/redshiftdata_statement.html.markdown @@ -0,0 +1,48 @@ +--- +subcategory: "Redshift Data" +layout: "aws" +page_title: "AWS: aws_redshiftdata_.subnet_group" +description: |- + Provides a Redshift Data Statement execution resource. +--- + +# Resource: aws_redshiftdata_statement + +Executes a Redshift Data Statement. + +## Example Usage + +```terraform +resource "aws_redshiftdata_statement" "example" { + cluster_identifier = aws_redshift_cluster.example.cluster_identifier + database = aws_redshift_cluster.example.database_name + db_user = aws_redshift_cluster.example.master_username + sql = "CREATE GROUP group_name;" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `cluster_identifier` - (Required) The cluster identifier. +* `database` - (Required) The name of the database. +* `db_user` - (Optional) The database user name. +* `secret_arn` - (Optional) The name or ARN of the secret that enables access to the database. +* `sql` - (Required) The SQL statement text to run. +* `statement_name` - (Optional) The name of the SQL statement. You can name the SQL statement when you create it to identify the query. +* `with_event` - (Optional) A value that indicates whether to send an event to the Amazon EventBridge event bus after the SQL statement runs. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The Redshift Data Statement ID. + +## Import + +Redshift Data Statements can be imported using the `id`, e.g., + +``` +$ terraform import aws_redshiftdata_statement.example example +``` diff --git a/website/docs/r/rum_app_monitor.html.markdown b/website/docs/r/rum_app_monitor.html.markdown new file mode 100644 index 00000000000..8a5b8b93c73 --- /dev/null +++ b/website/docs/r/rum_app_monitor.html.markdown @@ -0,0 +1,59 @@ +--- +subcategory: "CloudWatch RUM" +layout: "aws" +page_title: "AWS: aws_rum_app_monitor" +description: |- + Provides a CloudWatch RUM App Monitor resource. +--- + +# Resource: aws_rum_app_monitor + +Provides a CloudWatch RUM App Monitor resource. + +## Example Usage + +```terraform +resource "aws_rum_app_monitor" "example" { + name = "example" + domain = "localhost" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the log stream. +* `domain` - (Required) The top-level internet domain name for which your application has administrative authority. +* `domain` - (Optional) configuration data for the app monitor. See app_monitor_configuration below. +* `cw_log_enabled` - (Optional) Data collected by RUM is kept by RUM for 30 days and then deleted. This parameter specifies whether RUM sends a copy of this telemetry data to Amazon CloudWatch Logs in your account. This enables you to keep the telemetry data for more than 30 days, but it does incur Amazon CloudWatch Logs charges. Default value is `false`. +* `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. + +### app_monitor_configuration + +* `allow_cookies` - (Optional) If you set this to `true`, RUM web client sets two cookies, a session cookie and a user cookie. The cookies allow the RUM web client to collect data relating to the number of users an application has and the behavior of the application across a sequence of events. Cookies are stored in the top-level domain of the current page. +* `enable_xray` - (Optional) If you set this to `true`, RUM enables X-Ray tracing for the user sessions that RUM samples. RUM adds an X-Ray trace header to allowed HTTP requests. It also records an X-Ray segment for allowed HTTP requests. +* `excluded_pages` - (Optional) A list of URLs in your website or application to exclude from RUM data collection. +* `favorite_pages` - (Optional) A list of pages in the CloudWatch RUM console that are to be displayed with a "favorite" icon. +* `guest_role_arn` - (Optional) The ARN of the guest IAM role that is attached to the Amazon Cognito identity pool that is used to authorize the sending of data to RUM. +* `identity_pool_id` - (Optional) The ID of the Amazon Cognito identity pool that is used to authorize the sending of data to RUM. +* `included_pages` - (Optional) If this app monitor is to collect data from only certain pages in your application, this structure lists those pages. +* `session_sample_rate` - (Optional) Specifies the percentage of user sessions to use for RUM data collection. Choosing a higher percentage gives you more data but also incurs more costs. The number you specify is the percentage of user sessions that will be used. Default value is `0.1`. +* `telemetries` - (Optional) An array that lists the types of telemetry data that this app monitor is to collect. Valid values are `errors`, `performance`, and `http`. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - The Amazon Resource Name (ARN) specifying the app monitor. +* `id` - TThe Amazon Resource Name (ARN) specifying the app monitor. +* `cw_log_group` - The name of the log group where the copies are stored. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block). + +## Import + +Cloudwatch RUM App Monitor can be imported using the `name`, e.g., + +``` +$ terraform import aws_rum_app_monitor.example example +``` diff --git a/website/docs/r/s3_bucket_metric.html.markdown b/website/docs/r/s3_bucket_metric.html.markdown index 8474e2ed90c..85c6540b374 100644 --- a/website/docs/r/s3_bucket_metric.html.markdown +++ b/website/docs/r/s3_bucket_metric.html.markdown @@ -52,7 +52,7 @@ resource "aws_s3_bucket_metric" "example-filtered" { The following arguments are supported: * `bucket` - (Required) The name of the bucket to put metric configuration. -* `name` - (Required) Unique identifier of the metrics configuration for the bucket. +* `name` - (Required) Unique identifier of the metrics configuration for the bucket. Must be less than or equal to 64 characters in length. * `filter` - (Optional) [Object filtering](http://docs.aws.amazon.com/AmazonS3/latest/dev/metrics-configurations.html#metrics-configurations-filter) that accepts a prefix, tags, or a logical AND of prefix and tags (documented below). The `filter` metric configuration supports the following: diff --git a/website/docs/r/sagemaker_endpoint_configuration.html.markdown b/website/docs/r/sagemaker_endpoint_configuration.html.markdown index 5467c4a0ea5..e47df8c9cd2 100644 --- a/website/docs/r/sagemaker_endpoint_configuration.html.markdown +++ b/website/docs/r/sagemaker_endpoint_configuration.html.markdown @@ -43,16 +43,22 @@ The following arguments are supported: * `data_capture_config` - (Optional) Specifies the parameters to capture input/output of SageMaker models endpoints. Fields are documented below. * `async_inference_config` - (Optional) Specifies configuration for how an endpoint performs asynchronous inference. -The `production_variants` block supports: +### production_variants -* `initial_instance_count` - (Required) Initial number of instances used for auto-scaling. -* `instance_type` (Required) - The type of instance to start. +* `initial_instance_count` - (Optional) Initial number of instances used for auto-scaling. +* `instance_type` (Optional) - The type of instance to start. * `accelerator_type` (Optional) - The size of the Elastic Inference (EI) instance to use for the production variant. -* `initial_variant_weight` (Optional) - Determines initial traffic distribution among all of the models that you specify in the endpoint configuration. If unspecified, it defaults to 1.0. +* `initial_variant_weight` (Optional) - Determines initial traffic distribution among all of the models that you specify in the endpoint configuration. If unspecified, it defaults to `1.0`. * `model_name` - (Required) The name of the model to use. * `variant_name` - (Optional) The name of the variant. If omitted, Terraform will assign a random, unique name. +* `serverless_config` - (Optional) Specifies configuration for how an endpoint performs asynchronous inference. -The `data_capture_config` block supports: +#### serverless_config + +* `max_concurrency` - (Required) The maximum number of concurrent invocations your serverless endpoint can process. Valid values are between `1` and `200`. +* `memory_size_in_mb` - (Required) The memory size of your serverless endpoint. Valid values are in 1 GB increments: `1024` MB, `2048` MB, `3072` MB, `4096` MB, `5120` MB, or `6144` MB. + +### data_capture_config * `initial_sampling_percentage` - (Required) Portion of data to capture. Should be between 0 and 100. * `destination_s3_uri` - (Required) The URL for S3 location where the captured data is stored. @@ -61,31 +67,31 @@ The `data_capture_config` block supports: * `enable_capture` - (Optional) Flag to enable data capture. Defaults to `false`. * `capture_content_type_header` - (Optional) The content type headers to capture. Fields are documented below. -The `capture_options` block supports: +#### capture_options * `capture_mode` - (Required) Specifies the data to be captured. Should be one of `Input` or `Output`. -The `capture_content_type_header` block supports: +#### capture_content_type_header * `csv_content_types` - (Optional) The CSV content type headers to capture. * `json_content_types` - (Optional) The JSON content type headers to capture. -The `async_inference_config` block supports: +### async_inference_config * `output_config` - (Required) Specifies the configuration for asynchronous inference invocation outputs. * `client_config` - (Optional) Configures the behavior of the client used by Amazon SageMaker to interact with the model container during asynchronous inference. -The `client_config` block supports: +#### client_config * `max_concurrent_invocations_per_instance` - (Optional) The maximum number of concurrent requests sent by the SageMaker client to the model container. If no value is provided, Amazon SageMaker will choose an optimal value for you. -The `output_config` block supports: +#### output_config * `s3_output_path` - (Required) The Amazon S3 location to upload inference responses to. * `kms_key_id` - (Optional) The Amazon Web Services Key Management Service (Amazon Web Services KMS) key that Amazon SageMaker uses to encrypt the asynchronous inference output in Amazon S3. * `notification_config` - (Optional) Specifies the configuration for notifications of inference results for asynchronous inference. -The `notification_config` block supports: +##### notification_config * `error_topic` - (Optional) Amazon SNS topic to post a notification to when inference fails. If no topic is provided, no notification is sent on failure. * `success_topic` - (Optional) Amazon SNS topic to post a notification to when inference completes successfully. If no topic is provided, no notification is sent on success. diff --git a/website/docs/r/sagemaker_notebook_instance.html.markdown b/website/docs/r/sagemaker_notebook_instance.html.markdown index acc54b3e4c6..fda776bce08 100644 --- a/website/docs/r/sagemaker_notebook_instance.html.markdown +++ b/website/docs/r/sagemaker_notebook_instance.html.markdown @@ -56,7 +56,7 @@ The following arguments are supported: * `name` - (Required) The name of the notebook instance (must be unique). * `role_arn` - (Required) The ARN of the IAM role to be used by the notebook instance which allows SageMaker to call other services on your behalf. * `instance_type` - (Required) The name of ML compute instance type. -* `platform_identifier` - (Optional) The platform identifier of the notebook instance runtime environment. This value can be either `notebook-al1-v1` or `notebook-al2-v1`, depending on which version of Amazon Linux you require. +* `platform_identifier` - (Optional) The platform identifier of the notebook instance runtime environment. This value can be either `notebook-al1-v1`, `notebook-al2-v1`, or `notebook-al2-v2`, depending on which version of Amazon Linux you require. * `volume_size` - (Optional) The size, in GB, of the ML storage volume to attach to the notebook instance. The default value is 5 GB. * `subnet_id` - (Optional) The VPC subnet ID. * `security_groups` - (Optional) The associated security groups. @@ -67,8 +67,13 @@ The following arguments are supported: * `additional_code_repositories` - (Optional) An array of up to three Git repositories to associate with the notebook instance. These can be either the names of Git repositories stored as resources in your account, or the URL of Git repositories in [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) or in any other Git repository. These repositories are cloned at the same level as the default repository of your notebook instance. * `default_code_repository` - (Optional) The Git repository associated with the notebook instance as its default code repository. This can be either the name of a Git repository stored as a resource in your account, or the URL of a Git repository in [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) or in any other Git repository. +* `instance_metadata_service_configuration` - (Optional) Information on the IMDS configuration of the notebook instance. Conflicts with `instance_metadata_service_configuration`. see details below. * `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. +### instance_metadata_service_configuration + +* `minimum_instance_metadata_service_version` - (Optional) Indicates the minimum IMDS version that the notebook instance supports. When passed "1" is passed. This means that both IMDSv1 and IMDSv2 are supported. Valid values are `1` and `2`. + ## Attributes Reference In addition to all arguments above, the following attributes are exported: diff --git a/website/docs/r/servicecatalog_provisioned_product.html.markdown b/website/docs/r/servicecatalog_provisioned_product.html.markdown index 98eba8f15b3..e7e5ede18ce 100644 --- a/website/docs/r/servicecatalog_provisioned_product.html.markdown +++ b/website/docs/r/servicecatalog_provisioned_product.html.markdown @@ -105,6 +105,8 @@ In addition to all arguments above, the following attributes are exported: ### status Meanings +~> **NOTE:** [Enable logging](https://www.terraform.io/plugin/log/managing) to `WARN` verbosity to further investigate error messages associated with a provisioned product in the `ERROR` or `TAINTED` state which can occur during resource creation or update. + * `AVAILABLE` - Stable state, ready to perform any operation. The most recent operation succeeded and completed. * `UNDER_CHANGE` - Transitive state. Operations performed might not have valid results. Wait for an `AVAILABLE` status before performing operations. diff --git a/website/docs/r/snapshot_create_volume_permission.html.markdown b/website/docs/r/snapshot_create_volume_permission.html.markdown index e3b27031e61..7e27d842084 100644 --- a/website/docs/r/snapshot_create_volume_permission.html.markdown +++ b/website/docs/r/snapshot_create_volume_permission.html.markdown @@ -33,7 +33,7 @@ resource "aws_ebs_snapshot" "example_snapshot" { The following arguments are supported: * `snapshot_id` - (required) A snapshot ID -* `account_id` - (required) An AWS Account ID to add create volume permissions +* `account_id` - (required) An AWS Account ID to add create volume permissions. The AWS Account cannot be the snapshot's owner ## Attributes Reference diff --git a/website/docs/r/sns_platform_application.html.markdown b/website/docs/r/sns_platform_application.html.markdown index 74858ae3bcd..a62c6ed3b6d 100644 --- a/website/docs/r/sns_platform_application.html.markdown +++ b/website/docs/r/sns_platform_application.html.markdown @@ -40,14 +40,14 @@ The following arguments are supported: * `name` - (Required) The friendly name for the SNS platform application * `platform` - (Required) The platform that the app is registered with. See [Platform][1] for supported platforms. * `platform_credential` - (Required) Application Platform credential. See [Credential][1] for type of credential required for platform. The value of this attribute when stored into the Terraform state is only a hash of the real value, so therefore it is not practical to use this as an attribute for other resources. -* `event_delivery_failure_topic_arn` - (Optional) SNS Topic triggered when a delivery to any of the platform endpoints associated with your platform application encounters a permanent failure. -* `event_endpoint_created_topic_arn` - (Optional) SNS Topic triggered when a new platform endpoint is added to your platform application. -* `event_endpoint_deleted_topic_arn` - (Optional) SNS Topic triggered when an existing platform endpoint is deleted from your platform application. -* `event_endpoint_updated_topic_arn` - (Optional) SNS Topic triggered when an existing platform endpoint is changed from your platform application. -* `failure_feedback_role_arn` - (Optional) The IAM role permitted to receive failure feedback for this application. +* `event_delivery_failure_topic_arn` - (Optional) The ARN of the SNS Topic triggered when a delivery to any of the platform endpoints associated with your platform application encounters a permanent failure. +* `event_endpoint_created_topic_arn` - (Optional) The ARN of the SNS Topic triggered when a new platform endpoint is added to your platform application. +* `event_endpoint_deleted_topic_arn` - (Optional) The ARN of the SNS Topic triggered when an existing platform endpoint is deleted from your platform application. +* `event_endpoint_updated_topic_arn` - (Optional) The ARN of the SNS Topic triggered when an existing platform endpoint is changed from your platform application. +* `failure_feedback_role_arn` - (Optional) The IAM role ARN permitted to receive failure feedback for this application and give SNS write access to use CloudWatch logs on your behalf. * `platform_principal` - (Optional) Application Platform principal. See [Principal][2] for type of principal required for platform. The value of this attribute when stored into the Terraform state is only a hash of the real value, so therefore it is not practical to use this as an attribute for other resources. -* `success_feedback_role_arn` - (Optional) The IAM role permitted to receive success feedback for this application. -* `success_feedback_sample_rate` - (Optional) The percentage of success to sample (0-100) +* `success_feedback_role_arn` - (Optional) The IAM role ARN permitted to receive success feedback for this application and give SNS write access to use CloudWatch logs on your behalf. +* `success_feedback_sample_rate` - (Optional) The sample rate percentage (0-100) of successfully delivered messages. ## Attributes Reference diff --git a/website/docs/r/ssm_parameter.html.markdown b/website/docs/r/ssm_parameter.html.markdown index 124926fe0a3..2d019b88fd0 100644 --- a/website/docs/r/ssm_parameter.html.markdown +++ b/website/docs/r/ssm_parameter.html.markdown @@ -61,7 +61,11 @@ The following arguments are supported: * `type` - (Required) The type of the parameter. Valid types are `String`, `StringList` and `SecureString`. * `value` - (Required) The value of the parameter. This value is always marked as sensitive in the Terraform plan output, regardless of `type`. In Terraform CLI version 0.15 and later, this may require additional configuration handling for certain scenarios. For more information, see the [Terraform v0.15 Upgrade Guide](https://www.terraform.io/upgrade-guides/0-15.html#sensitive-output-values). * `description` - (Optional) The description of the parameter. -* `tier` - (Optional) The tier of the parameter. If not specified, will default to `Standard`. Valid tiers are `Standard`, `Advanced`, and `Intelligent-Tiering`. For more information on parameter tiers, see the [AWS SSM Parameter tier comparison and guide](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html). +* `tier` - (Optional) The parameter tier to assign to the parameter. + If not specified, will use the default parameter tier for the region. + Valid tiers are `Standard`, `Advanced`, and `Intelligent-Tiering`. + Downgrading an `Advanced` tier parameter to `Standard` will recreate the resource. + For more information on parameter tiers, see the [AWS SSM Parameter tier comparison and guide](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html). * `key_id` - (Optional) The KMS key id or arn for encrypting a SecureString. * `overwrite` - (Optional) Overwrite an existing parameter. If not specified, will default to `false` if the resource has not been created by terraform to avoid overwrite of existing resource and will default to `true` otherwise (terraform lifecycle rules should then be used to manage the update behavior). * `allowed_pattern` - (Optional) A regular expression used to validate the parameter value. diff --git a/website/docs/r/synthetics_canary.html.markdown b/website/docs/r/synthetics_canary.html.markdown index 5f53c6093de..750e6e42243 100644 --- a/website/docs/r/synthetics_canary.html.markdown +++ b/website/docs/r/synthetics_canary.html.markdown @@ -42,6 +42,7 @@ The following arguments are required: The following arguments are optional: +* `delete_lambda` - (Optional) Specifies whether to also delete the Lambda functions and layers used by this canary. The default is `false`. * `vpc_config` - (Optional) Configuration block. Detailed below. * `failure_retention_period` - (Optional) Number of days to retain data about failed runs of this canary. If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days. * `run_config` - (Optional) Configuration block for individual canary runs. Detailed below. diff --git a/website/docs/r/transfer_server.html.markdown b/website/docs/r/transfer_server.html.markdown index 4271a742096..b2da9f431fa 100644 --- a/website/docs/r/transfer_server.html.markdown +++ b/website/docs/r/transfer_server.html.markdown @@ -105,7 +105,7 @@ The following arguments are supported: * `force_destroy` - (Optional) A boolean that indicates all users associated with the server should be deleted so that the Server can be destroyed without error. The default value is `false`. This option only applies to servers configured with a `SERVICE_MANAGED` `identity_provider_type`. * `post_authentication_login_banner`- (Optional) Specify a string to display when users connect to a server. This string is displayed after the user authenticates. The SFTP protocol does not support post-authentication display banners. * `pre_authentication_login_banner`- (Optional) Specify a string to display when users connect to a server. This string is displayed before the user authenticates. -* `security_policy_name` - (Optional) Specifies the name of the security policy that is attached to the server. Possible values are `TransferSecurityPolicy-2018-11`, `TransferSecurityPolicy-2020-06`, and `TransferSecurityPolicy-FIPS-2020-06`. Default value is: `TransferSecurityPolicy-2018-11`. +* `security_policy_name` - (Optional) Specifies the name of the security policy that is attached to the server. Possible values are `TransferSecurityPolicy-2018-11`, `TransferSecurityPolicy-2020-06`, `TransferSecurityPolicy-FIPS-2020-06` and `TransferSecurityPolicy-2022-03`. Default value is: `TransferSecurityPolicy-2018-11`. * `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. * `workflow_details` - (Optional) Specifies the workflow details. See Workflow Details below. diff --git a/website/docs/r/vpc_endpoint.html.markdown b/website/docs/r/vpc_endpoint.html.markdown index 39acd91043e..a41602f5e7d 100644 --- a/website/docs/r/vpc_endpoint.html.markdown +++ b/website/docs/r/vpc_endpoint.html.markdown @@ -120,6 +120,8 @@ The following arguments are supported: * `policy` - (Optional) A policy to attach to the endpoint that controls access to the service. This is a JSON formatted string. Defaults to full access. All `Gateway` and some `Interface` endpoints support policies - see the [relevant AWS documentation](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints-access.html) for more details. For more information about building AWS IAM policy documents with Terraform, see the [AWS IAM Policy Document Guide](https://learn.hashicorp.com/terraform/aws/iam-policy). * `private_dns_enabled` - (Optional; AWS services and AWS Marketplace partner services only) Whether or not to associate a private hosted zone with the specified VPC. Applicable for endpoints of type `Interface`. Defaults to `false`. +* `dns_options` - (Optional) The DNS options for the endpoint. See dns_options below. +* `ip_address_type` - (Optional) The IP address type for the endpoint. Valid values are `ipv4`, `dualstack`, and `ipv6`. * `route_table_ids` - (Optional) One or more route table IDs. Applicable for endpoints of type `Gateway`. * `subnet_ids` - (Optional) The ID of one or more subnets in which to create a network interface for the endpoint. Applicable for endpoints of type `GatewayLoadBalancer` and `Interface`. * `security_group_ids` - (Optional) The ID of one or more security groups to associate with the network interface. Applicable for endpoints of type `Interface`. @@ -127,6 +129,10 @@ If no security groups are specified, the VPC's [default security group](https:// * `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. * `vpc_endpoint_type` - (Optional) The VPC endpoint type, `Gateway`, `GatewayLoadBalancer`, or `Interface`. Defaults to `Gateway`. +### dns_options + +* `dns_record_ip_type` - (Optional) The DNS records created for the endpoint. Valid values are `ipv4`, `dualstack`, `service-defined`, and `ipv6`. + ### Timeouts `aws_vpc_endpoint` provides the following diff --git a/website/docs/r/vpc_endpoint_service.html.markdown b/website/docs/r/vpc_endpoint_service.html.markdown index 4aea6f963d3..c3715132cc0 100644 --- a/website/docs/r/vpc_endpoint_service.html.markdown +++ b/website/docs/r/vpc_endpoint_service.html.markdown @@ -47,6 +47,7 @@ The following arguments are supported: * `network_load_balancer_arns` - (Optional) Amazon Resource Names (ARNs) of one or more Network Load Balancers for the endpoint service. * `tags` - (Optional) A map of tags to assign to the resource. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. * `private_dns_name` - (Optional) The private DNS name for the service. +* `supported_ip_address_types` - (Optional) The supported IP address types. The possible values are `ipv4` and `ipv6`. ## Attributes Reference diff --git a/website/docs/r/vpn_connection.html.markdown b/website/docs/r/vpn_connection.html.markdown index f7305bc6953..ed30b75fb47 100644 --- a/website/docs/r/vpn_connection.html.markdown +++ b/website/docs/r/vpn_connection.html.markdown @@ -62,6 +62,64 @@ resource "aws_vpn_connection" "main" { } ``` +### AWS Site to Site Private VPN + +```terraform +resource "aws_dx_gateway" "example" { + name = "terraform_ipsec_vpn_example" + amazon_side_asn = "64512" +} + +resource "aws_ec2_transit_gateway" "example" { + amazon_side_asn = "64513" + description = "terraform_ipsec_vpn_example" + transit_gateway_cidr_blocks = [ + "10.0.0.0/24", + ] +} + +resource "aws_customer_gateway" "example" { + bgp_asn = 64514 + ip_address = "10.0.0.1" + type = "ipsec.1" + + tags = { + Name = "terraform_ipsec_vpn_example" + } +} + +resource "aws_dx_gateway_association" "example" { + dx_gateway_id = aws_dx_gateway.example.id + associated_gateway_id = aws_ec2_transit_gateway.example.id + + allowed_prefixes = [ + "10.0.0.0/8", + ] +} + +data "aws_ec2_transit_gateway_dx_gateway_attachment" "example" { + transit_gateway_id = aws_ec2_transit_gateway.example.id + dx_gateway_id = aws_dx_gateway.example.id + + depends_on = [ + aws_dx_gateway_association.example + ] +} + +resource "aws_vpn_connection" "example" { + customer_gateway_id = aws_customer_gateway.example.id + outside_ip_address_type = "PrivateIpv4" + transit_gateway_id = aws_ec2_transit_gateway.example.id + transport_transit_gateway_attachment_id = data.aws_ec2_transit_gateway_dx_gateway_attachment.example.id + type = "ipsec.1" + + tags = { + Name = "terraform_ipsec_vpn_example" + } +} +``` + + ## Argument Reference The following arguments are required: @@ -81,8 +139,10 @@ Other arguments: * `tags` - (Optional) Tags to apply to the connection. If configured with a provider [`default_tags` configuration block](/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. * `local_ipv4_network_cidr` - (Optional, Default `0.0.0.0/0`) The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. * `local_ipv6_network_cidr` - (Optional, Default `::/0`) The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. +* `outside_ip_address_type` - (Optional, Default `PublicIpv4`) Indicates if a Public S2S VPN or Private S2S VPN over AWS Direct Connect. Valid values are `PublicIpv4 | PrivateIpv4` * `remote_ipv4_network_cidr` - (Optional, Default `0.0.0.0/0`) The IPv4 CIDR on the AWS side of the VPN connection. * `remote_ipv6_network_cidr` - (Optional, Default `::/0`) The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. +* `transport_transit_gateway_attachment_id` - (Required when outside_ip_address_type is set to `PrivateIpv4`). The attachment ID of the Transit Gateway attachment to Direct Connect Gateway. The ID is obtained through a data source only. * `tunnel_inside_ip_version` - (Optional, Default `ipv4`) Indicate whether the VPN tunnels process IPv4 or IPv6 traffic. Valid values are `ipv4 | ipv6`. `ipv6` Supports only EC2 Transit Gateway. * `tunnel1_inside_cidr` - (Optional) The CIDR block of the inside IP addresses for the first VPN tunnel. Valid value is a size /30 CIDR block from the 169.254.0.0/16 range. * `tunnel2_inside_cidr` - (Optional) The CIDR block of the inside IP addresses for the second VPN tunnel. Valid value is a size /30 CIDR block from the 169.254.0.0/16 range. diff --git a/website/docs/r/waf_byte_match_set.html.markdown b/website/docs/r/waf_byte_match_set.html.markdown index 5a283231218..67d3747dc2b 100644 --- a/website/docs/r/waf_byte_match_set.html.markdown +++ b/website/docs/r/waf_byte_match_set.html.markdown @@ -50,8 +50,8 @@ The following arguments are supported: e.g., `CONTAINS`, `CONTAINS_WORD` or `EXACTLY`. See [docs](http://docs.aws.amazon.com/waf/latest/APIReference/API_ByteMatchTuple.html#WAF-Type-ByteMatchTuple-PositionalConstraint) for all supported values. -* `target_string` - (Optional) The value that you want to search forE.g., `HEADER`, `METHOD` or `BODY`. - See [docs](http://docs.aws.amazon.com/waf/latest/APIReference/API_ByteMatchTuple.html#WAF-Type-ByteMatchTuple-TargetString) +* `target_string` - (Optional) The value that you want to search for within the field specified by `field_to_match`, e.g., `badrefer1`. + See [docs](https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ByteMatchTuple.html) for all supported values. * `text_transformation` - (Required) Text transformations used to eliminate unusual formatting that attackers use in web requests in an effort to bypass AWS WAF. If you specify a transformation, AWS WAF performs the transformation on `target_string` before inspecting a request for a match. diff --git a/website/docs/r/workspaces_workspace.html.markdown b/website/docs/r/workspaces_workspace.html.markdown index 3319fe58e8c..6c1c1436f41 100644 --- a/website/docs/r/workspaces_workspace.html.markdown +++ b/website/docs/r/workspaces_workspace.html.markdown @@ -57,7 +57,7 @@ The following arguments are supported: `workspace_properties` supports the following: -* `compute_type_name` – (Optional) The compute type. For more information, see [Amazon WorkSpaces Bundles](http://aws.amazon.com/workspaces/details/#Amazon_WorkSpaces_Bundles). Valid values are `VALUE`, `STANDARD`, `PERFORMANCE`, `POWER`, `GRAPHICS`, `POWERPRO` and `GRAPHICSPRO`. +* `compute_type_name` – (Optional) The compute type. For more information, see [Amazon WorkSpaces Bundles](http://aws.amazon.com/workspaces/details/#Amazon_WorkSpaces_Bundles). Valid values are `VALUE`, `STANDARD`, `PERFORMANCE`, `POWER`, `GRAPHICS`, `POWERPRO`, `GRAPHICSPRO`, `GRAPHICS_G4DN`, and `GRAPHICSPRO_G4DN`. * `root_volume_size_gib` – (Optional) The size of the root volume. * `running_mode` – (Optional) The running mode. For more information, see [Manage the WorkSpace Running Mode](https://docs.aws.amazon.com/workspaces/latest/adminguide/running-mode.html). Valid values are `AUTO_STOP` and `ALWAYS_ON`. * `running_mode_auto_stop_timeout_in_minutes` – (Optional) The time after a user logs off when WorkSpaces are automatically stopped. Configured in 60-minute intervals.